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
32e48870420571e83dbbcc7fbe19bda459f783b5
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/topology/category/Compactum.lean
b0a26f2fed396f99f93486262802c1241028c14c
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
17,936
lean
/- Copyright (c) 2020 Adam Topaz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Adam Topaz -/ import category_theory.monad.types import category_theory.monad.limits import category_theory.equivalence import topology.category.CompHaus.basic import topology.category.Profinite.basic import data.set.constructions /-! # Compacta and Compact Hausdorff Spaces > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. Recall that, given a monad `M` on `Type*`, an *algebra* for `M` consists of the following data: - A type `X : Type*` - A "structure" map `M X → X`. This data must also satisfy a distributivity and unit axiom, and algebras for `M` form a category in an evident way. See the file `category_theory.monad.algebra` for a general version, as well as the following link. https://ncatlab.org/nlab/show/monad This file proves the equivalence between the category of *compact Hausdorff topological spaces* and the category of algebras for the *ultrafilter monad*. ## Notation: Here are the main objects introduced in this file. - `Compactum` is the type of compacta, which we define as algebras for the ultrafilter monad. - `Compactum_to_CompHaus` is the functor `Compactum ⥤ CompHaus`. Here `CompHaus` is the usual category of compact Hausdorff spaces. - `Compactum_to_CompHaus.is_equivalence` is a term of type `is_equivalence Compactum_to_CompHaus`. The proof of this equivalence is a bit technical. But the idea is quite simply that the structure map `ultrafilter X → X` for an algebra `X` of the ultrafilter monad should be considered as the map sending an ultrafilter to its limit in `X`. The topology on `X` is then defined by mimicking the characterization of open sets in terms of ultrafilters. Any `X : Compactum` is endowed with a coercion to `Type*`, as well as the following instances: - `topological_space X`. - `compact_space X`. - `t2_space X`. Any morphism `f : X ⟶ Y` of is endowed with a coercion to a function `X → Y`, which is shown to be continuous in `continuous_of_hom`. The function `Compactum.of_topological_space` can be used to construct a `Compactum` from a topological space which satisfies `compact_space` and `t2_space`. We also add wrappers around structures which already exist. Here are the main ones, all in the `Compactum` namespace: - `forget : Compactum ⥤ Type*` is the forgetful functor, which induces a `concrete_category` instance for `Compactum`. - `free : Type* ⥤ Compactum` is the left adjoint to `forget`, and the adjunction is in `adj`. - `str : ultrafilter X → X` is the structure map for `X : Compactum`. The notation `X.str` is preferred. - `join : ultrafilter (ultrafilter X) → ultrafilter X` is the monadic join for `X : Compactum`. Again, the notation `X.join` is preferred. - `incl : X → ultrafilter X` is the unit for `X : Compactum`. The notation `X.incl` is preferred. ## References - E. Manes, Algebraic Theories, Graduate Texts in Mathematics 26, Springer-Verlag, 1976. - https://ncatlab.org/nlab/show/ultrafilter -/ universe u open category_theory filter ultrafilter topological_space category_theory.limits has_finite_inter open_locale classical topology local notation `β` := of_type_monad ultrafilter /-- The type `Compactum` of Compacta, defined as algebras for the ultrafilter monad. -/ @[derive [category, inhabited]] def Compactum := monad.algebra β namespace Compactum /-- The forgetful functor to Type* -/ @[derive [creates_limits,faithful]] def forget : Compactum ⥤ Type* := monad.forget _ /-- The "free" Compactum functor. -/ def free : Type* ⥤ Compactum := monad.free _ /-- The adjunction between `free` and `forget`. -/ def adj : free ⊣ forget := monad.adj _ -- Basic instances instance : concrete_category Compactum := { forget := forget } instance : has_coe_to_sort Compactum Type* := ⟨forget.obj⟩ instance {X Y : Compactum} : has_coe_to_fun (X ⟶ Y) (λ f, X → Y) := ⟨λ f, f.f⟩ instance : has_limits Compactum := has_limits_of_has_limits_creates_limits forget /-- The structure map for a compactum, essentially sending an ultrafilter to its limit. -/ def str (X : Compactum) : ultrafilter X → X := X.a /-- The monadic join. -/ def join (X : Compactum) : ultrafilter (ultrafilter X) → ultrafilter X := β .μ.app _ /-- The inclusion of `X` into `ultrafilter X`. -/ def incl (X : Compactum) : X → ultrafilter X := β .η.app _ @[simp] lemma str_incl (X : Compactum) (x : X) : X.str (X.incl x) = x := begin change (β .η.app _ ≫ X.a) _ = _, rw monad.algebra.unit, refl, end @[simp] lemma str_hom_commute (X Y : Compactum) (f : X ⟶ Y) (xs : ultrafilter X) : f (X.str xs) = Y.str (map f xs) := begin change (X.a ≫ f.f) _ = _, rw ←f.h, refl, end @[simp] lemma join_distrib (X : Compactum) (uux : ultrafilter (ultrafilter X)) : X.str (X.join uux) = X.str (map X.str uux) := begin change (β .μ.app _ ≫ X.a) _ = _, rw monad.algebra.assoc, refl, end instance {X : Compactum} : topological_space X := { is_open := λ U, ∀ (F : ultrafilter X), X.str F ∈ U → U ∈ F, is_open_univ := λ _ _, filter.univ_sets _, is_open_inter := λ S T h3 h4 h5 h6, filter.inter_sets _ (h3 _ h6.1) (h4 _ h6.2), is_open_sUnion := λ S h1 F ⟨T,hT,h2⟩, mem_of_superset (h1 T hT _ h2) (set.subset_sUnion_of_mem hT) } theorem is_closed_iff {X : Compactum} (S : set X) : is_closed S ↔ (∀ F : ultrafilter X, S ∈ F → X.str F ∈ S) := begin rw ← is_open_compl_iff, split, { intros cond F h, by_contradiction c, specialize cond F c, rw compl_mem_iff_not_mem at cond, contradiction }, { intros h1 F h2, specialize h1 F, cases F.mem_or_compl_mem S, exacts [absurd (h1 h) h2, h] } end instance {X : Compactum} : compact_space X := begin constructor, rw is_compact_iff_ultrafilter_le_nhds, intros F h, refine ⟨X.str F, by tauto, _⟩, rw le_nhds_iff, intros S h1 h2, exact h2 F h1 end /-- A local definition used only in the proofs. -/ private def basic {X : Compactum} (A : set X) : set (ultrafilter X) := {F | A ∈ F} /-- A local definition used only in the proofs. -/ private def cl {X : Compactum} (A : set X) : set X := X.str '' (basic A) private lemma basic_inter {X : Compactum} (A B : set X) : basic (A ∩ B) = basic A ∩ basic B := begin ext G, split, { intro hG, split; filter_upwards [hG] with _, exacts [and.left, and.right] }, { rintros ⟨h1, h2⟩, exact inter_mem h1 h2 } end private lemma subset_cl {X : Compactum} (A : set X) : A ⊆ cl A := λ a ha, ⟨X.incl a, ha,by simp⟩ private theorem cl_cl {X : Compactum} (A : set X) : cl (cl A) ⊆ cl A := begin rintros _ ⟨F,hF,rfl⟩, -- Notation to be used in this proof. let fsu := finset (set (ultrafilter X)), let ssu := set (set (ultrafilter X)), let ι : fsu → ssu := coe, let C0 : ssu := {Z | ∃ B ∈ F, X.str ⁻¹' B = Z}, let AA := {G : ultrafilter X | A ∈ G}, let C1 := insert AA C0, let C2 := finite_inter_closure C1, -- C0 is closed under intersections. have claim1 : ∀ B C ∈ C0, B ∩ C ∈ C0, { rintros B ⟨Q,hQ,rfl⟩ C ⟨R,hR,rfl⟩, use Q ∩ R, simp only [and_true, eq_self_iff_true, set.preimage_inter, subtype.val_eq_coe], exact inter_sets _ hQ hR }, -- All sets in C0 are nonempty. have claim2 : ∀ B ∈ C0, set.nonempty B, { rintros B ⟨Q,hQ,rfl⟩, obtain ⟨q⟩ := filter.nonempty_of_mem hQ, use X.incl q, simpa, }, -- The intersection of AA with every set in C0 is nonempty. have claim3 : ∀ B ∈ C0, (AA ∩ B).nonempty, { rintros B ⟨Q,hQ,rfl⟩, have : (Q ∩ cl A).nonempty := filter.nonempty_of_mem (inter_mem hQ hF), rcases this with ⟨q,hq1,P,hq2,hq3⟩, refine ⟨P,hq2,_⟩, rw ←hq3 at hq1, simpa }, -- Suffices to show that the intersection of any finite subcollection of C1 is nonempty. suffices : ∀ (T : fsu), ι T ⊆ C1 → (⋂₀ ι T).nonempty, { obtain ⟨G, h1⟩ := exists_ultrafilter_of_finite_inter_nonempty _ this, use X.join G, have : G.map X.str = F := ultrafilter.coe_le_coe.1 (λ S hS, h1 (or.inr ⟨S, hS, rfl⟩)), rw [join_distrib, this], exact ⟨h1 (or.inl rfl), rfl⟩ }, -- C2 is closed under finite intersections (by construction!). have claim4 := finite_inter_closure_has_finite_inter C1, -- C0 is closed under finite intersections by claim1. have claim5 : has_finite_inter C0 := ⟨⟨_, univ_mem, set.preimage_univ⟩, claim1⟩, -- Every element of C2 is nonempty. have claim6 : ∀ P ∈ C2, (P : set (ultrafilter X)).nonempty, { suffices : ∀ P ∈ C2, P ∈ C0 ∨ ∃ Q ∈ C0, P = AA ∩ Q, { intros P hP, cases this P hP, { exact claim2 _ h }, { rcases h with ⟨Q, hQ, rfl⟩, exact claim3 _ hQ } }, intros P hP, exact claim5.finite_inter_closure_insert _ hP }, intros T hT, -- Suffices to show that the intersection of the T's is contained in C2. suffices : ⋂₀ ι T ∈ C2, by exact claim6 _ this, -- Finish apply claim4.finite_inter_mem, intros t ht, exact finite_inter_closure.basic (@hT t ht), end lemma is_closed_cl {X : Compactum} (A : set X) : is_closed (cl A) := begin rw is_closed_iff, intros F hF, exact cl_cl _ ⟨F, hF, rfl⟩, end lemma str_eq_of_le_nhds {X : Compactum} (F : ultrafilter X) (x : X) : ↑F ≤ 𝓝 x → X.str F = x := begin -- Notation to be used in this proof. let fsu := finset (set (ultrafilter X)), let ssu := set (set (ultrafilter X)), let ι : fsu → ssu := coe, let T0 : ssu := { S | ∃ A ∈ F, S = basic A }, let AA := (X.str ⁻¹' {x}), let T1 := insert AA T0, let T2 := finite_inter_closure T1, intro cond, -- If F contains a closed set A, then x is contained in A. have claim1 : ∀ (A : set X), is_closed A → A ∈ F → x ∈ A, { intros A hA h, by_contradiction H, rw le_nhds_iff at cond, specialize cond Aᶜ H hA.is_open_compl, rw [ultrafilter.mem_coe, ultrafilter.compl_mem_iff_not_mem] at cond, contradiction }, -- If A ∈ F, then x ∈ cl A. have claim2 : ∀ (A : set X), A ∈ F → x ∈ cl A, { intros A hA, exact claim1 (cl A) (is_closed_cl A) (mem_of_superset hA (subset_cl A)) }, -- T0 is closed under intersections. have claim3 : ∀ (S1 S2 ∈ T0), S1 ∩ S2 ∈ T0, { rintros S1 ⟨S1, hS1, rfl⟩ S2 ⟨S2, hS2, rfl⟩, exact ⟨S1 ∩ S2, inter_mem hS1 hS2, by simp [basic_inter]⟩ }, -- For every S ∈ T0, the intersection AA ∩ S is nonempty. have claim4 : ∀ (S ∈ T0), (AA ∩ S).nonempty, { rintros S ⟨S, hS, rfl⟩, rcases claim2 _ hS with ⟨G, hG, hG2⟩, exact ⟨G, hG2, hG⟩ }, -- Every element of T0 is nonempty. have claim5 : ∀ (S ∈ T0), set.nonempty S, { rintros S ⟨S, hS, rfl⟩, exact ⟨F, hS⟩ }, -- Every element of T2 is nonempty. have claim6 : ∀ (S ∈ T2), set.nonempty S, { suffices : ∀ S ∈ T2, S ∈ T0 ∨ ∃ Q ∈ T0, S = AA ∩ Q, { intros S hS, cases this _ hS with h h, { exact claim5 S h }, { rcases h with ⟨Q, hQ, rfl⟩, exact claim4 Q hQ } }, intros S hS, apply finite_inter_closure_insert, { split, { use set.univ, refine ⟨filter.univ_sets _, _⟩, ext, refine ⟨_, by tauto⟩, { intro, apply filter.univ_sets, } }, { exact claim3 } }, { exact hS} }, -- It suffices to show that the intersection of any finite subset of T1 is nonempty. suffices : ∀ (F : fsu), ↑F ⊆ T1 → (⋂₀ ι F).nonempty, { obtain ⟨G,h1⟩ := ultrafilter.exists_ultrafilter_of_finite_inter_nonempty _ this, have c1 : X.join G = F := ultrafilter.coe_le_coe.1 (λ P hP, h1 (or.inr ⟨P, hP, rfl⟩)), have c2 : G.map X.str = X.incl x, { refine ultrafilter.coe_le_coe.1 (λ P hP, _), apply mem_of_superset (h1 (or.inl rfl)), rintros x ⟨rfl⟩, exact hP }, simp [←c1, c2] }, -- Finish... intros T hT, refine claim6 _ (finite_inter_mem (finite_inter_closure_has_finite_inter _) _ _), intros t ht, exact finite_inter_closure.basic (@hT t ht) end lemma le_nhds_of_str_eq {X : Compactum} (F : ultrafilter X) (x : X) : X.str F = x → ↑F ≤ 𝓝 x := λ h, le_nhds_iff.mpr (λ s hx hs, hs _ $ by rwa h) -- All the hard work above boils down to this t2_space instance. instance {X : Compactum} : t2_space X := begin rw t2_iff_ultrafilter, intros _ _ F hx hy, rw [← str_eq_of_le_nhds _ _ hx, ← str_eq_of_le_nhds _ _ hy] end /-- The structure map of a compactum actually computes limits. -/ lemma Lim_eq_str {X : Compactum} (F : ultrafilter X) : F.Lim = X.str F := begin rw [ultrafilter.Lim_eq_iff_le_nhds, le_nhds_iff], tauto, end lemma cl_eq_closure {X : Compactum} (A : set X) : cl A = closure A := begin ext, rw mem_closure_iff_ultrafilter, split, { rintro ⟨F, h1, h2⟩, exact ⟨F, h1, le_nhds_of_str_eq _ _ h2⟩ }, { rintro ⟨F, h1, h2⟩, exact ⟨F, h1, str_eq_of_le_nhds _ _ h2⟩ } end /-- Any morphism of compacta is continuous. -/ lemma continuous_of_hom {X Y : Compactum} (f : X ⟶ Y) : continuous f := begin rw continuous_iff_ultrafilter, intros x _ h, rw [tendsto, ← coe_map], apply le_nhds_of_str_eq, rw [← str_hom_commute, str_eq_of_le_nhds _ x h] end /-- Given any compact Hausdorff space, we construct a Compactum. -/ noncomputable def of_topological_space (X : Type*) [topological_space X] [compact_space X] [t2_space X] : Compactum := { A := X, a := ultrafilter.Lim, unit' := by {ext x, exact Lim_eq (pure_le_nhds _) }, assoc' := begin ext FF, change ultrafilter (ultrafilter X) at FF, set x := (ultrafilter.map ultrafilter.Lim FF).Lim with c1, have c2 : ∀ (U : set X) (F : ultrafilter X), F.Lim ∈ U → is_open U → U ∈ F, { intros U F h1 hU, exact c1 ▸ is_open_iff_ultrafilter.mp hU _ h1 _ (ultrafilter.le_nhds_Lim _) }, have c3 : ↑(ultrafilter.map ultrafilter.Lim FF) ≤ 𝓝 x, { rw le_nhds_iff, intros U hx hU, exact mem_coe.2 (c2 _ _ (by rwa ← c1) hU) }, have c4 : ∀ (U : set X), x ∈ U → is_open U → { G : ultrafilter X | U ∈ G } ∈ FF, { intros U hx hU, suffices : ultrafilter.Lim ⁻¹' U ∈ FF, { apply mem_of_superset this, intros P hP, exact c2 U P hP hU }, exact @c3 U (is_open.mem_nhds hU hx) }, apply Lim_eq, rw le_nhds_iff, exact c4, end } /-- Any continuous map between Compacta is a morphism of compacta. -/ def hom_of_continuous {X Y : Compactum} (f : X → Y) (cont : continuous f) : X ⟶ Y := { f := f, h' := begin rw continuous_iff_ultrafilter at cont, ext (F : ultrafilter X), specialize cont (X.str F) F (le_nhds_of_str_eq F (X.str F) rfl), have := str_eq_of_le_nhds (ultrafilter.map f F) _ cont, simpa only [←this, types_comp_apply, of_type_functor_map], end } end Compactum /-- The functor functor from Compactum to CompHaus. -/ def Compactum_to_CompHaus : Compactum ⥤ CompHaus := { obj := λ X, { to_Top := { α := X } }, map := λ X Y f, { to_fun := f, continuous_to_fun := Compactum.continuous_of_hom _ }} namespace Compactum_to_CompHaus /-- The functor Compactum_to_CompHaus is full. -/ def full : full Compactum_to_CompHaus.{u} := { preimage := λ X Y f, Compactum.hom_of_continuous f.1 f.2 } /-- The functor Compactum_to_CompHaus is faithful. -/ lemma faithful : faithful Compactum_to_CompHaus := {} /-- This definition is used to prove essential surjectivity of Compactum_to_CompHaus. -/ def iso_of_topological_space {D : CompHaus} : Compactum_to_CompHaus.obj (Compactum.of_topological_space D) ≅ D := { hom := { to_fun := id, continuous_to_fun := continuous_def.2 $ λ _ h, by {rw is_open_iff_ultrafilter' at h, exact h} }, inv := { to_fun := id, continuous_to_fun := continuous_def.2 $ λ _ h1, by {rw is_open_iff_ultrafilter', intros _ h2, exact h1 _ h2} } } /-- The functor Compactum_to_CompHaus is essentially surjective. -/ lemma ess_surj : ess_surj Compactum_to_CompHaus := { mem_ess_image := λ X, ⟨Compactum.of_topological_space X, ⟨iso_of_topological_space⟩⟩ } /-- The functor Compactum_to_CompHaus is an equivalence of categories. -/ noncomputable instance is_equivalence : is_equivalence Compactum_to_CompHaus := begin apply equivalence.of_fully_faithfully_ess_surj _, exact Compactum_to_CompHaus.full, exact Compactum_to_CompHaus.faithful, exact Compactum_to_CompHaus.ess_surj, end end Compactum_to_CompHaus /-- The forgetful functors of `Compactum` and `CompHaus` are compatible via `Compactum_to_CompHaus`. -/ def Compactum_to_CompHaus_comp_forget : Compactum_to_CompHaus ⋙ category_theory.forget CompHaus ≅ Compactum.forget := nat_iso.of_components (λ X, eq_to_iso rfl) $ by { intros X Y f, dsimp, simpa } /- TODO: `forget CompHaus` is monadic, as it is isomorphic to the composition of an equivalence with the monadic functor `forget Compactum`. Once we have the API to transfer monadicity of functors along such isomorphisms, the instance `creates_limits (forget CompHaus)` can be deduced from this monadicity. -/ noncomputable instance CompHaus.forget_creates_limits : creates_limits (forget CompHaus) := begin let e : forget CompHaus ≅ Compactum_to_CompHaus.inv ⋙ Compactum.forget := _ ≪≫ iso_whisker_left _ Compactum_to_CompHaus_comp_forget, swap, refine _ ≪≫ functor.associator _ _ _, refine (functor.left_unitor _).symm ≪≫ _, refine iso_whisker_right _ _, exact Compactum_to_CompHaus.as_equivalence.symm.unit_iso, exact creates_limits_of_nat_iso e.symm, end noncomputable instance Profinite.forget_creates_limits : creates_limits (forget Profinite) := begin change creates_limits (Profinite_to_CompHaus ⋙ forget _), apply_instance, end
461f097b2dfa4a8a82ae3fe31aa44662c4a783b3
a4673261e60b025e2c8c825dfa4ab9108246c32e
/src/Lean/Compiler/IR/Format.lean
1645751fce36c18ce95254d9f86429dcfb5725e2
[ "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
6,950
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Data.FormatMacro import Lean.Compiler.IR.Basic namespace Lean namespace IR private def formatArg : Arg → Format | Arg.var id => format id | Arg.irrelevant => "◾" instance : ToFormat Arg := ⟨formatArg⟩ def formatArray {α : Type} [ToFormat α] (args : Array α) : Format := args.foldl (fun r a => r ++ " " ++ format a) Format.nil private def formatLitVal : LitVal → Format | LitVal.num v => format v | LitVal.str v => format (repr v) instance : ToFormat LitVal := ⟨formatLitVal⟩ private def formatCtorInfo : CtorInfo → Format | { name := name, cidx := cidx, usize := usize, ssize := ssize, .. } => do let mut r := f!"ctor_{cidx}" if usize > 0 || ssize > 0 then r := f!"{r}.{usize}.{ssize}" if name != Name.anonymous then r := f!"{r}[{name}]" r instance : ToFormat CtorInfo := ⟨formatCtorInfo⟩ private def formatExpr : Expr → Format | Expr.ctor i ys => format i ++ formatArray ys | Expr.reset n x => "reset[" ++ format n ++ "] " ++ format x | Expr.reuse x i u ys => "reuse" ++ (if u then "!" else "") ++ " " ++ format x ++ " in " ++ format i ++ formatArray ys | Expr.proj i x => "proj[" ++ format i ++ "] " ++ format x | Expr.uproj i x => "uproj[" ++ format i ++ "] " ++ format x | Expr.sproj n o x => "sproj[" ++ format n ++ ", " ++ format o ++ "] " ++ format x | Expr.fap c ys => format c ++ formatArray ys | Expr.pap c ys => "pap " ++ format c ++ formatArray ys | Expr.ap x ys => "app " ++ format x ++ formatArray ys | Expr.box _ x => "box " ++ format x | Expr.unbox x => "unbox " ++ format x | Expr.lit v => format v | Expr.isShared x => "isShared " ++ format x | Expr.isTaggedPtr x => "isTaggedPtr " ++ format x instance : ToFormat Expr := ⟨formatExpr⟩ instance : ToString Expr := ⟨fun e => Format.pretty (format e)⟩ private partial def formatIRType : IRType → Format | IRType.float => "float" | IRType.uint8 => "u8" | IRType.uint16 => "u16" | IRType.uint32 => "u32" | IRType.uint64 => "u64" | IRType.usize => "usize" | IRType.irrelevant => "◾" | IRType.object => "obj" | IRType.tobject => "tobj" | IRType.struct _ tys => "struct " ++ Format.bracket "{" (@Format.joinSep _ ⟨formatIRType⟩ tys.toList ", ") "}" | IRType.union _ tys => "union " ++ Format.bracket "{" (@Format.joinSep _ ⟨formatIRType⟩ tys.toList ", ") "}" instance : ToFormat IRType := ⟨formatIRType⟩ instance : ToString IRType := ⟨toString ∘ format⟩ private def formatParam : Param → Format | { x := name, borrow := b, ty := ty } => "(" ++ format name ++ " : " ++ (if b then "@& " else "") ++ format ty ++ ")" instance : ToFormat Param := ⟨formatParam⟩ def formatAlt (fmt : FnBody → Format) (indent : Nat) : Alt → Format | Alt.ctor i b => format i.name ++ " →" ++ Format.nest indent (Format.line ++ fmt b) | Alt.default b => "default →" ++ Format.nest indent (Format.line ++ fmt b) def formatParams (ps : Array Param) : Format := formatArray ps @[export lean_ir_format_fn_body_head] def formatFnBodyHead : FnBody → Format | FnBody.vdecl x ty e b => "let " ++ format x ++ " : " ++ format ty ++ " := " ++ format e | FnBody.jdecl j xs v b => format j ++ formatParams xs ++ " := ..." | FnBody.set x i y b => "set " ++ format x ++ "[" ++ format i ++ "] := " ++ format y | FnBody.uset x i y b => "uset " ++ format x ++ "[" ++ format i ++ "] := " ++ format y | FnBody.sset x i o y ty b => "sset " ++ format x ++ "[" ++ format i ++ ", " ++ format o ++ "] : " ++ format ty ++ " := " ++ format y | FnBody.setTag x cidx b => "setTag " ++ format x ++ " := " ++ format cidx | FnBody.inc x n c _ b => "inc" ++ (if n != 1 then Format.sbracket (format n) else "") ++ " " ++ format x | FnBody.dec x n c _ b => "dec" ++ (if n != 1 then Format.sbracket (format n) else "") ++ " " ++ format x | FnBody.del x b => "del " ++ format x | FnBody.mdata d b => "mdata " ++ format d | FnBody.case tid x xType cs => "case " ++ format x ++ " of ..." | FnBody.jmp j ys => "jmp " ++ format j ++ formatArray ys | FnBody.ret x => "ret " ++ format x | FnBody.unreachable => "⊥" partial def formatFnBody (fnBody : FnBody) (indent : Nat := 2) : Format := let rec loop : FnBody → Format | FnBody.vdecl x ty e b => "let " ++ format x ++ " : " ++ format ty ++ " := " ++ format e ++ ";" ++ Format.line ++ loop b | FnBody.jdecl j xs v b => format j ++ formatParams xs ++ " :=" ++ Format.nest indent (Format.line ++ loop v) ++ ";" ++ Format.line ++ loop b | FnBody.set x i y b => "set " ++ format x ++ "[" ++ format i ++ "] := " ++ format y ++ ";" ++ Format.line ++ loop b | FnBody.uset x i y b => "uset " ++ format x ++ "[" ++ format i ++ "] := " ++ format y ++ ";" ++ Format.line ++ loop b | FnBody.sset x i o y ty b => "sset " ++ format x ++ "[" ++ format i ++ ", " ++ format o ++ "] : " ++ format ty ++ " := " ++ format y ++ ";" ++ Format.line ++ loop b | FnBody.setTag x cidx b => "setTag " ++ format x ++ " := " ++ format cidx ++ ";" ++ Format.line ++ loop b | FnBody.inc x n c _ b => "inc" ++ (if n != 1 then Format.sbracket (format n) else "") ++ " " ++ format x ++ ";" ++ Format.line ++ loop b | FnBody.dec x n c _ b => "dec" ++ (if n != 1 then Format.sbracket (format n) else "") ++ " " ++ format x ++ ";" ++ Format.line ++ loop b | FnBody.del x b => "del " ++ format x ++ ";" ++ Format.line ++ loop b | FnBody.mdata d b => "mdata " ++ format d ++ ";" ++ Format.line ++ loop b | FnBody.case tid x xType cs => "case " ++ format x ++ " : " ++ format xType ++ " of" ++ cs.foldl (fun r c => r ++ Format.line ++ formatAlt loop indent c) Format.nil | FnBody.jmp j ys => "jmp " ++ format j ++ formatArray ys | FnBody.ret x => "ret " ++ format x | FnBody.unreachable => "⊥" loop fnBody instance : ToFormat FnBody := ⟨formatFnBody⟩ instance : ToString FnBody := ⟨fun b => (format b).pretty⟩ def formatDecl (decl : Decl) (indent : Nat := 2) : Format := match decl with | Decl.fdecl f xs ty b => "def " ++ format f ++ formatParams xs ++ format " : " ++ format ty ++ " :=" ++ Format.nest indent (Format.line ++ formatFnBody b indent) | Decl.extern f xs ty _ => "extern " ++ format f ++ formatParams xs ++ format " : " ++ format ty instance : ToFormat Decl := ⟨formatDecl⟩ @[export lean_ir_decl_to_string] def declToString (d : Decl) : String := (format d).pretty instance : ToString Decl := ⟨declToString⟩ end Lean.IR
fcdd832e0b3f047a7c010565018bc1572af7ebbf
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/analysis/normed_space/inner_product.lean
368abee26d03580903cc0faec95e8694f14eee47
[ "Apache-2.0" ]
permissive
ilitzroth/mathlib
ea647e67f1fdfd19a0f7bdc5504e8acec6180011
5254ef14e3465f6504306132fe3ba9cec9ffff16
refs/heads/master
1,680,086,661,182
1,617,715,647,000
1,617,715,647,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
127,984
lean
/- Copyright (c) 2019 Zhouhang Zhou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Zhouhang Zhou, Sébastien Gouëzel, Frédéric Dupuis, Heather Macbeth -/ import linear_algebra.bilinear_form import linear_algebra.sesquilinear_form import topology.metric_space.pi_Lp import data.complex.is_R_or_C import analysis.special_functions.sqrt /-! # Inner Product Space This file defines inner product spaces and proves its basic properties. An inner product space is a vector space endowed with an inner product. It generalizes the notion of dot product in `ℝ^n` and provides the means of defining the length of a vector and the angle between two vectors. In particular vectors `x` and `y` are orthogonal if their inner product equals zero. We define both the real and complex cases at the same time using the `is_R_or_C` typeclass. ## Main results - We define the class `inner_product_space 𝕜 E` extending `normed_space 𝕜 E` with a number of basic properties, most notably the Cauchy-Schwarz inequality. Here `𝕜` is understood to be either `ℝ` or `ℂ`, through the `is_R_or_C` typeclass. - We show that if `f i` is an inner product space for each `i`, then so is `Π i, f i` - We define `euclidean_space 𝕜 n` to be `n → 𝕜` for any `fintype n`, and show that this an inner product space. - Existence of orthogonal projection onto nonempty complete subspace: Let `u` be a point in an inner product space, and let `K` be a nonempty complete subspace. Then there exists a unique `v` in `K` that minimizes the distance `∥u - v∥` to `u`. The point `v` is usually called the orthogonal projection of `u` onto `K`. - We define `orthonormal`, a predicate on a function `v : ι → E`. We prove the existence of a maximal orthonormal set, `exists_maximal_orthonormal`, and also prove that a maximal orthonormal set is a basis (`maximal_orthonormal_iff_is_basis_of_finite_dimensional`), if `E` is finite- dimensional, or in general (`maximal_orthonormal_iff_dense_span`) a set whose span is dense (i.e., a Hilbert basis, although we do not make that definition). ## Notation We globally denote the real and complex inner products by `⟪·, ·⟫_ℝ` and `⟪·, ·⟫_ℂ` respectively. We also provide two notation namespaces: `real_inner_product_space`, `complex_inner_product_space`, which respectively introduce the plain notation `⟪·, ·⟫` for the the real and complex inner product. The orthogonal complement of a submodule `K` is denoted by `Kᗮ`. ## Implementation notes We choose the convention that inner products are conjugate linear in the first argument and linear in the second. ## TODO - Fix the section on the existence of minimizers and orthogonal projections to make sure that it also applies in the complex case. ## Tags inner product space, norm ## References * [Clément & Martin, *The Lax-Milgram Theorem. A detailed proof to be formalized in Coq*] * [Clément & Martin, *A Coq formal proof of the Lax–Milgram theorem*] The Coq code is available at the following address: <http://www.lri.fr/~sboldo/elfic/index.html> -/ noncomputable theory open is_R_or_C real filter open_locale big_operators classical topological_space variables {𝕜 E F : Type*} [is_R_or_C 𝕜] /-- Syntactic typeclass for types endowed with an inner product -/ class has_inner (𝕜 E : Type*) := (inner : E → E → 𝕜) export has_inner (inner) notation `⟪`x`, `y`⟫_ℝ` := @inner ℝ _ _ x y notation `⟪`x`, `y`⟫_ℂ` := @inner ℂ _ _ x y section notations localized "notation `⟪`x`, `y`⟫` := @inner ℝ _ _ x y" in real_inner_product_space localized "notation `⟪`x`, `y`⟫` := @inner ℂ _ _ x y" in complex_inner_product_space end notations /-- An inner product space is a vector space with an additional operation called inner product. The norm could be derived from the inner product, instead we require the existence of a norm and the fact that `∥x∥^2 = re ⟪x, x⟫` to be able to put instances on `𝕂` or product spaces. To construct a norm from an inner product, see `inner_product_space.of_core`. -/ class inner_product_space (𝕜 : Type*) (E : Type*) [is_R_or_C 𝕜] extends normed_group E, normed_space 𝕜 E, has_inner 𝕜 E := (norm_sq_eq_inner : ∀ (x : E), ∥x∥^2 = re (inner x x)) (conj_sym : ∀ x y, conj (inner y x) = inner x y) (add_left : ∀ x y z, inner (x + y) z = inner x z + inner y z) (smul_left : ∀ x y r, inner (r • x) y = (conj r) * inner x y) attribute [nolint dangerous_instance] inner_product_space.to_normed_group -- note [is_R_or_C instance] /-! ### Constructing a normed space structure from an inner product In the definition of an inner product space, we require the existence of a norm, which is equal (but maybe not defeq) to the square root of the scalar product. This makes it possible to put an inner product space structure on spaces with a preexisting norm (for instance `ℝ`), with good properties. However, sometimes, one would like to define the norm starting only from a well-behaved scalar product. This is what we implement in this paragraph, starting from a structure `inner_product_space.core` stating that we have a nice scalar product. Our goal here is not to develop a whole theory with all the supporting API, as this will be done below for `inner_product_space`. Instead, we implement the bare minimum to go as directly as possible to the construction of the norm and the proof of the triangular inequality. Warning: Do not use this `core` structure if the space you are interested in already has a norm instance defined on it, otherwise this will create a second non-defeq norm instance! -/ /-- A structure requiring that a scalar product is positive definite and symmetric, from which one can construct an `inner_product_space` instance in `inner_product_space.of_core`. -/ @[nolint has_inhabited_instance] structure inner_product_space.core (𝕜 : Type*) (F : Type*) [is_R_or_C 𝕜] [add_comm_group F] [semimodule 𝕜 F] := (inner : F → F → 𝕜) (conj_sym : ∀ x y, conj (inner y x) = inner x y) (nonneg_re : ∀ x, 0 ≤ re (inner x x)) (definite : ∀ x, inner x x = 0 → x = 0) (add_left : ∀ x y z, inner (x + y) z = inner x z + inner y z) (smul_left : ∀ x y r, inner (r • x) y = (conj r) * inner x y) /- We set `inner_product_space.core` to be a class as we will use it as such in the construction of the normed space structure that it produces. However, all the instances we will use will be local to this proof. -/ attribute [class] inner_product_space.core namespace inner_product_space.of_core variables [add_comm_group F] [semimodule 𝕜 F] [c : inner_product_space.core 𝕜 F] include c local notation `⟪`x`, `y`⟫` := @inner 𝕜 F _ x y local notation `norm_sqK` := @is_R_or_C.norm_sq 𝕜 _ local notation `reK` := @is_R_or_C.re 𝕜 _ local notation `absK` := @is_R_or_C.abs 𝕜 _ local notation `ext_iff` := @is_R_or_C.ext_iff 𝕜 _ local postfix `†`:90 := @is_R_or_C.conj 𝕜 _ /-- Inner product defined by the `inner_product_space.core` structure. -/ def to_has_inner : has_inner 𝕜 F := { inner := c.inner } local attribute [instance] to_has_inner /-- The norm squared function for `inner_product_space.core` structure. -/ def norm_sq (x : F) := reK ⟪x, x⟫ local notation `norm_sqF` := @norm_sq 𝕜 F _ _ _ _ lemma inner_conj_sym (x y : F) : ⟪y, x⟫† = ⟪x, y⟫ := c.conj_sym x y lemma inner_self_nonneg {x : F} : 0 ≤ re ⟪x, x⟫ := c.nonneg_re _ lemma inner_self_nonneg_im {x : F} : im ⟪x, x⟫ = 0 := by rw [← @of_real_inj 𝕜, im_eq_conj_sub]; simp [inner_conj_sym] lemma inner_self_im_zero {x : F} : im ⟪x, x⟫ = 0 := inner_self_nonneg_im lemma inner_add_left {x y z : F} : ⟪x + y, z⟫ = ⟪x, z⟫ + ⟪y, z⟫ := c.add_left _ _ _ lemma inner_add_right {x y z : F} : ⟪x, y + z⟫ = ⟪x, y⟫ + ⟪x, z⟫ := by rw [←inner_conj_sym, inner_add_left, ring_hom.map_add]; simp only [inner_conj_sym] lemma inner_norm_sq_eq_inner_self (x : F) : (norm_sqF x : 𝕜) = ⟪x, x⟫ := begin rw ext_iff, exact ⟨by simp only [of_real_re]; refl, by simp only [inner_self_nonneg_im, of_real_im]⟩ end lemma inner_re_symm {x y : F} : re ⟪x, y⟫ = re ⟪y, x⟫ := by rw [←inner_conj_sym, conj_re] lemma inner_im_symm {x y : F} : im ⟪x, y⟫ = -im ⟪y, x⟫ := by rw [←inner_conj_sym, conj_im] lemma inner_smul_left {x y : F} {r : 𝕜} : ⟪r • x, y⟫ = r† * ⟪x, y⟫ := c.smul_left _ _ _ lemma inner_smul_right {x y : F} {r : 𝕜} : ⟪x, r • y⟫ = r * ⟪x, y⟫ := by rw [←inner_conj_sym, inner_smul_left]; simp only [conj_conj, inner_conj_sym, ring_hom.map_mul] lemma inner_zero_left {x : F} : ⟪0, x⟫ = 0 := by rw [←zero_smul 𝕜 (0 : F), inner_smul_left]; simp only [zero_mul, ring_hom.map_zero] lemma inner_zero_right {x : F} : ⟪x, 0⟫ = 0 := by rw [←inner_conj_sym, inner_zero_left]; simp only [ring_hom.map_zero] lemma inner_self_eq_zero {x : F} : ⟪x, x⟫ = 0 ↔ x = 0 := iff.intro (c.definite _) (by { rintro rfl, exact inner_zero_left }) lemma inner_self_re_to_K {x : F} : (re ⟪x, x⟫ : 𝕜) = ⟪x, x⟫ := by norm_num [ext_iff, inner_self_nonneg_im] lemma inner_abs_conj_sym {x y : F} : abs ⟪x, y⟫ = abs ⟪y, x⟫ := by rw [←inner_conj_sym, abs_conj] lemma inner_neg_left {x y : F} : ⟪-x, y⟫ = -⟪x, y⟫ := by { rw [← neg_one_smul 𝕜 x, inner_smul_left], simp } lemma inner_neg_right {x y : F} : ⟪x, -y⟫ = -⟪x, y⟫ := by rw [←inner_conj_sym, inner_neg_left]; simp only [ring_hom.map_neg, inner_conj_sym] lemma inner_sub_left {x y z : F} : ⟪x - y, z⟫ = ⟪x, z⟫ - ⟪y, z⟫ := by { simp [sub_eq_add_neg, inner_add_left, inner_neg_left] } lemma inner_sub_right {x y z : F} : ⟪x, y - z⟫ = ⟪x, y⟫ - ⟪x, z⟫ := by { simp [sub_eq_add_neg, inner_add_right, inner_neg_right] } lemma inner_mul_conj_re_abs {x y : F} : re (⟪x, y⟫ * ⟪y, x⟫) = abs (⟪x, y⟫ * ⟪y, x⟫) := by { rw[←inner_conj_sym, mul_comm], exact re_eq_abs_of_mul_conj (inner y x), } /-- Expand `inner (x + y) (x + y)` -/ lemma inner_add_add_self {x y : F} : ⟪x + y, x + y⟫ = ⟪x, x⟫ + ⟪x, y⟫ + ⟪y, x⟫ + ⟪y, y⟫ := by simp only [inner_add_left, inner_add_right]; ring /- Expand `inner (x - y) (x - y)` -/ lemma inner_sub_sub_self {x y : F} : ⟪x - y, x - y⟫ = ⟪x, x⟫ - ⟪x, y⟫ - ⟪y, x⟫ + ⟪y, y⟫ := by simp only [inner_sub_left, inner_sub_right]; ring /-- Cauchy–Schwarz inequality. This proof follows "Proof 2" on Wikipedia. We need this for the `core` structure to prove the triangle inequality below when showing the core is a normed group. -/ lemma inner_mul_inner_self_le (x y : F) : abs ⟪x, y⟫ * abs ⟪y, x⟫ ≤ re ⟪x, x⟫ * re ⟪y, y⟫ := begin by_cases hy : y = 0, { rw [hy], simp only [is_R_or_C.abs_zero, inner_zero_left, mul_zero, add_monoid_hom.map_zero] }, { change y ≠ 0 at hy, have hy' : ⟪y, y⟫ ≠ 0 := λ h, by rw [inner_self_eq_zero] at h; exact hy h, set T := ⟪y, x⟫ / ⟪y, y⟫ with hT, have h₁ : re ⟪y, x⟫ = re ⟪x, y⟫ := inner_re_symm, have h₂ : im ⟪y, x⟫ = -im ⟪x, y⟫ := inner_im_symm, have h₃ : ⟪y, x⟫ * ⟪x, y⟫ * ⟪y, y⟫ / (⟪y, y⟫ * ⟪y, y⟫) = ⟪y, x⟫ * ⟪x, y⟫ / ⟪y, y⟫, { rw [mul_div_assoc], have : ⟪y, y⟫ / (⟪y, y⟫ * ⟪y, y⟫) = 1 / ⟪y, y⟫ := by rw [div_mul_eq_div_mul_one_div, div_self hy', one_mul], rw [this, div_eq_mul_inv, one_mul, ←div_eq_mul_inv] }, have h₄ : ⟪y, y⟫ = re ⟪y, y⟫ := by simp only [inner_self_re_to_K], have h₅ : re ⟪y, y⟫ > 0, { refine lt_of_le_of_ne inner_self_nonneg _, intro H, apply hy', rw ext_iff, exact ⟨by simp [H],by simp [inner_self_nonneg_im]⟩ }, have h₆ : re ⟪y, y⟫ ≠ 0 := ne_of_gt h₅, have hmain := calc 0 ≤ re ⟪x - T • y, x - T • y⟫ : inner_self_nonneg ... = re ⟪x, x⟫ - re ⟪T • y, x⟫ - re ⟪x, T • y⟫ + re ⟪T • y, T • y⟫ : by simp [inner_sub_sub_self, inner_smul_left, inner_smul_right, h₁, h₂] ... = re ⟪x, x⟫ - re (T† * ⟪y, x⟫) - re (T * ⟪x, y⟫) + re (T * T† * ⟪y, y⟫) : by simp [inner_smul_left, inner_smul_right, mul_assoc] ... = re ⟪x, x⟫ - re (⟪x, y⟫ / ⟪y, y⟫ * ⟪y, x⟫) : by field_simp [-mul_re, inner_conj_sym, hT, conj_div, h₁, h₃] ... = re ⟪x, x⟫ - re (⟪x, y⟫ * ⟪y, x⟫ / ⟪y, y⟫) : by rw [div_mul_eq_mul_div_comm, ←mul_div_assoc] ... = re ⟪x, x⟫ - re (⟪x, y⟫ * ⟪y, x⟫ / re ⟪y, y⟫) : by conv_lhs { rw [h₄] } ... = re ⟪x, x⟫ - re (⟪x, y⟫ * ⟪y, x⟫) / re ⟪y, y⟫ : by rw [div_re_of_real] ... = re ⟪x, x⟫ - abs (⟪x, y⟫ * ⟪y, x⟫) / re ⟪y, y⟫ : by rw [inner_mul_conj_re_abs] ... = re ⟪x, x⟫ - abs ⟪x, y⟫ * abs ⟪y, x⟫ / re ⟪y, y⟫ : by rw is_R_or_C.abs_mul, have hmain' : abs ⟪x, y⟫ * abs ⟪y, x⟫ / re ⟪y, y⟫ ≤ re ⟪x, x⟫ := by linarith, have := (mul_le_mul_right h₅).mpr hmain', rwa [div_mul_cancel (abs ⟪x, y⟫ * abs ⟪y, x⟫) h₆] at this } end /-- Norm constructed from a `inner_product_space.core` structure, defined to be the square root of the scalar product. -/ def to_has_norm : has_norm F := { norm := λ x, sqrt (re ⟪x, x⟫) } local attribute [instance] to_has_norm lemma norm_eq_sqrt_inner (x : F) : ∥x∥ = sqrt (re ⟪x, x⟫) := rfl lemma inner_self_eq_norm_square (x : F) : re ⟪x, x⟫ = ∥x∥ * ∥x∥ := by rw[norm_eq_sqrt_inner, ←sqrt_mul inner_self_nonneg (re ⟪x, x⟫), sqrt_mul_self inner_self_nonneg] lemma sqrt_norm_sq_eq_norm {x : F} : sqrt (norm_sqF x) = ∥x∥ := rfl /-- Cauchy–Schwarz inequality with norm -/ lemma abs_inner_le_norm (x y : F) : abs ⟪x, y⟫ ≤ ∥x∥ * ∥y∥ := nonneg_le_nonneg_of_squares_le (mul_nonneg (sqrt_nonneg _) (sqrt_nonneg _)) begin have H : ∥x∥ * ∥y∥ * (∥x∥ * ∥y∥) = re ⟪y, y⟫ * re ⟪x, x⟫, { simp only [inner_self_eq_norm_square], ring, }, rw H, conv begin to_lhs, congr, rw[inner_abs_conj_sym], end, exact inner_mul_inner_self_le y x, end /-- Normed group structure constructed from an `inner_product_space.core` structure -/ def to_normed_group : normed_group F := normed_group.of_core F { norm_eq_zero_iff := assume x, begin split, { intro H, change sqrt (re ⟪x, x⟫) = 0 at H, rw [sqrt_eq_zero inner_self_nonneg] at H, apply (inner_self_eq_zero : ⟪x, x⟫ = 0 ↔ x = 0).mp, rw ext_iff, exact ⟨by simp [H], by simp [inner_self_im_zero]⟩ }, { rintro rfl, change sqrt (re ⟪0, 0⟫) = 0, simp only [sqrt_zero, inner_zero_right, add_monoid_hom.map_zero] } end, triangle := assume x y, begin have h₁ : abs ⟪x, y⟫ ≤ ∥x∥ * ∥y∥ := abs_inner_le_norm _ _, have h₂ : re ⟪x, y⟫ ≤ abs ⟪x, y⟫ := re_le_abs _, have h₃ : re ⟪x, y⟫ ≤ ∥x∥ * ∥y∥ := by linarith, have h₄ : re ⟪y, x⟫ ≤ ∥x∥ * ∥y∥ := by rwa [←inner_conj_sym, conj_re], have : ∥x + y∥ * ∥x + y∥ ≤ (∥x∥ + ∥y∥) * (∥x∥ + ∥y∥), { simp [←inner_self_eq_norm_square, inner_add_add_self, add_mul, mul_add, mul_comm], linarith }, exact nonneg_le_nonneg_of_squares_le (add_nonneg (sqrt_nonneg _) (sqrt_nonneg _)) this end, norm_neg := λ x, by simp only [norm, inner_neg_left, neg_neg, inner_neg_right] } local attribute [instance] to_normed_group /-- Normed space structure constructed from a `inner_product_space.core` structure -/ def to_normed_space : normed_space 𝕜 F := { norm_smul_le := assume r x, begin rw [norm_eq_sqrt_inner, inner_smul_left, inner_smul_right, ←mul_assoc], rw [conj_mul_eq_norm_sq_left, of_real_mul_re, sqrt_mul, ←inner_norm_sq_eq_inner_self, of_real_re], { simp [sqrt_norm_sq_eq_norm, is_R_or_C.sqrt_norm_sq_eq_norm] }, { exact norm_sq_nonneg r } end } end inner_product_space.of_core /-- Given a `inner_product_space.core` structure on a space, one can use it to turn the space into an inner product space, constructing the norm out of the inner product -/ def inner_product_space.of_core [add_comm_group F] [semimodule 𝕜 F] (c : inner_product_space.core 𝕜 F) : inner_product_space 𝕜 F := begin letI : normed_group F := @inner_product_space.of_core.to_normed_group 𝕜 F _ _ _ c, letI : normed_space 𝕜 F := @inner_product_space.of_core.to_normed_space 𝕜 F _ _ _ c, exact { norm_sq_eq_inner := λ x, begin have h₁ : ∥x∥^2 = (sqrt (re (c.inner x x))) ^ 2 := rfl, have h₂ : 0 ≤ re (c.inner x x) := inner_product_space.of_core.inner_self_nonneg, simp [h₁, sqr_sqrt, h₂], end, ..c } end /-! ### Properties of inner product spaces -/ variables [inner_product_space 𝕜 E] [inner_product_space ℝ F] local notation `⟪`x`, `y`⟫` := @inner 𝕜 _ _ x y local notation `IK` := @is_R_or_C.I 𝕜 _ local notation `absR` := _root_.abs local notation `absK` := @is_R_or_C.abs 𝕜 _ local postfix `†`:90 := @is_R_or_C.conj 𝕜 _ local postfix `⋆`:90 := complex.conj export inner_product_space (norm_sq_eq_inner) section basic_properties @[simp] lemma inner_conj_sym (x y : E) : ⟪y, x⟫† = ⟪x, y⟫ := inner_product_space.conj_sym _ _ lemma real_inner_comm (x y : F) : ⟪y, x⟫_ℝ = ⟪x, y⟫_ℝ := inner_conj_sym x y lemma inner_eq_zero_sym {x y : E} : ⟪x, y⟫ = 0 ↔ ⟪y, x⟫ = 0 := ⟨λ h, by simp [←inner_conj_sym, h], λ h, by simp [←inner_conj_sym, h]⟩ @[simp] lemma inner_self_nonneg_im {x : E} : im ⟪x, x⟫ = 0 := by rw [← @of_real_inj 𝕜, im_eq_conj_sub]; simp lemma inner_self_im_zero {x : E} : im ⟪x, x⟫ = 0 := inner_self_nonneg_im lemma inner_add_left {x y z : E} : ⟪x + y, z⟫ = ⟪x, z⟫ + ⟪y, z⟫ := inner_product_space.add_left _ _ _ lemma inner_add_right {x y z : E} : ⟪x, y + z⟫ = ⟪x, y⟫ + ⟪x, z⟫ := begin rw [←inner_conj_sym, inner_add_left, ring_hom.map_add], conv_rhs { rw ←inner_conj_sym, conv { congr, skip, rw ←inner_conj_sym } } end lemma inner_re_symm {x y : E} : re ⟪x, y⟫ = re ⟪y, x⟫ := by rw [←inner_conj_sym, conj_re] lemma inner_im_symm {x y : E} : im ⟪x, y⟫ = -im ⟪y, x⟫ := by rw [←inner_conj_sym, conj_im] lemma inner_smul_left {x y : E} {r : 𝕜} : ⟪r • x, y⟫ = r† * ⟪x, y⟫ := inner_product_space.smul_left _ _ _ lemma real_inner_smul_left {x y : F} {r : ℝ} : ⟪r • x, y⟫_ℝ = r * ⟪x, y⟫_ℝ := inner_smul_left lemma inner_smul_real_left {x y : E} {r : ℝ} : ⟪(r : 𝕜) • x, y⟫ = r • ⟪x, y⟫ := by { rw [inner_smul_left, conj_of_real, algebra.smul_def], refl } lemma inner_smul_right {x y : E} {r : 𝕜} : ⟪x, r • y⟫ = r * ⟪x, y⟫ := by rw [←inner_conj_sym, inner_smul_left, ring_hom.map_mul, conj_conj, inner_conj_sym] lemma real_inner_smul_right {x y : F} {r : ℝ} : ⟪x, r • y⟫_ℝ = r * ⟪x, y⟫_ℝ := inner_smul_right lemma inner_smul_real_right {x y : E} {r : ℝ} : ⟪x, (r : 𝕜) • y⟫ = r • ⟪x, y⟫ := by { rw [inner_smul_right, algebra.smul_def], refl } /-- The inner product as a sesquilinear form. -/ @[simps] def sesq_form_of_inner : sesq_form 𝕜 E (conj_to_ring_equiv 𝕜) := { sesq := λ x y, ⟪y, x⟫, -- Note that sesquilinear forms are linear in the first argument sesq_add_left := λ x y z, inner_add_right, sesq_add_right := λ x y z, inner_add_left, sesq_smul_left := λ r x y, inner_smul_right, sesq_smul_right := λ r x y, inner_smul_left } /-- The real inner product as a bilinear form. -/ @[simps] def bilin_form_of_real_inner : bilin_form ℝ F := { bilin := inner, bilin_add_left := λ x y z, inner_add_left, bilin_smul_left := λ a x y, inner_smul_left, bilin_add_right := λ x y z, inner_add_right, bilin_smul_right := λ a x y, inner_smul_right } /-- An inner product with a sum on the left. -/ lemma sum_inner {ι : Type*} (s : finset ι) (f : ι → E) (x : E) : ⟪∑ i in s, f i, x⟫ = ∑ i in s, ⟪f i, x⟫ := sesq_form.sum_right (sesq_form_of_inner) _ _ _ /-- An inner product with a sum on the right. -/ lemma inner_sum {ι : Type*} (s : finset ι) (f : ι → E) (x : E) : ⟪x, ∑ i in s, f i⟫ = ∑ i in s, ⟪x, f i⟫ := sesq_form.sum_left (sesq_form_of_inner) _ _ _ /-- An inner product with a sum on the left, `finsupp` version. -/ lemma finsupp.sum_inner {ι : Type*} (l : ι →₀ 𝕜) (v : ι → E) (x : E) : ⟪l.sum (λ (i : ι) (a : 𝕜), a • v i), x⟫ = l.sum (λ (i : ι) (a : 𝕜), (is_R_or_C.conj a) • ⟪v i, x⟫) := by { convert sum_inner l.support (λ a, l a • v a) x, simp [inner_smul_left, finsupp.sum] } /-- An inner product with a sum on the right, `finsupp` version. -/ lemma finsupp.inner_sum {ι : Type*} (l : ι →₀ 𝕜) (v : ι → E) (x : E) : ⟪x, l.sum (λ (i : ι) (a : 𝕜), a • v i)⟫ = l.sum (λ (i : ι) (a : 𝕜), a • ⟪x, v i⟫) := by { convert inner_sum l.support (λ a, l a • v a) x, simp [inner_smul_right, finsupp.sum] } @[simp] lemma inner_zero_left {x : E} : ⟪0, x⟫ = 0 := by rw [← zero_smul 𝕜 (0:E), inner_smul_left, ring_hom.map_zero, zero_mul] lemma inner_re_zero_left {x : E} : re ⟪0, x⟫ = 0 := by simp only [inner_zero_left, add_monoid_hom.map_zero] @[simp] lemma inner_zero_right {x : E} : ⟪x, 0⟫ = 0 := by rw [←inner_conj_sym, inner_zero_left, ring_hom.map_zero] lemma inner_re_zero_right {x : E} : re ⟪x, 0⟫ = 0 := by simp only [inner_zero_right, add_monoid_hom.map_zero] lemma inner_self_nonneg {x : E} : 0 ≤ re ⟪x, x⟫ := by rw [←norm_sq_eq_inner]; exact pow_nonneg (norm_nonneg x) 2 lemma real_inner_self_nonneg {x : F} : 0 ≤ ⟪x, x⟫_ℝ := @inner_self_nonneg ℝ F _ _ x @[simp] lemma inner_self_eq_zero {x : E} : ⟪x, x⟫ = 0 ↔ x = 0 := begin split, { intro h, have h₁ : re ⟪x, x⟫ = 0 := by rw is_R_or_C.ext_iff at h; simp [h.1], rw [←norm_sq_eq_inner x] at h₁, rw [←norm_eq_zero], exact pow_eq_zero h₁ }, { rintro rfl, exact inner_zero_left } end @[simp] lemma inner_self_nonpos {x : E} : re ⟪x, x⟫ ≤ 0 ↔ x = 0 := begin split, { intro h, rw ←inner_self_eq_zero, have H₁ : re ⟪x, x⟫ ≥ 0, exact inner_self_nonneg, have H₂ : re ⟪x, x⟫ = 0, exact le_antisymm h H₁, rw is_R_or_C.ext_iff, exact ⟨by simp [H₂], by simp [inner_self_nonneg_im]⟩ }, { rintro rfl, simp only [inner_zero_left, add_monoid_hom.map_zero] } end lemma real_inner_self_nonpos {x : F} : ⟪x, x⟫_ℝ ≤ 0 ↔ x = 0 := by { have h := @inner_self_nonpos ℝ F _ _ x, simpa using h } @[simp] lemma inner_self_re_to_K {x : E} : (re ⟪x, x⟫ : 𝕜) = ⟪x, x⟫ := by rw is_R_or_C.ext_iff; exact ⟨by simp, by simp [inner_self_nonneg_im]⟩ lemma inner_self_eq_norm_sq_to_K (x : E) : ⟪x, x⟫ = (∥x∥ ^ 2 : 𝕜) := begin suffices : (is_R_or_C.re ⟪x, x⟫ : 𝕜) = ∥x∥ ^ 2, { simpa [inner_self_re_to_K] using this }, exact_mod_cast (norm_sq_eq_inner x).symm end lemma inner_self_re_abs {x : E} : re ⟪x, x⟫ = abs ⟪x, x⟫ := begin have H : ⟪x, x⟫ = (re ⟪x, x⟫ : 𝕜) + im ⟪x, x⟫ * I, { rw re_add_im, }, rw [H, is_add_hom.map_add re ((re ⟪x, x⟫) : 𝕜) (((im ⟪x, x⟫) : 𝕜) * I)], rw [mul_re, I_re, mul_zero, I_im, zero_sub, tactic.ring.add_neg_eq_sub], rw [of_real_re, of_real_im, sub_zero, inner_self_nonneg_im], simp only [abs_of_real, add_zero, of_real_zero, zero_mul], exact (_root_.abs_of_nonneg inner_self_nonneg).symm, end lemma inner_self_abs_to_K {x : E} : (absK ⟪x, x⟫ : 𝕜) = ⟪x, x⟫ := by { rw[←inner_self_re_abs], exact inner_self_re_to_K } lemma real_inner_self_abs {x : F} : absR ⟪x, x⟫_ℝ = ⟪x, x⟫_ℝ := by { have h := @inner_self_abs_to_K ℝ F _ _ x, simpa using h } lemma inner_abs_conj_sym {x y : E} : abs ⟪x, y⟫ = abs ⟪y, x⟫ := by rw [←inner_conj_sym, abs_conj] @[simp] lemma inner_neg_left {x y : E} : ⟪-x, y⟫ = -⟪x, y⟫ := by { rw [← neg_one_smul 𝕜 x, inner_smul_left], simp } @[simp] lemma inner_neg_right {x y : E} : ⟪x, -y⟫ = -⟪x, y⟫ := by rw [←inner_conj_sym, inner_neg_left]; simp only [ring_hom.map_neg, inner_conj_sym] lemma inner_neg_neg {x y : E} : ⟪-x, -y⟫ = ⟪x, y⟫ := by simp @[simp] lemma inner_self_conj {x : E} : ⟪x, x⟫† = ⟪x, x⟫ := by rw [is_R_or_C.ext_iff]; exact ⟨by rw [conj_re], by rw [conj_im, inner_self_im_zero, neg_zero]⟩ lemma inner_sub_left {x y z : E} : ⟪x - y, z⟫ = ⟪x, z⟫ - ⟪y, z⟫ := by { simp [sub_eq_add_neg, inner_add_left] } lemma inner_sub_right {x y z : E} : ⟪x, y - z⟫ = ⟪x, y⟫ - ⟪x, z⟫ := by { simp [sub_eq_add_neg, inner_add_right] } lemma inner_mul_conj_re_abs {x y : E} : re (⟪x, y⟫ * ⟪y, x⟫) = abs (⟪x, y⟫ * ⟪y, x⟫) := by { rw[←inner_conj_sym, mul_comm], exact re_eq_abs_of_mul_conj (inner y x), } /-- Expand `⟪x + y, x + y⟫` -/ lemma inner_add_add_self {x y : E} : ⟪x + y, x + y⟫ = ⟪x, x⟫ + ⟪x, y⟫ + ⟪y, x⟫ + ⟪y, y⟫ := by simp only [inner_add_left, inner_add_right]; ring /-- Expand `⟪x + y, x + y⟫_ℝ` -/ lemma real_inner_add_add_self {x y : F} : ⟪x + y, x + y⟫_ℝ = ⟪x, x⟫_ℝ + 2 * ⟪x, y⟫_ℝ + ⟪y, y⟫_ℝ := begin have : ⟪y, x⟫_ℝ = ⟪x, y⟫_ℝ := by rw [←inner_conj_sym]; refl, simp [inner_add_add_self, this], ring, end /- Expand `⟪x - y, x - y⟫` -/ lemma inner_sub_sub_self {x y : E} : ⟪x - y, x - y⟫ = ⟪x, x⟫ - ⟪x, y⟫ - ⟪y, x⟫ + ⟪y, y⟫ := by simp only [inner_sub_left, inner_sub_right]; ring /-- Expand `⟪x - y, x - y⟫_ℝ` -/ lemma real_inner_sub_sub_self {x y : F} : ⟪x - y, x - y⟫_ℝ = ⟪x, x⟫_ℝ - 2 * ⟪x, y⟫_ℝ + ⟪y, y⟫_ℝ := begin have : ⟪y, x⟫_ℝ = ⟪x, y⟫_ℝ := by rw [←inner_conj_sym]; refl, simp [inner_sub_sub_self, this], ring, end /-- Parallelogram law -/ lemma parallelogram_law {x y : E} : ⟪x + y, x + y⟫ + ⟪x - y, x - y⟫ = 2 * (⟪x, x⟫ + ⟪y, y⟫) := by simp [inner_add_add_self, inner_sub_sub_self, two_mul, sub_eq_add_neg, add_comm, add_left_comm] /-- Cauchy–Schwarz inequality. This proof follows "Proof 2" on Wikipedia. -/ lemma inner_mul_inner_self_le (x y : E) : abs ⟪x, y⟫ * abs ⟪y, x⟫ ≤ re ⟪x, x⟫ * re ⟪y, y⟫ := begin by_cases hy : y = 0, { rw [hy], simp only [is_R_or_C.abs_zero, inner_zero_left, mul_zero, add_monoid_hom.map_zero] }, { change y ≠ 0 at hy, have hy' : ⟪y, y⟫ ≠ 0 := λ h, by rw [inner_self_eq_zero] at h; exact hy h, set T := ⟪y, x⟫ / ⟪y, y⟫ with hT, have h₁ : re ⟪y, x⟫ = re ⟪x, y⟫ := inner_re_symm, have h₂ : im ⟪y, x⟫ = -im ⟪x, y⟫ := inner_im_symm, have h₃ : ⟪y, x⟫ * ⟪x, y⟫ * ⟪y, y⟫ / (⟪y, y⟫ * ⟪y, y⟫) = ⟪y, x⟫ * ⟪x, y⟫ / ⟪y, y⟫, { rw [mul_div_assoc], have : ⟪y, y⟫ / (⟪y, y⟫ * ⟪y, y⟫) = 1 / ⟪y, y⟫ := by rw [div_mul_eq_div_mul_one_div, div_self hy', one_mul], rw [this, div_eq_mul_inv, one_mul, ←div_eq_mul_inv] }, have h₄ : ⟪y, y⟫ = re ⟪y, y⟫ := by simp, have h₅ : re ⟪y, y⟫ > 0, { refine lt_of_le_of_ne inner_self_nonneg _, intro H, apply hy', rw is_R_or_C.ext_iff, exact ⟨by simp [H],by simp [inner_self_nonneg_im]⟩ }, have h₆ : re ⟪y, y⟫ ≠ 0 := ne_of_gt h₅, have hmain := calc 0 ≤ re ⟪x - T • y, x - T • y⟫ : inner_self_nonneg ... = re ⟪x, x⟫ - re ⟪T • y, x⟫ - re ⟪x, T • y⟫ + re ⟪T • y, T • y⟫ : by simp [inner_sub_sub_self, inner_smul_left, inner_smul_right, h₁, h₂] ... = re ⟪x, x⟫ - re (T† * ⟪y, x⟫) - re (T * ⟪x, y⟫) + re (T * T† * ⟪y, y⟫) : by simp [inner_smul_left, inner_smul_right, mul_assoc] ... = re ⟪x, x⟫ - re (⟪x, y⟫ / ⟪y, y⟫ * ⟪y, x⟫) : by field_simp [-mul_re, hT, conj_div, h₁, h₃, inner_conj_sym] ... = re ⟪x, x⟫ - re (⟪x, y⟫ * ⟪y, x⟫ / ⟪y, y⟫) : by rw [div_mul_eq_mul_div_comm, ←mul_div_assoc] ... = re ⟪x, x⟫ - re (⟪x, y⟫ * ⟪y, x⟫ / re ⟪y, y⟫) : by conv_lhs { rw [h₄] } ... = re ⟪x, x⟫ - re (⟪x, y⟫ * ⟪y, x⟫) / re ⟪y, y⟫ : by rw [div_re_of_real] ... = re ⟪x, x⟫ - abs (⟪x, y⟫ * ⟪y, x⟫) / re ⟪y, y⟫ : by rw [inner_mul_conj_re_abs] ... = re ⟪x, x⟫ - abs ⟪x, y⟫ * abs ⟪y, x⟫ / re ⟪y, y⟫ : by rw is_R_or_C.abs_mul, have hmain' : abs ⟪x, y⟫ * abs ⟪y, x⟫ / re ⟪y, y⟫ ≤ re ⟪x, x⟫ := by linarith, have := (mul_le_mul_right h₅).mpr hmain', rwa [div_mul_cancel (abs ⟪x, y⟫ * abs ⟪y, x⟫) h₆] at this } end /-- Cauchy–Schwarz inequality for real inner products. -/ lemma real_inner_mul_inner_self_le (x y : F) : ⟪x, y⟫_ℝ * ⟪x, y⟫_ℝ ≤ ⟪x, x⟫_ℝ * ⟪y, y⟫_ℝ := begin have h₁ : ⟪y, x⟫_ℝ = ⟪x, y⟫_ℝ := by rw [←inner_conj_sym]; refl, have h₂ := @inner_mul_inner_self_le ℝ F _ _ x y, dsimp at h₂, have h₃ := abs_mul_abs_self ⟪x, y⟫_ℝ, rw [h₁] at h₂, simpa [h₃] using h₂, end /-- A family of vectors is linearly independent if they are nonzero and orthogonal. -/ lemma linear_independent_of_ne_zero_of_inner_eq_zero {ι : Type*} {v : ι → E} (hz : ∀ i, v i ≠ 0) (ho : ∀ i j, i ≠ j → ⟪v i, v j⟫ = 0) : linear_independent 𝕜 v := begin rw linear_independent_iff', intros s g hg i hi, have h' : g i * inner (v i) (v i) = inner (v i) (∑ j in s, g j • v j), { rw inner_sum, symmetry, convert finset.sum_eq_single i _ _, { rw inner_smul_right }, { intros j hj hji, rw [inner_smul_right, ho i j hji.symm, mul_zero] }, { exact λ h, false.elim (h hi) } }, simpa [hg, hz] using h' end end basic_properties section orthonormal_sets variables {ι : Type*} (𝕜) include 𝕜 /-- An orthonormal set of vectors in an `inner_product_space` -/ def orthonormal (v : ι → E) : Prop := (∀ i, ∥v i∥ = 1) ∧ (∀ {i j}, i ≠ j → ⟪v i, v j⟫ = 0) omit 𝕜 variables {𝕜} /-- `if ... then ... else` characterization of an indexed set of vectors being orthonormal. (Inner product equals Kronecker delta.) -/ lemma orthonormal_iff_ite {v : ι → E} : orthonormal 𝕜 v ↔ ∀ i j, ⟪v i, v j⟫ = if i = j then (1:𝕜) else (0:𝕜) := begin split, { intros hv i j, split_ifs, { simp [h, inner_self_eq_norm_sq_to_K, hv.1] }, { exact hv.2 h } }, { intros h, split, { intros i, have h' : ∥v i∥ ^ 2 = 1 ^ 2 := by simp [norm_sq_eq_inner, h i i], have h₁ : 0 ≤ ∥v i∥ := norm_nonneg _, have h₂ : (0:ℝ) ≤ 1 := by norm_num, rwa eq_of_pow_two_eq_pow_two h₁ h₂ at h' }, { intros i j hij, simpa [hij] using h i j } } end /-- `if ... then ... else` characterization of a set of vectors being orthonormal. (Inner product equals Kronecker delta.) -/ theorem orthonormal_subtype_iff_ite {s : set E} : orthonormal 𝕜 (coe : s → E) ↔ (∀ v ∈ s, ∀ w ∈ s, ⟪v, w⟫ = if v = w then 1 else 0) := begin rw orthonormal_iff_ite, split, { intros h v hv w hw, convert h ⟨v, hv⟩ ⟨w, hw⟩ using 1, simp }, { rintros h ⟨v, hv⟩ ⟨w, hw⟩, convert h v hv w hw using 1, simp } end /-- The inner product of a linear combination of a set of orthonormal vectors with one of those vectors picks out the coefficient of that vector. -/ lemma orthonormal.inner_right_finsupp {v : ι → E} (hv : orthonormal 𝕜 v) (l : ι →₀ 𝕜) (i : ι) : ⟪v i, finsupp.total ι E 𝕜 v l⟫ = l i := by simp [finsupp.total_apply, finsupp.inner_sum, orthonormal_iff_ite.mp hv] /-- The inner product of a linear combination of a set of orthonormal vectors with one of those vectors picks out the coefficient of that vector. -/ lemma orthonormal.inner_right_fintype [fintype ι] {v : ι → E} (hv : orthonormal 𝕜 v) (l : ι → 𝕜) (i : ι) : ⟪v i, ∑ i : ι, (l i) • (v i)⟫ = l i := by simp [inner_sum, inner_smul_right, orthonormal_iff_ite.mp hv] /-- The inner product of a linear combination of a set of orthonormal vectors with one of those vectors picks out the coefficient of that vector. -/ lemma orthonormal.inner_left_finsupp {v : ι → E} (hv : orthonormal 𝕜 v) (l : ι →₀ 𝕜) (i : ι) : ⟪finsupp.total ι E 𝕜 v l, v i⟫ = conj (l i) := by rw [← inner_conj_sym, hv.inner_right_finsupp] /-- The inner product of a linear combination of a set of orthonormal vectors with one of those vectors picks out the coefficient of that vector. -/ lemma orthonormal.inner_left_fintype [fintype ι] {v : ι → E} (hv : orthonormal 𝕜 v) (l : ι → 𝕜) (i : ι) : ⟪∑ i : ι, (l i) • (v i), v i⟫ = conj (l i) := by simp [sum_inner, inner_smul_left, orthonormal_iff_ite.mp hv] /-- An orthonormal set is linearly independent. -/ lemma orthonormal.linear_independent {v : ι → E} (hv : orthonormal 𝕜 v) : linear_independent 𝕜 v := begin rw linear_independent_iff, intros l hl, ext i, have key : ⟪v i, finsupp.total ι E 𝕜 v l⟫ = ⟪v i, 0⟫ := by rw hl, simpa [hv.inner_right_finsupp] using key end /-- A subfamily of an orthonormal family (i.e., a composition with an injective map) is an orthonormal family. -/ lemma orthonormal.comp {ι' : Type*} {v : ι → E} (hv : orthonormal 𝕜 v) (f : ι' → ι) (hf : function.injective f) : orthonormal 𝕜 (v ∘ f) := begin rw orthonormal_iff_ite at ⊢ hv, intros i j, convert hv (f i) (f j) using 1, simp [hf.eq_iff] end /-- A linear combination of some subset of an orthonormal set is orthogonal to other members of the set. -/ lemma orthonormal.inner_finsupp_eq_zero {v : ι → E} (hv : orthonormal 𝕜 v) {s : set ι} {i : ι} (hi : i ∉ s) {l : ι →₀ 𝕜} (hl : l ∈ finsupp.supported 𝕜 𝕜 s) : ⟪finsupp.total ι E 𝕜 v l, v i⟫ = 0 := begin rw finsupp.mem_supported' at hl, simp [hv.inner_left_finsupp, hl i hi], end /- The material that follows, culminating in the existence of a maximal orthonormal subset, is adapted from the corresponding development of the theory of linearly independents sets. See `exists_linear_independent` in particular. -/ variables (𝕜 E) lemma orthonormal_empty : orthonormal 𝕜 (λ x, x : (∅ : set E) → E) := by simp [orthonormal_subtype_iff_ite] variables {𝕜 E} lemma orthonormal_Union_of_directed {η : Type*} {s : η → set E} (hs : directed (⊆) s) (h : ∀ i, orthonormal 𝕜 (λ x, x : s i → E)) : orthonormal 𝕜 (λ x, x : (⋃ i, s i) → E) := begin rw orthonormal_subtype_iff_ite, rintros x ⟨_, ⟨i, rfl⟩, hxi⟩ y ⟨_, ⟨j, rfl⟩, hyj⟩, obtain ⟨k, hik, hjk⟩ := hs i j, have h_orth : orthonormal 𝕜 (λ x, x : (s k) → E) := h k, rw orthonormal_subtype_iff_ite at h_orth, exact h_orth x (hik hxi) y (hjk hyj) end lemma orthonormal_sUnion_of_directed {s : set (set E)} (hs : directed_on (⊆) s) (h : ∀ a ∈ s, orthonormal 𝕜 (λ x, x : (a : set E) → E)) : orthonormal 𝕜 (λ x, x : (⋃₀ s) → E) := by rw set.sUnion_eq_Union; exact orthonormal_Union_of_directed hs.directed_coe (by simpa using h) /-- Given an orthonormal set `v` of vectors in `E`, there exists a maximal orthonormal set containing it. -/ lemma exists_maximal_orthonormal {s : set E} (hs : orthonormal 𝕜 (coe : s → E)) : ∃ w ⊇ s, orthonormal 𝕜 (coe : w → E) ∧ ∀ u ⊇ w, orthonormal 𝕜 (coe : u → E) → u = w := begin rcases zorn.zorn_subset₀ {b | orthonormal 𝕜 (coe : b → E)} _ _ hs with ⟨b, bi, sb, h⟩, { refine ⟨b, sb, bi, _⟩, exact λ u hus hu, h u hu hus }, { refine λ c hc cc c0, ⟨⋃₀ c, _, _⟩, { exact orthonormal_sUnion_of_directed cc.directed_on (λ x xc, hc xc) }, { exact λ _, set.subset_sUnion_of_mem } } end lemma orthonormal.ne_zero {v : ι → E} (hv : orthonormal 𝕜 v) (i : ι) : v i ≠ 0 := begin have : ∥v i∥ ≠ 0, { rw hv.1 i, norm_num }, simpa using this end open finite_dimensional lemma is_basis_of_orthonormal_of_card_eq_findim [fintype ι] [nonempty ι] {v : ι → E} (hv : orthonormal 𝕜 v) (card_eq : fintype.card ι = findim 𝕜 E) : is_basis 𝕜 v := is_basis_of_linear_independent_of_card_eq_findim hv.linear_independent card_eq end orthonormal_sets section norm lemma norm_eq_sqrt_inner (x : E) : ∥x∥ = sqrt (re ⟪x, x⟫) := begin have h₁ : ∥x∥^2 = re ⟪x, x⟫ := norm_sq_eq_inner x, have h₂ := congr_arg sqrt h₁, simpa using h₂, end lemma norm_eq_sqrt_real_inner (x : F) : ∥x∥ = sqrt ⟪x, x⟫_ℝ := by { have h := @norm_eq_sqrt_inner ℝ F _ _ x, simpa using h } lemma inner_self_eq_norm_square (x : E) : re ⟪x, x⟫ = ∥x∥ * ∥x∥ := by rw[norm_eq_sqrt_inner, ←sqrt_mul inner_self_nonneg (re ⟪x, x⟫), sqrt_mul_self inner_self_nonneg] lemma real_inner_self_eq_norm_square (x : F) : ⟪x, x⟫_ℝ = ∥x∥ * ∥x∥ := by { have h := @inner_self_eq_norm_square ℝ F _ _ x, simpa using h } /-- Expand the square -/ lemma norm_add_pow_two {x y : E} : ∥x + y∥^2 = ∥x∥^2 + 2 * (re ⟪x, y⟫) + ∥y∥^2 := begin repeat {rw [pow_two, ←inner_self_eq_norm_square]}, rw[inner_add_add_self, two_mul], simp only [add_assoc, add_left_inj, add_right_inj, add_monoid_hom.map_add], rw [←inner_conj_sym, conj_re], end /-- Expand the square -/ lemma norm_add_pow_two_real {x y : F} : ∥x + y∥^2 = ∥x∥^2 + 2 * ⟪x, y⟫_ℝ + ∥y∥^2 := by { have h := @norm_add_pow_two ℝ F _ _, simpa using h } /-- Expand the square -/ lemma norm_add_mul_self {x y : E} : ∥x + y∥ * ∥x + y∥ = ∥x∥ * ∥x∥ + 2 * (re ⟪x, y⟫) + ∥y∥ * ∥y∥ := by { repeat {rw [← pow_two]}, exact norm_add_pow_two } /-- Expand the square -/ lemma norm_add_mul_self_real {x y : F} : ∥x + y∥ * ∥x + y∥ = ∥x∥ * ∥x∥ + 2 * ⟪x, y⟫_ℝ + ∥y∥ * ∥y∥ := by { have h := @norm_add_mul_self ℝ F _ _, simpa using h } /-- Expand the square -/ lemma norm_sub_pow_two {x y : E} : ∥x - y∥^2 = ∥x∥^2 - 2 * (re ⟪x, y⟫) + ∥y∥^2 := begin repeat {rw [pow_two, ←inner_self_eq_norm_square]}, rw[inner_sub_sub_self], calc re (⟪x, x⟫ - ⟪x, y⟫ - ⟪y, x⟫ + ⟪y, y⟫) = re ⟪x, x⟫ - re ⟪x, y⟫ - re ⟪y, x⟫ + re ⟪y, y⟫ : by simp ... = -re ⟪y, x⟫ - re ⟪x, y⟫ + re ⟪x, x⟫ + re ⟪y, y⟫ : by ring ... = -re (⟪x, y⟫†) - re ⟪x, y⟫ + re ⟪x, x⟫ + re ⟪y, y⟫ : by rw[inner_conj_sym] ... = -re ⟪x, y⟫ - re ⟪x, y⟫ + re ⟪x, x⟫ + re ⟪y, y⟫ : by rw[conj_re] ... = re ⟪x, x⟫ - 2*re ⟪x, y⟫ + re ⟪y, y⟫ : by ring end /-- Expand the square -/ lemma norm_sub_pow_two_real {x y : F} : ∥x - y∥^2 = ∥x∥^2 - 2 * ⟪x, y⟫_ℝ + ∥y∥^2 := norm_sub_pow_two /-- Expand the square -/ lemma norm_sub_mul_self {x y : E} : ∥x - y∥ * ∥x - y∥ = ∥x∥ * ∥x∥ - 2 * re ⟪x, y⟫ + ∥y∥ * ∥y∥ := by { repeat {rw [← pow_two]}, exact norm_sub_pow_two } /-- Expand the square -/ lemma norm_sub_mul_self_real {x y : F} : ∥x - y∥ * ∥x - y∥ = ∥x∥ * ∥x∥ - 2 * ⟪x, y⟫_ℝ + ∥y∥ * ∥y∥ := by { have h := @norm_sub_mul_self ℝ F _ _, simpa using h } /-- Cauchy–Schwarz inequality with norm -/ lemma abs_inner_le_norm (x y : E) : abs ⟪x, y⟫ ≤ ∥x∥ * ∥y∥ := nonneg_le_nonneg_of_squares_le (mul_nonneg (norm_nonneg _) (norm_nonneg _)) begin have : ∥x∥ * ∥y∥ * (∥x∥ * ∥y∥) = (re ⟪x, x⟫) * (re ⟪y, y⟫), simp only [inner_self_eq_norm_square], ring, rw this, conv_lhs { congr, skip, rw [inner_abs_conj_sym] }, exact inner_mul_inner_self_le _ _ end /-- Cauchy–Schwarz inequality with norm -/ lemma abs_real_inner_le_norm (x y : F) : absR ⟪x, y⟫_ℝ ≤ ∥x∥ * ∥y∥ := by { have h := @abs_inner_le_norm ℝ F _ _ x y, simpa using h } /-- Cauchy–Schwarz inequality with norm -/ lemma real_inner_le_norm (x y : F) : ⟪x, y⟫_ℝ ≤ ∥x∥ * ∥y∥ := le_trans (le_abs_self _) (abs_real_inner_le_norm _ _) include 𝕜 lemma parallelogram_law_with_norm {x y : E} : ∥x + y∥ * ∥x + y∥ + ∥x - y∥ * ∥x - y∥ = 2 * (∥x∥ * ∥x∥ + ∥y∥ * ∥y∥) := begin simp only [← inner_self_eq_norm_square], rw[← re.map_add, parallelogram_law, two_mul, two_mul], simp only [re.map_add], end omit 𝕜 lemma parallelogram_law_with_norm_real {x y : F} : ∥x + y∥ * ∥x + y∥ + ∥x - y∥ * ∥x - y∥ = 2 * (∥x∥ * ∥x∥ + ∥y∥ * ∥y∥) := by { have h := @parallelogram_law_with_norm ℝ F _ _ x y, simpa using h } /-- Polarization identity: The real part of the inner product, in terms of the norm. -/ lemma re_inner_eq_norm_add_mul_self_sub_norm_mul_self_sub_norm_mul_self_div_two (x y : E) : re ⟪x, y⟫ = (∥x + y∥ * ∥x + y∥ - ∥x∥ * ∥x∥ - ∥y∥ * ∥y∥) / 2 := by { rw norm_add_mul_self, ring } /-- Polarization identity: The real part of the inner product, in terms of the norm. -/ lemma re_inner_eq_norm_mul_self_add_norm_mul_self_sub_norm_sub_mul_self_div_two (x y : E) : re ⟪x, y⟫ = (∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ - ∥x - y∥ * ∥x - y∥) / 2 := by { rw [norm_sub_mul_self], ring } /-- Polarization identity: The real part of the inner product, in terms of the norm. -/ lemma re_inner_eq_norm_add_mul_self_sub_norm_sub_mul_self_div_four (x y : E) : re ⟪x, y⟫ = (∥x + y∥ * ∥x + y∥ - ∥x - y∥ * ∥x - y∥) / 4 := by { rw [norm_add_mul_self, norm_sub_mul_self], ring } /-- Polarization identity: The imaginary part of the inner product, in terms of the norm. -/ lemma im_inner_eq_norm_sub_I_smul_mul_self_sub_norm_add_I_smul_mul_self_div_four (x y : E) : im ⟪x, y⟫ = (∥x - IK • y∥ * ∥x - IK • y∥ - ∥x + IK • y∥ * ∥x + IK • y∥) / 4 := by { simp only [norm_add_mul_self, norm_sub_mul_self, inner_smul_right, I_mul_re], ring } /-- Polarization identity: The inner product, in terms of the norm. -/ lemma inner_eq_sum_norm_sq_div_four (x y : E) : ⟪x, y⟫ = (∥x + y∥ ^ 2 - ∥x - y∥ ^ 2 + (∥x - IK • y∥ ^ 2 - ∥x + IK • y∥ ^ 2) * IK) / 4 := begin rw [← re_add_im ⟪x, y⟫, re_inner_eq_norm_add_mul_self_sub_norm_sub_mul_self_div_four, im_inner_eq_norm_sub_I_smul_mul_self_sub_norm_add_I_smul_mul_self_div_four], push_cast, simp only [pow_two, ← mul_div_right_comm, ← add_div] end section variables {E' : Type*} [inner_product_space 𝕜 E'] /-- A linear isometry preserves the inner product. -/ @[simp] lemma linear_isometry.inner_map_map (f : E →ₗᵢ[𝕜] E') (x y : E) : ⟪f x, f y⟫ = ⟪x, y⟫ := by simp [inner_eq_sum_norm_sq_div_four, ← f.norm_map] /-- A linear isometric equivalence preserves the inner product. -/ @[simp] lemma linear_isometry_equiv.inner_map_map (f : E ≃ₗᵢ[𝕜] E') (x y : E) : ⟪f x, f y⟫ = ⟪x, y⟫ := f.to_linear_isometry.inner_map_map x y /-- A linear map that preserves the inner product is a linear isometry. -/ def linear_map.isometry_of_inner (f : E →ₗ[𝕜] E') (h : ∀ x y, ⟪f x, f y⟫ = ⟪x, y⟫) : E →ₗᵢ[𝕜] E' := ⟨f, λ x, by simp only [norm_eq_sqrt_inner, h]⟩ @[simp] lemma linear_map.coe_isometry_of_inner (f : E →ₗ[𝕜] E') (h) : ⇑(f.isometry_of_inner h) = f := rfl @[simp] lemma linear_map.isometry_of_inner_to_linear_map (f : E →ₗ[𝕜] E') (h) : (f.isometry_of_inner h).to_linear_map = f := rfl /-- A linear equivalence that preserves the inner product is a linear isometric equivalence. -/ def linear_equiv.isometry_of_inner (f : E ≃ₗ[𝕜] E') (h : ∀ x y, ⟪f x, f y⟫ = ⟪x, y⟫) : E ≃ₗᵢ[𝕜] E' := ⟨f, ((f : E →ₗ[𝕜] E').isometry_of_inner h).norm_map⟩ @[simp] lemma linear_equiv.coe_isometry_of_inner (f : E ≃ₗ[𝕜] E') (h) : ⇑(f.isometry_of_inner h) = f := rfl @[simp] lemma linear_equiv.isometry_of_inner_to_linear_equiv (f : E ≃ₗ[𝕜] E') (h) : (f.isometry_of_inner h).to_linear_equiv = f := rfl end /-- Polarization identity: The real inner product, in terms of the norm. -/ lemma real_inner_eq_norm_add_mul_self_sub_norm_mul_self_sub_norm_mul_self_div_two (x y : F) : ⟪x, y⟫_ℝ = (∥x + y∥ * ∥x + y∥ - ∥x∥ * ∥x∥ - ∥y∥ * ∥y∥) / 2 := re_to_real.symm.trans $ re_inner_eq_norm_add_mul_self_sub_norm_mul_self_sub_norm_mul_self_div_two x y /-- Polarization identity: The real inner product, in terms of the norm. -/ lemma real_inner_eq_norm_mul_self_add_norm_mul_self_sub_norm_sub_mul_self_div_two (x y : F) : ⟪x, y⟫_ℝ = (∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ - ∥x - y∥ * ∥x - y∥) / 2 := re_to_real.symm.trans $ re_inner_eq_norm_mul_self_add_norm_mul_self_sub_norm_sub_mul_self_div_two x y /-- Pythagorean theorem, if-and-only-if vector inner product form. -/ lemma norm_add_square_eq_norm_square_add_norm_square_iff_real_inner_eq_zero (x y : F) : ∥x + y∥ * ∥x + y∥ = ∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ ↔ ⟪x, y⟫_ℝ = 0 := begin rw [norm_add_mul_self, add_right_cancel_iff, add_right_eq_self, mul_eq_zero], norm_num end /-- Pythagorean theorem, vector inner product form. -/ lemma norm_add_square_eq_norm_square_add_norm_square_of_inner_eq_zero (x y : E) (h : ⟪x, y⟫ = 0) : ∥x + y∥ * ∥x + y∥ = ∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ := begin rw [norm_add_mul_self, add_right_cancel_iff, add_right_eq_self, mul_eq_zero], apply or.inr, simp only [h, zero_re'], end /-- Pythagorean theorem, vector inner product form. -/ lemma norm_add_square_eq_norm_square_add_norm_square_real {x y : F} (h : ⟪x, y⟫_ℝ = 0) : ∥x + y∥ * ∥x + y∥ = ∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ := (norm_add_square_eq_norm_square_add_norm_square_iff_real_inner_eq_zero x y).2 h /-- Pythagorean theorem, subtracting vectors, if-and-only-if vector inner product form. -/ lemma norm_sub_square_eq_norm_square_add_norm_square_iff_real_inner_eq_zero (x y : F) : ∥x - y∥ * ∥x - y∥ = ∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ ↔ ⟪x, y⟫_ℝ = 0 := begin rw [norm_sub_mul_self, add_right_cancel_iff, sub_eq_add_neg, add_right_eq_self, neg_eq_zero, mul_eq_zero], norm_num end /-- Pythagorean theorem, subtracting vectors, vector inner product form. -/ lemma norm_sub_square_eq_norm_square_add_norm_square_real {x y : F} (h : ⟪x, y⟫_ℝ = 0) : ∥x - y∥ * ∥x - y∥ = ∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ := (norm_sub_square_eq_norm_square_add_norm_square_iff_real_inner_eq_zero x y).2 h /-- The sum and difference of two vectors are orthogonal if and only if they have the same norm. -/ lemma real_inner_add_sub_eq_zero_iff (x y : F) : ⟪x + y, x - y⟫_ℝ = 0 ↔ ∥x∥ = ∥y∥ := begin conv_rhs { rw ←mul_self_inj_of_nonneg (norm_nonneg _) (norm_nonneg _) }, simp only [←inner_self_eq_norm_square, inner_add_left, inner_sub_right, real_inner_comm y x, sub_eq_zero, re_to_real], split, { intro h, rw [add_comm] at h, linarith }, { intro h, linarith } end /-- The real inner product of two vectors, divided by the product of their norms, has absolute value at most 1. -/ lemma abs_real_inner_div_norm_mul_norm_le_one (x y : F) : absR (⟪x, y⟫_ℝ / (∥x∥ * ∥y∥)) ≤ 1 := begin rw _root_.abs_div, by_cases h : 0 = absR (∥x∥ * ∥y∥), { rw [←h, div_zero], norm_num }, { change 0 ≠ absR (∥x∥ * ∥y∥) at h, rw div_le_iff' (lt_of_le_of_ne (ge_iff_le.mp (_root_.abs_nonneg (∥x∥ * ∥y∥))) h), convert abs_real_inner_le_norm x y using 1, rw [_root_.abs_mul, _root_.abs_of_nonneg (norm_nonneg x), _root_.abs_of_nonneg (norm_nonneg y), mul_one] } end /-- The inner product of a vector with a multiple of itself. -/ lemma real_inner_smul_self_left (x : F) (r : ℝ) : ⟪r • x, x⟫_ℝ = r * (∥x∥ * ∥x∥) := by rw [real_inner_smul_left, ←real_inner_self_eq_norm_square] /-- The inner product of a vector with a multiple of itself. -/ lemma real_inner_smul_self_right (x : F) (r : ℝ) : ⟪x, r • x⟫_ℝ = r * (∥x∥ * ∥x∥) := by rw [inner_smul_right, ←real_inner_self_eq_norm_square] /-- The inner product of a nonzero vector with a nonzero multiple of itself, divided by the product of their norms, has absolute value 1. -/ lemma abs_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_ne_zero_mul {x : E} {r : 𝕜} (hx : x ≠ 0) (hr : r ≠ 0) : abs ⟪x, r • x⟫ / (∥x∥ * ∥r • x∥) = 1 := begin have hx' : ∥x∥ ≠ 0 := by simp [norm_eq_zero, hx], have hr' : abs r ≠ 0 := by simp [is_R_or_C.abs_eq_zero, hr], rw [inner_smul_right, is_R_or_C.abs_mul, ←inner_self_re_abs, inner_self_eq_norm_square, norm_smul], rw [is_R_or_C.norm_eq_abs, ←mul_assoc, ←div_div_eq_div_mul, mul_div_cancel _ hx', ←div_div_eq_div_mul, mul_comm, mul_div_cancel _ hr', div_self hx'], end /-- The inner product of a nonzero vector with a nonzero multiple of itself, divided by the product of their norms, has absolute value 1. -/ lemma abs_real_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_ne_zero_mul {x : F} {r : ℝ} (hx : x ≠ 0) (hr : r ≠ 0) : absR ⟪x, r • x⟫_ℝ / (∥x∥ * ∥r • x∥) = 1 := begin rw ← abs_to_real, exact abs_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_ne_zero_mul hx hr end /-- The inner product of a nonzero vector with a positive multiple of itself, divided by the product of their norms, has value 1. -/ lemma real_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_pos_mul {x : F} {r : ℝ} (hx : x ≠ 0) (hr : 0 < r) : ⟪x, r • x⟫_ℝ / (∥x∥ * ∥r • x∥) = 1 := begin rw [real_inner_smul_self_right, norm_smul, real.norm_eq_abs, ←mul_assoc ∥x∥, mul_comm _ (absR r), mul_assoc, _root_.abs_of_nonneg (le_of_lt hr), div_self], exact mul_ne_zero (ne_of_gt hr) (λ h, hx (norm_eq_zero.1 (eq_zero_of_mul_self_eq_zero h))) end /-- The inner product of a nonzero vector with a negative multiple of itself, divided by the product of their norms, has value -1. -/ lemma real_inner_div_norm_mul_norm_eq_neg_one_of_ne_zero_of_neg_mul {x : F} {r : ℝ} (hx : x ≠ 0) (hr : r < 0) : ⟪x, r • x⟫_ℝ / (∥x∥ * ∥r • x∥) = -1 := begin rw [real_inner_smul_self_right, norm_smul, real.norm_eq_abs, ←mul_assoc ∥x∥, mul_comm _ (absR r), mul_assoc, abs_of_neg hr, ←neg_mul_eq_neg_mul, div_neg_eq_neg_div, div_self], exact mul_ne_zero (ne_of_lt hr) (λ h, hx (norm_eq_zero.1 (eq_zero_of_mul_self_eq_zero h))) end /-- The inner product of two vectors, divided by the product of their norms, has absolute value 1 if and only if they are nonzero and one is a multiple of the other. One form of equality case for Cauchy-Schwarz. -/ lemma abs_inner_div_norm_mul_norm_eq_one_iff (x y : E) : abs (⟪x, y⟫ / (∥x∥ * ∥y∥)) = 1 ↔ (x ≠ 0 ∧ ∃ (r : 𝕜), r ≠ 0 ∧ y = r • x) := begin split, { intro h, have hx0 : x ≠ 0, { intro hx0, rw [hx0, inner_zero_left, zero_div] at h, norm_num at h, }, refine and.intro hx0 _, set r := ⟪x, y⟫ / (∥x∥ * ∥x∥) with hr, use r, set t := y - r • x with ht, have ht0 : ⟪x, t⟫ = 0, { rw [ht, inner_sub_right, inner_smul_right, hr], norm_cast, rw [←inner_self_eq_norm_square, inner_self_re_to_K, div_mul_cancel _ (λ h, hx0 (inner_self_eq_zero.1 h)), sub_self] }, replace h : ∥r • x∥ / ∥t + r • x∥ = 1, { rw [←sub_add_cancel y (r • x), ←ht, inner_add_right, ht0, zero_add, inner_smul_right, is_R_or_C.abs_div, is_R_or_C.abs_mul, ←inner_self_re_abs, inner_self_eq_norm_square] at h, norm_cast at h, rwa [_root_.abs_mul, abs_norm_eq_norm, abs_norm_eq_norm, ←mul_assoc, mul_comm, mul_div_mul_left _ _ (λ h, hx0 (norm_eq_zero.1 h)), ←is_R_or_C.norm_eq_abs, ←norm_smul] at h }, have hr0 : r ≠ 0, { intro hr0, rw [hr0, zero_smul, norm_zero, zero_div] at h, norm_num at h }, refine and.intro hr0 _, have h2 : ∥r • x∥ ^ 2 = ∥t + r • x∥ ^ 2, { rw [eq_of_div_eq_one h] }, replace h2 : ⟪r • x, r • x⟫ = ⟪t, t⟫ + ⟪t, r • x⟫ + ⟪r • x, t⟫ + ⟪r • x, r • x⟫, { rw [pow_two, pow_two, ←inner_self_eq_norm_square, ←inner_self_eq_norm_square ] at h2, have h2' := congr_arg (λ z : ℝ, (z : 𝕜)) h2, simp_rw [inner_self_re_to_K, inner_add_add_self] at h2', exact h2' }, conv at h2 in ⟪r • x, t⟫ { rw [inner_smul_left, ht0, mul_zero] }, symmetry' at h2, have h₁ : ⟪t, r • x⟫ = 0 := by { rw [inner_smul_right, ←inner_conj_sym, ht0], simp }, rw [add_zero, h₁, add_left_eq_self, add_zero, inner_self_eq_zero] at h2, rw h2 at ht, exact eq_of_sub_eq_zero ht.symm }, { intro h, rcases h with ⟨hx, ⟨r, ⟨hr, hy⟩⟩⟩, rw [hy, is_R_or_C.abs_div], norm_cast, rw [_root_.abs_mul, abs_norm_eq_norm, abs_norm_eq_norm], exact abs_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_ne_zero_mul hx hr } end /-- The inner product of two vectors, divided by the product of their norms, has absolute value 1 if and only if they are nonzero and one is a multiple of the other. One form of equality case for Cauchy-Schwarz. -/ lemma abs_real_inner_div_norm_mul_norm_eq_one_iff (x y : F) : absR (⟪x, y⟫_ℝ / (∥x∥ * ∥y∥)) = 1 ↔ (x ≠ 0 ∧ ∃ (r : ℝ), r ≠ 0 ∧ y = r • x) := begin have := @abs_inner_div_norm_mul_norm_eq_one_iff ℝ F _ _ x y, simpa [coe_real_eq_id] using this, end /-- If the inner product of two vectors is equal to the product of their norms, then the two vectors are multiples of each other. One form of the equality case for Cauchy-Schwarz. Compare `inner_eq_norm_mul_iff`, which takes the stronger hypothesis `⟪x, y⟫ = ∥x∥ * ∥y∥`. -/ lemma abs_inner_eq_norm_iff (x y : E) (hx0 : x ≠ 0) (hy0 : y ≠ 0): abs ⟪x, y⟫ = ∥x∥ * ∥y∥ ↔ ∃ (r : 𝕜), r ≠ 0 ∧ y = r • x := begin have hx0' : ∥x∥ ≠ 0 := by simp [norm_eq_zero, hx0], have hy0' : ∥y∥ ≠ 0 := by simp [norm_eq_zero, hy0], have hxy0 : ∥x∥ * ∥y∥ ≠ 0 := by simp [hx0', hy0'], have h₁ : abs ⟪x, y⟫ = ∥x∥ * ∥y∥ ↔ abs (⟪x, y⟫ / (∥x∥ * ∥y∥)) = 1, { refine ⟨_ ,_⟩, { intro h, norm_cast, rw [is_R_or_C.abs_div, h, abs_of_real, _root_.abs_mul, abs_norm_eq_norm, abs_norm_eq_norm], exact div_self hxy0 }, { intro h, norm_cast at h, rwa [is_R_or_C.abs_div, abs_of_real, _root_.abs_mul, abs_norm_eq_norm, abs_norm_eq_norm, div_eq_one_iff_eq hxy0] at h } }, rw [h₁, abs_inner_div_norm_mul_norm_eq_one_iff x y], have : x ≠ 0 := λ h, (hx0' $ norm_eq_zero.mpr h), simp [this] end /-- The inner product of two vectors, divided by the product of their norms, has value 1 if and only if they are nonzero and one is a positive multiple of the other. -/ lemma real_inner_div_norm_mul_norm_eq_one_iff (x y : F) : ⟪x, y⟫_ℝ / (∥x∥ * ∥y∥) = 1 ↔ (x ≠ 0 ∧ ∃ (r : ℝ), 0 < r ∧ y = r • x) := begin split, { intro h, have ha := h, apply_fun absR at ha, norm_num at ha, rcases (abs_real_inner_div_norm_mul_norm_eq_one_iff x y).1 ha with ⟨hx, ⟨r, ⟨hr, hy⟩⟩⟩, use [hx, r], refine and.intro _ hy, by_contradiction hrneg, rw hy at h, rw real_inner_div_norm_mul_norm_eq_neg_one_of_ne_zero_of_neg_mul hx (lt_of_le_of_ne (le_of_not_lt hrneg) hr) at h, norm_num at h }, { intro h, rcases h with ⟨hx, ⟨r, ⟨hr, hy⟩⟩⟩, rw hy, exact real_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_pos_mul hx hr } end /-- The inner product of two vectors, divided by the product of their norms, has value -1 if and only if they are nonzero and one is a negative multiple of the other. -/ lemma real_inner_div_norm_mul_norm_eq_neg_one_iff (x y : F) : ⟪x, y⟫_ℝ / (∥x∥ * ∥y∥) = -1 ↔ (x ≠ 0 ∧ ∃ (r : ℝ), r < 0 ∧ y = r • x) := begin split, { intro h, have ha := h, apply_fun absR at ha, norm_num at ha, rcases (abs_real_inner_div_norm_mul_norm_eq_one_iff x y).1 ha with ⟨hx, ⟨r, ⟨hr, hy⟩⟩⟩, use [hx, r], refine and.intro _ hy, by_contradiction hrpos, rw hy at h, rw real_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_pos_mul hx (lt_of_le_of_ne (le_of_not_lt hrpos) hr.symm) at h, norm_num at h }, { intro h, rcases h with ⟨hx, ⟨r, ⟨hr, hy⟩⟩⟩, rw hy, exact real_inner_div_norm_mul_norm_eq_neg_one_of_ne_zero_of_neg_mul hx hr } end /-- If the inner product of two vectors is equal to the product of their norms (i.e., `⟪x, y⟫ = ∥x∥ * ∥y∥`), then the two vectors are nonnegative real multiples of each other. One form of the equality case for Cauchy-Schwarz. Compare `abs_inner_eq_norm_iff`, which takes the weaker hypothesis `abs ⟪x, y⟫ = ∥x∥ * ∥y∥`. -/ lemma inner_eq_norm_mul_iff {x y : E} : ⟪x, y⟫ = (∥x∥ : 𝕜) * ∥y∥ ↔ (∥y∥ : 𝕜) • x = (∥x∥ : 𝕜) • y := begin by_cases h : (x = 0 ∨ y = 0), -- WLOG `x` and `y` are nonzero { cases h; simp [h] }, calc ⟪x, y⟫ = (∥x∥ : 𝕜) * ∥y∥ ↔ ∥x∥ * ∥y∥ = re ⟪x, y⟫ : begin norm_cast, split, { intros h', simp [h'] }, { have cauchy_schwarz := abs_inner_le_norm x y, intros h', rw h' at ⊢ cauchy_schwarz, rwa re_eq_self_of_le } end ... ↔ 2 * ∥x∥ * ∥y∥ * (∥x∥ * ∥y∥ - re ⟪x, y⟫) = 0 : by simp [h, show (2:ℝ) ≠ 0, by norm_num, sub_eq_zero] ... ↔ ∥(∥y∥:𝕜) • x - (∥x∥:𝕜) • y∥ * ∥(∥y∥:𝕜) • x - (∥x∥:𝕜) • y∥ = 0 : begin simp only [norm_sub_mul_self, inner_smul_left, inner_smul_right, norm_smul, conj_of_real, is_R_or_C.norm_eq_abs, abs_of_real, of_real_im, of_real_re, mul_re, abs_norm_eq_norm], refine eq.congr _ rfl, ring end ... ↔ (∥y∥ : 𝕜) • x = (∥x∥ : 𝕜) • y : by simp [norm_sub_eq_zero_iff] end /-- If the inner product of two vectors is equal to the product of their norms (i.e., `⟪x, y⟫ = ∥x∥ * ∥y∥`), then the two vectors are nonnegative real multiples of each other. One form of the equality case for Cauchy-Schwarz. Compare `abs_inner_eq_norm_iff`, which takes the weaker hypothesis `abs ⟪x, y⟫ = ∥x∥ * ∥y∥`. -/ lemma inner_eq_norm_mul_iff_real {x y : F} : ⟪x, y⟫_ℝ = ∥x∥ * ∥y∥ ↔ ∥y∥ • x = ∥x∥ • y := inner_eq_norm_mul_iff /-- If the inner product of two unit vectors is `1`, then the two vectors are equal. One form of the equality case for Cauchy-Schwarz. -/ lemma inner_eq_norm_mul_iff_of_norm_one {x y : E} (hx : ∥x∥ = 1) (hy : ∥y∥ = 1) : ⟪x, y⟫ = 1 ↔ x = y := by { convert inner_eq_norm_mul_iff using 2; simp [hx, hy] } lemma inner_lt_norm_mul_iff_real {x y : F} : ⟪x, y⟫_ℝ < ∥x∥ * ∥y∥ ↔ ∥y∥ • x ≠ ∥x∥ • y := calc ⟪x, y⟫_ℝ < ∥x∥ * ∥y∥ ↔ ⟪x, y⟫_ℝ ≠ ∥x∥ * ∥y∥ : ⟨ne_of_lt, lt_of_le_of_ne (real_inner_le_norm _ _)⟩ ... ↔ ∥y∥ • x ≠ ∥x∥ • y : not_congr inner_eq_norm_mul_iff_real /-- If the inner product of two unit vectors is strictly less than `1`, then the two vectors are distinct. One form of the equality case for Cauchy-Schwarz. -/ lemma inner_lt_one_iff_real_of_norm_one {x y : F} (hx : ∥x∥ = 1) (hy : ∥y∥ = 1) : ⟪x, y⟫_ℝ < 1 ↔ x ≠ y := by { convert inner_lt_norm_mul_iff_real; simp [hx, hy] } /-- The inner product of two weighted sums, where the weights in each sum add to 0, in terms of the norms of pairwise differences. -/ lemma inner_sum_smul_sum_smul_of_sum_eq_zero {ι₁ : Type*} {s₁ : finset ι₁} {w₁ : ι₁ → ℝ} (v₁ : ι₁ → F) (h₁ : ∑ i in s₁, w₁ i = 0) {ι₂ : Type*} {s₂ : finset ι₂} {w₂ : ι₂ → ℝ} (v₂ : ι₂ → F) (h₂ : ∑ i in s₂, w₂ i = 0) : ⟪(∑ i₁ in s₁, w₁ i₁ • v₁ i₁), (∑ i₂ in s₂, w₂ i₂ • v₂ i₂)⟫_ℝ = (-∑ i₁ in s₁, ∑ i₂ in s₂, w₁ i₁ * w₂ i₂ * (∥v₁ i₁ - v₂ i₂∥ * ∥v₁ i₁ - v₂ i₂∥)) / 2 := by simp_rw [sum_inner, inner_sum, real_inner_smul_left, real_inner_smul_right, real_inner_eq_norm_mul_self_add_norm_mul_self_sub_norm_sub_mul_self_div_two, ←div_sub_div_same, ←div_add_div_same, mul_sub_left_distrib, left_distrib, finset.sum_sub_distrib, finset.sum_add_distrib, ←finset.mul_sum, ←finset.sum_mul, h₁, h₂, zero_mul, mul_zero, finset.sum_const_zero, zero_add, zero_sub, finset.mul_sum, neg_div, finset.sum_div, mul_div_assoc, mul_assoc] /-- The inner product with a fixed left element, as a continuous linear map. This can be upgraded to a continuous map which is jointly conjugate-linear in the left argument and linear in the right argument, once (TODO) conjugate-linear maps have been defined. -/ def inner_right (v : E) : E →L[𝕜] 𝕜 := linear_map.mk_continuous { to_fun := λ w, ⟪v, w⟫, map_add' := λ x y, inner_add_right, map_smul' := λ c x, inner_smul_right } ∥v∥ (by simpa [is_R_or_C.norm_eq_abs] using abs_inner_le_norm v) @[simp] lemma inner_right_coe (v : E) : (inner_right v : E → 𝕜) = λ w, ⟪v, w⟫ := rfl @[simp] lemma inner_right_apply (v w : E) : inner_right v w = ⟪v, w⟫ := rfl end norm /-! ### Inner product space structure on product spaces -/ /- If `ι` is a finite type and each space `f i`, `i : ι`, is an inner product space, then `Π i, f i` is an inner product space as well. Since `Π i, f i` is endowed with the sup norm, we use instead `pi_Lp 2 one_le_two f` for the product space, which is endowed with the `L^2` norm. -/ instance pi_Lp.inner_product_space {ι : Type*} [fintype ι] (f : ι → Type*) [Π i, inner_product_space 𝕜 (f i)] : inner_product_space 𝕜 (pi_Lp 2 one_le_two f) := { inner := λ x y, ∑ i, inner (x i) (y i), norm_sq_eq_inner := begin intro x, have h₁ : ∑ (i : ι), ∥x i∥ ^ (2 : ℕ) = ∑ (i : ι), ∥x i∥ ^ (2 : ℝ), { apply finset.sum_congr rfl, intros j hj, simp [←rpow_nat_cast] }, have h₂ : 0 ≤ ∑ (i : ι), ∥x i∥ ^ (2 : ℝ), { rw [←h₁], exact finset.sum_nonneg (λ j (hj : j ∈ finset.univ), pow_nonneg (norm_nonneg (x j)) 2) }, simp [norm, add_monoid_hom.map_sum, ←norm_sq_eq_inner], rw [←rpow_nat_cast ((∑ (i : ι), ∥x i∥ ^ (2 : ℝ)) ^ (2 : ℝ)⁻¹) 2], rw [←rpow_mul h₂], norm_num [h₁], end, conj_sym := begin intros x y, unfold inner, rw [←finset.sum_hom finset.univ conj], apply finset.sum_congr rfl, rintros z -, apply inner_conj_sym, apply_instance end, add_left := λ x y z, show ∑ i, inner (x i + y i) (z i) = ∑ i, inner (x i) (z i) + ∑ i, inner (y i) (z i), by simp only [inner_add_left, finset.sum_add_distrib], smul_left := λ x y r, show ∑ (i : ι), inner (r • x i) (y i) = (conj r) * ∑ i, inner (x i) (y i), by simp only [finset.mul_sum, inner_smul_left] } @[simp] lemma pi_Lp.inner_apply {ι : Type*} [fintype ι] {f : ι → Type*} [Π i, inner_product_space 𝕜 (f i)] (x y : pi_Lp 2 one_le_two f) : ⟪x, y⟫ = ∑ i, ⟪x i, y i⟫ := rfl lemma pi_Lp.norm_eq_of_L2 {ι : Type*} [fintype ι] {f : ι → Type*} [Π i, inner_product_space 𝕜 (f i)] (x : pi_Lp 2 one_le_two f) : ∥x∥ = sqrt (∑ (i : ι), ∥x i∥ ^ 2) := by { rw [pi_Lp.norm_eq_of_nat 2]; simp [sqrt_eq_rpow] } /-- A field `𝕜` satisfying `is_R_or_C` is itself a `𝕜`-inner product space. -/ instance is_R_or_C.inner_product_space : inner_product_space 𝕜 𝕜 := { inner := (λ x y, (conj x) * y), norm_sq_eq_inner := λ x, by { unfold inner, rw [mul_comm, mul_conj, of_real_re, norm_sq_eq_def'] }, conj_sym := λ x y, by simp [mul_comm], add_left := λ x y z, by simp [inner, add_mul], smul_left := λ x y z, by simp [inner, mul_assoc] } @[simp] lemma is_R_or_C.inner_apply (x y : 𝕜) : ⟪x, y⟫ = (conj x) * y := rfl /-- The standard real/complex Euclidean space, functions on a finite type. For an `n`-dimensional space use `euclidean_space 𝕜 (fin n)`. -/ @[reducible, nolint unused_arguments] def euclidean_space (𝕜 : Type*) [is_R_or_C 𝕜] (n : Type*) [fintype n] : Type* := pi_Lp 2 one_le_two (λ (i : n), 𝕜) lemma euclidean_space.norm_eq {𝕜 : Type*} [is_R_or_C 𝕜] {n : Type*} [fintype n] (x : euclidean_space 𝕜 n) : ∥x∥ = real.sqrt (∑ (i : n), ∥x i∥ ^ 2) := pi_Lp.norm_eq_of_L2 x /-! ### Inner product space structure on subspaces -/ /-- Induced inner product on a submodule. -/ instance submodule.inner_product_space (W : submodule 𝕜 E) : inner_product_space 𝕜 W := { inner := λ x y, ⟪(x:E), (y:E)⟫, conj_sym := λ _ _, inner_conj_sym _ _ , norm_sq_eq_inner := λ _, norm_sq_eq_inner _, add_left := λ _ _ _ , inner_add_left, smul_left := λ _ _ _, inner_smul_left, ..submodule.normed_space W } /-- The inner product on submodules is the same as on the ambient space. -/ @[simp] lemma submodule.coe_inner (W : submodule 𝕜 E) (x y : W) : ⟪x, y⟫ = ⟪(x:E), ↑y⟫ := rfl section is_R_or_C_to_real variables {G : Type*} variables (𝕜 E) include 𝕜 /-- A general inner product implies a real inner product. This is not registered as an instance since it creates problems with the case `𝕜 = ℝ`. -/ def has_inner.is_R_or_C_to_real : has_inner ℝ E := { inner := λ x y, re ⟪x, y⟫ } /-- A general inner product space structure implies a real inner product structure. This is not registered as an instance since it creates problems with the case `𝕜 = ℝ`, but in can be used in a proof to obtain a real inner product space structure from a given `𝕜`-inner product space structure. -/ def inner_product_space.is_R_or_C_to_real : inner_product_space ℝ E := { norm_sq_eq_inner := norm_sq_eq_inner, conj_sym := λ x y, inner_re_symm, add_left := λ x y z, by { change re ⟪x + y, z⟫ = re ⟪x, z⟫ + re ⟪y, z⟫, simp [inner_add_left] }, smul_left := λ x y r, by { change re ⟪(r : 𝕜) • x, y⟫ = r * re ⟪x, y⟫, simp [inner_smul_left] }, ..has_inner.is_R_or_C_to_real 𝕜 E, ..normed_space.restrict_scalars ℝ 𝕜 E } variable {E} lemma real_inner_eq_re_inner (x y : E) : @has_inner.inner ℝ E (has_inner.is_R_or_C_to_real 𝕜 E) x y = re ⟪x, y⟫ := rfl omit 𝕜 /-- A complex inner product implies a real inner product -/ instance inner_product_space.complex_to_real [inner_product_space ℂ G] : inner_product_space ℝ G := inner_product_space.is_R_or_C_to_real ℂ G end is_R_or_C_to_real section deriv /-! ### Derivative of the inner product In this section we prove that the inner product and square of the norm in an inner space are infinitely `ℝ`-smooth. In order to state these results, we need a `normed_space ℝ E` instance. Though we can deduce this structure from `inner_product_space 𝕜 E`, this instance may be not definitionally equal to some other “natural” instance. So, we assume `[normed_space ℝ E]` and `[is_scalar_tower ℝ 𝕜 E]`. In both interesting cases `𝕜 = ℝ` and `𝕜 = ℂ` we have these instances. -/ variables [normed_space ℝ E] [is_scalar_tower ℝ 𝕜 E] lemma is_bounded_bilinear_map_inner : is_bounded_bilinear_map ℝ (λ p : E × E, ⟪p.1, p.2⟫) := { add_left := λ _ _ _, inner_add_left, smul_left := λ r x y, by simp only [← algebra_map_smul 𝕜 r x, algebra_map_eq_of_real, inner_smul_real_left], add_right := λ _ _ _, inner_add_right, smul_right := λ r x y, by simp only [← algebra_map_smul 𝕜 r y, algebra_map_eq_of_real, inner_smul_real_right], bound := ⟨1, zero_lt_one, λ x y, by { rw [one_mul, is_R_or_C.norm_eq_abs], exact abs_inner_le_norm x y, }⟩ } /-- Derivative of the inner product. -/ def fderiv_inner_clm (p : E × E) : E × E →L[ℝ] 𝕜 := is_bounded_bilinear_map_inner.deriv p @[simp] lemma fderiv_inner_clm_apply (p x : E × E) : fderiv_inner_clm p x = ⟪p.1, x.2⟫ + ⟪x.1, p.2⟫ := rfl lemma times_cont_diff_inner {n} : times_cont_diff ℝ n (λ p : E × E, ⟪p.1, p.2⟫) := is_bounded_bilinear_map_inner.times_cont_diff lemma times_cont_diff_at_inner {p : E × E} {n} : times_cont_diff_at ℝ n (λ p : E × E, ⟪p.1, p.2⟫) p := times_cont_diff_inner.times_cont_diff_at lemma differentiable_inner : differentiable ℝ (λ p : E × E, ⟪p.1, p.2⟫) := is_bounded_bilinear_map_inner.differentiable_at variables {G : Type*} [normed_group G] [normed_space ℝ G] {f g : G → E} {f' g' : G →L[ℝ] E} {s : set G} {x : G} {n : with_top ℕ} include 𝕜 lemma times_cont_diff_within_at.inner (hf : times_cont_diff_within_at ℝ n f s x) (hg : times_cont_diff_within_at ℝ n g s x) : times_cont_diff_within_at ℝ n (λ x, ⟪f x, g x⟫) s x := times_cont_diff_at_inner.comp_times_cont_diff_within_at x (hf.prod hg) lemma times_cont_diff_at.inner (hf : times_cont_diff_at ℝ n f x) (hg : times_cont_diff_at ℝ n g x) : times_cont_diff_at ℝ n (λ x, ⟪f x, g x⟫) x := hf.inner hg lemma times_cont_diff_on.inner (hf : times_cont_diff_on ℝ n f s) (hg : times_cont_diff_on ℝ n g s) : times_cont_diff_on ℝ n (λ x, ⟪f x, g x⟫) s := λ x hx, (hf x hx).inner (hg x hx) lemma times_cont_diff.inner (hf : times_cont_diff ℝ n f) (hg : times_cont_diff ℝ n g) : times_cont_diff ℝ n (λ x, ⟪f x, g x⟫) := times_cont_diff_inner.comp (hf.prod hg) lemma has_fderiv_within_at.inner (hf : has_fderiv_within_at f f' s x) (hg : has_fderiv_within_at g g' s x) : has_fderiv_within_at (λ t, ⟪f t, g t⟫) ((fderiv_inner_clm (f x, g x)).comp $ f'.prod g') s x := (is_bounded_bilinear_map_inner.has_fderiv_at (f x, g x)).comp_has_fderiv_within_at x (hf.prod hg) lemma has_fderiv_at.inner (hf : has_fderiv_at f f' x) (hg : has_fderiv_at g g' x) : has_fderiv_at (λ t, ⟪f t, g t⟫) ((fderiv_inner_clm (f x, g x)).comp $ f'.prod g') x := (is_bounded_bilinear_map_inner.has_fderiv_at (f x, g x)).comp x (hf.prod hg) lemma has_deriv_within_at.inner {f g : ℝ → E} {f' g' : E} {s : set ℝ} {x : ℝ} (hf : has_deriv_within_at f f' s x) (hg : has_deriv_within_at g g' s x) : has_deriv_within_at (λ t, ⟪f t, g t⟫) (⟪f x, g'⟫ + ⟪f', g x⟫) s x := by simpa using (hf.has_fderiv_within_at.inner hg.has_fderiv_within_at).has_deriv_within_at lemma has_deriv_at.inner {f g : ℝ → E} {f' g' : E} {x : ℝ} : has_deriv_at f f' x → has_deriv_at g g' x → has_deriv_at (λ t, ⟪f t, g t⟫) (⟪f x, g'⟫ + ⟪f', g x⟫) x := by simpa only [← has_deriv_within_at_univ] using has_deriv_within_at.inner lemma differentiable_within_at.inner (hf : differentiable_within_at ℝ f s x) (hg : differentiable_within_at ℝ g s x) : differentiable_within_at ℝ (λ x, ⟪f x, g x⟫) s x := ((differentiable_inner _).has_fderiv_at.comp_has_fderiv_within_at x (hf.prod hg).has_fderiv_within_at).differentiable_within_at lemma differentiable_at.inner (hf : differentiable_at ℝ f x) (hg : differentiable_at ℝ g x) : differentiable_at ℝ (λ x, ⟪f x, g x⟫) x := (differentiable_inner _).comp x (hf.prod hg) lemma differentiable_on.inner (hf : differentiable_on ℝ f s) (hg : differentiable_on ℝ g s) : differentiable_on ℝ (λ x, ⟪f x, g x⟫) s := λ x hx, (hf x hx).inner (hg x hx) lemma differentiable.inner (hf : differentiable ℝ f) (hg : differentiable ℝ g) : differentiable ℝ (λ x, ⟪f x, g x⟫) := λ x, (hf x).inner (hg x) lemma fderiv_inner_apply (hf : differentiable_at ℝ f x) (hg : differentiable_at ℝ g x) (y : G) : fderiv ℝ (λ t, ⟪f t, g t⟫) x y = ⟪f x, fderiv ℝ g x y⟫ + ⟪fderiv ℝ f x y, g x⟫ := by { rw [(hf.has_fderiv_at.inner hg.has_fderiv_at).fderiv], refl } lemma deriv_inner_apply {f g : ℝ → E} {x : ℝ} (hf : differentiable_at ℝ f x) (hg : differentiable_at ℝ g x) : deriv (λ t, ⟪f t, g t⟫) x = ⟪f x, deriv g x⟫ + ⟪deriv f x, g x⟫ := (hf.has_deriv_at.inner hg.has_deriv_at).deriv lemma times_cont_diff_norm_square : times_cont_diff ℝ n (λ x : E, ∥x∥ ^ 2) := begin simp only [pow_two, ← inner_self_eq_norm_square], exact (re_clm : 𝕜 →L[ℝ] ℝ).times_cont_diff.comp (times_cont_diff_id.inner times_cont_diff_id) end lemma times_cont_diff.norm_square (hf : times_cont_diff ℝ n f) : times_cont_diff ℝ n (λ x, ∥f x∥ ^ 2) := times_cont_diff_norm_square.comp hf lemma times_cont_diff_within_at.norm_square (hf : times_cont_diff_within_at ℝ n f s x) : times_cont_diff_within_at ℝ n (λ y, ∥f y∥ ^ 2) s x := times_cont_diff_norm_square.times_cont_diff_at.comp_times_cont_diff_within_at x hf lemma times_cont_diff_at.norm_square (hf : times_cont_diff_at ℝ n f x) : times_cont_diff_at ℝ n (λ y, ∥f y∥ ^ 2) x := hf.norm_square lemma times_cont_diff_at_norm {x : E} (hx : x ≠ 0) : times_cont_diff_at ℝ n norm x := have ∥id x∥ ^ 2 ≠ 0, from pow_ne_zero _ (norm_pos_iff.2 hx).ne', by simpa only [id, sqrt_sqr, norm_nonneg] using times_cont_diff_at_id.norm_square.sqrt this lemma times_cont_diff_at.norm (hf : times_cont_diff_at ℝ n f x) (h0 : f x ≠ 0) : times_cont_diff_at ℝ n (λ y, ∥f y∥) x := (times_cont_diff_at_norm h0).comp x hf lemma times_cont_diff_at.dist (hf : times_cont_diff_at ℝ n f x) (hg : times_cont_diff_at ℝ n g x) (hne : f x ≠ g x) : times_cont_diff_at ℝ n (λ y, dist (f y) (g y)) x := by { simp only [dist_eq_norm], exact (hf.sub hg).norm (sub_ne_zero.2 hne) } lemma times_cont_diff_within_at.norm (hf : times_cont_diff_within_at ℝ n f s x) (h0 : f x ≠ 0) : times_cont_diff_within_at ℝ n (λ y, ∥f y∥) s x := (times_cont_diff_at_norm h0).comp_times_cont_diff_within_at x hf lemma times_cont_diff_within_at.dist (hf : times_cont_diff_within_at ℝ n f s x) (hg : times_cont_diff_within_at ℝ n g s x) (hne : f x ≠ g x) : times_cont_diff_within_at ℝ n (λ y, dist (f y) (g y)) s x := by { simp only [dist_eq_norm], exact (hf.sub hg).norm (sub_ne_zero.2 hne) } lemma times_cont_diff_on.norm_square (hf : times_cont_diff_on ℝ n f s) : times_cont_diff_on ℝ n (λ y, ∥f y∥ ^ 2) s := (λ x hx, (hf x hx).norm_square) lemma times_cont_diff_on.norm (hf : times_cont_diff_on ℝ n f s) (h0 : ∀ x ∈ s, f x ≠ 0) : times_cont_diff_on ℝ n (λ y, ∥f y∥) s := λ x hx, (hf x hx).norm (h0 x hx) lemma times_cont_diff_on.dist (hf : times_cont_diff_on ℝ n f s) (hg : times_cont_diff_on ℝ n g s) (hne : ∀ x ∈ s, f x ≠ g x) : times_cont_diff_on ℝ n (λ y, dist (f y) (g y)) s := λ x hx, (hf x hx).dist (hg x hx) (hne x hx) lemma times_cont_diff.norm (hf : times_cont_diff ℝ n f) (h0 : ∀ x, f x ≠ 0) : times_cont_diff ℝ n (λ y, ∥f y∥) := times_cont_diff_iff_times_cont_diff_at.2 $ λ x, hf.times_cont_diff_at.norm (h0 x) lemma times_cont_diff.dist (hf : times_cont_diff ℝ n f) (hg : times_cont_diff ℝ n g) (hne : ∀ x, f x ≠ g x) : times_cont_diff ℝ n (λ y, dist (f y) (g y)) := times_cont_diff_iff_times_cont_diff_at.2 $ λ x, hf.times_cont_diff_at.dist hg.times_cont_diff_at (hne x) lemma differentiable_at.norm_square (hf : differentiable_at ℝ f x) : differentiable_at ℝ (λ y, ∥f y∥ ^ 2) x := (times_cont_diff_at_id.norm_square.differentiable_at le_rfl).comp x hf lemma differentiable_at.norm (hf : differentiable_at ℝ f x) (h0 : f x ≠ 0) : differentiable_at ℝ (λ y, ∥f y∥) x := ((times_cont_diff_at_norm h0).differentiable_at le_rfl).comp x hf lemma differentiable_at.dist (hf : differentiable_at ℝ f x) (hg : differentiable_at ℝ g x) (hne : f x ≠ g x) : differentiable_at ℝ (λ y, dist (f y) (g y)) x := by { simp only [dist_eq_norm], exact (hf.sub hg).norm (sub_ne_zero.2 hne) } lemma differentiable.norm_square (hf : differentiable ℝ f) : differentiable ℝ (λ y, ∥f y∥ ^ 2) := λ x, (hf x).norm_square lemma differentiable.norm (hf : differentiable ℝ f) (h0 : ∀ x, f x ≠ 0) : differentiable ℝ (λ y, ∥f y∥) := λ x, (hf x).norm (h0 x) lemma differentiable.dist (hf : differentiable ℝ f) (hg : differentiable ℝ g) (hne : ∀ x, f x ≠ g x) : differentiable ℝ (λ y, dist (f y) (g y)) := λ x, (hf x).dist (hg x) (hne x) lemma differentiable_within_at.norm_square (hf : differentiable_within_at ℝ f s x) : differentiable_within_at ℝ (λ y, ∥f y∥ ^ 2) s x := (times_cont_diff_at_id.norm_square.differentiable_at le_rfl).comp_differentiable_within_at x hf lemma differentiable_within_at.norm (hf : differentiable_within_at ℝ f s x) (h0 : f x ≠ 0) : differentiable_within_at ℝ (λ y, ∥f y∥) s x := ((times_cont_diff_at_id.norm h0).differentiable_at le_rfl).comp_differentiable_within_at x hf lemma differentiable_within_at.dist (hf : differentiable_within_at ℝ f s x) (hg : differentiable_within_at ℝ g s x) (hne : f x ≠ g x) : differentiable_within_at ℝ (λ y, dist (f y) (g y)) s x := by { simp only [dist_eq_norm], exact (hf.sub hg).norm (sub_ne_zero.2 hne) } lemma differentiable_on.norm_square (hf : differentiable_on ℝ f s) : differentiable_on ℝ (λ y, ∥f y∥ ^ 2) s := λ x hx, (hf x hx).norm_square lemma differentiable_on.norm (hf : differentiable_on ℝ f s) (h0 : ∀ x ∈ s, f x ≠ 0) : differentiable_on ℝ (λ y, ∥f y∥) s := λ x hx, (hf x hx).norm (h0 x hx) lemma differentiable_on.dist (hf : differentiable_on ℝ f s) (hg : differentiable_on ℝ g s) (hne : ∀ x ∈ s, f x ≠ g x) : differentiable_on ℝ (λ y, dist (f y) (g y)) s := λ x hx, (hf x hx).dist (hg x hx) (hne x hx) end deriv section continuous /-! ### Continuity and measurability of the inner product Since the inner product is `ℝ`-smooth, it is continuous. We do not need a `[normed_space ℝ E]` structure to *state* this fact and its corollaries, so we introduce them in the proof instead. -/ lemma continuous_inner : continuous (λ p : E × E, ⟪p.1, p.2⟫) := begin letI : inner_product_space ℝ E := inner_product_space.is_R_or_C_to_real 𝕜 E, letI : is_scalar_tower ℝ 𝕜 E := restrict_scalars.is_scalar_tower _ _ _, exact differentiable_inner.continuous end variables {α : Type*} lemma filter.tendsto.inner {f g : α → E} {l : filter α} {x y : E} (hf : tendsto f l (𝓝 x)) (hg : tendsto g l (𝓝 y)) : tendsto (λ t, ⟪f t, g t⟫) l (𝓝 ⟪x, y⟫) := (continuous_inner.tendsto _).comp (hf.prod_mk_nhds hg) lemma measurable.inner [measurable_space α] [measurable_space E] [opens_measurable_space E] [topological_space.second_countable_topology E] [measurable_space 𝕜] [borel_space 𝕜] {f g : α → E} (hf : measurable f) (hg : measurable g) : measurable (λ t, ⟪f t, g t⟫) := continuous.measurable2 continuous_inner hf hg lemma ae_measurable.inner [measurable_space α] [measurable_space E] [opens_measurable_space E] [topological_space.second_countable_topology E] [measurable_space 𝕜] [borel_space 𝕜] {μ : measure_theory.measure α} {f g : α → E} (hf : ae_measurable f μ) (hg : ae_measurable g μ) : ae_measurable (λ x, ⟪f x, g x⟫) μ := begin refine ⟨λ x, ⟪hf.mk f x, hg.mk g x⟫, hf.measurable_mk.inner hg.measurable_mk, _⟩, refine hf.ae_eq_mk.mp (hg.ae_eq_mk.mono (λ x hxg hxf, _)), dsimp only, congr, { exact hxf, }, { exact hxg, }, end variables [topological_space α] {f g : α → E} {x : α} {s : set α} include 𝕜 lemma continuous_within_at.inner (hf : continuous_within_at f s x) (hg : continuous_within_at g s x) : continuous_within_at (λ t, ⟪f t, g t⟫) s x := hf.inner hg lemma continuous_at.inner (hf : continuous_at f x) (hg : continuous_at g x) : continuous_at (λ t, ⟪f t, g t⟫) x := hf.inner hg lemma continuous_on.inner (hf : continuous_on f s) (hg : continuous_on g s) : continuous_on (λ t, ⟪f t, g t⟫) s := λ x hx, (hf x hx).inner (hg x hx) lemma continuous.inner (hf : continuous f) (hg : continuous g) : continuous (λ t, ⟪f t, g t⟫) := continuous_iff_continuous_at.2 $ λ x, hf.continuous_at.inner hg.continuous_at end continuous section pi_Lp local attribute [reducible] pi_Lp variables {ι : Type*} [fintype ι] instance : finite_dimensional 𝕜 (euclidean_space 𝕜 ι) := by apply_instance instance : inner_product_space 𝕜 (euclidean_space 𝕜 ι) := by apply_instance @[simp] lemma findim_euclidean_space : finite_dimensional.findim 𝕜 (euclidean_space 𝕜 ι) = fintype.card ι := by simp lemma findim_euclidean_space_fin {n : ℕ} : finite_dimensional.findim 𝕜 (euclidean_space 𝕜 (fin n)) = n := by simp /-- An orthonormal basis on a fintype `ι` for an inner product space induces an isometry with `euclidean_space 𝕜 ι`. -/ def is_basis.isometry_euclidean_of_orthonormal {v : ι → E} (h : is_basis 𝕜 v) (hv : orthonormal 𝕜 v) : E ≃ₗᵢ[𝕜] (euclidean_space 𝕜 ι) := h.equiv_fun.isometry_of_inner begin intros x y, let p : euclidean_space 𝕜 ι := h.equiv_fun x, let q : euclidean_space 𝕜 ι := h.equiv_fun y, have key : ⟪p, q⟫ = ⟪∑ i, p i • v i, ∑ i, q i • v i⟫, { simp [sum_inner, inner_smul_left, hv.inner_right_fintype] }, convert key, { rw [← h.equiv_fun.symm_apply_apply x, h.equiv_fun_symm_apply] }, { rw [← h.equiv_fun.symm_apply_apply y, h.equiv_fun_symm_apply] } end /-- `ℂ` is isometric to ℝ² with the Euclidean inner product. -/ def complex.isometry_euclidean : ℂ ≃ₗᵢ[ℝ] (euclidean_space ℝ (fin 2)) := complex.is_basis_one_I.isometry_euclidean_of_orthonormal begin rw orthonormal_iff_ite, intros i, fin_cases i; intros j; fin_cases j; simp [real_inner_eq_re_inner] end @[simp] lemma complex.isometry_euclidean_symm_apply (x : euclidean_space ℝ (fin 2)) : complex.isometry_euclidean.symm x = (x 0) + (x 1) * I := begin convert complex.is_basis_one_I.equiv_fun_symm_apply x, { simpa }, { simp }, end lemma complex.isometry_euclidean_proj_eq_self (z : ℂ) : ↑(complex.isometry_euclidean z 0) + ↑(complex.isometry_euclidean z 1) * (I : ℂ) = z := by rw [← complex.isometry_euclidean_symm_apply (complex.isometry_euclidean z), complex.isometry_euclidean.symm_apply_apply z] @[simp] lemma complex.isometry_euclidean_apply_zero (z : ℂ) : complex.isometry_euclidean z 0 = z.re := by { conv_rhs { rw ← complex.isometry_euclidean_proj_eq_self z }, simp } @[simp] lemma complex.isometry_euclidean_apply_one (z : ℂ) : complex.isometry_euclidean z 1 = z.im := by { conv_rhs { rw ← complex.isometry_euclidean_proj_eq_self z }, simp } end pi_Lp /-! ### Orthogonal projection in inner product spaces -/ section orthogonal open filter /-- Existence of minimizers Let `u` be a point in a real inner product space, and let `K` be a nonempty complete convex subset. Then there exists a (unique) `v` in `K` that minimizes the distance `∥u - v∥` to `u`. -/ -- FIXME this monolithic proof causes a deterministic timeout with `-T50000` -- It should be broken in a sequence of more manageable pieces, -- perhaps with individual statements for the three steps below. theorem exists_norm_eq_infi_of_complete_convex {K : set F} (ne : K.nonempty) (h₁ : is_complete K) (h₂ : convex K) : ∀ u : F, ∃ v ∈ K, ∥u - v∥ = ⨅ w : K, ∥u - w∥ := assume u, begin let δ := ⨅ w : K, ∥u - w∥, letI : nonempty K := ne.to_subtype, have zero_le_δ : 0 ≤ δ := le_cinfi (λ _, norm_nonneg _), have δ_le : ∀ w : K, δ ≤ ∥u - w∥, from cinfi_le ⟨0, set.forall_range_iff.2 $ λ _, norm_nonneg _⟩, have δ_le' : ∀ w ∈ K, δ ≤ ∥u - w∥ := assume w hw, δ_le ⟨w, hw⟩, -- Step 1: since `δ` is the infimum, can find a sequence `w : ℕ → K` in `K` -- such that `∥u - w n∥ < δ + 1 / (n + 1)` (which implies `∥u - w n∥ --> δ`); -- maybe this should be a separate lemma have exists_seq : ∃ w : ℕ → K, ∀ n, ∥u - w n∥ < δ + 1 / (n + 1), { have hδ : ∀n:ℕ, δ < δ + 1 / (n + 1), from λ n, lt_add_of_le_of_pos (le_refl _) nat.one_div_pos_of_nat, have h := λ n, exists_lt_of_cinfi_lt (hδ n), let w : ℕ → K := λ n, classical.some (h n), exact ⟨w, λ n, classical.some_spec (h n)⟩ }, rcases exists_seq with ⟨w, hw⟩, have norm_tendsto : tendsto (λ n, ∥u - w n∥) at_top (nhds δ), { have h : tendsto (λ n:ℕ, δ) at_top (nhds δ) := tendsto_const_nhds, have h' : tendsto (λ n:ℕ, δ + 1 / (n + 1)) at_top (nhds δ), { convert h.add tendsto_one_div_add_at_top_nhds_0_nat, simp only [add_zero] }, exact tendsto_of_tendsto_of_tendsto_of_le_of_le h h' (λ x, δ_le _) (λ x, le_of_lt (hw _)) }, -- Step 2: Prove that the sequence `w : ℕ → K` is a Cauchy sequence have seq_is_cauchy : cauchy_seq (λ n, ((w n):F)), { rw cauchy_seq_iff_le_tendsto_0, -- splits into three goals let b := λ n:ℕ, (8 * δ * (1/(n+1)) + 4 * (1/(n+1)) * (1/(n+1))), use (λn, sqrt (b n)), split, -- first goal : `∀ (n : ℕ), 0 ≤ sqrt (b n)` assume n, exact sqrt_nonneg _, split, -- second goal : `∀ (n m N : ℕ), N ≤ n → N ≤ m → dist ↑(w n) ↑(w m) ≤ sqrt (b N)` assume p q N hp hq, let wp := ((w p):F), let wq := ((w q):F), let a := u - wq, let b := u - wp, let half := 1 / (2:ℝ), let div := 1 / ((N:ℝ) + 1), have : 4 * ∥u - half • (wq + wp)∥ * ∥u - half • (wq + wp)∥ + ∥wp - wq∥ * ∥wp - wq∥ = 2 * (∥a∥ * ∥a∥ + ∥b∥ * ∥b∥) := calc 4 * ∥u - half•(wq + wp)∥ * ∥u - half•(wq + wp)∥ + ∥wp - wq∥ * ∥wp - wq∥ = (2*∥u - half•(wq + wp)∥) * (2 * ∥u - half•(wq + wp)∥) + ∥wp-wq∥*∥wp-wq∥ : by ring ... = (absR ((2:ℝ)) * ∥u - half•(wq + wp)∥) * (absR ((2:ℝ)) * ∥u - half•(wq+wp)∥) + ∥wp-wq∥*∥wp-wq∥ : by { rw _root_.abs_of_nonneg, exact zero_le_two } ... = ∥(2:ℝ) • (u - half • (wq + wp))∥ * ∥(2:ℝ) • (u - half • (wq + wp))∥ + ∥wp-wq∥ * ∥wp-wq∥ : by simp [norm_smul] ... = ∥a + b∥ * ∥a + b∥ + ∥a - b∥ * ∥a - b∥ : begin rw [smul_sub, smul_smul, mul_one_div_cancel (_root_.two_ne_zero : (2 : ℝ) ≠ 0), ← one_add_one_eq_two, add_smul], simp only [one_smul], have eq₁ : wp - wq = a - b, from (sub_sub_sub_cancel_left _ _ _).symm, have eq₂ : u + u - (wq + wp) = a + b, show u + u - (wq + wp) = (u - wq) + (u - wp), abel, rw [eq₁, eq₂], end ... = 2 * (∥a∥ * ∥a∥ + ∥b∥ * ∥b∥) : parallelogram_law_with_norm, have eq : δ ≤ ∥u - half • (wq + wp)∥, { rw smul_add, apply δ_le', apply h₂, repeat {exact subtype.mem _}, repeat {exact le_of_lt one_half_pos}, exact add_halves 1 }, have eq₁ : 4 * δ * δ ≤ 4 * ∥u - half • (wq + wp)∥ * ∥u - half • (wq + wp)∥, { mono, mono, norm_num, apply mul_nonneg, norm_num, exact norm_nonneg _ }, have eq₂ : ∥a∥ * ∥a∥ ≤ (δ + div) * (δ + div) := mul_self_le_mul_self (norm_nonneg _) (le_trans (le_of_lt $ hw q) (add_le_add_left (nat.one_div_le_one_div hq) _)), have eq₂' : ∥b∥ * ∥b∥ ≤ (δ + div) * (δ + div) := mul_self_le_mul_self (norm_nonneg _) (le_trans (le_of_lt $ hw p) (add_le_add_left (nat.one_div_le_one_div hp) _)), rw dist_eq_norm, apply nonneg_le_nonneg_of_squares_le, { exact sqrt_nonneg _ }, rw mul_self_sqrt, exact calc ∥wp - wq∥ * ∥wp - wq∥ = 2 * (∥a∥*∥a∥ + ∥b∥*∥b∥) - 4 * ∥u - half • (wq+wp)∥ * ∥u - half • (wq+wp)∥ : by { rw ← this, simp } ... ≤ 2 * (∥a∥ * ∥a∥ + ∥b∥ * ∥b∥) - 4 * δ * δ : sub_le_sub_left eq₁ _ ... ≤ 2 * ((δ + div) * (δ + div) + (δ + div) * (δ + div)) - 4 * δ * δ : sub_le_sub_right (mul_le_mul_of_nonneg_left (add_le_add eq₂ eq₂') (by norm_num)) _ ... = 8 * δ * div + 4 * div * div : by ring, exact add_nonneg (mul_nonneg (mul_nonneg (by norm_num) zero_le_δ) (le_of_lt nat.one_div_pos_of_nat)) (mul_nonneg (mul_nonneg (by norm_num) nat.one_div_pos_of_nat.le) nat.one_div_pos_of_nat.le), -- third goal : `tendsto (λ (n : ℕ), sqrt (b n)) at_top (𝓝 0)` apply tendsto.comp, { convert continuous_sqrt.continuous_at, exact sqrt_zero.symm }, have eq₁ : tendsto (λ (n : ℕ), 8 * δ * (1 / (n + 1))) at_top (nhds (0:ℝ)), { convert (@tendsto_const_nhds _ _ _ (8 * δ) _).mul tendsto_one_div_add_at_top_nhds_0_nat, simp only [mul_zero] }, have : tendsto (λ (n : ℕ), (4:ℝ) * (1 / (n + 1))) at_top (nhds (0:ℝ)), { convert (@tendsto_const_nhds _ _ _ (4:ℝ) _).mul tendsto_one_div_add_at_top_nhds_0_nat, simp only [mul_zero] }, have eq₂ : tendsto (λ (n : ℕ), (4:ℝ) * (1 / (n + 1)) * (1 / (n + 1))) at_top (nhds (0:ℝ)), { convert this.mul tendsto_one_div_add_at_top_nhds_0_nat, simp only [mul_zero] }, convert eq₁.add eq₂, simp only [add_zero] }, -- Step 3: By completeness of `K`, let `w : ℕ → K` converge to some `v : K`. -- Prove that it satisfies all requirements. rcases cauchy_seq_tendsto_of_is_complete h₁ (λ n, _) seq_is_cauchy with ⟨v, hv, w_tendsto⟩, use v, use hv, have h_cont : continuous (λ v, ∥u - v∥) := continuous.comp continuous_norm (continuous.sub continuous_const continuous_id), have : tendsto (λ n, ∥u - w n∥) at_top (nhds ∥u - v∥), convert (tendsto.comp h_cont.continuous_at w_tendsto), exact tendsto_nhds_unique this norm_tendsto, exact subtype.mem _ end /-- Characterization of minimizers for the projection on a convex set in a real inner product space. -/ theorem norm_eq_infi_iff_real_inner_le_zero {K : set F} (h : convex K) {u : F} {v : F} (hv : v ∈ K) : ∥u - v∥ = (⨅ w : K, ∥u - w∥) ↔ ∀ w ∈ K, ⟪u - v, w - v⟫_ℝ ≤ 0 := iff.intro begin assume eq w hw, let δ := ⨅ w : K, ∥u - w∥, let p := ⟪u - v, w - v⟫_ℝ, let q := ∥w - v∥^2, letI : nonempty K := ⟨⟨v, hv⟩⟩, have zero_le_δ : 0 ≤ δ, apply le_cinfi, intro, exact norm_nonneg _, have δ_le : ∀ w : K, δ ≤ ∥u - w∥, assume w, apply cinfi_le, use (0:ℝ), rintros _ ⟨_, rfl⟩, exact norm_nonneg _, have δ_le' : ∀ w ∈ K, δ ≤ ∥u - w∥ := assume w hw, δ_le ⟨w, hw⟩, have : ∀θ:ℝ, 0 < θ → θ ≤ 1 → 2 * p ≤ θ * q, assume θ hθ₁ hθ₂, have : ∥u - v∥^2 ≤ ∥u - v∥^2 - 2 * θ * ⟪u - v, w - v⟫_ℝ + θ*θ*∥w - v∥^2 := calc ∥u - v∥^2 ≤ ∥u - (θ•w + (1-θ)•v)∥^2 : begin simp only [pow_two], apply mul_self_le_mul_self (norm_nonneg _), rw [eq], apply δ_le', apply h hw hv, exacts [le_of_lt hθ₁, sub_nonneg.2 hθ₂, add_sub_cancel'_right _ _], end ... = ∥(u - v) - θ • (w - v)∥^2 : begin have : u - (θ•w + (1-θ)•v) = (u - v) - θ • (w - v), { rw [smul_sub, sub_smul, one_smul], simp only [sub_eq_add_neg, add_comm, add_left_comm, add_assoc, neg_add_rev] }, rw this end ... = ∥u - v∥^2 - 2 * θ * inner (u - v) (w - v) + θ*θ*∥w - v∥^2 : begin rw [norm_sub_pow_two, inner_smul_right, norm_smul], simp only [pow_two], show ∥u-v∥*∥u-v∥-2*(θ*inner(u-v)(w-v))+absR (θ)*∥w-v∥*(absR (θ)*∥w-v∥)= ∥u-v∥*∥u-v∥-2*θ*inner(u-v)(w-v)+θ*θ*(∥w-v∥*∥w-v∥), rw abs_of_pos hθ₁, ring end, have eq₁ : ∥u-v∥^2-2*θ*inner(u-v)(w-v)+θ*θ*∥w-v∥^2=∥u-v∥^2+(θ*θ*∥w-v∥^2-2*θ*inner(u-v)(w-v)), by abel, rw [eq₁, le_add_iff_nonneg_right] at this, have eq₂ : θ*θ*∥w-v∥^2-2*θ*inner(u-v)(w-v)=θ*(θ*∥w-v∥^2-2*inner(u-v)(w-v)), ring, rw eq₂ at this, have := le_of_sub_nonneg (nonneg_of_mul_nonneg_left this hθ₁), exact this, by_cases hq : q = 0, { rw hq at this, have : p ≤ 0, have := this (1:ℝ) (by norm_num) (by norm_num), linarith, exact this }, { have q_pos : 0 < q, apply lt_of_le_of_ne, exact pow_two_nonneg _, intro h, exact hq h.symm, by_contradiction hp, rw not_le at hp, let θ := min (1:ℝ) (p / q), have eq₁ : θ*q ≤ p := calc θ*q ≤ (p/q) * q : mul_le_mul_of_nonneg_right (min_le_right _ _) (pow_two_nonneg _) ... = p : div_mul_cancel _ hq, have : 2 * p ≤ p := calc 2 * p ≤ θ*q : by { refine this θ (lt_min (by norm_num) (div_pos hp q_pos)) (by norm_num) } ... ≤ p : eq₁, linarith } end begin assume h, letI : nonempty K := ⟨⟨v, hv⟩⟩, apply le_antisymm, { apply le_cinfi, assume w, apply nonneg_le_nonneg_of_squares_le (norm_nonneg _), have := h w w.2, exact calc ∥u - v∥ * ∥u - v∥ ≤ ∥u - v∥ * ∥u - v∥ - 2 * inner (u - v) ((w:F) - v) : by linarith ... ≤ ∥u - v∥^2 - 2 * inner (u - v) ((w:F) - v) + ∥(w:F) - v∥^2 : by { rw pow_two, refine le_add_of_nonneg_right _, exact pow_two_nonneg _ } ... = ∥(u - v) - (w - v)∥^2 : norm_sub_pow_two.symm ... = ∥u - w∥ * ∥u - w∥ : by { have : (u - v) - (w - v) = u - w, abel, rw [this, pow_two] } }, { show (⨅ (w : K), ∥u - w∥) ≤ (λw:K, ∥u - w∥) ⟨v, hv⟩, apply cinfi_le, use 0, rintros y ⟨z, rfl⟩, exact norm_nonneg _ } end variables (K : submodule 𝕜 E) /-- Existence of projections on complete subspaces. Let `u` be a point in an inner product space, and let `K` be a nonempty complete subspace. Then there exists a (unique) `v` in `K` that minimizes the distance `∥u - v∥` to `u`. This point `v` is usually called the orthogonal projection of `u` onto `K`. -/ theorem exists_norm_eq_infi_of_complete_subspace (h : is_complete (↑K : set E)) : ∀ u : E, ∃ v ∈ K, ∥u - v∥ = ⨅ w : (K : set E), ∥u - w∥ := begin letI : inner_product_space ℝ E := inner_product_space.is_R_or_C_to_real 𝕜 E, letI : module ℝ E := restrict_scalars.semimodule ℝ 𝕜 E, letI : is_scalar_tower ℝ 𝕜 E := restrict_scalars.is_scalar_tower _ _ _, let K' : submodule ℝ E := submodule.restrict_scalars ℝ K, exact exists_norm_eq_infi_of_complete_convex ⟨0, K'.zero_mem⟩ h K'.convex end /-- Characterization of minimizers in the projection on a subspace, in the real case. Let `u` be a point in a real inner product space, and let `K` be a nonempty subspace. Then point `v` minimizes the distance `∥u - v∥` over points in `K` if and only if for all `w ∈ K`, `⟪u - v, w⟫ = 0` (i.e., `u - v` is orthogonal to the subspace `K`). This is superceded by `norm_eq_infi_iff_inner_eq_zero` that gives the same conclusion over any `is_R_or_C` field. -/ theorem norm_eq_infi_iff_real_inner_eq_zero (K : submodule ℝ F) {u : F} {v : F} (hv : v ∈ K) : ∥u - v∥ = (⨅ w : (↑K : set F), ∥u - w∥) ↔ ∀ w ∈ K, ⟪u - v, w⟫_ℝ = 0 := iff.intro begin assume h, have h : ∀ w ∈ K, ⟪u - v, w - v⟫_ℝ ≤ 0, { rwa [norm_eq_infi_iff_real_inner_le_zero] at h, exacts [K.convex, hv] }, assume w hw, have le : ⟪u - v, w⟫_ℝ ≤ 0, let w' := w + v, have : w' ∈ K := submodule.add_mem _ hw hv, have h₁ := h w' this, have h₂ : w' - v = w, simp only [add_neg_cancel_right, sub_eq_add_neg], rw h₂ at h₁, exact h₁, have ge : ⟪u - v, w⟫_ℝ ≥ 0, let w'' := -w + v, have : w'' ∈ K := submodule.add_mem _ (submodule.neg_mem _ hw) hv, have h₁ := h w'' this, have h₂ : w'' - v = -w, simp only [neg_inj, add_neg_cancel_right, sub_eq_add_neg], rw [h₂, inner_neg_right] at h₁, linarith, exact le_antisymm le ge end begin assume h, have : ∀ w ∈ K, ⟪u - v, w - v⟫_ℝ ≤ 0, assume w hw, let w' := w - v, have : w' ∈ K := submodule.sub_mem _ hw hv, have h₁ := h w' this, exact le_of_eq h₁, rwa norm_eq_infi_iff_real_inner_le_zero, exacts [submodule.convex _, hv] end /-- Characterization of minimizers in the projection on a subspace. Let `u` be a point in an inner product space, and let `K` be a nonempty subspace. Then point `v` minimizes the distance `∥u - v∥` over points in `K` if and only if for all `w ∈ K`, `⟪u - v, w⟫ = 0` (i.e., `u - v` is orthogonal to the subspace `K`) -/ theorem norm_eq_infi_iff_inner_eq_zero {u : E} {v : E} (hv : v ∈ K) : ∥u - v∥ = (⨅ w : (↑K : set E), ∥u - w∥) ↔ ∀ w ∈ K, ⟪u - v, w⟫ = 0 := begin letI : inner_product_space ℝ E := inner_product_space.is_R_or_C_to_real 𝕜 E, letI : module ℝ E := restrict_scalars.semimodule ℝ 𝕜 E, letI : is_scalar_tower ℝ 𝕜 E := restrict_scalars.is_scalar_tower _ _ _, let K' : submodule ℝ E := K.restrict_scalars ℝ, split, { assume H, have A : ∀ w ∈ K, re ⟪u - v, w⟫ = 0 := (norm_eq_infi_iff_real_inner_eq_zero K' hv).1 H, assume w hw, apply ext, { simp [A w hw] }, { symmetry, calc im (0 : 𝕜) = 0 : im.map_zero ... = re ⟪u - v, (-I) • w⟫ : (A _ (K.smul_mem (-I) hw)).symm ... = re ((-I) * ⟪u - v, w⟫) : by rw inner_smul_right ... = im ⟪u - v, w⟫ : by simp } }, { assume H, have : ∀ w ∈ K', ⟪u - v, w⟫_ℝ = 0, { assume w hw, rw [real_inner_eq_re_inner, H w hw], exact zero_re' }, exact (norm_eq_infi_iff_real_inner_eq_zero K' hv).2 this } end section orthogonal_projection variables [complete_space K] /-- The orthogonal projection onto a complete subspace, as an unbundled function. This definition is only intended for use in setting up the bundled version `orthogonal_projection` and should not be used once that is defined. -/ def orthogonal_projection_fn (v : E) := (exists_norm_eq_infi_of_complete_subspace K (complete_space_coe_iff_is_complete.mp ‹_›) v).some variables {K} /-- The unbundled orthogonal projection is in the given subspace. This lemma is only intended for use in setting up the bundled version and should not be used once that is defined. -/ lemma orthogonal_projection_fn_mem (v : E) : orthogonal_projection_fn K v ∈ K := (exists_norm_eq_infi_of_complete_subspace K (complete_space_coe_iff_is_complete.mp ‹_›) v).some_spec.some /-- The characterization of the unbundled orthogonal projection. This lemma is only intended for use in setting up the bundled version and should not be used once that is defined. -/ lemma orthogonal_projection_fn_inner_eq_zero (v : E) : ∀ w ∈ K, ⟪v - orthogonal_projection_fn K v, w⟫ = 0 := begin rw ←norm_eq_infi_iff_inner_eq_zero K (orthogonal_projection_fn_mem v), exact (exists_norm_eq_infi_of_complete_subspace K (complete_space_coe_iff_is_complete.mp ‹_›) v).some_spec.some_spec end /-- The unbundled orthogonal projection is the unique point in `K` with the orthogonality property. This lemma is only intended for use in setting up the bundled version and should not be used once that is defined. -/ lemma eq_orthogonal_projection_fn_of_mem_of_inner_eq_zero {u v : E} (hvm : v ∈ K) (hvo : ∀ w ∈ K, ⟪u - v, w⟫ = 0) : orthogonal_projection_fn K u = v := begin rw [←sub_eq_zero, ←inner_self_eq_zero], have hvs : orthogonal_projection_fn K u - v ∈ K := submodule.sub_mem K (orthogonal_projection_fn_mem u) hvm, have huo : ⟪u - orthogonal_projection_fn K u, orthogonal_projection_fn K u - v⟫ = 0 := orthogonal_projection_fn_inner_eq_zero u _ hvs, have huv : ⟪u - v, orthogonal_projection_fn K u - v⟫ = 0 := hvo _ hvs, have houv : ⟪(u - v) - (u - orthogonal_projection_fn K u), orthogonal_projection_fn K u - v⟫ = 0, { rw [inner_sub_left, huo, huv, sub_zero] }, rwa sub_sub_sub_cancel_left at houv end variables (K) lemma orthogonal_projection_fn_norm_sq (v : E) : ∥v∥ * ∥v∥ = ∥v - (orthogonal_projection_fn K v)∥ * ∥v - (orthogonal_projection_fn K v)∥ + ∥orthogonal_projection_fn K v∥ * ∥orthogonal_projection_fn K v∥ := begin set p := orthogonal_projection_fn K v, have h' : ⟪v - p, p⟫ = 0, { exact orthogonal_projection_fn_inner_eq_zero _ _ (orthogonal_projection_fn_mem v) }, convert norm_add_square_eq_norm_square_add_norm_square_of_inner_eq_zero (v - p) p h' using 2; simp, end /-- The orthogonal projection onto a complete subspace. -/ def orthogonal_projection : E →L[𝕜] K := linear_map.mk_continuous { to_fun := λ v, ⟨orthogonal_projection_fn K v, orthogonal_projection_fn_mem v⟩, map_add' := λ x y, begin have hm : orthogonal_projection_fn K x + orthogonal_projection_fn K y ∈ K := submodule.add_mem K (orthogonal_projection_fn_mem x) (orthogonal_projection_fn_mem y), have ho : ∀ w ∈ K, ⟪x + y - (orthogonal_projection_fn K x + orthogonal_projection_fn K y), w⟫ = 0, { intros w hw, rw [add_sub_comm, inner_add_left, orthogonal_projection_fn_inner_eq_zero _ w hw, orthogonal_projection_fn_inner_eq_zero _ w hw, add_zero] }, ext, simp [eq_orthogonal_projection_fn_of_mem_of_inner_eq_zero hm ho] end, map_smul' := λ c x, begin have hm : c • orthogonal_projection_fn K x ∈ K := submodule.smul_mem K _ (orthogonal_projection_fn_mem x), have ho : ∀ w ∈ K, ⟪c • x - c • orthogonal_projection_fn K x, w⟫ = 0, { intros w hw, rw [←smul_sub, inner_smul_left, orthogonal_projection_fn_inner_eq_zero _ w hw, mul_zero] }, ext, simp [eq_orthogonal_projection_fn_of_mem_of_inner_eq_zero hm ho] end } 1 (λ x, begin simp only [one_mul, linear_map.coe_mk], refine le_of_pow_le_pow 2 (norm_nonneg _) (by norm_num) _, change ∥orthogonal_projection_fn K x∥ ^ 2 ≤ ∥x∥ ^ 2, nlinarith [orthogonal_projection_fn_norm_sq K x] end) variables {K} @[simp] lemma orthogonal_projection_fn_eq (v : E) : orthogonal_projection_fn K v = (orthogonal_projection K v : E) := rfl /-- The characterization of the orthogonal projection. -/ @[simp] lemma orthogonal_projection_inner_eq_zero (v : E) : ∀ w ∈ K, ⟪v - orthogonal_projection K v, w⟫ = 0 := orthogonal_projection_fn_inner_eq_zero v /-- The orthogonal projection is the unique point in `K` with the orthogonality property. -/ lemma eq_orthogonal_projection_of_mem_of_inner_eq_zero {u v : E} (hvm : v ∈ K) (hvo : ∀ w ∈ K, ⟪u - v, w⟫ = 0) : (orthogonal_projection K u : E) = v := eq_orthogonal_projection_fn_of_mem_of_inner_eq_zero hvm hvo /-- The orthogonal projections onto equal subspaces are coerced back to the same point in `E`. -/ lemma eq_orthogonal_projection_of_eq_submodule {K' : submodule 𝕜 E} [complete_space K'] (h : K = K') (u : E) : (orthogonal_projection K u : E) = (orthogonal_projection K' u : E) := begin change orthogonal_projection_fn K u = orthogonal_projection_fn K' u, congr, exact h end /-- The orthogonal projection sends elements of `K` to themselves. -/ @[simp] lemma orthogonal_projection_mem_subspace_eq_self (v : K) : orthogonal_projection K v = v := by { ext, apply eq_orthogonal_projection_of_mem_of_inner_eq_zero; simp } local attribute [instance] finite_dimensional_bot /-- The orthogonal projection onto the trivial submodule is the zero map. -/ @[simp] lemma orthogonal_projection_bot : orthogonal_projection (⊥ : submodule 𝕜 E) = 0 := begin ext u, apply eq_orthogonal_projection_of_mem_of_inner_eq_zero, { simp }, { intros w hw, simp [(submodule.mem_bot 𝕜).mp hw] } end variables (K) /-- The orthogonal projection has norm `≤ 1`. -/ lemma orthogonal_projection_norm_le : ∥orthogonal_projection K∥ ≤ 1 := linear_map.mk_continuous_norm_le _ (by norm_num) _ variables (𝕜) lemma smul_orthogonal_projection_singleton {v : E} (w : E) : (∥v∥ ^ 2 : 𝕜) • (orthogonal_projection (𝕜 ∙ v) w : E) = ⟪v, w⟫ • v := begin suffices : ↑(orthogonal_projection (𝕜 ∙ v) ((∥v∥ ^ 2 : 𝕜) • w)) = ⟪v, w⟫ • v, { simpa using this }, apply eq_orthogonal_projection_of_mem_of_inner_eq_zero, { rw submodule.mem_span_singleton, use ⟪v, w⟫ }, { intros x hx, obtain ⟨c, rfl⟩ := submodule.mem_span_singleton.mp hx, have hv : ↑∥v∥ ^ 2 = ⟪v, v⟫ := by { norm_cast, simp [norm_sq_eq_inner] }, simp [inner_sub_left, inner_smul_left, inner_smul_right, is_R_or_C.conj_div, mul_comm, hv, inner_product_space.conj_sym, hv] } end /-- Formula for orthogonal projection onto a single vector. -/ lemma orthogonal_projection_singleton {v : E} (w : E) : (orthogonal_projection (𝕜 ∙ v) w : E) = (⟪v, w⟫ / ∥v∥ ^ 2) • v := begin by_cases hv : v = 0, { rw [hv, eq_orthogonal_projection_of_eq_submodule submodule.span_zero_singleton], { simp }, { apply_instance } }, have hv' : ∥v∥ ≠ 0 := ne_of_gt (norm_pos_iff.mpr hv), have key : ((∥v∥ ^ 2 : 𝕜)⁻¹ * ∥v∥ ^ 2) • ↑(orthogonal_projection (𝕜 ∙ v) w) = ((∥v∥ ^ 2 : 𝕜)⁻¹ * ⟪v, w⟫) • v, { simp [mul_smul, smul_orthogonal_projection_singleton 𝕜 w] }, convert key; field_simp [hv'] end /-- Formula for orthogonal projection onto a single unit vector. -/ lemma orthogonal_projection_unit_singleton {v : E} (hv : ∥v∥ = 1) (w : E) : (orthogonal_projection (𝕜 ∙ v) w : E) = ⟪v, w⟫ • v := by { rw ← smul_orthogonal_projection_singleton 𝕜 w, simp [hv] } end orthogonal_projection /-- The subspace of vectors orthogonal to a given subspace. -/ def submodule.orthogonal : submodule 𝕜 E := { carrier := {v | ∀ u ∈ K, ⟪u, v⟫ = 0}, zero_mem' := λ _ _, inner_zero_right, add_mem' := λ x y hx hy u hu, by rw [inner_add_right, hx u hu, hy u hu, add_zero], smul_mem' := λ c x hx u hu, by rw [inner_smul_right, hx u hu, mul_zero] } notation K`ᗮ`:1200 := submodule.orthogonal K /-- When a vector is in `Kᗮ`. -/ lemma submodule.mem_orthogonal (v : E) : v ∈ Kᗮ ↔ ∀ u ∈ K, ⟪u, v⟫ = 0 := iff.rfl /-- When a vector is in `Kᗮ`, with the inner product the other way round. -/ lemma submodule.mem_orthogonal' (v : E) : v ∈ Kᗮ ↔ ∀ u ∈ K, ⟪v, u⟫ = 0 := by simp_rw [submodule.mem_orthogonal, inner_eq_zero_sym] variables {K} /-- A vector in `K` is orthogonal to one in `Kᗮ`. -/ lemma submodule.inner_right_of_mem_orthogonal {u v : E} (hu : u ∈ K) (hv : v ∈ Kᗮ) : ⟪u, v⟫ = 0 := (K.mem_orthogonal v).1 hv u hu /-- A vector in `Kᗮ` is orthogonal to one in `K`. -/ lemma submodule.inner_left_of_mem_orthogonal {u v : E} (hu : u ∈ K) (hv : v ∈ Kᗮ) : ⟪v, u⟫ = 0 := by rw [inner_eq_zero_sym]; exact submodule.inner_right_of_mem_orthogonal hu hv /-- A vector in `(𝕜 ∙ u)ᗮ` is orthogonal to `u`. -/ lemma inner_right_of_mem_orthogonal_singleton (u : E) {v : E} (hv : v ∈ (𝕜 ∙ u)ᗮ) : ⟪u, v⟫ = 0 := submodule.inner_right_of_mem_orthogonal (submodule.mem_span_singleton_self u) hv /-- A vector in `(𝕜 ∙ u)ᗮ` is orthogonal to `u`. -/ lemma inner_left_of_mem_orthogonal_singleton (u : E) {v : E} (hv : v ∈ (𝕜 ∙ u)ᗮ) : ⟪v, u⟫ = 0 := submodule.inner_left_of_mem_orthogonal (submodule.mem_span_singleton_self u) hv variables (K) /-- `K` and `Kᗮ` have trivial intersection. -/ lemma submodule.inf_orthogonal_eq_bot : K ⊓ Kᗮ = ⊥ := begin rw submodule.eq_bot_iff, intros x, rw submodule.mem_inf, exact λ ⟨hx, ho⟩, inner_self_eq_zero.1 (ho x hx) end /-- `K` and `Kᗮ` have trivial intersection. -/ lemma submodule.orthogonal_disjoint : disjoint K Kᗮ := by simp [disjoint_iff, K.inf_orthogonal_eq_bot] /-- `Kᗮ` can be characterized as the intersection of the kernels of the operations of inner product with each of the elements of `K`. -/ lemma orthogonal_eq_inter : Kᗮ = ⨅ v : K, (inner_right (v:E)).ker := begin apply le_antisymm, { rw le_infi_iff, rintros ⟨v, hv⟩ w hw, simpa using hw _ hv }, { intros v hv w hw, simp only [submodule.mem_infi] at hv, exact hv ⟨w, hw⟩ } end /-- The orthogonal complement of any submodule `K` is closed. -/ lemma submodule.is_closed_orthogonal : is_closed (Kᗮ : set E) := begin rw orthogonal_eq_inter K, convert is_closed_Inter (λ v : K, (inner_right (v:E)).is_closed_ker), simp end /-- In a complete space, the orthogonal complement of any submodule `K` is complete. -/ instance [complete_space E] : complete_space Kᗮ := K.is_closed_orthogonal.complete_space_coe variables (𝕜 E) /-- `submodule.orthogonal` gives a `galois_connection` between `submodule 𝕜 E` and its `order_dual`. -/ lemma submodule.orthogonal_gc : @galois_connection (submodule 𝕜 E) (order_dual $ submodule 𝕜 E) _ _ submodule.orthogonal submodule.orthogonal := λ K₁ K₂, ⟨λ h v hv u hu, submodule.inner_left_of_mem_orthogonal hv (h hu), λ h v hv u hu, submodule.inner_left_of_mem_orthogonal hv (h hu)⟩ variables {𝕜 E} /-- `submodule.orthogonal` reverses the `≤` ordering of two subspaces. -/ lemma submodule.orthogonal_le {K₁ K₂ : submodule 𝕜 E} (h : K₁ ≤ K₂) : K₂ᗮ ≤ K₁ᗮ := (submodule.orthogonal_gc 𝕜 E).monotone_l h /-- `submodule.orthogonal.orthogonal` preserves the `≤` ordering of two subspaces. -/ lemma submodule.orthogonal_orthogonal_monotone {K₁ K₂ : submodule 𝕜 E} (h : K₁ ≤ K₂) : K₁ᗮᗮ ≤ K₂ᗮᗮ := submodule.orthogonal_le (submodule.orthogonal_le h) /-- `K` is contained in `Kᗮᗮ`. -/ lemma submodule.le_orthogonal_orthogonal : K ≤ Kᗮᗮ := (submodule.orthogonal_gc 𝕜 E).le_u_l _ /-- The inf of two orthogonal subspaces equals the subspace orthogonal to the sup. -/ lemma submodule.inf_orthogonal (K₁ K₂ : submodule 𝕜 E) : K₁ᗮ ⊓ K₂ᗮ = (K₁ ⊔ K₂)ᗮ := (submodule.orthogonal_gc 𝕜 E).l_sup.symm /-- The inf of an indexed family of orthogonal subspaces equals the subspace orthogonal to the sup. -/ lemma submodule.infi_orthogonal {ι : Type*} (K : ι → submodule 𝕜 E) : (⨅ i, (K i)ᗮ) = (supr K)ᗮ := (submodule.orthogonal_gc 𝕜 E).l_supr.symm /-- The inf of a set of orthogonal subspaces equals the subspace orthogonal to the sup. -/ lemma submodule.Inf_orthogonal (s : set $ submodule 𝕜 E) : (⨅ K ∈ s, Kᗮ) = (Sup s)ᗮ := (submodule.orthogonal_gc 𝕜 E).l_Sup.symm /-- If `K₁` is complete and contained in `K₂`, `K₁` and `K₁ᗮ ⊓ K₂` span `K₂`. -/ lemma submodule.sup_orthogonal_inf_of_is_complete {K₁ K₂ : submodule 𝕜 E} (h : K₁ ≤ K₂) (hc : is_complete (K₁ : set E)) : K₁ ⊔ (K₁ᗮ ⊓ K₂) = K₂ := begin ext x, rw submodule.mem_sup, rcases exists_norm_eq_infi_of_complete_subspace K₁ hc x with ⟨v, hv, hvm⟩, rw norm_eq_infi_iff_inner_eq_zero K₁ hv at hvm, split, { rintro ⟨y, hy, z, hz, rfl⟩, exact K₂.add_mem (h hy) hz.2 }, { exact λ hx, ⟨v, hv, x - v, ⟨(K₁.mem_orthogonal' _).2 hvm, K₂.sub_mem hx (h hv)⟩, add_sub_cancel'_right _ _⟩ } end variables {K} /-- If `K` is complete, `K` and `Kᗮ` span the whole space. -/ lemma submodule.sup_orthogonal_of_is_complete (h : is_complete (K : set E)) : K ⊔ Kᗮ = ⊤ := begin convert submodule.sup_orthogonal_inf_of_is_complete (le_top : K ≤ ⊤) h, simp end /-- If `K` is complete, `K` and `Kᗮ` span the whole space. Version using `complete_space`. -/ lemma submodule.sup_orthogonal_of_complete_space [complete_space K] : K ⊔ Kᗮ = ⊤ := submodule.sup_orthogonal_of_is_complete (complete_space_coe_iff_is_complete.mp ‹_›) variables (K) /-- If `K` is complete, any `v` in `E` can be expressed as a sum of elements of `K` and `Kᗮ`. -/ lemma submodule.exists_sum_mem_mem_orthogonal [complete_space K] (v : E) : ∃ (y ∈ K) (z ∈ Kᗮ), v = y + z := begin have h_mem : v ∈ K ⊔ Kᗮ := by simp [submodule.sup_orthogonal_of_complete_space], obtain ⟨y, hy, z, hz, hyz⟩ := submodule.mem_sup.mp h_mem, exact ⟨y, hy, z, hz, hyz.symm⟩ end /-- If `K` is complete, then the orthogonal complement of its orthogonal complement is itself. -/ @[simp] lemma submodule.orthogonal_orthogonal [complete_space K] : Kᗮᗮ = K := begin ext v, split, { obtain ⟨y, hy, z, hz, rfl⟩ := K.exists_sum_mem_mem_orthogonal v, intros hv, have hz' : z = 0, { have hyz : ⟪z, y⟫ = 0 := by simp [hz y hy, inner_eq_zero_sym], simpa [inner_add_right, hyz] using hv z hz }, simp [hy, hz'] }, { intros hv w hw, rw inner_eq_zero_sym, exact hw v hv } end lemma submodule.orthogonal_orthogonal_eq_closure [complete_space E] : Kᗮᗮ = K.topological_closure := begin refine le_antisymm _ _, { convert submodule.orthogonal_orthogonal_monotone K.submodule_topological_closure, haveI : complete_space K.topological_closure := K.is_closed_topological_closure.complete_space_coe, rw K.topological_closure.orthogonal_orthogonal }, { exact K.topological_closure_minimal K.le_orthogonal_orthogonal Kᗮ.is_closed_orthogonal } end variables {K} /-- If `K` is complete, `K` and `Kᗮ` are complements of each other. -/ lemma submodule.is_compl_orthogonal_of_is_complete (h : is_complete (K : set E)) : is_compl K Kᗮ := ⟨K.orthogonal_disjoint, le_of_eq (submodule.sup_orthogonal_of_is_complete h).symm⟩ @[simp] lemma submodule.top_orthogonal_eq_bot : (⊤ : submodule 𝕜 E)ᗮ = ⊥ := begin ext, rw [submodule.mem_bot, submodule.mem_orthogonal], exact ⟨λ h, inner_self_eq_zero.mp (h x submodule.mem_top), by { rintro rfl, simp }⟩ end @[simp] lemma submodule.bot_orthogonal_eq_top : (⊥ : submodule 𝕜 E)ᗮ = ⊤ := begin rw [← submodule.top_orthogonal_eq_bot, eq_top_iff], exact submodule.le_orthogonal_orthogonal ⊤ end @[simp] lemma submodule.orthogonal_eq_bot_iff (hK : is_complete (K : set E)) : Kᗮ = ⊥ ↔ K = ⊤ := begin refine ⟨_, by { rintro rfl, exact submodule.top_orthogonal_eq_bot }⟩, intro h, have : K ⊔ Kᗮ = ⊤ := submodule.sup_orthogonal_of_is_complete hK, rwa [h, sup_comm, bot_sup_eq] at this, end @[simp] lemma submodule.orthogonal_eq_top_iff : Kᗮ = ⊤ ↔ K = ⊥ := begin refine ⟨_, by { rintro rfl, exact submodule.bot_orthogonal_eq_top }⟩, intro h, have : K ⊓ Kᗮ = ⊥ := K.orthogonal_disjoint.eq_bot, rwa [h, inf_comm, top_inf_eq] at this end /-- A point in `K` with the orthogonality property (here characterized in terms of `Kᗮ`) must be the orthogonal projection. -/ lemma eq_orthogonal_projection_of_mem_orthogonal [complete_space K] {u v : E} (hv : v ∈ K) (hvo : u - v ∈ Kᗮ) : (orthogonal_projection K u : E) = v := eq_orthogonal_projection_fn_of_mem_of_inner_eq_zero hv (λ w, inner_eq_zero_sym.mp ∘ (hvo w)) /-- A point in `K` with the orthogonality property (here characterized in terms of `Kᗮ`) must be the orthogonal projection. -/ lemma eq_orthogonal_projection_of_mem_orthogonal' [complete_space K] {u v z : E} (hv : v ∈ K) (hz : z ∈ Kᗮ) (hu : u = v + z) : (orthogonal_projection K u : E) = v := eq_orthogonal_projection_of_mem_orthogonal hv (by simpa [hu]) /-- The orthogonal projection onto `K` of an element of `Kᗮ` is zero. -/ lemma orthogonal_projection_mem_subspace_orthogonal_complement_eq_zero [complete_space K] {v : E} (hv : v ∈ Kᗮ) : orthogonal_projection K v = 0 := by { ext, convert eq_orthogonal_projection_of_mem_orthogonal _ _; simp [hv] } /-- The orthogonal projection onto `Kᗮ` of an element of `K` is zero. -/ lemma orthogonal_projection_mem_subspace_orthogonal_precomplement_eq_zero [complete_space E] {v : E} (hv : v ∈ K) : orthogonal_projection Kᗮ v = 0 := orthogonal_projection_mem_subspace_orthogonal_complement_eq_zero (K.le_orthogonal_orthogonal hv) /-- The orthogonal projection onto `(𝕜 ∙ v)ᗮ` of `v` is zero. -/ lemma orthogonal_projection_orthogonal_complement_singleton_eq_zero [complete_space E] (v : E) : orthogonal_projection (𝕜 ∙ v)ᗮ v = 0 := orthogonal_projection_mem_subspace_orthogonal_precomplement_eq_zero (submodule.mem_span_singleton_self v) variables (K) /-- In a complete space `E`, a vector splits as the sum of its orthogonal projections onto a complete submodule `K` and onto the orthogonal complement of `K`.-/ lemma eq_sum_orthogonal_projection_self_orthogonal_complement [complete_space E] [complete_space K] (w : E) : w = (orthogonal_projection K w : E) + (orthogonal_projection Kᗮ w : E) := begin obtain ⟨y, hy, z, hz, hwyz⟩ := K.exists_sum_mem_mem_orthogonal w, convert hwyz, { exact eq_orthogonal_projection_of_mem_orthogonal' hy hz hwyz }, { rw add_comm at hwyz, refine eq_orthogonal_projection_of_mem_orthogonal' hz _ hwyz, simp [hy] } end /-- In a complete space `E`, the projection maps onto a complete subspace `K` and its orthogonal complement sum to the identity. -/ lemma id_eq_sum_orthogonal_projection_self_orthogonal_complement [complete_space E] [complete_space K] : continuous_linear_map.id 𝕜 E = K.subtypeL.comp (orthogonal_projection K) + Kᗮ.subtypeL.comp (orthogonal_projection Kᗮ) := by { ext w, exact eq_sum_orthogonal_projection_self_orthogonal_complement K w } open finite_dimensional /-- Given a finite-dimensional subspace `K₂`, and a subspace `K₁` containined in it, the dimensions of `K₁` and the intersection of its orthogonal subspace with `K₂` add to that of `K₂`. -/ lemma submodule.findim_add_inf_findim_orthogonal {K₁ K₂ : submodule 𝕜 E} [finite_dimensional 𝕜 K₂] (h : K₁ ≤ K₂) : findim 𝕜 K₁ + findim 𝕜 (K₁ᗮ ⊓ K₂ : submodule 𝕜 E) = findim 𝕜 K₂ := begin haveI := submodule.finite_dimensional_of_le h, have hd := submodule.dim_sup_add_dim_inf_eq K₁ (K₁ᗮ ⊓ K₂), rw [←inf_assoc, (submodule.orthogonal_disjoint K₁).eq_bot, bot_inf_eq, findim_bot, submodule.sup_orthogonal_inf_of_is_complete h (submodule.complete_of_finite_dimensional _)] at hd, rw add_zero at hd, exact hd.symm end /-- Given a finite-dimensional subspace `K₂`, and a subspace `K₁` containined in it, the dimensions of `K₁` and the intersection of its orthogonal subspace with `K₂` add to that of `K₂`. -/ lemma submodule.findim_add_inf_findim_orthogonal' {K₁ K₂ : submodule 𝕜 E} [finite_dimensional 𝕜 K₂] (h : K₁ ≤ K₂) {n : ℕ} (h_dim : findim 𝕜 K₁ + n = findim 𝕜 K₂) : findim 𝕜 (K₁ᗮ ⊓ K₂ : submodule 𝕜 E) = n := by { rw ← add_right_inj (findim 𝕜 K₁), simp [submodule.findim_add_inf_findim_orthogonal h, h_dim] } /-- Given a finite-dimensional space `E` and subspace `K`, the dimensions of `K` and `Kᗮ` add to that of `E`. -/ lemma submodule.findim_add_findim_orthogonal [finite_dimensional 𝕜 E] {K : submodule 𝕜 E} : findim 𝕜 K + findim 𝕜 Kᗮ = findim 𝕜 E := begin convert submodule.findim_add_inf_findim_orthogonal (le_top : K ≤ ⊤) using 1, { rw inf_top_eq }, { simp } end /-- Given a finite-dimensional space `E` and subspace `K`, the dimensions of `K` and `Kᗮ` add to that of `E`. -/ lemma submodule.findim_add_findim_orthogonal' [finite_dimensional 𝕜 E] {K : submodule 𝕜 E} {n : ℕ} (h_dim : findim 𝕜 K + n = findim 𝕜 E) : findim 𝕜 Kᗮ = n := by { rw ← add_right_inj (findim 𝕜 K), simp [submodule.findim_add_findim_orthogonal, h_dim] } local attribute [instance] finite_dimensional_of_findim_eq_succ /-- In a finite-dimensional inner product space, the dimension of the orthogonal complement of the span of a nonzero vector is one less than the dimension of the space. -/ lemma findim_orthogonal_span_singleton {n : ℕ} [_i : fact (findim 𝕜 E = n + 1)] {v : E} (hv : v ≠ 0) : findim 𝕜 (𝕜 ∙ v)ᗮ = n := submodule.findim_add_findim_orthogonal' $ by simp [findim_span_singleton hv, _i.elim, add_comm] end orthogonal section orthonormal_basis /-! ### Existence of Hilbert basis, orthonormal basis, etc. -/ variables {𝕜 E} {v : set E} open finite_dimensional submodule set /-- An orthonormal set in an `inner_product_space` is maximal, if and only if the orthogonal complement of its span is empty. -/ lemma maximal_orthonormal_iff_orthogonal_complement_eq_bot (hv : orthonormal 𝕜 (coe : v → E)) : (∀ u ⊇ v, orthonormal 𝕜 (coe : u → E) → u = v) ↔ (span 𝕜 v)ᗮ = ⊥ := begin rw submodule.eq_bot_iff, split, { contrapose!, -- ** direction 1: nonempty orthogonal complement implies nonmaximal rintros ⟨x, hx', hx⟩, -- take a nonzero vector and normalize it let e := (∥x∥⁻¹ : 𝕜) • x, have he : ∥e∥ = 1 := by simp [e, norm_smul_inv_norm hx], have he' : e ∈ (span 𝕜 v)ᗮ := smul_mem' _ _ hx', have he'' : e ∉ v, { intros hev, have : e = 0, { have : e ∈ (span 𝕜 v) ⊓ (span 𝕜 v)ᗮ := ⟨subset_span hev, he'⟩, simpa [(span 𝕜 v).inf_orthogonal_eq_bot] using this }, have : e ≠ 0 := hv.ne_zero ⟨e, hev⟩, contradiction }, -- put this together with `v` to provide a candidate orthonormal basis for the whole space refine ⟨v.insert e, v.subset_insert e, ⟨_, _⟩, (v.ne_insert_of_not_mem he'').symm⟩, { -- show that the elements of `v.insert e` have unit length rintros ⟨a, ha'⟩, cases eq_or_mem_of_mem_insert ha' with ha ha, { simp [ha, he] }, { exact hv.1 ⟨a, ha⟩ } }, { -- show that the elements of `v.insert e` are orthogonal have h_end : ∀ a ∈ v, ⟪a, e⟫ = 0, { intros a ha, exact he' a (submodule.subset_span ha) }, rintros ⟨a, ha'⟩, cases eq_or_mem_of_mem_insert ha' with ha ha, { rintros ⟨b, hb'⟩ hab', have hb : b ∈ v, { refine mem_of_mem_insert_of_ne hb' _, intros hbe', apply hab', simp [ha, hbe'] }, rw inner_eq_zero_sym, simpa [ha] using h_end b hb }, rintros ⟨b, hb'⟩ hab', cases eq_or_mem_of_mem_insert hb' with hb hb, { simpa [hb] using h_end a ha }, have : (⟨a, ha⟩ : v) ≠ ⟨b, hb⟩, { intros hab'', apply hab', simpa using hab'' }, exact hv.2 this } }, { -- ** direction 2: empty orthogonal complement implies maximal simp only [subset.antisymm_iff], rintros h u (huv : v ⊆ u) hu, refine ⟨_, huv⟩, intros x hxu, refine ((mt (h x)) (hu.ne_zero ⟨x, hxu⟩)).imp_symm _, intros hxv y hy, have hxv' : (⟨x, hxu⟩ : u) ∉ (coe ⁻¹' v : set u) := by simp [huv, hxv], obtain ⟨l, hl, rfl⟩ : ∃ l ∈ finsupp.supported 𝕜 𝕜 (coe ⁻¹' v : set u), (finsupp.total ↥u E 𝕜 coe) l = y, { rw ← finsupp.mem_span_iff_total, simp [huv, inter_eq_self_of_subset_left, hy] }, exact hu.inner_finsupp_eq_zero hxv' hl } end /-- An orthonormal set in an `inner_product_space` is maximal, if and only if the closure of its span is the whole space. -/ lemma maximal_orthonormal_iff_dense_span [complete_space E] (hv : orthonormal 𝕜 (coe : v → E)) : (∀ u ⊇ v, orthonormal 𝕜 (coe : u → E) → u = v) ↔ (span 𝕜 v).topological_closure = ⊤ := by rw [maximal_orthonormal_iff_orthogonal_complement_eq_bot hv, ← submodule.orthogonal_eq_top_iff, (span 𝕜 v).orthogonal_orthogonal_eq_closure] /-- Any orthonormal subset can be extended to an orthonormal set whose span is dense. -/ lemma exists_subset_is_orthonormal_dense_span [complete_space E] (hv : orthonormal 𝕜 (coe : v → E)) : ∃ u ⊇ v, orthonormal 𝕜 (coe : u → E) ∧ (span 𝕜 u).topological_closure = ⊤ := begin obtain ⟨u, hus, hu, hu_max⟩ := exists_maximal_orthonormal hv, rw maximal_orthonormal_iff_dense_span hu at hu_max, exact ⟨u, hus, hu, hu_max⟩ end variables (𝕜 E) /-- An inner product space admits an orthonormal set whose span is dense. -/ lemma exists_is_orthonormal_dense_span [complete_space E] : ∃ u : set E, orthonormal 𝕜 (coe : u → E) ∧ (span 𝕜 u).topological_closure = ⊤ := let ⟨u, hus, hu, hu_max⟩ := exists_subset_is_orthonormal_dense_span (orthonormal_empty 𝕜 E) in ⟨u, hu, hu_max⟩ variables {𝕜 E} /-- An orthonormal set in a finite-dimensional `inner_product_space` is maximal, if and only if it is a basis. -/ lemma maximal_orthonormal_iff_is_basis_of_finite_dimensional [finite_dimensional 𝕜 E] (hv : orthonormal 𝕜 (coe : v → E)) : (∀ u ⊇ v, orthonormal 𝕜 (coe : u → E) → u = v) ↔ is_basis 𝕜 (coe : v → E) := begin rw maximal_orthonormal_iff_orthogonal_complement_eq_bot hv, have hv_compl : is_complete (span 𝕜 v : set E) := (span 𝕜 v).complete_of_finite_dimensional, rw submodule.orthogonal_eq_bot_iff hv_compl, have hv_coe : range (coe : v → E) = v := by simp, split, { refine λ h, ⟨hv.linear_independent, _⟩, convert h }, { intros h, convert ← h.2 } end /-- In a finite-dimensional `inner_product_space`, any orthonormal subset can be extended to an orthonormal basis. -/ lemma exists_subset_is_orthonormal_basis [finite_dimensional 𝕜 E] (hv : orthonormal 𝕜 (coe : v → E)) : ∃ u ⊇ v, orthonormal 𝕜 (coe : u → E) ∧ is_basis 𝕜 (coe : u → E) := begin obtain ⟨u, hus, hu, hu_max⟩ := exists_maximal_orthonormal hv, rw maximal_orthonormal_iff_is_basis_of_finite_dimensional hu at hu_max, exact ⟨u, hus, hu, hu_max⟩ end variables (𝕜 E) /-- A finite-dimensional `inner_product_space` has an orthonormal basis. -/ lemma exists_is_orthonormal_basis [finite_dimensional 𝕜 E] : ∃ u : set E, orthonormal 𝕜 (coe : u → E) ∧ is_basis 𝕜 (coe : u → E) := let ⟨u, hus, hu, hu_max⟩ := exists_subset_is_orthonormal_basis (orthonormal_empty 𝕜 E) in ⟨u, hu, hu_max⟩ variables {𝕜 E} /-- Given a natural number `n` equal to the `findim` of a finite-dimensional inner product space, there exists an orthonormal basis for the space indexed by `fin n`. -/ lemma exists_is_orthonormal_basis' [finite_dimensional 𝕜 E] {n : ℕ} (hn : findim 𝕜 E = n) : ∃ v : fin n → E, orthonormal 𝕜 v ∧ is_basis 𝕜 v := begin obtain ⟨u, hu, hu_basis⟩ := exists_is_orthonormal_basis 𝕜 E, obtain ⟨g, hg⟩ := finite_dimensional.equiv_fin_of_dim_eq hn hu_basis, exact ⟨coe ∘ g, hu.comp _ g.injective, hg⟩ end /-- Given a natural number `n` equal to the `findim` of a finite-dimensional inner product space, there exists an isometry from the space to `euclidean_space 𝕜 (fin n)`. -/ def linear_isometry_equiv.of_inner_product_space [finite_dimensional 𝕜 E] {n : ℕ} (hn : findim 𝕜 E = n) : E ≃ₗᵢ[𝕜] (euclidean_space 𝕜 (fin n)) := let hv := classical.some_spec (exists_is_orthonormal_basis' hn) in hv.2.isometry_euclidean_of_orthonormal hv.1 local attribute [instance] finite_dimensional_of_findim_eq_succ /-- Given a natural number `n` one less than the `findim` of a finite-dimensional inner product space, there exists an isometry from the orthogonal complement of a nonzero singleton to `euclidean_space 𝕜 (fin n)`. -/ def linear_isometry_equiv.from_orthogonal_span_singleton (n : ℕ) [fact (findim 𝕜 E = n + 1)] {v : E} (hv : v ≠ 0) : (𝕜 ∙ v)ᗮ ≃ₗᵢ[𝕜] (euclidean_space 𝕜 (fin n)) := linear_isometry_equiv.of_inner_product_space (findim_orthogonal_span_singleton hv) end orthonormal_basis
dbdee493869bcada8f6e7fe84f9a3e520cce8440
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/ring_theory/adjoin/power_basis.lean
e400d257dc74d1c4a322aeca4f6ffcab8992d4ac
[ "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
7,996
lean
/- Copyright (c) 2021 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen -/ import ring_theory.adjoin.basic import ring_theory.power_basis import linear_algebra.matrix.basis /-! # Power basis for `algebra.adjoin R {x}` This file defines the canonical power basis on `algebra.adjoin R {x}`, where `x` is an integral element over `R`. -/ variables {K S : Type*} [field K] [comm_ring S] [algebra K S] namespace algebra open polynomial open power_basis open_locale big_operators /-- The elements `1, x, ..., x ^ (d - 1)` for a basis for the `K`-module `K[x]`, where `d` is the degree of the minimal polynomial of `x`. -/ noncomputable def adjoin.power_basis_aux {x : S} (hx : _root_.is_integral K x) : basis (fin (minpoly K x).nat_degree) K (adjoin K ({x} : set S)) := begin have hST : function.injective (algebra_map (adjoin K ({x} : set S)) S) := subtype.coe_injective, have hx' : _root_.is_integral K (show adjoin K ({x} : set S), from ⟨x, subset_adjoin (set.mem_singleton x)⟩), { apply (is_integral_algebra_map_iff hST).mp, convert hx, apply_instance }, have minpoly_eq := minpoly.eq_of_algebra_map_eq hST hx' rfl, apply @basis.mk (fin (minpoly K x).nat_degree) _ (adjoin K {x}) (λ i, ⟨x, subset_adjoin (set.mem_singleton x)⟩ ^ (i : ℕ)), { have := hx'.linear_independent_pow, rwa minpoly_eq at this }, { rintros ⟨y, hy⟩ _, have := hx'.mem_span_pow, rw minpoly_eq at this, apply this, { rw [adjoin_singleton_eq_range_aeval] at hy, obtain ⟨f, rfl⟩ := (aeval x).mem_range.mp hy, use f, ext, exact aeval_algebra_map_apply S (⟨x, _⟩ : adjoin K {x}) _, } } end /-- The power basis `1, x, ..., x ^ (d - 1)` for `K[x]`, where `d` is the degree of the minimal polynomial of `x`. See `algebra.adjoin.power_basis'` for a version over a more general base ring. -/ @[simps gen dim] noncomputable def adjoin.power_basis {x : S} (hx : _root_.is_integral K x) : power_basis K (adjoin K ({x} : set S)) := { gen := ⟨x, subset_adjoin (set.mem_singleton x)⟩, dim := (minpoly K x).nat_degree, basis := adjoin.power_basis_aux hx, basis_eq_pow := basis.mk_apply _ _ } end algebra open algebra /-- The power basis given by `x` if `B.gen ∈ adjoin K {x}`. See `power_basis.of_gen_mem_adjoin'` for a version over a more general base ring. -/ @[simps] noncomputable def power_basis.of_gen_mem_adjoin {x : S} (B : power_basis K S) (hint : _root_.is_integral K x) (hx : B.gen ∈ adjoin K ({x} : set S)) : power_basis K S := (algebra.adjoin.power_basis hint).map $ (subalgebra.equiv_of_eq _ _ $ power_basis.adjoin_eq_top_of_gen_mem_adjoin hx).trans subalgebra.top_equiv section is_integral namespace power_basis open polynomial open_locale polynomial variables {R : Type*} [comm_ring R] [algebra R S] [algebra R K] [is_scalar_tower R K S] variables {A : Type*} [comm_ring A] [algebra R A] [algebra S A] variables [is_scalar_tower R S A] {B : power_basis S A} (hB : is_integral R B.gen) include hB /-- If `B : power_basis S A` is such that `is_integral R B.gen`, then `is_integral R (B.basis.repr (B.gen ^ n) i)` for all `i` if `minpoly S B.gen = (minpoly R B.gen).map (algebra_map R S)`. This is the case if `R` is a GCD domain and `S` is its fraction ring. -/ lemma repr_gen_pow_is_integral [is_domain S] (hmin : minpoly S B.gen = (minpoly R B.gen).map (algebra_map R S)) (n : ℕ) : ∀ i, is_integral R (B.basis.repr (B.gen ^ n) i) := begin intro i, let Q := (X ^ n) %ₘ (minpoly R B.gen), have : B.gen ^ n = aeval B.gen Q, { rw [← @aeval_X_pow R _ _ _ _ B.gen, ← mod_by_monic_add_div (X ^ n) (minpoly.monic hB)], simp }, by_cases hQ : Q = 0, { simp [this, hQ, is_integral_zero] }, have hlt : Q.nat_degree < B.dim, { rw [← B.nat_degree_minpoly, hmin, (minpoly.monic hB).nat_degree_map, nat_degree_lt_nat_degree_iff hQ], letI : nontrivial R := nontrivial.of_polynomial_ne hQ, exact degree_mod_by_monic_lt _ (minpoly.monic hB), apply_instance }, rw [this, aeval_eq_sum_range' hlt], simp only [linear_equiv.map_sum, linear_equiv.map_smulₛₗ, ring_hom.id_apply, finset.sum_apply'], refine is_integral.sum _ (λ j hj, _), replace hj := finset.mem_range.1 hj, rw [← fin.coe_mk hj, ← B.basis_eq_pow, algebra.smul_def, is_scalar_tower.algebra_map_apply R S A, ← algebra.smul_def, linear_equiv.map_smul], simp only [algebra_map_smul, finsupp.coe_smul, pi.smul_apply, B.basis.repr_self_apply], by_cases hij : (⟨j, hj⟩ : fin _) = i, { simp only [hij, eq_self_iff_true, if_true], rw [algebra.smul_def, mul_one], exact is_integral_algebra_map }, { simp [hij, is_integral_zero] } end variable {B} /-- Let `B : power_basis S A` be such that `is_integral R B.gen`, and let `x y : A` be elements with integral coordinates in the base `B.basis`. Then `is_integral R ((B.basis.repr (x * y) i)` for all `i` if `minpoly S B.gen = (minpoly R B.gen).map (algebra_map R S)`. This is the case if `R` is a GCD domain and `S` is its fraction ring. -/ lemma repr_mul_is_integral [is_domain S] {x y : A} (hx : ∀ i, is_integral R (B.basis.repr x i)) (hy : ∀ i, is_integral R (B.basis.repr y i)) (hmin : minpoly S B.gen = (minpoly R B.gen).map (algebra_map R S)) : ∀ i, is_integral R ((B.basis.repr (x * y) i)) := begin intro i, rw [← B.basis.sum_repr x, ← B.basis.sum_repr y, finset.sum_mul_sum, linear_equiv.map_sum, finset.sum_apply'], refine is_integral.sum _ (λ I hI, _), simp only [algebra.smul_mul_assoc, algebra.mul_smul_comm, linear_equiv.map_smulₛₗ, ring_hom.id_apply, finsupp.coe_smul, pi.smul_apply, id.smul_eq_mul], refine is_integral_mul (hy _) (is_integral_mul (hx _) _), simp only [coe_basis, ← pow_add], refine repr_gen_pow_is_integral hB hmin _ _, end /-- Let `B : power_basis S A` be such that `is_integral R B.gen`, and let `x : A` be and element with integral coordinates in the base `B.basis`. Then `is_integral R ((B.basis.repr (x ^ n) i)` for all `i` and all `n` if `minpoly S B.gen = (minpoly R B.gen).map (algebra_map R S)`. This is the case if `R` is a GCD domain and `S` is its fraction ring. -/ lemma repr_pow_is_integral [is_domain S] {x : A} (hx : ∀ i, is_integral R (B.basis.repr x i)) (hmin : minpoly S B.gen = (minpoly R B.gen).map (algebra_map R S)) (n : ℕ) : ∀ i, is_integral R ((B.basis.repr (x ^ n) i)) := begin nontriviality A using [subsingleton.elim (x ^ n) 0, is_integral_zero], revert hx, refine nat.case_strong_induction_on n _ (λ n hn, _), { intros hx i, rw [pow_zero, ← pow_zero B.gen, ← fin.coe_mk B.dim_pos, ← B.basis_eq_pow, B.basis.repr_self_apply], split_ifs, { exact is_integral_one }, { exact is_integral_zero } }, { intros hx, rw [pow_succ], exact repr_mul_is_integral hB hx (λ _, hn _ le_rfl (λ _, hx _) _) hmin } end /-- Let `B B' : power_basis K S` be such that `is_integral R B.gen`, and let `P : R[X]` be such that `aeval B.gen P = B'.gen`. Then `is_integral R (B.basis.to_matrix B'.basis i j)` for all `i` and `j` if `minpoly K B.gen = (minpoly R B.gen).map (algebra_map R L)`. This is the case if `R` is a GCD domain and `K` is its fraction ring. -/ lemma to_matrix_is_integral {B B' : power_basis K S} {P : R[X]} (h : aeval B.gen P = B'.gen) (hB : is_integral R B.gen) (hmin : minpoly K B.gen = (minpoly R B.gen).map (algebra_map R K)) : ∀ i j, _root_.is_integral R (B.basis.to_matrix B'.basis i j) := begin intros i j, rw [B.basis.to_matrix_apply, B'.coe_basis], refine repr_pow_is_integral hB (λ i, _) hmin _ _, rw [← h, aeval_eq_sum_range, linear_equiv.map_sum, finset.sum_apply'], refine is_integral.sum _ (λ n hn, _), rw [algebra.smul_def, is_scalar_tower.algebra_map_apply R K S, ← algebra.smul_def, linear_equiv.map_smul, algebra_map_smul], exact is_integral_smul _ (repr_gen_pow_is_integral hB hmin _ _), end end power_basis end is_integral
b87393fb8af2e53a781a1afe22ac449648e236c8
d1a52c3f208fa42c41df8278c3d280f075eb020c
/src/Lean/Server/Requests.lean
b0ea8fe58b7f8da1cee8dd94ea526656729036ee
[ "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
6,353
lean
/- Copyright (c) 2021 Wojciech Nawrocki. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Wojciech Nawrocki, Marc Huisinga -/ import Lean.DeclarationRange import Lean.Data.Json import Lean.Data.Lsp import Lean.Server.FileSource import Lean.Server.FileWorker.Utils import Lean.Server.Rpc.Basic /-! We maintain a global map of LSP request handlers. This allows user code such as plugins to register its own handlers, for example to support ITP functionality such as goal state visualization. For details of how to register one, see `registerLspRequestHandler`. -/ namespace Lean.Server structure RequestError where code : JsonRpc.ErrorCode message : String namespace RequestError open JsonRpc def fileChanged : RequestError := { code := ErrorCode.contentModified message := "File changed." } def methodNotFound (method : String) : RequestError := { code := ErrorCode.methodNotFound message := s!"No request handler found for '{method}'" } instance : Coe IO.Error RequestError where coe e := { code := ErrorCode.internalError message := toString e } def toLspResponseError (id : RequestID) (e : RequestError) : ResponseError Unit := { id := id code := e.code message := e.message } end RequestError def parseRequestParams (paramType : Type) [FromJson paramType] (params : Json) : Except RequestError paramType := fromJson? params |>.mapError fun inner => { code := JsonRpc.ErrorCode.parseError message := s!"Cannot parse request params: {params.compress}\n{inner}" } structure RequestContext where rpcSessions : Std.RBMap UInt64 (IO.Ref FileWorker.RpcSession) compare srcSearchPath : SearchPath doc : FileWorker.EditableDocument hLog : IO.FS.Stream abbrev RequestTask α := Task (Except RequestError α) /-- Workers execute request handlers in this monad. -/ abbrev RequestM := ReaderT RequestContext <| EIO RequestError instance : Inhabited (RequestM α) := ⟨throw ("executing Inhabited instance?!" : RequestError)⟩ instance : MonadLift IO RequestM where monadLift x := x.toEIO fun e => (e : RequestError) namespace RequestM open FileWorker open Snapshots def readDoc : RequestM EditableDocument := fun rc => rc.doc def asTask (t : RequestM α) : RequestM (RequestTask α) := fun rc => do let t ← EIO.asTask <| t rc return t.map liftExcept def mapTask (t : Task α) (f : α → RequestM β) : RequestM (RequestTask β) := fun rc => do let t ← EIO.mapTask (f · rc) t return t.map liftExcept def bindTask (t : Task α) (f : α → RequestM (RequestTask β)) : RequestM (RequestTask β) := fun rc => do EIO.bindTask t (f · rc) /-- Create a task which waits for the first snapshot matching `p`, handles various errors, and if a matching snapshot was found executes `x` with it. If not found, the task executes `notFoundX`. -/ def withWaitFindSnap (doc : EditableDocument) (p : Snapshot → Bool) (notFoundX : RequestM β) (x : Snapshot → RequestM β) : RequestM (RequestTask β) := do let findTask ← doc.cmdSnaps.waitFind? p mapTask findTask fun /- The elaboration task that we're waiting for may be aborted if the file contents change. In that case, we reply with the `fileChanged` error. Thanks to this, the server doesn't get bogged down in requests for an old state of the document. -/ | Except.error FileWorker.ElabTaskError.aborted => throwThe RequestError RequestError.fileChanged | Except.error (FileWorker.ElabTaskError.ioError e) => throw (e : RequestError) | Except.error FileWorker.ElabTaskError.eof => notFoundX | Except.ok none => notFoundX | Except.ok (some snap) => x snap end RequestM /- The global request handlers table. -/ section HandlerTable open Lsp private structure RequestHandler where fileSource : Json → Except RequestError Lsp.DocumentUri handle : Json → RequestM (RequestTask Json) builtin_initialize requestHandlers : IO.Ref (Std.PersistentHashMap String RequestHandler) ← IO.mkRef {} /-- NB: This method may only be called in `builtin_initialize` blocks. A registration consists of: - a type of JSON-parsable request data `paramType` - a `FileSource` instance for it so the system knows where to route requests - a type of JSON-serializable response data `respType` - an actual `handler` which runs in the `RequestM` monad and is expected to produce an asynchronous `RequestTask` which does any waiting/computation A handler task may be cancelled at any time, so it should check the cancellation token when possible to handle this cooperatively. Any exceptions thrown in a request handler will be reported to the client as LSP error responses. -/ def registerLspRequestHandler (method : String) paramType [FromJson paramType] [FileSource paramType] respType [ToJson respType] (handler : paramType → RequestM (RequestTask respType)) : IO Unit := do if !(← IO.initializing) then throw <| IO.userError s!"Failed to register LSP request handler for '{method}': only possible during initialization" if (←requestHandlers.get).contains method then throw <| IO.userError s!"Failed to register LSP request handler for '{method}': already registered" let fileSource := fun j => parseRequestParams paramType j |>.map Lsp.fileSource let handle := fun j => do let params ← liftExcept <| parseRequestParams paramType j let t ← handler params t.map <| Except.map ToJson.toJson requestHandlers.modify fun rhs => rhs.insert method { fileSource, handle } private def lookupLspRequestHandler (method : String) : IO (Option RequestHandler) := do (← requestHandlers.get).find? method def routeLspRequest (method : String) (params : Json) : IO (Except RequestError DocumentUri) := do match (← lookupLspRequestHandler method) with | none => return Except.error <| RequestError.methodNotFound method | some rh => return rh.fileSource params def handleLspRequest (method : String) (params : Json) : RequestM (RequestTask Json) := do match (← lookupLspRequestHandler method) with | none => throw (s!"internal server error: request '{method}' routed through watchdog but unknown in worker; are both using the same plugins?" : RequestError) | some rh => rh.handle params end HandlerTable end Lean.Server
791efd0b11fa3fe7a3f2941fc01a6c76cd482675
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/analysis/normed_space/operator_norm.lean
fedd0062fb2b8817620f04551d053d45a579cad9
[ "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
59,488
lean
/- Copyright (c) 2019 Jan-David Salchow. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jan-David Salchow, Sébastien Gouëzel, Jean Lo -/ import algebra.algebra.tower import analysis.normed_space.linear_isometry import analysis.normed_space.riesz_lemma import data.equiv.transfer_instance /-! # Operator norm on the space of continuous linear maps Define the operator norm on the space of continuous linear maps between normed spaces, and prove its basic properties. In particular, show that this space is itself a normed space. Since a lot of elementary properties don't require `∥x∥ = 0 → x = 0` we start setting up the theory for `semi_normed_space` and we specialize to `normed_space` at the end. -/ noncomputable theory open_locale classical nnreal topological_space variables {𝕜 : Type*} {E : Type*} {F : Type*} {G : Type*} section semi_normed variables [semi_normed_group E] [semi_normed_group F] [semi_normed_group G] open metric continuous_linear_map section normed_field /-! Most statements in this file require the field to be non-discrete, as this is necessary to deduce an inequality `∥f x∥ ≤ C ∥x∥` from the continuity of f. However, the other direction always holds. In this section, we just assume that `𝕜` is a normed field. In the remainder of the file, it will be non-discrete. -/ variables [normed_field 𝕜] [semi_normed_space 𝕜 E] [semi_normed_space 𝕜 F] (f : E →ₗ[𝕜] F) lemma linear_map.lipschitz_of_bound (C : ℝ) (h : ∀x, ∥f x∥ ≤ C * ∥x∥) : lipschitz_with (real.to_nnreal C) f := f.to_add_monoid_hom.lipschitz_of_bound C h lemma linear_map.lipschitz_of_bound_nnnorm (C : ℝ≥0) (h : ∀ x, ∥f x∥₊ ≤ C * ∥x∥₊) : lipschitz_with C f := f.to_add_monoid_hom.lipschitz_of_bound_nnnorm C h theorem linear_map.antilipschitz_of_bound {K : ℝ≥0} (h : ∀ x, ∥x∥ ≤ K * ∥f x∥) : antilipschitz_with K f := antilipschitz_with.of_le_mul_dist $ λ x y, by simpa only [dist_eq_norm, f.map_sub] using h (x - y) lemma linear_map.bound_of_antilipschitz {K : ℝ≥0} (h : antilipschitz_with K f) (x) : ∥x∥ ≤ K * ∥f x∥ := by simpa only [dist_zero_right, f.map_zero] using h.le_mul_dist x 0 lemma linear_map.uniform_continuous_of_bound (C : ℝ) (h : ∀x, ∥f x∥ ≤ C * ∥x∥) : uniform_continuous f := (f.lipschitz_of_bound C h).uniform_continuous lemma linear_map.continuous_of_bound (C : ℝ) (h : ∀x, ∥f x∥ ≤ C * ∥x∥) : continuous f := (f.lipschitz_of_bound C h).continuous /-- Construct a continuous linear map from a linear map and a bound on this linear map. The fact that the norm of the continuous linear map is then controlled is given in `linear_map.mk_continuous_norm_le`. -/ def linear_map.mk_continuous (C : ℝ) (h : ∀x, ∥f x∥ ≤ C * ∥x∥) : E →L[𝕜] F := ⟨f, linear_map.continuous_of_bound f C h⟩ /-- Reinterpret a linear map `𝕜 →ₗ[𝕜] E` as a continuous linear map. This construction is generalized to the case of any finite dimensional domain in `linear_map.to_continuous_linear_map`. -/ def linear_map.to_continuous_linear_map₁ (f : 𝕜 →ₗ[𝕜] E) : 𝕜 →L[𝕜] E := f.mk_continuous (∥f 1∥) $ λ x, le_of_eq $ by { conv_lhs { rw ← mul_one x }, rw [← smul_eq_mul, f.map_smul, norm_smul, mul_comm] } /-- Construct a continuous linear map from a linear map and the existence of a bound on this linear map. If you have an explicit bound, use `linear_map.mk_continuous` instead, as a norm estimate will follow automatically in `linear_map.mk_continuous_norm_le`. -/ def linear_map.mk_continuous_of_exists_bound (h : ∃C, ∀x, ∥f x∥ ≤ C * ∥x∥) : E →L[𝕜] F := ⟨f, let ⟨C, hC⟩ := h in linear_map.continuous_of_bound f C hC⟩ lemma continuous_of_linear_of_bound {f : E → F} (h_add : ∀ x y, f (x + y) = f x + f y) (h_smul : ∀ (c : 𝕜) x, f (c • x) = c • f x) {C : ℝ} (h_bound : ∀ x, ∥f x∥ ≤ C*∥x∥) : continuous f := let φ : E →ₗ[𝕜] F := { to_fun := f, map_add' := h_add, map_smul' := h_smul } in φ.continuous_of_bound C h_bound @[simp, norm_cast] lemma linear_map.mk_continuous_coe (C : ℝ) (h : ∀x, ∥f x∥ ≤ C * ∥x∥) : ((f.mk_continuous C h) : E →ₗ[𝕜] F) = f := rfl @[simp] lemma linear_map.mk_continuous_apply (C : ℝ) (h : ∀x, ∥f x∥ ≤ C * ∥x∥) (x : E) : f.mk_continuous C h x = f x := rfl @[simp, norm_cast] lemma linear_map.mk_continuous_of_exists_bound_coe (h : ∃C, ∀x, ∥f x∥ ≤ C * ∥x∥) : ((f.mk_continuous_of_exists_bound h) : E →ₗ[𝕜] F) = f := rfl @[simp] lemma linear_map.mk_continuous_of_exists_bound_apply (h : ∃C, ∀x, ∥f x∥ ≤ C * ∥x∥) (x : E) : f.mk_continuous_of_exists_bound h x = f x := rfl @[simp] lemma linear_map.to_continuous_linear_map₁_coe (f : 𝕜 →ₗ[𝕜] E) : (f.to_continuous_linear_map₁ : 𝕜 →ₗ[𝕜] E) = f := rfl @[simp] lemma linear_map.to_continuous_linear_map₁_apply (f : 𝕜 →ₗ[𝕜] E) (x) : f.to_continuous_linear_map₁ x = f x := rfl end normed_field variables [nondiscrete_normed_field 𝕜] [semi_normed_space 𝕜 E] [semi_normed_space 𝕜 F] [semi_normed_space 𝕜 G] (c : 𝕜) (f g : E →L[𝕜] F) (h : F →L[𝕜] G) (x y z : E) include 𝕜 lemma linear_map.bound_of_shell_semi_normed (f : E →ₗ[𝕜] F) {ε C : ℝ} (ε_pos : 0 < ε) {c : 𝕜} (hc : 1 < ∥c∥) (hf : ∀ x, ε / ∥c∥ ≤ ∥x∥ → ∥x∥ < ε → ∥f x∥ ≤ C * ∥x∥) {x : E} (hx : ∥x∥ ≠ 0) : ∥f x∥ ≤ C * ∥x∥ := begin rcases rescale_to_shell_semi_normed hc ε_pos hx with ⟨δ, hδ, δxle, leδx, δinv⟩, simpa only [f.map_smul, norm_smul, mul_left_comm C, mul_le_mul_left (norm_pos_iff.2 hδ)] using hf (δ • x) leδx δxle end /-- If `∥x∥ = 0` and `f` is continuous then `∥f x∥ = 0`. -/ lemma norm_image_of_norm_zero {f : E →ₗ[𝕜] F} (hf : continuous f) {x : E} (hx : ∥x∥ = 0) : ∥f x∥ = 0 := begin refine le_antisymm (le_of_forall_pos_le_add (λ ε hε, _)) (norm_nonneg (f x)), rcases normed_group.tendsto_nhds_nhds.1 (hf.tendsto 0) ε hε with ⟨δ, δ_pos, hδ⟩, replace hδ := hδ x, rw [sub_zero, hx] at hδ, replace hδ := le_of_lt (hδ δ_pos), rw [linear_map.map_zero, sub_zero] at hδ, rwa [zero_add] end /-- A continuous linear map between seminormed spaces is bounded when the field is nondiscrete. The continuity ensures boundedness on a ball of some radius `ε`. The nondiscreteness is then used to rescale any element into an element of norm in `[ε/C, ε]`, whose image has a controlled norm. The norm control for the original element follows by rescaling. -/ lemma linear_map.bound_of_continuous (f : E →ₗ[𝕜] F) (hf : continuous f) : ∃ C, 0 < C ∧ (∀ x : E, ∥f x∥ ≤ C * ∥x∥) := begin rcases normed_group.tendsto_nhds_nhds.1 (hf.tendsto 0) 1 zero_lt_one with ⟨ε, ε_pos, hε⟩, simp only [sub_zero, f.map_zero] at hε, rcases normed_field.exists_one_lt_norm 𝕜 with ⟨c, hc⟩, have : 0 < ∥c∥ / ε, from div_pos (zero_lt_one.trans hc) ε_pos, refine ⟨∥c∥ / ε, this, λ x, _⟩, by_cases hx : ∥x∥ = 0, { rw [hx, mul_zero], exact le_of_eq (norm_image_of_norm_zero hf hx) }, refine f.bound_of_shell_semi_normed ε_pos hc (λ x hle hlt, _) hx, refine (hε _ hlt).le.trans _, rwa [← div_le_iff' this, one_div_div] end namespace continuous_linear_map theorem bound : ∃ C, 0 < C ∧ (∀ x : E, ∥f x∥ ≤ C * ∥x∥) := f.to_linear_map.bound_of_continuous f.2 section open filter /-- A linear map which is a homothety is a continuous linear map. Since the field `𝕜` need not have `ℝ` as a subfield, this theorem is not directly deducible from the corresponding theorem about isometries plus a theorem about scalar multiplication. Likewise for the other theorems about homotheties in this file. -/ def of_homothety (f : E →ₗ[𝕜] F) (a : ℝ) (hf : ∀x, ∥f x∥ = a * ∥x∥) : E →L[𝕜] F := f.mk_continuous a (λ x, le_of_eq (hf x)) variable (𝕜) lemma to_span_singleton_homothety (x : E) (c : 𝕜) : ∥linear_map.to_span_singleton 𝕜 E x c∥ = ∥x∥ * ∥c∥ := by {rw mul_comm, exact norm_smul _ _} /-- Given an element `x` of a normed space `E` over a field `𝕜`, the natural continuous linear map from `E` to the span of `x`.-/ def to_span_singleton (x : E) : 𝕜 →L[𝕜] E := of_homothety (linear_map.to_span_singleton 𝕜 E x) ∥x∥ (to_span_singleton_homothety 𝕜 x) lemma to_span_singleton_apply (x : E) (r : 𝕜) : to_span_singleton 𝕜 x r = r • x := by simp [to_span_singleton, of_homothety, linear_map.to_span_singleton] lemma to_span_singleton_add (x y : E) : to_span_singleton 𝕜 (x + y) = to_span_singleton 𝕜 x + to_span_singleton 𝕜 y := by { ext1, simp [to_span_singleton_apply], } lemma to_span_singleton_smul' (𝕜') [nondiscrete_normed_field 𝕜'] [semi_normed_space 𝕜' E] [smul_comm_class 𝕜 𝕜' E] (c : 𝕜') (x : E) : to_span_singleton 𝕜 (c • x) = c • to_span_singleton 𝕜 x := by { ext1, rw [to_span_singleton_apply, smul_apply, to_span_singleton_apply, smul_comm], } lemma to_span_singleton_smul (c : 𝕜) (x : E) : to_span_singleton 𝕜 (c • x) = c • to_span_singleton 𝕜 x := to_span_singleton_smul' 𝕜 𝕜 c x end section op_norm open set real /-- The operator norm of a continuous linear map is the inf of all its bounds. -/ def op_norm := Inf {c | 0 ≤ c ∧ ∀ x, ∥f x∥ ≤ c * ∥x∥} instance has_op_norm : has_norm (E →L[𝕜] F) := ⟨op_norm⟩ lemma norm_def : ∥f∥ = Inf {c | 0 ≤ c ∧ ∀ x, ∥f x∥ ≤ c * ∥x∥} := rfl -- So that invocations of `le_cInf` make sense: we show that the set of -- bounds is nonempty and bounded below. lemma bounds_nonempty {f : E →L[𝕜] F} : ∃ c, c ∈ { c | 0 ≤ c ∧ ∀ x, ∥f x∥ ≤ c * ∥x∥ } := let ⟨M, hMp, hMb⟩ := f.bound in ⟨M, le_of_lt hMp, hMb⟩ lemma bounds_bdd_below {f : E →L[𝕜] F} : bdd_below { c | 0 ≤ c ∧ ∀ x, ∥f x∥ ≤ c * ∥x∥ } := ⟨0, λ _ ⟨hn, _⟩, hn⟩ lemma op_norm_nonneg : 0 ≤ ∥f∥ := le_cInf bounds_nonempty (λ _ ⟨hx, _⟩, hx) /-- The fundamental property of the operator norm: `∥f x∥ ≤ ∥f∥ * ∥x∥`. -/ theorem le_op_norm : ∥f x∥ ≤ ∥f∥ * ∥x∥ := begin obtain ⟨C, Cpos, hC⟩ := f.bound, replace hC := hC x, by_cases h : ∥x∥ = 0, { rwa [h, mul_zero] at ⊢ hC }, have hlt : 0 < ∥x∥ := lt_of_le_of_ne (norm_nonneg x) (ne.symm h), exact (div_le_iff hlt).mp (le_cInf bounds_nonempty (λ c ⟨_, hc⟩, (div_le_iff hlt).mpr $ by { apply hc })), end theorem le_op_norm_of_le {c : ℝ} {x} (h : ∥x∥ ≤ c) : ∥f x∥ ≤ ∥f∥ * c := le_trans (f.le_op_norm x) (mul_le_mul_of_nonneg_left h f.op_norm_nonneg) theorem le_of_op_norm_le {c : ℝ} (h : ∥f∥ ≤ c) (x : E) : ∥f x∥ ≤ c * ∥x∥ := (f.le_op_norm x).trans (mul_le_mul_of_nonneg_right h (norm_nonneg x)) lemma ratio_le_op_norm : ∥f x∥ / ∥x∥ ≤ ∥f∥ := div_le_of_nonneg_of_le_mul (norm_nonneg _) f.op_norm_nonneg (le_op_norm _ _) /-- The image of the unit ball under a continuous linear map is bounded. -/ lemma unit_le_op_norm : ∥x∥ ≤ 1 → ∥f x∥ ≤ ∥f∥ := mul_one ∥f∥ ▸ f.le_op_norm_of_le /-- If one controls the norm of every `A x`, then one controls the norm of `A`. -/ lemma op_norm_le_bound {M : ℝ} (hMp: 0 ≤ M) (hM : ∀ x, ∥f x∥ ≤ M * ∥x∥) : ∥f∥ ≤ M := cInf_le bounds_bdd_below ⟨hMp, hM⟩ theorem op_norm_le_of_lipschitz {f : E →L[𝕜] F} {K : ℝ≥0} (hf : lipschitz_with K f) : ∥f∥ ≤ K := f.op_norm_le_bound K.2 $ λ x, by simpa only [dist_zero_right, f.map_zero] using hf.dist_le_mul x 0 lemma op_norm_le_of_shell {f : E →L[𝕜] F} {ε C : ℝ} (ε_pos : 0 < ε) (hC : 0 ≤ C) {c : 𝕜} (hc : 1 < ∥c∥) (hf : ∀ x, ε / ∥c∥ ≤ ∥x∥ → ∥x∥ < ε → ∥f x∥ ≤ C * ∥x∥) : ∥f∥ ≤ C := begin refine f.op_norm_le_bound hC (λ x, _), by_cases hx : ∥x∥ = 0, { rw [hx, mul_zero], exact le_of_eq (norm_image_of_norm_zero f.2 hx) }, exact linear_map.bound_of_shell_semi_normed f ε_pos hc hf hx end lemma op_norm_le_of_ball {f : E →L[𝕜] F} {ε : ℝ} {C : ℝ} (ε_pos : 0 < ε) (hC : 0 ≤ C) (hf : ∀ x ∈ ball (0 : E) ε, ∥f x∥ ≤ C * ∥x∥) : ∥f∥ ≤ C := begin rcases normed_field.exists_one_lt_norm 𝕜 with ⟨c, hc⟩, refine op_norm_le_of_shell ε_pos hC hc (λ x _ hx, hf x _), rwa ball_0_eq end lemma op_norm_le_of_nhds_zero {f : E →L[𝕜] F} {C : ℝ} (hC : 0 ≤ C) (hf : ∀ᶠ x in 𝓝 (0 : E), ∥f x∥ ≤ C * ∥x∥) : ∥f∥ ≤ C := let ⟨ε, ε0, hε⟩ := metric.eventually_nhds_iff_ball.1 hf in op_norm_le_of_ball ε0 hC hε lemma op_norm_le_of_shell' {f : E →L[𝕜] F} {ε C : ℝ} (ε_pos : 0 < ε) (hC : 0 ≤ C) {c : 𝕜} (hc : ∥c∥ < 1) (hf : ∀ x, ε * ∥c∥ ≤ ∥x∥ → ∥x∥ < ε → ∥f x∥ ≤ C * ∥x∥) : ∥f∥ ≤ C := begin by_cases h0 : c = 0, { refine op_norm_le_of_ball ε_pos hC (λ x hx, hf x _ _), { simp [h0] }, { rwa ball_0_eq at hx } }, { rw [← inv_inv' c, normed_field.norm_inv, inv_lt_one_iff_of_pos (norm_pos_iff.2 $ inv_ne_zero h0)] at hc, refine op_norm_le_of_shell ε_pos hC hc _, rwa [normed_field.norm_inv, div_eq_mul_inv, inv_inv'] } end lemma op_norm_eq_of_bounds {φ : E →L[𝕜] F} {M : ℝ} (M_nonneg : 0 ≤ M) (h_above : ∀ x, ∥φ x∥ ≤ M*∥x∥) (h_below : ∀ N ≥ 0, (∀ x, ∥φ x∥ ≤ N*∥x∥) → M ≤ N) : ∥φ∥ = M := le_antisymm (φ.op_norm_le_bound M_nonneg h_above) ((le_cInf_iff continuous_linear_map.bounds_bdd_below ⟨M, M_nonneg, h_above⟩).mpr $ λ N ⟨N_nonneg, hN⟩, h_below N N_nonneg hN) /-- The operator norm satisfies the triangle inequality. -/ theorem op_norm_add_le : ∥f + g∥ ≤ ∥f∥ + ∥g∥ := (f + g).op_norm_le_bound (add_nonneg f.op_norm_nonneg g.op_norm_nonneg) $ λ x, (norm_add_le_of_le (f.le_op_norm x) (g.le_op_norm x)).trans_eq (add_mul _ _ _).symm /-- The norm of the `0` operator is `0`. -/ theorem op_norm_zero : ∥(0 : E →L[𝕜] F)∥ = 0 := le_antisymm (cInf_le bounds_bdd_below ⟨ge_of_eq rfl, λ _, le_of_eq (by { rw [zero_mul], exact norm_zero })⟩) (op_norm_nonneg _) /-- The norm of the identity is at most `1`. It is in fact `1`, except when the space is trivial where it is `0`. It means that one can not do better than an inequality in general. -/ lemma norm_id_le : ∥id 𝕜 E∥ ≤ 1 := op_norm_le_bound _ zero_le_one (λx, by simp) /-- If there is an element with norm different from `0`, then the norm of the identity equals `1`. (Since we are working with seminorms supposing that the space is non-trivial is not enough.) -/ lemma norm_id_of_nontrivial_seminorm (h : ∃ (x : E), ∥x∥ ≠ 0) : ∥id 𝕜 E∥ = 1 := le_antisymm norm_id_le $ let ⟨x, hx⟩ := h in have _ := (id 𝕜 E).ratio_le_op_norm x, by rwa [id_apply, div_self hx] at this lemma op_norm_smul_le {𝕜' : Type*} [normed_field 𝕜'] [semi_normed_space 𝕜' F] [smul_comm_class 𝕜 𝕜' F] (c : 𝕜') (f : E →L[𝕜] F) : ∥c • f∥ ≤ ∥c∥ * ∥f∥ := ((c • f).op_norm_le_bound (mul_nonneg (norm_nonneg _) (op_norm_nonneg _)) (λ _, begin erw [norm_smul, mul_assoc], exact mul_le_mul_of_nonneg_left (le_op_norm _ _) (norm_nonneg _) end)) lemma op_norm_neg : ∥-f∥ = ∥f∥ := by simp only [norm_def, neg_apply, norm_neg] /-- Continuous linear maps themselves form a seminormed space with respect to the operator norm. -/ instance to_semi_normed_group : semi_normed_group (E →L[𝕜] F) := semi_normed_group.of_core _ ⟨op_norm_zero, op_norm_add_le, op_norm_neg⟩ instance to_semi_normed_space {𝕜' : Type*} [normed_field 𝕜'] [semi_normed_space 𝕜' F] [smul_comm_class 𝕜 𝕜' F] : semi_normed_space 𝕜' (E →L[𝕜] F) := ⟨op_norm_smul_le⟩ /-- The operator norm is submultiplicative. -/ lemma op_norm_comp_le (f : E →L[𝕜] F) : ∥h.comp f∥ ≤ ∥h∥ * ∥f∥ := (cInf_le bounds_bdd_below ⟨mul_nonneg (op_norm_nonneg _) (op_norm_nonneg _), λ x, by { rw mul_assoc, exact h.le_op_norm_of_le (f.le_op_norm x) } ⟩) /-- Continuous linear maps form a seminormed ring with respect to the operator norm. -/ instance to_semi_normed_ring : semi_normed_ring (E →L[𝕜] E) := { norm_mul := op_norm_comp_le, .. continuous_linear_map.to_semi_normed_group } theorem le_op_nnnorm : ∥f x∥₊ ≤ ∥f∥₊ * ∥x∥₊ := f.le_op_norm x /-- continuous linear maps are Lipschitz continuous. -/ theorem lipschitz : lipschitz_with ∥f∥₊ f := (f : E →ₗ[𝕜] F).lipschitz_of_bound_nnnorm _ f.le_op_nnnorm theorem le_op_norm₂ (f : E →L[𝕜] F →L[𝕜] G) (x : E) (y : F) : ∥f x y∥ ≤ ∥f∥ * ∥x∥ * ∥y∥ := (f x).le_of_op_norm_le (f.le_op_norm x) y theorem op_norm_le_bound₂ (f : E →L[𝕜] F →L[𝕜] G) {C : ℝ} (h0 : 0 ≤ C) (hC : ∀ x y, ∥f x y∥ ≤ C * ∥x∥ * ∥y∥) : ∥f∥ ≤ C := f.op_norm_le_bound h0 $ λ x, (f x).op_norm_le_bound (mul_nonneg h0 (norm_nonneg _)) $ hC x @[simp] lemma op_norm_prod (f : E →L[𝕜] F) (g : E →L[𝕜] G) : ∥f.prod g∥ = ∥(f, g)∥ := le_antisymm (op_norm_le_bound _ (norm_nonneg _) $ λ x, by simpa only [prod_apply, prod.semi_norm_def, max_mul_of_nonneg, norm_nonneg] using max_le_max (le_op_norm f x) (le_op_norm g x)) $ max_le (op_norm_le_bound _ (norm_nonneg _) $ λ x, (le_max_left _ _).trans ((f.prod g).le_op_norm x)) (op_norm_le_bound _ (norm_nonneg _) $ λ x, (le_max_right _ _).trans ((f.prod g).le_op_norm x)) /-- `continuous_linear_map.prod` as a `linear_isometry_equiv`. -/ def prodₗᵢ (R : Type*) [ring R] [topological_space R] [module R F] [module R G] [has_continuous_smul R F] [has_continuous_smul R G] [smul_comm_class 𝕜 R F] [smul_comm_class 𝕜 R G] : (E →L[𝕜] F) × (E →L[𝕜] G) ≃ₗᵢ[R] (E →L[𝕜] F × G) := ⟨prodₗ R, λ ⟨f, g⟩, op_norm_prod f g⟩ /-- A continuous linear map is automatically uniformly continuous. -/ protected theorem uniform_continuous : uniform_continuous f := f.lipschitz.uniform_continuous @[simp, nontriviality] lemma op_norm_subsingleton [subsingleton E] : ∥f∥ = 0 := begin refine le_antisymm _ (norm_nonneg _), apply op_norm_le_bound _ rfl.ge, intros x, simp [subsingleton.elim x 0] end /-- A continuous linear map is an isometry if and only if it preserves the norm. -/ lemma isometry_iff_norm : isometry f ↔ ∀x, ∥f x∥ = ∥x∥ := f.to_linear_map.to_add_monoid_hom.isometry_iff_norm end op_norm section is_O open asymptotics theorem is_O_with_id (l : filter E) : is_O_with ∥f∥ f (λ x, x) l := is_O_with_of_le' _ f.le_op_norm theorem is_O_id (l : filter E) : is_O f (λ x, x) l := (f.is_O_with_id l).is_O theorem is_O_with_comp {α : Type*} (g : F →L[𝕜] G) (f : α → F) (l : filter α) : is_O_with ∥g∥ (λ x', g (f x')) f l := (g.is_O_with_id ⊤).comp_tendsto le_top theorem is_O_comp {α : Type*} (g : F →L[𝕜] G) (f : α → F) (l : filter α) : is_O (λ x', g (f x')) f l := (g.is_O_with_comp f l).is_O theorem is_O_with_sub (f : E →L[𝕜] F) (l : filter E) (x : E) : is_O_with ∥f∥ (λ x', f (x' - x)) (λ x', x' - x) l := f.is_O_with_comp _ l theorem is_O_sub (f : E →L[𝕜] F) (l : filter E) (x : E) : is_O (λ x', f (x' - x)) (λ x', x' - x) l := f.is_O_comp _ l end is_O end continuous_linear_map namespace linear_isometry lemma norm_to_continuous_linear_map_le (f : E →ₗᵢ[𝕜] F) : ∥f.to_continuous_linear_map∥ ≤ 1 := f.to_continuous_linear_map.op_norm_le_bound zero_le_one $ λ x, by simp end linear_isometry namespace linear_map /-- If a continuous linear map is constructed from a linear map via the constructor `mk_continuous`, then its norm is bounded by the bound given to the constructor if it is nonnegative. -/ lemma mk_continuous_norm_le (f : E →ₗ[𝕜] F) {C : ℝ} (hC : 0 ≤ C) (h : ∀x, ∥f x∥ ≤ C * ∥x∥) : ∥f.mk_continuous C h∥ ≤ C := continuous_linear_map.op_norm_le_bound _ hC h /-- If a continuous linear map is constructed from a linear map via the constructor `mk_continuous`, then its norm is bounded by the bound or zero if bound is negative. -/ lemma mk_continuous_norm_le' (f : E →ₗ[𝕜] F) {C : ℝ} (h : ∀x, ∥f x∥ ≤ C * ∥x∥) : ∥f.mk_continuous C h∥ ≤ max C 0 := continuous_linear_map.op_norm_le_bound _ (le_max_right _ _) $ λ x, (h x).trans $ mul_le_mul_of_nonneg_right (le_max_left _ _) (norm_nonneg x) /-- Create a bilinear map (represented as a map `E →L[𝕜] F →L[𝕜] G`) from the corresponding linear map and a bound on the norm of the image. The linear map can be constructed using `linear_map.mk₂`. -/ def mk_continuous₂ (f : E →ₗ[𝕜] F →ₗ[𝕜] G) (C : ℝ) (hC : ∀ x y, ∥f x y∥ ≤ C * ∥x∥ * ∥y∥) : E →L[𝕜] F →L[𝕜] G := linear_map.mk_continuous { to_fun := λ x, (f x).mk_continuous (C * ∥x∥) (hC x), map_add' := λ x y, by { ext z, simp }, map_smul' := λ c x, by { ext z, simp } } (max C 0) $ λ x, (mk_continuous_norm_le' _ _).trans_eq $ by rw [max_mul_of_nonneg _ _ (norm_nonneg x), zero_mul] @[simp] lemma mk_continuous₂_apply (f : E →ₗ[𝕜] F →ₗ[𝕜] G) {C : ℝ} (hC : ∀ x y, ∥f x y∥ ≤ C * ∥x∥ * ∥y∥) (x : E) (y : F) : f.mk_continuous₂ C hC x y = f x y := rfl lemma mk_continuous₂_norm_le' (f : E →ₗ[𝕜] F →ₗ[𝕜] G) {C : ℝ} (hC : ∀ x y, ∥f x y∥ ≤ C * ∥x∥ * ∥y∥) : ∥f.mk_continuous₂ C hC∥ ≤ max C 0 := mk_continuous_norm_le _ (le_max_iff.2 $ or.inr le_rfl) _ lemma mk_continuous₂_norm_le (f : E →ₗ[𝕜] F →ₗ[𝕜] G) {C : ℝ} (h0 : 0 ≤ C) (hC : ∀ x y, ∥f x y∥ ≤ C * ∥x∥ * ∥y∥) : ∥f.mk_continuous₂ C hC∥ ≤ C := (f.mk_continuous₂_norm_le' hC).trans_eq $ max_eq_left h0 end linear_map namespace continuous_linear_map /-- Flip the order of arguments of a continuous bilinear map. For a version bundled as `linear_isometry_equiv`, see `continuous_linear_map.flipL`. -/ def flip (f : E →L[𝕜] F →L[𝕜] G) : F →L[𝕜] E →L[𝕜] G := linear_map.mk_continuous₂ (linear_map.mk₂ 𝕜 (λ y x, f x y) (λ x y z, (f z).map_add x y) (λ c y x, (f x).map_smul c y) (λ z x y, by rw [f.map_add, add_apply]) (λ c y x, by rw [map_smul, smul_apply])) ∥f∥ (λ y x, (f.le_op_norm₂ x y).trans_eq $ by rw mul_right_comm) private lemma le_norm_flip (f : E →L[𝕜] F →L[𝕜] G) : ∥f∥ ≤ ∥flip f∥ := f.op_norm_le_bound₂ (norm_nonneg _) $ λ x y, by { rw mul_right_comm, exact (flip f).le_op_norm₂ y x } @[simp] lemma flip_apply (f : E →L[𝕜] F →L[𝕜] G) (x : E) (y : F) : f.flip y x = f x y := rfl @[simp] lemma flip_flip (f : E →L[𝕜] F →L[𝕜] G) : f.flip.flip = f := by { ext, refl } @[simp] lemma op_norm_flip (f : E →L[𝕜] F →L[𝕜] G) : ∥f.flip∥ = ∥f∥ := le_antisymm (by simpa only [flip_flip] using le_norm_flip f.flip) (le_norm_flip f) @[simp] lemma flip_add (f g : E →L[𝕜] F →L[𝕜] G) : (f + g).flip = f.flip + g.flip := rfl @[simp] lemma flip_smul (c : 𝕜) (f : E →L[𝕜] F →L[𝕜] G) : (c • f).flip = c • f.flip := rfl variables (𝕜 E F G) /-- Flip the order of arguments of a continuous bilinear map. This is a version bundled as a `linear_isometry_equiv`. For an unbundled version see `continuous_linear_map.flip`. -/ def flipₗᵢ : (E →L[𝕜] F →L[𝕜] G) ≃ₗᵢ[𝕜] (F →L[𝕜] E →L[𝕜] G) := { to_fun := flip, inv_fun := flip, map_add' := flip_add, map_smul' := flip_smul, left_inv := flip_flip, right_inv := flip_flip, norm_map' := op_norm_flip } variables {𝕜 E F G} @[simp] lemma flipₗᵢ_symm : (flipₗᵢ 𝕜 E F G).symm = flipₗᵢ 𝕜 F E G := rfl @[simp] lemma coe_flipₗᵢ : ⇑(flipₗᵢ 𝕜 E F G) = flip := rfl variables (𝕜 F) /-- The continuous linear map obtained by applying a continuous linear map at a given vector. This is the continuous version of `linear_map.applyₗ`. -/ def apply : E →L[𝕜] (E →L[𝕜] F) →L[𝕜] F := flip (id 𝕜 (E →L[𝕜] F)) variables {𝕜 F} @[simp] lemma apply_apply (v : E) (f : E →L[𝕜] F) : apply 𝕜 F v f = f v := rfl variables (𝕜 E F G) /-- Composition of continuous linear maps as a continuous bilinear map. -/ def compL : (F →L[𝕜] G) →L[𝕜] (E →L[𝕜] F) →L[𝕜] (E →L[𝕜] G) := linear_map.mk_continuous₂ (linear_map.mk₂ _ comp add_comp smul_comp comp_add (λ c f g, comp_smul _ _ _)) 1 $ λ f g, by simpa only [one_mul] using op_norm_comp_le f g variables {𝕜 E F G} @[simp] lemma compL_apply (f : F →L[𝕜] G) (g : E →L[𝕜] F) : compL 𝕜 E F G f g = f.comp g := rfl section multiplication_linear variables (𝕜) (𝕜' : Type*) [normed_ring 𝕜'] [normed_algebra 𝕜 𝕜'] /-- Left multiplication in a normed algebra as a linear isometry to the space of continuous linear maps. -/ def lmulₗᵢ : 𝕜' →ₗᵢ[𝕜] 𝕜' →L[𝕜] 𝕜' := { to_linear_map := (algebra.lmul 𝕜 𝕜').to_linear_map.mk_continuous₂ 1 $ λ x y, by simpa using norm_mul_le x y, norm_map' := λ x, le_antisymm (op_norm_le_bound _ (norm_nonneg x) (norm_mul_le x)) (by { convert ratio_le_op_norm _ (1 : 𝕜'), simp [normed_algebra.norm_one 𝕜 𝕜'] }) } /-- Left multiplication in a normed algebra as a continuous bilinear map. -/ def lmul : 𝕜' →L[𝕜] 𝕜' →L[𝕜] 𝕜' := (lmulₗᵢ 𝕜 𝕜').to_continuous_linear_map @[simp] lemma lmul_apply (x y : 𝕜') : lmul 𝕜 𝕜' x y = x * y := rfl @[simp] lemma coe_lmulₗᵢ : ⇑(lmulₗᵢ 𝕜 𝕜') = lmul 𝕜 𝕜' := rfl @[simp] lemma op_norm_lmul_apply (x : 𝕜') : ∥lmul 𝕜 𝕜' x∥ = ∥x∥ := (lmulₗᵢ 𝕜 𝕜').norm_map x /-- Right-multiplication in a normed algebra, considered as a continuous linear map. -/ def lmul_right : 𝕜' →L[𝕜] 𝕜' →L[𝕜] 𝕜' := (lmul 𝕜 𝕜').flip @[simp] lemma lmul_right_apply (x y : 𝕜') : lmul_right 𝕜 𝕜' x y = y * x := rfl @[simp] lemma op_norm_lmul_right_apply (x : 𝕜') : ∥lmul_right 𝕜 𝕜' x∥ = ∥x∥ := le_antisymm (op_norm_le_bound _ (norm_nonneg x) (λ y, (norm_mul_le y x).trans_eq (mul_comm _ _))) (by { convert ratio_le_op_norm _ (1 : 𝕜'), simp [normed_algebra.norm_one 𝕜 𝕜'] }) /-- Right-multiplication in a normed algebra, considered as a linear isometry to the space of continuous linear maps. -/ def lmul_rightₗᵢ : 𝕜' →ₗᵢ[𝕜] 𝕜' →L[𝕜] 𝕜' := { to_linear_map := lmul_right 𝕜 𝕜', norm_map' := op_norm_lmul_right_apply 𝕜 𝕜' } @[simp] lemma coe_lmul_rightₗᵢ : ⇑(lmul_rightₗᵢ 𝕜 𝕜') = lmul_right 𝕜 𝕜' := rfl /-- Simultaneous left- and right-multiplication in a normed algebra, considered as a continuous trilinear map. -/ def lmul_left_right : 𝕜' →L[𝕜] 𝕜' →L[𝕜] 𝕜' →L[𝕜] 𝕜' := ((compL 𝕜 𝕜' 𝕜' 𝕜').comp (lmul_right 𝕜 𝕜')).flip.comp (lmul 𝕜 𝕜') @[simp] lemma lmul_left_right_apply (x y z : 𝕜') : lmul_left_right 𝕜 𝕜' x y z = x * z * y := rfl lemma op_norm_lmul_left_right_apply_apply_le (x y : 𝕜') : ∥lmul_left_right 𝕜 𝕜' x y∥ ≤ ∥x∥ * ∥y∥ := (op_norm_comp_le _ _).trans_eq $ by simp [mul_comm] lemma op_norm_lmul_left_right_apply_le (x : 𝕜') : ∥lmul_left_right 𝕜 𝕜' x∥ ≤ ∥x∥ := op_norm_le_bound _ (norm_nonneg x) (op_norm_lmul_left_right_apply_apply_le 𝕜 𝕜' x) lemma op_norm_lmul_left_right_le : ∥lmul_left_right 𝕜 𝕜'∥ ≤ 1 := op_norm_le_bound _ zero_le_one (λ x, (one_mul ∥x∥).symm ▸ op_norm_lmul_left_right_apply_le 𝕜 𝕜' x) end multiplication_linear section smul_linear variables (𝕜) (𝕜' : Type*) [normed_field 𝕜'] [normed_algebra 𝕜 𝕜'] [semi_normed_space 𝕜' E] [is_scalar_tower 𝕜 𝕜' E] /-- Scalar multiplication as a continuous bilinear map. -/ def lsmul : 𝕜' →L[𝕜] E →L[𝕜] E := ((algebra.lsmul 𝕜 E).to_linear_map : 𝕜' →ₗ[𝕜] E →ₗ[𝕜] E).mk_continuous₂ 1 $ λ c x, by simpa only [one_mul] using (norm_smul c x).le @[simp] lemma lsmul_apply (c : 𝕜') (x : E) : lsmul 𝕜 𝕜' c x = c • x := rfl variables {𝕜'} lemma norm_to_span_singleton (x : E) : ∥to_span_singleton 𝕜 x∥ = ∥x∥ := begin refine op_norm_eq_of_bounds (norm_nonneg _) (λ x, _) (λ N hN_nonneg h, _), { rw [to_span_singleton_apply, norm_smul, mul_comm], }, { specialize h 1, rw [to_span_singleton_apply, norm_smul, mul_comm] at h, exact (mul_le_mul_right (by simp)).mp h, }, end end smul_linear section restrict_scalars variables {𝕜' : Type*} [nondiscrete_normed_field 𝕜'] [normed_algebra 𝕜' 𝕜] variables [semi_normed_space 𝕜' E] [is_scalar_tower 𝕜' 𝕜 E] variables [semi_normed_space 𝕜' F] [is_scalar_tower 𝕜' 𝕜 F] @[simp] lemma norm_restrict_scalars (f : E →L[𝕜] F) : ∥f.restrict_scalars 𝕜'∥ = ∥f∥ := le_antisymm (op_norm_le_bound _ (norm_nonneg _) $ λ x, f.le_op_norm x) (op_norm_le_bound _ (norm_nonneg _) $ λ x, f.le_op_norm x) variables (𝕜 E F 𝕜') (𝕜'' : Type*) [ring 𝕜''] [topological_space 𝕜''] [module 𝕜'' F] [has_continuous_smul 𝕜'' F] [smul_comm_class 𝕜 𝕜'' F] [smul_comm_class 𝕜' 𝕜'' F] /-- `continuous_linear_map.restrict_scalars` as a `linear_isometry`. -/ def restrict_scalars_isometry : (E →L[𝕜] F) →ₗᵢ[𝕜''] (E →L[𝕜'] F) := ⟨restrict_scalarsₗ 𝕜 E F 𝕜' 𝕜'', norm_restrict_scalars⟩ variables {𝕜 E F 𝕜' 𝕜''} @[simp] lemma coe_restrict_scalars_isometry : ⇑(restrict_scalars_isometry 𝕜 E F 𝕜' 𝕜'') = restrict_scalars 𝕜' := rfl @[simp] lemma restrict_scalars_isometry_to_linear_map : (restrict_scalars_isometry 𝕜 E F 𝕜' 𝕜'').to_linear_map = restrict_scalarsₗ 𝕜 E F 𝕜' 𝕜'' := rfl variables (𝕜 E F 𝕜' 𝕜'') /-- `continuous_linear_map.restrict_scalars` as a `continuous_linear_map`. -/ def restrict_scalarsL : (E →L[𝕜] F) →L[𝕜''] (E →L[𝕜'] F) := (restrict_scalars_isometry 𝕜 E F 𝕜' 𝕜'').to_continuous_linear_map variables {𝕜 E F 𝕜' 𝕜''} @[simp] lemma coe_restrict_scalarsL : (restrict_scalarsL 𝕜 E F 𝕜' 𝕜'' : (E →L[𝕜] F) →ₗ[𝕜''] (E →L[𝕜'] F)) = restrict_scalarsₗ 𝕜 E F 𝕜' 𝕜'' := rfl @[simp] lemma coe_restrict_scalarsL' : ⇑(restrict_scalarsL 𝕜 E F 𝕜' 𝕜'') = restrict_scalars 𝕜' := rfl end restrict_scalars end continuous_linear_map namespace submodule lemma norm_subtypeL_le (K : submodule 𝕜 E) : ∥K.subtypeL∥ ≤ 1 := K.subtypeₗᵢ.norm_to_continuous_linear_map_le end submodule section has_sum -- Results in this section hold for continuous additive monoid homomorphisms or equivalences but we -- don't have bundled continuous additive homomorphisms. variables {ι R M M₂ : Type*} [semiring R] [add_comm_monoid M] [module R M] [add_comm_monoid M₂] [module R M₂] [topological_space M] [topological_space M₂] omit 𝕜 /-- Applying a continuous linear map commutes with taking an (infinite) sum. -/ protected lemma continuous_linear_map.has_sum {f : ι → M} (φ : M →L[R] M₂) {x : M} (hf : has_sum f x) : has_sum (λ (b:ι), φ (f b)) (φ x) := by simpa only using hf.map φ.to_linear_map.to_add_monoid_hom φ.continuous alias continuous_linear_map.has_sum ← has_sum.mapL protected lemma continuous_linear_map.summable {f : ι → M} (φ : M →L[R] M₂) (hf : summable f) : summable (λ b:ι, φ (f b)) := (hf.has_sum.mapL φ).summable alias continuous_linear_map.summable ← summable.mapL protected lemma continuous_linear_map.map_tsum [t2_space M₂] {f : ι → M} (φ : M →L[R] M₂) (hf : summable f) : φ (∑' z, f z) = ∑' z, φ (f z) := (hf.has_sum.mapL φ).tsum_eq.symm /-- Applying a continuous linear map commutes with taking an (infinite) sum. -/ protected lemma continuous_linear_equiv.has_sum {f : ι → M} (e : M ≃L[R] M₂) {y : M₂} : has_sum (λ (b:ι), e (f b)) y ↔ has_sum f (e.symm y) := ⟨λ h, by simpa only [e.symm.coe_coe, e.symm_apply_apply] using h.mapL (e.symm : M₂ →L[R] M), λ h, by simpa only [e.coe_coe, e.apply_symm_apply] using (e : M →L[R] M₂).has_sum h⟩ protected lemma continuous_linear_equiv.summable {f : ι → M} (e : M ≃L[R] M₂) : summable (λ b:ι, e (f b)) ↔ summable f := ⟨λ hf, (e.has_sum.1 hf.has_sum).summable, (e : M →L[R] M₂).summable⟩ lemma continuous_linear_equiv.tsum_eq_iff [t2_space M] [t2_space M₂] {f : ι → M} (e : M ≃L[R] M₂) {y : M₂} : ∑' z, e (f z) = y ↔ ∑' z, f z = e.symm y := begin by_cases hf : summable f, { exact ⟨λ h, (e.has_sum.mp ((e.summable.mpr hf).has_sum_iff.mpr h)).tsum_eq, λ h, (e.has_sum.mpr (hf.has_sum_iff.mpr h)).tsum_eq⟩ }, { have hf' : ¬summable (λ z, e (f z)) := λ h, hf (e.summable.mp h), rw [tsum_eq_zero_of_not_summable hf, tsum_eq_zero_of_not_summable hf'], exact ⟨by { rintro rfl, simp }, λ H, by simpa using (congr_arg (λ z, e z) H)⟩ } end protected lemma continuous_linear_equiv.map_tsum [t2_space M] [t2_space M₂] {f : ι → M} (e : M ≃L[R] M₂) : e (∑' z, f z) = ∑' z, e (f z) := by { refine symm (e.tsum_eq_iff.mpr _), rw e.symm_apply_apply _ } end has_sum namespace continuous_linear_equiv variables (e : E ≃L[𝕜] F) protected lemma lipschitz : lipschitz_with (∥(e : E →L[𝕜] F)∥₊) e := (e : E →L[𝕜] F).lipschitz theorem is_O_comp {α : Type*} (f : α → E) (l : filter α) : asymptotics.is_O (λ x', e (f x')) f l := (e : E →L[𝕜] F).is_O_comp f l theorem is_O_sub (l : filter E) (x : E) : asymptotics.is_O (λ x', e (x' - x)) (λ x', x' - x) l := (e : E →L[𝕜] F).is_O_sub l x theorem is_O_comp_rev {α : Type*} (f : α → E) (l : filter α) : asymptotics.is_O f (λ x', e (f x')) l := (e.symm.is_O_comp _ l).congr_left $ λ _, e.symm_apply_apply _ theorem is_O_sub_rev (l : filter E) (x : E) : asymptotics.is_O (λ x', x' - x) (λ x', e (x' - x)) l := e.is_O_comp_rev _ _ lemma homothety_inverse (a : ℝ) (ha : 0 < a) (f : E ≃ₗ[𝕜] F) : (∀ (x : E), ∥f x∥ = a * ∥x∥) → (∀ (y : F), ∥f.symm y∥ = a⁻¹ * ∥y∥) := begin intros hf y, calc ∥(f.symm) y∥ = a⁻¹ * (a * ∥ (f.symm) y∥) : _ ... = a⁻¹ * ∥f ((f.symm) y)∥ : by rw hf ... = a⁻¹ * ∥y∥ : by simp, rw [← mul_assoc, inv_mul_cancel (ne_of_lt ha).symm, one_mul], end /-- A linear equivalence which is a homothety is a continuous linear equivalence. -/ def of_homothety (f : E ≃ₗ[𝕜] F) (a : ℝ) (ha : 0 < a) (hf : ∀x, ∥f x∥ = a * ∥x∥) : E ≃L[𝕜] F := { to_linear_equiv := f, continuous_to_fun := f.to_linear_map.continuous_of_bound a (λ x, le_of_eq (hf x)), continuous_inv_fun := f.symm.to_linear_map.continuous_of_bound a⁻¹ (λ x, le_of_eq (homothety_inverse a ha f hf x)) } variable (𝕜) lemma to_span_nonzero_singleton_homothety (x : E) (h : x ≠ 0) (c : 𝕜) : ∥linear_equiv.to_span_nonzero_singleton 𝕜 E x h c∥ = ∥x∥ * ∥c∥ := continuous_linear_map.to_span_singleton_homothety _ _ _ end continuous_linear_equiv /-- Construct a continuous linear equivalence from a linear equivalence together with bounds in both directions. -/ def linear_equiv.to_continuous_linear_equiv_of_bounds (e : E ≃ₗ[𝕜] F) (C_to C_inv : ℝ) (h_to : ∀ x, ∥e x∥ ≤ C_to * ∥x∥) (h_inv : ∀ x : F, ∥e.symm x∥ ≤ C_inv * ∥x∥) : E ≃L[𝕜] F := { to_linear_equiv := e, continuous_to_fun := e.to_linear_map.continuous_of_bound C_to h_to, continuous_inv_fun := e.symm.to_linear_map.continuous_of_bound C_inv h_inv } namespace continuous_linear_map variables (𝕜) (𝕜' : Type*) [normed_ring 𝕜'] [normed_algebra 𝕜 𝕜'] variables {𝕜} variables {E' F' : Type*} [semi_normed_group E'] [semi_normed_group F'] [semi_normed_space 𝕜 E'] [semi_normed_space 𝕜 F'] /-- Compose a bilinear map `E →L[𝕜] F →L[𝕜] G` with two linear maps `E' →L[𝕜] E` and `F' →L[𝕜] F`. -/ def bilinear_comp (f : E →L[𝕜] F →L[𝕜] G) (gE : E' →L[𝕜] E) (gF : F' →L[𝕜] F) : E' →L[𝕜] F' →L[𝕜] G := ((f.comp gE).flip.comp gF).flip @[simp] lemma bilinear_comp_apply (f : E →L[𝕜] F →L[𝕜] G) (gE : E' →L[𝕜] E) (gF : F' →L[𝕜] F) (x : E') (y : F') : f.bilinear_comp gE gF x y = f (gE x) (gF y) := rfl /-- Derivative of a continuous bilinear map `f : E →L[𝕜] F →L[𝕜] G` interpreted as a map `E × F → G` at point `p : E × F` evaluated at `q : E × F`, as a continuous bilinear map. -/ def deriv₂ (f : E →L[𝕜] F →L[𝕜] G) : (E × F) →L[𝕜] (E × F) →L[𝕜] G := f.bilinear_comp (fst _ _ _) (snd _ _ _) + f.flip.bilinear_comp (snd _ _ _) (fst _ _ _) @[simp] lemma coe_deriv₂ (f : E →L[𝕜] F →L[𝕜] G) (p : E × F) : ⇑(f.deriv₂ p) = λ q : E × F, f p.1 q.2 + f q.1 p.2 := rfl lemma map_add₂ (f : E →L[𝕜] F →L[𝕜] G) (x x' : E) (y y' : F) : f (x + x') (y + y') = f x y + f.deriv₂ (x, y) (x', y') + f x' y' := by simp only [map_add, add_apply, coe_deriv₂, add_assoc] end continuous_linear_map end semi_normed section normed variables [normed_group E] [normed_group F] [normed_group G] open metric continuous_linear_map section normed_field variables [normed_field 𝕜] [normed_space 𝕜 E] [normed_space 𝕜 F] (f : E →ₗ[𝕜] F) lemma linear_map.continuous_iff_is_closed_ker {f : E →ₗ[𝕜] 𝕜} : continuous f ↔ is_closed (f.ker : set E) := begin -- the continuity of f obviously implies that its kernel is closed refine ⟨λh, (t1_space.t1 (0 : 𝕜)).preimage h, λh, _⟩, -- for the other direction, we assume that the kernel is closed by_cases hf : ∀x, x ∈ f.ker, { -- if `f = 0`, its continuity is obvious have : (f : E → 𝕜) = (λx, 0), by { ext x, simpa using hf x }, rw this, exact continuous_const }, { /- if `f` is not zero, we use an element `x₀ ∉ ker f` such that `∥x₀∥ ≤ 2 ∥x₀ - y∥` for all `y ∈ ker f`, given by Riesz's lemma, and prove that `2 ∥f x₀∥ / ∥x₀∥` gives a bound on the operator norm of `f`. For this, start from an arbitrary `x` and note that `y = x₀ - (f x₀ / f x) x` belongs to the kernel of `f`. Applying the above inequality to `x₀` and `y` readily gives the conclusion. -/ push_neg at hf, let r : ℝ := (2 : ℝ)⁻¹, have : 0 ≤ r, by norm_num [r], have : r < 1, by norm_num [r], obtain ⟨x₀, x₀ker, h₀⟩ : ∃ (x₀ : E), x₀ ∉ f.ker ∧ ∀ y ∈ linear_map.ker f, r * ∥x₀∥ ≤ ∥x₀ - y∥, from riesz_lemma h hf this, have : x₀ ≠ 0, { assume h, have : x₀ ∈ f.ker, by { rw h, exact (linear_map.ker f).zero_mem }, exact x₀ker this }, have rx₀_ne_zero : r * ∥x₀∥ ≠ 0, by { simp [norm_eq_zero, this], }, have : ∀x, ∥f x∥ ≤ (((r * ∥x₀∥)⁻¹) * ∥f x₀∥) * ∥x∥, { assume x, by_cases hx : f x = 0, { rw [hx, norm_zero], apply_rules [mul_nonneg, norm_nonneg, inv_nonneg.2] }, { let y := x₀ - (f x₀ * (f x)⁻¹ ) • x, have fy_zero : f y = 0, by calc f y = f x₀ - (f x₀ * (f x)⁻¹ ) * f x : by simp [y] ... = 0 : by { rw [mul_assoc, inv_mul_cancel hx, mul_one, sub_eq_zero_of_eq], refl }, have A : r * ∥x₀∥ ≤ ∥f x₀∥ * ∥f x∥⁻¹ * ∥x∥, from calc r * ∥x₀∥ ≤ ∥x₀ - y∥ : h₀ _ (linear_map.mem_ker.2 fy_zero) ... = ∥(f x₀ * (f x)⁻¹ ) • x∥ : by { dsimp [y], congr, abel } ... = ∥f x₀∥ * ∥f x∥⁻¹ * ∥x∥ : by rw [norm_smul, normed_field.norm_mul, normed_field.norm_inv], calc ∥f x∥ = (r * ∥x₀∥)⁻¹ * (r * ∥x₀∥) * ∥f x∥ : by rwa [inv_mul_cancel, one_mul] ... ≤ (r * ∥x₀∥)⁻¹ * (∥f x₀∥ * ∥f x∥⁻¹ * ∥x∥) * ∥f x∥ : begin apply mul_le_mul_of_nonneg_right (mul_le_mul_of_nonneg_left A _) (norm_nonneg _), exact inv_nonneg.2 (mul_nonneg (by norm_num) (norm_nonneg _)) end ... = (∥f x∥ ⁻¹ * ∥f x∥) * (((r * ∥x₀∥)⁻¹) * ∥f x₀∥) * ∥x∥ : by ring ... = (((r * ∥x₀∥)⁻¹) * ∥f x₀∥) * ∥x∥ : by { rw [inv_mul_cancel, one_mul], simp [norm_eq_zero, hx] } } }, exact linear_map.continuous_of_bound f _ this } end end normed_field variables [nondiscrete_normed_field 𝕜] [normed_space 𝕜 E] [normed_space 𝕜 F] [normed_space 𝕜 G] (c : 𝕜) (f g : E →L[𝕜] F) (h : F →L[𝕜] G) (x y z : E) include 𝕜 lemma linear_map.bound_of_shell (f : E →ₗ[𝕜] F) {ε C : ℝ} (ε_pos : 0 < ε) {c : 𝕜} (hc : 1 < ∥c∥) (hf : ∀ x, ε / ∥c∥ ≤ ∥x∥ → ∥x∥ < ε → ∥f x∥ ≤ C * ∥x∥) (x : E) : ∥f x∥ ≤ C * ∥x∥ := begin by_cases hx : x = 0, { simp [hx] }, exact linear_map.bound_of_shell_semi_normed f ε_pos hc hf (ne_of_lt (norm_pos_iff.2 hx)).symm end namespace continuous_linear_map section op_norm open set real /-- An operator is zero iff its norm vanishes. -/ theorem op_norm_zero_iff : ∥f∥ = 0 ↔ f = 0 := iff.intro (λ hn, continuous_linear_map.ext (λ x, norm_le_zero_iff.1 (calc _ ≤ ∥f∥ * ∥x∥ : le_op_norm _ _ ... = _ : by rw [hn, zero_mul]))) (λ hf, le_antisymm (cInf_le bounds_bdd_below ⟨le_rfl, λ _, le_of_eq (by { rw [zero_mul, hf], exact norm_zero })⟩) (op_norm_nonneg _)) /-- If a normed space is non-trivial, then the norm of the identity equals `1`. -/ @[simp] lemma norm_id [nontrivial E] : ∥id 𝕜 E∥ = 1 := begin refine norm_id_of_nontrivial_seminorm _, obtain ⟨x, hx⟩ := exists_ne (0 : E), exact ⟨x, ne_of_gt (norm_pos_iff.2 hx)⟩, end instance norm_one_class [nontrivial E] : norm_one_class (E →L[𝕜] E) := ⟨norm_id⟩ /-- Continuous linear maps themselves form a normed space with respect to the operator norm. -/ instance to_normed_group : normed_group (E →L[𝕜] F) := normed_group.of_core _ ⟨op_norm_zero_iff, op_norm_add_le, op_norm_neg⟩ instance to_normed_space {𝕜' : Type*} [normed_field 𝕜'] [normed_space 𝕜' F] [smul_comm_class 𝕜 𝕜' F] : normed_space 𝕜' (E →L[𝕜] F) := ⟨op_norm_smul_le⟩ /-- Continuous linear maps form a normed ring with respect to the operator norm. -/ instance to_normed_ring : normed_ring (E →L[𝕜] E) := { norm_mul := op_norm_comp_le, .. continuous_linear_map.to_normed_group } /-- For a nonzero normed space `E`, continuous linear endomorphisms form a normed algebra with respect to the operator norm. -/ instance to_normed_algebra [nontrivial E] : normed_algebra 𝕜 (E →L[𝕜] E) := { norm_algebra_map_eq := λ c, show ∥c • id 𝕜 E∥ = ∥c∥, by {rw [norm_smul, norm_id], simp}, .. continuous_linear_map.algebra } variable {f} lemma homothety_norm [nontrivial E] (f : E →L[𝕜] F) {a : ℝ} (hf : ∀x, ∥f x∥ = a * ∥x∥) : ∥f∥ = a := begin obtain ⟨x, hx⟩ : ∃ (x : E), x ≠ 0 := exists_ne 0, rw ← norm_pos_iff at hx, have ha : 0 ≤ a, by simpa only [hf, hx, zero_le_mul_right] using norm_nonneg (f x), apply le_antisymm (f.op_norm_le_bound ha (λ y, le_of_eq (hf y))), simpa only [hf, hx, mul_le_mul_right] using f.le_op_norm x, end lemma to_span_singleton_norm (x : E) : ∥to_span_singleton 𝕜 x∥ = ∥x∥ := homothety_norm _ (to_span_singleton_homothety 𝕜 x) variable (f) theorem uniform_embedding_of_bound {K : ℝ≥0} (hf : ∀ x, ∥x∥ ≤ K * ∥f x∥) : uniform_embedding f := (f.to_linear_map.antilipschitz_of_bound hf).uniform_embedding f.uniform_continuous /-- If a continuous linear map is a uniform embedding, then it is expands the distances by a positive factor.-/ theorem antilipschitz_of_uniform_embedding (hf : uniform_embedding f) : ∃ K, antilipschitz_with K f := begin obtain ⟨ε, εpos, hε⟩ : ∃ (ε : ℝ) (H : ε > 0), ∀ {x y : E}, dist (f x) (f y) < ε → dist x y < 1, from (uniform_embedding_iff.1 hf).2.2 1 zero_lt_one, let δ := ε/2, have δ_pos : δ > 0 := half_pos εpos, have H : ∀{x}, ∥f x∥ ≤ δ → ∥x∥ ≤ 1, { assume x hx, have : dist x 0 ≤ 1, { refine (hε _).le, rw [f.map_zero, dist_zero_right], exact hx.trans_lt (half_lt_self εpos) }, simpa using this }, rcases normed_field.exists_one_lt_norm 𝕜 with ⟨c, hc⟩, refine ⟨⟨δ⁻¹, _⟩ * nnnorm c, f.to_linear_map.antilipschitz_of_bound $ λx, _⟩, exact inv_nonneg.2 (le_of_lt δ_pos), by_cases hx : f x = 0, { have : f x = f 0, by { simp [hx] }, have : x = 0 := (uniform_embedding_iff.1 hf).1 this, simp [this] }, { rcases rescale_to_shell hc δ_pos hx with ⟨d, hd, dxlt, ledx, dinv⟩, rw [← f.map_smul d] at dxlt, have : ∥d • x∥ ≤ 1 := H dxlt.le, calc ∥x∥ = ∥d∥⁻¹ * ∥d • x∥ : by rwa [← normed_field.norm_inv, ← norm_smul, ← mul_smul, inv_mul_cancel, one_smul] ... ≤ ∥d∥⁻¹ * 1 : mul_le_mul_of_nonneg_left this (inv_nonneg.2 (norm_nonneg _)) ... ≤ δ⁻¹ * ∥c∥ * ∥f x∥ : by rwa [mul_one] } end section completeness open_locale topological_space open filter /-- If the target space is complete, the space of continuous linear maps with its norm is also complete. This works also if the source space is seminormed. -/ instance {E : Type*} [semi_normed_group E] [semi_normed_space 𝕜 E] [complete_space F] : complete_space (E →L[𝕜] F) := begin -- We show that every Cauchy sequence converges. refine metric.complete_of_cauchy_seq_tendsto (λ f hf, _), -- We now expand out the definition of a Cauchy sequence, rcases cauchy_seq_iff_le_tendsto_0.1 hf with ⟨b, b0, b_bound, b_lim⟩, clear hf, -- and establish that the evaluation at any point `v : E` is Cauchy. have cau : ∀ v, cauchy_seq (λ n, f n v), { assume v, apply cauchy_seq_iff_le_tendsto_0.2 ⟨λ n, b n * ∥v∥, λ n, _, _, _⟩, { exact mul_nonneg (b0 n) (norm_nonneg _) }, { assume n m N hn hm, rw dist_eq_norm, apply le_trans ((f n - f m).le_op_norm v) _, exact mul_le_mul_of_nonneg_right (b_bound n m N hn hm) (norm_nonneg v) }, { simpa using b_lim.mul tendsto_const_nhds } }, -- We assemble the limits points of those Cauchy sequences -- (which exist as `F` is complete) -- into a function which we call `G`. choose G hG using λv, cauchy_seq_tendsto_of_complete (cau v), -- Next, we show that this `G` is linear, let Glin : E →ₗ[𝕜] F := { to_fun := G, map_add' := λ v w, begin have A := hG (v + w), have B := (hG v).add (hG w), simp only [map_add] at A B, exact tendsto_nhds_unique A B, end, map_smul' := λ c v, begin have A := hG (c • v), have B := filter.tendsto.smul (@tendsto_const_nhds _ ℕ _ c _) (hG v), simp only [map_smul] at A B, exact tendsto_nhds_unique A B end }, -- and that `G` has norm at most `(b 0 + ∥f 0∥)`. have Gnorm : ∀ v, ∥G v∥ ≤ (b 0 + ∥f 0∥) * ∥v∥, { assume v, have A : ∀ n, ∥f n v∥ ≤ (b 0 + ∥f 0∥) * ∥v∥, { assume n, apply le_trans ((f n).le_op_norm _) _, apply mul_le_mul_of_nonneg_right _ (norm_nonneg v), calc ∥f n∥ = ∥(f n - f 0) + f 0∥ : by { congr' 1, abel } ... ≤ ∥f n - f 0∥ + ∥f 0∥ : norm_add_le _ _ ... ≤ b 0 + ∥f 0∥ : begin apply add_le_add_right, simpa [dist_eq_norm] using b_bound n 0 0 (zero_le _) (zero_le _) end }, exact le_of_tendsto (hG v).norm (eventually_of_forall A) }, -- Thus `G` is continuous, and we propose that as the limit point of our original Cauchy sequence. let Gcont := Glin.mk_continuous _ Gnorm, use Gcont, -- Our last task is to establish convergence to `G` in norm. have : ∀ n, ∥f n - Gcont∥ ≤ b n, { assume n, apply op_norm_le_bound _ (b0 n) (λ v, _), have A : ∀ᶠ m in at_top, ∥(f n - f m) v∥ ≤ b n * ∥v∥, { refine eventually_at_top.2 ⟨n, λ m hm, _⟩, apply le_trans ((f n - f m).le_op_norm _) _, exact mul_le_mul_of_nonneg_right (b_bound n m n (le_refl _) hm) (norm_nonneg v) }, have B : tendsto (λ m, ∥(f n - f m) v∥) at_top (𝓝 (∥(f n - Gcont) v∥)) := tendsto.norm (tendsto_const_nhds.sub (hG v)), exact le_of_tendsto B A }, erw tendsto_iff_norm_tendsto_zero, exact squeeze_zero (λ n, norm_nonneg _) this b_lim, end end completeness section uniformly_extend variables [complete_space F] (e : E →L[𝕜] G) (h_dense : dense_range e) section variables (h_e : uniform_inducing e) /-- Extension of a continuous linear map `f : E →L[𝕜] F`, with `E` a normed space and `F` a complete normed space, along a uniform and dense embedding `e : E →L[𝕜] G`. -/ def extend : G →L[𝕜] F := /- extension of `f` is continuous -/ have cont : _ := (uniform_continuous_uniformly_extend h_e h_dense f.uniform_continuous).continuous, /- extension of `f` agrees with `f` on the domain of the embedding `e` -/ have eq : _ := uniformly_extend_of_ind h_e h_dense f.uniform_continuous, { to_fun := (h_e.dense_inducing h_dense).extend f, map_add' := begin refine h_dense.induction_on₂ _ _, { exact is_closed_eq (cont.comp continuous_add) ((cont.comp continuous_fst).add (cont.comp continuous_snd)) }, { assume x y, simp only [eq, ← e.map_add], exact f.map_add _ _ }, end, map_smul' := λk, begin refine (λ b, h_dense.induction_on b _ _), { exact is_closed_eq (cont.comp (continuous_const.smul continuous_id)) ((continuous_const.smul continuous_id).comp cont) }, { assume x, rw ← map_smul, simp only [eq], exact map_smul _ _ _ }, end, cont := cont } lemma extend_unique (g : G →L[𝕜] F) (H : g.comp e = f) : extend f e h_dense h_e = g := continuous_linear_map.coe_fn_injective $ uniformly_extend_unique h_e h_dense (continuous_linear_map.ext_iff.1 H) g.continuous @[simp] lemma extend_zero : extend (0 : E →L[𝕜] F) e h_dense h_e = 0 := extend_unique _ _ _ _ _ (zero_comp _) end section variables {N : ℝ≥0} (h_e : ∀x, ∥x∥ ≤ N * ∥e x∥) local notation `ψ` := f.extend e h_dense (uniform_embedding_of_bound _ h_e).to_uniform_inducing /-- If a dense embedding `e : E →L[𝕜] G` expands the norm by a constant factor `N⁻¹`, then the norm of the extension of `f` along `e` is bounded by `N * ∥f∥`. -/ lemma op_norm_extend_le : ∥ψ∥ ≤ N * ∥f∥ := begin have uni : uniform_inducing e := (uniform_embedding_of_bound _ h_e).to_uniform_inducing, have eq : ∀x, ψ (e x) = f x := uniformly_extend_of_ind uni h_dense f.uniform_continuous, by_cases N0 : 0 ≤ N, { refine op_norm_le_bound ψ _ (is_closed_property h_dense (is_closed_le _ _) _), { exact mul_nonneg N0 (norm_nonneg _) }, { exact continuous_norm.comp (cont ψ) }, { exact continuous_const.mul continuous_norm }, { assume x, rw eq, calc ∥f x∥ ≤ ∥f∥ * ∥x∥ : le_op_norm _ _ ... ≤ ∥f∥ * (N * ∥e x∥) : mul_le_mul_of_nonneg_left (h_e x) (norm_nonneg _) ... ≤ N * ∥f∥ * ∥e x∥ : by rw [mul_comm ↑N ∥f∥, mul_assoc] } }, { have he : ∀ x : E, x = 0, { assume x, have N0 : N ≤ 0 := le_of_lt (lt_of_not_ge N0), rw ← norm_le_zero_iff, exact le_trans (h_e x) (mul_nonpos_of_nonpos_of_nonneg N0 (norm_nonneg _)) }, have hf : f = 0, { ext, simp only [he x, zero_apply, map_zero] }, have hψ : ψ = 0, { rw hf, apply extend_zero }, rw [hψ, hf, norm_zero, norm_zero, mul_zero] } end end end uniformly_extend end op_norm end continuous_linear_map namespace linear_isometry @[simp] lemma norm_to_continuous_linear_map [nontrivial E] (f : E →ₗᵢ[𝕜] F) : ∥f.to_continuous_linear_map∥ = 1 := f.to_continuous_linear_map.homothety_norm $ by simp end linear_isometry namespace continuous_linear_map /-- Precomposition with a linear isometry preserves the operator norm. -/ lemma op_norm_comp_linear_isometry_equiv {G : Type*} [semi_normed_group G] [semi_normed_space 𝕜 G] (f : F →L[𝕜] G) (g : E ≃ₗᵢ[𝕜] F) : ∥f.comp g.to_linear_isometry.to_continuous_linear_map∥ = ∥f∥ := begin casesI subsingleton_or_nontrivial E, { haveI := g.symm.to_linear_equiv.to_equiv.subsingleton, simp }, refine le_antisymm _ _, { convert f.op_norm_comp_le g.to_linear_isometry.to_continuous_linear_map, simp [g.to_linear_isometry.norm_to_continuous_linear_map] }, { convert (f.comp g.to_linear_isometry.to_continuous_linear_map).op_norm_comp_le g.symm.to_linear_isometry.to_continuous_linear_map, { ext, simp }, haveI := g.symm.to_linear_equiv.to_equiv.nontrivial, simp [g.symm.to_linear_isometry.norm_to_continuous_linear_map] }, end /-- The norm of the tensor product of a scalar linear map and of an element of a normed space is the product of the norms. -/ @[simp] lemma norm_smul_right_apply (c : E →L[𝕜] 𝕜) (f : F) : ∥smul_right c f∥ = ∥c∥ * ∥f∥ := begin refine le_antisymm _ _, { apply op_norm_le_bound _ (mul_nonneg (norm_nonneg _) (norm_nonneg _)) (λx, _), calc ∥(c x) • f∥ = ∥c x∥ * ∥f∥ : norm_smul _ _ ... ≤ (∥c∥ * ∥x∥) * ∥f∥ : mul_le_mul_of_nonneg_right (le_op_norm _ _) (norm_nonneg _) ... = ∥c∥ * ∥f∥ * ∥x∥ : by ring }, { by_cases h : f = 0, { simp [h] }, { have : 0 < ∥f∥ := norm_pos_iff.2 h, rw ← le_div_iff this, apply op_norm_le_bound _ (div_nonneg (norm_nonneg _) (norm_nonneg f)) (λx, _), rw [div_mul_eq_mul_div, le_div_iff this], calc ∥c x∥ * ∥f∥ = ∥c x • f∥ : (norm_smul _ _).symm ... = ∥smul_right c f x∥ : rfl ... ≤ ∥smul_right c f∥ * ∥x∥ : le_op_norm _ _ } }, end /-- The non-negative norm of the tensor product of a scalar linear map and of an element of a normed space is the product of the non-negative norms. -/ @[simp] lemma nnnorm_smul_right_apply (c : E →L[𝕜] 𝕜) (f : F) : ∥smul_right c f∥₊ = ∥c∥₊ * ∥f∥₊ := nnreal.eq $ c.norm_smul_right_apply f variables (𝕜 E F) /-- `continuous_linear_map.smul_right` as a continuous trilinear map: `smul_rightL (c : E →L[𝕜] 𝕜) (f : F) (x : E) = c x • f`. -/ def smul_rightL : (E →L[𝕜] 𝕜) →L[𝕜] F →L[𝕜] E →L[𝕜] F := linear_map.mk_continuous₂ { to_fun := smul_rightₗ, map_add' := λ c₁ c₂, by { ext x, simp [add_smul] }, map_smul' := λ m c, by { ext x, simp [smul_smul] } } 1 $ λ c x, by simp variables {𝕜 E F} @[simp] lemma norm_smul_rightL_apply (c : E →L[𝕜] 𝕜) (f : F) : ∥smul_rightL 𝕜 E F c f∥ = ∥c∥ * ∥f∥ := norm_smul_right_apply c f @[simp] lemma norm_smul_rightL (c : E →L[𝕜] 𝕜) [nontrivial F] : ∥smul_rightL 𝕜 E F c∥ = ∥c∥ := continuous_linear_map.homothety_norm _ c.norm_smul_right_apply variables (𝕜) (𝕜' : Type*) [normed_ring 𝕜'] [normed_algebra 𝕜 𝕜'] @[simp] lemma op_norm_lmul : ∥lmul 𝕜 𝕜'∥ = 1 := by haveI := normed_algebra.nontrivial 𝕜 𝕜'; exact (lmulₗᵢ 𝕜 𝕜').norm_to_continuous_linear_map @[simp] lemma op_norm_lmul_right : ∥lmul_right 𝕜 𝕜'∥ = 1 := (op_norm_flip (@lmul 𝕜 _ 𝕜' _ _)).trans (op_norm_lmul _ _) end continuous_linear_map namespace submodule lemma norm_subtypeL (K : submodule 𝕜 E) [nontrivial K] : ∥K.subtypeL∥ = 1 := K.subtypeₗᵢ.norm_to_continuous_linear_map end submodule namespace continuous_linear_equiv variables (e : E ≃L[𝕜] F) protected lemma antilipschitz : antilipschitz_with (nnnorm (e.symm : F →L[𝕜] E)) e := e.symm.lipschitz.to_right_inverse e.left_inv /-- A continuous linear equiv is a uniform embedding. -/ lemma uniform_embedding : uniform_embedding e := e.antilipschitz.uniform_embedding e.lipschitz.uniform_continuous lemma one_le_norm_mul_norm_symm [nontrivial E] : 1 ≤ ∥(e : E →L[𝕜] F)∥ * ∥(e.symm : F →L[𝕜] E)∥ := begin rw [mul_comm], convert (e.symm : F →L[𝕜] E).op_norm_comp_le (e : E →L[𝕜] F), rw [e.coe_symm_comp_coe, continuous_linear_map.norm_id] end lemma norm_pos [nontrivial E] : 0 < ∥(e : E →L[𝕜] F)∥ := pos_of_mul_pos_right (lt_of_lt_of_le zero_lt_one e.one_le_norm_mul_norm_symm) (norm_nonneg _) lemma norm_symm_pos [nontrivial E] : 0 < ∥(e.symm : F →L[𝕜] E)∥ := pos_of_mul_pos_left (lt_of_lt_of_le zero_lt_one e.one_le_norm_mul_norm_symm) (norm_nonneg _) lemma nnnorm_symm_pos [nontrivial E] : 0 < nnnorm (e.symm : F →L[𝕜] E) := e.norm_symm_pos lemma subsingleton_or_norm_symm_pos : subsingleton E ∨ 0 < ∥(e.symm : F →L[𝕜] E)∥ := begin rcases subsingleton_or_nontrivial E with _i|_i; resetI, { left, apply_instance }, { right, exact e.norm_symm_pos } end lemma subsingleton_or_nnnorm_symm_pos : subsingleton E ∨ 0 < (nnnorm $ (e.symm : F →L[𝕜] E)) := subsingleton_or_norm_symm_pos e variable (𝕜) /-- Given a nonzero element `x` of a normed space `E₁` over a field `𝕜`, the natural continuous linear equivalence from `E₁` to the span of `x`.-/ def to_span_nonzero_singleton (x : E) (h : x ≠ 0) : 𝕜 ≃L[𝕜] (𝕜 ∙ x) := of_homothety (linear_equiv.to_span_nonzero_singleton 𝕜 E x h) ∥x∥ (norm_pos_iff.mpr h) (to_span_nonzero_singleton_homothety 𝕜 x h) /-- Given a nonzero element `x` of a normed space `E₁` over a field `𝕜`, the natural continuous linear map from the span of `x` to `𝕜`.-/ def coord (x : E) (h : x ≠ 0) : (𝕜 ∙ x) →L[𝕜] 𝕜 := (to_span_nonzero_singleton 𝕜 x h).symm @[simp] lemma coe_to_span_nonzero_singleton_symm {x : E} (h : x ≠ 0) : ⇑(to_span_nonzero_singleton 𝕜 x h).symm = coord 𝕜 x h := rfl @[simp] lemma coord_to_span_nonzero_singleton {x : E} (h : x ≠ 0) (c : 𝕜) : coord 𝕜 x h (to_span_nonzero_singleton 𝕜 x h c) = c := (to_span_nonzero_singleton 𝕜 x h).symm_apply_apply c @[simp] lemma to_span_nonzero_singleton_coord {x : E} (h : x ≠ 0) (y : 𝕜 ∙ x) : to_span_nonzero_singleton 𝕜 x h (coord 𝕜 x h y) = y := (to_span_nonzero_singleton 𝕜 x h).apply_symm_apply y @[simp] lemma coord_norm (x : E) (h : x ≠ 0) : ∥coord 𝕜 x h∥ = ∥x∥⁻¹ := begin have hx : 0 < ∥x∥ := (norm_pos_iff.mpr h), haveI : nontrivial (𝕜 ∙ x) := submodule.nontrivial_span_singleton h, exact continuous_linear_map.homothety_norm _ (λ y, homothety_inverse _ hx _ (to_span_nonzero_singleton_homothety 𝕜 x h) _) end @[simp] lemma coord_self (x : E) (h : x ≠ 0) : (coord 𝕜 x h) (⟨x, submodule.mem_span_singleton_self x⟩ : 𝕜 ∙ x) = 1 := linear_equiv.coord_self 𝕜 E x h end continuous_linear_equiv lemma linear_equiv.uniform_embedding (e : E ≃ₗ[𝕜] F) (h₁ : continuous e) (h₂ : continuous e.symm) : uniform_embedding e := continuous_linear_equiv.uniform_embedding { continuous_to_fun := h₁, continuous_inv_fun := h₂, .. e } end normed
0d154c85832209839cd9b3fb554eb073dacd3de2
d436468d80b739ba7e06843c4d0d2070e43448e5
/src/analysis/normed_space/basic.lean
f3aef5d6a4dcd6f705a9224654c8289db60603b2
[ "Apache-2.0" ]
permissive
roro47/mathlib
761fdc002aef92f77818f3fef06bf6ec6fc1a28e
80aa7d52537571a2ca62a3fdf71c9533a09422cf
refs/heads/master
1,599,656,410,625
1,573,649,488,000
1,573,649,488,000
221,452,951
0
0
Apache-2.0
1,573,647,693,000
1,573,647,692,000
null
UTF-8
Lean
false
false
24,966
lean
/- Copyright (c) 2018 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Normed spaces. Authors: Patrick Massot, Johannes Hölzl -/ import algebra.pi_instances import linear_algebra.basic import topology.instances.nnreal topology.instances.complex import topology.algebra.module variables {α : Type*} {β : Type*} {γ : Type*} {ι : Type*} noncomputable theory open filter metric open_locale topological_space localized "notation f `→_{`:50 a `}`:0 b := filter.tendsto f (_root_.nhds a) (_root_.nhds b)" in filter class has_norm (α : Type*) := (norm : α → ℝ) export has_norm (norm) notation `∥`:1024 e:1 `∥`:1 := norm e class normed_group (α : Type*) extends has_norm α, add_comm_group α, metric_space α := (dist_eq : ∀ x y, dist x y = norm (x - y)) /-- Construct a normed group from a translation invariant distance -/ def normed_group.of_add_dist [has_norm α] [add_comm_group α] [metric_space α] (H1 : ∀ x:α, ∥x∥ = dist x 0) (H2 : ∀ x y z : α, dist x y ≤ dist (x + z) (y + z)) : normed_group α := { dist_eq := λ x y, begin rw H1, apply le_antisymm, { rw [sub_eq_add_neg, ← add_right_neg y], apply H2 }, { have := H2 (x-y) 0 y, rwa [sub_add_cancel, zero_add] at this } end } /-- Construct a normed group from a translation invariant distance -/ def normed_group.of_add_dist' [has_norm α] [add_comm_group α] [metric_space α] (H1 : ∀ x:α, ∥x∥ = dist x 0) (H2 : ∀ x y z : α, dist (x + z) (y + z) ≤ dist x y) : normed_group α := { dist_eq := λ x y, begin rw H1, apply le_antisymm, { have := H2 (x-y) 0 y, rwa [sub_add_cancel, zero_add] at this }, { rw [sub_eq_add_neg, ← add_right_neg y], apply H2 } end } /-- A normed group can be built from a norm that satisfies algebraic properties. This is formalised in this structure. -/ structure normed_group.core (α : Type*) [add_comm_group α] [has_norm α] := (norm_eq_zero_iff : ∀ x : α, ∥x∥ = 0 ↔ x = 0) (triangle : ∀ x y : α, ∥x + y∥ ≤ ∥x∥ + ∥y∥) (norm_neg : ∀ x : α, ∥-x∥ = ∥x∥) noncomputable def normed_group.of_core (α : Type*) [add_comm_group α] [has_norm α] (C : normed_group.core α) : normed_group α := { dist := λ x y, ∥x - y∥, dist_eq := assume x y, by refl, dist_self := assume x, (C.norm_eq_zero_iff (x - x)).mpr (show x - x = 0, by simp), eq_of_dist_eq_zero := assume x y h, show (x = y), from sub_eq_zero.mp $ (C.norm_eq_zero_iff (x - y)).mp h, dist_triangle := assume x y z, calc ∥x - z∥ = ∥x - y + (y - z)∥ : by simp ... ≤ ∥x - y∥ + ∥y - z∥ : C.triangle _ _, dist_comm := assume x y, calc ∥x - y∥ = ∥ -(y - x)∥ : by simp ... = ∥y - x∥ : by { rw [C.norm_neg] } } section normed_group variables [normed_group α] [normed_group β] lemma dist_eq_norm (g h : α) : dist g h = ∥g - h∥ := normed_group.dist_eq _ _ @[simp] lemma dist_zero_right (g : α) : dist g 0 = ∥g∥ := by { rw[dist_eq_norm], simp } lemma norm_triangle (g h : α) : ∥g + h∥ ≤ ∥g∥ + ∥h∥ := calc ∥g + h∥ = ∥g - (-h)∥ : by simp ... = dist g (-h) : by simp[dist_eq_norm] ... ≤ dist g 0 + dist 0 (-h) : by apply dist_triangle ... = ∥g∥ + ∥h∥ : by simp[dist_eq_norm] @[simp] lemma norm_nonneg (g : α) : 0 ≤ ∥g∥ := by { rw[←dist_zero_right], exact dist_nonneg } lemma norm_eq_zero (g : α) : ∥g∥ = 0 ↔ g = 0 := by { rw[←dist_zero_right], exact dist_eq_zero } @[simp] lemma norm_zero : ∥(0:α)∥ = 0 := (norm_eq_zero _).2 (by simp) lemma norm_triangle_sum {β} : ∀(s : finset β) (f : β → α), ∥s.sum f∥ ≤ s.sum (λa, ∥ f a ∥) := finset.le_sum_of_subadditive norm norm_zero norm_triangle lemma norm_pos_iff (g : α) : 0 < ∥ g ∥ ↔ g ≠ 0 := begin split ; intro h ; rw[←dist_zero_right] at *, { exact dist_pos.1 h }, { exact dist_pos.2 h } end lemma norm_le_zero_iff (g : α) : ∥g∥ ≤ 0 ↔ g = 0 := by { rw[←dist_zero_right], exact dist_le_zero } @[simp] lemma norm_neg (g : α) : ∥-g∥ = ∥g∥ := calc ∥-g∥ = ∥0 - g∥ : by simp ... = dist 0 g : (dist_eq_norm 0 g).symm ... = dist g 0 : dist_comm _ _ ... = ∥g - 0∥ : (dist_eq_norm g 0) ... = ∥g∥ : by simp lemma norm_reverse_triangle' (a b : α) : ∥a∥ - ∥b∥ ≤ ∥a - b∥ := by simpa using add_le_add (norm_triangle (a - b) (b)) (le_refl (-∥b∥)) lemma norm_reverse_triangle (a b : α) : abs(∥a∥ - ∥b∥) ≤ ∥a - b∥ := suffices -(∥a∥ - ∥b∥) ≤ ∥a - b∥, from abs_le_of_le_of_neg_le (norm_reverse_triangle' a b) this, calc -(∥a∥ - ∥b∥) = ∥b∥ - ∥a∥ : by abel ... ≤ ∥b - a∥ : norm_reverse_triangle' b a ... = ∥a - b∥ : by rw ← norm_neg (a - b); simp lemma norm_triangle_sub {a b : α} : ∥a - b∥ ≤ ∥a∥ + ∥b∥ := by simpa only [sub_eq_add_neg, norm_neg] using norm_triangle a (-b) lemma abs_norm_sub_norm_le (g h : α) : abs(∥g∥ - ∥h∥) ≤ ∥g - h∥ := abs_le.2 $ and.intro (suffices -∥g - h∥ ≤ -(∥h∥ - ∥g∥), by simpa, neg_le_neg $ sub_right_le_of_le_add $ calc ∥h∥ = ∥h - g + g∥ : by simp ... ≤ ∥h - g∥ + ∥g∥ : norm_triangle _ _ ... = ∥-(g - h)∥ + ∥g∥ : by simp ... = ∥g - h∥ + ∥g∥ : by { rw [norm_neg (g-h)] }) (sub_right_le_of_le_add $ calc ∥g∥ = ∥g - h + h∥ : by simp ... ≤ ∥g-h∥ + ∥h∥ : norm_triangle _ _) lemma dist_norm_norm_le (g h : α) : dist ∥g∥ ∥h∥ ≤ ∥g - h∥ := abs_norm_sub_norm_le g h lemma norm_sub_rev (g h : α) : ∥g - h∥ = ∥h - g∥ := by rw ←norm_neg; simp lemma ball_0_eq (ε : ℝ) : ball (0:α) ε = {x | ∥x∥ < ε} := set.ext $ assume a, by simp theorem normed_group.tendsto_nhds_zero {f : γ → α} {l : filter γ} : tendsto f l (𝓝 0) ↔ ∀ ε > 0, { x | ∥ f x ∥ < ε } ∈ l := begin rw [metric.tendsto_nhds], simp only [normed_group.dist_eq, sub_zero], split, { intros h ε εgt0, rcases h ε εgt0 with ⟨s, ssets, hs⟩, exact mem_sets_of_superset ssets hs }, intros h ε εgt0, exact ⟨_, h ε εgt0, set.subset.refl _⟩ end section nnnorm def nnnorm (a : α) : nnreal := ⟨norm a, norm_nonneg a⟩ @[simp] lemma coe_nnnorm (a : α) : (nnnorm a : ℝ) = norm a := rfl lemma nndist_eq_nnnorm (a b : α) : nndist a b = nnnorm (a - b) := nnreal.eq $ dist_eq_norm _ _ lemma nnnorm_eq_zero (a : α) : nnnorm a = 0 ↔ a = 0 := by simp only [nnreal.eq_iff.symm, nnreal.coe_zero, coe_nnnorm, norm_eq_zero] @[simp] lemma nnnorm_zero : nnnorm (0 : α) = 0 := nnreal.eq norm_zero lemma nnnorm_triangle (g h : α) : nnnorm (g + h) ≤ nnnorm g + nnnorm h := by simpa [nnreal.coe_le] using norm_triangle g h @[simp] lemma nnnorm_neg (g : α) : nnnorm (-g) = nnnorm g := nnreal.eq $ norm_neg g lemma nndist_nnnorm_nnnorm_le (g h : α) : nndist (nnnorm g) (nnnorm h) ≤ nnnorm (g - h) := nnreal.coe_le.2 $ dist_norm_norm_le g h end nnnorm instance prod.normed_group : normed_group (α × β) := { norm := λx, max ∥x.1∥ ∥x.2∥, dist_eq := assume (x y : α × β), show max (dist x.1 y.1) (dist x.2 y.2) = (max ∥(x - y).1∥ ∥(x - y).2∥), by simp [dist_eq_norm] } lemma norm_fst_le (x : α × β) : ∥x.1∥ ≤ ∥x∥ := begin have : ∥x∥ = max (∥x.fst∥) (∥x.snd∥) := rfl, rw this, simp[le_max_left] end lemma norm_snd_le (x : α × β) : ∥x.2∥ ≤ ∥x∥ := begin have : ∥x∥ = max (∥x.fst∥) (∥x.snd∥) := rfl, rw this, simp[le_max_right] end instance fintype.normed_group {π : ι → Type*} [fintype ι] [∀i, normed_group (π i)] : normed_group (Πb, π b) := { norm := λf, ((finset.sup finset.univ (λ b, nnnorm (f b)) : nnreal) : ℝ), dist_eq := assume x y, congr_arg (coe : nnreal → ℝ) $ congr_arg (finset.sup finset.univ) $ funext $ assume a, show nndist (x a) (y a) = nnnorm (x a - y a), from nndist_eq_nnnorm _ _ } lemma tendsto_iff_norm_tendsto_zero {f : ι → β} {a : filter ι} {b : β} : tendsto f a (𝓝 b) ↔ tendsto (λ e, ∥ f e - b ∥) a (𝓝 0) := by rw tendsto_iff_dist_tendsto_zero ; simp only [(dist_eq_norm _ _).symm] lemma tendsto_zero_iff_norm_tendsto_zero {f : γ → β} {a : filter γ} : tendsto f a (𝓝 0) ↔ tendsto (λ e, ∥ f e ∥) a (𝓝 0) := have tendsto f a (𝓝 0) ↔ tendsto (λ e, ∥ f e - 0 ∥) a (𝓝 0) := tendsto_iff_norm_tendsto_zero, by simpa lemma lim_norm (x : α) : (λg:α, ∥g - x∥) →_{x} 0 := tendsto_iff_norm_tendsto_zero.1 (continuous_iff_continuous_at.1 continuous_id x) lemma lim_norm_zero : (λg:α, ∥g∥) →_{0} 0 := by simpa using lim_norm (0:α) lemma continuous_norm : continuous (λg:α, ∥g∥) := begin rw continuous_iff_continuous_at, intro x, rw [continuous_at, tendsto_iff_dist_tendsto_zero], exact squeeze_zero (λ t, abs_nonneg _) (λ t, abs_norm_sub_norm_le _ _) (lim_norm x) end lemma continuous_nnnorm : continuous (nnnorm : α → nnreal) := continuous_subtype_mk _ continuous_norm instance normed_uniform_group : uniform_add_group α := begin refine ⟨metric.uniform_continuous_iff.2 $ assume ε hε, ⟨ε / 2, half_pos hε, assume a b h, _⟩⟩, rw [prod.dist_eq, max_lt_iff, dist_eq_norm, dist_eq_norm] at h, calc dist (a.1 - a.2) (b.1 - b.2) = ∥(a.1 - b.1) - (a.2 - b.2)∥ : by simp [dist_eq_norm] ... ≤ ∥a.1 - b.1∥ + ∥a.2 - b.2∥ : norm_triangle_sub ... < ε / 2 + ε / 2 : add_lt_add h.1 h.2 ... = ε : add_halves _ end instance normed_top_monoid : topological_add_monoid α := by apply_instance instance normed_top_group : topological_add_group α := by apply_instance end normed_group section normed_ring class normed_ring (α : Type*) extends has_norm α, ring α, metric_space α := (dist_eq : ∀ x y, dist x y = norm (x - y)) (norm_mul : ∀ a b, norm (a * b) ≤ norm a * norm b) instance normed_ring.to_normed_group [β : normed_ring α] : normed_group α := { ..β } lemma norm_mul_le {α : Type*} [normed_ring α] (a b : α) : (∥a*b∥) ≤ (∥a∥) * (∥b∥) := normed_ring.norm_mul _ _ lemma norm_pow_le {α : Type*} [normed_ring α] (a : α) : ∀ {n : ℕ}, 0 < n → ∥a^n∥ ≤ ∥a∥^n | 1 h := by simp | (n+2) h := le_trans (norm_mul_le a (a^(n+1))) (mul_le_mul (le_refl _) (norm_pow_le (nat.succ_pos _)) (norm_nonneg _) (norm_nonneg _)) instance prod.normed_ring [normed_ring α] [normed_ring β] : normed_ring (α × β) := { norm_mul := assume x y, calc ∥x * y∥ = ∥(x.1*y.1, x.2*y.2)∥ : rfl ... = (max ∥x.1*y.1∥ ∥x.2*y.2∥) : rfl ... ≤ (max (∥x.1∥*∥y.1∥) (∥x.2∥*∥y.2∥)) : max_le_max (norm_mul_le (x.1) (y.1)) (norm_mul_le (x.2) (y.2)) ... = (max (∥x.1∥*∥y.1∥) (∥y.2∥*∥x.2∥)) : by simp[mul_comm] ... ≤ (max (∥x.1∥) (∥x.2∥)) * (max (∥y.2∥) (∥y.1∥)) : by { apply max_mul_mul_le_max_mul_max; simp [norm_nonneg] } ... = (max (∥x.1∥) (∥x.2∥)) * (max (∥y.1∥) (∥y.2∥)) : by simp[max_comm] ... = (∥x∥*∥y∥) : rfl, ..prod.normed_group } end normed_ring instance normed_ring_top_monoid [normed_ring α] : topological_monoid α := ⟨ continuous_iff_continuous_at.2 $ λ x, tendsto_iff_norm_tendsto_zero.2 $ have ∀ e : α × α, e.fst * e.snd - x.fst * x.snd = e.fst * e.snd - e.fst * x.snd + (e.fst * x.snd - x.fst * x.snd), by intro; rw sub_add_sub_cancel, begin apply squeeze_zero, { intro, apply norm_nonneg }, { simp only [this], intro, apply norm_triangle }, { rw ←zero_add (0 : ℝ), apply tendsto_add, { apply squeeze_zero, { intro, apply norm_nonneg }, { intro t, show ∥t.fst * t.snd - t.fst * x.snd∥ ≤ ∥t.fst∥ * ∥t.snd - x.snd∥, rw ←mul_sub, apply norm_mul_le }, { rw ←mul_zero (∥x.fst∥), apply tendsto_mul, { apply continuous_iff_continuous_at.1, apply continuous_norm.comp continuous_fst }, { apply tendsto_iff_norm_tendsto_zero.1, apply continuous_iff_continuous_at.1, apply continuous_snd }}}, { apply squeeze_zero, { intro, apply norm_nonneg }, { intro t, show ∥t.fst * x.snd - x.fst * x.snd∥ ≤ ∥t.fst - x.fst∥ * ∥x.snd∥, rw ←sub_mul, apply norm_mul_le }, { rw ←zero_mul (∥x.snd∥), apply tendsto_mul, { apply tendsto_iff_norm_tendsto_zero.1, apply continuous_iff_continuous_at.1, apply continuous_fst }, { apply tendsto_const_nhds }}}} end ⟩ instance normed_top_ring [normed_ring α] : topological_ring α := ⟨ continuous_iff_continuous_at.2 $ λ x, tendsto_iff_norm_tendsto_zero.2 $ have ∀ e : α, -e - -x = -(e - x), by intro; simp, by simp only [this, norm_neg]; apply lim_norm ⟩ class normed_field (α : Type*) extends has_norm α, discrete_field α, metric_space α := (dist_eq : ∀ x y, dist x y = norm (x - y)) (norm_mul' : ∀ a b, norm (a * b) = norm a * norm b) class nondiscrete_normed_field (α : Type*) extends normed_field α := (non_trivial : ∃x:α, 1<∥x∥) instance normed_field.to_normed_ring [i : normed_field α] : normed_ring α := { norm_mul := by finish [i.norm_mul'], ..i } namespace normed_field @[simp] lemma norm_one {α : Type*} [normed_field α] : ∥(1 : α)∥ = 1 := have ∥(1 : α)∥ * ∥(1 : α)∥ = ∥(1 : α)∥ * 1, by calc ∥(1 : α)∥ * ∥(1 : α)∥ = ∥(1 : α) * (1 : α)∥ : by rw normed_field.norm_mul' ... = ∥(1 : α)∥ * 1 : by simp, eq_of_mul_eq_mul_left (ne_of_gt ((norm_pos_iff _).2 (by simp))) this @[simp] lemma norm_mul [normed_field α] (a b : α) : ∥a * b∥ = ∥a∥ * ∥b∥ := normed_field.norm_mul' a b instance normed_field.is_monoid_hom_norm [normed_field α] : is_monoid_hom (norm : α → ℝ) := { map_one := norm_one, map_mul := norm_mul } @[simp] lemma norm_pow [normed_field α] (a : α) : ∀ (n : ℕ), ∥a^n∥ = ∥a∥^n := is_monoid_hom.map_pow norm a @[simp] lemma norm_prod {β : Type*} [normed_field α] (s : finset β) (f : β → α) : ∥s.prod f∥ = s.prod (λb, ∥f b∥) := eq.symm (finset.prod_hom norm) @[simp] lemma norm_div {α : Type*} [normed_field α] (a b : α) : ∥a/b∥ = ∥a∥/∥b∥ := if hb : b = 0 then by simp [hb] else begin apply eq_div_of_mul_eq, { apply ne_of_gt, apply (norm_pos_iff _).mpr hb }, { rw [←normed_field.norm_mul, div_mul_cancel _ hb] } end @[simp] lemma norm_inv {α : Type*} [normed_field α] (a : α) : ∥a⁻¹∥ = ∥a∥⁻¹ := by simp only [inv_eq_one_div, norm_div, norm_one] @[simp] lemma norm_fpow {α : Type*} [normed_field α] (a : α) : ∀n : ℤ, ∥a^n∥ = ∥a∥^n | (n : ℕ) := norm_pow a n | -[1+ n] := by simp [fpow_neg_succ_of_nat] lemma exists_one_lt_norm (α : Type*) [i : nondiscrete_normed_field α] : ∃x : α, 1 < ∥x∥ := i.non_trivial lemma exists_norm_lt_one (α : Type*) [nondiscrete_normed_field α] : ∃x : α, 0 < ∥x∥ ∧ ∥x∥ < 1 := begin rcases exists_one_lt_norm α with ⟨y, hy⟩, refine ⟨y⁻¹, _, _⟩, { simp only [inv_eq_zero, ne.def, norm_pos_iff], assume h, rw ← norm_eq_zero at h, rw h at hy, exact lt_irrefl _ (lt_trans zero_lt_one hy) }, { simp [inv_lt_one hy] } end instance : normed_field ℝ := { norm := λ x, abs x, dist_eq := assume x y, rfl, norm_mul' := abs_mul } instance : nondiscrete_normed_field ℝ := { non_trivial := ⟨2, by { unfold norm, rw abs_of_nonneg; norm_num }⟩ } end normed_field lemma real.norm_eq_abs (r : ℝ) : norm r = abs r := rfl @[simp] lemma norm_norm [normed_group α] (x : α) : ∥∥x∥∥ = ∥x∥ := by rw [real.norm_eq_abs, abs_of_nonneg (norm_nonneg _)] @[simp] lemma nnnorm_norm [normed_group α] (a : α) : nnnorm ∥a∥ = nnnorm a := by simp only [nnnorm, norm_norm] instance : normed_ring ℤ := { norm := λ n, ∥(n : ℝ)∥, norm_mul := λ m n, le_of_eq $ by simp only [norm, int.cast_mul, abs_mul], dist_eq := λ m n, by simp only [int.dist_eq, norm, int.cast_sub] } @[elim_cast] lemma int.norm_cast_real (m : ℤ) : ∥(m : ℝ)∥ = ∥m∥ := rfl instance : normed_field ℚ := { norm := λ r, ∥(r : ℝ)∥, norm_mul' := λ r₁ r₂, by simp only [norm, rat.cast_mul, abs_mul], dist_eq := λ r₁ r₂, by simp only [rat.dist_eq, norm, rat.cast_sub] } instance : nondiscrete_normed_field ℚ := { non_trivial := ⟨2, by { unfold norm, rw abs_of_nonneg; norm_num }⟩ } @[elim_cast, simp] lemma rat.norm_cast_real (r : ℚ) : ∥(r : ℝ)∥ = ∥r∥ := rfl @[elim_cast, simp] lemma int.norm_cast_rat (m : ℤ) : ∥(m : ℚ)∥ = ∥m∥ := by rw [← rat.norm_cast_real, ← int.norm_cast_real]; congr' 1; norm_cast section normed_space class normed_space (α : Type*) (β : Type*) [normed_field α] [normed_group β] extends vector_space α β := (norm_smul : ∀ (a:α) (b:β), norm (a • b) = has_norm.norm a * norm b) variables [normed_field α] [normed_group β] instance normed_field.to_normed_space : normed_space α α := { norm_smul := normed_field.norm_mul } set_option class.instance_max_depth 43 lemma norm_smul [normed_space α β] (s : α) (x : β) : ∥s • x∥ = ∥s∥ * ∥x∥ := normed_space.norm_smul s x lemma nnnorm_smul [normed_space α β] (s : α) (x : β) : nnnorm (s • x) = nnnorm s * nnnorm x := nnreal.eq $ norm_smul s x variables {E : Type*} {F : Type*} [normed_group E] [normed_space α E] [normed_group F] [normed_space α F] lemma tendsto_smul {f : γ → α} { g : γ → F} {e : filter γ} {s : α} {b : F} : (tendsto f e (𝓝 s)) → (tendsto g e (𝓝 b)) → tendsto (λ x, (f x) • (g x)) e (𝓝 (s • b)) := begin intros limf limg, rw tendsto_iff_norm_tendsto_zero, have ineq := λ x : γ, calc ∥f x • g x - s • b∥ = ∥(f x • g x - s • g x) + (s • g x - s • b)∥ : by simp[add_assoc] ... ≤ ∥f x • g x - s • g x∥ + ∥s • g x - s • b∥ : norm_triangle (f x • g x - s • g x) (s • g x - s • b) ... ≤ ∥f x - s∥*∥g x∥ + ∥s∥*∥g x - b∥ : by { rw [←smul_sub, ←sub_smul, norm_smul, norm_smul] }, apply squeeze_zero, { intro t, exact norm_nonneg _ }, { exact ineq }, { clear ineq, have limf': tendsto (λ x, ∥f x - s∥) e (𝓝 0) := tendsto_iff_norm_tendsto_zero.1 limf, have limg' : tendsto (λ x, ∥g x∥) e (𝓝 ∥b∥) := filter.tendsto.comp (continuous_iff_continuous_at.1 continuous_norm _) limg, have lim1 := tendsto_mul limf' limg', simp only [zero_mul, sub_eq_add_neg] at lim1, have limg3 := tendsto_iff_norm_tendsto_zero.1 limg, have lim2 := tendsto_mul (tendsto_const_nhds : tendsto _ _ (𝓝 ∥ s ∥)) limg3, simp only [sub_eq_add_neg, mul_zero] at lim2, rw [show (0:ℝ) = 0 + 0, by simp], exact tendsto_add lim1 lim2 } end lemma tendsto_smul_const {g : γ → F} {e : filter γ} (s : α) {b : F} : (tendsto g e (𝓝 b)) → tendsto (λ x, s • (g x)) e (𝓝 (s • b)) := tendsto_smul tendsto_const_nhds instance normed_space.topological_vector_space : topological_vector_space α E := { continuous_smul := continuous_iff_continuous_at.2 $ λp, tendsto_smul (continuous_iff_continuous_at.1 continuous_fst _) (continuous_iff_continuous_at.1 continuous_snd _) } open normed_field /-- If there is a scalar `c` with `∥c∥>1`, then any element can be moved by scalar multiplication to any shell of width `∥c∥`. Also recap information on the norm of the rescaling element that shows up in applications. -/ lemma rescale_to_shell {c : α} (hc : 1 < ∥c∥) {ε : ℝ} (εpos : 0 < ε) {x : E} (hx : x ≠ 0) : ∃d:α, d ≠ 0 ∧ ∥d • x∥ ≤ ε ∧ (ε/∥c∥ ≤ ∥d • x∥) ∧ (∥d∥⁻¹ ≤ ε⁻¹ * ∥c∥ * ∥x∥) := begin have xεpos : 0 < ∥x∥/ε := div_pos_of_pos_of_pos ((norm_pos_iff _).2 hx) εpos, rcases exists_int_pow_near xεpos hc with ⟨n, hn⟩, have cpos : 0 < ∥c∥ := lt_trans (zero_lt_one : (0 :ℝ) < 1) hc, have cnpos : 0 < ∥c^(n+1)∥ := by { rw norm_fpow, exact lt_trans xεpos hn.2 }, refine ⟨(c^(n+1))⁻¹, _, _, _, _⟩, show (c ^ (n + 1))⁻¹ ≠ 0, by rwa [ne.def, inv_eq_zero, ← ne.def, ← norm_pos_iff], show ∥(c ^ (n + 1))⁻¹ • x∥ ≤ ε, { rw [norm_smul, norm_inv, ← div_eq_inv_mul, div_le_iff cnpos, mul_comm, norm_fpow], exact (div_le_iff εpos).1 (le_of_lt (hn.2)) }, show ε / ∥c∥ ≤ ∥(c ^ (n + 1))⁻¹ • x∥, { rw [div_le_iff cpos, norm_smul, norm_inv, norm_fpow, fpow_add (ne_of_gt cpos), fpow_one, mul_inv', mul_comm, ← mul_assoc, ← mul_assoc, mul_inv_cancel (ne_of_gt cpos), one_mul, ← div_eq_inv_mul, le_div_iff (fpow_pos_of_pos cpos _), mul_comm], exact (le_div_iff εpos).1 hn.1 }, show ∥(c ^ (n + 1))⁻¹∥⁻¹ ≤ ε⁻¹ * ∥c∥ * ∥x∥, { have : ε⁻¹ * ∥c∥ * ∥x∥ = ε⁻¹ * ∥x∥ * ∥c∥, by ring, rw [norm_inv, inv_inv', norm_fpow, fpow_add (ne_of_gt cpos), fpow_one, this, ← div_eq_inv_mul], exact mul_le_mul_of_nonneg_right hn.1 (norm_nonneg _) } end instance : normed_space α (E × F) := { norm_smul := begin intros s x, cases x with x₁ x₂, change max (∥s • x₁∥) (∥s • x₂∥) = ∥s∥ * max (∥x₁∥) (∥x₂∥), rw [norm_smul, norm_smul, ← mul_max_of_nonneg _ _ (norm_nonneg _)] end, add_smul := λ r x y, prod.ext (add_smul _ _ _) (add_smul _ _ _), smul_add := λ r x y, prod.ext (smul_add _ _ _) (smul_add _ _ _), ..prod.normed_group, ..prod.vector_space } instance fintype.normed_space {E : ι → Type*} [fintype ι] [∀i, normed_group (E i)] [∀i, normed_space α (E i)] : normed_space α (Πi, E i) := { norm_smul := λ a f, show (↑(finset.sup finset.univ (λ (b : ι), nnnorm (a • f b))) : ℝ) = nnnorm a * ↑(finset.sup finset.univ (λ (b : ι), nnnorm (f b))), by simp only [(nnreal.coe_mul _ _).symm, nnreal.mul_finset_sup, nnnorm_smul] } end normed_space section summable open_locale classical open finset filter variables [normed_group α] [complete_space α] lemma summable_iff_vanishing_norm {f : ι → α} : summable f ↔ ∀ε>0, (∃s:finset ι, ∀t, disjoint t s → ∥ t.sum f ∥ < ε) := begin simp only [summable_iff_vanishing, metric.mem_nhds_iff, exists_imp_distrib], split, { assume h ε hε, refine h {x | ∥x∥ < ε} ε hε _, rw [ball_0_eq ε] }, { assume h s ε hε hs, rcases h ε hε with ⟨t, ht⟩, refine ⟨t, assume u hu, hs _⟩, rw [ball_0_eq], exact ht u hu } end lemma summable_of_norm_bounded {f : ι → α} (g : ι → ℝ) (hf : summable g) (h : ∀i, ∥f i∥ ≤ g i) : summable f := summable_iff_vanishing_norm.2 $ assume ε hε, let ⟨s, hs⟩ := summable_iff_vanishing_norm.1 hf ε hε in ⟨s, assume t ht, have ∥t.sum g∥ < ε := hs t ht, have nn : 0 ≤ t.sum g := finset.sum_nonneg (assume a _, le_trans (norm_nonneg _) (h a)), lt_of_le_of_lt (norm_triangle_sum t f) $ lt_of_le_of_lt (finset.sum_le_sum $ assume i _, h i) $ by rwa [real.norm_eq_abs, abs_of_nonneg nn] at this⟩ lemma summable_of_summable_norm {f : ι → α} (hf : summable (λa, ∥f a∥)) : summable f := summable_of_norm_bounded _ hf (assume i, le_refl _) lemma norm_tsum_le_tsum_norm {f : ι → α} (hf : summable (λi, ∥f i∥)) : ∥(∑i, f i)∥ ≤ (∑ i, ∥f i∥) := have h₁ : tendsto (λs:finset ι, ∥s.sum f∥) at_top (𝓝 ∥(∑ i, f i)∥) := (continuous_norm.tendsto _).comp (has_sum_tsum $ summable_of_summable_norm hf), have h₂ : tendsto (λs:finset ι, s.sum (λi, ∥f i∥)) at_top (𝓝 (∑ i, ∥f i∥)) := has_sum_tsum hf, le_of_tendsto_of_tendsto at_top_ne_bot h₁ h₂ $ univ_mem_sets' $ assume s, norm_triangle_sum _ _ end summable namespace complex instance : normed_field ℂ := { norm := complex.abs, dist_eq := λ _ _, rfl, norm_mul' := complex.abs_mul, .. complex.discrete_field } instance : nondiscrete_normed_field ℂ := { non_trivial := ⟨2, by simp [norm]; norm_num⟩ } @[simp] lemma norm_real (r : ℝ) : ∥(r : ℂ)∥ = ∥r∥ := complex.abs_of_real _ @[simp] lemma norm_rat (r : ℚ) : ∥(r : ℂ)∥ = _root_.abs (r : ℝ) := suffices ∥((r : ℝ) : ℂ)∥ = _root_.abs r, by simpa, by rw [norm_real, real.norm_eq_abs] @[simp] lemma norm_nat (n : ℕ) : ∥(n : ℂ)∥ = n := complex.abs_of_nat _ @[simp] lemma norm_int {n : ℤ} : ∥(n : ℂ)∥ = _root_.abs n := suffices ∥((n : ℝ) : ℂ)∥ = _root_.abs n, by simpa, by rw [norm_real, real.norm_eq_abs] lemma norm_int_of_nonneg {n : ℤ} (hn : 0 ≤ n) : ∥(n : ℂ)∥ = n := by rw [norm_int, _root_.abs_of_nonneg]; exact int.cast_nonneg.2 hn end complex
dda28ba7532bd59601f319f5fa288c8c0fabf2bd
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/src/Init/Control/StateRef.lean
fd05a47bd451ed67f51f581afcf1200643abdd28
[ "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
2,528
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Sebastian Ullrich The State monad transformer using IO references. -/ prelude import Init.System.IO import Init.Control.State def StateRefT' (ω : Type) (σ : Type) (m : Type → Type) (α : Type) : Type := ReaderT (ST.Ref ω σ) m α /-! Recall that `StateRefT` is a macro that infers `ω` from the `m`. -/ @[inline] def StateRefT'.run {ω σ : Type} {m : Type → Type} [Monad m] [MonadLiftT (ST ω) m] {α : Type} (x : StateRefT' ω σ m α) (s : σ) : m (α × σ) := do let ref ← ST.mkRef s let a ← x ref let s ← ref.get pure (a, s) @[inline] def StateRefT'.run' {ω σ : Type} {m : Type → Type} [Monad m] [MonadLiftT (ST ω) m] {α : Type} (x : StateRefT' ω σ m α) (s : σ) : m α := do let (a, _) ← x.run s pure a namespace StateRefT' variable {ω σ : Type} {m : Type → Type} {α : Type} @[inline] protected def lift (x : m α) : StateRefT' ω σ m α := fun _ => x instance [Monad m] : Monad (StateRefT' ω σ m) := inferInstanceAs (Monad (ReaderT _ _)) instance : MonadLift m (StateRefT' ω σ m) := ⟨StateRefT'.lift⟩ instance (σ m) [Monad m] : MonadFunctor m (StateRefT' ω σ m) := inferInstanceAs (MonadFunctor m (ReaderT _ _)) instance [Alternative m] [Monad m] : Alternative (StateRefT' ω σ m) := inferInstanceAs (Alternative (ReaderT _ _)) @[inline] protected def get [Monad m] [MonadLiftT (ST ω) m] : StateRefT' ω σ m σ := fun ref => ref.get @[inline] protected def set [Monad m] [MonadLiftT (ST ω) m] (s : σ) : StateRefT' ω σ m PUnit := fun ref => ref.set s @[inline] protected def modifyGet [Monad m] [MonadLiftT (ST ω) m] (f : σ → α × σ) : StateRefT' ω σ m α := fun ref => ref.modifyGet f instance [MonadLiftT (ST ω) m] [Monad m] : MonadStateOf σ (StateRefT' ω σ m) where get := StateRefT'.get set := StateRefT'.set modifyGet := StateRefT'.modifyGet instance (ε) [MonadExceptOf ε m] : MonadExceptOf ε (StateRefT' ω σ m) where throw := StateRefT'.lift ∘ throwThe ε tryCatch := fun x c s => tryCatchThe ε (x s) (fun e => c e s) end StateRefT' instance (ω σ : Type) (m : Type → Type) : MonadControl m (StateRefT' ω σ m) := inferInstanceAs (MonadControl m (ReaderT _ _)) instance {m : Type → Type} {ω σ : Type} [MonadFinally m] [Monad m] : MonadFinally (StateRefT' ω σ m) := inferInstanceAs (MonadFinally (ReaderT _ _))
8ad496b87212f746f9224fa5ae0cdbad4ec87edf
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/order/basic.lean
47d1bc5ebc1599ae9b75c4db8df61793490af118
[ "Apache-2.0" ]
permissive
dupuisf/mathlib
62de4ec6544bf3b79086afd27b6529acfaf2c1bb
8582b06b0a5d06c33ee07d0bdf7c646cae22cf36
refs/heads/master
1,669,494,854,016
1,595,692,409,000
1,595,692,409,000
272,046,630
0
0
Apache-2.0
1,592,066,143,000
1,592,066,142,000
null
UTF-8
Lean
false
false
16,963
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Mario Carneiro -/ import data.subtype import data.prod open function /-! # Basic definitions about `≤` and `<` ## Definitions ### Predicates on functions - `monotone f`: a function between two types equipped with `≤` is monotone if `a ≤ b` implies `f a ≤ f b`. - `strict_mono f` : a function between two types equipped with `<` is strictly monotone if `a < b` implies `f a < f b`. - `order_dual α` : a type tag reversing the meaning of all inequalities. ### Transfering orders - `order.preimage`, `preorder.lift`: transfer a (pre)order on `β` to an order on `α` using a function `f : α → β`. - `partial_order.lift`, `linear_order.lift`, `decidable_linear_order.lift`: transfer a partial (resp., linear, decidable linear) order on `β` to a partial (resp., linear, decidable linear) order on `α` using an injective function `f`. ### Extra classes - `no_top_order`, `no_bot_order`: an order without a maximal/minimal element. - `densely_ordered`: an order with no gaps, i.e. for any two elements `a<b` there exists `c`, `a<c<b`. ## Main theorems - `monotone_of_monotone_nat`: if `f : ℕ → α` and `f n ≤ f (n + 1)` for all `n`, then `f` is monotone; - `strict_mono.nat`: if `f : ℕ → α` and `f n < f (n + 1)` for all `n`, then f is strictly monotone. ## TODO - expand module docs - automatic construction of dual definitions / theorems ## Tags preorder, order, partial order, linear order, monotone, strictly monotone -/ universes u v w variables {α : Type u} {β : Type v} {γ : Type w} {r : α → α → Prop} @[nolint ge_or_gt] -- see Note [nolint_ge] theorem ge_of_eq [preorder α] {a b : α} : a = b → a ≥ b := λ h, h ▸ le_refl a theorem preorder.ext {α} {A B : preorder α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := begin casesI A, casesI B, congr, { funext x y, exact propext (H x y) }, { funext x y, dsimp [(≤)] at A_lt_iff_le_not_le B_lt_iff_le_not_le H, simp [A_lt_iff_le_not_le, B_lt_iff_le_not_le, H] }, end theorem partial_order.ext {α} {A B : partial_order α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := by { haveI this := preorder.ext H, casesI A, casesI B, injection this, congr' } theorem linear_order.ext {α} {A B : linear_order α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := by { haveI this := partial_order.ext H, casesI A, casesI B, injection this, congr' } /-- Given an order `R` on `β` and a function `f : α → β`, the preimage order on `α` is defined by `x ≤ y ↔ f x ≤ f y`. It is the unique order on `α` making `f` an order embedding (assuming `f` is injective). -/ @[simp] def order.preimage {α β} (f : α → β) (s : β → β → Prop) (x y : α) := s (f x) (f y) infix ` ⁻¹'o `:80 := order.preimage /-- The preimage of a decidable order is decidable. -/ instance order.preimage.decidable {α β} (f : α → β) (s : β → β → Prop) [H : decidable_rel s] : decidable_rel (f ⁻¹'o s) := λ x y, H _ _ section monotone variables [preorder α] [preorder β] [preorder γ] /-- A function between preorders is monotone if `a ≤ b` implies `f a ≤ f b`. -/ def monotone (f : α → β) := ∀⦃a b⦄, a ≤ b → f a ≤ f b theorem monotone_id : @monotone α α _ _ id := assume x y h, h theorem monotone_const {b : β} : monotone (λ(a:α), b) := assume x y h, le_refl b protected theorem monotone.comp {g : β → γ} {f : α → β} (m_g : monotone g) (m_f : monotone f) : monotone (g ∘ f) := assume a b h, m_g (m_f h) protected theorem monotone.iterate {f : α → α} (hf : monotone f) (n : ℕ) : monotone (f^[n]) := nat.rec_on n monotone_id (λ n ihn, ihn.comp hf) lemma monotone_of_monotone_nat {f : ℕ → α} (hf : ∀n, f n ≤ f (n + 1)) : monotone f | n m h := begin induction h, { refl }, { transitivity, assumption, exact hf _ } end lemma reflect_lt {α β} [linear_order α] [preorder β] {f : α → β} (hf : monotone f) {x x' : α} (h : f x < f x') : x < x' := by { rw [← not_le], intro h', apply not_le_of_lt h, exact hf h' } end monotone /-- A function `f` is strictly monotone if `a < b` implies `f a < f b`. -/ def strict_mono [has_lt α] [has_lt β] (f : α → β) : Prop := ∀ ⦃a b⦄, a < b → f a < f b lemma strict_mono_id [has_lt α] : strict_mono (id : α → α) := λ a b, id /-- A function `f` is strictly monotone increasing on `t` if `x < y` for `x,y ∈ t` implies `f x < f y`. -/ def strict_mono_incr_on [has_lt α] [has_lt β] (f : α → β) (t : set α) : Prop := ∀ (x ∈ t) (y ∈ t), x < y → f x < f y /-- A function `f` is strictly monotone decreasing on `t` if `x < y` for `x,y ∈ t` implies `f y < f x`. -/ def strict_mono_decr_on [has_lt α] [has_lt β] (f : α → β) (t : set α) : Prop := ∀ (x ∈ t) (y ∈ t), x < y → f y < f x namespace strict_mono open ordering function lemma comp [has_lt α] [has_lt β] [has_lt γ] {g : β → γ} {f : α → β} (hg : strict_mono g) (hf : strict_mono f) : strict_mono (g ∘ f) := λ a b h, hg (hf h) protected theorem iterate [has_lt α] {f : α → α} (hf : strict_mono f) (n : ℕ) : strict_mono (f^[n]) := nat.rec_on n strict_mono_id (λ n ihn, ihn.comp hf) lemma id_le {φ : ℕ → ℕ} (h : strict_mono φ) : ∀ n, n ≤ φ n := λ n, nat.rec_on n (nat.zero_le _) (λ n hn, nat.succ_le_of_lt (lt_of_le_of_lt hn $ h $ nat.lt_succ_self n)) section variables [linear_order α] [preorder β] {f : α → β} lemma lt_iff_lt (H : strict_mono f) {a b} : f a < f b ↔ a < b := ⟨λ h, ((lt_trichotomy b a) .resolve_left $ λ h', lt_asymm h $ H h') .resolve_left $ λ e, ne_of_gt h $ congr_arg _ e, @H _ _⟩ lemma injective (H : strict_mono f) : injective f | a b e := ((lt_trichotomy a b) .resolve_left $ λ h, ne_of_lt (H h) e) .resolve_right $ λ h, ne_of_gt (H h) e theorem compares (H : strict_mono f) {a b} : ∀ {o}, compares o (f a) (f b) ↔ compares o a b | lt := H.lt_iff_lt | eq := ⟨λ h, H.injective h, congr_arg _⟩ | gt := H.lt_iff_lt lemma le_iff_le (H : strict_mono f) {a b} : f a ≤ f b ↔ a ≤ b := ⟨λ h, le_of_not_gt $ λ h', not_le_of_lt (H h') h, λ h, (lt_or_eq_of_le h).elim (λ h', le_of_lt (H h')) (λ h', h' ▸ le_refl _)⟩ end protected lemma nat {β} [preorder β] {f : ℕ → β} (h : ∀n, f n < f (n+1)) : strict_mono f := by { intros n m hnm, induction hnm with m' hnm' ih, apply h, exact lt.trans ih (h _) } -- `preorder α` isn't strong enough: if the preorder on α is an equivalence relation, -- then `strict_mono f` is vacuously true. lemma monotone [partial_order α] [preorder β] {f : α → β} (H : strict_mono f) : monotone f := λ a b h, (lt_or_eq_of_le h).rec (le_of_lt ∘ (@H _ _)) (by rintro rfl; refl) end strict_mono section open function lemma injective_of_lt_imp_ne [linear_order α] {f : α → β} (h : ∀ x y, x < y → f x ≠ f y) : injective f := begin intros x y k, contrapose k, rw [←ne.def, ne_iff_lt_or_gt] at k, cases k, { apply h _ _ k }, { rw eq_comm, apply h _ _ k } end variables [partial_order α] [partial_order β] {f : α → β} lemma strict_mono_of_monotone_of_injective (h₁ : monotone f) (h₂ : injective f) : strict_mono f := λ a b h, begin rw lt_iff_le_and_ne at ⊢ h, exact ⟨h₁ h.1, λ e, h.2 (h₂ e)⟩ end end /-- Type tag for a set with dual order: `≤` means `≥` and `<` means `>`. -/ def order_dual (α : Type*) := α namespace order_dual instance (α : Type*) [h : nonempty α] : nonempty (order_dual α) := h instance (α : Type*) [has_le α] : has_le (order_dual α) := ⟨λx y:α, y ≤ x⟩ instance (α : Type*) [has_lt α] : has_lt (order_dual α) := ⟨λx y:α, y < x⟩ -- `dual_le` and `dual_lt` should not be simp lemmas: -- they cause a loop since `α` and `order_dual α` are definitionally equal lemma dual_le [has_le α] {a b : α} : @has_le.le (order_dual α) _ a b ↔ @has_le.le α _ b a := iff.rfl lemma dual_lt [has_lt α] {a b : α} : @has_lt.lt (order_dual α) _ a b ↔ @has_lt.lt α _ b a := iff.rfl instance (α : Type*) [preorder α] : preorder (order_dual α) := { le_refl := le_refl, le_trans := assume a b c hab hbc, le_trans hbc hab, lt_iff_le_not_le := λ _ _, lt_iff_le_not_le, .. order_dual.has_le α, .. order_dual.has_lt α } instance (α : Type*) [partial_order α] : partial_order (order_dual α) := { le_antisymm := assume a b hab hba, @le_antisymm α _ a b hba hab, .. order_dual.preorder α } instance (α : Type*) [linear_order α] : linear_order (order_dual α) := { le_total := assume a b:α, le_total b a, .. order_dual.partial_order α } instance (α : Type*) [decidable_linear_order α] : decidable_linear_order (order_dual α) := { decidable_le := show decidable_rel (λa b:α, b ≤ a), by apply_instance, decidable_lt := show decidable_rel (λa b:α, b < a), by apply_instance, .. order_dual.linear_order α } instance : Π [inhabited α], inhabited (order_dual α) := id end order_dual /- order instances on the function space -/ instance pi.preorder {ι : Type u} {α : ι → Type v} [∀i, preorder (α i)] : preorder (Πi, α i) := { le := λx y, ∀i, x i ≤ y i, le_refl := assume a i, le_refl (a i), le_trans := assume a b c h₁ h₂ i, le_trans (h₁ i) (h₂ i) } instance pi.partial_order {ι : Type u} {α : ι → Type v} [∀i, partial_order (α i)] : partial_order (Πi, α i) := { le_antisymm := λf g h1 h2, funext (λb, le_antisymm (h1 b) (h2 b)), ..pi.preorder } theorem comp_le_comp_left_of_monotone [preorder α] [preorder β] {f : β → α} {g h : γ → β} (m_f : monotone f) (le_gh : g ≤ h) : has_le.le.{max w u} (f ∘ g) (f ∘ h) := assume x, m_f (le_gh x) section monotone variables [preorder α] [preorder γ] protected theorem monotone.order_dual {f : α → γ} (hf : monotone f) : @monotone (order_dual α) (order_dual γ) _ _ f := λ x y hxy, hf hxy theorem monotone_lam {f : α → β → γ} (m : ∀b, monotone (λa, f a b)) : monotone f := assume a a' h b, m b h theorem monotone_app (f : β → α → γ) (b : β) (m : monotone (λa b, f b a)) : monotone (f b) := assume a a' h, m h b end monotone theorem strict_mono.order_dual [has_lt α] [has_lt β] {f : α → β} (hf : strict_mono f) : @strict_mono (order_dual α) (order_dual β) _ _ f := λ x y hxy, hf hxy /-- Transfer a `preorder` on `β` to a `preorder` on `α` using a function `f : α → β`. -/ def preorder.lift {α β} [preorder β] (f : α → β) : preorder α := { le := λx y, f x ≤ f y, le_refl := λ a, le_refl _, le_trans := λ a b c, le_trans, lt := λx y, f x < f y, lt_iff_le_not_le := λ a b, lt_iff_le_not_le } /-- Transfer a `partial_order` on `β` to a `partial_order` on `α` using an injective function `f : α → β`. -/ def partial_order.lift {α β} [partial_order β] (f : α → β) (inj : injective f) : partial_order α := { le_antisymm := λ a b h₁ h₂, inj (le_antisymm h₁ h₂), .. preorder.lift f } /-- Transfer a `linear_order` on `β` to a `linear_order` on `α` using an injective function `f : α → β`. -/ def linear_order.lift {α β} [linear_order β] (f : α → β) (inj : injective f) : linear_order α := { le_total := λx y, le_total (f x) (f y), .. partial_order.lift f inj } /-- Transfer a `decidable_linear_order` on `β` to a `decidable_linear_order` on `α` using an injective function `f : α → β`. -/ def decidable_linear_order.lift {α β} [decidable_linear_order β] (f : α → β) (inj : injective f) : decidable_linear_order α := { decidable_le := λ x y, show decidable (f x ≤ f y), by apply_instance, decidable_lt := λ x y, show decidable (f x < f y), by apply_instance, decidable_eq := λ x y, decidable_of_iff _ ⟨@inj x y, congr_arg f⟩, .. linear_order.lift f inj } instance subtype.preorder {α} [preorder α] (p : α → Prop) : preorder (subtype p) := preorder.lift subtype.val instance subtype.partial_order {α} [partial_order α] (p : α → Prop) : partial_order (subtype p) := partial_order.lift subtype.val subtype.val_injective instance subtype.linear_order {α} [linear_order α] (p : α → Prop) : linear_order (subtype p) := linear_order.lift subtype.val subtype.val_injective instance subtype.decidable_linear_order {α} [decidable_linear_order α] (p : α → Prop) : decidable_linear_order (subtype p) := decidable_linear_order.lift subtype.val subtype.val_injective instance prod.has_le (α : Type u) (β : Type v) [has_le α] [has_le β] : has_le (α × β) := ⟨λp q, p.1 ≤ q.1 ∧ p.2 ≤ q.2⟩ instance prod.preorder (α : Type u) (β : Type v) [preorder α] [preorder β] : preorder (α × β) := { le_refl := assume ⟨a, b⟩, ⟨le_refl a, le_refl b⟩, le_trans := assume ⟨a, b⟩ ⟨c, d⟩ ⟨e, f⟩ ⟨hac, hbd⟩ ⟨hce, hdf⟩, ⟨le_trans hac hce, le_trans hbd hdf⟩, .. prod.has_le α β } /-- The pointwise partial order on a product. (The lexicographic ordering is defined in order/lexicographic.lean, and the instances are available via the type synonym `lex α β = α × β`.) -/ instance prod.partial_order (α : Type u) (β : Type v) [partial_order α] [partial_order β] : partial_order (α × β) := { le_antisymm := assume ⟨a, b⟩ ⟨c, d⟩ ⟨hac, hbd⟩ ⟨hca, hdb⟩, prod.ext (le_antisymm hac hca) (le_antisymm hbd hdb), .. prod.preorder α β } /-! ### Additional order classes -/ /-- order without a top element; somtimes called cofinal -/ class no_top_order (α : Type u) [preorder α] : Prop := (no_top : ∀a:α, ∃a', a < a') lemma no_top [preorder α] [no_top_order α] : ∀a:α, ∃a', a < a' := no_top_order.no_top instance nonempty_gt {α : Type u} [preorder α] [no_top_order α] (a : α) : nonempty {x // a < x} := nonempty_subtype.2 (no_top a) /-- order without a bottom element; somtimes called coinitial or dense -/ class no_bot_order (α : Type u) [preorder α] : Prop := (no_bot : ∀a:α, ∃a', a' < a) lemma no_bot [preorder α] [no_bot_order α] : ∀a:α, ∃a', a' < a := no_bot_order.no_bot instance order_dual.no_top_order (α : Type u) [preorder α] [no_bot_order α] : no_top_order (order_dual α) := ⟨λ a, @no_bot α _ _ a⟩ instance order_dual.no_bot_order (α : Type u) [preorder α] [no_top_order α] : no_bot_order (order_dual α) := ⟨λ a, @no_top α _ _ a⟩ instance nonempty_lt {α : Type u} [preorder α] [no_bot_order α] (a : α) : nonempty {x // x < a} := nonempty_subtype.2 (no_bot a) /-- An order is dense if there is an element between any pair of distinct elements. -/ class densely_ordered (α : Type u) [preorder α] : Prop := (dense : ∀a₁ a₂:α, a₁ < a₂ → ∃a, a₁ < a ∧ a < a₂) lemma dense [preorder α] [densely_ordered α] : ∀{a₁ a₂:α}, a₁ < a₂ → ∃a, a₁ < a ∧ a < a₂ := densely_ordered.dense instance order_dual.densely_ordered (α : Type u) [preorder α] [densely_ordered α] : densely_ordered (order_dual α) := ⟨λ a₁ a₂ ha, (@dense α _ _ _ _ ha).imp $ λ a, and.symm⟩ lemma le_of_forall_le_of_dense [linear_order α] [densely_ordered α] {a₁ a₂ : α} (h : ∀a₃>a₂, a₁ ≤ a₃) : a₁ ≤ a₂ := le_of_not_gt $ assume ha, let ⟨a, ha₁, ha₂⟩ := dense ha in lt_irrefl a $ lt_of_lt_of_le ‹a < a₁› (h _ ‹a₂ < a›) lemma eq_of_le_of_forall_le_of_dense [linear_order α] [densely_ordered α] {a₁ a₂ : α} (h₁ : a₂ ≤ a₁) (h₂ : ∀a₃>a₂, a₁ ≤ a₃) : a₁ = a₂ := le_antisymm (le_of_forall_le_of_dense h₂) h₁ lemma le_of_forall_ge_of_dense [linear_order α] [densely_ordered α] {a₁ a₂ : α} (h : ∀a₃<a₁, a₂ ≥ a₃) : a₁ ≤ a₂ := le_of_not_gt $ assume ha, let ⟨a, ha₁, ha₂⟩ := dense ha in lt_irrefl a $ lt_of_le_of_lt (h _ ‹a < a₁›) ‹a₂ < a› lemma eq_of_le_of_forall_ge_of_dense [linear_order α] [densely_ordered α] {a₁ a₂ : α} (h₁ : a₂ ≤ a₁) (h₂ : ∀a₃<a₁, a₂ ≥ a₃) : a₁ = a₂ := le_antisymm (le_of_forall_ge_of_dense h₂) h₁ @[nolint ge_or_gt] -- see Note [nolint_ge] lemma dense_or_discrete [linear_order α] (a₁ a₂ : α) : (∃a, a₁ < a ∧ a < a₂) ∨ ((∀a>a₁, a ≥ a₂) ∧ (∀a<a₂, a ≤ a₁)) := classical.or_iff_not_imp_left.2 $ assume h, ⟨assume a ha₁, le_of_not_gt $ assume ha₂, h ⟨a, ha₁, ha₂⟩, assume a ha₂, le_of_not_gt $ assume ha₁, h ⟨a, ha₁, ha₂⟩⟩ variables {s : β → β → Prop} {t : γ → γ → Prop} /-- Any `linear_order` is a noncomputable `decidable_linear_order`. This is not marked as an instance to avoid a loop. -/ noncomputable def classical.DLO (α) [LO : linear_order α] : decidable_linear_order α := { decidable_le := classical.dec_rel _, ..LO }
0ce839e1f1be491a93df02f7faf03c6512e96d3b
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/analysis/normed_space/basic_auto.lean
9e7a5d04f48ac8dfa69db32e4b1d71839865e67b
[]
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
56,714
lean
/- Copyright (c) 2018 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Johannes Hölzl -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.topology.instances.nnreal import Mathlib.topology.algebra.module import Mathlib.topology.metric_space.antilipschitz import Mathlib.PostPort universes u_5 l u_1 u_2 u_3 u_4 u_6 u_7 namespace Mathlib /-! # Normed spaces -/ /-- Auxiliary class, endowing a type `α` with a function `norm : α → ℝ`. This class is designed to be extended in more interesting classes specifying the properties of the norm. -/ class has_norm (α : Type u_5) where norm : α → ℝ /-- A normed group is an additive group endowed with a norm for which `dist x y = ∥x - y∥` defines a metric space structure. -/ class normed_group (α : Type u_5) extends metric_space α, has_norm α, add_comm_group α where dist_eq : ∀ (x y : α), dist x y = norm (x - y) /-- Construct a normed group from a translation invariant distance -/ def normed_group.of_add_dist {α : Type u_1} [has_norm α] [add_comm_group α] [metric_space α] (H1 : ∀ (x : α), norm x = dist x 0) (H2 : ∀ (x y z : α), dist x y ≤ dist (x + z) (y + z)) : normed_group α := normed_group.mk sorry /-- Construct a normed group from a translation invariant distance -/ def normed_group.of_add_dist' {α : Type u_1} [has_norm α] [add_comm_group α] [metric_space α] (H1 : ∀ (x : α), norm x = dist x 0) (H2 : ∀ (x y z : α), dist (x + z) (y + z) ≤ dist x y) : normed_group α := normed_group.mk sorry /-- A normed group can be built from a norm that satisfies algebraic properties. This is formalised in this structure. -/ structure normed_group.core (α : Type u_5) [add_comm_group α] [has_norm α] where norm_eq_zero_iff : ∀ (x : α), norm x = 0 ↔ x = 0 triangle : ∀ (x y : α), norm (x + y) ≤ norm x + norm y norm_neg : ∀ (x : α), norm (-x) = norm x /-- Constructing a normed group from core properties of a norm, i.e., registering the distance and the metric space structure from the norm properties. -/ def normed_group.of_core (α : Type u_1) [add_comm_group α] [has_norm α] (C : normed_group.core α) : normed_group α := normed_group.mk sorry theorem dist_eq_norm {α : Type u_1} [normed_group α] (g : α) (h : α) : dist g h = norm (g - h) := normed_group.dist_eq g h theorem dist_eq_norm' {α : Type u_1} [normed_group α] (g : α) (h : α) : dist g h = norm (h - g) := eq.mpr (id (Eq._oldrec (Eq.refl (dist g h = norm (h - g))) (dist_comm g h))) (eq.mpr (id (Eq._oldrec (Eq.refl (dist h g = norm (h - g))) (dist_eq_norm h g))) (Eq.refl (norm (h - g)))) @[simp] theorem dist_zero_right {α : Type u_1} [normed_group α] (g : α) : dist g 0 = norm g := eq.mpr (id (Eq._oldrec (Eq.refl (dist g 0 = norm g)) (dist_eq_norm g 0))) (eq.mpr (id (Eq._oldrec (Eq.refl (norm (g - 0) = norm g)) (sub_zero g))) (Eq.refl (norm g))) theorem tendsto_norm_cocompact_at_top {α : Type u_1} [normed_group α] [proper_space α] : filter.tendsto norm (filter.cocompact α) filter.at_top := sorry theorem norm_sub_rev {α : Type u_1} [normed_group α] (g : α) (h : α) : norm (g - h) = norm (h - g) := sorry @[simp] theorem norm_neg {α : Type u_1} [normed_group α] (g : α) : norm (-g) = norm g := sorry @[simp] theorem dist_add_left {α : Type u_1} [normed_group α] (g : α) (h₁ : α) (h₂ : α) : dist (g + h₁) (g + h₂) = dist h₁ h₂ := sorry @[simp] theorem dist_add_right {α : Type u_1} [normed_group α] (g₁ : α) (g₂ : α) (h : α) : dist (g₁ + h) (g₂ + h) = dist g₁ g₂ := sorry @[simp] theorem dist_neg_neg {α : Type u_1} [normed_group α] (g : α) (h : α) : dist (-g) (-h) = dist g h := sorry @[simp] theorem dist_sub_left {α : Type u_1} [normed_group α] (g : α) (h₁ : α) (h₂ : α) : dist (g - h₁) (g - h₂) = dist h₁ h₂ := sorry @[simp] theorem dist_sub_right {α : Type u_1} [normed_group α] (g₁ : α) (g₂ : α) (h : α) : dist (g₁ - h) (g₂ - h) = dist g₁ g₂ := sorry /-- Triangle inequality for the norm. -/ theorem norm_add_le {α : Type u_1} [normed_group α] (g : α) (h : α) : norm (g + h) ≤ norm g + norm h := sorry theorem norm_add_le_of_le {α : Type u_1} [normed_group α] {g₁ : α} {g₂ : α} {n₁ : ℝ} {n₂ : ℝ} (H₁ : norm g₁ ≤ n₁) (H₂ : norm g₂ ≤ n₂) : norm (g₁ + g₂) ≤ n₁ + n₂ := le_trans (norm_add_le g₁ g₂) (add_le_add H₁ H₂) theorem dist_add_add_le {α : Type u_1} [normed_group α] (g₁ : α) (g₂ : α) (h₁ : α) (h₂ : α) : dist (g₁ + g₂) (h₁ + h₂) ≤ dist g₁ h₁ + dist g₂ h₂ := sorry theorem dist_add_add_le_of_le {α : Type u_1} [normed_group α] {g₁ : α} {g₂ : α} {h₁ : α} {h₂ : α} {d₁ : ℝ} {d₂ : ℝ} (H₁ : dist g₁ h₁ ≤ d₁) (H₂ : dist g₂ h₂ ≤ d₂) : dist (g₁ + g₂) (h₁ + h₂) ≤ d₁ + d₂ := le_trans (dist_add_add_le g₁ g₂ h₁ h₂) (add_le_add H₁ H₂) theorem dist_sub_sub_le {α : Type u_1} [normed_group α] (g₁ : α) (g₂ : α) (h₁ : α) (h₂ : α) : dist (g₁ - g₂) (h₁ - h₂) ≤ dist g₁ h₁ + dist g₂ h₂ := sorry theorem dist_sub_sub_le_of_le {α : Type u_1} [normed_group α] {g₁ : α} {g₂ : α} {h₁ : α} {h₂ : α} {d₁ : ℝ} {d₂ : ℝ} (H₁ : dist g₁ h₁ ≤ d₁) (H₂ : dist g₂ h₂ ≤ d₂) : dist (g₁ - g₂) (h₁ - h₂) ≤ d₁ + d₂ := le_trans (dist_sub_sub_le g₁ g₂ h₁ h₂) (add_le_add H₁ H₂) theorem abs_dist_sub_le_dist_add_add {α : Type u_1} [normed_group α] (g₁ : α) (g₂ : α) (h₁ : α) (h₂ : α) : abs (dist g₁ h₁ - dist g₂ h₂) ≤ dist (g₁ + g₂) (h₁ + h₂) := sorry @[simp] theorem norm_nonneg {α : Type u_1} [normed_group α] (g : α) : 0 ≤ norm g := eq.mpr (id (Eq._oldrec (Eq.refl (0 ≤ norm g)) (Eq.symm (dist_zero_right g)))) dist_nonneg @[simp] theorem norm_eq_zero {α : Type u_1} [normed_group α] {g : α} : norm g = 0 ↔ g = 0 := dist_zero_right g ▸ dist_eq_zero @[simp] theorem norm_zero {α : Type u_1} [normed_group α] : norm 0 = 0 := iff.mpr norm_eq_zero rfl theorem norm_of_subsingleton {α : Type u_1} [normed_group α] [subsingleton α] (x : α) : norm x = 0 := eq.mpr (id (Eq._oldrec (Eq.refl (norm x = 0)) (subsingleton.elim x 0))) (eq.mpr (id (Eq._oldrec (Eq.refl (norm 0 = 0)) norm_zero)) (Eq.refl 0)) theorem norm_sum_le {α : Type u_1} [normed_group α] {β : Type u_2} (s : finset β) (f : β → α) : norm (finset.sum s fun (a : β) => f a) ≤ finset.sum s fun (a : β) => norm (f a) := finset.le_sum_of_subadditive norm norm_zero norm_add_le theorem norm_sum_le_of_le {α : Type u_1} [normed_group α] {β : Type u_2} (s : finset β) {f : β → α} {n : β → ℝ} (h : ∀ (b : β), b ∈ s → norm (f b) ≤ n b) : norm (finset.sum s fun (b : β) => f b) ≤ finset.sum s fun (b : β) => n b := le_trans (norm_sum_le s f) (finset.sum_le_sum h) @[simp] theorem norm_pos_iff {α : Type u_1} [normed_group α] {g : α} : 0 < norm g ↔ g ≠ 0 := dist_zero_right g ▸ dist_pos @[simp] theorem norm_le_zero_iff {α : Type u_1} [normed_group α] {g : α} : norm g ≤ 0 ↔ g = 0 := eq.mpr (id (Eq._oldrec (Eq.refl (norm g ≤ 0 ↔ g = 0)) (Eq.symm (dist_zero_right g)))) dist_le_zero theorem eq_of_norm_sub_le_zero {α : Type u_1} [normed_group α] {g : α} {h : α} (a : norm (g - h) ≤ 0) : g = h := eq.mpr (id (Eq._oldrec (Eq.refl (g = h)) (Eq.symm (propext sub_eq_zero)))) (eq.mpr (id (Eq._oldrec (Eq.refl (g - h = 0)) (Eq.symm (propext norm_le_zero_iff)))) a) theorem norm_sub_le {α : Type u_1} [normed_group α] (g : α) (h : α) : norm (g - h) ≤ norm g + norm h := sorry theorem norm_sub_le_of_le {α : Type u_1} [normed_group α] {g₁ : α} {g₂ : α} {n₁ : ℝ} {n₂ : ℝ} (H₁ : norm g₁ ≤ n₁) (H₂ : norm g₂ ≤ n₂) : norm (g₁ - g₂) ≤ n₁ + n₂ := le_trans (norm_sub_le g₁ g₂) (add_le_add H₁ H₂) theorem dist_le_norm_add_norm {α : Type u_1} [normed_group α] (g : α) (h : α) : dist g h ≤ norm g + norm h := eq.mpr (id (Eq._oldrec (Eq.refl (dist g h ≤ norm g + norm h)) (dist_eq_norm g h))) (norm_sub_le g h) theorem abs_norm_sub_norm_le {α : Type u_1} [normed_group α] (g : α) (h : α) : abs (norm g - norm h) ≤ norm (g - h) := sorry theorem norm_sub_norm_le {α : Type u_1} [normed_group α] (g : α) (h : α) : norm g - norm h ≤ norm (g - h) := le_trans (le_abs_self (norm g - norm h)) (abs_norm_sub_norm_le g h) theorem dist_norm_norm_le {α : Type u_1} [normed_group α] (g : α) (h : α) : dist (norm g) (norm h) ≤ norm (g - h) := abs_norm_sub_norm_le g h theorem eq_of_norm_sub_eq_zero {α : Type u_1} [normed_group α] {u : α} {v : α} (h : norm (u - v) = 0) : u = v := eq_of_dist_eq_zero (eq.mpr (id (Eq._oldrec (Eq.refl (dist u v = 0)) (dist_eq_norm u v))) h) theorem norm_sub_eq_zero_iff {α : Type u_1} [normed_group α] {u : α} {v : α} : norm (u - v) = 0 ↔ u = v := sorry theorem norm_le_insert {α : Type u_1} [normed_group α] (u : α) (v : α) : norm v ≤ norm u + norm (u - v) := sorry theorem ball_0_eq {α : Type u_1} [normed_group α] (ε : ℝ) : metric.ball 0 ε = set_of fun (x : α) => norm x < ε := sorry theorem mem_ball_iff_norm {α : Type u_1} [normed_group α] {g : α} {h : α} {r : ℝ} : h ∈ metric.ball g r ↔ norm (h - g) < r := eq.mpr (id (Eq._oldrec (Eq.refl (h ∈ metric.ball g r ↔ norm (h - g) < r)) (propext metric.mem_ball))) (eq.mpr (id (Eq._oldrec (Eq.refl (dist h g < r ↔ norm (h - g) < r)) (dist_eq_norm h g))) (iff.refl (norm (h - g) < r))) theorem mem_ball_iff_norm' {α : Type u_1} [normed_group α] {g : α} {h : α} {r : ℝ} : h ∈ metric.ball g r ↔ norm (g - h) < r := eq.mpr (id (Eq._oldrec (Eq.refl (h ∈ metric.ball g r ↔ norm (g - h) < r)) (propext metric.mem_ball'))) (eq.mpr (id (Eq._oldrec (Eq.refl (dist g h < r ↔ norm (g - h) < r)) (dist_eq_norm g h))) (iff.refl (norm (g - h) < r))) theorem mem_closed_ball_iff_norm {α : Type u_1} [normed_group α] {g : α} {h : α} {r : ℝ} : h ∈ metric.closed_ball g r ↔ norm (h - g) ≤ r := eq.mpr (id (Eq._oldrec (Eq.refl (h ∈ metric.closed_ball g r ↔ norm (h - g) ≤ r)) (propext metric.mem_closed_ball))) (eq.mpr (id (Eq._oldrec (Eq.refl (dist h g ≤ r ↔ norm (h - g) ≤ r)) (dist_eq_norm h g))) (iff.refl (norm (h - g) ≤ r))) theorem mem_closed_ball_iff_norm' {α : Type u_1} [normed_group α] {g : α} {h : α} {r : ℝ} : h ∈ metric.closed_ball g r ↔ norm (g - h) ≤ r := eq.mpr (id (Eq._oldrec (Eq.refl (h ∈ metric.closed_ball g r ↔ norm (g - h) ≤ r)) (propext metric.mem_closed_ball'))) (eq.mpr (id (Eq._oldrec (Eq.refl (dist g h ≤ r ↔ norm (g - h) ≤ r)) (dist_eq_norm g h))) (iff.refl (norm (g - h) ≤ r))) theorem norm_le_of_mem_closed_ball {α : Type u_1} [normed_group α] {g : α} {h : α} {r : ℝ} (H : h ∈ metric.closed_ball g r) : norm h ≤ norm g + r := sorry theorem norm_lt_of_mem_ball {α : Type u_1} [normed_group α] {g : α} {h : α} {r : ℝ} (H : h ∈ metric.ball g r) : norm h < norm g + r := sorry @[simp] theorem mem_sphere_iff_norm {α : Type u_1} [normed_group α] (v : α) (w : α) (r : ℝ) : w ∈ metric.sphere v r ↔ norm (w - v) = r := sorry @[simp] theorem mem_sphere_zero_iff_norm {α : Type u_1} [normed_group α] {w : α} {r : ℝ} : w ∈ metric.sphere 0 r ↔ norm w = r := sorry @[simp] theorem norm_eq_of_mem_sphere {α : Type u_1} [normed_group α] {r : ℝ} (x : ↥(metric.sphere 0 r)) : norm ↑x = r := iff.mp mem_sphere_zero_iff_norm (subtype.property x) theorem nonzero_of_mem_sphere {α : Type u_1} [normed_group α] {r : ℝ} (hr : 0 < r) (x : ↥(metric.sphere 0 r)) : ↑x ≠ 0 := eq.mpr (id (Eq._oldrec (Eq.refl (↑x ≠ 0)) (Eq.symm (propext norm_pos_iff)))) (eq.mpr (id (Eq._oldrec (Eq.refl (0 < norm ↑x)) (norm_eq_of_mem_sphere x))) hr) theorem nonzero_of_mem_unit_sphere {α : Type u_1} [normed_group α] (x : ↥(metric.sphere 0 1)) : ↑x ≠ 0 := nonzero_of_mem_sphere (eq.mpr (id (eq_true_intro zero_lt_one')) trivial) x /-- We equip the sphere, in a normed group, with a formal operation of negation, namely the antipodal map. -/ protected instance metric.sphere.has_neg {α : Type u_1} [normed_group α] {r : ℝ} : Neg ↥(metric.sphere 0 r) := { neg := fun (w : ↥(metric.sphere 0 r)) => { val := -↑w, property := sorry } } @[simp] theorem coe_neg_sphere {α : Type u_1} [normed_group α] {r : ℝ} (v : ↥(metric.sphere 0 r)) : ↑(-v) = -↑v := rfl theorem normed_group.tendsto_nhds_zero {α : Type u_1} {γ : Type u_3} [normed_group α] {f : γ → α} {l : filter γ} : filter.tendsto f l (nhds 0) ↔ ∀ (ε : ℝ), ε > 0 → filter.eventually (fun (x : γ) => norm (f x) < ε) l := sorry theorem normed_group.tendsto_nhds_nhds {α : Type u_1} {β : Type u_2} [normed_group α] [normed_group β] {f : α → β} {x : α} {y : β} : filter.tendsto f (nhds x) (nhds y) ↔ ∀ (ε : ℝ) (H : ε > 0), ∃ (δ : ℝ), ∃ (H : δ > 0), ∀ (x' : α), norm (x' - x) < δ → norm (f x' - y) < ε := sorry /-- A homomorphism `f` of normed groups is Lipschitz, if there exists a constant `C` such that for all `x`, one has `∥f x∥ ≤ C * ∥x∥`. The analogous condition for a linear map of normed spaces is in `normed_space.operator_norm`. -/ theorem add_monoid_hom.lipschitz_of_bound {α : Type u_1} {β : Type u_2} [normed_group α] [normed_group β] (f : α →+ β) (C : ℝ) (h : ∀ (x : α), norm (coe_fn f x) ≤ C * norm x) : lipschitz_with (nnreal.of_real C) ⇑f := sorry theorem lipschitz_on_with_iff_norm_sub_le {α : Type u_1} {β : Type u_2} [normed_group α] [normed_group β] {f : α → β} {C : nnreal} {s : set α} : lipschitz_on_with C f s ↔ ∀ (x : α), x ∈ s → ∀ (y : α), y ∈ s → norm (f x - f y) ≤ ↑C * norm (x - y) := sorry theorem lipschitz_on_with.norm_sub_le {α : Type u_1} {β : Type u_2} [normed_group α] [normed_group β] {f : α → β} {C : nnreal} {s : set α} (h : lipschitz_on_with C f s) {x : α} {y : α} (x_in : x ∈ s) (y_in : y ∈ s) : norm (f x - f y) ≤ ↑C * norm (x - y) := iff.mp lipschitz_on_with_iff_norm_sub_le h x x_in y y_in /-- A homomorphism `f` of normed groups is continuous, if there exists a constant `C` such that for all `x`, one has `∥f x∥ ≤ C * ∥x∥`. The analogous condition for a linear map of normed spaces is in `normed_space.operator_norm`. -/ theorem add_monoid_hom.continuous_of_bound {α : Type u_1} {β : Type u_2} [normed_group α] [normed_group β] (f : α →+ β) (C : ℝ) (h : ∀ (x : α), norm (coe_fn f x) ≤ C * norm x) : continuous ⇑f := lipschitz_with.continuous (add_monoid_hom.lipschitz_of_bound f C h) /-- Version of the norm taking values in nonnegative reals. -/ def nnnorm {α : Type u_1} [normed_group α] (a : α) : nnreal := { val := norm a, property := norm_nonneg a } @[simp] theorem coe_nnnorm {α : Type u_1} [normed_group α] (a : α) : ↑(nnnorm a) = norm a := rfl theorem nndist_eq_nnnorm {α : Type u_1} [normed_group α] (a : α) (b : α) : nndist a b = nnnorm (a - b) := nnreal.eq (dist_eq_norm a b) @[simp] theorem nnnorm_eq_zero {α : Type u_1} [normed_group α] {a : α} : nnnorm a = 0 ↔ a = 0 := sorry @[simp] theorem nnnorm_zero {α : Type u_1} [normed_group α] : nnnorm 0 = 0 := nnreal.eq norm_zero theorem nnnorm_add_le {α : Type u_1} [normed_group α] (g : α) (h : α) : nnnorm (g + h) ≤ nnnorm g + nnnorm h := iff.mpr nnreal.coe_le_coe (norm_add_le g h) @[simp] theorem nnnorm_neg {α : Type u_1} [normed_group α] (g : α) : nnnorm (-g) = nnnorm g := nnreal.eq (norm_neg g) theorem nndist_nnnorm_nnnorm_le {α : Type u_1} [normed_group α] (g : α) (h : α) : nndist (nnnorm g) (nnnorm h) ≤ nnnorm (g - h) := iff.mpr nnreal.coe_le_coe (dist_norm_norm_le g h) theorem of_real_norm_eq_coe_nnnorm {β : Type u_2} [normed_group β] (x : β) : ennreal.of_real (norm x) = ↑(nnnorm x) := ennreal.of_real_eq_coe_nnreal (norm_nonneg x) theorem edist_eq_coe_nnnorm_sub {β : Type u_2} [normed_group β] (x : β) (y : β) : edist x y = ↑(nnnorm (x - y)) := sorry theorem edist_eq_coe_nnnorm {β : Type u_2} [normed_group β] (x : β) : edist x 0 = ↑(nnnorm x) := eq.mpr (id (Eq._oldrec (Eq.refl (edist x 0 = ↑(nnnorm x))) (edist_eq_coe_nnnorm_sub x 0))) (eq.mpr (id (Eq._oldrec (Eq.refl (↑(nnnorm (x - 0)) = ↑(nnnorm x))) (sub_zero x))) (Eq.refl ↑(nnnorm x))) theorem mem_emetric_ball_0_iff {β : Type u_2} [normed_group β] {x : β} {r : ennreal} : x ∈ emetric.ball 0 r ↔ ↑(nnnorm x) < r := eq.mpr (id (Eq._oldrec (Eq.refl (x ∈ emetric.ball 0 r ↔ ↑(nnnorm x) < r)) (propext emetric.mem_ball))) (eq.mpr (id (Eq._oldrec (Eq.refl (edist x 0 < r ↔ ↑(nnnorm x) < r)) (edist_eq_coe_nnnorm x))) (iff.refl (↑(nnnorm x) < r))) theorem nndist_add_add_le {α : Type u_1} [normed_group α] (g₁ : α) (g₂ : α) (h₁ : α) (h₂ : α) : nndist (g₁ + g₂) (h₁ + h₂) ≤ nndist g₁ h₁ + nndist g₂ h₂ := iff.mpr nnreal.coe_le_coe (dist_add_add_le g₁ g₂ h₁ h₂) theorem edist_add_add_le {α : Type u_1} [normed_group α] (g₁ : α) (g₂ : α) (h₁ : α) (h₂ : α) : edist (g₁ + g₂) (h₁ + h₂) ≤ edist g₁ h₁ + edist g₂ h₂ := sorry theorem nnnorm_sum_le {α : Type u_1} [normed_group α] {β : Type u_2} (s : finset β) (f : β → α) : nnnorm (finset.sum s fun (a : β) => f a) ≤ finset.sum s fun (a : β) => nnnorm (f a) := finset.le_sum_of_subadditive nnnorm nnnorm_zero nnnorm_add_le theorem lipschitz_with.neg {β : Type u_2} [normed_group β] {α : Type u_1} [emetric_space α] {K : nnreal} {f : α → β} (hf : lipschitz_with K f) : lipschitz_with K fun (x : α) => -f x := sorry theorem lipschitz_with.add {β : Type u_2} [normed_group β] {α : Type u_1} [emetric_space α] {Kf : nnreal} {f : α → β} (hf : lipschitz_with Kf f) {Kg : nnreal} {g : α → β} (hg : lipschitz_with Kg g) : lipschitz_with (Kf + Kg) fun (x : α) => f x + g x := fun (x y : α) => trans_rel_left LessEq (le_trans (edist_add_add_le (f x) (g x) (f y) (g y)) (add_le_add (hf x y) (hg x y))) (Eq.symm (add_mul (↑Kf) (↑Kg) (edist x y))) theorem lipschitz_with.sub {β : Type u_2} [normed_group β] {α : Type u_1} [emetric_space α] {Kf : nnreal} {f : α → β} (hf : lipschitz_with Kf f) {Kg : nnreal} {g : α → β} (hg : lipschitz_with Kg g) : lipschitz_with (Kf + Kg) fun (x : α) => f x - g x := sorry theorem antilipschitz_with.add_lipschitz_with {β : Type u_2} [normed_group β] {α : Type u_1} [metric_space α] {Kf : nnreal} {f : α → β} (hf : antilipschitz_with Kf f) {Kg : nnreal} {g : α → β} (hg : lipschitz_with Kg g) (hK : Kg < (Kf⁻¹)) : antilipschitz_with (Kf⁻¹ - Kg⁻¹) fun (x : α) => f x + g x := sorry /-- A submodule of a normed group is also a normed group, with the restriction of the norm. As all instances can be inferred from the submodule `s`, they are put as implicit instead of typeclasses. -/ protected instance submodule.normed_group {𝕜 : Type u_1} {_x : ring 𝕜} {E : Type u_2} [normed_group E] : {_x_1 : module 𝕜 E} → (s : submodule 𝕜 E) → normed_group ↥s := fun (s : submodule 𝕜 E) => normed_group.mk sorry /-- normed group instance on the product of two normed groups, using the sup norm. -/ protected instance prod.normed_group {α : Type u_1} {β : Type u_2} [normed_group α] [normed_group β] : normed_group (α × β) := normed_group.mk sorry theorem prod.norm_def {α : Type u_1} {β : Type u_2} [normed_group α] [normed_group β] (x : α × β) : norm x = max (norm (prod.fst x)) (norm (prod.snd x)) := rfl theorem prod.nnnorm_def {α : Type u_1} {β : Type u_2} [normed_group α] [normed_group β] (x : α × β) : nnnorm x = max (nnnorm (prod.fst x)) (nnnorm (prod.snd x)) := sorry theorem norm_fst_le {α : Type u_1} {β : Type u_2} [normed_group α] [normed_group β] (x : α × β) : norm (prod.fst x) ≤ norm x := le_max_left (norm (prod.fst x)) (norm (prod.snd x)) theorem norm_snd_le {α : Type u_1} {β : Type u_2} [normed_group α] [normed_group β] (x : α × β) : norm (prod.snd x) ≤ norm x := le_max_right (norm (prod.fst x)) (norm (prod.snd x)) theorem norm_prod_le_iff {α : Type u_1} {β : Type u_2} [normed_group α] [normed_group β] {x : α × β} {r : ℝ} : norm x ≤ r ↔ norm (prod.fst x) ≤ r ∧ norm (prod.snd x) ≤ r := max_le_iff /-- normed group instance on the product of finitely many normed groups, using the sup norm. -/ protected instance pi.normed_group {ι : Type u_4} {π : ι → Type u_1} [fintype ι] [(i : ι) → normed_group (π i)] : normed_group ((i : ι) → π i) := normed_group.mk sorry /-- The norm of an element in a product space is `≤ r` if and only if the norm of each component is. -/ theorem pi_norm_le_iff {ι : Type u_4} {π : ι → Type u_1} [fintype ι] [(i : ι) → normed_group (π i)] {r : ℝ} (hr : 0 ≤ r) {x : (i : ι) → π i} : norm x ≤ r ↔ ∀ (i : ι), norm (x i) ≤ r := sorry /-- The norm of an element in a product space is `< r` if and only if the norm of each component is. -/ theorem pi_norm_lt_iff {ι : Type u_4} {π : ι → Type u_1} [fintype ι] [(i : ι) → normed_group (π i)] {r : ℝ} (hr : 0 < r) {x : (i : ι) → π i} : norm x < r ↔ ∀ (i : ι), norm (x i) < r := sorry theorem norm_le_pi_norm {ι : Type u_4} {π : ι → Type u_1} [fintype ι] [(i : ι) → normed_group (π i)] (x : (i : ι) → π i) (i : ι) : norm (x i) ≤ norm x := iff.mp (pi_norm_le_iff (norm_nonneg x)) (le_refl (norm x)) i @[simp] theorem pi_norm_const {α : Type u_1} {ι : Type u_4} [normed_group α] [Nonempty ι] [fintype ι] (a : α) : (norm fun (i : ι) => a) = norm a := sorry @[simp] theorem pi_nnnorm_const {α : Type u_1} {ι : Type u_4} [normed_group α] [Nonempty ι] [fintype ι] (a : α) : (nnnorm fun (i : ι) => a) = nnnorm a := nnreal.eq (pi_norm_const a) theorem tendsto_iff_norm_tendsto_zero {β : Type u_2} {ι : Type u_4} [normed_group β] {f : ι → β} {a : filter ι} {b : β} : filter.tendsto f a (nhds b) ↔ filter.tendsto (fun (e : ι) => norm (f e - b)) a (nhds 0) := sorry theorem tendsto_zero_iff_norm_tendsto_zero {β : Type u_2} {γ : Type u_3} [normed_group β] {f : γ → β} {a : filter γ} : filter.tendsto f a (nhds 0) ↔ filter.tendsto (fun (e : γ) => norm (f e)) a (nhds 0) := sorry /-- Special case of the sandwich theorem: if the norm of `f` is eventually bounded by a real function `g` which tends to `0`, then `f` tends to `0`. In this pair of lemmas (`squeeze_zero_norm'` and `squeeze_zero_norm`), following a convention of similar lemmas in `topology.metric_space.basic` and `topology.algebra.ordered`, the `'` version is phrased using "eventually" and the non-`'` version is phrased absolutely. -/ theorem squeeze_zero_norm' {α : Type u_1} {γ : Type u_3} [normed_group α] {f : γ → α} {g : γ → ℝ} {t₀ : filter γ} (h : filter.eventually (fun (n : γ) => norm (f n) ≤ g n) t₀) (h' : filter.tendsto g t₀ (nhds 0)) : filter.tendsto f t₀ (nhds 0) := iff.mpr tendsto_zero_iff_norm_tendsto_zero (squeeze_zero' (filter.eventually_of_forall fun (n : γ) => norm_nonneg (f n)) h h') /-- Special case of the sandwich theorem: if the norm of `f` is bounded by a real function `g` which tends to `0`, then `f` tends to `0`. -/ theorem squeeze_zero_norm {α : Type u_1} {γ : Type u_3} [normed_group α] {f : γ → α} {g : γ → ℝ} {t₀ : filter γ} (h : ∀ (n : γ), norm (f n) ≤ g n) (h' : filter.tendsto g t₀ (nhds 0)) : filter.tendsto f t₀ (nhds 0) := squeeze_zero_norm' (filter.eventually_of_forall h) h' theorem tendsto_norm_sub_self {α : Type u_1} [normed_group α] (x : α) : filter.tendsto (fun (g : α) => norm (g - x)) (nhds x) (nhds 0) := sorry theorem tendsto_norm {α : Type u_1} [normed_group α] {x : α} : filter.tendsto (fun (g : α) => norm g) (nhds x) (nhds (norm x)) := sorry theorem tendsto_norm_zero {α : Type u_1} [normed_group α] : filter.tendsto (fun (g : α) => norm g) (nhds 0) (nhds 0) := sorry theorem continuous_norm {α : Type u_1} [normed_group α] : continuous fun (g : α) => norm g := sorry theorem continuous_nnnorm {α : Type u_1} [normed_group α] : continuous nnnorm := continuous_subtype_mk (fun (a : α) => norm_nonneg a) continuous_norm theorem tendsto_norm_nhds_within_zero {α : Type u_1} [normed_group α] : filter.tendsto norm (nhds_within 0 (singleton 0ᶜ)) (nhds_within 0 (set.Ioi 0)) := filter.tendsto.inf (continuous.tendsto' continuous_norm 0 0 norm_zero) (iff.mpr filter.tendsto_principal_principal fun (x : α) => iff.mpr norm_pos_iff) theorem filter.tendsto.norm {α : Type u_1} {γ : Type u_3} [normed_group α] {l : filter γ} {f : γ → α} {a : α} (h : filter.tendsto f l (nhds a)) : filter.tendsto (fun (x : γ) => norm (f x)) l (nhds (norm a)) := filter.tendsto.comp tendsto_norm h theorem filter.tendsto.nnnorm {α : Type u_1} {γ : Type u_3} [normed_group α] {l : filter γ} {f : γ → α} {a : α} (h : filter.tendsto f l (nhds a)) : filter.tendsto (fun (x : γ) => nnnorm (f x)) l (nhds (nnnorm a)) := filter.tendsto.comp (continuous.continuous_at continuous_nnnorm) h theorem continuous.norm {α : Type u_1} {γ : Type u_3} [normed_group α] [topological_space γ] {f : γ → α} (h : continuous f) : continuous fun (x : γ) => norm (f x) := continuous.comp continuous_norm h theorem continuous.nnnorm {α : Type u_1} {γ : Type u_3} [normed_group α] [topological_space γ] {f : γ → α} (h : continuous f) : continuous fun (x : γ) => nnnorm (f x) := continuous.comp continuous_nnnorm h theorem continuous_at.norm {α : Type u_1} {γ : Type u_3} [normed_group α] [topological_space γ] {f : γ → α} {a : γ} (h : continuous_at f a) : continuous_at (fun (x : γ) => norm (f x)) a := filter.tendsto.norm h theorem continuous_at.nnnorm {α : Type u_1} {γ : Type u_3} [normed_group α] [topological_space γ] {f : γ → α} {a : γ} (h : continuous_at f a) : continuous_at (fun (x : γ) => nnnorm (f x)) a := filter.tendsto.nnnorm h theorem continuous_within_at.norm {α : Type u_1} {γ : Type u_3} [normed_group α] [topological_space γ] {f : γ → α} {s : set γ} {a : γ} (h : continuous_within_at f s a) : continuous_within_at (fun (x : γ) => norm (f x)) s a := filter.tendsto.norm h theorem continuous_within_at.nnnorm {α : Type u_1} {γ : Type u_3} [normed_group α] [topological_space γ] {f : γ → α} {s : set γ} {a : γ} (h : continuous_within_at f s a) : continuous_within_at (fun (x : γ) => nnnorm (f x)) s a := filter.tendsto.nnnorm h theorem continuous_on.norm {α : Type u_1} {γ : Type u_3} [normed_group α] [topological_space γ] {f : γ → α} {s : set γ} (h : continuous_on f s) : continuous_on (fun (x : γ) => norm (f x)) s := fun (x : γ) (hx : x ∈ s) => continuous_within_at.norm (h x hx) theorem continuous_on.nnnorm {α : Type u_1} {γ : Type u_3} [normed_group α] [topological_space γ] {f : γ → α} {s : set γ} (h : continuous_on f s) : continuous_on (fun (x : γ) => nnnorm (f x)) s := fun (x : γ) (hx : x ∈ s) => continuous_within_at.nnnorm (h x hx) /-- If `∥y∥→∞`, then we can assume `y≠x` for any fixed `x`. -/ theorem eventually_ne_of_tendsto_norm_at_top {α : Type u_1} {γ : Type u_3} [normed_group α] {l : filter γ} {f : γ → α} (h : filter.tendsto (fun (y : γ) => norm (f y)) l filter.at_top) (x : α) : filter.eventually (fun (y : γ) => f y ≠ x) l := sorry /-- A normed group is a uniform additive group, i.e., addition and subtraction are uniformly continuous. -/ protected instance normed_uniform_group {α : Type u_1} [normed_group α] : uniform_add_group α := uniform_add_group.mk (lipschitz_with.uniform_continuous (lipschitz_with.sub lipschitz_with.prod_fst lipschitz_with.prod_snd)) protected instance normed_top_monoid {α : Type u_1} [normed_group α] : has_continuous_add α := topological_add_group.to_has_continuous_add protected instance normed_top_group {α : Type u_1} [normed_group α] : topological_add_group α := uniform_add_group.to_topological_add_group theorem nat.norm_cast_le {α : Type u_1} [normed_group α] [HasOne α] (n : ℕ) : norm ↑n ≤ ↑n * norm 1 := sorry /-- A normed ring is a ring endowed with a norm which satisfies the inequality `∥x y∥ ≤ ∥x∥ ∥y∥`. -/ class normed_ring (α : Type u_5) extends ring α, has_norm α, metric_space α where dist_eq : ∀ (x y : α), dist x y = norm (x - y) norm_mul : ∀ (a b : α), norm (a * b) ≤ norm a * norm b /-- A normed commutative ring is a commutative ring endowed with a norm which satisfies the inequality `∥x y∥ ≤ ∥x∥ ∥y∥`. -/ class normed_comm_ring (α : Type u_5) extends normed_ring α where mul_comm : ∀ (x y : α), x * y = y * x /-- A mixin class with the axiom `∥1∥ = 1`. Many `normed_ring`s and all `normed_field`s satisfy this axiom. -/ class norm_one_class (α : Type u_5) [has_norm α] [HasOne α] where norm_one : norm 1 = 1 @[simp] theorem nnnorm_one {α : Type u_1} [normed_group α] [HasOne α] [norm_one_class α] : nnnorm 1 = 1 := nnreal.eq norm_one protected instance normed_comm_ring.to_comm_ring {α : Type u_1} [β : normed_comm_ring α] : comm_ring α := comm_ring.mk ring.add sorry ring.zero sorry sorry ring.neg ring.sub sorry sorry ring.mul sorry ring.one sorry sorry sorry sorry normed_comm_ring.mul_comm protected instance normed_ring.to_normed_group {α : Type u_1} [β : normed_ring α] : normed_group α := normed_group.mk normed_ring.dist_eq protected instance prod.norm_one_class {α : Type u_1} {β : Type u_2} [normed_group α] [HasOne α] [norm_one_class α] [normed_group β] [HasOne β] [norm_one_class β] : norm_one_class (α × β) := norm_one_class.mk (eq.mpr (id (Eq.trans ((fun (a a_1 : ℝ) (e_1 : a = a_1) (ᾰ ᾰ_1 : ℝ) (e_2 : ᾰ = ᾰ_1) => congr (congr_arg Eq e_1) e_2) (norm 1) 1 (Eq.trans (Eq.trans (prod.norm_def 1) ((fun (a a_1 : ℝ) (e_2 : a = a_1) (b b_1 : ℝ) (e_3 : b = b_1) => congr (congr_arg max e_2) e_3) (norm (prod.fst 1)) 1 (Eq.trans ((fun (ᾰ ᾰ_1 : α) (e_2 : ᾰ = ᾰ_1) => congr_arg norm e_2) (prod.fst 1) 1 prod.fst_one) norm_one) (norm (prod.snd 1)) 1 (Eq.trans ((fun (ᾰ ᾰ_1 : β) (e_2 : ᾰ = ᾰ_1) => congr_arg norm e_2) (prod.snd 1) 1 prod.snd_one) norm_one))) (max_eq_right (le_refl 1))) 1 1 (Eq.refl 1)) (propext (eq_self_iff_true 1)))) trivial) theorem norm_mul_le {α : Type u_1} [normed_ring α] (a : α) (b : α) : norm (a * b) ≤ norm a * norm b := normed_ring.norm_mul a b theorem list.norm_prod_le' {α : Type u_1} [normed_ring α] {l : List α} : l ≠ [] → norm (list.prod l) ≤ list.prod (list.map norm l) := sorry theorem list.norm_prod_le {α : Type u_1} [normed_ring α] [norm_one_class α] (l : List α) : norm (list.prod l) ≤ list.prod (list.map norm l) := sorry theorem finset.norm_prod_le' {ι : Type u_4} {α : Type u_1} [normed_comm_ring α] (s : finset ι) (hs : finset.nonempty s) (f : ι → α) : norm (finset.prod s fun (i : ι) => f i) ≤ finset.prod s fun (i : ι) => norm (f i) := sorry theorem finset.norm_prod_le {ι : Type u_4} {α : Type u_1} [normed_comm_ring α] [norm_one_class α] (s : finset ι) (f : ι → α) : norm (finset.prod s fun (i : ι) => f i) ≤ finset.prod s fun (i : ι) => norm (f i) := sorry /-- If `α` is a normed ring, then `∥a^n∥≤ ∥a∥^n` for `n > 0`. See also `norm_pow_le`. -/ theorem norm_pow_le' {α : Type u_1} [normed_ring α] (a : α) {n : ℕ} : 0 < n → norm (a ^ n) ≤ norm a ^ n := sorry /-- If `α` is a normed ring with `∥1∥=1`, then `∥a^n∥≤ ∥a∥^n`. See also `norm_pow_le'`. -/ theorem norm_pow_le {α : Type u_1} [normed_ring α] [norm_one_class α] (a : α) (n : ℕ) : norm (a ^ n) ≤ norm a ^ n := sorry theorem eventually_norm_pow_le {α : Type u_1} [normed_ring α] (a : α) : filter.eventually (fun (n : ℕ) => norm (a ^ n) ≤ norm a ^ n) filter.at_top := iff.mpr filter.eventually_at_top (Exists.intro 1 fun (b : ℕ) (h : b ≥ 1) => norm_pow_le' a (iff.mp nat.succ_le_iff h)) theorem units.norm_pos {α : Type u_1} [normed_ring α] [nontrivial α] (x : units α) : 0 < norm ↑x := iff.mpr norm_pos_iff (units.ne_zero x) /-- In a normed ring, the left-multiplication `add_monoid_hom` is bounded. -/ theorem mul_left_bound {α : Type u_1} [normed_ring α] (x : α) (y : α) : norm (coe_fn (add_monoid_hom.mul_left x) y) ≤ norm x * norm y := norm_mul_le x /-- In a normed ring, the right-multiplication `add_monoid_hom` is bounded. -/ theorem mul_right_bound {α : Type u_1} [normed_ring α] (x : α) (y : α) : norm (coe_fn (add_monoid_hom.mul_right x) y) ≤ norm x * norm y := sorry /-- Normed ring structure on the product of two normed rings, using the sup norm. -/ protected instance prod.normed_ring {α : Type u_1} {β : Type u_2} [normed_ring α] [normed_ring β] : normed_ring (α × β) := normed_ring.mk sorry sorry protected instance normed_ring_top_monoid {α : Type u_1} [normed_ring α] : has_continuous_mul α := sorry /-- A normed ring is a topological ring. -/ protected instance normed_top_ring {α : Type u_1} [normed_ring α] : topological_ring α := sorry /-- A normed field is a field with a norm satisfying ∥x y∥ = ∥x∥ ∥y∥. -/ class normed_field (α : Type u_5) extends metric_space α, has_norm α, field α where dist_eq : ∀ (x y : α), dist x y = norm (x - y) norm_mul' : ∀ (a b : α), norm (a * b) = norm a * norm b /-- A nondiscrete normed field is a normed field in which there is an element of norm different from `0` and `1`. This makes it possible to bring any element arbitrarily close to `0` by multiplication by the powers of any element, and thus to relate algebra and topology. -/ class nondiscrete_normed_field (α : Type u_5) extends normed_field α where non_trivial : ∃ (x : α), 1 < norm x namespace normed_field @[simp] theorem norm_mul {α : Type u_1} [normed_field α] (a : α) (b : α) : norm (a * b) = norm a * norm b := norm_mul' a b protected instance to_normed_comm_ring {α : Type u_1} [normed_field α] : normed_comm_ring α := normed_comm_ring.mk sorry protected instance to_norm_one_class {α : Type u_1} [normed_field α] : norm_one_class α := norm_one_class.mk (mul_left_cancel' (mt (iff.mp norm_eq_zero) one_ne_zero) (eq.mpr (id (Eq._oldrec (Eq.refl (norm 1 * norm 1 = norm 1 * 1)) (Eq.symm (norm_mul 1 1)))) (eq.mpr (id (Eq._oldrec (Eq.refl (norm (1 * 1) = norm 1 * 1)) (mul_one 1))) (eq.mpr (id (Eq._oldrec (Eq.refl (norm 1 = norm 1 * 1)) (mul_one (norm 1)))) (Eq.refl (norm 1)))))) @[simp] theorem nnnorm_mul {α : Type u_1} [normed_field α] (a : α) (b : α) : nnnorm (a * b) = nnnorm a * nnnorm b := nnreal.eq (norm_mul a b) /-- `norm` as a `monoid_hom`. -/ @[simp] theorem norm_hom_apply {α : Type u_1} [normed_field α] : ∀ (ᾰ : α), coe_fn norm_hom ᾰ = norm ᾰ := fun (ᾰ : α) => Eq.refl (coe_fn norm_hom ᾰ) /-- `nnnorm` as a `monoid_hom`. -/ def nnnorm_hom {α : Type u_1} [normed_field α] : monoid_with_zero_hom α nnreal := monoid_with_zero_hom.mk nnnorm sorry sorry nnnorm_mul @[simp] theorem norm_pow {α : Type u_1} [normed_field α] (a : α) (n : ℕ) : norm (a ^ n) = norm a ^ n := monoid_hom.map_pow (monoid_with_zero_hom.to_monoid_hom norm_hom) a @[simp] theorem nnnorm_pow {α : Type u_1} [normed_field α] (a : α) (n : ℕ) : nnnorm (a ^ n) = nnnorm a ^ n := monoid_hom.map_pow (monoid_with_zero_hom.to_monoid_hom nnnorm_hom) a n @[simp] theorem norm_prod {α : Type u_1} {β : Type u_2} [normed_field α] (s : finset β) (f : β → α) : norm (finset.prod s fun (b : β) => f b) = finset.prod s fun (b : β) => norm (f b) := monoid_hom.map_prod (monoid_with_zero_hom.to_monoid_hom norm_hom) f s @[simp] theorem nnnorm_prod {α : Type u_1} {β : Type u_2} [normed_field α] (s : finset β) (f : β → α) : nnnorm (finset.prod s fun (b : β) => f b) = finset.prod s fun (b : β) => nnnorm (f b) := monoid_hom.map_prod (monoid_with_zero_hom.to_monoid_hom nnnorm_hom) f s @[simp] theorem norm_div {α : Type u_1} [normed_field α] (a : α) (b : α) : norm (a / b) = norm a / norm b := monoid_with_zero_hom.map_div norm_hom a b @[simp] theorem nnnorm_div {α : Type u_1} [normed_field α] (a : α) (b : α) : nnnorm (a / b) = nnnorm a / nnnorm b := monoid_with_zero_hom.map_div nnnorm_hom a b @[simp] theorem norm_inv {α : Type u_1} [normed_field α] (a : α) : norm (a⁻¹) = (norm a⁻¹) := monoid_with_zero_hom.map_inv' norm_hom a @[simp] theorem nnnorm_inv {α : Type u_1} [normed_field α] (a : α) : nnnorm (a⁻¹) = (nnnorm a⁻¹) := sorry @[simp] theorem norm_fpow {α : Type u_1} [normed_field α] (a : α) (n : ℤ) : norm (a ^ n) = norm a ^ n := monoid_with_zero_hom.map_fpow norm_hom @[simp] theorem nnnorm_fpow {α : Type u_1} [normed_field α] (a : α) (n : ℤ) : nnnorm (a ^ n) = nnnorm a ^ n := monoid_with_zero_hom.map_fpow nnnorm_hom protected instance has_continuous_inv' {α : Type u_1} [normed_field α] : has_continuous_inv' α := has_continuous_inv'.mk sorry end normed_field theorem normed_field.exists_one_lt_norm (α : Type u_1) [nondiscrete_normed_field α] : ∃ (x : α), 1 < norm x := nondiscrete_normed_field.non_trivial theorem normed_field.exists_norm_lt_one (α : Type u_1) [nondiscrete_normed_field α] : ∃ (x : α), 0 < norm x ∧ norm x < 1 := sorry theorem normed_field.exists_lt_norm (α : Type u_1) [nondiscrete_normed_field α] (r : ℝ) : ∃ (x : α), r < norm x := sorry theorem normed_field.exists_norm_lt (α : Type u_1) [nondiscrete_normed_field α] {r : ℝ} (hr : 0 < r) : ∃ (x : α), 0 < norm x ∧ norm x < r := sorry instance normed_field.punctured_nhds_ne_bot {α : Type u_1} [nondiscrete_normed_field α] (x : α) : filter.ne_bot (nhds_within x (singleton xᶜ)) := sorry instance normed_field.nhds_within_is_unit_ne_bot {α : Type u_1} [nondiscrete_normed_field α] : filter.ne_bot (nhds_within 0 (set_of fun (x : α) => is_unit x)) := sorry protected instance real.normed_field : normed_field ℝ := normed_field.mk sorry abs_mul protected instance real.nondiscrete_normed_field : nondiscrete_normed_field ℝ := nondiscrete_normed_field.mk sorry namespace real theorem norm_eq_abs (r : ℝ) : norm r = abs r := rfl theorem norm_of_nonneg {x : ℝ} (hx : 0 ≤ x) : norm x = x := abs_of_nonneg hx @[simp] theorem norm_coe_nat (n : ℕ) : norm ↑n = ↑n := abs_of_nonneg (nat.cast_nonneg n) @[simp] theorem nnnorm_coe_nat (n : ℕ) : nnnorm ↑n = ↑n := sorry @[simp] theorem norm_two : norm (bit0 1) = bit0 1 := abs_of_pos zero_lt_two @[simp] theorem nnnorm_two : nnnorm (bit0 1) = bit0 1 := sorry @[simp] theorem nnreal.norm_eq (x : nnreal) : norm ↑x = ↑x := eq.mpr (id (Eq._oldrec (Eq.refl (norm ↑x = ↑x)) (norm_eq_abs ↑x))) (eq.mpr (id (Eq._oldrec (Eq.refl (abs ↑x = ↑x)) (nnreal.abs_eq x))) (Eq.refl ↑x)) theorem nnnorm_coe_eq_self {x : nnreal} : nnnorm ↑x = x := subtype.ext (norm_of_nonneg (zero_le x)) theorem nnnorm_of_nonneg {x : ℝ} (hx : 0 ≤ x) : nnnorm x = { val := x, property := hx } := nnnorm_coe_eq_self theorem ennnorm_eq_of_real {x : ℝ} (hx : 0 ≤ x) : ↑(nnnorm x) = ennreal.of_real x := eq.mpr (id (Eq._oldrec (Eq.refl (↑(nnnorm x) = ennreal.of_real x)) (Eq.symm (of_real_norm_eq_coe_nnnorm x)))) (eq.mpr (id (Eq._oldrec (Eq.refl (ennreal.of_real (norm x) = ennreal.of_real x)) (norm_of_nonneg hx))) (Eq.refl (ennreal.of_real x))) end real @[simp] theorem norm_norm {α : Type u_1} [normed_group α] (x : α) : norm (norm x) = norm x := eq.mpr (id (Eq._oldrec (Eq.refl (norm (norm x) = norm x)) (real.norm_of_nonneg (norm_nonneg x)))) (Eq.refl (norm x)) @[simp] theorem nnnorm_norm {α : Type u_1} [normed_group α] (a : α) : nnnorm (norm a) = nnnorm a := sorry protected instance int.normed_comm_ring : normed_comm_ring ℤ := normed_comm_ring.mk mul_comm theorem int.norm_cast_real (m : ℤ) : norm ↑m = norm m := rfl protected instance int.norm_one_class : norm_one_class ℤ := norm_one_class.mk (eq.mpr (id (Eq.trans ((fun (a a_1 : ℝ) (e_1 : a = a_1) (ᾰ ᾰ_1 : ℝ) (e_2 : ᾰ = ᾰ_1) => congr (congr_arg Eq e_1) e_2) (norm 1) 1 (Eq.trans (Eq.trans (Eq.symm (int.norm_cast_real 1)) ((fun (ᾰ ᾰ_1 : ℝ) (e_2 : ᾰ = ᾰ_1) => congr_arg norm e_2) (↑1) 1 int.cast_one)) norm_one) 1 1 (Eq.refl 1)) (propext (eq_self_iff_true 1)))) trivial) protected instance rat.normed_field : normed_field ℚ := normed_field.mk sorry sorry protected instance rat.nondiscrete_normed_field : nondiscrete_normed_field ℚ := nondiscrete_normed_field.mk sorry @[simp] theorem rat.norm_cast_real (r : ℚ) : norm ↑r = norm r := rfl @[simp] theorem int.norm_cast_rat (m : ℤ) : norm ↑m = norm m := sorry -- Here, we set a rather high priority for the instance `[normed_space α β] : semimodule α β` -- to take precedence over `semiring.to_semimodule` as this leads to instance paths with better -- unification properties. -- see Note[vector space definition] for why we extend `semimodule`. /-- A normed space over a normed field is a vector space endowed with a norm which satisfies the equality `∥c • x∥ = ∥c∥ ∥x∥`. We require only `∥c • x∥ ≤ ∥c∥ ∥x∥` in the definition, then prove `∥c • x∥ = ∥c∥ ∥x∥` in `norm_smul`. -/ class normed_space (α : Type u_5) (β : Type u_6) [normed_field α] [normed_group β] extends semimodule α β where norm_smul_le : ∀ (a : α) (b : β), norm (a • b) ≤ norm a * norm b protected instance normed_field.to_normed_space {α : Type u_1} [normed_field α] : normed_space α α := normed_space.mk sorry theorem norm_smul {α : Type u_1} {β : Type u_2} [normed_field α] [normed_group β] [normed_space α β] (s : α) (x : β) : norm (s • x) = norm s * norm x := sorry @[simp] theorem abs_norm_eq_norm {β : Type u_2} [normed_group β] (z : β) : abs (norm z) = norm z := iff.mpr (abs_eq (norm_nonneg z)) (Or.inl rfl) theorem dist_smul {α : Type u_1} {β : Type u_2} [normed_field α] [normed_group β] [normed_space α β] (s : α) (x : β) (y : β) : dist (s • x) (s • y) = norm s * dist x y := sorry theorem nnnorm_smul {α : Type u_1} {β : Type u_2} [normed_field α] [normed_group β] [normed_space α β] (s : α) (x : β) : nnnorm (s • x) = nnnorm s * nnnorm x := nnreal.eq (norm_smul s x) theorem nndist_smul {α : Type u_1} {β : Type u_2} [normed_field α] [normed_group β] [normed_space α β] (s : α) (x : β) (y : β) : nndist (s • x) (s • y) = nnnorm s * nndist x y := nnreal.eq (dist_smul s x y) theorem norm_smul_of_nonneg {β : Type u_2} [normed_group β] [normed_space ℝ β] {t : ℝ} (ht : 0 ≤ t) (x : β) : norm (t • x) = t * norm x := eq.mpr (id (Eq._oldrec (Eq.refl (norm (t • x) = t * norm x)) (norm_smul t x))) (eq.mpr (id (Eq._oldrec (Eq.refl (norm t * norm x = t * norm x)) (real.norm_eq_abs t))) (eq.mpr (id (Eq._oldrec (Eq.refl (abs t * norm x = t * norm x)) (abs_of_nonneg ht))) (Eq.refl (t * norm x)))) protected instance normed_space.topological_vector_space {α : Type u_1} [normed_field α] {E : Type u_5} [normed_group E] [normed_space α E] : topological_vector_space α E := sorry theorem closure_ball {E : Type u_5} [normed_group E] [normed_space ℝ E] (x : E) {r : ℝ} (hr : 0 < r) : closure (metric.ball x r) = metric.closed_ball x r := sorry theorem frontier_ball {E : Type u_5} [normed_group E] [normed_space ℝ E] (x : E) {r : ℝ} (hr : 0 < r) : frontier (metric.ball x r) = metric.sphere x r := sorry theorem interior_closed_ball {E : Type u_5} [normed_group E] [normed_space ℝ E] (x : E) {r : ℝ} (hr : 0 < r) : interior (metric.closed_ball x r) = metric.ball x r := sorry theorem interior_closed_ball' {E : Type u_5} [normed_group E] [normed_space ℝ E] [nontrivial E] (x : E) (r : ℝ) : interior (metric.closed_ball x r) = metric.ball x r := sorry theorem frontier_closed_ball {E : Type u_5} [normed_group E] [normed_space ℝ E] (x : E) {r : ℝ} (hr : 0 < r) : frontier (metric.closed_ball x r) = metric.sphere x r := sorry theorem frontier_closed_ball' {E : Type u_5} [normed_group E] [normed_space ℝ E] [nontrivial E] (x : E) (r : ℝ) : frontier (metric.closed_ball x r) = metric.sphere x r := sorry theorem ne_neg_of_mem_sphere (α : Type u_1) [normed_field α] {E : Type u_5} [normed_group E] [normed_space α E] [char_zero α] {r : ℝ} (hr : 0 < r) (x : ↥(metric.sphere 0 r)) : x ≠ -x := sorry theorem ne_neg_of_mem_unit_sphere (α : Type u_1) [normed_field α] {E : Type u_5} [normed_group E] [normed_space α E] [char_zero α] (x : ↥(metric.sphere 0 1)) : x ≠ -x := ne_neg_of_mem_sphere α (eq.mpr (id (eq_true_intro zero_lt_one')) trivial) x /-- If there is a scalar `c` with `∥c∥>1`, then any element can be moved by scalar multiplication to any shell of width `∥c∥`. Also recap information on the norm of the rescaling element that shows up in applications. -/ theorem rescale_to_shell {α : Type u_1} [normed_field α] {E : Type u_5} [normed_group E] [normed_space α E] {c : α} (hc : 1 < norm c) {ε : ℝ} (εpos : 0 < ε) {x : E} (hx : x ≠ 0) : ∃ (d : α), d ≠ 0 ∧ norm (d • x) < ε ∧ ε / norm c ≤ norm (d • x) ∧ norm d⁻¹ ≤ ε⁻¹ * norm c * norm x := sorry /-- The product of two normed spaces is a normed space, with the sup norm. -/ protected instance prod.normed_space {α : Type u_1} [normed_field α] {E : Type u_5} {F : Type u_6} [normed_group E] [normed_space α E] [normed_group F] [normed_space α F] : normed_space α (E × F) := normed_space.mk sorry /-- The product of finitely many normed spaces is a normed space, with the sup norm. -/ protected instance pi.normed_space {α : Type u_1} {ι : Type u_4} [normed_field α] {E : ι → Type u_2} [fintype ι] [(i : ι) → normed_group (E i)] [(i : ι) → normed_space α (E i)] : normed_space α ((i : ι) → E i) := normed_space.mk sorry /-- A subspace of a normed space is also a normed space, with the restriction of the norm. -/ protected instance submodule.normed_space {𝕜 : Type u_1} [normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] (s : submodule 𝕜 E) : normed_space 𝕜 ↥s := normed_space.mk sorry /-- A normed algebra `𝕜'` over `𝕜` is an algebra endowed with a norm for which the embedding of `𝕜` in `𝕜'` is an isometry. -/ class normed_algebra (𝕜 : Type u_5) (𝕜' : Type u_6) [normed_field 𝕜] [normed_ring 𝕜'] extends algebra 𝕜 𝕜' where norm_algebra_map_eq : ∀ (x : 𝕜), norm (coe_fn (algebra_map 𝕜 𝕜') x) = norm x @[simp] theorem norm_algebra_map_eq {𝕜 : Type u_1} (𝕜' : Type u_2) [normed_field 𝕜] [normed_ring 𝕜'] [h : normed_algebra 𝕜 𝕜'] (x : 𝕜) : norm (coe_fn (algebra_map 𝕜 𝕜') x) = norm x := normed_algebra.norm_algebra_map_eq x protected instance normed_algebra.to_normed_space (𝕜 : Type u_5) [normed_field 𝕜] (𝕜' : Type u_6) [normed_ring 𝕜'] [h : normed_algebra 𝕜 𝕜'] : normed_space 𝕜 𝕜' := normed_space.mk sorry protected instance normed_algebra.id (𝕜 : Type u_5) [normed_field 𝕜] : normed_algebra 𝕜 𝕜 := normed_algebra.mk sorry @[simp] theorem normed_algebra.norm_one (𝕜 : Type u_5) [normed_field 𝕜] {𝕜' : Type u_6} [normed_ring 𝕜'] [normed_algebra 𝕜 𝕜'] : norm 1 = 1 := sorry theorem normed_algebra.norm_one_class (𝕜 : Type u_5) [normed_field 𝕜] {𝕜' : Type u_6} [normed_ring 𝕜'] [normed_algebra 𝕜 𝕜'] : norm_one_class 𝕜' := norm_one_class.mk (normed_algebra.norm_one 𝕜) theorem normed_algebra.zero_ne_one (𝕜 : Type u_5) [normed_field 𝕜] {𝕜' : Type u_6} [normed_ring 𝕜'] [normed_algebra 𝕜 𝕜'] : 0 ≠ 1 := sorry theorem normed_algebra.nontrivial (𝕜 : Type u_5) [normed_field 𝕜] {𝕜' : Type u_6} [normed_ring 𝕜'] [normed_algebra 𝕜 𝕜'] : nontrivial 𝕜' := nontrivial.mk (Exists.intro 0 (Exists.intro 1 (normed_algebra.zero_ne_one 𝕜))) /-- Warning: This declaration should be used judiciously. Please consider using `is_scalar_tower` instead. `𝕜`-normed space structure induced by a `𝕜'`-normed space structure when `𝕜'` is a normed algebra over `𝕜`. Not registered as an instance as `𝕜'` can not be inferred. The type synonym `semimodule.restrict_scalars 𝕜 𝕜' E` will be endowed with this instance by default. -/ def normed_space.restrict_scalars (𝕜 : Type u_5) (𝕜' : Type u_6) [normed_field 𝕜] [normed_field 𝕜'] [normed_algebra 𝕜 𝕜'] (E : Type u_7) [normed_group E] [normed_space 𝕜' E] : normed_space 𝕜 E := normed_space.mk sorry protected instance restrict_scalars.normed_group {𝕜 : Type u_1} {𝕜' : Type u_2} {E : Type u_3} [I : normed_group E] : normed_group (restrict_scalars 𝕜 𝕜' E) := I protected instance semimodule.restrict_scalars.normed_space_orig {𝕜 : Type u_1} {𝕜' : Type u_2} {E : Type u_3} [normed_field 𝕜'] [normed_group E] [I : normed_space 𝕜' E] : normed_space 𝕜' (restrict_scalars 𝕜 𝕜' E) := I protected instance restrict_scalars.normed_space (𝕜 : Type u_5) (𝕜' : Type u_6) [normed_field 𝕜] [normed_field 𝕜'] [normed_algebra 𝕜 𝕜'] (E : Type u_7) [normed_group E] [normed_space 𝕜' E] : normed_space 𝕜 (restrict_scalars 𝕜 𝕜' E) := normed_space.restrict_scalars 𝕜 𝕜' E theorem cauchy_seq_finset_iff_vanishing_norm {α : Type u_1} {ι : Type u_4} [normed_group α] {f : ι → α} : (cauchy_seq fun (s : finset ι) => finset.sum s fun (i : ι) => f i) ↔ ∀ (ε : ℝ), ε > 0 → ∃ (s : finset ι), ∀ (t : finset ι), disjoint t s → norm (finset.sum t fun (i : ι) => f i) < ε := sorry theorem summable_iff_vanishing_norm {α : Type u_1} {ι : Type u_4} [normed_group α] [complete_space α] {f : ι → α} : summable f ↔ ∀ (ε : ℝ), ε > 0 → ∃ (s : finset ι), ∀ (t : finset ι), disjoint t s → norm (finset.sum t fun (i : ι) => f i) < ε := sorry theorem cauchy_seq_finset_of_norm_bounded {α : Type u_1} {ι : Type u_4} [normed_group α] {f : ι → α} (g : ι → ℝ) (hg : summable g) (h : ∀ (i : ι), norm (f i) ≤ g i) : cauchy_seq fun (s : finset ι) => finset.sum s fun (i : ι) => f i := sorry theorem cauchy_seq_finset_of_summable_norm {α : Type u_1} {ι : Type u_4} [normed_group α] {f : ι → α} (hf : summable fun (a : ι) => norm (f a)) : cauchy_seq fun (s : finset ι) => finset.sum s fun (a : ι) => f a := cauchy_seq_finset_of_norm_bounded (fun (a : ι) => norm (f a)) hf fun (i : ι) => le_refl (norm (f i)) /-- If a function `f` is summable in norm, and along some sequence of finsets exhausting the space its sum is converging to a limit `a`, then this holds along all finsets, i.e., `f` is summable with sum `a`. -/ theorem has_sum_of_subseq_of_summable {α : Type u_1} {γ : Type u_3} {ι : Type u_4} [normed_group α] {f : ι → α} (hf : summable fun (a : ι) => norm (f a)) {s : γ → finset ι} {p : filter γ} [filter.ne_bot p] (hs : filter.tendsto s p filter.at_top) {a : α} (ha : filter.tendsto (fun (b : γ) => finset.sum (s b) fun (i : ι) => f i) p (nhds a)) : has_sum f a := tendsto_nhds_of_cauchy_seq_of_subseq (cauchy_seq_finset_of_summable_norm hf) hs ha theorem has_sum_iff_tendsto_nat_of_summable_norm {α : Type u_1} [normed_group α] {f : ℕ → α} {a : α} (hf : summable fun (i : ℕ) => norm (f i)) : has_sum f a ↔ filter.tendsto (fun (n : ℕ) => finset.sum (finset.range n) fun (i : ℕ) => f i) filter.at_top (nhds a) := sorry /-- The direct comparison test for series: if the norm of `f` is bounded by a real function `g` which is summable, then `f` is summable. -/ theorem summable_of_norm_bounded {α : Type u_1} {ι : Type u_4} [normed_group α] [complete_space α] {f : ι → α} (g : ι → ℝ) (hg : summable g) (h : ∀ (i : ι), norm (f i) ≤ g i) : summable f := eq.mpr (id (Eq._oldrec (Eq.refl (summable f)) (propext summable_iff_cauchy_seq_finset))) (cauchy_seq_finset_of_norm_bounded g hg h) theorem has_sum.norm_le_of_bounded {α : Type u_1} {ι : Type u_4} [normed_group α] {f : ι → α} {g : ι → ℝ} {a : α} {b : ℝ} (hf : has_sum f a) (hg : has_sum g b) (h : ∀ (i : ι), norm (f i) ≤ g i) : norm a ≤ b := le_of_tendsto_of_tendsto' (filter.tendsto.norm hf) hg fun (s : finset ι) => norm_sum_le_of_le s fun (i : ι) (hi : i ∈ s) => h i /-- Quantitative result associated to the direct comparison test for series: If `∑' i, g i` is summable, and for all `i`, `∥f i∥ ≤ g i`, then `∥∑' i, f i∥ ≤ ∑' i, g i`. Note that we do not assume that `∑' i, f i` is summable, and it might not be the case if `α` is not a complete space. -/ theorem tsum_of_norm_bounded {α : Type u_1} {ι : Type u_4} [normed_group α] {f : ι → α} {g : ι → ℝ} {a : ℝ} (hg : has_sum g a) (h : ∀ (i : ι), norm (f i) ≤ g i) : norm (tsum fun (i : ι) => f i) ≤ a := sorry /-- If `∑' i, ∥f i∥` is summable, then `∥∑' i, f i∥ ≤ (∑' i, ∥f i∥)`. Note that we do not assume that `∑' i, f i` is summable, and it might not be the case if `α` is not a complete space. -/ theorem norm_tsum_le_tsum_norm {α : Type u_1} {ι : Type u_4} [normed_group α] {f : ι → α} (hf : summable fun (i : ι) => norm (f i)) : norm (tsum fun (i : ι) => f i) ≤ tsum fun (i : ι) => norm (f i) := tsum_of_norm_bounded (summable.has_sum hf) fun (i : ι) => le_rfl /-- Variant of the direct comparison test for series: if the norm of `f` is eventually bounded by a real function `g` which is summable, then `f` is summable. -/ theorem summable_of_norm_bounded_eventually {α : Type u_1} {ι : Type u_4} [normed_group α] [complete_space α] {f : ι → α} (g : ι → ℝ) (hg : summable g) (h : filter.eventually (fun (i : ι) => norm (f i) ≤ g i) filter.cofinite) : summable f := sorry theorem summable_of_nnnorm_bounded {α : Type u_1} {ι : Type u_4} [normed_group α] [complete_space α] {f : ι → α} (g : ι → nnreal) (hg : summable g) (h : ∀ (i : ι), nnnorm (f i) ≤ g i) : summable f := summable_of_norm_bounded (fun (i : ι) => ↑(g i)) (iff.mpr nnreal.summable_coe hg) fun (i : ι) => h i theorem summable_of_summable_norm {α : Type u_1} {ι : Type u_4} [normed_group α] [complete_space α] {f : ι → α} (hf : summable fun (a : ι) => norm (f a)) : summable f := summable_of_norm_bounded (fun (a : ι) => norm (f a)) hf fun (i : ι) => le_refl (norm (f i)) theorem summable_of_summable_nnnorm {α : Type u_1} {ι : Type u_4} [normed_group α] [complete_space α] {f : ι → α} (hf : summable fun (a : ι) => nnnorm (f a)) : summable f := summable_of_nnnorm_bounded (fun (a : ι) => nnnorm (f a)) hf fun (i : ι) => le_refl (nnnorm (f i)) end Mathlib
0926518a12f597a9720398a0959a790ca660ba19
4fa161becb8ce7378a709f5992a594764699e268
/src/tactic/ext.lean
a6873c4e839db78d5ce232c47f350b0c60e2b936
[ "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
14,639
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import tactic.rcases import data.sum universes u₁ u₂ open interactive interactive.types open lean.parser nat tactic /-- `derive_struct_ext_lemma n` generates two extensionality lemmas based on the equality of all non-propositional projections. On the following: ```lean @[ext] structure foo (α : Type*) := (x y : ℕ) (z : {z // z < x}) (k : α) (h : x < y) ``` `derive_struct_lemma` generates: ```lean lemma foo.ext : ∀ {α : Type u_1} (x y : foo α), x.x = y.x → x.y = y.y → x.z == y.z → x.k = y.k → x = y lemma foo.ext_iff : ∀ {α : Type u_1} (x y : foo α), x = y ↔ x.x = y.x ∧ x.y = y.y ∧ x.z == y.z ∧ x.k = y.k ``` -/ meta def derive_struct_ext_lemma (n : name) : tactic name := do e ← get_env, fs ← e.structure_fields n, d ← get_decl n, n ← resolve_constant n, let r := @expr.const tt n $ d.univ_params.map level.param, (args,_) ← infer_type r >>= mk_local_pis, let args := args.map expr.to_implicit_local_const, let t := r.mk_app args, x ← mk_local_def `x t, y ← mk_local_def `y t, let args_x := args ++ [x], let args_y := args ++ [y], bs ← fs.mmap $ λ f, do { d ← get_decl (n ++ f), let a := @expr.const tt (n ++ f) $ d.univ_params.map level.param, t ← infer_type a, s ← infer_type t, if s ≠ `(Prop) then do let x := a.mk_app args_x, let y := a.mk_app args_y, t ← infer_type x, t' ← infer_type y, some <$> if t = t' then mk_app `eq [x,y] >>= mk_local_def `h else mk_mapp `heq [none,x,none,y] >>= mk_local_def `h else pure none }, let bs := bs.filter_map id, eq_t ← mk_app `eq [x,y], t ← pis (args ++ [x,y] ++ bs) eq_t, pr ← run_async $ do { (_,pr) ← solve_aux t (do { args ← intron args.length, x ← intro1, y ← intro1, cases x, cases y, bs.mmap' (λ _, do e ← intro1, cases e), reflexivity }), instantiate_mvars pr }, let decl_n := n <.> "ext", add_decl (declaration.thm decl_n d.univ_params t pr), bs ← bs.mmap infer_type, let rhs := expr.mk_and_lst bs, iff_t ← mk_app `iff [eq_t,rhs], t ← pis (args ++ [x,y]) iff_t, pr ← run_async $ do { (_,pr) ← solve_aux t $ do { args ← intron args.length, x ← intro1, y ← intro1, cases x, cases y, split, solve1 $ do { h ← intro1, hs ← injection h, subst_vars, repeat (refine ``( and.intro _ _ ) >> reflexivity ), done <|> reflexivity }, solve1 $ do { repeat (do refine ``(and_imp.mpr _), h ← intro1, cases h, skip ), h ← intro1, cases h, reflexivity } }, instantiate_mvars pr }, add_decl (declaration.thm (n <.> "ext_iff") d.univ_params t pr), pure decl_n meta def get_ext_subject : expr → tactic name | (expr.pi n bi d b) := do v ← mk_local' n bi d, b' ← whnf $ b.instantiate_var v, get_ext_subject b' | (expr.app _ e) := do t ← infer_type e >>= instantiate_mvars >>= head_beta, if t.get_app_fn.is_constant then pure $ t.get_app_fn.const_name else if t.is_pi then pure $ name.mk_numeral 0 name.anonymous else if t.is_sort then pure $ name.mk_numeral 1 name.anonymous else do t ← pp t, fail format!"only constants and Pi types are supported: {t}" | e := fail format!"Only expressions of the form `_ → _ → ... → R ... e are supported: {e}" open native @[reducible] def ext_param_type := option name ⊕ option name meta def opt_minus : lean.parser (option name → ext_param_type) := sum.inl <$ tk "-" <|> pure sum.inr meta def ext_param := opt_minus <*> ( name.mk_numeral 0 name.anonymous <$ brackets "(" ")" (tk "→" <|> tk "->") <|> none <$ tk "*" <|> some <$> ident ) meta def saturate_fun : name → tactic expr | (name.mk_numeral 0 name.anonymous) := do v₀ ← mk_mvar, v₁ ← mk_mvar, return $ v₀.imp v₁ | (name.mk_numeral 1 name.anonymous) := do u ← mk_meta_univ, pure $ expr.sort u | n := do e ← resolve_constant n >>= mk_const, a ← get_arity e, e.mk_app <$> (list.iota a).mmap (λ _, mk_mvar) meta def equiv_type_constr (n n' : name) : tactic unit := do e ← saturate_fun n, e' ← saturate_fun n', unify e e' <|> fail format!"{n} and {n'} are not definitionally equal types" section performance_hack /-- For performance reasons, it is inadvisable to use `user_attribute.get_param`. The parameter is stored as a reflected expression. When calling `get_param`, the stored parameter is evaluated using `eval_expr`, which first compiles the expression into VM bytecode. The unevaluated expression is available using `user_attribute.get_param_untyped`. In particular, `user_attribute.get_param` MUST NEVER BE USED in the implementation of an attribute cache. This is because calling `eval_expr` disables the attribute cache. There are several possible workarounds: 1. Set a different attribute depending on the parameter. 2. Use your own evaluation function instead of `eval_expr`, such as e.g. `expr.to_nat`. 3. Write your own `has_reflect Param` instance (using a more efficient serialization format). The `user_attribute` code unfortunately checks whether the expression has the correct type, but you can use `` `(id %%e : Param) `` to pretend that your expression `e` has type `Param`. -/ library_note "user attribute parameters" /-! For performance reasons, the parameters of the `@[ext]` attribute are stored in two auxiliary attributes: ```lean attribute [ext [thunk]] funext -- is turned into attribute [_ext_core (@id name @funext)] thunk attribute [_ext_lemma_core] funext ``` see Note [user attribute parameters] -/ local attribute [semireducible] reflected local attribute [instance, priority 9000] private meta def hacky_name_reflect : has_reflect name := λ n, `(id %%(expr.const n []) : name) @[user_attribute] private meta def ext_attr_core : user_attribute (name_map name) name := { name := `_ext_core, descr := "(internal attribute used by ext)", cache_cfg := { dependencies := [], mk_cache := λ ns, do attrs ← ns.mmap (λ n, do ext_l ← ext_attr_core.get_param_untyped n, pure (n, ext_l.app_arg.const_name)), pure $ rb_map.of_list attrs }, parser := failure } end performance_hack /-- Private attribute used to tag extensionality lemmas. -/ @[user_attribute] private meta def ext_lemma_attr_core : user_attribute := { name := `_ext_lemma_core, descr := "(internal attribute used by ext)", parser := failure } /-- Returns the extensionality lemmas in the environment, as a map from structure name to lemma name. -/ meta def get_ext_lemmas : tactic (name_map name) := ext_attr_core.get_cache /-- Returns the extensionality lemmas in the environment, as a list of lemma names. -/ meta def get_ext_lemma_names : tactic (list name) := attribute.get_instances ext_lemma_attr_core.name /-- Tag lemmas of the form: ```lean @[ext] lemma my_collection.ext (a b : my_collection) (h : ∀ x, a.lookup x = b.lookup y) : a = b := ... ``` The attribute indexes extensionality lemma using the type of the objects (i.e. `my_collection`) which it gets from the statement of the lemma. In some cases, the same lemma can be used to state the extensionality of multiple types that are definitionally equivalent. ```lean attribute [ext [(→),thunk,stream]] funext ``` Those parameters are cumulative. The following are equivalent: ```lean attribute [ext [(→),thunk]] funext attribute [ext [stream]] funext ``` and ```lean attribute [ext [(→),thunk,stream]] funext ``` One removes type names from the list for one lemma with: ```lean attribute [ext [-stream,-thunk]] funext ``` Also, the following: ```lean @[ext] lemma my_collection.ext (a b : my_collection) (h : ∀ x, a.lookup x = b.lookup y) : a = b := ... ``` is equivalent to ```lean @[ext *] lemma my_collection.ext (a b : my_collection) (h : ∀ x, a.lookup x = b.lookup y) : a = b := ... ``` This allows us specify type synonyms along with the type that is referred to in the lemma statement. ```lean @[ext [*,my_type_synonym]] lemma my_collection.ext (a b : my_collection) (h : ∀ x, a.lookup x = b.lookup y) : a = b := ... ``` The `ext` attribute can be applied to a structure to generate its extensionality lemmas: ```lean @[ext] structure foo (α : Type*) := (x y : ℕ) (z : {z // z < x}) (k : α) (h : x < y) ``` will generate: ```lean @[ext] lemma foo.ext : ∀ {α : Type u_1} (x y : foo α), x.x = y.x → x.y = y.y → x.z == y.z → x.k = y.k → x = y lemma foo.ext_iff : ∀ {α : Type u_1} (x y : foo α), x = y ↔ x.x = y.x ∧ x.y = y.y ∧ x.z == y.z ∧ x.k = y.k ``` -/ @[user_attribute] meta def extensional_attribute : user_attribute unit (list ext_param_type) := { name := `ext, descr := "lemmas usable by `ext` tactic", parser := pure <$> ext_param <|> list_of ext_param <|> pure [], after_set := some $ λ n prio b, do ls ← extensional_attribute.get_param n, e ← get_env, n ← if (e.structure_fields n).is_some then derive_struct_ext_lemma n else pure n, s ← mk_const n >>= infer_type >>= get_ext_subject, let (rs,ls'') := if ls.empty then ([],[s]) else ls.partition_map (sum.map (flip option.get_or_else s) (flip option.get_or_else s)), ls''.mmap' (equiv_type_constr s), ls' ← get_ext_lemmas, let l := ls'' ∪ (ls'.to_list.filter $ λ l, prod.snd l = n).map prod.fst \ rs, l.mmap' $ λ l, do ext_attr_core.set l n b prio, ext_lemma_attr_core.set n () b prio } add_tactic_doc { name := "ext", category := doc_category.attr, decl_names := [`extensional_attribute], tags := ["rewrite", "logic"] } -- We mark some existing extensionality lemmas. attribute [ext] array.ext propext attribute [ext [(→),thunk]] _root_.funext -- We create some extensionality lemmas for existing structures. attribute [ext] ulift namespace plift -- This is stronger than the one generated automatically. @[ext] lemma ext {P : Prop} (a b : plift P) : a = b := begin cases a, cases b, refl end end plift -- Conservatively, we'll only add extensionality lemmas for `has_*` structures -- as they become useful. attribute [ext] has_zero namespace tactic meta def try_intros : ext_patt → tactic ext_patt | [] := try intros $> [] | (x::xs) := do tgt ← target >>= whnf, if tgt.is_pi then rintro [x] >> try_intros xs else pure (x :: xs) meta def ext1 (xs : ext_patt) (cfg : apply_cfg := {}) : tactic ext_patt := do subject ← target >>= get_ext_subject, m ← get_ext_lemmas, do { rule ← m.find subject, applyc rule cfg } <|> do { ls ← get_ext_lemma_names, ls.any_of (λ n, applyc n cfg) } <|> fail format!"no applicable extensionality rule found for {subject}", try_intros xs meta def ext : ext_patt → option ℕ → tactic unit | _ (some 0) := skip | xs n := focus1 $ do ys ← ext1 xs, try (ext ys (nat.pred <$> n)) local postfix `?`:9001 := optional local postfix *:9001 := many /-- `ext1 id` selects and apply one extensionality lemma (with attribute `ext`), using `id`, if provided, to name a local constant introduced by the lemma. If `id` is omitted, the local constant is named automatically, as per `intro`. -/ meta def interactive.ext1 (xs : parse ext_parse) : tactic unit := ext1 xs $> () /-- - `ext` applies as many extensionality lemmas as possible; - `ext ids`, with `ids` a list of identifiers, finds extentionality and applies them until it runs out of identifiers in `ids` to name the local constants. - `ext` can also be given an `rcases` pattern in place of an identifier. This will destruct the introduced local constant. When trying to prove: ```lean α β : Type, f g : α → set β ⊢ f = g ``` applying `ext x y` yields: ```lean α β : Type, f g : α → set β, x : α, y : β ⊢ y ∈ f x ↔ y ∈ f x ``` by applying functional extensionality and set extensionality. When trying to prove: ```lean α β γ : Type f g : α × β → γ ⊢ f = g ``` applying `ext ⟨a, b⟩` yields: ```lean α β γ : Type, f g : α × β → γ, a : α, b : β ⊢ f (a, b) = g (a, b) ``` by applying functional extensionality and destructing the introduced pair. A maximum depth can be provided with `ext x y z : 3`. -/ meta def interactive.ext : parse ext_parse → parse (tk ":" *> small_nat)? → tactic unit | [] (some n) := iterate_range 1 n (ext1 [] $> ()) | [] none := repeat1 (ext1 [] $> ()) | xs n := tactic.ext xs n /-- * `ext1 id` selects and apply one extensionality lemma (with attribute `ext`), using `id`, if provided, to name a local constant introduced by the lemma. If `id` is omitted, the local constant is named automatically, as per `intro`. * `ext` applies as many extensionality lemmas as possible; * `ext ids`, with `ids` a list of identifiers, finds extensionality lemmas and applies them until it runs out of identifiers in `ids` to name the local constants. * `ext` can also be given an `rcases` pattern in place of an identifier. This will destruct the introduced local constant. When trying to prove: ```lean α β : Type, f g : α → set β ⊢ f = g ``` applying `ext x y` yields: ```lean α β : Type, f g : α → set β, x : α, y : β ⊢ y ∈ f x ↔ y ∈ g x ``` by applying functional extensionality and set extensionality. When trying to prove: ```lean α β γ : Type f g : α × β → γ ⊢ f = g ``` applying `ext ⟨a, b⟩` yields: ```lean α β γ : Type, f g : α × β → γ, a : α, b : β ⊢ f (a, b) = g (a, b) ``` by applying functional extensionality and destructing the introduced pair. A maximum depth can be provided with `ext x y z : 3`. -/ add_tactic_doc { name := "ext1 / ext", category := doc_category.tactic, decl_names := [`tactic.interactive.ext1, `tactic.interactive.ext], tags := ["rewriting", "logic"] } end tactic
2aed1fb9080fd1fc3c86da4e94789b96178dcd9f
ecad13897fdb44984cf1968424224d1750040236
/lean/lean/examples/example03.lean
da5f3ec36e08fa8aae5fb4208284d98c3bf06eba
[]
no_license
MetaBorgCube/sdf3-demo
4899159b1cfb0a95ae3af325035bbba8a1255477
e831606d5b404eba75b087916a1162923143b98a
refs/heads/master
1,609,472,086,310
1,553,380,857,000
1,553,380,857,000
59,577,395
0
0
null
null
null
null
UTF-8
Lean
false
false
28
lean
(a : A) -> (z : S) -> x c
3f01fdf8d84c8321b75b9cc51b492b26e9000ecf
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/algebra/star/basic_auto.lean
37885a9745622301961b1bf22bab22804a956d42
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
4,683
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison. -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.tactic.apply_fun import Mathlib.algebra.ordered_ring import Mathlib.algebra.big_operators.basic import Mathlib.data.equiv.ring import Mathlib.PostPort universes u l u_1 namespace Mathlib /-! # Star monoids and star rings We introduce the basic algebraic notions of star monoids, and star rings. Star algebras are introduced in `algebra.algebra.star`. These are implemented as "mixin" typeclasses, so to summon a star ring (for example) one needs to write `(R : Type) [ring R] [star_ring R]`. This avoids difficulties with diamond inheritance. For now we simply do not introduce notations, as different users are expected to feel strongly about the relative merits of `r^*`, `r†`, `rᘁ`, and so on. Our star rings are actually star semirings, but of course we can prove `star_neg : star (-r) = - star r` when the underlying semiring is a ring. -/ /-- Notation typeclass (with no default notation!) for an algebraic structure with a star operation. -/ class has_star (R : Type u) where star : R → R /-- A star operation (e.g. complex conjugate). -/ def star {R : Type u} [has_star R] (r : R) : R := has_star.star r /-- Typeclass for a star operation with is involutive. -/ class has_involutive_star (R : Type u) extends has_star R where star_involutive : function.involutive has_star.star @[simp] theorem star_star {R : Type u} [has_involutive_star R] (r : R) : star (star r) = r := has_involutive_star.star_involutive r theorem star_injective {R : Type u} [has_involutive_star R] : function.injective star := function.involutive.injective has_involutive_star.star_involutive /-- A *-monoid is a monoid `R` with an involutive operations `star` so `star (r * s) = star s * star r`. -/ class star_monoid (R : Type u) [monoid R] extends has_involutive_star R where star_mul : ∀ (r s : R), has_star.star (r * s) = has_star.star s * has_star.star r @[simp] theorem star_mul {R : Type u} [monoid R] [star_monoid R] (r : R) (s : R) : star (r * s) = star s * star r := star_monoid.star_mul r s /-- `star` as an `mul_equiv` from `R` to `Rᵒᵖ` -/ @[simp] theorem star_mul_equiv_apply {R : Type u} [monoid R] [star_monoid R] (x : R) : coe_fn star_mul_equiv x = opposite.op (star x) := Eq.refl (coe_fn star_mul_equiv x) @[simp] theorem star_one (R : Type u) [monoid R] [star_monoid R] : star 1 = 1 := sorry /-- A *-ring `R` is a (semi)ring with an involutive `star` operation which is additive which makes `R` with its multiplicative structure into a *-monoid (i.e. `star (r * s) = star s * star r`). -/ class star_ring (R : Type u) [semiring R] extends star_monoid R where star_add : ∀ (r s : R), has_star.star (r + s) = has_star.star r + has_star.star s @[simp] theorem star_add {R : Type u} [semiring R] [star_ring R] (r : R) (s : R) : star (r + s) = star r + star s := star_ring.star_add r s /-- `star` as an `add_equiv` -/ def star_add_equiv {R : Type u} [semiring R] [star_ring R] : R ≃+ R := add_equiv.mk star (equiv.inv_fun (function.involutive.to_equiv star sorry)) sorry sorry star_add @[simp] theorem star_zero (R : Type u) [semiring R] [star_ring R] : star 0 = 0 := add_equiv.map_zero star_add_equiv /-- `star` as an `ring_equiv` from `R` to `Rᵒᵖ` -/ @[simp] theorem star_ring_equiv_apply {R : Type u} [semiring R] [star_ring R] (x : R) : coe_fn star_ring_equiv x = opposite.op (star x) := Eq.refl (coe_fn star_ring_equiv x) @[simp] theorem star_sum {R : Type u} [semiring R] [star_ring R] {α : Type u_1} (s : finset α) (f : α → R) : star (finset.sum s fun (x : α) => f x) = finset.sum s fun (x : α) => star (f x) := add_equiv.map_sum star_add_equiv (fun (x : α) => f x) s @[simp] theorem star_neg {R : Type u} [ring R] [star_ring R] (r : R) : star (-r) = -star r := add_equiv.map_neg star_add_equiv r @[simp] theorem star_sub {R : Type u} [ring R] [star_ring R] (r : R) (s : R) : star (r - s) = star r - star s := add_equiv.map_sub star_add_equiv r s @[simp] theorem star_bit0 {R : Type u} [ring R] [star_ring R] (r : R) : star (bit0 r) = bit0 (star r) := sorry @[simp] theorem star_bit1 {R : Type u} [ring R] [star_ring R] (r : R) : star (bit1 r) = bit1 (star r) := sorry /-- Any commutative semiring admits the trivial *-structure. -/ def star_ring_of_comm {R : Type u_1} [comm_semiring R] : star_ring R := star_ring.mk sorry @[simp] theorem star_id_of_comm {R : Type u_1} [comm_semiring R] {x : R} : star x = x := rfl end Mathlib
56c477e2e829f58c4f362878698df5f96dbdaa6e
ae1e94c332e17c7dc7051ce976d5a9eebe7ab8a5
/stage0/src/Lean/Meta/Tactic/Cases.lean
3854b02ff2209298a54bbab9e818be82c56e2ec5
[ "Apache-2.0" ]
permissive
dupuisf/lean4
d082d13b01243e1de29ae680eefb476961221eef
6a39c65bd28eb0e28c3870188f348c8914502718
refs/heads/master
1,676,948,755,391
1,610,665,114,000
1,610,665,114,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
14,597
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.AppBuilder import Lean.Meta.Tactic.Induction import Lean.Meta.Tactic.Injection import Lean.Meta.Tactic.Assert import Lean.Meta.Tactic.Subst namespace Lean.Meta private def throwInductiveTypeExpected {α} (type : Expr) : MetaM α := do throwError! "failed to compile pattern matching, inductive type expected{indentExpr type}" def getInductiveUniverseAndParams (type : Expr) : MetaM (List Level × Array Expr) := do let type ← whnfD type matchConstInduct type.getAppFn (fun _ => throwInductiveTypeExpected type) fun val us => let I := type.getAppFn let Iargs := type.getAppArgs let params := Iargs.extract 0 val.nparams pure (us, params) private def mkEqAndProof (lhs rhs : Expr) : MetaM (Expr × Expr) := do let lhsType ← inferType lhs let rhsType ← inferType rhs let u ← getLevel lhsType if (← isDefEq lhsType rhsType) then pure (mkApp3 (mkConst `Eq [u]) lhsType lhs rhs, mkApp2 (mkConst `Eq.refl [u]) lhsType lhs) else pure (mkApp4 (mkConst `HEq [u]) lhsType lhs rhsType rhs, mkApp2 (mkConst `HEq.refl [u]) lhsType lhs) private partial def withNewEqs {α} (targets targetsNew : Array Expr) (k : Array Expr → Array Expr → MetaM α) : MetaM α := let rec loop (i : Nat) (newEqs : Array Expr) (newRefls : Array Expr) := do if h : i < targets.size then let (newEqType, newRefl) ← mkEqAndProof targets[i] targetsNew[i] withLocalDeclD `h newEqType fun newEq => do loop (i+1) (newEqs.push newEq) (newRefls.push newRefl) else k newEqs newRefls loop 0 #[] #[] def generalizeTargets (mvarId : MVarId) (motiveType : Expr) (targets : Array Expr) : MetaM MVarId := withMVarContext mvarId do checkNotAssigned mvarId `generalizeTargets let (typeNew, eqRefls) ← forallTelescopeReducing motiveType fun targetsNew _ => do unless targetsNew.size == targets.size do throwError! "invalid number of targets #{targets.size}, motive expects #{targetsNew.size}" withNewEqs targets targetsNew fun eqs eqRefls => do let type ← getMVarType mvarId let typeNew ← mkForallFVars eqs type let typeNew ← mkForallFVars targetsNew typeNew pure (typeNew, eqRefls) let mvarNew ← mkFreshExprSyntheticOpaqueMVar typeNew (← getMVarTag mvarId) assignExprMVar mvarId (mkAppN (mkAppN mvarNew targets) eqRefls) pure mvarNew.mvarId! structure GeneralizeIndicesSubgoal where mvarId : MVarId indicesFVarIds : Array FVarId fvarId : FVarId numEqs : Nat /-- Similar to `generalizeTargets` but customized for the `casesOn` motive. Given a metavariable `mvarId` representing the ``` Ctx, h : I A j, D |- T ``` where `fvarId` is `h`s id, and the type `I A j` is an inductive datatype where `A` are parameters, and `j` the indices. Generate the goal ``` Ctx, h : I A j, D, j' : J, h' : I A j' |- j == j' -> h == h' -> T ``` Remark: `(j == j' -> h == h')` is a "telescopic" equality. Remark: `j` is sequence of terms, and `j'` a sequence of free variables. The result contains the fields - `mvarId`: the new goal - `indicesFVarIds`: `j'` ids - `fvarId`: `h'` id - `numEqs`: number of equations in the target -/ def generalizeIndices (mvarId : MVarId) (fvarId : FVarId) : MetaM GeneralizeIndicesSubgoal := withMVarContext mvarId do let lctx ← getLCtx let localInsts ← getLocalInstances checkNotAssigned mvarId `generalizeIndices let fvarDecl ← getLocalDecl fvarId let type ← whnf fvarDecl.type type.withApp fun f args => matchConstInduct f (fun _ => throwTacticEx `generalizeIndices mvarId "inductive type expected") fun val _ => do unless val.nindices > 0 do throwTacticEx `generalizeIndices mvarId "indexed inductive type expected" unless args.size == val.nindices + val.nparams do throwTacticEx `generalizeIndices mvarId "ill-formed inductive datatype" let indices := args.extract (args.size - val.nindices) args.size let IA := mkAppN f (args.extract 0 val.nparams) -- `I A` let IAType ← inferType IA forallTelescopeReducing IAType fun newIndices _ => do let newType := mkAppN IA newIndices withLocalDeclD fvarDecl.userName newType fun h' => withNewEqs indices newIndices fun newEqs newRefls => do let (newEqType, newRefl) ← mkEqAndProof fvarDecl.toExpr h' let newRefls := newRefls.push newRefl withLocalDeclD `h newEqType fun newEq => do let newEqs := newEqs.push newEq /- auxType `forall (j' : J) (h' : I A j'), j == j' -> h == h' -> target -/ let target ← getMVarType mvarId let tag ← getMVarTag mvarId let auxType ← mkForallFVars newEqs target let auxType ← mkForallFVars #[h'] auxType let auxType ← mkForallFVars newIndices auxType let newMVar ← mkFreshExprMVarAt lctx localInsts auxType MetavarKind.syntheticOpaque tag /- assign mvarId := newMVar indices h refls -/ assignExprMVar mvarId (mkAppN (mkApp (mkAppN newMVar indices) fvarDecl.toExpr) newRefls) let (indicesFVarIds, newMVarId) ← introNP newMVar.mvarId! newIndices.size let (fvarId, newMVarId) ← intro1P newMVarId pure { mvarId := newMVarId, indicesFVarIds := indicesFVarIds, fvarId := fvarId, numEqs := newEqs.size } structure CasesSubgoal extends InductionSubgoal where ctorName : Name namespace Cases structure Context where inductiveVal : InductiveVal casesOnVal : DefinitionVal nminors : Nat := inductiveVal.ctors.length majorDecl : LocalDecl majorTypeFn : Expr majorTypeArgs : Array Expr majorTypeIndices : Array Expr := majorTypeArgs.extract (majorTypeArgs.size - inductiveVal.nindices) majorTypeArgs.size private def mkCasesContext? (majorFVarId : FVarId) : MetaM (Option Context) := do let env ← getEnv if !env.contains `Eq || !env.contains `HEq then pure none else let majorDecl ← getLocalDecl majorFVarId let majorType ← whnf majorDecl.type majorType.withApp fun f args => matchConstInduct f (fun _ => pure none) fun ival _ => if args.size != ival.nindices + ival.nparams then pure none else match env.find? (Name.mkStr ival.name "casesOn") with | ConstantInfo.defnInfo cval => pure $ some { inductiveVal := ival, casesOnVal := cval, majorDecl := majorDecl, majorTypeFn := f, majorTypeArgs := args } | _ => pure none /- We say the major premise has independent indices IF 1- its type is *not* an indexed inductive family, OR 2- its type is an indexed inductive family, but all indices are distinct free variables, and all local declarations different from the major and its indices do not depend on the indices. -/ private def hasIndepIndices (ctx : Context) : MetaM Bool := do if ctx.majorTypeIndices.isEmpty then pure true else if ctx.majorTypeIndices.any $ fun idx => !idx.isFVar then /- One of the indices is not a free variable. -/ pure false else if ctx.majorTypeIndices.size.any fun i => i.any fun j => ctx.majorTypeIndices[i] == ctx.majorTypeIndices[j] then /- An index ocurrs more than once -/ pure false else let lctx ← getLCtx let mctx ← getMCtx pure $ lctx.all fun decl => decl.fvarId == ctx.majorDecl.fvarId || -- decl is the major ctx.majorTypeIndices.any (fun index => decl.fvarId == index.fvarId!) || -- decl is one of the indices mctx.findLocalDeclDependsOn decl (fun fvarId => ctx.majorTypeIndices.all $ fun idx => idx.fvarId! != fvarId) -- or does not depend on any index private def elimAuxIndices (s₁ : GeneralizeIndicesSubgoal) (s₂ : Array CasesSubgoal) : MetaM (Array CasesSubgoal) := let indicesFVarIds := s₁.indicesFVarIds s₂.mapM fun s => do indicesFVarIds.foldlM (init := s) fun s indexFVarId => match s.subst.get indexFVarId with | Expr.fvar indexFVarId' _ => (do let mvarId ← clear s.mvarId indexFVarId'; pure { s with mvarId := mvarId, subst := s.subst.erase indexFVarId }) <|> (pure s) | _ => pure s /- Convert `s` into an array of `CasesSubgoal`, by attaching the corresponding constructor name, and adding the substitution `majorFVarId -> ctor_i us params fields` into each subgoal. -/ private def toCasesSubgoals (s : Array InductionSubgoal) (ctorNames : Array Name) (majorFVarId : FVarId) (us : List Level) (params : Array Expr) : Array CasesSubgoal := s.mapIdx fun i s => let ctorName := ctorNames[i] let ctorApp := mkAppN (mkAppN (mkConst ctorName us) params) s.fields let s := { s with subst := s.subst.insert majorFVarId ctorApp } { ctorName := ctorName, toInductionSubgoal := s } /- Convert heterogeneous equality into a homegeneous one -/ private def heqToEq (mvarId : MVarId) (eqDecl : LocalDecl) : MetaM MVarId := do /- Convert heterogeneous equality into a homegeneous one -/ let prf ← mkEqOfHEq (mkFVar eqDecl.fvarId) let aEqb ← whnf (← inferType prf) let mvarId ← assert mvarId eqDecl.userName aEqb prf clear mvarId eqDecl.fvarId partial def unifyEqs (numEqs : Nat) (mvarId : MVarId) (subst : FVarSubst) : MetaM (Option (MVarId × FVarSubst)) := do if numEqs == 0 then pure (some (mvarId, subst)) else let (eqFVarId, mvarId) ← intro1 mvarId withMVarContext mvarId do let eqDecl ← getLocalDecl eqFVarId if eqDecl.type.isHEq then let mvarId ← heqToEq mvarId eqDecl unifyEqs numEqs mvarId subst else match eqDecl.type.eq? with | none => throwError! "equality expected{indentExpr eqDecl.type}" | some (α, a, b) => if (← isDefEq a b) then /- Skip equality -/ unifyEqs (numEqs - 1) (← clear mvarId eqFVarId) subst else -- Remark: we use `let rec` here because otherwise the compiler would generate an insane amount of code. -- We can remove the `rec` after we fix the eagerly inlining issue in the compiler. let rec substEq (symm : Bool) := do /- TODO: support for acyclicity (e.g., `xs ≠ x :: xs`) -/ let (substNew, mvarId) ← substCore mvarId eqFVarId symm subst unifyEqs (numEqs - 1) mvarId substNew let rec injection (a b : Expr) := do let env ← getEnv if a.isConstructorApp env && b.isConstructorApp env then /- ctor_i ... = ctor_j ... -/ match (← injectionCore mvarId eqFVarId) with | InjectionResultCore.solved => pure none -- this alternative has been solved | InjectionResultCore.subgoal mvarId numEqsNew => unifyEqs (numEqs - 1 + numEqsNew) mvarId subst else let a' ← whnf a let b' ← whnf b if a' != a || b' != b then /- Reduced lhs/rhs of current equality -/ let prf := mkFVar eqFVarId let aEqb' ← mkEq a' b' let mvarId ← assert mvarId eqDecl.userName aEqb' prf let mvarId ← clear mvarId eqFVarId unifyEqs numEqs mvarId subst else throwError! "dependent elimination failed, stuck at auxiliary equation{indentExpr eqDecl.type}" match a, b with | Expr.fvar aFVarId _, Expr.fvar bFVarId _ => /- x = y -/ let aDecl ← getLocalDecl aFVarId let bDecl ← getLocalDecl bFVarId substEq (aDecl.index < bDecl.index) | Expr.fvar .., _ => /- x = t -/ substEq (symm := false) | _, Expr.fvar .. => /- t = x -/ substEq (symm := true) | a, b => injection a b private def unifyCasesEqs (numEqs : Nat) (subgoals : Array CasesSubgoal) : MetaM (Array CasesSubgoal) := subgoals.foldlM (init := #[]) fun subgoals s => do match (← unifyEqs numEqs s.mvarId s.subst) with | none => pure subgoals | some (mvarId, subst) => pure $ subgoals.push { s with mvarId := mvarId, subst := subst, fields := s.fields.map (subst.apply ·) } private def inductionCasesOn (mvarId : MVarId) (majorFVarId : FVarId) (givenNames : Array (List Name)) (useUnusedNames : Bool) (ctx : Context) : MetaM (Array CasesSubgoal) := do withMVarContext mvarId do let majorType ← inferType (mkFVar majorFVarId) let (us, params) ← getInductiveUniverseAndParams majorType let casesOn := mkCasesOnName ctx.inductiveVal.name let ctors := ctx.inductiveVal.ctors.toArray let s ← induction mvarId majorFVarId casesOn givenNames useUnusedNames pure $ toCasesSubgoals s ctors majorFVarId us params def cases (mvarId : MVarId) (majorFVarId : FVarId) (givenNames : Array (List Name) := #[]) (useUnusedNames := false) : MetaM (Array CasesSubgoal) := withMVarContext mvarId do checkNotAssigned mvarId `cases let context? ← mkCasesContext? majorFVarId match context? with | none => throwTacticEx `cases mvarId "not applicable to the given hypothesis" | some ctx => /- Remark: if caller does not need a `FVarSubst` (variable substitution), and `hasIndepIndices ctx` is true, then we can also use the simple case. This is a minor optimization, and we currently do not even allow callers to specify whether they want the `FVarSubst` or not. -/ if ctx.inductiveVal.nindices == 0 then -- Simple case inductionCasesOn mvarId majorFVarId givenNames useUnusedNames ctx else let s₁ ← generalizeIndices mvarId majorFVarId trace[Meta.Tactic.cases]! "after generalizeIndices\n{MessageData.ofGoal s₁.mvarId}" let s₂ ← inductionCasesOn s₁.mvarId s₁.fvarId givenNames useUnusedNames ctx let s₂ ← elimAuxIndices s₁ s₂ unifyCasesEqs s₁.numEqs s₂ end Cases def cases (mvarId : MVarId) (majorFVarId : FVarId) (givenNames : Array (List Name) := #[]) (useUnusedNames := false) : MetaM (Array CasesSubgoal) := Cases.cases mvarId majorFVarId givenNames useUnusedNames builtin_initialize registerTraceClass `Meta.Tactic.cases end Lean.Meta
ee6029c11696913b60e42b72c2e8450846b84122
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/testing/slim_check/gen.lean
811128a16a335fffec67ab919db90ddc31f70000
[ "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,690
lean
/- Copyright (c) 2020 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import control.uliftable import system.random import system.random.basic /-! # `gen` Monad This monad is used to formulate randomized computations with a parameter to specify the desired size of the result. This is a port of the Haskell QuickCheck library. ## Main definitions * `gen` monad ## Local notation * `i .. j` : `Icc i j`, the set of values between `i` and `j` inclusively; ## Tags random testing ## References * https://hackage.haskell.org/package/QuickCheck -/ universes u v namespace slim_check /-- Monad to generate random examples to test properties with. It has a `nat` parameter so that the caller can decide on the size of the examples. -/ @[reducible, derive [monad, is_lawful_monad]] def gen (α : Type u) := reader_t (ulift ℕ) rand α variable (α : Type u) local infix ` .. `:41 := set.Icc /-- Execute a `gen` inside the `io` monad using `i` as the example size and with a fresh random number generator. -/ def io.run_gen {α} (x : gen α) (i : ℕ) : io α := io.run_rand (x.run ⟨i⟩) namespace gen section rand /-- Lift `random.random` to the `gen` monad. -/ def choose_any [random α] : gen α := ⟨ λ _, rand.random α ⟩ variables {α} [preorder α] /-- Lift `random.random_r` to the `gen` monad. -/ def choose [bounded_random α] (x y : α) (p : x ≤ y) : gen (x .. y) := ⟨ λ _, rand.random_r x y p ⟩ end rand open nat (hiding choose) /-- Generate a `nat` example between `x` and `y`. -/ def choose_nat (x y : ℕ) (p : x ≤ y) : gen (x .. y) := choose x y p /-- Generate a `nat` example between `x` and `y`. -/ def choose_nat' (x y : ℕ) (p : x < y) : gen (set.Ico x y) := have ∀ i, x < i → i ≤ y → i.pred < y, from λ i h₀ h₁, show i.pred.succ ≤ y, by rwa succ_pred_eq_of_pos; apply lt_of_le_of_lt (nat.zero_le _) h₀, subtype.map pred (λ i (h : x+1 ≤ i ∧ i ≤ y), ⟨le_pred_of_lt h.1, this _ h.1 h.2⟩) <$> choose (x+1) y p open nat instance : uliftable gen.{u} gen.{v} := reader_t.uliftable' (equiv.ulift.trans equiv.ulift.symm) instance : has_orelse gen.{u} := ⟨ λ α x y, do b ← uliftable.up $ choose_any bool, if b.down then x else y ⟩ variable {α} /-- Get access to the size parameter of the `gen` monad. For reasons of universe polymorphism, it is specified in continuation passing style. -/ def sized (cmd : ℕ → gen α) : gen α := ⟨ λ ⟨sz⟩, reader_t.run (cmd sz) ⟨sz⟩ ⟩ /-- Apply a function to the size parameter. -/ def resize (f : ℕ → ℕ) (cmd : gen α) : gen α := ⟨ λ ⟨sz⟩, reader_t.run cmd ⟨f sz⟩ ⟩ /-- Create `n` examples using `cmd`. -/ def vector_of : ∀ (n : ℕ) (cmd : gen α), gen (vector α n) | 0 _ := return vector.nil | (succ n) cmd := vector.cons <$> cmd <*> vector_of n cmd /-- Create a list of examples using `cmd`. The size is controlled by the size parameter of `gen`. -/ def list_of (cmd : gen α) : gen (list α) := sized $ λ sz, do do ⟨ n ⟩ ← uliftable.up $ choose_nat 0 (sz + 1) dec_trivial, v ← vector_of n.val cmd, return v.to_list open ulift /-- Given a list of example generators, choose one to create an example. -/ def one_of (xs : list (gen α)) (pos : 0 < xs.length) : gen α := do ⟨⟨n, h, h'⟩⟩ ← uliftable.up $ choose_nat' 0 xs.length pos, list.nth_le xs n h' /-- Given a list of example generators, choose one to create an example. -/ def elements (xs : list α) (pos : 0 < xs.length) : gen α := do ⟨⟨n,h₀,h₁⟩⟩ ← uliftable.up $ choose_nat' 0 xs.length pos, pure $ list.nth_le xs n h₁ /-- `freq_aux xs i _` takes a weighted list of generator and a number meant to select one of the generators. If we consider `freq_aux [(1, gena), (3, genb), (5, genc)] 4 _`, we choose a generator by splitting the interval 1-9 into 1-1, 2-4, 5-9 so that the width of each interval corresponds to one of the number in the list of generators. Then, we check which interval 4 falls into: it selects `genb`. -/ def freq_aux : Π (xs : list (ℕ+ × gen α)) i, i < (xs.map (subtype.val ∘ prod.fst)).sum → gen α | [] i h := false.elim (nat.not_lt_zero _ h) | ((i, x) :: xs) j h := if h' : j < i then x else freq_aux xs (j - i) (by { rw sub_lt_iff_right (le_of_not_gt h'), simpa [list.sum_cons, add_comm] using h }) /-- `freq [(1, gena), (3, genb), (5, genc)] _` will choose one of `gena`, `genb`, `genc` with probabilities proportional to the number accompanying them. In this example, the sum of those numbers is 9, `gena` will be chosen with probability ~1/9, `genb` with ~3/9 (i.e. 1/3) and `genc` with probability 5/9. -/ def freq (xs : list (ℕ+ × gen α)) (pos : 0 < xs.length) : gen α := let s := (xs.map (subtype.val ∘ prod.fst)).sum in have ha : 1 ≤ s, from (le_trans pos $ list.length_map (subtype.val ∘ prod.fst) xs ▸ (list.length_le_sum_of_one_le _ (λ i, by { simp, intros, assumption }))), have 0 ≤ s - 1, from le_sub_of_add_le_right' ha, uliftable.adapt_up gen.{0} gen.{u} (choose_nat 0 (s-1) this) $ λ i, freq_aux xs i.1 (by rcases i with ⟨i,h₀,h₁⟩; rwa le_sub_iff_right at h₁; exact ha) /-- Generate a random permutation of a given list. -/ def permutation_of {α : Type u} : Π xs : list α, gen (subtype $ list.perm xs) | [] := pure ⟨[], list.perm.nil ⟩ | (x :: xs) := do ⟨xs',h⟩ ← permutation_of xs, ⟨⟨n,_,h'⟩⟩ ← uliftable.up $ choose_nat 0 xs'.length dec_trivial, pure ⟨list.insert_nth n x xs', list.perm.trans (list.perm.cons _ h) (list.perm_insert_nth _ _ h').symm ⟩ end gen end slim_check
7f3dcb34714ca2e3520e74088212acaf5a8b39e9
957a80ea22c5abb4f4670b250d55534d9db99108
/tests/lean/cyclic_default_fields.lean
3c432f810581fbdb720e40d5bb0c10c80b4e8861
[ "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
179
lean
class Eq (α : Type) := (eq : α → α → Prop := λ a b, ¬ne a b) (ne : α → α → Prop := λ a b, ¬eq a b) #check ({eq := (=)} : Eq ℕ) #check ({ne := (≠)} : Eq ℕ)
13106b6e9e04f2a0edea69729809a3e0eb158eb6
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/heap_code.lean
57e3ee62dfa0051af946b2c10aa9790a0fb9970d
[ "Apache-2.0" ]
permissive
leanprover-community/lean
12b87f69d92e614daea8bcc9d4de9a9ace089d0e
cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0
refs/heads/master
1,687,508,156,644
1,684,951,104,000
1,684,951,104,000
169,960,991
457
107
Apache-2.0
1,686,744,372,000
1,549,790,268,000
C++
UTF-8
Lean
false
false
2,420
lean
structure coding := (code : Type) [code_dec_eq : decidable_eq code] (decode : code → Type) instance coding_code_has_dec_eq (β : coding) : decidable_eq β.code := β.code_dec_eq @[reducible] def typeof (β : coding) (c : β.code) : Type := β.decode c structure ref {code : Type} (c : code) := (idx : nat) structure heap (β : coding) := (next : nat) (mem : array next (Σ c : β.code, β.decode c)) def mk_heap (β : coding) : heap β := { next := 0, mem := array.nil } def mk_ref {β : coding} : heap β → Π c : β.code, typeof β c → ref c × heap β | ⟨n, mem⟩ c v := ({ idx := n }, ⟨n+1, mem.push_back ⟨c, v⟩⟩) def read {β : coding} {c : β.code} (h : heap β) (r : ref c) : option (typeof β c) := match h, r with | ⟨n, mem⟩, {idx := i} := if h₁ : i < n then let ⟨c', v⟩ := mem.read ⟨i, h₁⟩ in if h₂ : c' = c then eq.rec_on h₂ v else none else none end def write {β : coding} {c : β.code} (h : heap β) (r : ref c) (v : typeof β c) : heap β := match h, v with | ⟨n, mem⟩, v := if h₁ : r.idx < n then ⟨n, mem.write ⟨r.idx, h₁⟩ ⟨c, v⟩⟩ else h end @[derive decidable_eq] inductive simple_code | Pair : simple_code → simple_code → simple_code | Bool : simple_code | Nat : simple_code | Ref : simple_code → simple_code open simple_code def decode_simple_code : simple_code → Type | Bool := bool | Nat := nat | (Ref c) := ref c | (Pair c₁ c₂) := decode_simple_code c₁ × decode_simple_code c₂ def PairRefNat := Pair (Ref Nat) (Ref Nat) def C : coding := { code := simple_code, decode := decode_simple_code } def h : heap C := let h₀ := mk_heap C in let (r₀, h₁) := mk_ref h₀ Bool tt in let (r₁, h₂) := mk_ref h₁ Nat (10:nat) in let (r₂, h₃) := mk_ref h₂ PairRefNat (r₁, r₁) in let h₄ := write h₃ r₀ ff in let h₅ := write h₄ r₁ (20:nat) in h₅ def r₀ : ref Bool := { idx := 0 } def r₁ : ref Nat := { idx := 1 } def r₂ : ref PairRefNat := { idx := 2 } #eval @id (option nat) $ read h r₁ /- In the following example the type_context exposes the internal encoding of decode_simple_code. TODO(Leo): fix this issue by using refl lemmas. -/ #eval match read h r₂ : _ → option nat with | some (r, _) := read h r -- to observe problem, hover over the first `r` | none := some 0 end
e17c49520747882ac1a474affe87e9277178fdd7
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/category/Group/epi_mono.lean
c43176e057940f7ec6eaa8da4f465a34493b831c
[ "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
13,484
lean
/- Copyright (c) 2022 Jujian Zhang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jujian Zhang -/ import algebra.category.Group.equivalence_Group_AddGroup import group_theory.quotient_group /-! # Monomorphisms and epimorphisms in `Group` > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file, we prove monomorphisms in category of group are injective homomorphisms and epimorphisms are surjective homomorphisms. -/ noncomputable theory universes u v namespace monoid_hom open quotient_group variables {A : Type u} {B : Type v} section variables [group A] [group B] @[to_additive add_monoid_hom.ker_eq_bot_of_cancel] lemma ker_eq_bot_of_cancel {f : A →* B} (h : ∀ (u v : f.ker →* A), f.comp u = f.comp v → u = v) : f.ker = ⊥ := by simpa using _root_.congr_arg range (h f.ker.subtype 1 (by tidy)) end section variables [comm_group A] [comm_group B] @[to_additive add_monoid_hom.range_eq_top_of_cancel] lemma range_eq_top_of_cancel {f : A →* B} (h : ∀ (u v : B →* B ⧸ f.range), u.comp f = v.comp f → u = v) : f.range = ⊤ := begin specialize h 1 (quotient_group.mk' _) _, { ext1, simp only [one_apply, coe_comp, coe_mk', function.comp_app], rw [show (1 : B ⧸ f.range) = (1 : B), from quotient_group.coe_one _, quotient_group.eq, inv_one, one_mul], exact ⟨x, rfl⟩, }, replace h : (quotient_group.mk' _).ker = (1 : B →* B ⧸ f.range).ker := by rw h, rwa [ker_one, quotient_group.ker_mk] at h, end end end monoid_hom section open category_theory namespace Group variables {A B : Group.{u}} (f : A ⟶ B) @[to_additive AddGroup.ker_eq_bot_of_mono] lemma ker_eq_bot_of_mono [mono f] : f.ker = ⊥ := monoid_hom.ker_eq_bot_of_cancel $ λ u v, (@cancel_mono _ _ _ _ _ f _ (show Group.of f.ker ⟶ A, from u) _).1 @[to_additive AddGroup.mono_iff_ker_eq_bot] lemma mono_iff_ker_eq_bot : mono f ↔ f.ker = ⊥ := ⟨λ h, @@ker_eq_bot_of_mono f h, λ h, concrete_category.mono_of_injective _ $ (monoid_hom.ker_eq_bot_iff f).1 h⟩ @[to_additive AddGroup.mono_iff_injective] lemma mono_iff_injective : mono f ↔ function.injective f := iff.trans (mono_iff_ker_eq_bot f) $ monoid_hom.ker_eq_bot_iff f namespace surjective_of_epi_auxs local notation `X` := set.range (function.swap left_coset f.range.carrier) /-- Define `X'` to be the set of all left cosets with an extra point at "infinity". -/ @[nolint has_nonempty_instance] inductive X_with_infinity | from_coset : set.range (function.swap left_coset f.range.carrier) → X_with_infinity | infinity : X_with_infinity open X_with_infinity equiv.perm open_locale coset local notation `X'` := X_with_infinity f local notation `∞` := X_with_infinity.infinity local notation `SX'` := equiv.perm X' instance : has_smul B X' := { smul := λ b x, match x with | from_coset y := from_coset ⟨b *l y, begin rw [←subtype.val_eq_coe, ←y.2.some_spec, left_coset_assoc], use b * y.2.some, end⟩ | ∞ := ∞ end } lemma mul_smul (b b' : B) (x : X') : (b * b') • x = b • b' • x := match x with | from_coset y := begin change from_coset _ = from_coset _, simp only [←subtype.val_eq_coe, left_coset_assoc], end | ∞ := rfl end lemma one_smul (x : X') : (1 : B) • x = x := match x with | from_coset y := begin change from_coset _ = from_coset _, simp only [←subtype.val_eq_coe, one_left_coset, subtype.ext_iff_val], end | ∞ := rfl end lemma from_coset_eq_of_mem_range {b : B} (hb : b ∈ f.range) : from_coset ⟨b *l f.range.carrier, ⟨b, rfl⟩⟩ = from_coset ⟨f.range.carrier, ⟨1, one_left_coset _⟩⟩ := begin congr, change b *l f.range = f.range, nth_rewrite 1 [show (f.range : set B) = 1 *l f.range, from (one_left_coset _).symm], rw [left_coset_eq_iff, mul_one], exact subgroup.inv_mem _ hb, end lemma from_coset_ne_of_nin_range {b : B} (hb : b ∉ f.range) : from_coset ⟨b *l f.range.carrier, ⟨b, rfl⟩⟩ ≠ from_coset ⟨f.range.carrier, ⟨1, one_left_coset _⟩⟩ := begin intros r, simp only [subtype.mk_eq_mk] at r, change b *l f.range = f.range at r, nth_rewrite 1 [show (f.range : set B) = 1 *l f.range, from (one_left_coset _).symm] at r, rw [left_coset_eq_iff, mul_one] at r, exact hb (inv_inv b ▸ (subgroup.inv_mem _ r)), end instance : decidable_eq X' := classical.dec_eq _ /-- Let `τ` be the permutation on `X'` exchanging `f.range` and the point at infinity. -/ noncomputable def tau : SX' := equiv.swap (from_coset ⟨f.range.carrier, ⟨1, one_left_coset _⟩⟩) ∞ local notation `τ` := tau f lemma τ_apply_infinity : τ ∞ = from_coset ⟨f.range.carrier, ⟨1, one_left_coset _⟩⟩ := equiv.swap_apply_right _ _ lemma τ_apply_from_coset : τ (from_coset ⟨f.range.carrier, ⟨1, one_left_coset _⟩⟩) = ∞ := equiv.swap_apply_left _ _ lemma τ_apply_from_coset' (x : B) (hx : x ∈ f.range) : τ (from_coset ⟨x *l f.range.carrier, ⟨x, rfl⟩⟩) = ∞ := (from_coset_eq_of_mem_range _ hx).symm ▸ τ_apply_from_coset _ lemma τ_symm_apply_from_coset : (equiv.symm τ) (from_coset ⟨f.range.carrier, ⟨1, one_left_coset _⟩⟩) = ∞ := by rw [tau, equiv.symm_swap, equiv.swap_apply_left] lemma τ_symm_apply_infinity : (equiv.symm τ) ∞ = from_coset ⟨f.range.carrier, ⟨1, one_left_coset _⟩⟩ := by rw [tau, equiv.symm_swap, equiv.swap_apply_right] /-- Let `g : B ⟶ S(X')` be defined as such that, for any `β : B`, `g(β)` is the function sending point at infinity to point at infinity and sending coset `y` to `β *l y`. -/ def G : B →* SX' := { to_fun := λ β, { to_fun := λ x, β • x, inv_fun := λ x, β⁻¹ • x, left_inv := λ x, by { dsimp only, rw [←mul_smul, mul_left_inv, one_smul] }, right_inv := λ x, by { dsimp only, rw [←mul_smul, mul_right_inv, one_smul] } }, map_one' := by { ext, simp [one_smul] }, map_mul' := λ b1 b2, by { ext, simp [mul_smul] } } local notation `g` := G f /-- Define `h : B ⟶ S(X')` to be `τ g τ⁻¹` -/ def H : B →* SX':= { to_fun := λ β, ((τ).symm.trans (g β)).trans τ, map_one' := by { ext, simp }, map_mul' := λ b1 b2, by { ext, simp } } local notation `h` := H f /-! The strategy is the following: assuming `epi f` * prove that `f.range = {x | h x = g x}`; * thus `f ≫ h = f ≫ g` so that `h = g`; * but if `f` is not surjective, then some `x ∉ f.range`, then `h x ≠ g x` at the coset `f.range`. -/ lemma g_apply_from_coset (x : B) (y : X) : (g x) (from_coset y) = from_coset ⟨x *l y, by tidy⟩ := rfl lemma g_apply_infinity (x : B) : (g x) ∞ = ∞ := rfl lemma h_apply_infinity (x : B) (hx : x ∈ f.range) : (h x) ∞ = ∞ := begin simp only [H, monoid_hom.coe_mk, equiv.to_fun_as_coe, equiv.coe_trans, function.comp_app], rw [τ_symm_apply_infinity, g_apply_from_coset], simpa only [←subtype.val_eq_coe] using τ_apply_from_coset' f x hx, end lemma h_apply_from_coset (x : B) : (h x) (from_coset ⟨f.range.carrier, ⟨1, one_left_coset _⟩⟩) = from_coset ⟨f.range.carrier, ⟨1, one_left_coset _⟩⟩ := by simp [H, τ_symm_apply_from_coset, g_apply_infinity, τ_apply_infinity] lemma h_apply_from_coset' (x : B) (b : B) (hb : b ∈ f.range): (h x) (from_coset ⟨b *l f.range.carrier, ⟨b, rfl⟩⟩) = from_coset ⟨b *l f.range.carrier, ⟨b, rfl⟩⟩ := (from_coset_eq_of_mem_range _ hb).symm ▸ h_apply_from_coset f x lemma h_apply_from_coset_nin_range (x : B) (hx : x ∈ f.range) (b : B) (hb : b ∉ f.range) : (h x) (from_coset ⟨b *l f.range.carrier, ⟨b, rfl⟩⟩) = from_coset ⟨(x * b) *l f.range.carrier, ⟨x * b, rfl⟩⟩ := begin simp only [H, tau, monoid_hom.coe_mk, equiv.to_fun_as_coe, equiv.coe_trans, function.comp_app], rw [equiv.symm_swap, @equiv.swap_apply_of_ne_of_ne X' _ (from_coset ⟨f.range.carrier, ⟨1, one_left_coset _⟩⟩) ∞ (from_coset ⟨b *l f.range.carrier, ⟨b, rfl⟩⟩) (from_coset_ne_of_nin_range _ hb) (by simp)], simp only [g_apply_from_coset, ←subtype.val_eq_coe, left_coset_assoc], refine equiv.swap_apply_of_ne_of_ne (from_coset_ne_of_nin_range _ (λ r, hb _)) (by simp), convert subgroup.mul_mem _ (subgroup.inv_mem _ hx) r, rw [←mul_assoc, mul_left_inv, one_mul], end lemma agree : f.range.carrier = {x | h x = g x} := begin refine set.ext (λ b, ⟨_, λ (hb : h b = g b), classical.by_contradiction (λ r, _)⟩), { rintros ⟨a, rfl⟩, change h (f a) = g (f a), ext ⟨⟨_, ⟨y, rfl⟩⟩⟩, { rw [g_apply_from_coset], by_cases m : y ∈ f.range, { rw [h_apply_from_coset' _ _ _ m, from_coset_eq_of_mem_range _ m], change from_coset _ = from_coset ⟨f a *l (y *l _), _⟩, simpa only [←from_coset_eq_of_mem_range _ (subgroup.mul_mem _ ⟨a, rfl⟩ m), left_coset_assoc] }, { rw [h_apply_from_coset_nin_range _ _ ⟨_, rfl⟩ _ m], simpa only [←subtype.val_eq_coe, left_coset_assoc], }, }, { rw [g_apply_infinity, h_apply_infinity _ _ ⟨_, rfl⟩], } }, { have eq1 : (h b) (from_coset ⟨f.range.carrier, ⟨1, one_left_coset _⟩⟩) = (from_coset ⟨f.range.carrier, ⟨1, one_left_coset _⟩⟩) := by simp [H, tau, g_apply_infinity], have eq2 : (g b) (from_coset ⟨f.range.carrier, ⟨1, one_left_coset _⟩⟩) = (from_coset ⟨b *l f.range.carrier, ⟨b, rfl⟩⟩) := rfl, exact (from_coset_ne_of_nin_range _ r).symm (by rw [←eq1, ←eq2, fun_like.congr_fun hb]) } end lemma comp_eq : f ≫ (show B ⟶ Group.of SX', from g) = f ≫ h := fun_like.ext _ _ $ λ a, by simp only [comp_apply, show h (f a) = _, from (by simp [←agree] : f a ∈ {b | h b = g b})] lemma g_ne_h (x : B) (hx : x ∉ f.range) : g ≠ h := begin intros r, replace r := fun_like.congr_fun (fun_like.congr_fun r x) ((from_coset ⟨f.range, ⟨1, one_left_coset _⟩⟩)), rw [H, g_apply_from_coset, monoid_hom.coe_mk, tau] at r, simp only [monoid_hom.coe_range, subtype.coe_mk, equiv.symm_swap, equiv.to_fun_as_coe, equiv.coe_trans, function.comp_app] at r, erw [equiv.swap_apply_left, g_apply_infinity, equiv.swap_apply_right] at r, exact from_coset_ne_of_nin_range _ hx r, end end surjective_of_epi_auxs lemma surjective_of_epi [epi f] : function.surjective f := begin by_contra r, push_neg at r, rcases r with ⟨b, hb⟩, exact surjective_of_epi_auxs.g_ne_h f b (λ ⟨c, hc⟩, hb _ hc) ((cancel_epi f).1 (surjective_of_epi_auxs.comp_eq f)), end lemma epi_iff_surjective : epi f ↔ function.surjective f := ⟨λ h, @@surjective_of_epi f h, concrete_category.epi_of_surjective _⟩ lemma epi_iff_range_eq_top : epi f ↔ f.range = ⊤ := iff.trans (epi_iff_surjective _) (subgroup.eq_top_iff' f.range).symm end Group namespace AddGroup variables {A B : AddGroup.{u}} (f : A ⟶ B) lemma epi_iff_surjective : epi f ↔ function.surjective f := begin have i1 : epi f ↔ epi (Group_AddGroup_equivalence.inverse.map f), { refine ⟨_, Group_AddGroup_equivalence.inverse.epi_of_epi_map⟩, introsI e', apply Group_AddGroup_equivalence.inverse.map_epi }, rwa Group.epi_iff_surjective at i1, end lemma epi_iff_range_eq_top : epi f ↔ f.range = ⊤ := iff.trans (epi_iff_surjective _) (add_subgroup.eq_top_iff' f.range).symm end AddGroup namespace Group variables {A B : Group.{u}} (f : A ⟶ B) @[to_additive] instance forget_Group_preserves_mono : (forget Group).preserves_monomorphisms := { preserves := λ X Y f e, by rwa [mono_iff_injective, ←category_theory.mono_iff_injective] at e } @[to_additive] instance forget_Group_preserves_epi : (forget Group).preserves_epimorphisms := { preserves := λ X Y f e, by rwa [epi_iff_surjective, ←category_theory.epi_iff_surjective] at e } end Group namespace CommGroup variables {A B : CommGroup.{u}} (f : A ⟶ B) @[to_additive AddCommGroup.ker_eq_bot_of_mono] lemma ker_eq_bot_of_mono [mono f] : f.ker = ⊥ := monoid_hom.ker_eq_bot_of_cancel $ λ u v, (@cancel_mono _ _ _ _ _ f _ (show CommGroup.of f.ker ⟶ A, from u) _).1 @[to_additive AddCommGroup.mono_iff_ker_eq_bot] lemma mono_iff_ker_eq_bot : mono f ↔ f.ker = ⊥ := ⟨λ h, @@ker_eq_bot_of_mono f h, λ h, concrete_category.mono_of_injective _ $ (monoid_hom.ker_eq_bot_iff f).1 h⟩ @[to_additive AddCommGroup.mono_iff_injective] lemma mono_iff_injective : mono f ↔ function.injective f := iff.trans (mono_iff_ker_eq_bot f) $ monoid_hom.ker_eq_bot_iff f @[to_additive] lemma range_eq_top_of_epi [epi f] : f.range = ⊤ := monoid_hom.range_eq_top_of_cancel $ λ u v h, (@cancel_epi _ _ _ _ _ f _ (show B ⟶ ⟨B ⧸ monoid_hom.range f⟩, from u) v).1 h @[to_additive] lemma epi_iff_range_eq_top : epi f ↔ f.range = ⊤ := ⟨λ hf, by exactI range_eq_top_of_epi _, λ hf, concrete_category.epi_of_surjective _ $ monoid_hom.range_top_iff_surjective.mp hf⟩ @[to_additive] lemma epi_iff_surjective : epi f ↔ function.surjective f := by rw [epi_iff_range_eq_top, monoid_hom.range_top_iff_surjective] @[to_additive] instance forget_CommGroup_preserves_mono : (forget CommGroup).preserves_monomorphisms := { preserves := λ X Y f e, by rwa [mono_iff_injective, ←category_theory.mono_iff_injective] at e } @[to_additive] instance forget_CommGroup_preserves_epi : (forget CommGroup).preserves_epimorphisms := { preserves := λ X Y f e, by rwa [epi_iff_surjective, ←category_theory.epi_iff_surjective] at e } end CommGroup end
7de64ae80a2c6e73c360ba950cfe354d24d4592e
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/ring_theory/graded_algebra/homogeneous_ideal.lean
535d934b73de82e1a6a91f4e1e03eec8eedad46d
[ "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
21,624
lean
/- Copyright (c) 2021 Jujian Zhang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jujian Zhang, Eric Wieser -/ import ring_theory.ideal.basic import ring_theory.ideal.operations import linear_algebra.finsupp import ring_theory.graded_algebra.basic /-! # Homogeneous ideals of a graded algebra > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines homogeneous ideals of `graded_ring 𝒜` where `𝒜 : ι → submodule R A` and operations on them. ## Main definitions For any `I : ideal A`: * `ideal.is_homogeneous 𝒜 I`: The property that an ideal is closed under `graded_ring.proj`. * `homogeneous_ideal 𝒜`: The structure extending ideals which satisfy `ideal.is_homogeneous` * `ideal.homogeneous_core I 𝒜`: The largest homogeneous ideal smaller than `I`. * `ideal.homogeneous_hull I 𝒜`: The smallest homogeneous ideal larger than `I`. ## Main statements * `homogeneous_ideal.complete_lattice`: `ideal.is_homogeneous` is preserved by `⊥`, `⊤`, `⊔`, `⊓`, `⨆`, `⨅`, and so the subtype of homogeneous ideals inherits a complete lattice structure. * `ideal.homogeneous_core.gi`: `ideal.homogeneous_core` forms a galois insertion with coercion. * `ideal.homogeneous_hull.gi`: `ideal.homogeneous_hull` forms a galois insertion with coercion. ## Implementation notes We introduce `ideal.homogeneous_core'` earlier than might be expected so that we can get access to `ideal.is_homogeneous.iff_exists` as quickly as possible. ## Tags graded algebra, homogeneous -/ open set_like direct_sum set open_locale big_operators pointwise direct_sum variables {ι σ R A : Type*} section homogeneous_def variables [semiring A] variables [set_like σ A] [add_submonoid_class σ A] (𝒜 : ι → σ) variables [decidable_eq ι] [add_monoid ι] [graded_ring 𝒜] variable (I : ideal A) include A /--An `I : ideal A` is homogeneous if for every `r ∈ I`, all homogeneous components of `r` are in `I`.-/ def ideal.is_homogeneous : Prop := ∀ (i : ι) ⦃r : A⦄, r ∈ I → (direct_sum.decompose 𝒜 r i : A) ∈ I /-- For any `semiring A`, we collect the homogeneous ideals of `A` into a type. -/ structure homogeneous_ideal extends submodule A A := (is_homogeneous' : ideal.is_homogeneous 𝒜 to_submodule) variable {𝒜} /--Converting a homogeneous ideal to an ideal-/ def homogeneous_ideal.to_ideal (I : homogeneous_ideal 𝒜) : ideal A := I.to_submodule lemma homogeneous_ideal.is_homogeneous (I : homogeneous_ideal 𝒜) : I.to_ideal.is_homogeneous 𝒜 := I.is_homogeneous' lemma homogeneous_ideal.to_ideal_injective : function.injective (homogeneous_ideal.to_ideal : homogeneous_ideal 𝒜 → ideal A) := λ ⟨x, hx⟩ ⟨y, hy⟩ (h : x = y), by simp [h] instance homogeneous_ideal.set_like : set_like (homogeneous_ideal 𝒜) A := { coe := λ I, I.to_ideal, coe_injective' := λ I J h, homogeneous_ideal.to_ideal_injective $ set_like.coe_injective h } @[ext] lemma homogeneous_ideal.ext {I J : homogeneous_ideal 𝒜} (h : I.to_ideal = J.to_ideal) : I = J := homogeneous_ideal.to_ideal_injective h @[simp] lemma homogeneous_ideal.mem_iff {I : homogeneous_ideal 𝒜} {x : A} : x ∈ I.to_ideal ↔ x ∈ I := iff.rfl end homogeneous_def section homogeneous_core variables [semiring A] variables [set_like σ A] (𝒜 : ι → σ) variable (I : ideal A) include A /-- For any `I : ideal A`, not necessarily homogeneous, `I.homogeneous_core' 𝒜` is the largest homogeneous ideal of `A` contained in `I`, as an ideal. -/ def ideal.homogeneous_core' (I : ideal A) : ideal A := ideal.span (coe '' ((coe : subtype (is_homogeneous 𝒜) → A) ⁻¹' I)) lemma ideal.homogeneous_core'_mono : monotone (ideal.homogeneous_core' 𝒜) := λ I J I_le_J, ideal.span_mono $ set.image_subset _ $ λ x, @I_le_J _ lemma ideal.homogeneous_core'_le : I.homogeneous_core' 𝒜 ≤ I := ideal.span_le.2 $ image_preimage_subset _ _ end homogeneous_core section is_homogeneous_ideal_defs variables [semiring A] variables [set_like σ A] [add_submonoid_class σ A] (𝒜 : ι → σ) variables [decidable_eq ι] [add_monoid ι] [graded_ring 𝒜] variable (I : ideal A) include A lemma ideal.is_homogeneous_iff_forall_subset : I.is_homogeneous 𝒜 ↔ ∀ i, (I : set A) ⊆ graded_ring.proj 𝒜 i ⁻¹' I := iff.rfl lemma ideal.is_homogeneous_iff_subset_Inter : I.is_homogeneous 𝒜 ↔ (I : set A) ⊆ ⋂ i, graded_ring.proj 𝒜 i ⁻¹' ↑I := subset_Inter_iff.symm lemma ideal.mul_homogeneous_element_mem_of_mem {I : ideal A} (r x : A) (hx₁ : is_homogeneous 𝒜 x) (hx₂ : x ∈ I) (j : ι) : graded_ring.proj 𝒜 j (r * x) ∈ I := begin classical, rw [←direct_sum.sum_support_decompose 𝒜 r, finset.sum_mul, map_sum], apply ideal.sum_mem, intros k hk, obtain ⟨i, hi⟩ := hx₁, have mem₁ : (direct_sum.decompose 𝒜 r k : A) * x ∈ 𝒜 (k + i) := graded_monoid.mul_mem (set_like.coe_mem _) hi, erw [graded_ring.proj_apply, direct_sum.decompose_of_mem 𝒜 mem₁, coe_of_apply, set_like.coe_mk], split_ifs, { exact I.mul_mem_left _ hx₂ }, { exact I.zero_mem }, end lemma ideal.is_homogeneous_span (s : set A) (h : ∀ x ∈ s, is_homogeneous 𝒜 x) : (ideal.span s).is_homogeneous 𝒜 := begin rintros i r hr, rw [ideal.span, finsupp.span_eq_range_total] at hr, rw linear_map.mem_range at hr, obtain ⟨s, rfl⟩ := hr, rw [finsupp.total_apply, finsupp.sum, decompose_sum, dfinsupp.finset_sum_apply, add_submonoid_class.coe_finset_sum], refine ideal.sum_mem _ _, rintros z hz1, rw [smul_eq_mul], refine ideal.mul_homogeneous_element_mem_of_mem 𝒜 (s z) z _ _ i, { rcases z with ⟨z, hz2⟩, apply h _ hz2, }, { exact ideal.subset_span z.2 }, end /--For any `I : ideal A`, not necessarily homogeneous, `I.homogeneous_core' 𝒜` is the largest homogeneous ideal of `A` contained in `I`.-/ def ideal.homogeneous_core : homogeneous_ideal 𝒜 := ⟨ideal.homogeneous_core' 𝒜 I, ideal.is_homogeneous_span _ _ (λ x h, by { rw [subtype.image_preimage_coe] at h, exact h.2 })⟩ lemma ideal.homogeneous_core_mono : monotone (ideal.homogeneous_core 𝒜) := ideal.homogeneous_core'_mono 𝒜 lemma ideal.to_ideal_homogeneous_core_le : (I.homogeneous_core 𝒜).to_ideal ≤ I := ideal.homogeneous_core'_le 𝒜 I variables {𝒜 I} lemma ideal.mem_homogeneous_core_of_is_homogeneous_of_mem {x : A} (h : set_like.is_homogeneous 𝒜 x) (hmem : x ∈ I) : x ∈ I.homogeneous_core 𝒜 := ideal.subset_span ⟨⟨x, h⟩, hmem, rfl⟩ lemma ideal.is_homogeneous.to_ideal_homogeneous_core_eq_self (h : I.is_homogeneous 𝒜) : (I.homogeneous_core 𝒜).to_ideal = I := begin apply le_antisymm (I.homogeneous_core'_le 𝒜) _, intros x hx, classical, rw ←direct_sum.sum_support_decompose 𝒜 x, exact ideal.sum_mem _ (λ j hj, ideal.subset_span ⟨⟨_, is_homogeneous_coe _⟩, h _ hx, rfl⟩) end @[simp] lemma homogeneous_ideal.to_ideal_homogeneous_core_eq_self (I : homogeneous_ideal 𝒜) : I.to_ideal.homogeneous_core 𝒜 = I := by ext1; convert ideal.is_homogeneous.to_ideal_homogeneous_core_eq_self I.is_homogeneous variables (𝒜 I) lemma ideal.is_homogeneous.iff_eq : I.is_homogeneous 𝒜 ↔ (I.homogeneous_core 𝒜).to_ideal = I := ⟨ λ hI, hI.to_ideal_homogeneous_core_eq_self, λ hI, hI ▸ (ideal.homogeneous_core 𝒜 I).2 ⟩ lemma ideal.is_homogeneous.iff_exists : I.is_homogeneous 𝒜 ↔ ∃ (S : set (homogeneous_submonoid 𝒜)), I = ideal.span (coe '' S) := begin rw [ideal.is_homogeneous.iff_eq, eq_comm], exact ((set.image_preimage.compose (submodule.gi _ _).gc).exists_eq_l _).symm, end end is_homogeneous_ideal_defs /-! ### Operations In this section, we show that `ideal.is_homogeneous` is preserved by various notations, then use these results to provide these notation typeclasses for `homogeneous_ideal`. -/ section operations section semiring variables [semiring A] [decidable_eq ι] [add_monoid ι] variables [set_like σ A] [add_submonoid_class σ A] (𝒜 : ι → σ) [graded_ring 𝒜] include A namespace ideal.is_homogeneous lemma bot : ideal.is_homogeneous 𝒜 ⊥ := λ i r hr, begin simp only [ideal.mem_bot] at hr, rw [hr, decompose_zero, zero_apply], apply ideal.zero_mem end lemma top : ideal.is_homogeneous 𝒜 ⊤ := λ i r hr, by simp only [submodule.mem_top] variables {𝒜} lemma inf {I J : ideal A} (HI : I.is_homogeneous 𝒜) (HJ : J.is_homogeneous 𝒜) : (I ⊓ J).is_homogeneous 𝒜 := λ i r hr, ⟨HI _ hr.1, HJ _ hr.2⟩ lemma sup {I J : ideal A} (HI : I.is_homogeneous 𝒜) (HJ : J.is_homogeneous 𝒜) : (I ⊔ J).is_homogeneous 𝒜 := begin rw iff_exists at HI HJ ⊢, obtain ⟨⟨s₁, rfl⟩, ⟨s₂, rfl⟩⟩ := ⟨HI, HJ⟩, refine ⟨s₁ ∪ s₂, _⟩, rw [set.image_union], exact (submodule.span_union _ _).symm, end protected lemma supr {κ : Sort*} {f : κ → ideal A} (h : ∀ i, (f i).is_homogeneous 𝒜) : (⨆ i, f i).is_homogeneous 𝒜 := begin simp_rw iff_exists at h ⊢, choose s hs using h, refine ⟨⋃ i, s i, _⟩, simp_rw [set.image_Union, ideal.span_Union], congr', exact funext hs, end protected lemma infi {κ : Sort*} {f : κ → ideal A} (h : ∀ i, (f i).is_homogeneous 𝒜) : (⨅ i, f i).is_homogeneous 𝒜 := begin intros i x hx, simp only [ideal.mem_infi] at ⊢ hx, exact λ j, h _ _ (hx j), end lemma supr₂ {κ : Sort*} {κ' : κ → Sort*} {f : Π i, κ' i → ideal A} (h : ∀ i j, (f i j).is_homogeneous 𝒜) : (⨆ i j, f i j).is_homogeneous 𝒜 := is_homogeneous.supr $ λ i, is_homogeneous.supr $ h i lemma infi₂ {κ : Sort*} {κ' : κ → Sort*} {f : Π i, κ' i → ideal A} (h : ∀ i j, (f i j).is_homogeneous 𝒜) : (⨅ i j, f i j).is_homogeneous 𝒜 := is_homogeneous.infi $ λ i, is_homogeneous.infi $ h i lemma Sup {ℐ : set (ideal A)} (h : ∀ I ∈ ℐ, ideal.is_homogeneous 𝒜 I) : (Sup ℐ).is_homogeneous 𝒜 := by { rw Sup_eq_supr, exact supr₂ h } lemma Inf {ℐ : set (ideal A)} (h : ∀ I ∈ ℐ, ideal.is_homogeneous 𝒜 I) : (Inf ℐ).is_homogeneous 𝒜 := by { rw Inf_eq_infi, exact infi₂ h } end ideal.is_homogeneous variables {𝒜} namespace homogeneous_ideal instance : partial_order (homogeneous_ideal 𝒜) := set_like.partial_order instance : has_top (homogeneous_ideal 𝒜) := ⟨⟨⊤, ideal.is_homogeneous.top 𝒜⟩⟩ instance : has_bot (homogeneous_ideal 𝒜) := ⟨⟨⊥, ideal.is_homogeneous.bot 𝒜⟩⟩ instance : has_sup (homogeneous_ideal 𝒜) := ⟨λ I J, ⟨_, I.is_homogeneous.sup J.is_homogeneous⟩⟩ instance : has_inf (homogeneous_ideal 𝒜) := ⟨λ I J, ⟨_, I.is_homogeneous.inf J.is_homogeneous⟩⟩ instance : has_Sup (homogeneous_ideal 𝒜) := ⟨λ S, ⟨⨆ s ∈ S, to_ideal s, ideal.is_homogeneous.supr₂ $ λ s _, s.is_homogeneous⟩⟩ instance : has_Inf (homogeneous_ideal 𝒜) := ⟨λ S, ⟨⨅ s ∈ S, to_ideal s, ideal.is_homogeneous.infi₂ $ λ s _, s.is_homogeneous⟩⟩ @[simp] lemma coe_top : ((⊤ : homogeneous_ideal 𝒜) : set A) = univ := rfl @[simp] lemma coe_bot : ((⊥ : homogeneous_ideal 𝒜) : set A) = 0 := rfl @[simp] lemma coe_sup (I J : homogeneous_ideal 𝒜) : ↑(I ⊔ J) = (I + J : set A) := submodule.coe_sup _ _ @[simp] lemma coe_inf (I J : homogeneous_ideal 𝒜) : (↑(I ⊓ J) : set A) = I ∩ J := rfl @[simp] lemma to_ideal_top : (⊤ : homogeneous_ideal 𝒜).to_ideal = (⊤ : ideal A) := rfl @[simp] lemma to_ideal_bot : (⊥ : homogeneous_ideal 𝒜).to_ideal = (⊥ : ideal A) := rfl @[simp] lemma to_ideal_sup (I J : homogeneous_ideal 𝒜) : (I ⊔ J).to_ideal = I.to_ideal ⊔ J.to_ideal := rfl @[simp] lemma to_ideal_inf (I J : homogeneous_ideal 𝒜) : (I ⊓ J).to_ideal = I.to_ideal ⊓ J.to_ideal := rfl @[simp] lemma to_ideal_Sup (ℐ : set (homogeneous_ideal 𝒜)) : (Sup ℐ).to_ideal = ⨆ s ∈ ℐ, to_ideal s := rfl @[simp] lemma to_ideal_Inf (ℐ : set (homogeneous_ideal 𝒜)) : (Inf ℐ).to_ideal = ⨅ s ∈ ℐ, to_ideal s := rfl @[simp] lemma to_ideal_supr {κ : Sort*} (s : κ → homogeneous_ideal 𝒜) : (⨆ i, s i).to_ideal = ⨆ i, (s i).to_ideal := by rw [supr, to_ideal_Sup, supr_range] @[simp] lemma to_ideal_infi {κ : Sort*} (s : κ → homogeneous_ideal 𝒜) : (⨅ i, s i).to_ideal = ⨅ i, (s i).to_ideal := by rw [infi, to_ideal_Inf, infi_range] @[simp] lemma to_ideal_supr₂ {κ : Sort*} {κ' : κ → Sort*} (s : Π i, κ' i → homogeneous_ideal 𝒜) : (⨆ i j, s i j).to_ideal = ⨆ i j, (s i j).to_ideal := by simp_rw to_ideal_supr @[simp] lemma to_ideal_infi₂ {κ : Sort*} {κ' : κ → Sort*} (s : Π i, κ' i → homogeneous_ideal 𝒜) : (⨅ i j, s i j).to_ideal = ⨅ i j, (s i j).to_ideal := by simp_rw to_ideal_infi @[simp] lemma eq_top_iff (I : homogeneous_ideal 𝒜) : I = ⊤ ↔ I.to_ideal = ⊤ := to_ideal_injective.eq_iff.symm @[simp] lemma eq_bot_iff (I : homogeneous_ideal 𝒜) : I = ⊥ ↔ I.to_ideal = ⊥ := to_ideal_injective.eq_iff.symm instance : complete_lattice (homogeneous_ideal 𝒜) := to_ideal_injective.complete_lattice _ to_ideal_sup to_ideal_inf to_ideal_Sup to_ideal_Inf to_ideal_top to_ideal_bot instance : has_add (homogeneous_ideal 𝒜) := ⟨(⊔)⟩ @[simp] lemma to_ideal_add (I J : homogeneous_ideal 𝒜) : (I + J).to_ideal = I.to_ideal + J.to_ideal := rfl instance : inhabited (homogeneous_ideal 𝒜) := { default := ⊥ } end homogeneous_ideal end semiring section comm_semiring variables [comm_semiring A] variables [decidable_eq ι] [add_monoid ι] variables [set_like σ A] [add_submonoid_class σ A] {𝒜 : ι → σ} [graded_ring 𝒜] variable (I : ideal A) include A lemma ideal.is_homogeneous.mul {I J : ideal A} (HI : I.is_homogeneous 𝒜) (HJ : J.is_homogeneous 𝒜) : (I * J).is_homogeneous 𝒜 := begin rw ideal.is_homogeneous.iff_exists at HI HJ ⊢, obtain ⟨⟨s₁, rfl⟩, ⟨s₂, rfl⟩⟩ := ⟨HI, HJ⟩, rw ideal.span_mul_span', exact ⟨s₁ * s₂, congr_arg _ $ (set.image_mul (homogeneous_submonoid 𝒜).subtype).symm⟩, end variables {𝒜} instance : has_mul (homogeneous_ideal 𝒜) := { mul := λ I J, ⟨I.to_ideal * J.to_ideal, I.is_homogeneous.mul J.is_homogeneous⟩ } @[simp] lemma homogeneous_ideal.to_ideal_mul (I J : homogeneous_ideal 𝒜) : (I * J).to_ideal = I.to_ideal * J.to_ideal := rfl end comm_semiring end operations /-! ### Homogeneous core Note that many results about the homogeneous core came earlier in this file, as they are helpful for building the lattice structure. -/ section homogeneous_core open homogeneous_ideal variables [semiring A] [decidable_eq ι] [add_monoid ι] variables [set_like σ A] [add_submonoid_class σ A] (𝒜 : ι → σ) [graded_ring 𝒜] variable (I : ideal A) include A lemma ideal.homogeneous_core.gc : galois_connection to_ideal (ideal.homogeneous_core 𝒜) := λ I J, ⟨ λ H, I.to_ideal_homogeneous_core_eq_self ▸ ideal.homogeneous_core_mono 𝒜 H, λ H, le_trans H (ideal.homogeneous_core'_le _ _)⟩ /--`to_ideal : homogeneous_ideal 𝒜 → ideal A` and `ideal.homogeneous_core 𝒜` forms a galois coinsertion-/ def ideal.homogeneous_core.gi : galois_coinsertion to_ideal (ideal.homogeneous_core 𝒜) := { choice := λ I HI, ⟨I, le_antisymm (I.to_ideal_homogeneous_core_le 𝒜) HI ▸ homogeneous_ideal.is_homogeneous _⟩, gc := ideal.homogeneous_core.gc 𝒜, u_l_le := λ I, ideal.homogeneous_core'_le _ _, choice_eq := λ I H, le_antisymm H (I.to_ideal_homogeneous_core_le _) } lemma ideal.homogeneous_core_eq_Sup : I.homogeneous_core 𝒜 = Sup {J : homogeneous_ideal 𝒜 | J.to_ideal ≤ I} := eq.symm $ is_lub.Sup_eq $ (ideal.homogeneous_core.gc 𝒜).is_greatest_u.is_lub lemma ideal.homogeneous_core'_eq_Sup : I.homogeneous_core' 𝒜 = Sup {J : ideal A | J.is_homogeneous 𝒜 ∧ J ≤ I} := begin refine (is_lub.Sup_eq _).symm, apply is_greatest.is_lub, have coe_mono : monotone (to_ideal : homogeneous_ideal 𝒜 → ideal A) := λ x y, id, convert coe_mono.map_is_greatest (ideal.homogeneous_core.gc 𝒜).is_greatest_u using 1, ext, rw [mem_image, mem_set_of_eq], refine ⟨λ hI, ⟨⟨x, hI.1⟩, ⟨hI.2, rfl⟩⟩, by rintro ⟨x, ⟨hx, rfl⟩⟩; exact ⟨x.is_homogeneous, hx⟩⟩, end end homogeneous_core /-! ### Homogeneous hulls -/ section homogeneous_hull open homogeneous_ideal variables [semiring A] [decidable_eq ι] [add_monoid ι] variables [set_like σ A] [add_submonoid_class σ A] (𝒜 : ι → σ) [graded_ring 𝒜] variable (I : ideal A) include A /--For any `I : ideal A`, not necessarily homogeneous, `I.homogeneous_hull 𝒜` is the smallest homogeneous ideal containing `I`. -/ def ideal.homogeneous_hull : homogeneous_ideal 𝒜 := ⟨ideal.span {r : A | ∃ (i : ι) (x : I), (direct_sum.decompose 𝒜 (x : A) i : A) = r}, begin refine ideal.is_homogeneous_span _ _ (λ x hx, _), obtain ⟨i, x, rfl⟩ := hx, apply set_like.is_homogeneous_coe end⟩ lemma ideal.le_to_ideal_homogeneous_hull : I ≤ (ideal.homogeneous_hull 𝒜 I).to_ideal := begin intros r hr, classical, rw [←direct_sum.sum_support_decompose 𝒜 r], refine ideal.sum_mem _ _, intros j hj, apply ideal.subset_span, use j, use ⟨r, hr⟩, refl, end lemma ideal.homogeneous_hull_mono : monotone (ideal.homogeneous_hull 𝒜) := λ I J I_le_J, begin apply ideal.span_mono, rintros r ⟨hr1, ⟨x, hx⟩, rfl⟩, refine ⟨hr1, ⟨⟨x, I_le_J hx⟩, rfl⟩⟩, end variables {I 𝒜} lemma ideal.is_homogeneous.to_ideal_homogeneous_hull_eq_self (h : I.is_homogeneous 𝒜) : (ideal.homogeneous_hull 𝒜 I).to_ideal = I := begin apply le_antisymm _ (ideal.le_to_ideal_homogeneous_hull _ _), apply (ideal.span_le).2, rintros _ ⟨i, x, rfl⟩, exact h _ x.prop, end @[simp] lemma homogeneous_ideal.homogeneous_hull_to_ideal_eq_self (I : homogeneous_ideal 𝒜) : I.to_ideal.homogeneous_hull 𝒜 = I := homogeneous_ideal.to_ideal_injective $ I.is_homogeneous.to_ideal_homogeneous_hull_eq_self variables (I 𝒜) lemma ideal.to_ideal_homogeneous_hull_eq_supr : (I.homogeneous_hull 𝒜).to_ideal = ⨆ i, ideal.span (graded_ring.proj 𝒜 i '' I) := begin rw ←ideal.span_Union, apply congr_arg ideal.span _, ext1, simp only [set.mem_Union, set.mem_image, mem_set_of_eq, graded_ring.proj_apply, set_like.exists, exists_prop, subtype.coe_mk, set_like.mem_coe], end lemma ideal.homogeneous_hull_eq_supr : (I.homogeneous_hull 𝒜) = ⨆ i, ⟨ideal.span (graded_ring.proj 𝒜 i '' I), ideal.is_homogeneous_span 𝒜 _ (by {rintros _ ⟨x, -, rfl⟩, apply set_like.is_homogeneous_coe})⟩ := by { ext1, rw [ideal.to_ideal_homogeneous_hull_eq_supr, to_ideal_supr], refl } end homogeneous_hull section galois_connection open homogeneous_ideal variables [semiring A] [decidable_eq ι] [add_monoid ι] variables [set_like σ A] [add_submonoid_class σ A] (𝒜 : ι → σ) [graded_ring 𝒜] include A lemma ideal.homogeneous_hull.gc : galois_connection (ideal.homogeneous_hull 𝒜) to_ideal := λ I J, ⟨ le_trans (ideal.le_to_ideal_homogeneous_hull _ _), λ H, J.homogeneous_hull_to_ideal_eq_self ▸ ideal.homogeneous_hull_mono 𝒜 H⟩ /-- `ideal.homogeneous_hull 𝒜` and `to_ideal : homogeneous_ideal 𝒜 → ideal A` form a galois insertion-/ def ideal.homogeneous_hull.gi : galois_insertion (ideal.homogeneous_hull 𝒜) to_ideal := { choice := λ I H, ⟨I, le_antisymm H (I.le_to_ideal_homogeneous_hull 𝒜) ▸ is_homogeneous _⟩, gc := ideal.homogeneous_hull.gc 𝒜, le_l_u := λ I, ideal.le_to_ideal_homogeneous_hull _ _, choice_eq := λ I H, le_antisymm (I.le_to_ideal_homogeneous_hull 𝒜) H} lemma ideal.homogeneous_hull_eq_Inf (I : ideal A) : ideal.homogeneous_hull 𝒜 I = Inf { J : homogeneous_ideal 𝒜 | I ≤ J.to_ideal } := eq.symm $ is_glb.Inf_eq $ (ideal.homogeneous_hull.gc 𝒜).is_least_l.is_glb end galois_connection section irrelevant_ideal variables [semiring A] variables [decidable_eq ι] variables [canonically_ordered_add_monoid ι] variables [set_like σ A] [add_submonoid_class σ A] (𝒜 : ι → σ) [graded_ring 𝒜] include A open graded_ring set_like.graded_monoid direct_sum /-- For a graded ring `⨁ᵢ 𝒜ᵢ` graded by a `canonically_ordered_add_monoid ι`, the irrelevant ideal refers to `⨁_{i>0} 𝒜ᵢ`, or equivalently `{a | a₀ = 0}`. This definition is used in `Proj` construction where `ι` is always `ℕ` so the irrelevant ideal is simply elements with `0` as 0-th coordinate. # Future work Here in the definition, `ι` is assumed to be `canonically_ordered_add_monoid`. However, the notion of irrelevant ideal makes sense in a more general setting by defining it as the ideal of elements with `0` as i-th coordinate for all `i ≤ 0`, i.e. `{a | ∀ (i : ι), i ≤ 0 → aᵢ = 0}`. -/ def homogeneous_ideal.irrelevant : homogeneous_ideal 𝒜 := ⟨(graded_ring.proj_zero_ring_hom 𝒜).ker, λ i r (hr : (decompose 𝒜 r 0 : A) = 0), begin change (decompose 𝒜 (decompose 𝒜 r _ : A) 0 : A) = 0, by_cases h : i = 0, { rw [h, hr, decompose_zero, zero_apply, zero_mem_class.coe_zero] }, { rw [decompose_of_mem_ne 𝒜 (set_like.coe_mem _) h] } end⟩ @[simp] lemma homogeneous_ideal.mem_irrelevant_iff (a : A) : a ∈ homogeneous_ideal.irrelevant 𝒜 ↔ proj 𝒜 0 a = 0 := iff.rfl @[simp] lemma homogeneous_ideal.to_ideal_irrelevant : (homogeneous_ideal.irrelevant 𝒜).to_ideal = (graded_ring.proj_zero_ring_hom 𝒜).ker := rfl end irrelevant_ideal
3db1344ad0ef18affac0b0180d3db33a94131777
432d948a4d3d242fdfb44b81c9e1b1baacd58617
/src/ring_theory/valuation/basic.lean
cb27f4ed81d6b70713d46c58dd7d6b97669c692c
[ "Apache-2.0" ]
permissive
JLimperg/aesop3
306cc6570c556568897ed2e508c8869667252e8a
a4a116f650cc7403428e72bd2e2c4cda300fe03f
refs/heads/master
1,682,884,916,368
1,620,320,033,000
1,620,320,033,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
23,252
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Buzzard, Johan Commelin, Patrick Massot -/ import algebra.linear_ordered_comm_group_with_zero import algebra.group_power import ring_theory.ideal.operations import algebra.punit_instances /-! # The basics of valuation theory. The basic theory of valuations (non-archimedean norms) on a commutative ring, following T. Wedhorn's unpublished notes “Adic Spaces” ([wedhorn_adic]). The definition of a valuation we use here is Definition 1.22 of [wedhorn_adic]. A valuation on a ring `R` is a monoid homomorphism `v` to a linearly ordered commutative monoid with zero, that in addition satisfies the following two axioms: * `v 0 = 0` * `∀ x y, v (x + y) ≤ max (v x) (v y)` `valuation R Γ₀`is the type of valuations `R → Γ₀`, with a coercion to the underlying function. If `v` is a valuation from `R` to `Γ₀` then the induced group homomorphism `units(R) → Γ₀` is called `unit_map v`. The equivalence "relation" `is_equiv v₁ v₂ : Prop` defined in 1.27 of [wedhorn_adic] is not strictly speaking a relation, because `v₁ : valuation R Γ₁` and `v₂ : valuation R Γ₂` might not have the same type. This corresponds in ZFC to the set-theoretic difficulty that the class of all valuations (as `Γ₀` varies) on a ring `R` is not a set. The "relation" is however reflexive, symmetric and transitive in the obvious sense. Note that we use 1.27(iii) of [wedhorn_adic] as the definition of equivalence. The support of a valuation `v : valuation R Γ₀` is `supp v`. If `J` is an ideal of `R` with `h : J ⊆ supp v` then the induced valuation on R / J = `ideal.quotient J` is `on_quot v h`. ## Main definitions * `valuation R Γ₀`, the type of valuations on `R` with values in `Γ₀` * `valuation.is_equiv`, the heterogeneous equivalence relation on valuations * `valuation.supp`, the support of a valuation * `add_valuation R Γ₀`, the type of additive valuations on `R` with values in a linearly ordered additive commutative group with a top element, `Γ₀`. ## Implementation Details `add_valuation R Γ₀` is implemented as `valuation R (multiplicative (order_dual Γ₀))`. -/ open_locale classical big_operators noncomputable theory open function ideal variables {R : Type*} -- This will be a ring, assumed commutative in some sections set_option old_structure_cmd true section variables (R) (Γ₀ : Type*) [linear_ordered_comm_monoid_with_zero Γ₀] [ring R] /-- The type of `Γ₀`-valued valuations on `R`. -/ @[nolint has_inhabited_instance] structure valuation extends monoid_with_zero_hom R Γ₀ := (map_add' : ∀ x y, to_fun (x + y) ≤ max (to_fun x) (to_fun y)) /-- The `monoid_with_zero_hom` underlying a valuation. -/ add_decl_doc valuation.to_monoid_with_zero_hom end namespace valuation variables {Γ₀ : Type*} variables {Γ'₀ : Type*} variables {Γ''₀ : Type*} [linear_ordered_comm_monoid_with_zero Γ''₀] section basic variables (R) (Γ₀) [ring R] section monoid variables [linear_ordered_comm_monoid_with_zero Γ₀] [linear_ordered_comm_monoid_with_zero Γ'₀] /-- A valuation is coerced to the underlying function `R → Γ₀`. -/ instance : has_coe_to_fun (valuation R Γ₀) := { F := λ _, R → Γ₀, coe := valuation.to_fun } /-- A valuation is coerced to a monoid morphism R → Γ₀. -/ instance : has_coe (valuation R Γ₀) (monoid_with_zero_hom R Γ₀) := ⟨valuation.to_monoid_with_zero_hom⟩ variables {R} {Γ₀} (v : valuation R Γ₀) {x y z : R} @[simp, norm_cast] lemma coe_coe : ((v : monoid_with_zero_hom R Γ₀) : R → Γ₀) = v := rfl @[simp] lemma map_zero : v 0 = 0 := v.map_zero' @[simp] lemma map_one : v 1 = 1 := v.map_one' @[simp] lemma map_mul : ∀ x y, v (x * y) = v x * v y := v.map_mul' @[simp] lemma map_add : ∀ x y, v (x + y) ≤ max (v x) (v y) := v.map_add' lemma map_add_le {x y g} (hx : v x ≤ g) (hy : v y ≤ g) : v (x + y) ≤ g := le_trans (v.map_add x y) $ max_le hx hy lemma map_add_lt {x y g} (hx : v x < g) (hy : v y < g) : v (x + y) < g := lt_of_le_of_lt (v.map_add x y) $ max_lt hx hy lemma map_sum_le {ι : Type*} {s : finset ι} {f : ι → R} {g : Γ₀} (hf : ∀ i ∈ s, v (f i) ≤ g) : v (∑ i in s, f i) ≤ g := begin refine finset.induction_on s (λ _, trans_rel_right (≤) v.map_zero zero_le') (λ a s has ih hf, _) hf, rw finset.forall_mem_insert at hf, rw finset.sum_insert has, exact v.map_add_le hf.1 (ih hf.2) end lemma map_sum_lt {ι : Type*} {s : finset ι} {f : ι → R} {g : Γ₀} (hg : g ≠ 0) (hf : ∀ i ∈ s, v (f i) < g) : v (∑ i in s, f i) < g := begin refine finset.induction_on s (λ _, trans_rel_right (<) v.map_zero (zero_lt_iff.2 hg)) (λ a s has ih hf, _) hf, rw finset.forall_mem_insert at hf, rw finset.sum_insert has, exact v.map_add_lt hf.1 (ih hf.2) end lemma map_sum_lt' {ι : Type*} {s : finset ι} {f : ι → R} {g : Γ₀} (hg : 0 < g) (hf : ∀ i ∈ s, v (f i) < g) : v (∑ i in s, f i) < g := v.map_sum_lt (ne_of_gt hg) hf @[simp] lemma map_pow : ∀ x (n:ℕ), v (x^n) = (v x)^n := v.to_monoid_with_zero_hom.to_monoid_hom.map_pow @[ext] lemma ext {v₁ v₂ : valuation R Γ₀} (h : ∀ r, v₁ r = v₂ r) : v₁ = v₂ := by { cases v₁, cases v₂, congr, funext r, exact h r } lemma ext_iff {v₁ v₂ : valuation R Γ₀} : v₁ = v₂ ↔ ∀ r, v₁ r = v₂ r := ⟨λ h r, congr_arg _ h, ext⟩ -- The following definition is not an instance, because we have more than one `v` on a given `R`. -- In addition, type class inference would not be able to infer `v`. /-- A valuation gives a preorder on the underlying ring. -/ def to_preorder : preorder R := preorder.lift v /-- If `v` is a valuation on a division ring then `v(x) = 0` iff `x = 0`. -/ @[simp] lemma zero_iff [nontrivial Γ₀] {K : Type*} [division_ring K] (v : valuation K Γ₀) {x : K} : v x = 0 ↔ x = 0 := v.to_monoid_with_zero_hom.map_eq_zero lemma ne_zero_iff [nontrivial Γ₀] {K : Type*} [division_ring K] (v : valuation K Γ₀) {x : K} : v x ≠ 0 ↔ x ≠ 0 := v.to_monoid_with_zero_hom.map_ne_zero theorem unit_map_eq (u : units R) : (units.map (v : R →* Γ₀) u : Γ₀) = v u := rfl /-- A ring homomorphism `S → R` induces a map `valuation R Γ₀ → valuation S Γ₀`. -/ def comap {S : Type*} [ring S] (f : S →+* R) (v : valuation R Γ₀) : valuation S Γ₀ := { to_fun := v ∘ f, map_add' := λ x y, by simp only [comp_app, map_add, f.map_add], .. v.to_monoid_with_zero_hom.comp f.to_monoid_with_zero_hom, } @[simp] lemma comap_id : v.comap (ring_hom.id R) = v := ext $ λ r, rfl lemma comap_comp {S₁ : Type*} {S₂ : Type*} [ring S₁] [ring S₂] (f : S₁ →+* S₂) (g : S₂ →+* R) : v.comap (g.comp f) = (v.comap g).comap f := ext $ λ r, rfl /-- A `≤`-preserving group homomorphism `Γ₀ → Γ'₀` induces a map `valuation R Γ₀ → valuation R Γ'₀`. -/ def map (f : monoid_with_zero_hom Γ₀ Γ'₀) (hf : monotone f) (v : valuation R Γ₀) : valuation R Γ'₀ := { to_fun := f ∘ v, map_add' := λ r s, calc f (v (r + s)) ≤ f (max (v r) (v s)) : hf (v.map_add r s) ... = max (f (v r)) (f (v s)) : hf.map_max, .. monoid_with_zero_hom.comp f v.to_monoid_with_zero_hom } /-- Two valuations on `R` are defined to be equivalent if they induce the same preorder on `R`. -/ def is_equiv (v₁ : valuation R Γ₀) (v₂ : valuation R Γ'₀) : Prop := ∀ r s, v₁ r ≤ v₁ s ↔ v₂ r ≤ v₂ s end monoid section group variables [linear_ordered_comm_group_with_zero Γ₀] {R} {Γ₀} (v : valuation R Γ₀) {x y z : R} @[simp] lemma map_inv {K : Type*} [division_ring K] (v : valuation K Γ₀) {x : K} : v x⁻¹ = (v x)⁻¹ := v.to_monoid_with_zero_hom.map_inv' x lemma map_units_inv (x : units R) : v (x⁻¹ : units R) = (v x)⁻¹ := v.to_monoid_with_zero_hom.to_monoid_hom.map_units_inv x @[simp] lemma map_neg (x : R) : v (-x) = v x := v.to_monoid_with_zero_hom.to_monoid_hom.map_neg x lemma map_sub_swap (x y : R) : v (x - y) = v (y - x) := v.to_monoid_with_zero_hom.to_monoid_hom.map_sub_swap x y lemma map_sub_le_max (x y : R) : v (x - y) ≤ max (v x) (v y) := calc v (x - y) = v (x + -y) : by rw [sub_eq_add_neg] ... ≤ max (v x) (v $ -y) : v.map_add _ _ ... = max (v x) (v y) : by rw map_neg lemma map_add_of_distinct_val (h : v x ≠ v y) : v (x + y) = max (v x) (v y) := begin suffices : ¬v (x + y) < max (v x) (v y), from or_iff_not_imp_right.1 (le_iff_eq_or_lt.1 (v.map_add x y)) this, intro h', wlog vyx : v y < v x using x y, { apply lt_or_gt_of_ne h.symm }, { rw max_eq_left_of_lt vyx at h', apply lt_irrefl (v x), calc v x = v ((x+y) - y) : by simp ... ≤ max (v $ x + y) (v y) : map_sub_le_max _ _ _ ... < v x : max_lt h' vyx }, { apply this h.symm, rwa [add_comm, max_comm] at h' } end lemma map_eq_of_sub_lt (h : v (y - x) < v x) : v y = v x := begin have := valuation.map_add_of_distinct_val v (ne_of_gt h).symm, rw max_eq_right (le_of_lt h) at this, simpa using this end end group end basic -- end of section namespace is_equiv variables [ring R] variables [linear_ordered_comm_monoid_with_zero Γ₀] [linear_ordered_comm_monoid_with_zero Γ'₀] variables {v : valuation R Γ₀} variables {v₁ : valuation R Γ₀} {v₂ : valuation R Γ'₀} {v₃ : valuation R Γ''₀} @[refl] lemma refl : v.is_equiv v := λ _ _, iff.refl _ @[symm] lemma symm (h : v₁.is_equiv v₂) : v₂.is_equiv v₁ := λ _ _, iff.symm (h _ _) @[trans] lemma trans (h₁₂ : v₁.is_equiv v₂) (h₂₃ : v₂.is_equiv v₃) : v₁.is_equiv v₃ := λ _ _, iff.trans (h₁₂ _ _) (h₂₃ _ _) lemma of_eq {v' : valuation R Γ₀} (h : v = v') : v.is_equiv v' := by { subst h } lemma map {v' : valuation R Γ₀} (f : monoid_with_zero_hom Γ₀ Γ'₀) (hf : monotone f) (inf : injective f) (h : v.is_equiv v') : (v.map f hf).is_equiv (v'.map f hf) := let H : strict_mono f := strict_mono_of_monotone_of_injective hf inf in λ r s, calc f (v r) ≤ f (v s) ↔ v r ≤ v s : by rw H.le_iff_le ... ↔ v' r ≤ v' s : h r s ... ↔ f (v' r) ≤ f (v' s) : by rw H.le_iff_le /-- `comap` preserves equivalence. -/ lemma comap {S : Type*} [ring S] (f : S →+* R) (h : v₁.is_equiv v₂) : (v₁.comap f).is_equiv (v₂.comap f) := λ r s, h (f r) (f s) lemma val_eq (h : v₁.is_equiv v₂) {r s : R} : v₁ r = v₁ s ↔ v₂ r = v₂ s := by simpa only [le_antisymm_iff] using and_congr (h r s) (h s r) lemma ne_zero (h : v₁.is_equiv v₂) {r : R} : v₁ r ≠ 0 ↔ v₂ r ≠ 0 := begin have : v₁ r ≠ v₁ 0 ↔ v₂ r ≠ v₂ 0 := not_iff_not_of_iff h.val_eq, rwa [v₁.map_zero, v₂.map_zero] at this, end end is_equiv -- end of namespace section lemma is_equiv_of_map_strict_mono [linear_ordered_comm_monoid_with_zero Γ₀] [linear_ordered_comm_monoid_with_zero Γ'₀] [ring R] {v : valuation R Γ₀} (f : monoid_with_zero_hom Γ₀ Γ'₀) (H : strict_mono f) : is_equiv (v.map f (H.monotone)) v := λ x y, ⟨H.le_iff_le.mp, λ h, H.monotone h⟩ lemma is_equiv_of_val_le_one [linear_ordered_comm_group_with_zero Γ₀] [linear_ordered_comm_group_with_zero Γ'₀] {K : Type*} [division_ring K] (v : valuation K Γ₀) (v' : valuation K Γ'₀) (h : ∀ {x:K}, v x ≤ 1 ↔ v' x ≤ 1) : v.is_equiv v' := begin intros x y, by_cases hy : y = 0, { simp [hy, zero_iff], }, rw show y = 1 * y, by rw one_mul, rw [← (inv_mul_cancel_right' hy x)], iterate 2 {rw [v.map_mul _ y, v'.map_mul _ y]}, rw [v.map_one, v'.map_one], split; intro H, { apply mul_le_mul_right', replace hy := v.ne_zero_iff.mpr hy, replace H := le_of_le_mul_right hy H, rwa h at H, }, { apply mul_le_mul_right', replace hy := v'.ne_zero_iff.mpr hy, replace H := le_of_le_mul_right hy H, rwa h, }, end end section supp variables [comm_ring R] variables [linear_ordered_comm_monoid_with_zero Γ₀] [linear_ordered_comm_monoid_with_zero Γ'₀] variables (v : valuation R Γ₀) /-- The support of a valuation `v : R → Γ₀` is the ideal of `R` where `v` vanishes. -/ def supp : ideal R := { carrier := {x | v x = 0}, zero_mem' := map_zero v, add_mem' := λ x y hx hy, le_zero_iff.mp $ calc v (x + y) ≤ max (v x) (v y) : v.map_add x y ... ≤ 0 : max_le (le_zero_iff.mpr hx) (le_zero_iff.mpr hy), smul_mem' := λ c x hx, calc v (c * x) = v c * v x : map_mul v c x ... = v c * 0 : congr_arg _ hx ... = 0 : mul_zero _ } @[simp] lemma mem_supp_iff (x : R) : x ∈ supp v ↔ v x = 0 := iff.rfl -- @[simp] lemma mem_supp_iff' (x : R) : x ∈ (supp v : set R) ↔ v x = 0 := iff.rfl /-- The support of a valuation is a prime ideal. -/ instance [nontrivial Γ₀] [no_zero_divisors Γ₀] : ideal.is_prime (supp v) := ⟨λ (h : v.supp = ⊤), one_ne_zero $ show (1 : Γ₀) = 0, from calc 1 = v 1 : v.map_one.symm ... = 0 : show (1:R) ∈ supp v, by { rw h, trivial }, λ x y hxy, begin show v x = 0 ∨ v y = 0, change v (x * y) = 0 at hxy, rw [v.map_mul x y] at hxy, exact eq_zero_or_eq_zero_of_mul_eq_zero hxy end⟩ lemma map_add_supp (a : R) {s : R} (h : s ∈ supp v) : v (a + s) = v a := begin have aux : ∀ a s, v s = 0 → v (a + s) ≤ v a, { intros a' s' h', refine le_trans (v.map_add a' s') (max_le (le_refl _) _), simp [h'], }, apply le_antisymm (aux a s h), calc v a = v (a + s + -s) : by simp ... ≤ v (a + s) : aux (a + s) (-s) (by rwa ←ideal.neg_mem_iff at h) end /-- If `hJ : J ⊆ supp v` then `on_quot_val hJ` is the induced function on R/J as a function. Note: it's just the function; the valuation is `on_quot hJ`. -/ def on_quot_val {J : ideal R} (hJ : J ≤ supp v) : J.quotient → Γ₀ := λ q, quotient.lift_on' q v $ λ a b h, calc v a = v (b + (a - b)) : by simp ... = v b : v.map_add_supp b (hJ h) /-- The extension of valuation v on R to valuation on R/J if J ⊆ supp v -/ def on_quot {J : ideal R} (hJ : J ≤ supp v) : valuation J.quotient Γ₀ := { to_fun := v.on_quot_val hJ, map_zero' := v.map_zero, map_one' := v.map_one, map_mul' := λ xbar ybar, quotient.ind₂' v.map_mul xbar ybar, map_add' := λ xbar ybar, quotient.ind₂' v.map_add xbar ybar } @[simp] lemma on_quot_comap_eq {J : ideal R} (hJ : J ≤ supp v) : (v.on_quot hJ).comap (ideal.quotient.mk J) = v := ext $ λ r, begin refine @quotient.lift_on_mk _ _ (J.quotient_rel) v (λ a b h, _) _, calc v a = v (b + (a - b)) : by simp ... = v b : v.map_add_supp b (hJ h) end lemma comap_supp {S : Type*} [comm_ring S] (f : S →+* R) : supp (v.comap f) = ideal.comap f v.supp := ideal.ext $ λ x, begin rw [mem_supp_iff, ideal.mem_comap, mem_supp_iff], refl, end lemma self_le_supp_comap (J : ideal R) (v : valuation (quotient J) Γ₀) : J ≤ (v.comap (ideal.quotient.mk J)).supp := by { rw [comap_supp, ← ideal.map_le_iff_le_comap], simp } @[simp] lemma comap_on_quot_eq (J : ideal R) (v : valuation J.quotient Γ₀) : (v.comap (ideal.quotient.mk J)).on_quot (v.self_le_supp_comap J) = v := ext $ by { rintro ⟨x⟩, refl } /-- The quotient valuation on R/J has support supp(v)/J if J ⊆ supp v. -/ lemma supp_quot {J : ideal R} (hJ : J ≤ supp v) : supp (v.on_quot hJ) = (supp v).map (ideal.quotient.mk J) := begin apply le_antisymm, { rintro ⟨x⟩ hx, apply ideal.subset_span, exact ⟨x, hx, rfl⟩ }, { rw ideal.map_le_iff_le_comap, intros x hx, exact hx } end lemma supp_quot_supp : supp (v.on_quot (le_refl _)) = 0 := by { rw supp_quot, exact ideal.map_quotient_self _ } end supp -- end of section end valuation section add_monoid variables (R) [ring R] (Γ₀ : Type*) [linear_ordered_add_comm_monoid_with_top Γ₀] /-- The type of `Γ₀`-valued additive valuations on `R`. -/ @[nolint has_inhabited_instance] def add_valuation := valuation R (multiplicative (order_dual Γ₀)) end add_monoid namespace add_valuation variables {Γ₀ : Type*} [linear_ordered_add_comm_monoid_with_top Γ₀] variables {Γ'₀ : Type*} [linear_ordered_add_comm_monoid_with_top Γ'₀] section basic variables (R) (Γ₀) [ring R] /-- A valuation is coerced to the underlying function `R → Γ₀`. -/ instance : has_coe_to_fun (add_valuation R Γ₀) := { F := λ _, R → Γ₀, coe := valuation.to_fun } variables {R} {Γ₀} (v : add_valuation R Γ₀) {x y z : R} section variables (f : R → Γ₀) (h0 : f 0 = ⊤) (h1 : f 1 = 0) variables (hadd : ∀ x y, min (f x) (f y) ≤ f (x + y)) (hmul : ∀ x y, f (x * y) = f x + f y) /-- An alternate constructor of `add_valuation`, that doesn't reference `multiplicative (order_dual Γ₀)` -/ def of : add_valuation R Γ₀ := { to_fun := f, map_one' := h1, map_zero' := h0, map_add' := hadd, map_mul' := hmul } variables {h0} {h1} {hadd} {hmul} {r : R} @[simp] theorem of_apply : (of f h0 h1 hadd hmul) r = f r := rfl end @[simp] lemma map_zero : v 0 = ⊤ := v.map_zero @[simp] lemma map_one : v 1 = 0 := v.map_one @[simp] lemma map_mul : ∀ x y, v (x * y) = v x + v y := v.map_mul @[simp] lemma map_add : ∀ x y, min (v x) (v y) ≤ v (x + y) := v.map_add lemma map_le_add {x y g} (hx : g ≤ v x) (hy : g ≤ v y) : g ≤ v (x + y) := v.map_add_le hx hy lemma map_lt_add {x y g} (hx : g < v x) (hy : g < v y) : g < v (x + y) := v.map_add_lt hx hy lemma map_le_sum {ι : Type*} {s : finset ι} {f : ι → R} {g : Γ₀} (hf : ∀ i ∈ s, g ≤ v (f i)) : g ≤ v (∑ i in s, f i) := v.map_sum_le hf lemma map_lt_sum {ι : Type*} {s : finset ι} {f : ι → R} {g : Γ₀} (hg : g ≠ ⊤) (hf : ∀ i ∈ s, g < v (f i)) : g < v (∑ i in s, f i) := v.map_sum_lt hg hf lemma map_lt_sum' {ι : Type*} {s : finset ι} {f : ι → R} {g : Γ₀} (hg : g < ⊤) (hf : ∀ i ∈ s, g < v (f i)) : g < v (∑ i in s, f i) := v.map_sum_lt' hg hf @[simp] lemma map_pow : ∀ x (n:ℕ), v (x^n) = n • (v x) := v.map_pow @[ext] lemma ext {v₁ v₂ : add_valuation R Γ₀} (h : ∀ r, v₁ r = v₂ r) : v₁ = v₂ := valuation.ext h lemma ext_iff {v₁ v₂ : add_valuation R Γ₀} : v₁ = v₂ ↔ ∀ r, v₁ r = v₂ r := valuation.ext_iff -- The following definition is not an instance, because we have more than one `v` on a given `R`. -- In addition, type class inference would not be able to infer `v`. /-- A valuation gives a preorder on the underlying ring. -/ def to_preorder : preorder R := preorder.lift v /-- If `v` is an additive valuation on a division ring then `v(x) = ⊤` iff `x = 0`. -/ @[simp] lemma top_iff [nontrivial Γ₀] {K : Type*} [division_ring K] (v : add_valuation K Γ₀) {x : K} : v x = ⊤ ↔ x = 0 := v.zero_iff lemma ne_top_iff [nontrivial Γ₀] {K : Type*} [division_ring K] (v : add_valuation K Γ₀) {x : K} : v x ≠ ⊤ ↔ x ≠ 0 := v.ne_zero_iff /-- A ring homomorphism `S → R` induces a map `add_valuation R Γ₀ → add_valuation S Γ₀`. -/ def comap {S : Type*} [ring S] (f : S →+* R) (v : add_valuation R Γ₀) : add_valuation S Γ₀ := v.comap f @[simp] lemma comap_id : v.comap (ring_hom.id R) = v := v.comap_id lemma comap_comp {S₁ : Type*} {S₂ : Type*} [ring S₁] [ring S₂] (f : S₁ →+* S₂) (g : S₂ →+* R) : v.comap (g.comp f) = (v.comap g).comap f := v.comap_comp f g /-- A `≤`-preserving, `⊤`-preserving group homomorphism `Γ₀ → Γ'₀` induces a map `add_valuation R Γ₀ → add_valuation R Γ'₀`. -/ def map (f : Γ₀ →+ Γ'₀) (ht : f ⊤ = ⊤) (hf : monotone f) (v : add_valuation R Γ₀) : add_valuation R Γ'₀ := v.map { to_fun := f, map_mul' := f.map_add, map_one' := f.map_zero, map_zero' := ht } (λ x y h, hf h) /-- Two additive valuations on `R` are defined to be equivalent if they induce the same preorder on `R`. -/ def is_equiv (v₁ : add_valuation R Γ₀) (v₂ : add_valuation R Γ'₀) : Prop := v₁.is_equiv v₂ end basic namespace is_equiv variables [ring R] variables {Γ''₀ : Type*} [linear_ordered_add_comm_monoid_with_top Γ''₀] variables {v : add_valuation R Γ₀} variables {v₁ : add_valuation R Γ₀} {v₂ : add_valuation R Γ'₀} {v₃ : add_valuation R Γ''₀} @[refl] lemma refl : v.is_equiv v := valuation.is_equiv.refl @[symm] lemma symm (h : v₁.is_equiv v₂) : v₂.is_equiv v₁ := h.symm @[trans] lemma trans (h₁₂ : v₁.is_equiv v₂) (h₂₃ : v₂.is_equiv v₃) : v₁.is_equiv v₃ := h₁₂.trans h₂₃ lemma of_eq {v' : add_valuation R Γ₀} (h : v = v') : v.is_equiv v' := valuation.is_equiv.of_eq h lemma map {v' : add_valuation R Γ₀} (f : Γ₀ →+ Γ'₀) (ht : f ⊤ = ⊤) (hf : monotone f) (inf : injective f) (h : v.is_equiv v') : (v.map f ht hf).is_equiv (v'.map f ht hf) := h.map { to_fun := f, map_mul' := f.map_add, map_one' := f.map_zero, map_zero' := ht } (λ x y h, hf h) inf /-- `comap` preserves equivalence. -/ lemma comap {S : Type*} [ring S] (f : S →+* R) (h : v₁.is_equiv v₂) : (v₁.comap f).is_equiv (v₂.comap f) := h.comap f lemma val_eq (h : v₁.is_equiv v₂) {r s : R} : v₁ r = v₁ s ↔ v₂ r = v₂ s := h.val_eq lemma ne_top (h : v₁.is_equiv v₂) {r : R} : v₁ r ≠ ⊤ ↔ v₂ r ≠ ⊤ := h.ne_zero end is_equiv section supp variables [comm_ring R] variables (v : add_valuation R Γ₀) /-- The support of an additive valuation `v : R → Γ₀` is the ideal of `R` where `v x = ⊤` -/ def supp : ideal R := v.supp @[simp] lemma mem_supp_iff (x : R) : x ∈ supp v ↔ v x = ⊤ := v.mem_supp_iff x lemma map_add_supp (a : R) {s : R} (h : s ∈ supp v) : v (a + s) = v a := v.map_add_supp a h /-- If `hJ : J ⊆ supp v` then `on_quot_val hJ` is the induced function on R/J as a function. Note: it's just the function; the valuation is `on_quot hJ`. -/ def on_quot_val {J : ideal R} (hJ : J ≤ supp v) : J.quotient → Γ₀ := v.on_quot_val hJ /-- The extension of valuation v on R to valuation on R/J if J ⊆ supp v -/ def on_quot {J : ideal R} (hJ : J ≤ supp v) : add_valuation J.quotient Γ₀ := v.on_quot hJ @[simp] lemma on_quot_comap_eq {J : ideal R} (hJ : J ≤ supp v) : (v.on_quot hJ).comap (ideal.quotient.mk J) = v := v.on_quot_comap_eq hJ lemma comap_supp {S : Type*} [comm_ring S] (f : S →+* R) : supp (v.comap f) = ideal.comap f v.supp := v.comap_supp f lemma self_le_supp_comap (J : ideal R) (v : add_valuation (quotient J) Γ₀) : J ≤ (v.comap (ideal.quotient.mk J)).supp := v.self_le_supp_comap J @[simp] lemma comap_on_quot_eq (J : ideal R) (v : add_valuation J.quotient Γ₀) : (v.comap (ideal.quotient.mk J)).on_quot (v.self_le_supp_comap J) = v := v.comap_on_quot_eq J /-- The quotient valuation on R/J has support supp(v)/J if J ⊆ supp v. -/ lemma supp_quot {J : ideal R} (hJ : J ≤ supp v) : supp (v.on_quot hJ) = (supp v).map (ideal.quotient.mk J) := v.supp_quot hJ lemma supp_quot_supp : supp (v.on_quot (le_refl _)) = 0 := v.supp_quot_supp end supp -- end of section end add_valuation
e212d55e5baf42b4b74cdd2220cbe1af1127c9f5
83c8119e3298c0bfc53fc195c41a6afb63d01513
/library/init/data/list/lemmas.lean
baa54c9de1544de8d4a531efa74773931afb302e
[ "Apache-2.0" ]
permissive
anfelor/lean
584b91c4e87a6d95f7630c2a93fb082a87319ed0
31cfc2b6bf7d674f3d0f73848b842c9c9869c9f1
refs/heads/master
1,610,067,141,310
1,585,992,232,000
1,585,992,232,000
251,683,543
0
0
Apache-2.0
1,585,676,570,000
1,585,676,569,000
null
UTF-8
Lean
false
false
10,451
lean
/- Copyright (c) 2014 Parikshit Khanna. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Parikshit Khanna, Jeremy Avigad, Leonardo de Moura, Floris van Doorn -/ prelude import init.data.list.basic init.function init.meta init.data.nat.lemmas import init.meta.interactive init.meta.smt.rsimp universes u v w w₁ w₂ variables {α : Type u} {β : Type v} {γ : Type w} namespace list open nat /- append -/ @[simp] lemma nil_append (s : list α) : [] ++ s = s := rfl @[simp] lemma cons_append (x : α) (s t : list α) : (x::s) ++ t = x::(s ++ t) := rfl @[simp] lemma append_nil (t : list α) : t ++ [] = t := by induction t; simp [*] @[simp] lemma append_assoc (s t u : list α) : s ++ t ++ u = s ++ (t ++ u) := by induction s; simp [*] /- length -/ lemma length_cons (a : α) (l : list α) : length (a :: l) = length l + 1 := rfl @[simp] lemma length_append (s t : list α) : length (s ++ t) = length s + length t := by induction s; simp [*, add_comm, add_left_comm] @[simp] lemma length_repeat (a : α) (n : ℕ) : length (repeat a n) = n := by induction n; simp [*]; refl @[simp] lemma length_tail (l : list α) : length (tail l) = length l - 1 := by cases l; refl -- TODO(Leo): cleanup proof after arith dec proc @[simp] lemma length_drop : ∀ (i : ℕ) (l : list α), length (drop i l) = length l - i | 0 l := rfl | (succ i) [] := eq.symm (nat.zero_sub (succ i)) | (succ i) (x::l) := calc length (drop (succ i) (x::l)) = length l - i : length_drop i l ... = succ (length l) - succ i : (nat.succ_sub_succ_eq_sub (length l) i).symm /- map -/ lemma map_cons (f : α → β) (a l) : map f (a::l) = f a :: map f l := rfl @[simp] lemma map_append (f : α → β) : ∀ l₁ l₂, map f (l₁ ++ l₂) = (map f l₁) ++ (map f l₂) := by intro l₁; induction l₁; intros; simp [*] lemma map_singleton (f : α → β) (a : α) : map f [a] = [f a] := rfl @[simp] lemma map_id (l : list α) : map id l = l := by induction l; simp [*] @[simp] lemma map_map (g : β → γ) (f : α → β) (l : list α) : map g (map f l) = map (g ∘ f) l := by induction l; simp [*] @[simp] lemma length_map (f : α → β) (l : list α) : length (map f l) = length l := by induction l; simp [*] /- bind -/ @[simp] lemma nil_bind (f : α → list β) : list.bind [] f = [] := by simp [join, list.bind] @[simp] lemma cons_bind (x xs) (f : α → list β) : list.bind (x :: xs) f = f x ++ list.bind xs f := by simp [join, list.bind] @[simp] lemma append_bind (xs ys) (f : α → list β) : list.bind (xs ++ ys) f = list.bind xs f ++ list.bind ys f := by induction xs; [refl, simp [*, cons_bind]] /- mem -/ @[simp] lemma mem_nil_iff (a : α) : a ∈ ([] : list α) ↔ false := iff.rfl @[simp] lemma not_mem_nil (a : α) : a ∉ ([] : list α) := iff.mp $ mem_nil_iff a @[simp] lemma mem_cons_self (a : α) (l : list α) : a ∈ a :: l := or.inl rfl @[simp] lemma mem_cons_iff (a y : α) (l : list α) : a ∈ y :: l ↔ (a = y ∨ a ∈ l) := iff.rfl @[rsimp] lemma mem_cons_eq (a y : α) (l : list α) : (a ∈ y :: l) = (a = y ∨ a ∈ l) := rfl lemma mem_cons_of_mem (y : α) {a : α} {l : list α} : a ∈ l → a ∈ y :: l := assume H, or.inr H lemma eq_or_mem_of_mem_cons {a y : α} {l : list α} : a ∈ y::l → a = y ∨ a ∈ l := assume h, h @[simp] lemma mem_append {a : α} {s t : list α} : a ∈ s ++ t ↔ a ∈ s ∨ a ∈ t := by induction s; simp [*, or_assoc] @[rsimp] lemma mem_append_eq (a : α) (s t : list α) : (a ∈ s ++ t) = (a ∈ s ∨ a ∈ t) := propext mem_append lemma mem_append_left {a : α} {l₁ : list α} (l₂ : list α) (h : a ∈ l₁) : a ∈ l₁ ++ l₂ := mem_append.2 (or.inl h) lemma mem_append_right {a : α} (l₁ : list α) {l₂ : list α} (h : a ∈ l₂) : a ∈ l₁ ++ l₂ := mem_append.2 (or.inr h) @[simp] lemma not_bex_nil (p : α → Prop) : ¬ (∃ x ∈ @nil α, p x) := λ⟨x, hx, px⟩, hx @[simp] lemma ball_nil (p : α → Prop) : ∀ x ∈ @nil α, p x := λx, false.elim @[simp] lemma bex_cons (p : α → Prop) (a : α) (l : list α) : (∃ x ∈ (a :: l), p x) ↔ (p a ∨ ∃ x ∈ l, p x) := ⟨λ⟨x, h, px⟩, by { simp at h, cases h with h h, {cases h, exact or.inl px}, {exact or.inr ⟨x, h, px⟩}}, λo, o.elim (λpa, ⟨a, mem_cons_self _ _, pa⟩) (λ⟨x, h, px⟩, ⟨x, mem_cons_of_mem _ h, px⟩)⟩ @[simp] lemma ball_cons (p : α → Prop) (a : α) (l : list α) : (∀ x ∈ (a :: l), p x) ↔ (p a ∧ ∀ x ∈ l, p x) := ⟨λal, ⟨al a (mem_cons_self _ _), λx h, al x (mem_cons_of_mem _ h)⟩, λ⟨pa, al⟩ x o, o.elim (λe, e.symm ▸ pa) (al x)⟩ /- list subset -/ protected def subset (l₁ l₂ : list α) := ∀ ⦃a : α⦄, a ∈ l₁ → a ∈ l₂ instance : has_subset (list α) := ⟨list.subset⟩ @[simp] lemma nil_subset (l : list α) : [] ⊆ l := λ b i, false.elim (iff.mp (mem_nil_iff b) i) @[refl, simp] lemma subset.refl (l : list α) : l ⊆ l := λ b i, i @[trans] lemma subset.trans {l₁ l₂ l₃ : list α} (h₁ : l₁ ⊆ l₂) (h₂ : l₂ ⊆ l₃) : l₁ ⊆ l₃ := λ b i, h₂ (h₁ i) @[simp] lemma subset_cons (a : α) (l : list α) : l ⊆ a::l := λ b i, or.inr i lemma subset_of_cons_subset {a : α} {l₁ l₂ : list α} : a::l₁ ⊆ l₂ → l₁ ⊆ l₂ := λ s b i, s (mem_cons_of_mem _ i) lemma cons_subset_cons {l₁ l₂ : list α} (a : α) (s : l₁ ⊆ l₂) : (a::l₁) ⊆ (a::l₂) := λ b hin, or.elim (eq_or_mem_of_mem_cons hin) (λ e : b = a, or.inl e) (λ i : b ∈ l₁, or.inr (s i)) @[simp] lemma subset_append_left (l₁ l₂ : list α) : l₁ ⊆ l₁++l₂ := λ b, mem_append_left _ @[simp] lemma subset_append_right (l₁ l₂ : list α) : l₂ ⊆ l₁++l₂ := λ b, mem_append_right _ lemma subset_cons_of_subset (a : α) {l₁ l₂ : list α} : l₁ ⊆ l₂ → l₁ ⊆ (a::l₂) := λ (s : l₁ ⊆ l₂) (a : α) (i : a ∈ l₁), or.inr (s i) theorem eq_nil_of_length_eq_zero {l : list α} : length l = 0 → l = [] := by {induction l; intros, refl, contradiction} theorem ne_nil_of_length_eq_succ {l : list α} : ∀ {n : nat}, length l = succ n → l ≠ [] := by induction l; intros; contradiction @[simp] theorem length_map₂ (f : α → β → γ) (l₁) : ∀ l₂, length (map₂ f l₁ l₂) = min (length l₁) (length l₂) := by {induction l₁; intro l₂; cases l₂; simp [*, add_one, min_succ_succ]} @[simp] theorem length_take : ∀ (i : ℕ) (l : list α), length (take i l) = min i (length l) | 0 l := by simp | (succ n) [] := by simp | (succ n) (a::l) := by simp [*, nat.min_succ_succ, add_one] theorem length_take_le (n) (l : list α) : length (take n l) ≤ n := by simp [min_le_left] theorem length_remove_nth : ∀ (l : list α) (i : ℕ), i < length l → length (remove_nth l i) = length l - 1 | [] _ h := rfl | (x::xs) 0 h := by simp [remove_nth, -add_comm] | (x::xs) (i+1) h := have i < length xs, from lt_of_succ_lt_succ h, by dsimp [remove_nth]; rw [length_remove_nth xs i this, nat.sub_add_cancel (lt_of_le_of_lt (nat.zero_le _) this)]; refl @[simp] lemma partition_eq_filter_filter (p : α → Prop) [decidable_pred p] : ∀ (l : list α), partition p l = (filter p l, filter (not ∘ p) l) | [] := rfl | (a::l) := by { by_cases pa : p a; simp [partition, filter, pa, partition_eq_filter_filter l] } /- sublists -/ inductive sublist : list α → list α → Prop | slnil : sublist [] [] | cons (l₁ l₂ a) : sublist l₁ l₂ → sublist l₁ (a::l₂) | cons2 (l₁ l₂ a) : sublist l₁ l₂ → sublist (a::l₁) (a::l₂) infix ` <+ `:50 := sublist lemma length_le_of_sublist : ∀ {l₁ l₂ : list α}, l₁ <+ l₂ → length l₁ ≤ length l₂ | _ _ sublist.slnil := le_refl 0 | _ _ (sublist.cons l₁ l₂ a s) := le_succ_of_le (length_le_of_sublist s) | _ _ (sublist.cons2 l₁ l₂ a s) := succ_le_succ (length_le_of_sublist s) /- filter -/ @[simp] theorem filter_nil (p : α → Prop) [h : decidable_pred p] : filter p [] = [] := rfl @[simp] theorem filter_cons_of_pos {p : α → Prop} [h : decidable_pred p] {a : α} : ∀ l, p a → filter p (a::l) = a :: filter p l := λ l pa, if_pos pa @[simp] theorem filter_cons_of_neg {p : α → Prop} [h : decidable_pred p] {a : α} : ∀ l, ¬ p a → filter p (a::l) = filter p l := λ l pa, if_neg pa @[simp] theorem filter_append {p : α → Prop} [h : decidable_pred p] : ∀ (l₁ l₂ : list α), filter p (l₁++l₂) = filter p l₁ ++ filter p l₂ | [] l₂ := rfl | (a::l₁) l₂ := by by_cases pa : p a; simp [pa, filter_append] @[simp] theorem filter_sublist {p : α → Prop} [h : decidable_pred p] : Π (l : list α), filter p l <+ l | [] := sublist.slnil | (a::l) := if pa : p a then by simp [pa]; apply sublist.cons2; apply filter_sublist l else by simp [pa]; apply sublist.cons; apply filter_sublist l /- map_accumr -/ section map_accumr variables {φ : Type w₁} {σ : Type w₂} -- This runs a function over a list returning the intermediate results and a -- a final result. def map_accumr (f : α → σ → σ × β) : list α → σ → (σ × list β) | [] c := (c, []) | (y::yr) c := let r := map_accumr yr c in let z := f y r.1 in (z.1, z.2 :: r.2) @[simp] theorem length_map_accumr : ∀ (f : α → σ → σ × β) (x : list α) (s : σ), length (map_accumr f x s).2 = length x | f (a::x) s := congr_arg succ (length_map_accumr f x s) | f [] s := rfl end map_accumr section map_accumr₂ variables {φ : Type w₁} {σ : Type w₂} -- This runs a function over two lists returning the intermediate results and a -- a final result. def map_accumr₂ (f : α → β → σ → σ × φ) : list α → list β → σ → σ × list φ | [] _ c := (c,[]) | _ [] c := (c,[]) | (x::xr) (y::yr) c := let r := map_accumr₂ xr yr c in let q := f x y r.1 in (q.1, q.2 :: r.2) @[simp] theorem length_map_accumr₂ : ∀ (f : α → β → σ → σ × φ) x y c, length (map_accumr₂ f x y c).2 = min (length x) (length y) | f (a::x) (b::y) c := calc succ (length (map_accumr₂ f x y c).2) = succ (min (length x) (length y)) : congr_arg succ (length_map_accumr₂ f x y c) ... = min (succ (length x)) (succ (length y)) : eq.symm (min_succ_succ (length x) (length y)) | f (a::x) [] c := rfl | f [] (b::y) c := rfl | f [] [] c := rfl end map_accumr₂ end list
92787edbda291bc10b5bea2cd02c065880d6a844
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/data/dlist/basic.lean
d241690d7c43743b34a6861c45a52824f22f1d77
[ "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
1,139
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import data.dlist /-! # Difference list This file provides a few results about `dlist`, which is defined in core Lean. A difference list is a function that, given a list, returns the original content of the difference list prepended to the given list. It is useful to represent elements of a given type as `a₁ + ... + aₙ` where `+ : α → α → α` is any operation, without actually computing. This structure supports `O(1)` `append` and `concat` operations on lists, making it useful for append-heavy uses such as logging and pretty printing. -/ /-- Concatenates a list of difference lists to form a single difference list. Similar to `list.join`. -/ def dlist.join {α : Type*} : list (dlist α) → dlist α | [] := dlist.empty | (x :: xs) := x ++ dlist.join xs @[simp] lemma dlist_singleton {α : Type*} {a : α} : dlist.singleton a = dlist.lazy_of_list ([a]) := rfl @[simp] lemma dlist_lazy {α : Type*} {l : list α} : dlist.lazy_of_list l = dlist.of_list l := rfl
126019f8a3bc241400e13ef70d29dcadf3fe60ce
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/data/polynomial.lean
8772e85d2c18f77e217851b93034ce2d1ea5b53b
[ "Apache-2.0" ]
permissive
gebner/mathlib
eab0150cc4f79ec45d2016a8c21750244a2e7ff0
cc6a6edc397c55118df62831e23bfbd6e6c6b4ab
refs/heads/master
1,625,574,853,976
1,586,712,827,000
1,586,712,827,000
99,101,412
1
0
Apache-2.0
1,586,716,389,000
1,501,667,958,000
Lean
UTF-8
Lean
false
false
105,169
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Jens Wagemaker Theory of univariate polynomials, represented as `add_monoid_algebra α ℕ`, where α is a commutative semiring. -/ import data.monoid_algebra ring_theory.algebra import algebra.gcd_domain ring_theory.euclidean_domain ring_theory.multiplicity import tactic.ring_exp noncomputable theory local attribute [instance, priority 100] classical.prop_decidable local attribute [instance, priority 10] is_semiring_hom.comp is_ring_hom.comp /-- `polynomial α` is the type of univariate polynomials over `α`. Polynomials should be seen as (semi-)rings with the additional constructor `X`. The embedding from α is called `C`. -/ def polynomial (α : Type*) [comm_semiring α] := add_monoid_algebra α ℕ open finsupp finset add_monoid_algebra namespace polynomial universes u v variables {α : Type u} {β : Type v} {a b : α} {m n : ℕ} section comm_semiring variables [comm_semiring α] {p q r : polynomial α} instance : inhabited (polynomial α) := finsupp.inhabited instance : comm_semiring (polynomial α) := add_monoid_algebra.comm_semiring instance : has_scalar α (polynomial α) := add_monoid_algebra.has_scalar instance : semimodule α (polynomial α) := add_monoid_algebra.semimodule /-- the coercion turning a `polynomial` into the function which reports the coefficient of a given monomial `X^n` -/ def coeff_coe_to_fun : has_coe_to_fun (polynomial α) := finsupp.has_coe_to_fun local attribute [instance] coeff_coe_to_fun @[simp] lemma support_zero : (0 : polynomial α).support = ∅ := rfl /-- `monomial s a` is the monomial `a * X^s` -/ @[reducible] def monomial (n : ℕ) (a : α) : polynomial α := finsupp.single n a /-- `C a` is the constant polynomial `a`. -/ def C (a : α) : polynomial α := monomial 0 a /-- `X` is the polynomial variable (aka indeterminant). -/ def X : polynomial α := monomial 1 1 /-- coeff p n is the coefficient of X^n in p -/ def coeff (p : polynomial α) := p.to_fun @[simp] lemma coeff_mk (s) (f) (h) : coeff (finsupp.mk s f h : polynomial α) = f := rfl instance [has_repr α] : has_repr (polynomial α) := ⟨λ p, if p = 0 then "0" else (p.support.sort (≤)).foldr (λ n a, a ++ (if a = "" then "" else " + ") ++ if n = 0 then "C (" ++ repr (coeff p n) ++ ")" else if n = 1 then if (coeff p n) = 1 then "X" else "C (" ++ repr (coeff p n) ++ ") * X" else if (coeff p n) = 1 then "X ^ " ++ repr n else "C (" ++ repr (coeff p n) ++ ") * X ^ " ++ repr n) ""⟩ theorem ext_iff {p q : polynomial α} : p = q ↔ ∀ n, coeff p n = coeff q n := ⟨λ h n, h ▸ rfl, finsupp.ext⟩ @[ext] lemma ext {p q : polynomial α} : (∀ n, coeff p n = coeff q n) → p = q := (@ext_iff _ _ p q).2 /-- `degree p` is the degree of the polynomial `p`, i.e. the largest `X`-exponent in `p`. `degree p = some n` when `p ≠ 0` and `n` is the highest power of `X` that appears in `p`, otherwise `degree 0 = ⊥`. -/ def degree (p : polynomial α) : with_bot ℕ := p.support.sup some lemma degree_lt_wf : well_founded (λp q : polynomial α, degree p < degree q) := inv_image.wf degree (with_bot.well_founded_lt nat.lt_wf) instance : has_well_founded (polynomial α) := ⟨_, degree_lt_wf⟩ /-- `nat_degree p` forces `degree p` to ℕ, by defining nat_degree 0 = 0. -/ def nat_degree (p : polynomial α) : ℕ := (degree p).get_or_else 0 lemma single_eq_C_mul_X : ∀{n}, monomial n a = C a * X^n | 0 := (mul_one _).symm | (n+1) := calc monomial (n + 1) a = monomial n a * X : by rw [X, single_mul_single, mul_one] ... = (C a * X^n) * X : by rw [single_eq_C_mul_X] ... = C a * X^(n+1) : by simp only [pow_add, mul_assoc, pow_one] lemma sum_C_mul_X_eq (p : polynomial α) : p.sum (λn a, C a * X^n) = p := eq.trans (sum_congr rfl $ assume n hn, single_eq_C_mul_X.symm) (finsupp.sum_single _) @[elab_as_eliminator] protected lemma induction_on {M : polynomial α → Prop} (p : polynomial α) (h_C : ∀a, M (C a)) (h_add : ∀p q, M p → M q → M (p + q)) (h_monomial : ∀(n : ℕ) (a : α), M (C a * X^n) → M (C a * X^(n+1))) : M p := have ∀{n:ℕ} {a}, M (C a * X^n), begin assume n a, induction n with n ih, { simp only [pow_zero, mul_one, h_C] }, { exact h_monomial _ _ ih } end, finsupp.induction p (suffices M (C 0), by { convert this, exact single_zero.symm, }, h_C 0) (assume n a p _ _ hp, suffices M (C a * X^n + p), by { convert this, exact single_eq_C_mul_X }, h_add _ _ this hp) @[simp] lemma C_0 : C (0 : α) = 0 := single_zero @[simp] lemma C_1 : C (1 : α) = 1 := rfl @[simp] lemma C_mul : C (a * b) = C a * C b := (@single_mul_single _ _ _ _ 0 0 a b).symm @[simp] lemma C_add : C (a + b) = C a + C b := finsupp.single_add instance C.is_semiring_hom : is_semiring_hom (C : α → polynomial α) := ⟨C_0, C_1, λ _ _, C_add, λ _ _, C_mul⟩ @[simp] lemma C_pow : C (a ^ n) = C a ^ n := is_semiring_hom.map_pow _ _ _ lemma nat_cast_eq_C (n : ℕ) : (n : polynomial α) = C n := by refine (nat.eq_cast (λ n, C (n : α)) _ _ _ n).symm; simp section coeff lemma apply_eq_coeff : p n = coeff p n := rfl @[simp] lemma coeff_zero (n : ℕ) : coeff (0 : polynomial α) n = 0 := rfl lemma coeff_single : coeff (single n a) m = if n = m then a else 0 := by { dsimp [single, finsupp.single], congr } @[simp] lemma coeff_one_zero : coeff (1 : polynomial α) 0 = 1 := coeff_single @[simp] lemma coeff_add (p q : polynomial α) (n : ℕ) : coeff (p + q) n = coeff p n + coeff q n := rfl instance coeff.is_add_monoid_hom {n : ℕ} : is_add_monoid_hom (λ p : polynomial α, p.coeff n) := { map_add := λ p q, coeff_add p q n, map_zero := coeff_zero _ } lemma coeff_C : coeff (C a) n = ite (n = 0) a 0 := by simp [coeff, eq_comm, C, monomial, single]; congr @[simp] lemma coeff_C_zero : coeff (C a) 0 = a := coeff_single @[simp] lemma coeff_X_one : coeff (X : polynomial α) 1 = 1 := coeff_single @[simp] lemma coeff_X_zero : coeff (X : polynomial α) 0 = 0 := coeff_single lemma coeff_X : coeff (X : polynomial α) n = if 1 = n then 1 else 0 := coeff_single lemma coeff_C_mul_X (x : α) (k n : ℕ) : coeff (C x * X^k : polynomial α) n = if n = k then x else 0 := by rw [← single_eq_C_mul_X]; simp [monomial, single, eq_comm, coeff]; congr lemma coeff_sum [comm_semiring β] (n : ℕ) (f : ℕ → α → polynomial β) : coeff (p.sum f) n = p.sum (λ a b, coeff (f a b) n) := finsupp.sum_apply @[simp] lemma coeff_C_mul (p : polynomial α) : coeff (C a * p) n = a * coeff p n := begin conv in (a * _) { rw [← @sum_single _ _ _ p, coeff_sum] }, rw [mul_def, C, sum_single_index], { simp [coeff_single, finsupp.mul_sum, coeff_sum], apply sum_congr rfl, assume i hi, by_cases i = n; simp [h] }, { simp [finsupp.sum] } end @[simp] lemma coeff_smul (p : polynomial α) (r : α) (n : ℕ) : coeff (r • p) n = r * coeff p n := finsupp.smul_apply lemma C_mul' (a : α) (f : polynomial α) : C a * f = a • f := ext $ λ n, coeff_C_mul f @[simp, priority 990] lemma coeff_one (n : ℕ) : coeff (1 : polynomial α) n = if 0 = n then 1 else 0 := coeff_single @[simp] lemma coeff_X_pow (k n : ℕ) : coeff (X^k : polynomial α) n = if n = k then 1 else 0 := by simpa only [C_1, one_mul] using coeff_C_mul_X (1:α) k n lemma coeff_mul (p q : polynomial α) (n : ℕ) : coeff (p * q) n = (nat.antidiagonal n).sum (λ x, coeff p x.1 * coeff q x.2) := have hite : ∀ a : ℕ × ℕ, ite (a.1 + a.2 = n) (coeff p (a.fst) * coeff q (a.snd)) 0 ≠ 0 → a.1 + a.2 = n, from λ a ha, by_contradiction (λ h, absurd (eq.refl (0 : α)) (by rwa if_neg h at ha)), calc coeff (p * q) n = p.support.sum (λ a, q.support.sum (λ b, ite (a + b = n) (coeff p a * coeff q b) 0)) : by simp only [mul_def, coeff_sum, coeff_single]; refl ... = (p.support.product q.support).sum (λ v : ℕ × ℕ, ite (v.1 + v.2 = n) (coeff p v.1 * coeff q v.2) 0) : by rw sum_product ... = (nat.antidiagonal n).sum (λ x, coeff p x.1 * coeff q x.2) : begin refine sum_bij_ne_zero (λ x _ _, x) (λ x _ hx, nat.mem_antidiagonal.2 (hite x hx)) (λ _ _ _ _ _ _ h, h) (λ x h₁ h₂, ⟨x, _, _, rfl⟩) _, { rw [mem_product, mem_support_iff, mem_support_iff], exact ⟨ne_zero_of_mul_ne_zero_right h₂, ne_zero_of_mul_ne_zero_left h₂⟩ }, { rw nat.mem_antidiagonal at h₁, rwa [if_pos h₁] }, { intros x h hx, rw [if_pos (hite x hx)] } end theorem coeff_mul_X_pow (p : polynomial α) (n d : ℕ) : coeff (p * polynomial.X ^ n) (d + n) = coeff p d := begin rw [coeff_mul, sum_eq_single (d,n), coeff_X_pow, if_pos rfl, mul_one], { rintros ⟨i,j⟩ h1 h2, rw [coeff_X_pow, if_neg, mul_zero], rintro rfl, apply h2, rw [nat.mem_antidiagonal, add_right_cancel_iff] at h1, subst h1 }, { exact λ h1, (h1 (nat.mem_antidiagonal.2 rfl)).elim } end theorem coeff_mul_X (p : polynomial α) (n : ℕ) : coeff (p * X) (n + 1) = coeff p n := by simpa only [pow_one] using coeff_mul_X_pow p 1 n theorem mul_X_pow_eq_zero {p : polynomial α} {n : ℕ} (H : p * X ^ n = 0) : p = 0 := ext $ λ k, (coeff_mul_X_pow p n k).symm.trans $ ext_iff.1 H (k+n) end coeff lemma C_inj : C a = C b ↔ a = b := ⟨λ h, coeff_C_zero.symm.trans (h.symm ▸ coeff_C_zero), congr_arg C⟩ section eval₂ variables [semiring β] variables (f : α → β) (x : β) open is_semiring_hom /-- Evaluate a polynomial `p` given a ring hom `f` from the scalar ring to the target and a value `x` for the variable in the target -/ def eval₂ (p : polynomial α) : β := p.sum (λ e a, f a * x ^ e) variables [is_semiring_hom f] @[simp] lemma eval₂_C : (C a).eval₂ f x = f a := (sum_single_index $ by rw [map_zero f, zero_mul]).trans $ by rw [pow_zero, mul_one] @[simp] lemma eval₂_X : X.eval₂ f x = x := (sum_single_index $ by rw [map_zero f, zero_mul]).trans $ by rw [map_one f, one_mul, pow_one] @[simp] lemma eval₂_zero : (0 : polynomial α).eval₂ f x = 0 := finsupp.sum_zero_index @[simp] lemma eval₂_add : (p + q).eval₂ f x = p.eval₂ f x + q.eval₂ f x := finsupp.sum_add_index (λ _, by rw [map_zero f, zero_mul]) (λ _ _ _, by rw [map_add f, add_mul]) @[simp] lemma eval₂_one : (1 : polynomial α).eval₂ f x = 1 := by rw [← C_1, eval₂_C, map_one f] instance eval₂.is_add_monoid_hom : is_add_monoid_hom (eval₂ f x) := { map_zero := eval₂_zero _ _, map_add := λ _ _, eval₂_add _ _ } end eval₂ section eval₂ variables [comm_semiring β] variables (f : α → β) [is_semiring_hom f] (x : β) open is_semiring_hom @[simp] lemma eval₂_mul : (p * q).eval₂ f x = p.eval₂ f x * q.eval₂ f x := begin dunfold eval₂, rw [mul_def, finsupp.sum_mul _ p], simp only [finsupp.mul_sum _ q], rw [sum_sum_index], { apply sum_congr rfl, assume i hi, dsimp only, rw [sum_sum_index], { apply sum_congr rfl, assume j hj, dsimp only, rw [sum_single_index, map_mul f, pow_add], { simp only [mul_assoc, mul_left_comm] }, { rw [map_zero f, zero_mul] } }, { intro, rw [map_zero f, zero_mul] }, { intros, rw [map_add f, add_mul] } }, { intro, rw [map_zero f, zero_mul] }, { intros, rw [map_add f, add_mul] } end instance eval₂.is_semiring_hom : is_semiring_hom (eval₂ f x) := ⟨eval₂_zero _ _, eval₂_one _ _, λ _ _, eval₂_add _ _, λ _ _, eval₂_mul _ _⟩ /-- `eval₂` as a `ring_hom` -/ def eval₂_ring_hom (f : α →+* β) (x) : polynomial α →+* β := ring_hom.of (eval₂ f x) @[simp] lemma coe_eval₂_ring_hom (f : α →+* β) (x) : ⇑(eval₂_ring_hom f x) = eval₂ f x := rfl lemma eval₂_pow (n : ℕ) : (p ^ n).eval₂ f x = p.eval₂ f x ^ n := map_pow _ _ _ lemma eval₂_sum (p : polynomial α) (g : ℕ → α → polynomial α) (x : β) : (p.sum g).eval₂ f x = p.sum (λ n a, (g n a).eval₂ f x) := finsupp.sum_sum_index (by simp [is_add_monoid_hom.map_zero f]) (by intros; simp [right_distrib, is_add_monoid_hom.map_add f]) end eval₂ section eval variable {x : α} /-- `eval x p` is the evaluation of the polynomial `p` at `x` -/ def eval : α → polynomial α → α := eval₂ id @[simp] lemma eval_C : (C a).eval x = a := eval₂_C _ _ @[simp] lemma eval_X : X.eval x = x := eval₂_X _ _ @[simp] lemma eval_zero : (0 : polynomial α).eval x = 0 := eval₂_zero _ _ @[simp] lemma eval_add : (p + q).eval x = p.eval x + q.eval x := eval₂_add _ _ @[simp] lemma eval_one : (1 : polynomial α).eval x = 1 := eval₂_one _ _ @[simp] lemma eval_mul : (p * q).eval x = p.eval x * q.eval x := eval₂_mul _ _ instance eval.is_semiring_hom : is_semiring_hom (eval x) := eval₂.is_semiring_hom _ _ @[simp] lemma eval_pow (n : ℕ) : (p ^ n).eval x = p.eval x ^ n := eval₂_pow _ _ _ lemma eval_sum (p : polynomial α) (f : ℕ → α → polynomial α) (x : α) : (p.sum f).eval x = p.sum (λ n a, (f n a).eval x) := eval₂_sum _ _ _ _ lemma eval₂_hom [comm_semiring β] (f : α → β) [is_semiring_hom f] (x : α) : p.eval₂ f (f x) = f (p.eval x) := polynomial.induction_on p (by simp) (by simp [is_semiring_hom.map_add f] {contextual := tt}) (by simp [is_semiring_hom.map_mul f, eval_pow, is_semiring_hom.map_pow f, pow_succ', (mul_assoc _ _ _).symm] {contextual := tt}) /-- `is_root p x` implies `x` is a root of `p`. The evaluation of `p` at `x` is zero -/ def is_root (p : polynomial α) (a : α) : Prop := p.eval a = 0 instance [decidable_eq α] : decidable (is_root p a) := by unfold is_root; apply_instance @[simp] lemma is_root.def : is_root p a ↔ p.eval a = 0 := iff.rfl lemma root_mul_left_of_is_root (p : polynomial α) {q : polynomial α} : is_root q a → is_root (p * q) a := λ H, by rw [is_root, eval_mul, is_root.def.1 H, mul_zero] lemma root_mul_right_of_is_root {p : polynomial α} (q : polynomial α) : is_root p a → is_root (p * q) a := λ H, by rw [is_root, eval_mul, is_root.def.1 H, zero_mul] lemma coeff_zero_eq_eval_zero (p : polynomial α) : coeff p 0 = p.eval 0 := calc coeff p 0 = coeff p 0 * 0 ^ 0 : by simp ... = p.eval 0 : eq.symm $ finset.sum_eq_single _ (λ b _ hb, by simp [zero_pow (nat.pos_of_ne_zero hb)]) (by simp) lemma zero_is_root_of_coeff_zero_eq_zero {p : polynomial α} (hp : p.coeff 0 = 0) : is_root p 0 := by rwa coeff_zero_eq_eval_zero at hp end eval section comp def comp (p q : polynomial α) : polynomial α := p.eval₂ C q lemma eval₂_comp [comm_semiring β] (f : α → β) [is_semiring_hom f] {x : β} : (p.comp q).eval₂ f x = p.eval₂ f (q.eval₂ f x) := show (p.sum (λ e a, C a * q ^ e)).eval₂ f x = p.eval₂ f (eval₂ f x q), by simp only [eval₂_mul, eval₂_C, eval₂_pow, eval₂_sum]; refl lemma eval_comp : (p.comp q).eval a = p.eval (q.eval a) := eval₂_comp _ @[simp] lemma comp_X : p.comp X = p := begin refine ext (λ n, _), rw [comp, eval₂], conv in (C _ * _) { rw ← single_eq_C_mul_X }, rw finsupp.sum_single end @[simp] lemma X_comp : X.comp p = p := eval₂_X _ _ @[simp] lemma comp_C : p.comp (C a) = C (p.eval a) := begin dsimp [comp, eval₂, eval, finsupp.sum], rw [← p.support.sum_hom (@C α _)], apply finset.sum_congr rfl; simp end @[simp] lemma C_comp : (C a).comp p = C a := eval₂_C _ _ @[simp] lemma comp_zero : p.comp (0 : polynomial α) = C (p.eval 0) := by rw [← C_0, comp_C] @[simp] lemma zero_comp : comp (0 : polynomial α) p = 0 := by rw [← C_0, C_comp] @[simp] lemma comp_one : p.comp 1 = C (p.eval 1) := by rw [← C_1, comp_C] @[simp] lemma one_comp : comp (1 : polynomial α) p = 1 := by rw [← C_1, C_comp] instance : is_semiring_hom (λ q : polynomial α, q.comp p) := by unfold comp; apply_instance @[simp] lemma add_comp : (p + q).comp r = p.comp r + q.comp r := eval₂_add _ _ @[simp] lemma mul_comp : (p * q).comp r = p.comp r * q.comp r := eval₂_mul _ _ end comp /-- `leading_coeff p` gives the coefficient of the highest power of `X` in `p`-/ def leading_coeff (p : polynomial α) : α := coeff p (nat_degree p) /-- a polynomial is `monic` if its leading coefficient is 1 -/ def monic (p : polynomial α) := leading_coeff p = (1 : α) lemma monic.def : monic p ↔ leading_coeff p = 1 := iff.rfl instance monic.decidable [decidable_eq α] : decidable (monic p) := by unfold monic; apply_instance @[simp] lemma monic.leading_coeff {p : polynomial α} (hp : p.monic) : leading_coeff p = 1 := hp @[simp] lemma degree_zero : degree (0 : polynomial α) = ⊥ := rfl @[simp] lemma nat_degree_zero : nat_degree (0 : polynomial α) = 0 := rfl @[simp] lemma degree_C (ha : a ≠ 0) : degree (C a) = (0 : with_bot ℕ) := show sup (ite (a = 0) ∅ {0}) some = 0, by rw if_neg ha; refl lemma degree_C_le : degree (C a) ≤ (0 : with_bot ℕ) := by by_cases h : a = 0; [rw [h, C_0], rw [degree_C h]]; [exact bot_le, exact le_refl _] lemma degree_one_le : degree (1 : polynomial α) ≤ (0 : with_bot ℕ) := by rw [← C_1]; exact degree_C_le lemma degree_eq_bot : degree p = ⊥ ↔ p = 0 := ⟨λ h, by rw [degree, ← max_eq_sup_with_bot] at h; exact support_eq_empty.1 (max_eq_none.1 h), λ h, h.symm ▸ rfl⟩ lemma degree_eq_nat_degree (hp : p ≠ 0) : degree p = (nat_degree p : with_bot ℕ) := let ⟨n, hn⟩ := classical.not_forall.1 (mt option.eq_none_iff_forall_not_mem.2 (mt degree_eq_bot.1 hp)) in have hn : degree p = some n := not_not.1 hn, by rw [nat_degree, hn]; refl lemma degree_eq_iff_nat_degree_eq {p : polynomial α} {n : ℕ} (hp : p ≠ 0) : p.degree = n ↔ p.nat_degree = n := by rw [degree_eq_nat_degree hp, with_bot.coe_eq_coe] lemma degree_eq_iff_nat_degree_eq_of_pos {p : polynomial α} {n : ℕ} (hn : n > 0) : p.degree = n ↔ p.nat_degree = n := begin split, { intro H, rwa ← degree_eq_iff_nat_degree_eq, rintro rfl, rw degree_zero at H, exact option.no_confusion H }, { intro H, rwa degree_eq_iff_nat_degree_eq, rintro rfl, rw nat_degree_zero at H, rw H at hn, exact lt_irrefl _ hn } end lemma nat_degree_eq_of_degree_eq_some {p : polynomial α} {n : ℕ} (h : degree p = n) : nat_degree p = n := have hp0 : p ≠ 0, from λ hp0, by rw hp0 at h; exact option.no_confusion h, option.some_inj.1 $ show (nat_degree p : with_bot ℕ) = n, by rwa [← degree_eq_nat_degree hp0] @[simp] lemma degree_le_nat_degree : degree p ≤ nat_degree p := begin by_cases hp : p = 0, { rw hp, exact bot_le }, rw [degree_eq_nat_degree hp], exact le_refl _ end lemma nat_degree_eq_of_degree_eq [comm_semiring β] {q : polynomial β} (h : degree p = degree q) : nat_degree p = nat_degree q := by unfold nat_degree; rw h lemma le_degree_of_ne_zero (h : coeff p n ≠ 0) : (n : with_bot ℕ) ≤ degree p := show @has_le.le (with_bot ℕ) _ (some n : with_bot ℕ) (p.support.sup some : with_bot ℕ), from finset.le_sup (finsupp.mem_support_iff.2 h) lemma le_nat_degree_of_ne_zero (h : coeff p n ≠ 0) : n ≤ nat_degree p := begin rw [← with_bot.coe_le_coe, ← degree_eq_nat_degree], exact le_degree_of_ne_zero h, { assume h, subst h, exact h rfl } end lemma degree_le_degree (h : coeff q (nat_degree p) ≠ 0) : degree p ≤ degree q := begin by_cases hp : p = 0, { rw hp, exact bot_le }, { rw degree_eq_nat_degree hp, exact le_degree_of_ne_zero h } end @[simp] lemma nat_degree_C (a : α) : nat_degree (C a) = 0 := begin by_cases ha : a = 0, { have : C a = 0, { rw [ha, C_0] }, rw [nat_degree, degree_eq_bot.2 this], refl }, { rw [nat_degree, degree_C ha], refl } end @[simp] lemma nat_degree_one : nat_degree (1 : polynomial α) = 0 := nat_degree_C 1 @[simp] lemma nat_degree_nat_cast (n : ℕ) : nat_degree (n : polynomial α) = 0 := by simp [nat_cast_eq_C] @[simp] lemma degree_monomial (n : ℕ) (ha : a ≠ 0) : degree (C a * X ^ n) = n := by rw [← single_eq_C_mul_X, degree, support_single_ne_zero ha]; refl lemma degree_monomial_le (n : ℕ) (a : α) : degree (C a * X ^ n) ≤ n := if h : a = 0 then by rw [h, C_0, zero_mul]; exact bot_le else le_of_eq (degree_monomial n h) lemma coeff_eq_zero_of_degree_lt (h : degree p < n) : coeff p n = 0 := not_not.1 (mt le_degree_of_ne_zero (not_le_of_gt h)) lemma coeff_eq_zero_of_nat_degree_lt {p : polynomial α} {n : ℕ} (h : p.nat_degree < n) : p.coeff n = 0 := begin apply coeff_eq_zero_of_degree_lt, by_cases hp : p = 0, { subst hp, exact with_bot.bot_lt_coe n }, { rwa [degree_eq_nat_degree hp, with_bot.coe_lt_coe] } end -- TODO find a home (this file) @[simp] lemma finset_sum_coeff (s : finset β) (f : β → polynomial α) (n : ℕ) : coeff (s.sum f) n = s.sum (λ b, coeff (f b) n) := (s.sum_hom (λ q : polynomial α, q.coeff n)).symm -- We need the explicit `decidable` argument here because an exotic one shows up in a moment! lemma ite_le_nat_degree_coeff (p : polynomial α) (n : ℕ) (I : decidable (n < 1 + nat_degree p)) : @ite (n < 1 + nat_degree p) I _ (coeff p n) 0 = coeff p n := begin split_ifs, { refl }, { exact (coeff_eq_zero_of_nat_degree_lt (not_le.1 (λ w, h (nat.lt_one_add_iff.2 w)))).symm, } end lemma as_sum (p : polynomial α) : p = (range (p.nat_degree + 1)).sum (λ i, C (p.coeff i) * X^i) := begin ext n, simp only [add_comm, coeff_X_pow, coeff_C_mul, finset.mem_range, finset.sum_mul_boole, finset_sum_coeff, ite_le_nat_degree_coeff], end lemma monic.as_sum {p : polynomial α} (hp : p.monic) : p = X^(p.nat_degree) + ((finset.range p.nat_degree).sum $ λ i, C (p.coeff i) * X^i) := begin conv_lhs { rw [p.as_sum, finset.sum_range_succ] }, suffices : C (p.coeff p.nat_degree) = 1, { rw [this, one_mul] }, exact congr_arg C hp end section map variables [comm_semiring β] variables (f : α →+* β) /-- `map f p` maps a polynomial `p` across a ring hom `f` -/ def map : polynomial α → polynomial β := eval₂ (C ∘ f) X instance is_semiring_hom_C_f : is_semiring_hom (C ∘ f) := is_semiring_hom.comp _ _ @[simp] lemma map_C : (C a).map f = C (f a) := eval₂_C _ _ @[simp] lemma map_X : X.map f = X := eval₂_X _ _ @[simp] lemma map_zero : (0 : polynomial α).map f = 0 := eval₂_zero _ _ @[simp] lemma map_add : (p + q).map f = p.map f + q.map f := eval₂_add _ _ @[simp] lemma map_one : (1 : polynomial α).map f = 1 := eval₂_one _ _ @[simp] lemma map_mul : (p * q).map f = p.map f * q.map f := eval₂_mul _ _ instance map.is_semiring_hom : is_semiring_hom (map f) := eval₂.is_semiring_hom _ _ @[simp] lemma map_pow (n : ℕ) : (p ^ n).map f = p.map f ^ n := eval₂_pow _ _ _ lemma coeff_map (n : ℕ) : coeff (p.map f) n = f (coeff p n) := begin rw [map, eval₂, coeff_sum], conv_rhs { rw [← sum_C_mul_X_eq p, coeff_sum, finsupp.sum, ← p.support.sum_hom f], }, refine finset.sum_congr rfl (λ x hx, _), simp [function.comp, coeff_C_mul_X, is_semiring_hom.map_mul f], split_ifs; simp [is_semiring_hom.map_zero f], end lemma map_map {γ : Type*} [comm_semiring γ] (g : β →+* γ) (p : polynomial α) : (p.map f).map g = p.map (g.comp f) := ext (by simp [coeff_map]) lemma eval₂_map {γ : Type*} [comm_semiring γ] (g : β → γ) [is_semiring_hom g] (x : γ) : (p.map f).eval₂ g x = p.eval₂ (λ y, g (f y)) x := polynomial.induction_on p (by simp) (by simp [is_semiring_hom.map_add f] {contextual := tt}) (by simp [is_semiring_hom.map_mul f, is_semiring_hom.map_pow f, pow_succ', (mul_assoc _ _ _).symm] {contextual := tt}) lemma eval_map (x : β) : (p.map f).eval x = p.eval₂ f x := eval₂_map _ _ _ @[simp] lemma map_id : p.map (ring_hom.id _) = p := by simp [polynomial.ext_iff, coeff_map] lemma mem_map_range {p : polynomial β} : p ∈ set.range (map f) ↔ ∀ n, p.coeff n ∈ (set.range f) := begin split, { rintro ⟨p, rfl⟩ n, rw coeff_map, exact set.mem_range_self _ }, { intro h, rw p.as_sum, apply is_add_submonoid.finset_sum_mem, intros i hi, rcases h i with ⟨c, hc⟩, use [C c * X^i], rw [map_mul, map_C, hc, map_pow, map_X] } end end map section variables {γ : Type*} [comm_semiring β] [comm_semiring γ] variables (f : α →+* β) (g : β →+* γ) (p) lemma hom_eval₂ (x : β) : g (p.eval₂ f x) = p.eval₂ (g ∘ f) (g x) := begin apply polynomial.induction_on p; clear p, { intros a, rw [eval₂_C, eval₂_C] }, { intros p q hp hq, simp only [hp, hq, eval₂_add, is_semiring_hom.map_add g] }, { intros n a ih, replace ih := congr_arg (λ y, y * g x) ih, simpa [pow_succ', is_semiring_hom.map_mul g, (mul_assoc _ _ _).symm, eval₂_C, eval₂_mul, eval₂_X] using ih } end end lemma coeff_nat_degree_eq_zero_of_degree_lt (h : degree p < degree q) : coeff p (nat_degree q) = 0 := coeff_eq_zero_of_degree_lt (lt_of_lt_of_le h degree_le_nat_degree) lemma ne_zero_of_degree_gt {n : with_bot ℕ} (h : n < degree p) : p ≠ 0 := mt degree_eq_bot.2 (ne.symm (ne_of_lt (lt_of_le_of_lt bot_le h))) lemma eq_C_of_degree_le_zero (h : degree p ≤ 0) : p = C (coeff p 0) := begin refine ext (λ n, _), cases n, { simp }, { have : degree p < ↑(nat.succ n) := lt_of_le_of_lt h (with_bot.some_lt_some.2 (nat.succ_pos _)), rw [coeff_C, if_neg (nat.succ_ne_zero _), coeff_eq_zero_of_degree_lt this] } end lemma eq_C_of_degree_eq_zero (h : degree p = 0) : p = C (coeff p 0) := eq_C_of_degree_le_zero (h ▸ le_refl _) lemma degree_le_zero_iff : degree p ≤ 0 ↔ p = C (coeff p 0) := ⟨eq_C_of_degree_le_zero, λ h, h.symm ▸ degree_C_le⟩ lemma degree_add_le (p q : polynomial α) : degree (p + q) ≤ max (degree p) (degree q) := calc degree (p + q) = ((p + q).support).sup some : rfl ... ≤ (p.support ∪ q.support).sup some : by convert sup_mono support_add ... = p.support.sup some ⊔ q.support.sup some : by convert sup_union ... = _ : with_bot.sup_eq_max _ _ @[simp] lemma leading_coeff_zero : leading_coeff (0 : polynomial α) = 0 := rfl @[simp] lemma leading_coeff_eq_zero : leading_coeff p = 0 ↔ p = 0 := ⟨λ h, by_contradiction $ λ hp, mt mem_support_iff.1 (not_not.2 h) (mem_of_max (degree_eq_nat_degree hp)), λ h, h.symm ▸ leading_coeff_zero⟩ lemma leading_coeff_eq_zero_iff_deg_eq_bot : leading_coeff p = 0 ↔ degree p = ⊥ := by rw [leading_coeff_eq_zero, degree_eq_bot] lemma degree_add_eq_of_degree_lt (h : degree p < degree q) : degree (p + q) = degree q := le_antisymm (max_eq_right_of_lt h ▸ degree_add_le _ _) $ degree_le_degree $ begin rw [coeff_add, coeff_nat_degree_eq_zero_of_degree_lt h, zero_add], exact mt leading_coeff_eq_zero.1 (ne_zero_of_degree_gt h) end lemma degree_add_C (hp : 0 < degree p) : degree (p + C a) = degree p := add_comm (C a) p ▸ degree_add_eq_of_degree_lt $ lt_of_le_of_lt degree_C_le hp lemma degree_add_eq_of_leading_coeff_add_ne_zero (h : leading_coeff p + leading_coeff q ≠ 0) : degree (p + q) = max p.degree q.degree := le_antisymm (degree_add_le _ _) $ match lt_trichotomy (degree p) (degree q) with | or.inl hlt := by rw [degree_add_eq_of_degree_lt hlt, max_eq_right_of_lt hlt]; exact le_refl _ | or.inr (or.inl heq) := le_of_not_gt $ assume hlt : max (degree p) (degree q) > degree (p + q), h $ show leading_coeff p + leading_coeff q = 0, begin rw [heq, max_self] at hlt, rw [leading_coeff, leading_coeff, nat_degree_eq_of_degree_eq heq, ← coeff_add], exact coeff_nat_degree_eq_zero_of_degree_lt hlt end | or.inr (or.inr hlt) := by rw [add_comm, degree_add_eq_of_degree_lt hlt, max_eq_left_of_lt hlt]; exact le_refl _ end lemma degree_erase_le (p : polynomial α) (n : ℕ) : degree (p.erase n) ≤ degree p := by convert sup_mono (erase_subset _ _) lemma degree_erase_lt (hp : p ≠ 0) : degree (p.erase (nat_degree p)) < degree p := lt_of_le_of_ne (degree_erase_le _ _) $ (degree_eq_nat_degree hp).symm ▸ (by convert λ h, not_mem_erase _ _ (mem_of_max h)) lemma degree_sum_le (s : finset β) (f : β → polynomial α) : degree (s.sum f) ≤ s.sup (λ b, degree (f b)) := finset.induction_on s (by simp only [sum_empty, sup_empty, degree_zero, le_refl]) $ assume a s has ih, calc degree ((insert a s).sum f) ≤ max (degree (f a)) (degree (s.sum f)) : by rw sum_insert has; exact degree_add_le _ _ ... ≤ _ : by rw [sup_insert, with_bot.sup_eq_max]; exact max_le_max (le_refl _) ih lemma degree_mul_le (p q : polynomial α) : degree (p * q) ≤ degree p + degree q := calc degree (p * q) ≤ (p.support).sup (λi, degree (sum q (λj a, C (coeff p i * a) * X ^ (i + j)))) : by simp only [single_eq_C_mul_X.symm]; exact degree_sum_le _ _ ... ≤ p.support.sup (λi, q.support.sup (λj, degree (C (coeff p i * coeff q j) * X ^ (i + j)))) : finset.sup_mono_fun (assume i hi, degree_sum_le _ _) ... ≤ degree p + degree q : begin refine finset.sup_le (λ a ha, finset.sup_le (λ b hb, le_trans (degree_monomial_le _ _) _)), rw [with_bot.coe_add], rw mem_support_iff at ha hb, exact add_le_add' (le_degree_of_ne_zero ha) (le_degree_of_ne_zero hb) end lemma degree_pow_le (p : polynomial α) : ∀ n, degree (p ^ n) ≤ add_monoid.smul n (degree p) | 0 := by rw [pow_zero, add_monoid.zero_smul]; exact degree_one_le | (n+1) := calc degree (p ^ (n + 1)) ≤ degree p + degree (p ^ n) : by rw pow_succ; exact degree_mul_le _ _ ... ≤ _ : by rw succ_smul; exact add_le_add' (le_refl _) (degree_pow_le _) @[simp] lemma leading_coeff_monomial (a : α) (n : ℕ) : leading_coeff (C a * X ^ n) = a := begin by_cases ha : a = 0, { simp only [ha, C_0, zero_mul, leading_coeff_zero] }, { rw [leading_coeff, nat_degree, degree_monomial _ ha, ← single_eq_C_mul_X], exact @finsupp.single_eq_same _ _ _ n a } end @[simp] lemma leading_coeff_C (a : α) : leading_coeff (C a) = a := suffices leading_coeff (C a * X^0) = a, by rwa [pow_zero, mul_one] at this, leading_coeff_monomial a 0 @[simp] lemma leading_coeff_X : leading_coeff (X : polynomial α) = 1 := suffices leading_coeff (C (1:α) * X^1) = 1, by rwa [C_1, pow_one, one_mul] at this, leading_coeff_monomial 1 1 @[simp] lemma monic_X : monic (X : polynomial α) := leading_coeff_X @[simp] lemma leading_coeff_one : leading_coeff (1 : polynomial α) = 1 := suffices leading_coeff (C (1:α) * X^0) = 1, by rwa [C_1, pow_zero, mul_one] at this, leading_coeff_monomial 1 0 @[simp] lemma monic_one : monic (1 : polynomial α) := leading_coeff_C _ lemma monic.ne_zero_of_zero_ne_one (h : (0:α) ≠ 1) {p : polynomial α} (hp : p.monic) : p ≠ 0 := by { contrapose! h, rwa [h] at hp } lemma monic.ne_zero {α : Type*} [nonzero_comm_ring α] {p : polynomial α} (hp : p.monic) : p ≠ 0 := hp.ne_zero_of_zero_ne_one $ zero_ne_one lemma leading_coeff_add_of_degree_lt (h : degree p < degree q) : leading_coeff (p + q) = leading_coeff q := have coeff p (nat_degree q) = 0, from coeff_nat_degree_eq_zero_of_degree_lt h, by simp only [leading_coeff, nat_degree_eq_of_degree_eq (degree_add_eq_of_degree_lt h), this, coeff_add, zero_add] lemma leading_coeff_add_of_degree_eq (h : degree p = degree q) (hlc : leading_coeff p + leading_coeff q ≠ 0) : leading_coeff (p + q) = leading_coeff p + leading_coeff q := have nat_degree (p + q) = nat_degree p, by apply nat_degree_eq_of_degree_eq; rw [degree_add_eq_of_leading_coeff_add_ne_zero hlc, h, max_self], by simp only [leading_coeff, this, nat_degree_eq_of_degree_eq h, coeff_add] @[simp] lemma coeff_mul_degree_add_degree (p q : polynomial α) : coeff (p * q) (nat_degree p + nat_degree q) = leading_coeff p * leading_coeff q := calc coeff (p * q) (nat_degree p + nat_degree q) = (nat.antidiagonal (nat_degree p + nat_degree q)).sum (λ x, coeff p x.1 * coeff q x.2) : coeff_mul _ _ _ ... = coeff p (nat_degree p) * coeff q (nat_degree q) : begin refine finset.sum_eq_single (nat_degree p, nat_degree q) _ _, { rintro ⟨i,j⟩ h₁ h₂, rw nat.mem_antidiagonal at h₁, by_cases H : nat_degree p < i, { rw [coeff_eq_zero_of_degree_lt (lt_of_le_of_lt degree_le_nat_degree (with_bot.coe_lt_coe.2 H)), zero_mul] }, { rw not_lt_iff_eq_or_lt at H, cases H, { subst H, rw add_left_cancel_iff at h₁, dsimp at h₁, subst h₁, exfalso, exact h₂ rfl }, { suffices : nat_degree q < j, { rw [coeff_eq_zero_of_degree_lt (lt_of_le_of_lt degree_le_nat_degree (with_bot.coe_lt_coe.2 this)), mul_zero] }, { by_contra H', rw not_lt at H', exact ne_of_lt (nat.lt_of_lt_of_le (nat.add_lt_add_right H j) (nat.add_le_add_left H' _)) h₁ } } } }, { intro H, exfalso, apply H, rw nat.mem_antidiagonal } end lemma degree_mul_eq' (h : leading_coeff p * leading_coeff q ≠ 0) : degree (p * q) = degree p + degree q := have hp : p ≠ 0 := by refine mt _ h; exact λ hp, by rw [hp, leading_coeff_zero, zero_mul], have hq : q ≠ 0 := by refine mt _ h; exact λ hq, by rw [hq, leading_coeff_zero, mul_zero], le_antisymm (degree_mul_le _ _) begin rw [degree_eq_nat_degree hp, degree_eq_nat_degree hq], refine le_degree_of_ne_zero _, rwa coeff_mul_degree_add_degree end lemma nat_degree_mul_eq' (h : leading_coeff p * leading_coeff q ≠ 0) : nat_degree (p * q) = nat_degree p + nat_degree q := have hp : p ≠ 0 := mt leading_coeff_eq_zero.2 (λ h₁, h $ by rw [h₁, zero_mul]), have hq : q ≠ 0 := mt leading_coeff_eq_zero.2 (λ h₁, h $ by rw [h₁, mul_zero]), have hpq : p * q ≠ 0 := λ hpq, by rw [← coeff_mul_degree_add_degree, hpq, coeff_zero] at h; exact h rfl, option.some_inj.1 (show (nat_degree (p * q) : with_bot ℕ) = nat_degree p + nat_degree q, by rw [← degree_eq_nat_degree hpq, degree_mul_eq' h, degree_eq_nat_degree hp, degree_eq_nat_degree hq]) lemma leading_coeff_mul' (h : leading_coeff p * leading_coeff q ≠ 0) : leading_coeff (p * q) = leading_coeff p * leading_coeff q := begin unfold leading_coeff, rw [nat_degree_mul_eq' h, coeff_mul_degree_add_degree], refl end lemma leading_coeff_pow' : leading_coeff p ^ n ≠ 0 → leading_coeff (p ^ n) = leading_coeff p ^ n := nat.rec_on n (by simp) $ λ n ih h, have h₁ : leading_coeff p ^ n ≠ 0 := λ h₁, h $ by rw [pow_succ, h₁, mul_zero], have h₂ : leading_coeff p * leading_coeff (p ^ n) ≠ 0 := by rwa [pow_succ, ← ih h₁] at h, by rw [pow_succ, pow_succ, leading_coeff_mul' h₂, ih h₁] lemma degree_pow_eq' : ∀ {n}, leading_coeff p ^ n ≠ 0 → degree (p ^ n) = add_monoid.smul n (degree p) | 0 := λ h, by rw [pow_zero, ← C_1] at *; rw [degree_C h, add_monoid.zero_smul] | (n+1) := λ h, have h₁ : leading_coeff p ^ n ≠ 0 := λ h₁, h $ by rw [pow_succ, h₁, mul_zero], have h₂ : leading_coeff p * leading_coeff (p ^ n) ≠ 0 := by rwa [pow_succ, ← leading_coeff_pow' h₁] at h, by rw [pow_succ, degree_mul_eq' h₂, succ_smul, degree_pow_eq' h₁] lemma nat_degree_pow_eq' {n : ℕ} (h : leading_coeff p ^ n ≠ 0) : nat_degree (p ^ n) = n * nat_degree p := if hp0 : p = 0 then if hn0 : n = 0 then by simp * else by rw [hp0, zero_pow (nat.pos_of_ne_zero hn0)]; simp else have hpn : p ^ n ≠ 0, from λ hpn0, have h1 : _ := h, by rw [← leading_coeff_pow' h1, hpn0, leading_coeff_zero] at h; exact h rfl, option.some_inj.1 $ show (nat_degree (p ^ n) : with_bot ℕ) = (n * nat_degree p : ℕ), by rw [← degree_eq_nat_degree hpn, degree_pow_eq' h, degree_eq_nat_degree hp0, ← with_bot.coe_smul]; simp @[simp] lemma leading_coeff_X_pow : ∀ n : ℕ, leading_coeff ((X : polynomial α) ^ n) = 1 | 0 := by simp | (n+1) := if h10 : (1 : α) = 0 then by rw [pow_succ, ← one_mul X, ← C_1, h10]; simp else have h : leading_coeff (X : polynomial α) * leading_coeff (X ^ n) ≠ 0, by rw [leading_coeff_X, leading_coeff_X_pow n, one_mul]; exact h10, by rw [pow_succ, leading_coeff_mul' h, leading_coeff_X, leading_coeff_X_pow, one_mul] lemma nat_degree_comp_le : nat_degree (p.comp q) ≤ nat_degree p * nat_degree q := if h0 : p.comp q = 0 then by rw [h0, nat_degree_zero]; exact nat.zero_le _ else with_bot.coe_le_coe.1 $ calc ↑(nat_degree (p.comp q)) = degree (p.comp q) : (degree_eq_nat_degree h0).symm ... ≤ _ : degree_sum_le _ _ ... ≤ _ : sup_le (λ n hn, calc degree (C (coeff p n) * q ^ n) ≤ degree (C (coeff p n)) + degree (q ^ n) : degree_mul_le _ _ ... ≤ nat_degree (C (coeff p n)) + add_monoid.smul n (degree q) : add_le_add' degree_le_nat_degree (degree_pow_le _ _) ... ≤ nat_degree (C (coeff p n)) + add_monoid.smul n (nat_degree q) : add_le_add_left' (add_monoid.smul_le_smul_of_le_right (@degree_le_nat_degree _ _ q) n) ... = (n * nat_degree q : ℕ) : by rw [nat_degree_C, with_bot.coe_zero, zero_add, ← with_bot.coe_smul, add_monoid.smul_eq_mul]; simp ... ≤ (nat_degree p * nat_degree q : ℕ) : with_bot.coe_le_coe.2 $ mul_le_mul_of_nonneg_right (le_nat_degree_of_ne_zero (finsupp.mem_support_iff.1 hn)) (nat.zero_le _)) lemma degree_map_le [comm_semiring β] (f : α →+* β) : degree (p.map f) ≤ degree p := if h : p.map f = 0 then by simp [h] else begin rw [degree_eq_nat_degree h], refine le_degree_of_ne_zero (mt (congr_arg f) _), rw [← coeff_map f, is_semiring_hom.map_zero f], exact mt leading_coeff_eq_zero.1 h end lemma subsingleton_of_monic_zero (h : monic (0 : polynomial α)) : (∀ p q : polynomial α, p = q) ∧ (∀ a b : α, a = b) := by rw [monic.def, leading_coeff_zero] at h; exact ⟨λ p q, by rw [← mul_one p, ← mul_one q, ← C_1, ← h, C_0, mul_zero, mul_zero], λ a b, by rw [← mul_one a, ← mul_one b, ← h, mul_zero, mul_zero]⟩ lemma degree_map_eq_of_leading_coeff_ne_zero [comm_semiring β] (f : α →+* β) (hf : f (leading_coeff p) ≠ 0) : degree (p.map f) = degree p := le_antisymm (degree_map_le f) $ have hp0 : p ≠ 0, from λ hp0, by simpa [hp0, is_semiring_hom.map_zero f] using hf, begin rw [degree_eq_nat_degree hp0], refine le_degree_of_ne_zero _, rw [coeff_map], exact hf end lemma monic_map [comm_semiring β] (f : α →+* β) (hp : monic p) : monic (p.map f) := if h : (0 : β) = 1 then by haveI := subsingleton_of_zero_eq_one β h; exact subsingleton.elim _ _ else have f (leading_coeff p) ≠ 0, by rwa [show _ = _, from hp, is_semiring_hom.map_one f, ne.def, eq_comm], by erw [monic, leading_coeff, nat_degree_eq_of_degree_eq (degree_map_eq_of_leading_coeff_ne_zero f this), coeff_map, ← leading_coeff, show _ = _, from hp, is_semiring_hom.map_one f] lemma zero_le_degree_iff {p : polynomial α} : 0 ≤ degree p ↔ p ≠ 0 := by rw [ne.def, ← degree_eq_bot]; cases degree p; exact dec_trivial @[simp] lemma coeff_mul_X_zero (p : polynomial α) : coeff (p * X) 0 = 0 := by rw [coeff_mul, nat.antidiagonal_zero]; simp only [polynomial.coeff_X_zero, finset.insert_empty_eq_singleton, finset.sum_singleton, mul_zero] end comm_semiring instance subsingleton [subsingleton α] [comm_semiring α] : subsingleton (polynomial α) := ⟨λ _ _, ext (λ _, subsingleton.elim _ _)⟩ section comm_semiring variables [comm_semiring α] {p q r : polynomial α} lemma ne_zero_of_monic_of_zero_ne_one (hp : monic p) (h : (0 : α) ≠ 1) : p ≠ 0 := mt (congr_arg leading_coeff) $ by rw [monic.def.1 hp, leading_coeff_zero]; cc lemma eq_X_add_C_of_degree_le_one (h : degree p ≤ 1) : p = C (p.coeff 1) * X + C (p.coeff 0) := ext (λ n, nat.cases_on n (by simp) (λ n, nat.cases_on n (by simp [coeff_C]) (λ m, have degree p < m.succ.succ, from lt_of_le_of_lt h dec_trivial, by simp [coeff_eq_zero_of_degree_lt this, coeff_C, nat.succ_ne_zero, coeff_X, nat.succ_inj', @eq_comm ℕ 0]))) lemma eq_X_add_C_of_degree_eq_one (h : degree p = 1) : p = C (p.leading_coeff) * X + C (p.coeff 0) := (eq_X_add_C_of_degree_le_one (show degree p ≤ 1, from h ▸ le_refl _)).trans (by simp [leading_coeff, nat_degree_eq_of_degree_eq_some h]) theorem degree_C_mul_X_pow_le (r : α) (n : ℕ) : degree (C r * X^n) ≤ n := begin rw [← single_eq_C_mul_X], refine finset.sup_le (λ b hb, _), rw list.eq_of_mem_singleton (finsupp.support_single_subset hb), exact le_refl _ end theorem degree_X_pow_le (n : ℕ) : degree (X^n : polynomial α) ≤ n := by simpa only [C_1, one_mul] using degree_C_mul_X_pow_le (1:α) n theorem degree_X_le : degree (X : polynomial α) ≤ 1 := by simpa only [C_1, one_mul, pow_one] using degree_C_mul_X_pow_le (1:α) 1 section injective open function variables [comm_semiring β] {f : α →+* β} (hf : function.injective f) include hf lemma degree_map_eq_of_injective (p : polynomial α) : degree (p.map f) = degree p := if h : p = 0 then by simp [h] else degree_map_eq_of_leading_coeff_ne_zero _ (by rw [← is_semiring_hom.map_zero f]; exact mt hf.eq_iff.1 (mt leading_coeff_eq_zero.1 h)) lemma degree_map' (p : polynomial α) : degree (p.map f) = degree p := p.degree_map_eq_of_injective hf lemma nat_degree_map' (p : polynomial α) : nat_degree (p.map f) = nat_degree p := nat_degree_eq_of_degree_eq (degree_map' hf p) lemma map_injective (p : polynomial α) : injective (map f) := λ p q h, ext $ λ m, hf $ begin rw ext_iff at h, specialize h m, rw [coeff_map f, coeff_map f] at h, exact h end lemma leading_coeff_of_injective (p : polynomial α) : leading_coeff (p.map f) = f (leading_coeff p) := begin delta leading_coeff, rw [coeff_map f, nat_degree_map' hf p] end lemma monic_of_injective {p : polynomial α} (hp : (p.map f).monic) : p.monic := begin apply hf, rw [← leading_coeff_of_injective hf, hp.leading_coeff, is_semiring_hom.map_one f] end end injective theorem monic_of_degree_le (n : ℕ) (H1 : degree p ≤ n) (H2 : coeff p n = 1) : monic p := decidable.by_cases (assume H : degree p < n, @subsingleton.elim _ (subsingleton_of_zero_eq_one α $ H2 ▸ (coeff_eq_zero_of_degree_lt H).symm) _ _) (assume H : ¬degree p < n, by rwa [monic, leading_coeff, nat_degree, (lt_or_eq_of_le H1).resolve_left H]) theorem monic_X_pow_add {n : ℕ} (H : degree p ≤ n) : monic (X ^ (n+1) + p) := have H1 : degree p < n+1, from lt_of_le_of_lt H (with_bot.coe_lt_coe.2 (nat.lt_succ_self n)), monic_of_degree_le (n+1) (le_trans (degree_add_le _ _) (max_le (degree_X_pow_le _) (le_of_lt H1))) (by rw [coeff_add, coeff_X_pow, if_pos rfl, coeff_eq_zero_of_degree_lt H1, add_zero]) theorem monic_X_add_C (x : α) : monic (X + C x) := pow_one (X : polynomial α) ▸ monic_X_pow_add degree_C_le theorem degree_le_iff_coeff_zero (f : polynomial α) (n : with_bot ℕ) : degree f ≤ n ↔ ∀ m : ℕ, n < m → coeff f m = 0 := ⟨λ (H : finset.sup (f.support) some ≤ n) m (Hm : n < (m : with_bot ℕ)), decidable.of_not_not $ λ H4, have H1 : m ∉ f.support, from λ H2, not_lt_of_ge ((finset.sup_le_iff.1 H) m H2 : ((m : with_bot ℕ) ≤ n)) Hm, H1 $ (finsupp.mem_support_to_fun f m).2 H4, λ H, finset.sup_le $ λ b Hb, decidable.of_not_not $ λ Hn, (finsupp.mem_support_to_fun f b).1 Hb $ H b $ lt_of_not_ge Hn⟩ theorem nat_degree_le_of_degree_le {p : polynomial α} {n : ℕ} (H : degree p ≤ n) : nat_degree p ≤ n := show option.get_or_else (degree p) 0 ≤ n, from match degree p, H with | none, H := zero_le _ | (some d), H := with_bot.coe_le_coe.1 H end theorem leading_coeff_mul_X_pow {p : polynomial α} {n : ℕ} : leading_coeff (p * X ^ n) = leading_coeff p := decidable.by_cases (assume H : leading_coeff p = 0, by rw [H, leading_coeff_eq_zero.1 H, zero_mul, leading_coeff_zero]) (assume H : leading_coeff p ≠ 0, by rw [leading_coeff_mul', leading_coeff_X_pow, mul_one]; rwa [leading_coeff_X_pow, mul_one]) lemma monic_mul (hp : monic p) (hq : monic q) : monic (p * q) := if h0 : (0 : α) = 1 then by haveI := subsingleton_of_zero_eq_one _ h0; exact subsingleton.elim _ _ else have leading_coeff p * leading_coeff q ≠ 0, by simp [monic.def.1 hp, monic.def.1 hq, ne.symm h0], by rw [monic.def, leading_coeff_mul' this, monic.def.1 hp, monic.def.1 hq, one_mul] lemma monic_pow (hp : monic p) : ∀ (n : ℕ), monic (p ^ n) | 0 := monic_one | (n+1) := monic_mul hp (monic_pow n) lemma multiplicity_finite_of_degree_pos_of_monic (hp : (0 : with_bot ℕ) < degree p) (hmp : monic p) (hq : q ≠ 0) : multiplicity.finite p q := have zn0 : (0 : α) ≠ 1, from λ h, by haveI := subsingleton_of_zero_eq_one _ h; exact hq (subsingleton.elim _ _), ⟨nat_degree q, λ ⟨r, hr⟩, have hp0 : p ≠ 0, from λ hp0, by simp [hp0] at hp; contradiction, have hr0 : r ≠ 0, from λ hr0, by simp * at *, have hpn1 : leading_coeff p ^ (nat_degree q + 1) = 1, by simp [show _ = _, from hmp], have hpn0' : leading_coeff p ^ (nat_degree q + 1) ≠ 0, from hpn1.symm ▸ zn0.symm, have hpnr0 : leading_coeff (p ^ (nat_degree q + 1)) * leading_coeff r ≠ 0, by simp only [leading_coeff_pow' hpn0', leading_coeff_eq_zero, hpn1, one_pow, one_mul, ne.def, hr0]; simp, have hpn0 : p ^ (nat_degree q + 1) ≠ 0, from mt leading_coeff_eq_zero.2 $ by rw [leading_coeff_pow' hpn0', show _ = _, from hmp, one_pow]; exact zn0.symm, have hnp : 0 < nat_degree p, by rw [← with_bot.coe_lt_coe, ← degree_eq_nat_degree hp0]; exact hp, begin have := congr_arg nat_degree hr, rw [nat_degree_mul_eq' hpnr0, nat_degree_pow_eq' hpn0', add_mul, add_assoc] at this, exact ne_of_lt (lt_add_of_le_of_pos (le_mul_of_one_le_right' (nat.zero_le _) hnp) (add_pos_of_pos_of_nonneg (by rwa one_mul) (nat.zero_le _))) this end⟩ end comm_semiring section nonzero_comm_semiring variables [nonzero_comm_semiring α] {p q : polynomial α} instance : nonzero_comm_semiring (polynomial α) := { zero_ne_one := λ (h : (0 : polynomial α) = 1), @zero_ne_one α _ $ calc (0 : α) = eval 0 0 : eval_zero.symm ... = eval 0 1 : congr_arg _ h ... = 1 : eval_C, ..polynomial.comm_semiring } @[simp] lemma degree_one : degree (1 : polynomial α) = (0 : with_bot ℕ) := degree_C (show (1 : α) ≠ 0, from zero_ne_one.symm) @[simp] lemma degree_X : degree (X : polynomial α) = 1 := begin unfold X degree monomial single finsupp.support, rw if_neg (zero_ne_one).symm, refl end lemma X_ne_zero : (X : polynomial α) ≠ 0 := mt (congr_arg (λ p, coeff p 1)) (by simp) @[simp] lemma degree_X_pow : ∀ (n : ℕ), degree ((X : polynomial α) ^ n) = n | 0 := by simp only [pow_zero, degree_one]; refl | (n+1) := have h : leading_coeff (X : polynomial α) * leading_coeff (X ^ n) ≠ 0, by rw [leading_coeff_X, leading_coeff_X_pow n, one_mul]; exact zero_ne_one.symm, by rw [pow_succ, degree_mul_eq' h, degree_X, degree_X_pow, add_comm]; refl @[simp] lemma not_monic_zero : ¬monic (0 : polynomial α) := by simpa only [monic, leading_coeff_zero] using zero_ne_one lemma ne_zero_of_monic (h : monic p) : p ≠ 0 := λ h₁, @not_monic_zero α _ (h₁ ▸ h) end nonzero_comm_semiring section comm_semiring variables [comm_semiring α] {p q : polynomial α} /-- `dix_X p` return a polynomial `q` such that `q * X + C (p.coeff 0) = p`. It can be used in a semiring where the usual division algorithm is not possible -/ def div_X (p : polynomial α) : polynomial α := { to_fun := λ n, p.coeff (n + 1), support := ⟨(p.support.filter (> 0)).1.map (λ n, n - 1), multiset.nodup_map_on begin simp only [finset.mem_def.symm, finset.mem_erase, finset.mem_filter], assume x hx y hy hxy, rwa [← @add_right_cancel_iff _ _ 1, nat.sub_add_cancel hx.2, nat.sub_add_cancel hy.2] at hxy end (p.support.filter (> 0)).2⟩, mem_support_to_fun := λ n, suffices (∃ (a : ℕ), (¬coeff p a = 0 ∧ a > 0) ∧ a - 1 = n) ↔ ¬coeff p (n + 1) = 0, by simpa [finset.mem_def.symm, apply_eq_coeff], ⟨λ ⟨a, ha⟩, by rw [← ha.2, nat.sub_add_cancel ha.1.2]; exact ha.1.1, λ h, ⟨n + 1, ⟨h, nat.succ_pos _⟩, nat.succ_sub_one _⟩⟩ } lemma div_X_mul_X_add (p : polynomial α) : div_X p * X + C (p.coeff 0) = p := ext $ λ n, nat.cases_on n (by simp) (by simp [coeff_C, nat.succ_ne_zero, coeff_mul_X, div_X]) @[simp] lemma div_X_C (a : α) : div_X (C a) = 0 := ext $ λ n, by cases n; simp [div_X, coeff_C]; simp [coeff] lemma div_X_eq_zero_iff : div_X p = 0 ↔ p = C (p.coeff 0) := ⟨λ h, by simpa [eq_comm, h] using div_X_mul_X_add p, λ h, by rw [h, div_X_C]⟩ lemma div_X_add : div_X (p + q) = div_X p + div_X q := ext $ by simp [div_X] def nonzero_comm_semiring.of_polynomial_ne (h : p ≠ q) : nonzero_comm_semiring α := { zero_ne_one := λ h01 : 0 = 1, h $ by rw [← mul_one p, ← mul_one q, ← C_1, ← h01, C_0, mul_zero, mul_zero], ..show comm_semiring α, by apply_instance } lemma degree_lt_degree_mul_X (hp : p ≠ 0) : p.degree < (p * X).degree := by letI := nonzero_comm_semiring.of_polynomial_ne hp; exact have leading_coeff p * leading_coeff X ≠ 0, by simpa, by erw [degree_mul_eq' this, degree_eq_nat_degree hp, degree_X, ← with_bot.coe_one, ← with_bot.coe_add, with_bot.coe_lt_coe]; exact nat.lt_succ_self _ lemma degree_div_X_lt (hp0 : p ≠ 0) : (div_X p).degree < p.degree := by letI := nonzero_comm_semiring.of_polynomial_ne hp0; exact calc (div_X p).degree < (div_X p * X + C (p.coeff 0)).degree : if h : degree p ≤ 0 then begin have h' : C (p.coeff 0) ≠ 0, by rwa [← eq_C_of_degree_le_zero h], rw [eq_C_of_degree_le_zero h, div_X_C, degree_zero, zero_mul, zero_add], exact lt_of_le_of_ne bot_le (ne.symm (mt degree_eq_bot.1 $ by simp [h'])), end else have hXp0 : div_X p ≠ 0, by simpa [div_X_eq_zero_iff, -not_le, degree_le_zero_iff] using h, have leading_coeff (div_X p) * leading_coeff X ≠ 0, by simpa, have degree (C (p.coeff 0)) < degree (div_X p * X), from calc degree (C (p.coeff 0)) ≤ 0 : degree_C_le ... < 1 : dec_trivial ... = degree (X : polynomial α) : degree_X.symm ... ≤ degree (div_X p * X) : by rw [← zero_add (degree X), degree_mul_eq' this]; exact add_le_add' (by rw [zero_le_degree_iff, ne.def, div_X_eq_zero_iff]; exact λ h0, h (h0.symm ▸ degree_C_le)) (le_refl _), by rw [add_comm, degree_add_eq_of_degree_lt this]; exact degree_lt_degree_mul_X hXp0 ... = p.degree : by rw div_X_mul_X_add @[elab_as_eliminator] noncomputable def rec_on_horner {M : polynomial α → Sort*} : Π (p : polynomial α), M 0 → (Π p a, coeff p 0 = 0 → a ≠ 0 → M p → M (p + C a)) → (Π p, p ≠ 0 → M p → M (p * X)) → M p | p := λ M0 MC MX, if hp : p = 0 then eq.rec_on hp.symm M0 else have wf : degree (div_X p) < degree p, from degree_div_X_lt hp, by rw [← div_X_mul_X_add p] at *; exact if hcp0 : coeff p 0 = 0 then by rw [hcp0, C_0, add_zero]; exact MX _ (λ h : div_X p = 0, by simpa [h, hcp0] using hp) (rec_on_horner _ M0 MC MX) else MC _ _ (coeff_mul_X_zero _) hcp0 (if hpX0 : div_X p = 0 then show M (div_X p * X), by rw [hpX0, zero_mul]; exact M0 else MX (div_X p) hpX0 (rec_on_horner _ M0 MC MX)) using_well_founded {dec_tac := tactic.assumption} @[elab_as_eliminator] lemma degree_pos_induction_on {P : polynomial α → Prop} (p : polynomial α) (h0 : 0 < degree p) (hC : ∀ {a}, a ≠ 0 → P (C a * X)) (hX : ∀ {p}, 0 < degree p → P p → P (p * X)) (hadd : ∀ {p} {a}, 0 < degree p → P p → P (p + C a)) : P p := rec_on_horner p (λ h, by rw degree_zero at h; exact absurd h dec_trivial) (λ p a _ _ ih h0, have 0 < degree p, from lt_of_not_ge (λ h, (not_lt_of_ge degree_C_le) $ by rwa [eq_C_of_degree_le_zero h, ← C_add] at h0), hadd this (ih this)) (λ p _ ih h0', if h0 : 0 < degree p then hX h0 (ih h0) else by rw [eq_C_of_degree_le_zero (le_of_not_gt h0)] at *; exact hC (λ h : coeff p 0 = 0, by simpa [h, nat.not_lt_zero] using h0')) h0 end comm_semiring section comm_ring variables [comm_ring α] {p q : polynomial α} instance : comm_ring (polynomial α) := add_monoid_algebra.comm_ring instance : module α (polynomial α) := add_monoid_algebra.module variable (α) def lcoeff (n : ℕ) : polynomial α →ₗ α := { to_fun := λ f, coeff f n, add := λ f g, coeff_add f g n, smul := λ r p, coeff_smul p r n } variable {α} @[simp] lemma lcoeff_apply (n : ℕ) (f : polynomial α) : lcoeff α n f = coeff f n := rfl instance C.is_ring_hom : is_ring_hom (@C α _) := by apply is_ring_hom.of_semiring lemma int_cast_eq_C (n : ℤ) : (n : polynomial α) = C n := ((ring_hom.of C).map_int_cast n).symm @[simp] lemma C_neg : C (-a) = -C a := is_ring_hom.map_neg C @[simp] lemma C_sub : C (a - b) = C a - C b := is_ring_hom.map_sub C instance eval₂.is_ring_hom {β} [comm_ring β] (f : α → β) [is_ring_hom f] {x : β} : is_ring_hom (eval₂ f x) := by apply is_ring_hom.of_semiring instance eval.is_ring_hom {x : α} : is_ring_hom (eval x) := eval₂.is_ring_hom _ instance map.is_ring_hom {β} [comm_ring β] (f : α →+* β) : is_ring_hom (map f) := eval₂.is_ring_hom (C ∘ f) @[simp] lemma map_sub {β} [comm_ring β] (f : α →+* β) : (p - q).map f = p.map f - q.map f := is_ring_hom.map_sub _ @[simp] lemma map_neg {β} [comm_ring β] (f : α →+* β) : (-p).map f = -(p.map f) := is_ring_hom.map_neg _ @[simp] lemma degree_neg (p : polynomial α) : degree (-p) = degree p := by unfold degree; rw support_neg @[simp] lemma nat_degree_neg (p : polynomial α) : nat_degree (-p) = nat_degree p := by simp [nat_degree] @[simp] lemma nat_degree_int_cast (n : ℤ) : nat_degree (n : polynomial α) = 0 := by simp [int_cast_eq_C] @[simp] lemma coeff_neg (p : polynomial α) (n : ℕ) : coeff (-p) n = -coeff p n := rfl @[simp] lemma coeff_sub (p q : polynomial α) (n : ℕ) : coeff (p - q) n = coeff p n - coeff q n := rfl @[simp] lemma eval₂_neg {β} [comm_ring β] (f : α → β) [is_ring_hom f] {x : β} : (-p).eval₂ f x = -p.eval₂ f x := is_ring_hom.map_neg _ @[simp] lemma eval₂_sub {β} [comm_ring β] (f : α → β) [is_ring_hom f] {x : β} : (p - q).eval₂ f x = p.eval₂ f x - q.eval₂ f x := is_ring_hom.map_sub _ @[simp] lemma eval_neg (p : polynomial α) (x : α) : (-p).eval x = -p.eval x := is_ring_hom.map_neg _ @[simp] lemma eval_sub (p q : polynomial α) (x : α) : (p - q).eval x = p.eval x - q.eval x := is_ring_hom.map_sub _ section aeval /-- `R[X]` is the generator of the category `R-Alg`. -/ instance polynomial (R : Type u) [comm_semiring R] : algebra R (polynomial R) := { commutes' := λ _ _, mul_comm _ _, smul_def' := λ c p, (polynomial.C_mul' c p).symm, .. polynomial.semimodule, .. ring_hom.of polynomial.C, } variables (R : Type u) (A : Type v) variables [comm_ring R] [comm_ring A] [algebra R A] variables (x : A) /-- Given a valuation `x` of the variable in an `R`-algebra `A`, `aeval R A x` is the unique `R`-algebra homomorphism from `R[X]` to `A` sending `X` to `x`. -/ def aeval : polynomial R →ₐ[R] A := { commutes' := λ r, eval₂_C _ _, ..eval₂_ring_hom (algebra_map R A) x } theorem aeval_def (p : polynomial R) : aeval R A x p = eval₂ (algebra_map R A) x p := rfl @[simp] lemma aeval_X : aeval R A x X = x := eval₂_X _ x @[simp] lemma aeval_C (r : R) : aeval R A x (C r) = algebra_map R A r := eval₂_C _ x theorem eval_unique (φ : polynomial R →ₐ[R] A) (p) : φ p = eval₂ (algebra_map R A) (φ X) p := begin apply polynomial.induction_on p, { intro r, rw eval₂_C, exact φ.commutes r }, { intros f g ih1 ih2, rw [φ.map_add, ih1, ih2, eval₂_add] }, { intros n r ih, rw [pow_succ', ← mul_assoc, φ.map_mul, eval₂_mul (algebra_map R A), eval₂_X, ih] } end end aeval lemma degree_sub_lt (hd : degree p = degree q) (hp0 : p ≠ 0) (hlc : leading_coeff p = leading_coeff q) : degree (p - q) < degree p := have hp : single (nat_degree p) (leading_coeff p) + p.erase (nat_degree p) = p := finsupp.single_add_erase, have hq : single (nat_degree q) (leading_coeff q) + q.erase (nat_degree q) = q := finsupp.single_add_erase, have hd' : nat_degree p = nat_degree q := by unfold nat_degree; rw hd, have hq0 : q ≠ 0 := mt degree_eq_bot.2 (hd ▸ mt degree_eq_bot.1 hp0), calc degree (p - q) = degree (erase (nat_degree q) p + -erase (nat_degree q) q) : by conv {to_lhs, rw [← hp, ← hq, hlc, hd', add_sub_add_left_eq_sub, sub_eq_add_neg]} ... ≤ max (degree (erase (nat_degree q) p)) (degree (erase (nat_degree q) q)) : degree_neg (erase (nat_degree q) q) ▸ degree_add_le _ _ ... < degree p : max_lt_iff.2 ⟨hd' ▸ degree_erase_lt hp0, hd.symm ▸ degree_erase_lt hq0⟩ lemma ne_zero_of_ne_zero_of_monic (hp : p ≠ 0) (hq : monic q) : q ≠ 0 | h := begin rw [h, monic.def, leading_coeff_zero] at hq, rw [← mul_one p, ← C_1, ← hq, C_0, mul_zero] at hp, exact hp rfl end lemma div_wf_lemma (h : degree q ≤ degree p ∧ p ≠ 0) (hq : monic q) : degree (p - C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q) < degree p := have hp : leading_coeff p ≠ 0 := mt leading_coeff_eq_zero.1 h.2, have hpq : leading_coeff (C (leading_coeff p) * X ^ (nat_degree p - nat_degree q)) * leading_coeff q ≠ 0, by rwa [leading_coeff_monomial, monic.def.1 hq, mul_one], if h0 : p - C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q = 0 then h0.symm ▸ (lt_of_not_ge $ mt le_bot_iff.1 (mt degree_eq_bot.1 h.2)) else have hq0 : q ≠ 0 := ne_zero_of_ne_zero_of_monic h.2 hq, have hlt : nat_degree q ≤ nat_degree p := with_bot.coe_le_coe.1 (by rw [← degree_eq_nat_degree h.2, ← degree_eq_nat_degree hq0]; exact h.1), degree_sub_lt (by rw [degree_mul_eq' hpq, degree_monomial _ hp, degree_eq_nat_degree h.2, degree_eq_nat_degree hq0, ← with_bot.coe_add, nat.sub_add_cancel hlt]) h.2 (by rw [leading_coeff_mul' hpq, leading_coeff_monomial, monic.def.1 hq, mul_one]) noncomputable def div_mod_by_monic_aux : Π (p : polynomial α) {q : polynomial α}, monic q → polynomial α × polynomial α | p := λ q hq, if h : degree q ≤ degree p ∧ p ≠ 0 then let z := C (leading_coeff p) * X^(nat_degree p - nat_degree q) in have wf : _ := div_wf_lemma h hq, let dm := div_mod_by_monic_aux (p - z * q) hq in ⟨z + dm.1, dm.2⟩ else ⟨0, p⟩ using_well_founded {dec_tac := tactic.assumption} /-- `div_by_monic` gives the quotient of `p` by a monic polynomial `q`. -/ def div_by_monic (p q : polynomial α) : polynomial α := if hq : monic q then (div_mod_by_monic_aux p hq).1 else 0 /-- `mod_by_monic` gives the remainder of `p` by a monic polynomial `q`. -/ def mod_by_monic (p q : polynomial α) : polynomial α := if hq : monic q then (div_mod_by_monic_aux p hq).2 else p infixl ` /ₘ ` : 70 := div_by_monic infixl ` %ₘ ` : 70 := mod_by_monic lemma degree_mod_by_monic_lt : ∀ (p : polynomial α) {q : polynomial α} (hq : monic q) (hq0 : q ≠ 0), degree (p %ₘ q) < degree q | p := λ q hq hq0, if h : degree q ≤ degree p ∧ p ≠ 0 then have wf : _ := div_wf_lemma ⟨h.1, h.2⟩ hq, have degree ((p - C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q) %ₘ q) < degree q := degree_mod_by_monic_lt (p - C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q) hq hq0, begin unfold mod_by_monic at this ⊢, unfold div_mod_by_monic_aux, rw dif_pos hq at this ⊢, rw if_pos h, exact this end else or.cases_on (not_and_distrib.1 h) begin unfold mod_by_monic div_mod_by_monic_aux, rw [dif_pos hq, if_neg h], exact lt_of_not_ge, end begin assume hp, unfold mod_by_monic div_mod_by_monic_aux, rw [dif_pos hq, if_neg h, not_not.1 hp], exact lt_of_le_of_ne bot_le (ne.symm (mt degree_eq_bot.1 hq0)), end using_well_founded {dec_tac := tactic.assumption} lemma mod_by_monic_eq_sub_mul_div : ∀ (p : polynomial α) {q : polynomial α} (hq : monic q), p %ₘ q = p - q * (p /ₘ q) | p := λ q hq, if h : degree q ≤ degree p ∧ p ≠ 0 then have wf : _ := div_wf_lemma h hq, have ih : _ := mod_by_monic_eq_sub_mul_div (p - C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q) hq, begin unfold mod_by_monic div_by_monic div_mod_by_monic_aux, rw [dif_pos hq, if_pos h], rw [mod_by_monic, dif_pos hq] at ih, refine ih.trans _, unfold div_by_monic, rw [dif_pos hq, dif_pos hq, if_pos h, mul_add, sub_add_eq_sub_sub, mul_comm] end else begin unfold mod_by_monic div_by_monic div_mod_by_monic_aux, rw [dif_pos hq, if_neg h, dif_pos hq, if_neg h, mul_zero, sub_zero] end using_well_founded {dec_tac := tactic.assumption} lemma mod_by_monic_add_div (p : polynomial α) {q : polynomial α} (hq : monic q) : p %ₘ q + q * (p /ₘ q) = p := eq_sub_iff_add_eq.1 (mod_by_monic_eq_sub_mul_div p hq) @[simp] lemma zero_mod_by_monic (p : polynomial α) : 0 %ₘ p = 0 := begin unfold mod_by_monic div_mod_by_monic_aux, by_cases hp : monic p, { rw [dif_pos hp, if_neg (mt and.right (not_not_intro rfl))] }, { rw [dif_neg hp] } end @[simp] lemma zero_div_by_monic (p : polynomial α) : 0 /ₘ p = 0 := begin unfold div_by_monic div_mod_by_monic_aux, by_cases hp : monic p, { rw [dif_pos hp, if_neg (mt and.right (not_not_intro rfl))] }, { rw [dif_neg hp] } end @[simp] lemma mod_by_monic_zero (p : polynomial α) : p %ₘ 0 = p := if h : monic (0 : polynomial α) then (subsingleton_of_monic_zero h).1 _ _ else by unfold mod_by_monic div_mod_by_monic_aux; rw dif_neg h @[simp] lemma div_by_monic_zero (p : polynomial α) : p /ₘ 0 = 0 := if h : monic (0 : polynomial α) then (subsingleton_of_monic_zero h).1 _ _ else by unfold div_by_monic div_mod_by_monic_aux; rw dif_neg h lemma div_by_monic_eq_of_not_monic (p : polynomial α) (hq : ¬monic q) : p /ₘ q = 0 := dif_neg hq lemma mod_by_monic_eq_of_not_monic (p : polynomial α) (hq : ¬monic q) : p %ₘ q = p := dif_neg hq lemma mod_by_monic_eq_self_iff (hq : monic q) (hq0 : q ≠ 0) : p %ₘ q = p ↔ degree p < degree q := ⟨λ h, h ▸ degree_mod_by_monic_lt _ hq hq0, λ h, have ¬ degree q ≤ degree p := not_le_of_gt h, by unfold mod_by_monic div_mod_by_monic_aux; rw [dif_pos hq, if_neg (mt and.left this)]⟩ lemma div_by_monic_eq_zero_iff (hq : monic q) (hq0 : q ≠ 0) : p /ₘ q = 0 ↔ degree p < degree q := ⟨λ h, by have := mod_by_monic_add_div p hq; rwa [h, mul_zero, add_zero, mod_by_monic_eq_self_iff hq hq0] at this, λ h, have ¬ degree q ≤ degree p := not_le_of_gt h, by unfold div_by_monic div_mod_by_monic_aux; rw [dif_pos hq, if_neg (mt and.left this)]⟩ lemma degree_add_div_by_monic (hq : monic q) (h : degree q ≤ degree p) : degree q + degree (p /ₘ q) = degree p := if hq0 : q = 0 then have ∀ (p : polynomial α), p = 0, from λ p, (@subsingleton_of_monic_zero α _ (hq0 ▸ hq)).1 _ _, by rw [this (p /ₘ q), this p, this q]; refl else have hdiv0 : p /ₘ q ≠ 0 := by rwa [(≠), div_by_monic_eq_zero_iff hq hq0, not_lt], have hlc : leading_coeff q * leading_coeff (p /ₘ q) ≠ 0 := by rwa [monic.def.1 hq, one_mul, (≠), leading_coeff_eq_zero], have hmod : degree (p %ₘ q) < degree (q * (p /ₘ q)) := calc degree (p %ₘ q) < degree q : degree_mod_by_monic_lt _ hq hq0 ... ≤ _ : by rw [degree_mul_eq' hlc, degree_eq_nat_degree hq0, degree_eq_nat_degree hdiv0, ← with_bot.coe_add, with_bot.coe_le_coe]; exact nat.le_add_right _ _, calc degree q + degree (p /ₘ q) = degree (q * (p /ₘ q)) : eq.symm (degree_mul_eq' hlc) ... = degree (p %ₘ q + q * (p /ₘ q)) : (degree_add_eq_of_degree_lt hmod).symm ... = _ : congr_arg _ (mod_by_monic_add_div _ hq) lemma degree_div_by_monic_le (p q : polynomial α) : degree (p /ₘ q) ≤ degree p := if hp0 : p = 0 then by simp only [hp0, zero_div_by_monic, le_refl] else if hq : monic q then have hq0 : q ≠ 0 := ne_zero_of_ne_zero_of_monic hp0 hq, if h : degree q ≤ degree p then by rw [← degree_add_div_by_monic hq h, degree_eq_nat_degree hq0, degree_eq_nat_degree (mt (div_by_monic_eq_zero_iff hq hq0).1 (not_lt.2 h))]; exact with_bot.coe_le_coe.2 (nat.le_add_left _ _) else by unfold div_by_monic div_mod_by_monic_aux; simp only [dif_pos hq, h, false_and, if_false, degree_zero, bot_le] else (div_by_monic_eq_of_not_monic p hq).symm ▸ bot_le lemma degree_div_by_monic_lt (p : polynomial α) {q : polynomial α} (hq : monic q) (hp0 : p ≠ 0) (h0q : 0 < degree q) : degree (p /ₘ q) < degree p := have hq0 : q ≠ 0 := ne_zero_of_ne_zero_of_monic hp0 hq, if hpq : degree p < degree q then begin rw [(div_by_monic_eq_zero_iff hq hq0).2 hpq, degree_eq_nat_degree hp0], exact with_bot.bot_lt_some _ end else begin rw [← degree_add_div_by_monic hq (not_lt.1 hpq), degree_eq_nat_degree hq0, degree_eq_nat_degree (mt (div_by_monic_eq_zero_iff hq hq0).1 hpq)], exact with_bot.coe_lt_coe.2 (nat.lt_add_of_pos_left (with_bot.coe_lt_coe.1 $ (degree_eq_nat_degree hq0) ▸ h0q)) end lemma div_mod_by_monic_unique {f g} (q r : polynomial α) (hg : monic g) (h : r + g * q = f ∧ degree r < degree g) : f /ₘ g = q ∧ f %ₘ g = r := if hg0 : g = 0 then by split; exact (subsingleton_of_monic_zero (hg0 ▸ hg : monic (0 : polynomial α))).1 _ _ else have h₁ : r - f %ₘ g = -g * (q - f /ₘ g), from eq_of_sub_eq_zero (by rw [← sub_eq_zero_of_eq (h.1.trans (mod_by_monic_add_div f hg).symm)]; simp [mul_add, mul_comm, sub_eq_add_neg, add_comm, add_left_comm]), have h₂ : degree (r - f %ₘ g) = degree (g * (q - f /ₘ g)), by simp [h₁], have h₄ : degree (r - f %ₘ g) < degree g, from calc degree (r - f %ₘ g) ≤ max (degree r) (degree (-(f %ₘ g))) : degree_add_le _ _ ... < degree g : max_lt_iff.2 ⟨h.2, by rw degree_neg; exact degree_mod_by_monic_lt _ hg hg0⟩, have h₅ : q - (f /ₘ g) = 0, from by_contradiction (λ hqf, not_le_of_gt h₄ $ calc degree g ≤ degree g + degree (q - f /ₘ g) : by erw [degree_eq_nat_degree hg0, degree_eq_nat_degree hqf, with_bot.coe_le_coe]; exact nat.le_add_right _ _ ... = degree (r - f %ₘ g) : by rw [h₂, degree_mul_eq']; simpa [monic.def.1 hg]), ⟨eq.symm $ eq_of_sub_eq_zero h₅, eq.symm $ eq_of_sub_eq_zero $ by simpa [h₅] using h₁⟩ lemma map_mod_div_by_monic [comm_ring β] (f : α →+* β) (hq : monic q) : (p /ₘ q).map f = p.map f /ₘ q.map f ∧ (p %ₘ q).map f = p.map f %ₘ q.map f := if h01 : (0 : β) = 1 then by haveI := subsingleton_of_zero_eq_one β h01; exact ⟨subsingleton.elim _ _, subsingleton.elim _ _⟩ else have h01α : (0 : α) ≠ 1, from mt (congr_arg f) (by rwa [is_semiring_hom.map_one f, is_semiring_hom.map_zero f]), have map f p /ₘ map f q = map f (p /ₘ q) ∧ map f p %ₘ map f q = map f (p %ₘ q), from (div_mod_by_monic_unique ((p /ₘ q).map f) _ (monic_map f hq) ⟨eq.symm $ by rw [← map_mul, ← map_add, mod_by_monic_add_div _ hq], calc _ ≤ degree (p %ₘ q) : degree_map_le _ ... < degree q : degree_mod_by_monic_lt _ hq $ (ne_zero_of_monic_of_zero_ne_one hq h01α) ... = _ : eq.symm $ degree_map_eq_of_leading_coeff_ne_zero _ (by rw [monic.def.1 hq, is_semiring_hom.map_one f]; exact ne.symm h01)⟩), ⟨this.1.symm, this.2.symm⟩ lemma map_div_by_monic [comm_ring β] (f : α →+* β) (hq : monic q) : (p /ₘ q).map f = p.map f /ₘ q.map f := (map_mod_div_by_monic f hq).1 lemma map_mod_by_monic [comm_ring β] (f : α →+* β) (hq : monic q) : (p %ₘ q).map f = p.map f %ₘ q.map f := (map_mod_div_by_monic f hq).2 lemma dvd_iff_mod_by_monic_eq_zero (hq : monic q) : p %ₘ q = 0 ↔ q ∣ p := ⟨λ h, by rw [← mod_by_monic_add_div p hq, h, zero_add]; exact dvd_mul_right _ _, λ h, if hq0 : q = 0 then by rw hq0 at hq; exact (subsingleton_of_monic_zero hq).1 _ _ else let ⟨r, hr⟩ := exists_eq_mul_right_of_dvd h in by_contradiction (λ hpq0, have hmod : p %ₘ q = q * (r - p /ₘ q) := by rw [mod_by_monic_eq_sub_mul_div _ hq, mul_sub, ← hr], have degree (q * (r - p /ₘ q)) < degree q := hmod ▸ degree_mod_by_monic_lt _ hq hq0, have hrpq0 : leading_coeff (r - p /ₘ q) ≠ 0 := λ h, hpq0 $ leading_coeff_eq_zero.1 (by rw [hmod, leading_coeff_eq_zero.1 h, mul_zero, leading_coeff_zero]), have hlc : leading_coeff q * leading_coeff (r - p /ₘ q) ≠ 0 := by rwa [monic.def.1 hq, one_mul], by rw [degree_mul_eq' hlc, degree_eq_nat_degree hq0, degree_eq_nat_degree (mt leading_coeff_eq_zero.2 hrpq0)] at this; exact not_lt_of_ge (nat.le_add_right _ _) (with_bot.some_lt_some.1 this))⟩ @[simp] lemma mod_by_monic_one (p : polynomial α) : p %ₘ 1 = 0 := (dvd_iff_mod_by_monic_eq_zero monic_one).2 (one_dvd _) @[simp] lemma div_by_monic_one (p : polynomial α) : p /ₘ 1 = p := by conv_rhs { rw [← mod_by_monic_add_div p monic_one] }; simp lemma degree_pos_of_root (hp : p ≠ 0) (h : is_root p a) : 0 < degree p := lt_of_not_ge $ λ hlt, begin have := eq_C_of_degree_le_zero hlt, rw [is_root, this, eval_C] at h, exact hp (finsupp.ext (λ n, show coeff p n = 0, from nat.cases_on n h (λ _, coeff_eq_zero_of_degree_lt (lt_of_le_of_lt hlt (with_bot.coe_lt_coe.2 (nat.succ_pos _)))))), end theorem monic_X_sub_C (x : α) : monic (X - C x) := by simpa only [C_neg] using monic_X_add_C (-x) theorem monic_X_pow_sub {n : ℕ} (H : degree p ≤ n) : monic (X ^ (n+1) - p) := monic_X_pow_add ((degree_neg p).symm ▸ H) theorem degree_mod_by_monic_le (p : polynomial α) {q : polynomial α} (hq : monic q) : degree (p %ₘ q) ≤ degree q := decidable.by_cases (assume H : q = 0, by rw [monic, H, leading_coeff_zero] at hq; have : (0:polynomial α) = 1 := (by rw [← C_0, ← C_1, hq]); rw [eq_zero_of_zero_eq_one _ this (p %ₘ q), eq_zero_of_zero_eq_one _ this q]; exact le_refl _) (assume H : q ≠ 0, le_of_lt $ degree_mod_by_monic_lt _ hq H) lemma root_X_sub_C : is_root (X - C a) b ↔ a = b := by rw [is_root.def, eval_sub, eval_X, eval_C, sub_eq_zero_iff_eq, eq_comm] def nonzero_comm_ring.of_polynomial_ne (h : p ≠ q) : nonzero_comm_ring α := { zero := 0, one := 1, zero_ne_one := λ h01, h $ by rw [← one_mul p, ← one_mul q, ← C_1, ← h01, C_0, zero_mul, zero_mul], ..show comm_ring α, by apply_instance } end comm_ring section nonzero_comm_ring variables [nonzero_comm_ring α] {p q : polynomial α} instance : nonzero_comm_ring (polynomial α) := { ..polynomial.nonzero_comm_semiring, ..polynomial.comm_ring } @[simp] lemma degree_X_sub_C (a : α) : degree (X - C a) = 1 := begin rw [sub_eq_add_neg, add_comm, ← @degree_X α], by_cases ha : a = 0, { simp only [ha, C_0, neg_zero, zero_add] }, exact degree_add_eq_of_degree_lt (by rw [degree_X, degree_neg, degree_C ha]; exact dec_trivial) end lemma degree_X_pow_sub_C {n : ℕ} (hn : 0 < n) (a : α) : degree ((X : polynomial α) ^ n - C a) = n := have degree (-C a) < degree ((X : polynomial α) ^ n), from calc degree (-C a) ≤ 0 : by rw degree_neg; exact degree_C_le ... < degree ((X : polynomial α) ^ n) : by rwa [degree_X_pow]; exact with_bot.coe_lt_coe.2 hn, by rw [sub_eq_add_neg, add_comm, degree_add_eq_of_degree_lt this, degree_X_pow] lemma X_pow_sub_C_ne_zero {n : ℕ} (hn : 0 < n) (a : α) : (X : polynomial α) ^ n - C a ≠ 0 := mt degree_eq_bot.2 (show degree ((X : polynomial α) ^ n - C a) ≠ ⊥, by rw degree_X_pow_sub_C hn; exact dec_trivial) end nonzero_comm_ring section comm_ring variables [comm_ring α] {p q : polynomial α} @[simp] lemma mod_by_monic_X_sub_C_eq_C_eval (p : polynomial α) (a : α) : p %ₘ (X - C a) = C (p.eval a) := if h0 : (0 : α) = 1 then by letI := subsingleton_of_zero_eq_one α h0; exact subsingleton.elim _ _ else by letI : nonzero_comm_ring α := nonzero_comm_ring.of_ne h0; exact have h : (p %ₘ (X - C a)).eval a = p.eval a := by rw [mod_by_monic_eq_sub_mul_div _ (monic_X_sub_C a), eval_sub, eval_mul, eval_sub, eval_X, eval_C, sub_self, zero_mul, sub_zero], have degree (p %ₘ (X - C a)) < 1 := degree_X_sub_C a ▸ degree_mod_by_monic_lt p (monic_X_sub_C a) ((degree_X_sub_C a).symm ▸ ne_zero_of_monic (monic_X_sub_C _)), have degree (p %ₘ (X - C a)) ≤ 0 := begin cases (degree (p %ₘ (X - C a))), { exact bot_le }, { exact with_bot.some_le_some.2 (nat.le_of_lt_succ (with_bot.some_lt_some.1 this)) } end, begin rw [eq_C_of_degree_le_zero this, eval_C] at h, rw [eq_C_of_degree_le_zero this, h] end lemma mul_div_by_monic_eq_iff_is_root : (X - C a) * (p /ₘ (X - C a)) = p ↔ is_root p a := ⟨λ h, by rw [← h, is_root.def, eval_mul, eval_sub, eval_X, eval_C, sub_self, zero_mul], λ h : p.eval a = 0, by conv {to_rhs, rw ← mod_by_monic_add_div p (monic_X_sub_C a)}; rw [mod_by_monic_X_sub_C_eq_C_eval, h, C_0, zero_add]⟩ lemma dvd_iff_is_root : (X - C a) ∣ p ↔ is_root p a := ⟨λ h, by rwa [← dvd_iff_mod_by_monic_eq_zero (monic_X_sub_C _), mod_by_monic_X_sub_C_eq_C_eval, ← C_0, C_inj] at h, λ h, ⟨(p /ₘ (X - C a)), by rw mul_div_by_monic_eq_iff_is_root.2 h⟩⟩ lemma mod_by_monic_X (p : polynomial α) : p %ₘ X = C (p.eval 0) := by rw [← mod_by_monic_X_sub_C_eq_C_eval, C_0, sub_zero] section multiplicity def decidable_dvd_monic (p : polynomial α) (hq : monic q) : decidable (q ∣ p) := decidable_of_iff (p %ₘ q = 0) (dvd_iff_mod_by_monic_eq_zero hq) open_locale classical lemma multiplicity_X_sub_C_finite (a : α) (h0 : p ≠ 0) : multiplicity.finite (X - C a) p := multiplicity_finite_of_degree_pos_of_monic (have (0 : α) ≠ 1, from (λ h, by haveI := subsingleton_of_zero_eq_one _ h; exact h0 (subsingleton.elim _ _)), by letI : nonzero_comm_ring α := { zero_ne_one := this, ..show comm_ring α, by apply_instance }; rw degree_X_sub_C; exact dec_trivial) (monic_X_sub_C _) h0 def root_multiplicity (a : α) (p : polynomial α) : ℕ := if h0 : p = 0 then 0 else let I : decidable_pred (λ n : ℕ, ¬(X - C a) ^ (n + 1) ∣ p) := λ n, @not.decidable _ (decidable_dvd_monic p (monic_pow (monic_X_sub_C a) (n + 1))) in by exactI nat.find (multiplicity_X_sub_C_finite a h0) lemma root_multiplicity_eq_multiplicity (p : polynomial α) (a : α) : root_multiplicity a p = if h0 : p = 0 then 0 else (multiplicity (X - C a) p).get (multiplicity_X_sub_C_finite a h0) := by simp [multiplicity, root_multiplicity, roption.dom]; congr; funext; congr lemma pow_root_multiplicity_dvd (p : polynomial α) (a : α) : (X - C a) ^ root_multiplicity a p ∣ p := if h : p = 0 then by simp [h] else by rw [root_multiplicity_eq_multiplicity, dif_neg h]; exact multiplicity.pow_multiplicity_dvd _ lemma div_by_monic_mul_pow_root_multiplicity_eq (p : polynomial α) (a : α) : p /ₘ ((X - C a) ^ root_multiplicity a p) * (X - C a) ^ root_multiplicity a p = p := have monic ((X - C a) ^ root_multiplicity a p), from monic_pow (monic_X_sub_C _) _, by conv_rhs { rw [← mod_by_monic_add_div p this, (dvd_iff_mod_by_monic_eq_zero this).2 (pow_root_multiplicity_dvd _ _)] }; simp [mul_comm] lemma eval_div_by_monic_pow_root_multiplicity_ne_zero {p : polynomial α} (a : α) (hp : p ≠ 0) : (p /ₘ ((X - C a) ^ root_multiplicity a p)).eval a ≠ 0 := begin letI : nonzero_comm_ring α := nonzero_comm_ring.of_polynomial_ne hp, rw [ne.def, ← is_root.def, ← dvd_iff_is_root], rintros ⟨q, hq⟩, have := div_by_monic_mul_pow_root_multiplicity_eq p a, rw [mul_comm, hq, ← mul_assoc, ← pow_succ', root_multiplicity_eq_multiplicity, dif_neg hp] at this, exact multiplicity.is_greatest' (multiplicity_finite_of_degree_pos_of_monic (show (0 : with_bot ℕ) < degree (X - C a), by rw degree_X_sub_C; exact dec_trivial) _ hp) (nat.lt_succ_self _) (dvd_of_mul_right_eq _ this) end end multiplicity end comm_ring section integral_domain variables [integral_domain α] {p q : polynomial α} @[simp] lemma degree_mul_eq : degree (p * q) = degree p + degree q := if hp0 : p = 0 then by simp only [hp0, degree_zero, zero_mul, with_bot.bot_add] else if hq0 : q = 0 then by simp only [hq0, degree_zero, mul_zero, with_bot.add_bot] else degree_mul_eq' $ mul_ne_zero (mt leading_coeff_eq_zero.1 hp0) (mt leading_coeff_eq_zero.1 hq0) @[simp] lemma degree_pow_eq (p : polynomial α) (n : ℕ) : degree (p ^ n) = add_monoid.smul n (degree p) := by induction n; [simp only [pow_zero, degree_one, add_monoid.zero_smul], simp only [*, pow_succ, succ_smul, degree_mul_eq]] @[simp] lemma leading_coeff_mul (p q : polynomial α) : leading_coeff (p * q) = leading_coeff p * leading_coeff q := begin by_cases hp : p = 0, { simp only [hp, zero_mul, leading_coeff_zero] }, { by_cases hq : q = 0, { simp only [hq, mul_zero, leading_coeff_zero] }, { rw [leading_coeff_mul'], exact mul_ne_zero (mt leading_coeff_eq_zero.1 hp) (mt leading_coeff_eq_zero.1 hq) } } end @[simp] lemma leading_coeff_pow (p : polynomial α) (n : ℕ) : leading_coeff (p ^ n) = leading_coeff p ^ n := by induction n; [simp only [pow_zero, leading_coeff_one], simp only [*, pow_succ, leading_coeff_mul]] instance : integral_domain (polynomial α) := { eq_zero_or_eq_zero_of_mul_eq_zero := λ a b h, begin have : leading_coeff 0 = leading_coeff a * leading_coeff b := h ▸ leading_coeff_mul a b, rw [leading_coeff_zero, eq_comm] at this, erw [← leading_coeff_eq_zero, ← leading_coeff_eq_zero], exact eq_zero_or_eq_zero_of_mul_eq_zero this end, ..polynomial.nonzero_comm_ring } lemma nat_degree_mul_eq (hp : p ≠ 0) (hq : q ≠ 0) : nat_degree (p * q) = nat_degree p + nat_degree q := by rw [← with_bot.coe_eq_coe, ← degree_eq_nat_degree (mul_ne_zero hp hq), with_bot.coe_add, ← degree_eq_nat_degree hp, ← degree_eq_nat_degree hq, degree_mul_eq] @[simp] lemma nat_degree_pow_eq (p : polynomial α) (n : ℕ) : nat_degree (p ^ n) = n * nat_degree p := if hp0 : p = 0 then if hn0 : n = 0 then by simp [hp0, hn0] else by rw [hp0, zero_pow (nat.pos_of_ne_zero hn0)]; simp else nat_degree_pow_eq' (by rw [← leading_coeff_pow, ne.def, leading_coeff_eq_zero]; exact pow_ne_zero _ hp0) lemma root_or_root_of_root_mul (h : is_root (p * q) a) : is_root p a ∨ is_root q a := by rw [is_root, eval_mul] at h; exact eq_zero_or_eq_zero_of_mul_eq_zero h lemma degree_le_mul_left (p : polynomial α) (hq : q ≠ 0) : degree p ≤ degree (p * q) := if hp : p = 0 then by simp only [hp, zero_mul, le_refl] else by rw [degree_mul_eq, degree_eq_nat_degree hp, degree_eq_nat_degree hq]; exact with_bot.coe_le_coe.2 (nat.le_add_right _ _) lemma exists_finset_roots : ∀ {p : polynomial α} (hp : p ≠ 0), ∃ s : finset α, (s.card : with_bot ℕ) ≤ degree p ∧ ∀ x, x ∈ s ↔ is_root p x | p := λ hp, by haveI := classical.prop_decidable (∃ x, is_root p x); exact if h : ∃ x, is_root p x then let ⟨x, hx⟩ := h in have hpd : 0 < degree p := degree_pos_of_root hp hx, have hd0 : p /ₘ (X - C x) ≠ 0 := λ h, by rw [← mul_div_by_monic_eq_iff_is_root.2 hx, h, mul_zero] at hp; exact hp rfl, have wf : degree (p /ₘ _) < degree p := degree_div_by_monic_lt _ (monic_X_sub_C x) hp ((degree_X_sub_C x).symm ▸ dec_trivial), let ⟨t, htd, htr⟩ := @exists_finset_roots (p /ₘ (X - C x)) hd0 in have hdeg : degree (X - C x) ≤ degree p := begin rw [degree_X_sub_C, degree_eq_nat_degree hp], rw degree_eq_nat_degree hp at hpd, exact with_bot.coe_le_coe.2 (with_bot.coe_lt_coe.1 hpd) end, have hdiv0 : p /ₘ (X - C x) ≠ 0 := mt (div_by_monic_eq_zero_iff (monic_X_sub_C x) (ne_zero_of_monic (monic_X_sub_C x))).1 $ not_lt.2 hdeg, ⟨insert x t, calc (card (insert x t) : with_bot ℕ) ≤ card t + 1 : with_bot.coe_le_coe.2 $ finset.card_insert_le _ _ ... ≤ degree p : by rw [← degree_add_div_by_monic (monic_X_sub_C x) hdeg, degree_X_sub_C, add_comm]; exact add_le_add' (le_refl (1 : with_bot ℕ)) htd, begin assume y, rw [mem_insert, htr, eq_comm, ← root_X_sub_C], conv {to_rhs, rw ← mul_div_by_monic_eq_iff_is_root.2 hx}, exact ⟨λ h, or.cases_on h (root_mul_right_of_is_root _) (root_mul_left_of_is_root _), root_or_root_of_root_mul⟩ end⟩ else ⟨∅, (degree_eq_nat_degree hp).symm ▸ with_bot.coe_le_coe.2 (nat.zero_le _), by simpa only [not_mem_empty, false_iff, not_exists] using h⟩ using_well_founded {dec_tac := tactic.assumption} /-- `roots p` noncomputably gives a finset containing all the roots of `p` -/ noncomputable def roots (p : polynomial α) : finset α := if h : p = 0 then ∅ else classical.some (exists_finset_roots h) lemma card_roots (hp0 : p ≠ 0) : ((roots p).card : with_bot ℕ) ≤ degree p := begin unfold roots, rw dif_neg hp0, exact (classical.some_spec (exists_finset_roots hp0)).1 end lemma card_roots' {p : polynomial α} (hp0 : p ≠ 0) : p.roots.card ≤ nat_degree p := with_bot.coe_le_coe.1 (le_trans (card_roots hp0) (le_of_eq $ degree_eq_nat_degree hp0)) lemma card_roots_sub_C {p : polynomial α} {a : α} (hp0 : 0 < degree p) : ((p - C a).roots.card : with_bot ℕ) ≤ degree p := calc ((p - C a).roots.card : with_bot ℕ) ≤ degree (p - C a) : card_roots $ mt sub_eq_zero.1 $ λ h, not_le_of_gt hp0 $ h.symm ▸ degree_C_le ... = degree p : by rw [sub_eq_add_neg, ← C_neg]; exact degree_add_C hp0 lemma card_roots_sub_C' {p : polynomial α} {a : α} (hp0 : 0 < degree p) : (p - C a).roots.card ≤ nat_degree p := with_bot.coe_le_coe.1 (le_trans (card_roots_sub_C hp0) (le_of_eq $ degree_eq_nat_degree (λ h, by simp [*, lt_irrefl] at *))) @[simp] lemma mem_roots (hp : p ≠ 0) : a ∈ p.roots ↔ is_root p a := by unfold roots; rw dif_neg hp; exact (classical.some_spec (exists_finset_roots hp)).2 _ @[simp] lemma mem_roots_sub_C {p : polynomial α} {a x : α} (hp0 : 0 < degree p) : x ∈ (p - C a).roots ↔ p.eval x = a := (mem_roots (show p - C a ≠ 0, from mt sub_eq_zero.1 $ λ h, not_le_of_gt hp0 $ h.symm ▸ degree_C_le)).trans (by rw [is_root.def, eval_sub, eval_C, sub_eq_zero]) lemma card_roots_X_pow_sub_C {n : ℕ} (hn : 0 < n) (a : α) : (roots ((X : polynomial α) ^ n - C a)).card ≤ n := with_bot.coe_le_coe.1 $ calc ((roots ((X : polynomial α) ^ n - C a)).card : with_bot ℕ) ≤ degree ((X : polynomial α) ^ n - C a) : card_roots (X_pow_sub_C_ne_zero hn a) ... = n : degree_X_pow_sub_C hn a /-- `nth_roots n a` noncomputably returns the solutions to `x ^ n = a`-/ def nth_roots {α : Type*} [integral_domain α] (n : ℕ) (a : α) : finset α := roots ((X : polynomial α) ^ n - C a) @[simp] lemma mem_nth_roots {α : Type*} [integral_domain α] {n : ℕ} (hn : 0 < n) {a x : α} : x ∈ nth_roots n a ↔ x ^ n = a := by rw [nth_roots, mem_roots (X_pow_sub_C_ne_zero hn a), is_root.def, eval_sub, eval_C, eval_pow, eval_X, sub_eq_zero_iff_eq] lemma card_nth_roots {α : Type*} [integral_domain α] (n : ℕ) (a : α) : (nth_roots n a).card ≤ n := if hn : n = 0 then if h : (X : polynomial α) ^ n - C a = 0 then by simp only [nat.zero_le, nth_roots, roots, h, dif_pos rfl, card_empty] else with_bot.coe_le_coe.1 (le_trans (card_roots h) (by rw [hn, pow_zero, ← C_1, ← @is_ring_hom.map_sub _ _ _ _ (@C α _)]; exact degree_C_le)) else by rw [← with_bot.coe_le_coe, ← degree_X_pow_sub_C (nat.pos_of_ne_zero hn) a]; exact card_roots (X_pow_sub_C_ne_zero (nat.pos_of_ne_zero hn) a) lemma coeff_comp_degree_mul_degree (hqd0 : nat_degree q ≠ 0) : coeff (p.comp q) (nat_degree p * nat_degree q) = leading_coeff p * leading_coeff q ^ nat_degree p := if hp0 : p = 0 then by simp [hp0] else calc coeff (p.comp q) (nat_degree p * nat_degree q) = p.sum (λ n a, coeff (C a * q ^ n) (nat_degree p * nat_degree q)) : by rw [comp, eval₂, coeff_sum] ... = coeff (C (leading_coeff p) * q ^ nat_degree p) (nat_degree p * nat_degree q) : finset.sum_eq_single _ begin assume b hbs hbp, have hq0 : q ≠ 0, from λ hq0, hqd0 (by rw [hq0, nat_degree_zero]), have : coeff p b ≠ 0, rwa [← apply_eq_coeff, ← finsupp.mem_support_iff], dsimp [apply_eq_coeff], refine coeff_eq_zero_of_degree_lt _, rw [degree_mul_eq, degree_C this, degree_pow_eq, zero_add, degree_eq_nat_degree hq0, ← with_bot.coe_smul, add_monoid.smul_eq_mul, with_bot.coe_lt_coe, nat.cast_id], exact (mul_lt_mul_right (nat.pos_of_ne_zero hqd0)).2 (lt_of_le_of_ne (with_bot.coe_le_coe.1 (by rw ← degree_eq_nat_degree hp0; exact le_sup hbs)) hbp) end (by rw [finsupp.mem_support_iff, apply_eq_coeff, ← leading_coeff, ne.def, leading_coeff_eq_zero, classical.not_not]; simp {contextual := tt}) ... = _ : have coeff (q ^ nat_degree p) (nat_degree p * nat_degree q) = leading_coeff (q ^ nat_degree p), by rw [leading_coeff, nat_degree_pow_eq], by rw [coeff_C_mul, this, leading_coeff_pow] lemma nat_degree_comp : nat_degree (p.comp q) = nat_degree p * nat_degree q := le_antisymm nat_degree_comp_le (if hp0 : p = 0 then by rw [hp0, zero_comp, nat_degree_zero, zero_mul] else if hqd0 : nat_degree q = 0 then have degree q ≤ 0, by rw [← with_bot.coe_zero, ← hqd0]; exact degree_le_nat_degree, by rw [eq_C_of_degree_le_zero this]; simp else le_nat_degree_of_ne_zero $ have hq0 : q ≠ 0, from λ hq0, hqd0 $ by rw [hq0, nat_degree_zero], calc coeff (p.comp q) (nat_degree p * nat_degree q) = leading_coeff p * leading_coeff q ^ nat_degree p : coeff_comp_degree_mul_degree hqd0 ... ≠ 0 : mul_ne_zero (mt leading_coeff_eq_zero.1 hp0) (pow_ne_zero _ (mt leading_coeff_eq_zero.1 hq0))) lemma leading_coeff_comp (hq : nat_degree q ≠ 0) : leading_coeff (p.comp q) = leading_coeff p * leading_coeff q ^ nat_degree p := by rw [← coeff_comp_degree_mul_degree hq, ← nat_degree_comp]; refl lemma degree_eq_zero_of_is_unit (h : is_unit p) : degree p = 0 := let ⟨q, hq⟩ := is_unit_iff_dvd_one.1 h in have hp0 : p ≠ 0, from λ hp0, by simpa [hp0] using hq, have hq0 : q ≠ 0, from λ hp0, by simpa [hp0] using hq, have nat_degree (1 : polynomial α) = nat_degree (p * q), from congr_arg _ hq, by rw [nat_degree_one, nat_degree_mul_eq hp0 hq0, eq_comm, _root_.add_eq_zero_iff, ← with_bot.coe_eq_coe, ← degree_eq_nat_degree hp0] at this; exact this.1 @[simp] lemma degree_coe_units (u : units (polynomial α)) : degree (u : polynomial α) = 0 := degree_eq_zero_of_is_unit ⟨u, rfl⟩ @[simp] lemma nat_degree_coe_units (u : units (polynomial α)) : nat_degree (u : polynomial α) = 0 := nat_degree_eq_of_degree_eq_some (degree_coe_units u) lemma coeff_coe_units_zero_ne_zero (u : units (polynomial α)) : coeff (u : polynomial α) 0 ≠ 0 := begin conv in (0) {rw [← nat_degree_coe_units u]}, rw [← leading_coeff, ne.def, leading_coeff_eq_zero], exact units.coe_ne_zero _ end lemma degree_eq_degree_of_associated (h : associated p q) : degree p = degree q := let ⟨u, hu⟩ := h in by simp [hu.symm] lemma degree_eq_one_of_irreducible_of_root (hi : irreducible p) {x : α} (hx : is_root p x) : degree p = 1 := let ⟨g, hg⟩ := dvd_iff_is_root.2 hx in have is_unit (X - C x) ∨ is_unit g, from hi.2 _ _ hg, this.elim (λ h, have h₁ : degree (X - C x) = 1, from degree_X_sub_C x, have h₂ : degree (X - C x) = 0, from degree_eq_zero_of_is_unit h, by rw h₁ at h₂; exact absurd h₂ dec_trivial) (λ hgu, by rw [hg, degree_mul_eq, degree_X_sub_C, degree_eq_zero_of_is_unit hgu, add_zero]) end integral_domain section field variables [field α] {p q : polynomial α} instance : vector_space α (polynomial α) := finsupp.vector_space _ _ lemma is_unit_iff_degree_eq_zero : is_unit p ↔ degree p = 0 := ⟨degree_eq_zero_of_is_unit, λ h, have degree p ≤ 0, by simp [*, le_refl], have hc : coeff p 0 ≠ 0, from λ hc, by rw [eq_C_of_degree_le_zero this, hc] at h; simpa using h, is_unit_iff_dvd_one.2 ⟨C (coeff p 0)⁻¹, begin conv in p { rw eq_C_of_degree_le_zero this }, rw [← C_mul, _root_.mul_inv_cancel hc, C_1] end⟩⟩ lemma degree_pos_of_ne_zero_of_nonunit (hp0 : p ≠ 0) (hp : ¬is_unit p) : 0 < degree p := lt_of_not_ge (λ h, by rw [eq_C_of_degree_le_zero h] at hp0 hp; exact (hp $ is_unit.map' C $ is_unit.mk0 (coeff p 0) (mt C_inj.2 (by simpa using hp0)))) lemma irreducible_of_degree_eq_one (hp1 : degree p = 1) : irreducible p := ⟨mt is_unit_iff_dvd_one.1 (λ ⟨q, hq⟩, absurd (congr_arg degree hq) (λ h, have degree q = 0, by rw [degree_one, degree_mul_eq, hp1, eq_comm, nat.with_bot.add_eq_zero_iff] at h; exact h.2, by simp [degree_mul_eq, this, degree_one, hp1] at h; exact absurd h dec_trivial)), λ q r hpqr, begin have := congr_arg degree hpqr, rw [hp1, degree_mul_eq, eq_comm, nat.with_bot.add_eq_one_iff] at this, rw [is_unit_iff_degree_eq_zero, is_unit_iff_degree_eq_zero]; tautology end⟩ lemma monic_mul_leading_coeff_inv (h : p ≠ 0) : monic (p * C (leading_coeff p)⁻¹) := by rw [monic, leading_coeff_mul, leading_coeff_C, mul_inv_cancel (show leading_coeff p ≠ 0, from mt leading_coeff_eq_zero.1 h)] lemma degree_mul_leading_coeff_inv (p : polynomial α) (h : q ≠ 0) : degree (p * C (leading_coeff q)⁻¹) = degree p := have h₁ : (leading_coeff q)⁻¹ ≠ 0 := inv_ne_zero (mt leading_coeff_eq_zero.1 h), by rw [degree_mul_eq, degree_C h₁, add_zero] def div (p q : polynomial α) := C (leading_coeff q)⁻¹ * (p /ₘ (q * C (leading_coeff q)⁻¹)) def mod (p q : polynomial α) := p %ₘ (q * C (leading_coeff q)⁻¹) private lemma quotient_mul_add_remainder_eq_aux (p q : polynomial α) : q * div p q + mod p q = p := if h : q = 0 then by simp only [h, zero_mul, mod, mod_by_monic_zero, zero_add] else begin conv {to_rhs, rw ← mod_by_monic_add_div p (monic_mul_leading_coeff_inv h)}, rw [div, mod, add_comm, mul_assoc] end private lemma remainder_lt_aux (p : polynomial α) (hq : q ≠ 0) : degree (mod p q) < degree q := by rw ← degree_mul_leading_coeff_inv q hq; exact degree_mod_by_monic_lt p (monic_mul_leading_coeff_inv hq) (mul_ne_zero hq (mt leading_coeff_eq_zero.2 (by rw leading_coeff_C; exact inv_ne_zero (mt leading_coeff_eq_zero.1 hq)))) instance : has_div (polynomial α) := ⟨div⟩ instance : has_mod (polynomial α) := ⟨mod⟩ lemma div_def : p / q = C (leading_coeff q)⁻¹ * (p /ₘ (q * C (leading_coeff q)⁻¹)) := rfl lemma mod_def : p % q = p %ₘ (q * C (leading_coeff q)⁻¹) := rfl lemma mod_by_monic_eq_mod (p : polynomial α) (hq : monic q) : p %ₘ q = p % q := show p %ₘ q = p %ₘ (q * C (leading_coeff q)⁻¹), by simp only [monic.def.1 hq, inv_one, mul_one, C_1] lemma div_by_monic_eq_div (p : polynomial α) (hq : monic q) : p /ₘ q = p / q := show p /ₘ q = C (leading_coeff q)⁻¹ * (p /ₘ (q * C (leading_coeff q)⁻¹)), by simp only [monic.def.1 hq, inv_one, C_1, one_mul, mul_one] lemma mod_X_sub_C_eq_C_eval (p : polynomial α) (a : α) : p % (X - C a) = C (p.eval a) := mod_by_monic_eq_mod p (monic_X_sub_C a) ▸ mod_by_monic_X_sub_C_eq_C_eval _ _ lemma mul_div_eq_iff_is_root : (X - C a) * (p / (X - C a)) = p ↔ is_root p a := div_by_monic_eq_div p (monic_X_sub_C a) ▸ mul_div_by_monic_eq_iff_is_root instance : euclidean_domain (polynomial α) := { quotient := (/), quotient_zero := by simp [div_def], remainder := (%), r := _, r_well_founded := degree_lt_wf, quotient_mul_add_remainder_eq := quotient_mul_add_remainder_eq_aux, remainder_lt := λ p q hq, remainder_lt_aux _ hq, mul_left_not_lt := λ p q hq, not_lt_of_ge (degree_le_mul_left _ hq) } lemma mod_eq_self_iff (hq0 : q ≠ 0) : p % q = p ↔ degree p < degree q := ⟨λ h, h ▸ euclidean_domain.mod_lt _ hq0, λ h, have ¬degree (q * C (leading_coeff q)⁻¹) ≤ degree p := not_le_of_gt $ by rwa degree_mul_leading_coeff_inv q hq0, begin rw [mod_def, mod_by_monic, dif_pos (monic_mul_leading_coeff_inv hq0)], unfold div_mod_by_monic_aux, simp only [this, false_and, if_false] end⟩ lemma div_eq_zero_iff (hq0 : q ≠ 0) : p / q = 0 ↔ degree p < degree q := ⟨λ h, by have := euclidean_domain.div_add_mod p q; rwa [h, mul_zero, zero_add, mod_eq_self_iff hq0] at this, λ h, have hlt : degree p < degree (q * C (leading_coeff q)⁻¹), by rwa degree_mul_leading_coeff_inv q hq0, have hm : monic (q * C (leading_coeff q)⁻¹) := monic_mul_leading_coeff_inv hq0, by rw [div_def, (div_by_monic_eq_zero_iff hm (ne_zero_of_monic hm)).2 hlt, mul_zero]⟩ lemma degree_add_div (hq0 : q ≠ 0) (hpq : degree q ≤ degree p) : degree q + degree (p / q) = degree p := have degree (p % q) < degree (q * (p / q)) := calc degree (p % q) < degree q : euclidean_domain.mod_lt _ hq0 ... ≤ _ : degree_le_mul_left _ (mt (div_eq_zero_iff hq0).1 (not_lt_of_ge hpq)), by conv {to_rhs, rw [← euclidean_domain.div_add_mod p q, add_comm, degree_add_eq_of_degree_lt this, degree_mul_eq]} lemma degree_div_le (p q : polynomial α) : degree (p / q) ≤ degree p := if hq : q = 0 then by simp [hq] else by rw [div_def, mul_comm, degree_mul_leading_coeff_inv _ hq]; exact degree_div_by_monic_le _ _ lemma degree_div_lt (hp : p ≠ 0) (hq : 0 < degree q) : degree (p / q) < degree p := have hq0 : q ≠ 0, from λ hq0, by simpa [hq0] using hq, by rw [div_def, mul_comm, degree_mul_leading_coeff_inv _ hq0]; exact degree_div_by_monic_lt _ (monic_mul_leading_coeff_inv hq0) hp (by rw degree_mul_leading_coeff_inv _ hq0; exact hq) @[simp] lemma degree_map [field β] (p : polynomial α) (f : α →+* β) : degree (p.map f) = degree p := p.degree_map_eq_of_injective (is_ring_hom.injective f) @[simp] lemma nat_degree_map [field β] (f : α →+* β) : nat_degree (p.map f) = nat_degree p := nat_degree_eq_of_degree_eq (degree_map _ f) @[simp] lemma leading_coeff_map [field β] (f : α →+* β) : leading_coeff (p.map f) = f (leading_coeff p) := by simp [leading_coeff, coeff_map f] lemma map_div [field β] (f : α →+* β) : (p / q).map f = p.map f / q.map f := if hq0 : q = 0 then by simp [hq0] else by rw [div_def, div_def, map_mul, map_div_by_monic f (monic_mul_leading_coeff_inv hq0)]; simp [is_ring_hom.map_inv f, leading_coeff, coeff_map f] lemma map_mod [field β] (f : α →+* β) : (p % q).map f = p.map f % q.map f := if hq0 : q = 0 then by simp [hq0] else by rw [mod_def, mod_def, leading_coeff_map f, ← is_ring_hom.map_inv f, ← map_C f, ← map_mul f, map_mod_by_monic f (monic_mul_leading_coeff_inv hq0)] @[simp] lemma map_eq_zero [field β] (f : α →+* β) : p.map f = 0 ↔ p = 0 := by simp [polynomial.ext_iff, is_ring_hom.map_eq_zero f, coeff_map] lemma exists_root_of_degree_eq_one (h : degree p = 1) : ∃ x, is_root p x := ⟨-(p.coeff 0 / p.coeff 1), have p.coeff 1 ≠ 0, by rw ← nat_degree_eq_of_degree_eq_some h; exact mt leading_coeff_eq_zero.1 (λ h0, by simpa [h0] using h), by conv in p { rw [eq_X_add_C_of_degree_le_one (show degree p ≤ 1, by rw h; exact le_refl _)] }; simp [is_root, mul_div_cancel' _ this]⟩ lemma coeff_inv_units (u : units (polynomial α)) (n : ℕ) : ((↑u : polynomial α).coeff n)⁻¹ = ((↑u⁻¹ : polynomial α).coeff n) := begin rw [eq_C_of_degree_eq_zero (degree_coe_units u), eq_C_of_degree_eq_zero (degree_coe_units u⁻¹), coeff_C, coeff_C, inv_eq_one_div], split_ifs, { rw [div_eq_iff_mul_eq (coeff_coe_units_zero_ne_zero u), coeff_zero_eq_eval_zero, coeff_zero_eq_eval_zero, ← eval_mul, ← units.coe_mul, inv_mul_self]; simp }, { simp } end instance : normalization_domain (polynomial α) := { norm_unit := λ p, if hp0 : p = 0 then 1 else ⟨C p.leading_coeff⁻¹, C p.leading_coeff, by rw [← C_mul, inv_mul_cancel, C_1]; exact mt leading_coeff_eq_zero.1 hp0, by rw [← C_mul, mul_inv_cancel, C_1]; exact mt leading_coeff_eq_zero.1 hp0,⟩, norm_unit_zero := dif_pos rfl, norm_unit_mul := λ p q hp0 hq0, begin rw [dif_neg hp0, dif_neg hq0, dif_neg (mul_ne_zero hp0 hq0)], apply units.ext, show C (leading_coeff (p * q))⁻¹ = C (leading_coeff p)⁻¹ * C (leading_coeff q)⁻¹, rw [leading_coeff_mul, mul_inv', C_mul, mul_comm] end, norm_unit_coe_units := λ u, have hu : degree ↑u⁻¹ = 0, from degree_eq_zero_of_is_unit ⟨u⁻¹, rfl⟩, begin apply units.ext, rw [dif_neg (units.coe_ne_zero u)], conv_rhs {rw eq_C_of_degree_eq_zero hu}, refine C_inj.2 _, rw [← nat_degree_eq_of_degree_eq_some hu, leading_coeff, coeff_inv_units], simp end, ..polynomial.integral_domain } lemma monic_normalize (hp0 : p ≠ 0) : monic (normalize p) := show leading_coeff (p * ↑(dite _ _ _)) = 1, by rw dif_neg hp0; exact monic_mul_leading_coeff_inv hp0 lemma coe_norm_unit (hp : p ≠ 0) : (norm_unit p : polynomial α) = C p.leading_coeff⁻¹ := show ↑(dite _ _ _) = C p.leading_coeff⁻¹, by rw dif_neg hp; refl end field section derivative variables [comm_semiring α] /-- `derivative p` formal derivative of the polynomial `p` -/ def derivative (p : polynomial α) : polynomial α := p.sum (λn a, C (a * n) * X^(n - 1)) lemma coeff_derivative (p : polynomial α) (n : ℕ) : coeff (derivative p) n = coeff p (n + 1) * (n + 1) := begin rw [derivative], simp only [coeff_X_pow, coeff_sum, coeff_C_mul], rw [finsupp.sum, finset.sum_eq_single (n + 1), apply_eq_coeff], { rw [if_pos (nat.add_sub_cancel _ _).symm, mul_one, nat.cast_add, nat.cast_one] }, { assume b, cases b, { intros, rw [nat.cast_zero, mul_zero, zero_mul] }, { intros _ H, rw [nat.succ_sub_one b, if_neg (mt (congr_arg nat.succ) H.symm), mul_zero] } }, { intro H, rw [not_mem_support_iff.1 H, zero_mul, zero_mul] } end @[simp] lemma derivative_zero : derivative (0 : polynomial α) = 0 := finsupp.sum_zero_index lemma derivative_monomial (a : α) (n : ℕ) : derivative (C a * X ^ n) = C (a * n) * X^(n - 1) := by rw [← single_eq_C_mul_X, ← single_eq_C_mul_X, derivative, sum_single_index, single_eq_C_mul_X]; simp only [zero_mul, C_0]; refl @[simp] lemma derivative_C {a : α} : derivative (C a) = 0 := suffices derivative (C a * X^0) = C (a * 0:α) * X ^ 0, by simpa only [mul_one, zero_mul, C_0, mul_zero, pow_zero], derivative_monomial a 0 @[simp] lemma derivative_X : derivative (X : polynomial α) = 1 := suffices derivative (C (1:α) * X^1) = C (1 * (1:ℕ)) * X ^ 0, by simpa only [mul_one, one_mul, C_1, pow_one, nat.cast_one, pow_zero], derivative_monomial 1 1 @[simp] lemma derivative_one : derivative (1 : polynomial α) = 0 := derivative_C @[simp] lemma derivative_add {f g : polynomial α} : derivative (f + g) = derivative f + derivative g := by refine finsupp.sum_add_index _ _; intros; simp only [add_mul, zero_mul, C_0, C_add, C_mul] instance : is_add_monoid_hom (derivative : polynomial α → polynomial α) := { map_add := λ _ _, derivative_add, map_zero := derivative_zero } @[simp] lemma derivative_sum {s : finset β} {f : β → polynomial α} : derivative (s.sum f) = s.sum (λb, derivative (f b)) := (s.sum_hom derivative).symm @[simp] lemma derivative_mul {f g : polynomial α} : derivative (f * g) = derivative f * g + f * derivative g := calc derivative (f * g) = f.sum (λn a, g.sum (λm b, C ((a * b) * (n + m : ℕ)) * X^((n + m) - 1))) : begin transitivity, exact derivative_sum, transitivity, { apply finset.sum_congr rfl, assume x hx, exact derivative_sum }, apply finset.sum_congr rfl, assume n hn, apply finset.sum_congr rfl, assume m hm, transitivity, { apply congr_arg, exact single_eq_C_mul_X }, exact derivative_monomial _ _ end ... = f.sum (λn a, g.sum (λm b, (C (a * n) * X^(n - 1)) * (C b * X^m) + (C a * X^n) * (C (b * m) * X^(m - 1)))) : sum_congr rfl $ assume n hn, sum_congr rfl $ assume m hm, by simp only [nat.cast_add, mul_add, add_mul, C_add, C_mul]; cases n; simp only [nat.succ_sub_succ, pow_zero]; cases m; simp only [nat.cast_zero, C_0, nat.succ_sub_succ, zero_mul, mul_zero, nat.sub_zero, pow_zero, pow_add, one_mul, pow_succ, mul_comm, mul_left_comm] ... = derivative f * g + f * derivative g : begin conv { to_rhs, congr, { rw [← sum_C_mul_X_eq g] }, { rw [← sum_C_mul_X_eq f] } }, unfold derivative finsupp.sum, simp only [sum_add_distrib, finset.mul_sum, finset.sum_mul] end lemma derivative_eval (p : polynomial α) (x : α) : p.derivative.eval x = p.sum (λ n a, (a * n)*x^(n-1)) := by simp [derivative, eval_sum, eval_pow] end derivative section domain variables [integral_domain α] lemma mem_support_derivative [char_zero α] (p : polynomial α) (n : ℕ) : n ∈ (derivative p).support ↔ n + 1 ∈ p.support := suffices (¬(coeff p (n + 1) = 0 ∨ ((n + 1:ℕ) : α) = 0)) ↔ coeff p (n + 1) ≠ 0, by simpa only [coeff_derivative, apply_eq_coeff, mem_support_iff, ne.def, mul_eq_zero], by rw [nat.cast_eq_zero]; simp only [nat.succ_ne_zero, or_false] @[simp] lemma degree_derivative_eq [char_zero α] (p : polynomial α) (hp : 0 < nat_degree p) : degree (derivative p) = (nat_degree p - 1 : ℕ) := le_antisymm (le_trans (degree_sum_le _ _) $ sup_le $ assume n hn, have n ≤ nat_degree p, begin rw [← with_bot.coe_le_coe, ← degree_eq_nat_degree], { refine le_degree_of_ne_zero _, simpa only [mem_support_iff] using hn }, { assume h, simpa only [h, support_zero] using hn } end, le_trans (degree_monomial_le _ _) $ with_bot.coe_le_coe.2 $ nat.sub_le_sub_right this _) begin refine le_sup _, rw [mem_support_derivative, nat.sub_add_cancel, mem_support_iff], { show ¬ leading_coeff p = 0, rw [leading_coeff_eq_zero], assume h, rw [h, nat_degree_zero] at hp, exact lt_irrefl 0 (lt_of_le_of_lt (zero_le _) hp), }, exact hp end end domain section identities /- @TODO: pow_add_expansion and pow_sub_pow_factor are not specific to polynomials. These belong somewhere else. But not in group_power because they depend on tactic.ring Maybe use data.nat.choose to prove it. -/ def pow_add_expansion {α : Type*} [comm_semiring α] (x y : α) : ∀ (n : ℕ), {k // (x + y)^n = x^n + n*x^(n-1)*y + k * y^2} | 0 := ⟨0, by simp⟩ | 1 := ⟨0, by simp⟩ | (n+2) := begin cases pow_add_expansion (n+1) with z hz, existsi x*z + (n+1)*x^n+z*y, calc (x + y) ^ (n + 2) = (x + y) * (x + y) ^ (n + 1) : by ring_exp ... = (x + y) * (x ^ (n + 1) + ↑(n + 1) * x ^ (n + 1 - 1) * y + z * y ^ 2) : by rw hz ... = x ^ (n + 2) + ↑(n + 2) * x ^ (n + 1) * y + (x*z + (n+1)*x^n+z*y) * y ^ 2 : by { push_cast, ring_exp! } end variables [comm_ring α] private def poly_binom_aux1 (x y : α) (e : ℕ) (a : α) : {k : α // a * (x + y)^e = a * (x^e + e*x^(e-1)*y + k*y^2)} := begin existsi (pow_add_expansion x y e).val, congr, apply (pow_add_expansion _ _ _).property end private lemma poly_binom_aux2 (f : polynomial α) (x y : α) : f.eval (x + y) = f.sum (λ e a, a * (x^e + e*x^(e-1)*y + (poly_binom_aux1 x y e a).val*y^2)) := begin unfold eval eval₂, congr, ext, apply (poly_binom_aux1 x y _ _).property end private lemma poly_binom_aux3 (f : polynomial α) (x y : α) : f.eval (x + y) = f.sum (λ e a, a * x^e) + f.sum (λ e a, (a * e * x^(e-1)) * y) + f.sum (λ e a, (a *(poly_binom_aux1 x y e a).val)*y^2) := by rw poly_binom_aux2; simp [left_distrib, finsupp.sum_add, mul_assoc] def binom_expansion (f : polynomial α) (x y : α) : {k : α // f.eval (x + y) = f.eval x + (f.derivative.eval x) * y + k * y^2} := begin existsi f.sum (λ e a, a *((poly_binom_aux1 x y e a).val)), rw poly_binom_aux3, congr, { rw derivative_eval, symmetry, apply finsupp.sum_mul }, { symmetry, apply finsupp.sum_mul } end def pow_sub_pow_factor (x y : α) : Π {i : ℕ},{z : α // x^i - y^i = z*(x - y)} | 0 := ⟨0, by simp⟩ | 1 := ⟨1, by simp⟩ | (k+2) := begin cases @pow_sub_pow_factor (k+1) with z hz, existsi z*x + y^(k+1), calc x ^ (k + 2) - y ^ (k + 2) = x * (x ^ (k + 1) - y ^ (k + 1)) + (x * y ^ (k + 1) - y ^ (k + 2)) : by ring_exp ... = x * (z * (x - y)) + (x * y ^ (k + 1) - y ^ (k + 2)) : by rw hz ... = (z * x + y ^ (k + 1)) * (x - y) : by ring_exp end def eval_sub_factor (f : polynomial α) (x y : α) : {z : α // f.eval x - f.eval y = z*(x - y)} := begin existsi f.sum (λ a b, b * (pow_sub_pow_factor x y).val), unfold eval eval₂, rw [←finsupp.sum_sub], have : finsupp.sum f (λ (a : ℕ) (b : α), b * (pow_sub_pow_factor x y).val) * (x - y) = finsupp.sum f (λ (a : ℕ) (b : α), b * (pow_sub_pow_factor x y).val * (x - y)), { apply finsupp.sum_mul }, rw this, congr, ext e a, rw [mul_assoc, ←(pow_sub_pow_factor x y).property], simp [mul_sub] end end identities end polynomial namespace is_integral_domain variables {α : Type*} [comm_ring α] /-- Lift evidence that `is_integral_domain α` to `is_integral_domain (polynomial α)`. -/ lemma polynomial (h : is_integral_domain α) : is_integral_domain (polynomial α) := @integral_domain.to_is_integral_domain _ (@polynomial.integral_domain _ (h.to_integral_domain _)) end is_integral_domain
53ce8e5203a9eb98827960eb89e1258cf7f8a968
968e2f50b755d3048175f176376eff7139e9df70
/examples/pred_logic/unnamed_196.lean
f3c3f138705b7d79ab21f626a13d1ac20d0f415b
[]
no_license
gihanmarasingha/mth1001_sphinx
190a003269ba5e54717b448302a27ca26e31d491
05126586cbf5786e521be1ea2ef5b4ba3c44e74a
refs/heads/master
1,672,913,933,677
1,604,516,583,000
1,604,516,583,000
309,245,750
1
0
null
null
null
null
UTF-8
Lean
false
false
92
lean
def even (x : ℤ) : Prop := ∃ m : ℤ, x = 2 *m -- BEGIN #check even #check even 5 -- END
b9df4da5d7b804e729207b6dd05854f514ed302c
5412d79aa1dc0b521605c38bef9f0d4557b5a29d
/stage0/src/Lean/MonadEnv.lean
1fbfb87a84079e834e4961684e956d0740b9b208
[ "Apache-2.0" ]
permissive
smunix/lean4
a450ec0927dc1c74816a1bf2818bf8600c9fc9bf
3407202436c141e3243eafbecb4b8720599b970a
refs/heads/master
1,676,334,875,188
1,610,128,510,000
1,610,128,521,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,821
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.Environment import Lean.Exception namespace Lean def setEnv [MonadEnv m] (env : Environment) : m Unit := modifyEnv fun _ => env def isInductive [Monad m] [MonadEnv m] (declName : Name) : m Bool := do match (← getEnv).find? declName with | some (ConstantInfo.inductInfo ..) => return true | _ => return false @[inline] def withoutModifyingEnv [Monad m] [MonadEnv m] [MonadFinally m] {α : Type} (x : m α) : m α := do let env ← getEnv try x finally setEnv env @[inline] def matchConst [Monad m] [MonadEnv m] (e : Expr) (failK : Unit → m α) (k : ConstantInfo → List Level → m α) : m α := do match e with | Expr.const constName us _ => do match (← getEnv).find? constName with | some cinfo => k cinfo us | none => failK () | _ => failK () @[inline] def matchConstInduct [Monad m] [MonadEnv m] (e : Expr) (failK : Unit → m α) (k : InductiveVal → List Level → m α) : m α := matchConst e failK fun cinfo us => match cinfo with | ConstantInfo.inductInfo val => k val us | _ => failK () @[inline] def matchConstCtor [Monad m] [MonadEnv m] (e : Expr) (failK : Unit → m α) (k : ConstructorVal → List Level → m α) : m α := matchConst e failK fun cinfo us => match cinfo with | ConstantInfo.ctorInfo val => k val us | _ => failK () @[inline] def matchConstRec [Monad m] [MonadEnv m] (e : Expr) (failK : Unit → m α) (k : RecursorVal → List Level → m α) : m α := matchConst e failK fun cinfo us => match cinfo with | ConstantInfo.recInfo val => k val us | _ => failK () def hasConst [Monad m] [MonadEnv m] (constName : Name) : m Bool := do return (← getEnv).contains constName private partial def mkAuxNameAux (env : Environment) (base : Name) (i : Nat) : Name := let candidate := base.appendIndexAfter i if env.contains candidate then mkAuxNameAux env base (i+1) else candidate def mkAuxName [Monad m] [MonadEnv m] (baseName : Name) (idx : Nat) : m Name := do return mkAuxNameAux (← getEnv) baseName idx def getConstInfo [Monad m] [MonadEnv m] [MonadError m] (constName : Name) : m ConstantInfo := do match (← getEnv).find? constName with | some info => pure info | none => throwError! "unknown constant '{mkConst constName}'" def getConstInfoInduct [Monad m] [MonadEnv m] [MonadError m] (constName : Name) : m InductiveVal := do match (← getConstInfo constName) with | ConstantInfo.inductInfo v => pure v | _ => throwError! "'{mkConst constName}' is not a inductive type" def getConstInfoCtor [Monad m] [MonadEnv m] [MonadError m] (constName : Name) : m ConstructorVal := do match (← getConstInfo constName) with | ConstantInfo.ctorInfo v => pure v | _ => throwError! "'{mkConst constName}' is not a constructor" def getConstInfoRec [Monad m] [MonadEnv m] [MonadError m] (constName : Name) : m RecursorVal := do match (← getConstInfo constName) with | ConstantInfo.recInfo v => pure v | _ => throwError! "'{mkConst constName}' is not a recursor" @[inline] def matchConstStruct [Monad m] [MonadEnv m] [MonadError m] (e : Expr) (failK : Unit → m α) (k : InductiveVal → List Level → ConstructorVal → m α) : m α := matchConstInduct e failK fun ival us => do if ival.isRec then failK () else match ival.ctors with | [ctor] => match (← getConstInfo ctor) with | ConstantInfo.ctorInfo cval => k ival us cval | _ => failK () | _ => failK () def addDecl [Monad m] [MonadEnv m] [MonadError m] [MonadOptions m] (decl : Declaration) : m Unit := do match (← getEnv).addDecl decl with | Except.ok env => setEnv env | Except.error ex => throwKernelException ex def compileDecl [Monad m] [MonadEnv m] [MonadError m] [MonadOptions m] (decl : Declaration) : m Unit := do match (← getEnv).compileDecl (← getOptions) decl with | Except.ok env => setEnv env | Except.error ex => throwKernelException ex def addAndCompile [Monad m] [MonadEnv m] [MonadError m] [MonadOptions m] (decl : Declaration) : m Unit := do addDecl decl; compileDecl decl unsafe def evalConst [Monad m] [MonadEnv m] [MonadError m] [MonadOptions m] (α) (constName : Name) : m α := do ofExcept <| (← getEnv).evalConst α (← getOptions) constName unsafe def evalConstCheck [Monad m] [MonadEnv m] [MonadError m] [MonadOptions m] (α) (typeName : Name) (constName : Name) : m α := do ofExcept <| (← getEnv).evalConstCheck α (← getOptions) typeName constName end Lean
34762d02fd96d1a347973e6905fe2d3e1ace519f
a7eef317ddec01b9fc6cfbb876fe7ac00f205ac7
/src/data/matrix/basic.lean
68c1f6134430ea637f6f3bdaa03fa20e34562617
[ "Apache-2.0" ]
permissive
kmill/mathlib
ea5a007b67ae4e9e18dd50d31d8aa60f650425ee
1a419a9fea7b959317eddd556e1bb9639f4dcc05
refs/heads/master
1,668,578,197,719
1,593,629,163,000
1,593,629,163,000
276,482,939
0
0
null
1,593,637,960,000
1,593,637,959,000
null
UTF-8
Lean
false
false
23,828
lean
/- Copyright (c) 2018 Ellen Arlt. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Ellen Arlt, Blair Shi, Sean Leather, Mario Carneiro, Johan Commelin -/ import algebra.pi_instances /-! # Matrices -/ universes u v w open_locale big_operators @[nolint unused_arguments] def matrix (m n : Type u) [fintype m] [fintype n] (α : Type v) : Type (max u v) := m → n → α namespace matrix variables {l m n o : Type u} [fintype l] [fintype m] [fintype n] [fintype o] variables {α : Type v} section ext variables {M N : matrix m n α} theorem ext_iff : (∀ i j, M i j = N i j) ↔ M = N := ⟨λ h, funext $ λ i, funext $ h i, λ h, by simp [h]⟩ @[ext] theorem ext : (∀ i j, M i j = N i j) → M = N := ext_iff.mp end ext def transpose (M : matrix m n α) : matrix n m α | x y := M y x localized "postfix `ᵀ`:1500 := matrix.transpose" in matrix def col (w : m → α) : matrix m punit α | x y := w x def row (v : n → α) : matrix punit n α | x y := v y instance [inhabited α] : inhabited (matrix m n α) := pi.inhabited _ instance [has_add α] : has_add (matrix m n α) := pi.has_add instance [add_semigroup α] : add_semigroup (matrix m n α) := pi.add_semigroup instance [add_comm_semigroup α] : add_comm_semigroup (matrix m n α) := pi.add_comm_semigroup instance [has_zero α] : has_zero (matrix m n α) := pi.has_zero instance [add_monoid α] : add_monoid (matrix m n α) := pi.add_monoid instance [add_comm_monoid α] : add_comm_monoid (matrix m n α) := pi.add_comm_monoid instance [has_neg α] : has_neg (matrix m n α) := pi.has_neg instance [add_group α] : add_group (matrix m n α) := pi.add_group instance [add_comm_group α] : add_comm_group (matrix m n α) := pi.add_comm_group @[simp] theorem zero_val [has_zero α] (i j) : (0 : matrix m n α) i j = 0 := rfl @[simp] theorem neg_val [has_neg α] (M : matrix m n α) (i j) : (- M) i j = - M i j := rfl @[simp] theorem add_val [has_add α] (M N : matrix m n α) (i j) : (M + N) i j = M i j + N i j := rfl section diagonal variables [decidable_eq n] /-- `diagonal d` is the square matrix such that `(diagonal d) i i = d i` and `(diagonal d) i j = 0` if `i ≠ j`. -/ def diagonal [has_zero α] (d : n → α) : matrix n n α := λ i j, if i = j then d i else 0 @[simp] theorem diagonal_val_eq [has_zero α] {d : n → α} (i : n) : (diagonal d) i i = d i := by simp [diagonal] @[simp] theorem diagonal_val_ne [has_zero α] {d : n → α} {i j : n} (h : i ≠ j) : (diagonal d) i j = 0 := by simp [diagonal, h] theorem diagonal_val_ne' [has_zero α] {d : n → α} {i j : n} (h : j ≠ i) : (diagonal d) i j = 0 := diagonal_val_ne h.symm @[simp] theorem diagonal_zero [has_zero α] : (diagonal (λ _, 0) : matrix n n α) = 0 := by simp [diagonal]; refl @[simp] lemma diagonal_transpose [has_zero α] (v : n → α) : (diagonal v)ᵀ = diagonal v := begin ext i j, by_cases h : i = j, { simp [h, transpose] }, { simp [h, transpose, diagonal_val_ne' h] } end @[simp] theorem diagonal_add [add_monoid α] (d₁ d₂ : n → α) : diagonal d₁ + diagonal d₂ = diagonal (λ i, d₁ i + d₂ i) := by ext i j; by_cases h : i = j; simp [h] section one variables [has_zero α] [has_one α] instance : has_one (matrix n n α) := ⟨diagonal (λ _, 1)⟩ @[simp] theorem diagonal_one : (diagonal (λ _, 1) : matrix n n α) = 1 := rfl theorem one_val {i j} : (1 : matrix n n α) i j = if i = j then 1 else 0 := rfl @[simp] theorem one_val_eq (i) : (1 : matrix n n α) i i = 1 := diagonal_val_eq i @[simp] theorem one_val_ne {i j} : i ≠ j → (1 : matrix n n α) i j = 0 := diagonal_val_ne theorem one_val_ne' {i j} : j ≠ i → (1 : matrix n n α) i j = 0 := diagonal_val_ne' end one section numeral @[simp] lemma bit0_val [has_add α] (M : matrix m m α) (i : m) (j : m) : (bit0 M) i j = bit0 (M i j) := rfl variables [add_monoid α] [has_one α] lemma bit1_val (M : matrix n n α) (i : n) (j : n) : (bit1 M) i j = if i = j then bit1 (M i j) else bit0 (M i j) := by dsimp [bit1]; by_cases h : i = j; simp [h] @[simp] lemma bit1_val_eq (M : matrix n n α) (i : n) : (bit1 M) i i = bit1 (M i i) := by simp [bit1_val] @[simp] lemma bit1_val_ne (M : matrix n n α) {i j : n} (h : i ≠ j) : (bit1 M) i j = bit0 (M i j) := by simp [bit1_val, h] end numeral end diagonal section dot_product /-- `dot_product v w` is the sum of the entrywise products `v i * w i` -/ def dot_product [has_mul α] [add_comm_monoid α] (v w : m → α) : α := ∑ i, v i * w i lemma dot_product_assoc [semiring α] (u : m → α) (v : m → n → α) (w : n → α) : dot_product (λ j, dot_product u (λ i, v i j)) w = dot_product u (λ i, dot_product (v i) w) := by simpa [dot_product, finset.mul_sum, finset.sum_mul, mul_assoc] using finset.sum_comm lemma dot_product_comm [comm_semiring α] (v w : m → α) : dot_product v w = dot_product w v := by simp_rw [dot_product, mul_comm] @[simp] lemma dot_product_punit [add_comm_monoid α] [has_mul α] (v w : punit → α) : dot_product v w = v ⟨⟩ * w ⟨⟩ := by simp [dot_product] @[simp] lemma dot_product_zero [semiring α] (v : m → α) : dot_product v 0 = 0 := by simp [dot_product] @[simp] lemma dot_product_zero' [semiring α] (v : m → α) : dot_product v (λ _, 0) = 0 := dot_product_zero v @[simp] lemma zero_dot_product [semiring α] (v : m → α) : dot_product 0 v = 0 := by simp [dot_product] @[simp] lemma zero_dot_product' [semiring α] (v : m → α) : dot_product (λ _, (0 : α)) v = 0 := zero_dot_product v @[simp] lemma add_dot_product [semiring α] (u v w : m → α) : dot_product (u + v) w = dot_product u w + dot_product v w := by simp [dot_product, add_mul, finset.sum_add_distrib] @[simp] lemma dot_product_add [semiring α] (u v w : m → α) : dot_product u (v + w) = dot_product u v + dot_product u w := by simp [dot_product, mul_add, finset.sum_add_distrib] @[simp] lemma diagonal_dot_product [decidable_eq m] [semiring α] (v w : m → α) (i : m) : dot_product (diagonal v i) w = v i * w i := have ∀ j ≠ i, diagonal v i j * w j = 0 := λ j hij, by simp [diagonal_val_ne' hij], by convert finset.sum_eq_single i (λ j _, this j) _; simp @[simp] lemma dot_product_diagonal [decidable_eq m] [semiring α] (v w : m → α) (i : m) : dot_product v (diagonal w i) = v i * w i := have ∀ j ≠ i, v j * diagonal w i j = 0 := λ j hij, by simp [diagonal_val_ne' hij], by convert finset.sum_eq_single i (λ j _, this j) _; simp @[simp] lemma dot_product_diagonal' [decidable_eq m] [semiring α] (v w : m → α) (i : m) : dot_product v (λ j, diagonal w j i) = v i * w i := have ∀ j ≠ i, v j * diagonal w j i = 0 := λ j hij, by simp [diagonal_val_ne hij], by convert finset.sum_eq_single i (λ j _, this j) _; simp @[simp] lemma neg_dot_product [ring α] (v w : m → α) : dot_product (-v) w = - dot_product v w := by simp [dot_product] @[simp] lemma dot_product_neg [ring α] (v w : m → α) : dot_product v (-w) = - dot_product v w := by simp [dot_product] @[simp] lemma smul_dot_product [semiring α] (x : α) (v w : m → α) : dot_product (x • v) w = x * dot_product v w := by simp [dot_product, finset.mul_sum, mul_assoc] @[simp] lemma dot_product_smul [comm_semiring α] (x : α) (v w : m → α) : dot_product v (x • w) = x * dot_product v w := by simp [dot_product, finset.mul_sum, mul_assoc, mul_comm, mul_left_comm] end dot_product protected def mul [has_mul α] [add_comm_monoid α] (M : matrix l m α) (N : matrix m n α) : matrix l n α := λ i k, dot_product (λ j, M i j) (λ j, N j k) localized "infixl ` ⬝ `:75 := matrix.mul" in matrix theorem mul_val [has_mul α] [add_comm_monoid α] {M : matrix l m α} {N : matrix m n α} {i k} : (M ⬝ N) i k = ∑ j, M i j * N j k := rfl instance [has_mul α] [add_comm_monoid α] : has_mul (matrix n n α) := ⟨matrix.mul⟩ @[simp] theorem mul_eq_mul [has_mul α] [add_comm_monoid α] (M N : matrix n n α) : M * N = M ⬝ N := rfl theorem mul_val' [has_mul α] [add_comm_monoid α] {M N : matrix n n α} {i k} : (M ⬝ N) i k = dot_product (λ j, M i j) (λ j, N j k) := rfl section semigroup variables [semiring α] protected theorem mul_assoc (L : matrix l m α) (M : matrix m n α) (N : matrix n o α) : (L ⬝ M) ⬝ N = L ⬝ (M ⬝ N) := by { ext, apply dot_product_assoc } instance : semigroup (matrix n n α) := { mul_assoc := matrix.mul_assoc, ..matrix.has_mul } end semigroup @[simp] theorem diagonal_neg [decidable_eq n] [add_group α] (d : n → α) : -diagonal d = diagonal (λ i, -d i) := by ext i j; by_cases i = j; simp [h] section semiring variables [semiring α] @[simp] protected theorem mul_zero (M : matrix m n α) : M ⬝ (0 : matrix n o α) = 0 := by { ext i j, apply dot_product_zero } @[simp] protected theorem zero_mul (M : matrix m n α) : (0 : matrix l m α) ⬝ M = 0 := by { ext i j, apply zero_dot_product } protected theorem mul_add (L : matrix m n α) (M N : matrix n o α) : L ⬝ (M + N) = L ⬝ M + L ⬝ N := by { ext i j, apply dot_product_add } protected theorem add_mul (L M : matrix l m α) (N : matrix m n α) : (L + M) ⬝ N = L ⬝ N + M ⬝ N := by { ext i j, apply add_dot_product } @[simp] theorem diagonal_mul [decidable_eq m] (d : m → α) (M : matrix m n α) (i j) : (diagonal d).mul M i j = d i * M i j := diagonal_dot_product _ _ _ @[simp] theorem mul_diagonal [decidable_eq n] (d : n → α) (M : matrix m n α) (i j) : (M ⬝ diagonal d) i j = M i j * d j := by { rw ← diagonal_transpose, apply dot_product_diagonal } @[simp] protected theorem one_mul [decidable_eq m] (M : matrix m n α) : (1 : matrix m m α) ⬝ M = M := by ext i j; rw [← diagonal_one, diagonal_mul, one_mul] @[simp] protected theorem mul_one [decidable_eq n] (M : matrix m n α) : M ⬝ (1 : matrix n n α) = M := by ext i j; rw [← diagonal_one, mul_diagonal, mul_one] instance [decidable_eq n] : monoid (matrix n n α) := { one_mul := matrix.one_mul, mul_one := matrix.mul_one, ..matrix.has_one, ..matrix.semigroup } instance [decidable_eq n] : semiring (matrix n n α) := { mul_zero := matrix.mul_zero, zero_mul := matrix.zero_mul, left_distrib := matrix.mul_add, right_distrib := matrix.add_mul, ..matrix.add_comm_monoid, ..matrix.monoid } @[simp] theorem diagonal_mul_diagonal [decidable_eq n] (d₁ d₂ : n → α) : (diagonal d₁) ⬝ (diagonal d₂) = diagonal (λ i, d₁ i * d₂ i) := by ext i j; by_cases i = j; simp [h] theorem diagonal_mul_diagonal' [decidable_eq n] (d₁ d₂ : n → α) : diagonal d₁ * diagonal d₂ = diagonal (λ i, d₁ i * d₂ i) := diagonal_mul_diagonal _ _ lemma is_add_monoid_hom_mul_left (M : matrix l m α) : is_add_monoid_hom (λ x : matrix m n α, M ⬝ x) := { to_is_add_hom := ⟨matrix.mul_add _⟩, map_zero := matrix.mul_zero _ } lemma is_add_monoid_hom_mul_right (M : matrix m n α) : is_add_monoid_hom (λ x : matrix l m α, x ⬝ M) := { to_is_add_hom := ⟨λ _ _, matrix.add_mul _ _ _⟩, map_zero := matrix.zero_mul _ } protected lemma sum_mul {β : Type*} (s : finset β) (f : β → matrix l m α) (M : matrix m n α) : (∑ a in s, f a) ⬝ M = ∑ a in s, f a ⬝ M := (@finset.sum_hom _ _ _ _ _ s f (λ x, x ⬝ M) /- This line does not type-check without `id` and `: _`. Lean did not recognize that two different `add_monoid` instances were def-eq -/ (id (@is_add_monoid_hom_mul_right l _ _ _ _ _ _ _ M) : _)).symm protected lemma mul_sum {β : Type*} (s : finset β) (f : β → matrix m n α) (M : matrix l m α) : M ⬝ ∑ a in s, f a = ∑ a in s, M ⬝ f a := (@finset.sum_hom _ _ _ _ _ s f (λ x, M ⬝ x) /- This line does not type-check without `id` and `: _`. Lean did not recognize that two different `add_monoid` instances were def-eq -/ (id (@is_add_monoid_hom_mul_left _ _ n _ _ _ _ _ M) : _)).symm @[simp] lemma row_mul_col_val (v w : m → α) (i j) : (row v ⬝ col w) i j = dot_product v w := rfl end semiring section ring variables [ring α] @[simp] theorem neg_mul (M : matrix m n α) (N : matrix n o α) : (-M) ⬝ N = -(M ⬝ N) := by { ext, apply neg_dot_product } @[simp] theorem mul_neg (M : matrix m n α) (N : matrix n o α) : M ⬝ (-N) = -(M ⬝ N) := by { ext, apply dot_product_neg } end ring instance [decidable_eq n] [ring α] : ring (matrix n n α) := { ..matrix.semiring, ..matrix.add_comm_group } instance [semiring α] : has_scalar α (matrix m n α) := pi.has_scalar instance {β : Type w} [semiring α] [add_comm_monoid β] [semimodule α β] : semimodule α (matrix m n β) := pi.semimodule _ _ _ @[simp] lemma smul_val [semiring α] (a : α) (A : matrix m n α) (i : m) (j : n) : (a • A) i j = a * A i j := rfl section semiring variables [semiring α] lemma smul_eq_diagonal_mul [decidable_eq m] (M : matrix m n α) (a : α) : a • M = diagonal (λ _, a) ⬝ M := by { ext, simp } @[simp] lemma smul_mul (M : matrix m n α) (a : α) (N : matrix n l α) : (a • M) ⬝ N = a • M ⬝ N := by { ext, apply smul_dot_product } @[simp] lemma mul_mul_left (M : matrix m n α) (N : matrix n o α) (a : α) : (λ i j, a * M i j) ⬝ N = a • (M ⬝ N) := begin simp only [←smul_val], simp, end /-- The ring homomorphism `α →+* matrix n n α` sending `a` to the diagonal matrix with `a` on the diagonal. -/ def scalar (n : Type u) [fintype n] [decidable_eq n] : α →+* matrix n n α := { to_fun := λ a, a • 1, map_zero' := by simp, map_add' := by { intros, ext, simp [add_mul], }, map_one' := by simp, map_mul' := by { intros, ext, simp [mul_assoc], }, } section scalar variable [decidable_eq n] @[simp] lemma coe_scalar : (scalar n : α → matrix n n α) = λ a, a • 1 := rfl lemma scalar_apply_eq (a : α) (i : n) : scalar n a i i = a := by simp only [coe_scalar, mul_one, one_val_eq, smul_val] lemma scalar_apply_ne (a : α) (i j : n) (h : i ≠ j) : scalar n a i j = 0 := by simp only [h, coe_scalar, one_val_ne, ne.def, not_false_iff, smul_val, mul_zero] end scalar end semiring section comm_semiring variables [comm_semiring α] lemma smul_eq_mul_diagonal [decidable_eq n] (M : matrix m n α) (a : α) : a • M = M ⬝ diagonal (λ _, a) := by { ext, simp [mul_comm] } @[simp] lemma mul_smul (M : matrix m n α) (a : α) (N : matrix n l α) : M ⬝ (a • N) = a • M ⬝ N := by { ext, apply dot_product_smul } @[simp] lemma mul_mul_right (M : matrix m n α) (N : matrix n o α) (a : α) : M ⬝ (λ i j, a * N i j) = a • (M ⬝ N) := begin simp only [←smul_val], simp, end end comm_semiring section semiring variables [semiring α] def vec_mul_vec (w : m → α) (v : n → α) : matrix m n α | x y := w x * v y def mul_vec (M : matrix m n α) (v : n → α) : m → α | i := dot_product (λ j, M i j) v def vec_mul (v : m → α) (M : matrix m n α) : n → α | j := dot_product v (λ i, M i j) instance mul_vec.is_add_monoid_hom_left (v : n → α) : is_add_monoid_hom (λM:matrix m n α, mul_vec M v) := { map_zero := by ext; simp [mul_vec]; refl, map_add := begin intros x y, ext m, apply add_dot_product end } lemma mul_vec_diagonal [decidable_eq m] (v w : m → α) (x : m) : mul_vec (diagonal v) w x = v x * w x := diagonal_dot_product v w x lemma vec_mul_diagonal [decidable_eq m] (v w : m → α) (x : m) : vec_mul v (diagonal w) x = v x * w x := dot_product_diagonal' v w x @[simp] lemma mul_vec_one [decidable_eq m] (v : m → α) : mul_vec 1 v = v := by { ext, rw [←diagonal_one, mul_vec_diagonal, one_mul] } @[simp] lemma vec_mul_one [decidable_eq m] (v : m → α) : vec_mul v 1 = v := by { ext, rw [←diagonal_one, vec_mul_diagonal, mul_one] } @[simp] lemma mul_vec_zero (A : matrix m n α) : mul_vec A 0 = 0 := by { ext, simp [mul_vec] } @[simp] lemma vec_mul_zero (A : matrix m n α) : vec_mul 0 A = 0 := by { ext, simp [vec_mul] } @[simp] lemma vec_mul_vec_mul (v : m → α) (M : matrix m n α) (N : matrix n o α) : vec_mul (vec_mul v M) N = vec_mul v (M ⬝ N) := by { ext, apply dot_product_assoc } @[simp] lemma mul_vec_mul_vec (v : o → α) (M : matrix m n α) (N : matrix n o α) : mul_vec M (mul_vec N v) = mul_vec (M ⬝ N) v := by { ext, symmetry, apply dot_product_assoc } lemma vec_mul_vec_eq (w : m → α) (v : n → α) : vec_mul_vec w v = (col w) ⬝ (row v) := by { ext i j, simp [vec_mul_vec, mul_val], refl } variables [decidable_eq m] [decidable_eq n] /-- `std_basis_matrix i j a` is the matrix with `a` in the `i`-th row, `j`-th column, and zeroes elsewhere. -/ def std_basis_matrix (i : m) (j : n) (a : α) : matrix m n α := (λ i' j', if i' = i ∧ j' = j then a else 0) @[simp] lemma smul_std_basis_matrix (i : m) (j : n) (a b : α) : b • std_basis_matrix i j a = std_basis_matrix i j (b • a) := by { unfold std_basis_matrix, ext, dsimp, simp } @[simp] lemma std_basis_matrix_zero (i : m) (j : n) : std_basis_matrix i j (0 : α) = 0 := by { unfold std_basis_matrix, ext, simp } lemma std_basis_matrix_add (i : m) (j : n) (a b : α) : std_basis_matrix i j (a + b) = std_basis_matrix i j a + std_basis_matrix i j b := begin unfold std_basis_matrix, ext, split_ifs with h; simp [h], end lemma matrix_eq_sum_elementary (x : matrix n m α) : x = ∑ (i : n) (j : m), std_basis_matrix i j (x i j) := begin ext, iterate 2 {rw finset.sum_apply}, rw ← finset.sum_subset, swap 4, exact {i}, { norm_num [std_basis_matrix] }, { simp }, intros, norm_num at a, norm_num, convert finset.sum_const_zero, ext, norm_num [std_basis_matrix], rw if_neg, tauto!, end -- TODO: tie this up with the `basis` machinery of linear algebra -- this is not completely trivial because we are indexing by two types, instead of one -- TODO: add `std_basis_vec` lemma elementary_eq_basis_mul_basis (i : m) (j : n) : std_basis_matrix i j 1 = vec_mul_vec (λ i', ite (i = i') 1 0) (λ j', ite (j = j') 1 0) := begin ext, norm_num [std_basis_matrix, vec_mul_vec], split_ifs; tauto, end @[elab_as_eliminator] protected lemma induction_on' {X : Type*} [semiring X] {M : matrix n n X → Prop} (m : matrix n n X) (h_zero : M 0) (h_add : ∀p q, M p → M q → M (p + q)) (h_elementary : ∀ i j x, M (std_basis_matrix i j x)) : M m := begin rw [matrix_eq_sum_elementary m, ← finset.sum_product'], apply finset.sum_induction _ _ h_add h_zero, { intros, apply h_elementary, } end @[elab_as_eliminator] protected lemma induction_on [nonempty n] {X : Type*} [semiring X] {M : matrix n n X → Prop} (m : matrix n n X) (h_add : ∀p q, M p → M q → M (p + q)) (h_elementary : ∀ i j x, M (std_basis_matrix i j x)) : M m := matrix.induction_on' m begin have i : n := classical.choice (by assumption), simpa using h_elementary i i 0, end h_add h_elementary end semiring section ring variables [ring α] lemma neg_vec_mul (v : m → α) (A : matrix m n α) : vec_mul (-v) A = - vec_mul v A := by { ext, apply neg_dot_product } lemma vec_mul_neg (v : m → α) (A : matrix m n α) : vec_mul v (-A) = - vec_mul v A := by { ext, apply dot_product_neg } lemma neg_mul_vec (v : n → α) (A : matrix m n α) : mul_vec (-A) v = - mul_vec A v := by { ext, apply neg_dot_product } lemma mul_vec_neg (v : n → α) (A : matrix m n α) : mul_vec A (-v) = - mul_vec A v := by { ext, apply dot_product_neg } end ring section transpose open_locale matrix /-- Tell `simp` what the entries are in a transposed matrix. Compare with `mul_val`, `diagonal_val_eq`, etc. -/ @[simp] lemma transpose_val (M : matrix m n α) (i j) : M.transpose j i = M i j := rfl @[simp] lemma transpose_transpose (M : matrix m n α) : Mᵀᵀ = M := by ext; refl @[simp] lemma transpose_zero [has_zero α] : (0 : matrix m n α)ᵀ = 0 := by ext i j; refl @[simp] lemma transpose_one [decidable_eq n] [has_zero α] [has_one α] : (1 : matrix n n α)ᵀ = 1 := begin ext i j, unfold has_one.one transpose, by_cases i = j, { simp only [h, diagonal_val_eq] }, { simp only [diagonal_val_ne h, diagonal_val_ne (λ p, h (symm p))] } end @[simp] lemma transpose_add [has_add α] (M : matrix m n α) (N : matrix m n α) : (M + N)ᵀ = Mᵀ + Nᵀ := by { ext i j, simp } @[simp] lemma transpose_sub [add_comm_group α] (M : matrix m n α) (N : matrix m n α) : (M - N)ᵀ = Mᵀ - Nᵀ := by { ext i j, simp } @[simp] lemma transpose_mul [comm_ring α] (M : matrix m n α) (N : matrix n l α) : (M ⬝ N)ᵀ = Nᵀ ⬝ Mᵀ := begin ext i j, apply dot_product_comm end @[simp] lemma transpose_smul [comm_ring α] (c : α)(M : matrix m n α) : (c • M)ᵀ = c • Mᵀ := by { ext i j, refl } @[simp] lemma transpose_neg [comm_ring α] (M : matrix m n α) : (- M)ᵀ = - Mᵀ := by ext i j; refl end transpose def minor (A : matrix m n α) (row : l → m) (col : o → n) : matrix l o α := λ i j, A (row i) (col j) @[reducible] def sub_left {m l r : nat} (A : matrix (fin m) (fin (l + r)) α) : matrix (fin m) (fin l) α := minor A id (fin.cast_add r) @[reducible] def sub_right {m l r : nat} (A : matrix (fin m) (fin (l + r)) α) : matrix (fin m) (fin r) α := minor A id (fin.nat_add l) @[reducible] def sub_up {d u n : nat} (A : matrix (fin (u + d)) (fin n) α) : matrix (fin u) (fin n) α := minor A (fin.cast_add d) id @[reducible] def sub_down {d u n : nat} (A : matrix (fin (u + d)) (fin n) α) : matrix (fin d) (fin n) α := minor A (fin.nat_add u) id @[reducible] def sub_up_right {d u l r : nat} (A: matrix (fin (u + d)) (fin (l + r)) α) : matrix (fin u) (fin r) α := sub_up (sub_right A) @[reducible] def sub_down_right {d u l r : nat} (A : matrix (fin (u + d)) (fin (l + r)) α) : matrix (fin d) (fin r) α := sub_down (sub_right A) @[reducible] def sub_up_left {d u l r : nat} (A : matrix (fin (u + d)) (fin (l + r)) α) : matrix (fin u) (fin (l)) α := sub_up (sub_left A) @[reducible] def sub_down_left {d u l r : nat} (A: matrix (fin (u + d)) (fin (l + r)) α) : matrix (fin d) (fin (l)) α := sub_down (sub_left A) section row_col /-! ### `row_col` section Simplification lemmas for `matrix.row` and `matrix.col`. -/ open_locale matrix @[simp] lemma col_add [semiring α] (v w : m → α) : col (v + w) = col v + col w := by { ext, refl } @[simp] lemma col_smul [semiring α] (x : α) (v : m → α) : col (x • v) = x • col v := by { ext, refl } @[simp] lemma row_add [semiring α] (v w : m → α) : row (v + w) = row v + row w := by { ext, refl } @[simp] lemma row_smul [semiring α] (x : α) (v : m → α) : row (x • v) = x • row v := by { ext, refl } @[simp] lemma col_val (v : m → α) (i j) : matrix.col v i j = v i := rfl @[simp] lemma row_val (v : m → α) (i j) : matrix.row v i j = v j := rfl @[simp] lemma transpose_col (v : m → α) : (matrix.col v).transpose = matrix.row v := by {ext, refl} @[simp] lemma transpose_row (v : m → α) : (matrix.row v).transpose = matrix.col v := by {ext, refl} lemma row_vec_mul [semiring α] (M : matrix m n α) (v : m → α) : matrix.row (matrix.vec_mul v M) = matrix.row v ⬝ M := by {ext, refl} lemma col_vec_mul [semiring α] (M : matrix m n α) (v : m → α) : matrix.col (matrix.vec_mul v M) = (matrix.row v ⬝ M)ᵀ := by {ext, refl} lemma col_mul_vec [semiring α] (M : matrix m n α) (v : n → α) : matrix.col (matrix.mul_vec M v) = M ⬝ matrix.col v := by {ext, refl} lemma row_mul_vec [semiring α] (M : matrix m n α) (v : n → α) : matrix.row (matrix.mul_vec M v) = (M ⬝ matrix.col v)ᵀ := by {ext, refl} end row_col end matrix namespace ring_hom variables {α β : Type*} [semiring α] [semiring β] variables {m n o : Type u} [fintype m] [fintype n] [fintype o] lemma map_matrix_mul (M : matrix m n α) (N : matrix n o α) (i : m) (j : o) (f : α →+* β) : f (matrix.mul M N i j) = matrix.mul (λ i j, f (M i j)) (λ i j, f (N i j)) i j := by simp [matrix.mul_val, ring_hom.map_sum] end ring_hom
25db0910095ca616d02d97b4f2c3b5255ff531f8
ba4794a0deca1d2aaa68914cd285d77880907b5c
/src/game/world5/level1.lean
9754fc69199728d5013a9390c8e20f1e7910ea8a
[ "Apache-2.0" ]
permissive
ChrisHughes24/natural_number_game
c7c00aa1f6a95004286fd456ed13cf6e113159ce
9d09925424da9f6275e6cfe427c8bcf12bb0944f
refs/heads/master
1,600,715,773,528
1,573,910,462,000
1,573,910,462,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,408
lean
-- World name : Function world /- # Function world. If you have beaten Addition World, then you have got quite good at manipulating equalities in Lean using the `rw` tactic. But there are plenty of levels later on which will require you to manipulate functions, and `rw` is not the tool for you here. To manipulate functions effectively, we need to learn about a new collection of tactics, namely `exact`, `intro`, `have` and `apply`. These tactics are specially designed for dealing with functions. Of course we are ultimately interested in using these tactics to prove theorems about the natural numbers -- but in this world there is little point in working with specific sets like `mynat`, everything works for general sets. So our notation for this level is: $P$, $Q$, $R$ and so on denote general sets, and $h$, $j$, $k$ and so on denote general functions between them. What we will learn in this world is how to use Lean to move elements around between these sets using the functions we are given, and the tactics we will learn. A word of warning -- even though there's no harm at all in thinking of $P$ being a set and $p$ being an element, you will not see Lean using the notation $p\in P$, because internally Lean stores $P$ as a "Type" and $p$ as a "term", and it uses `p : P` to mean "$p$ is a term of type $P$", Lean's way of expressing the idea that $p$ is an element of the set $P$. You have seen this already -- Lean has been writing `n : mynat` to mean that $n$ is a natural number. ## A new kind of goal. All through addition world, our goals have been theorems, and it was our job to find the proofs. **The levels in function world aren't theorems**. This is the only world where the levels aren't theorems in fact. In function world the object of a level is to create an element of the set in the goal. The goal will look like `⊢ X` with $X$ a set and you get rid of the goal by constructing an element of $X$. I don't know if you noticed this, but you finished essentially every goal of Addition World (and Multiplication World and Power World, if you played them) with `refl`. This tactic is no use to us here. We are going to have to learn a new way of solving goals -- the `exact` tactic. If you delete the sorry below then your local context will look like this: ``` P Q : Type, p : P, h : P → Q ⊢ Q ``` In this situation, we have sets $P$ and $Q$ (but Lean calls them types), and an element $p$ of $P$ (written `p : P` but meaning $p\in P$). We also have a function $h$ from $P$ to $Q$, and our goal is to construct an element of the set $Q$. It's clear what to do *mathematically* to solve this goal -- we can make an element of $Q$ by applying the function $h$ to the element $p$. But how to do it in Lean? There are at least two ways to explain this idea to Lean, and here we will learn about one of them, namely the method which uses the `exact` tactic. ## The `exact` tactic. If you can explicitly see how to make an element of of your goal set, i.e. you have a formula for it, then you can just write `exact <formula>` and this will close the goal. ### Example If your local context looks like this ``` P Q : Type, p : P, h : P → Q ⊢ Q ``` then $h(p)$ is an element of $Q$ so you can just write `exact h(p),` to close the goal. ## Important note Note that `exact h(P),` won't work (with a capital $P$); this is a common error I see from beginners. $P$ is not an element of $P$, it's $p$ that is an element of $P$. ## Level 1: the `exact` tactic. -/ /- Definition Given an element of $P$ and a function from $P$ to $Q$, we define an element of $Q$. -/ example (P Q : Type) (p : P) (h : P → Q) : Q := begin exact h(p), end /- Tactic : exact ## Summary If the goal is `⊢ X` then `exact x` will close the goal if and only if `x` is a term of type `X`. ## Details Say $P$, $Q$ and $R$ are types (i.e., what a mathematician might think of as either sets or propositions), and the local context looks like this: ``` p : P, h : P → Q, j : Q → R ⊢ R ``` If you can spot how to make a term of type `R`, then you can just make it and say you're done using the `exact` tactic together with the formula you have spotted. For example the above goal could be solved with `exact j(h(p)),` because $j(h(p))$ is easily checked to be a term of type $R$ (i.e., an element of the set $R$, or a proof of the proposition $R$). -/
35e41be0fadaa13f4b0fbe1f5f169c1d4ebaecb4
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/cyclic_default_fields.lean
873683b051cceae0258166993b5dac3fbf379a97
[ "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
205
lean
class Eq (α : Type) := (eq : α → α → Prop) (ne : α → α → Prop := λ a b, ¬eq a b) (eq := λ a b, ¬ne a b) #check ({} : Eq ℕ) #check ({eq := (=)} : Eq ℕ) #check ({ne := (≠)} : Eq ℕ)
80985ef52ba534d8d50337c168f3617042e96f2b
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/interactive/hoverAt.lean
e523ae9492dbaf149292b94167ef1fe23e1e15c3
[ "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
448
lean
inductive Palindrome : List α → Prop where | nil : Palindrome [] | single : (a : α) → Palindrome [a] | sandwish : (a : α) → Palindrome as → Palindrome ([a] ++ as ++ [a]) theorem palindrome_reverse (h : Palindrome as) : Palindrome as.reverse := match h with | .nil => .nil | .single a => Palindrome.single a --^ textDocument/hover | .sandwish a h => by simp; exact .sandwish _ (palindrome_reverse h)
76903b382e0b0fb3e87046427906df5e74c115d4
30b012bb72d640ec30c8fdd4c45fdfa67beb012c
/tactic/norm_num.lean
d6d04f382dd469001cfb30f2a73dd1df7afe1647
[ "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
18,794
lean
/- Copyright (c) 2017 Simon Hudon All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon, Mario Carneiro Evaluating arithmetic expressions including *, +, -, ^, ≤ -/ import algebra.group_power data.rat data.nat.prime import tactic.interactive tactic.converter.interactive universes u v w namespace expr protected meta def to_pos_rat : expr → option ℚ | `(%%e₁ / %%e₂) := do m ← e₁.to_nat, n ← e₂.to_nat, some (rat.mk m n) | e := do n ← e.to_nat, return (rat.of_int n) protected meta def to_rat : expr → option ℚ | `(has_neg.neg %%e) := do q ← e.to_pos_rat, some (-q) | e := e.to_pos_rat protected meta def of_rat (α : expr) : ℚ → tactic expr | ⟨(n:ℕ), d, h, c⟩ := do e₁ ← expr.of_nat α n, if d = 1 then return e₁ else do e₂ ← expr.of_nat α d, tactic.mk_app ``has_div.div [e₁, e₂] | ⟨-[1+n], d, h, c⟩ := do e₁ ← expr.of_nat α (n+1), e ← (if d = 1 then return e₁ else do e₂ ← expr.of_nat α d, tactic.mk_app ``has_div.div [e₁, e₂]), tactic.mk_app ``has_neg.neg [e] end expr namespace tactic meta def refl_conv (e : expr) : tactic (expr × expr) := do p ← mk_eq_refl e, return (e, p) meta def trans_conv (t₁ t₂ : expr → tactic (expr × expr)) (e : expr) : tactic (expr × expr) := (do (e₁, p₁) ← t₁ e, (do (e₂, p₂) ← t₂ e₁, p ← mk_eq_trans p₁ p₂, return (e₂, p)) <|> return (e₁, p₁)) <|> t₂ e end tactic open tactic namespace norm_num variable {α : Type u} lemma subst_into_neg {α} [has_neg α] (a ta t : α) (pra : a = ta) (prt : -ta = t) : -a = t := by simp [pra, prt] theorem bit0_zero [add_group α] : bit0 (0 : α) = 0 := add_zero _ theorem bit1_zero [add_group α] [has_one α] : bit1 (0 : α) = 1 := by rw [bit1, bit0_zero, zero_add] lemma pow_bit0_helper [monoid α] (a t : α) (b : ℕ) (h : a ^ b = t) : a ^ bit0 b = t * t := by simp [pow_bit0, h] lemma pow_bit1_helper [monoid α] (a t : α) (b : ℕ) (h : a ^ b = t) : a ^ bit1 b = t * t * a := by simp [pow_bit1, h] lemma lt_add_of_pos_helper [ordered_cancel_comm_monoid α] (a b c : α) (h : a + b = c) (h₂ : 0 < b) : a < c := h ▸ (lt_add_iff_pos_right _).2 h₂ lemma nat_div_helper (a b q r : ℕ) (h : r + q * b = a) (h₂ : r < b) : a / b = q := by rw [← h, nat.add_mul_div_right _ _ (lt_of_le_of_lt (nat.zero_le _) h₂), nat.div_eq_of_lt h₂, zero_add] lemma int_div_helper (a b q r : ℤ) (h : r + q * b = a) (h₁ : 0 ≤ r) (h₂ : r < b) : a / b = q := by rw [← h, int.add_mul_div_right _ _ (ne_of_gt (lt_of_le_of_lt h₁ h₂)), int.div_eq_zero_of_lt h₁ h₂, zero_add] lemma nat_mod_helper (a b q r : ℕ) (h : r + q * b = a) (h₂ : r < b) : a % b = r := by rw [← h, nat.add_mul_mod_self_right, nat.mod_eq_of_lt h₂] lemma int_mod_helper (a b q r : ℤ) (h : r + q * b = a) (h₁ : 0 ≤ r) (h₂ : r < b) : a % b = r := by rw [← h, int.add_mul_mod_self, int.mod_eq_of_lt h₁ h₂] meta def eval_pow (simp : expr → tactic (expr × expr)) : expr → tactic (expr × expr) | `(@has_pow.pow %%α _ %%m %%e₁ %%e₂) := match m with | `(nat.has_pow) := mk_app ``nat.pow [e₁, e₂] >>= eval_pow | `(@monoid.has_pow %%α %%m) := mk_app ``monoid.pow [e₁, e₂] >>= eval_pow | _ := failed end | `(monoid.pow %%e₁ 0) := do p ← mk_app ``pow_zero [e₁], a ← infer_type e₁, o ← mk_app ``has_one.one [a], return (o, p) | `(monoid.pow %%e₁ 1) := do p ← mk_app ``pow_one [e₁], return (e₁, p) | `(monoid.pow %%e₁ (bit0 %%e₂)) := do e ← mk_app ``monoid.pow [e₁, e₂], (e', p) ← simp e, p' ← mk_app ``norm_num.pow_bit0_helper [e₁, e', e₂, p], e'' ← to_expr ``(%%e' * %%e'), return (e'', p') | `(monoid.pow %%e₁ (bit1 %%e₂)) := do e ← mk_app ``monoid.pow [e₁, e₂], (e', p) ← simp e, p' ← mk_app ``norm_num.pow_bit1_helper [e₁, e', e₂, p], e'' ← to_expr ``(%%e' * %%e' * %%e₁), return (e'', p') | `(nat.pow %%e₁ %%e₂) := do p₁ ← mk_app ``nat.pow_eq_pow [e₁, e₂], e ← mk_app ``monoid.pow [e₁, e₂], (e', p₂) ← simp e, p ← mk_eq_trans p₁ p₂, return (e', p) | _ := failed meta def prove_pos : instance_cache → expr → tactic (instance_cache × expr) | c `(has_one.one _) := do (c, p) ← c.mk_app ``zero_lt_one [], return (c, p) | c `(bit0 %%e) := do (c, p) ← prove_pos c e, (c, p) ← c.mk_app ``bit0_pos [e, p], return (c, p) | c `(bit1 %%e) := do (c, p) ← prove_pos c e, (c, p) ← c.mk_app ``bit1_pos' [e, p], return (c, p) | c `(%%e₁ / %%e₂) := do (c, p₁) ← prove_pos c e₁, (c, p₂) ← prove_pos c e₂, (c, p) ← c.mk_app ``div_pos_of_pos_of_pos [e₁, e₂, p₁, p₂], return (c, p) | c e := failed meta def prove_lt (simp : expr → tactic (expr × expr)) : instance_cache → expr → expr → tactic (instance_cache × expr) | c `(- %%e₁) `(- %%e₂) := do (c, p) ← prove_lt c e₁ e₂, (c, p) ← c.mk_app ``neg_lt_neg [e₁, e₂, p], return (c, p) | c `(- %%e₁) `(has_zero.zero _) := do (c, p) ← prove_pos c e₁, (c, p) ← c.mk_app ``neg_neg_of_pos [e₁, p], return (c, p) | c `(- %%e₁) e₂ := do (c, p₁) ← prove_pos c e₁, (c, me₁) ← c.mk_app ``has_neg.neg [e₁], (c, p₁) ← c.mk_app ``neg_neg_of_pos [e₁, p₁], (c, p₂) ← prove_pos c e₂, (c, z) ← c.mk_app ``has_zero.zero [], (c, p) ← c.mk_app ``lt_trans [me₁, z, e₂, p₁, p₂], return (c, p) | c `(has_zero.zero _) e₂ := prove_pos c e₂ | c e₁ e₂ := do n₁ ← e₁.to_rat, n₂ ← e₂.to_rat, d ← expr.of_rat c.α (n₂ - n₁), (c, e₃) ← c.mk_app ``has_add.add [e₁, d], (e₂', p) ← norm_num e₃, guard (e₂' =ₐ e₂), (c, p') ← prove_pos c d, (c, p) ← c.mk_app ``norm_num.lt_add_of_pos_helper [e₁, d, e₂, p, p'], return (c, p) private meta def true_intro (p : expr) : tactic (expr × expr) := prod.mk <$> mk_const `true <*> mk_app ``eq_true_intro [p] private meta def false_intro (p : expr) : tactic (expr × expr) := prod.mk <$> mk_const `false <*> mk_app ``eq_false_intro [p] meta def eval_ineq (simp : expr → tactic (expr × expr)) : expr → tactic (expr × expr) | `(%%e₁ < %%e₂) := do n₁ ← e₁.to_rat, n₂ ← e₂.to_rat, c ← infer_type e₁ >>= mk_instance_cache, if n₁ < n₂ then do (_, p) ← prove_lt simp c e₁ e₂, true_intro p else do (c, p) ← if n₁ = n₂ then c.mk_app ``lt_irrefl [e₁] else (do (c, p') ← prove_lt simp c e₂ e₁, c.mk_app ``not_lt_of_gt [e₁, e₂, p']), false_intro p | `(%%e₁ ≤ %%e₂) := do n₁ ← e₁.to_rat, n₂ ← e₂.to_rat, c ← infer_type e₁ >>= mk_instance_cache, if n₁ ≤ n₂ then do (c, p) ← if n₁ = n₂ then c.mk_app ``le_refl [e₁] else (do (c, p') ← prove_lt simp c e₁ e₂, c.mk_app ``le_of_lt [e₁, e₂, p']), true_intro p else do (c, p) ← prove_lt simp c e₂ e₁, (c, p) ← c.mk_app ``not_le_of_gt [e₁, e₂, p], false_intro p | `(%%e₁ = %%e₂) := do n₁ ← e₁.to_rat, n₂ ← e₂.to_rat, c ← infer_type e₁ >>= mk_instance_cache, if n₁ < n₂ then do (c, p) ← prove_lt simp c e₁ e₂, (c, p) ← c.mk_app ``ne_of_lt [e₁, e₂, p], false_intro p else if n₂ < n₁ then do (c, p) ← prove_lt simp c e₂ e₁, (c, p) ← c.mk_app ``ne_of_gt [e₁, e₂, p], false_intro p else mk_eq_refl e₁ >>= true_intro | `(%%e₁ > %%e₂) := mk_app ``has_lt.lt [e₂, e₁] >>= simp | `(%%e₁ ≥ %%e₂) := mk_app ``has_le.le [e₂, e₁] >>= simp | `(%%e₁ ≠ %%e₂) := do e ← mk_app ``eq [e₁, e₂], mk_app ``not [e] >>= simp | _ := failed meta def eval_div_ext (simp : expr → tactic (expr × expr)) : expr → tactic (expr × expr) | `(has_inv.inv %%e) := do c ← infer_type e >>= mk_instance_cache, (c, p₁) ← c.mk_app ``inv_eq_one_div [e], (c, o) ← c.mk_app ``has_one.one [], (c, e') ← c.mk_app ``has_div.div [o, e], (do (e'', p₂) ← simp e', p ← mk_eq_trans p₁ p₂, return (e'', p)) <|> return (e', p₁) | `(%%e₁ / %%e₂) := do α ← infer_type e₁, c ← mk_instance_cache α, match α with | `(nat) := do n₁ ← e₁.to_nat, n₂ ← e₂.to_nat, q ← expr.of_nat α (n₁ / n₂), r ← expr.of_nat α (n₁ % n₂), (c, e₃) ← c.mk_app ``has_mul.mul [q, e₂], (c, e₃) ← c.mk_app ``has_add.add [r, e₃], (e₁', p) ← norm_num e₃, guard (e₁' =ₐ e₁), (c, p') ← prove_lt simp c r e₂, p ← mk_app ``norm_num.nat_div_helper [e₁, e₂, q, r, p, p'], return (q, p) | `(int) := match e₂ with | `(- %%e₂') := do (c, p₁) ← c.mk_app ``int.div_neg [e₁, e₂'], (c, e) ← c.mk_app ``has_div.div [e₁, e₂'], (c, e) ← c.mk_app ``has_neg.neg [e], (e', p₂) ← simp e, p ← mk_eq_trans p₁ p₂, return (e', p) | _ := do n₁ ← e₁.to_int, n₂ ← e₂.to_int, q ← expr.of_rat α $ rat.of_int (n₁ / n₂), r ← expr.of_rat α $ rat.of_int (n₁ % n₂), (c, e₃) ← c.mk_app ``has_mul.mul [q, e₂], (c, e₃) ← c.mk_app ``has_add.add [r, e₃], (e₁', p) ← norm_num e₃, guard (e₁' =ₐ e₁), (c, r0) ← c.mk_app ``has_zero.zero [], (c, r0) ← c.mk_app ``has_le.le [r0, r], (_, p₁) ← simp r0, p₁ ← mk_app ``of_eq_true [p₁], (c, p₂) ← prove_lt simp c r e₂, p ← mk_app ``norm_num.int_div_helper [e₁, e₂, q, r, p, p₁, p₂], return (q, p) end | _ := failed end | `(%%e₁ % %%e₂) := do α ← infer_type e₁, c ← mk_instance_cache α, match α with | `(nat) := do n₁ ← e₁.to_nat, n₂ ← e₂.to_nat, q ← expr.of_nat α (n₁ / n₂), r ← expr.of_nat α (n₁ % n₂), (c, e₃) ← c.mk_app ``has_mul.mul [q, e₂], (c, e₃) ← c.mk_app ``has_add.add [r, e₃], (e₁', p) ← norm_num e₃, guard (e₁' =ₐ e₁), (c, p') ← prove_lt simp c r e₂, p ← mk_app ``norm_num.nat_mod_helper [e₁, e₂, q, r, p, p'], return (r, p) | `(int) := match e₂ with | `(- %%e₂') := do let p₁ := (expr.const ``int.mod_neg []).mk_app [e₁, e₂'], (c, e) ← c.mk_app ``has_mod.mod [e₁, e₂'], (e', p₂) ← simp e, p ← mk_eq_trans p₁ p₂, return (e', p) | _ := do n₁ ← e₁.to_int, n₂ ← e₂.to_int, q ← expr.of_rat α $ rat.of_int (n₁ / n₂), r ← expr.of_rat α $ rat.of_int (n₁ % n₂), (c, e₃) ← c.mk_app ``has_mul.mul [q, e₂], (c, e₃) ← c.mk_app ``has_add.add [r, e₃], (e₁', p) ← norm_num e₃, guard (e₁' =ₐ e₁), (c, r0) ← c.mk_app ``has_zero.zero [], (c, r0) ← c.mk_app ``has_le.le [r0, r], (_, p₁) ← simp r0, p₁ ← mk_app ``of_eq_true [p₁], (c, p₂) ← prove_lt simp c r e₂, p ← mk_app ``norm_num.int_mod_helper [e₁, e₂, q, r, p, p₁, p₂], return (r, p) end | _ := failed end | `(%%e₁ ∣ %%e₂) := do α ← infer_type e₁, c ← mk_instance_cache α, n ← match α with | `(nat) := return ``nat.dvd_iff_mod_eq_zero | `(int) := return ``int.dvd_iff_mod_eq_zero | _ := failed end, p₁ ← mk_app ``propext [@expr.const tt n [] e₁ e₂], (e', p₂) ← simp `(%%e₂ % %%e₁ = 0), p' ← mk_eq_trans p₁ p₂, return (e', p') | _ := failed lemma not_prime_helper (a b n : ℕ) (h : a * b = n) (h₁ : 1 < a) (h₂ : 1 < b) : ¬ nat.prime n := by rw ← h; exact nat.not_prime_mul h₁ h₂ lemma is_prime_helper (n : ℕ) (h₁ : 1 < n) (h₂ : nat.min_fac n = n) : nat.prime n := nat.prime_def_min_fac.2 ⟨h₁, h₂⟩ lemma min_fac_bit0 (n : ℕ) : nat.min_fac (bit0 n) = 2 := by simp [nat.min_fac_eq, show 2 ∣ bit0 n, by simp [bit0_eq_two_mul n]] def min_fac_helper (n k : ℕ) : Prop := 0 < k ∧ bit1 k ≤ nat.min_fac (bit1 n) theorem min_fac_helper.n_pos {n k : ℕ} (h : min_fac_helper n k) : 0 < n := nat.pos_iff_ne_zero.2 $ λ e, by rw e at h; exact not_le_of_lt (nat.bit1_lt h.1) h.2 lemma min_fac_ne_bit0 {n k : ℕ} : nat.min_fac (bit1 n) ≠ bit0 k := by rw bit0_eq_two_mul; exact λ e, absurd ((nat.dvd_add_iff_right (by simp [bit0_eq_two_mul n])).2 (dvd_trans ⟨_, e⟩ (nat.min_fac_dvd _))) dec_trivial lemma min_fac_helper_0 (n : ℕ) (h : 0 < n) : min_fac_helper n 1 := begin refine ⟨zero_lt_one, lt_of_le_of_ne _ min_fac_ne_bit0.symm⟩, refine @lt_of_le_of_ne ℕ _ _ _ (nat.min_fac_pos _) _, intro e, have := nat.min_fac_prime _, { rw ← e at this, exact nat.not_prime_one this }, { exact ne_of_gt (nat.bit1_lt h) } end lemma min_fac_helper_1 {n k k' : ℕ} (e : k + 1 = k') (np : nat.min_fac (bit1 n) ≠ bit1 k) (h : min_fac_helper n k) : min_fac_helper n k' := begin rw ← e, refine ⟨nat.succ_pos _, (lt_of_le_of_ne (lt_of_le_of_ne _ _ : k+1+k < _) min_fac_ne_bit0.symm : bit0 (k+1) < _)⟩, { rw add_right_comm, exact h.2 }, { rw add_right_comm, exact np.symm } end lemma min_fac_helper_2 (n k k' : ℕ) (e : k + 1 = k') (np : ¬ nat.prime (bit1 k)) (h : min_fac_helper n k) : min_fac_helper n k' := begin refine min_fac_helper_1 e _ h, intro e₁, rw ← e₁ at np, exact np (nat.min_fac_prime $ ne_of_gt $ nat.bit1_lt h.n_pos) end lemma min_fac_helper_3 (n k k' : ℕ) (e : k + 1 = k') (nd : bit1 k ∣ bit1 n = false) (h : min_fac_helper n k) : min_fac_helper n k' := begin refine min_fac_helper_1 e _ h, intro e₁, rw [eq_false, ← e₁] at nd, exact nd (nat.min_fac_dvd _) end lemma min_fac_helper_4 (n k : ℕ) (hd : bit1 k ∣ bit1 n = true) (h : min_fac_helper n k) : nat.min_fac (bit1 n) = bit1 k := by rw eq_true at hd; exact le_antisymm (nat.min_fac_le_of_dvd (nat.bit1_lt h.1) hd) h.2 lemma min_fac_helper_5 (n k k' : ℕ) (e : bit1 k * bit1 k = k') (hd : bit1 n < k') (h : min_fac_helper n k) : nat.min_fac (bit1 n) = bit1 n := begin refine (nat.prime_def_min_fac.1 (nat.prime_def_le_sqrt.2 ⟨nat.bit1_lt h.n_pos, _⟩)).2, rw ← e at hd, intros m m2 hm md, have := le_trans h.2 (le_trans (nat.min_fac_le_of_dvd m2 md) hm), rw nat.le_sqrt at this, exact not_le_of_lt hd this end meta def prove_non_prime (simp : expr → tactic (expr × expr)) (e : expr) (n d₁ : ℕ) : tactic expr := do let e₁ := reflect d₁, c ← mk_instance_cache `(nat), (c, p₁) ← prove_lt simp c `(1) e₁, let d₂ := n / d₁, let e₂ := reflect d₂, (e', p) ← mk_app ``has_mul.mul [e₁, e₂] >>= norm_num, guard (e' =ₐ e), (c, p₂) ← prove_lt simp c `(1) e₂, return $ (expr.const ``not_prime_helper []).mk_app [e₁, e₂, e, p, p₁, p₂] meta def prove_min_fac (simp : expr → tactic (expr × expr)) (e₁ : expr) (n1 : ℕ) : expr → expr → tactic (expr × expr) | e₂ p := do k ← e₂.to_nat, let k1 := bit1 k, e₁1 ← mk_app ``bit1 [e₁], e₂1 ← mk_app ``bit1 [e₂], if n1 < k1*k1 then do c ← mk_instance_cache `(nat), (c, e') ← c.mk_app ``has_mul.mul [e₂1, e₂1], (e', p₁) ← norm_num e', (c, p₂) ← prove_lt simp c e₁1 e', p' ← mk_app ``min_fac_helper_5 [e₁, e₂, e', p₁, p₂, p], return (e₁1, p') else let d := k1.min_fac in if to_bool (d < k1) then do (e', p₁) ← norm_num `(%%e₂ + 1), p₂ ← prove_non_prime simp e₂1 k1 d, mk_app ``min_fac_helper_2 [e₁, e₂, e', p₁, p₂, p] >>= prove_min_fac e' else do (_, p₂) ← simp `((%%e₂1 : ℕ) ∣ %%e₁1), if k1 ∣ n1 then do p' ← mk_app ``min_fac_helper_4 [e₁, e₂, p₂, p], return (e₂1, p') else do (e', p₁) ← norm_num `(%%e₂ + 1), mk_app ``min_fac_helper_3 [e₁, e₂, e', p₁, p₂, p] >>= prove_min_fac e' meta def eval_prime (simp : expr → tactic (expr × expr)) : expr → tactic (expr × expr) | `(nat.prime %%e) := do n ← e.to_nat, match n with | 0 := false_intro `(nat.not_prime_zero) | 1 := false_intro `(nat.not_prime_one) | _ := let d₁ := n.min_fac in if d₁ < n then prove_non_prime simp e n d₁ >>= false_intro else do let e₁ := reflect d₁, c ← mk_instance_cache `(nat), (c, p₁) ← prove_lt simp c `(1) e₁, (e₁, p) ← simp `(nat.min_fac %%e), true_intro $ (expr.const ``is_prime_helper []).mk_app [e, p₁, p] end | `(nat.min_fac 0) := refl_conv (reflect (0:ℕ)) | `(nat.min_fac 1) := refl_conv (reflect (1:ℕ)) | `(nat.min_fac (bit0 %%e)) := prod.mk `(2) <$> mk_app ``min_fac_bit0 [e] | `(nat.min_fac (bit1 %%e)) := do n ← e.to_nat, c ← mk_instance_cache `(nat), (c, p) ← prove_pos c e, mk_app ``min_fac_helper_0 [e, p] >>= prove_min_fac simp e (bit1 n) `(1) | _ := failed meta def derive1 (simp : expr → tactic (expr × expr)) (e : expr) : tactic (expr × expr) := norm_num e <|> eval_div_ext simp e <|> eval_pow simp e <|> eval_ineq simp e <|> eval_prime simp e meta def derive : expr → tactic (expr × expr) | e := do (_, e', pr) ← ext_simplify_core () {} simp_lemmas.mk (λ _, failed) (λ _ _ _ _ _, failed) (λ _ _ _ _ e, do (new_e, pr) ← derive1 derive e, guard (¬ new_e =ₐ e), return ((), new_e, some pr, tt)) `eq e, return (e', pr) end norm_num namespace tactic.interactive open norm_num interactive interactive.types /-- Basic version of `norm_num` that does not call `simp`. -/ meta def norm_num1 (loc : parse location) : tactic unit := do ns ← loc.get_locals, tt ← tactic.replace_at derive ns loc.include_goal | fail "norm_num failed to simplify", when loc.include_goal $ try tactic.triv, when (¬ ns.empty) $ try tactic.contradiction /-- Normalize numerical expressions. Supports the operations `+` `-` `*` `/` `^` `<` `≤` over ordered fields (or other appropriate classes), as well as `-` `/` `%` over `ℤ` and `ℕ`. -/ meta def norm_num (hs : parse simp_arg_list) (l : parse location) : tactic unit := repeat1 $ orelse' (norm_num1 l) $ simp_core {} (norm_num1 (loc.ns [none])) ff hs [] l meta def apply_normed (x : parse texpr) : tactic unit := do x₁ ← to_expr x, (x₂,_) ← derive x₁, tactic.exact x₂ end tactic.interactive namespace conv.interactive open conv interactive tactic.interactive open norm_num (derive) meta def norm_num1 : conv unit := replace_lhs derive meta def norm_num (hs : parse simp_arg_list) : conv unit := repeat1 $ orelse' norm_num1 $ simp_core {} norm_num1 ff hs [] (loc.ns [none]) end conv.interactive
347c5eb05eb848336389ca361283d55c2f859136
97f752b44fd85ec3f635078a2dd125ddae7a82b6
/library/data/finset/comb.lean
bc7b16df4cc0c27644a7687148ff25a3035d28de
[ "Apache-2.0" ]
permissive
tectronics/lean
ab977ba6be0fcd46047ddbb3c8e16e7c26710701
f38af35e0616f89c6e9d7e3eb1d48e47ee666efe
refs/heads/master
1,532,358,526,384
1,456,276,623,000
1,456,276,623,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
18,720
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura, Jeremy Avigad Combinators for finite sets. -/ import data.finset.basic logic.identities open list quot subtype decidable perm function namespace finset /- image (corresponds to map on list) -/ section image variables {A B : Type} variable [h : decidable_eq B] include h definition image (f : A → B) (s : finset A) : finset B := quot.lift_on s (λ l, to_finset (list.map f (elt_of l))) (λ l₁ l₂ p, quot.sound (perm_erase_dup_of_perm (perm_map _ p))) infix [priority finset.prio] `'` := image theorem image_empty (f : A → B) : image f ∅ = ∅ := rfl theorem mem_image_of_mem (f : A → B) {s : finset A} {a : A} : a ∈ s → f a ∈ image f s := quot.induction_on s (take l, assume H : a ∈ elt_of l, mem_to_finset (mem_map f H)) theorem mem_image {f : A → B} {s : finset A} {a : A} {b : B} (H1 : a ∈ s) (H2 : f a = b) : b ∈ image f s := eq.subst H2 (mem_image_of_mem f H1) theorem exists_of_mem_image {f : A → B} {s : finset A} {b : B} : b ∈ image f s → ∃a, a ∈ s ∧ f a = b := quot.induction_on s (take l, assume H : b ∈ erase_dup (list.map f (elt_of l)), exists_of_mem_map (mem_of_mem_erase_dup H)) theorem mem_image_iff (f : A → B) {s : finset A} {y : B} : y ∈ image f s ↔ ∃x, x ∈ s ∧ f x = y := iff.intro exists_of_mem_image (assume H, obtain x (H₁ : x ∈ s) (H₂ : f x = y), from H, mem_image H₁ H₂) theorem mem_image_eq (f : A → B) {s : finset A} {y : B} : y ∈ image f s = ∃x, x ∈ s ∧ f x = y := propext (mem_image_iff f) theorem mem_image_of_mem_image_of_subset {f : A → B} {s t : finset A} {y : B} (H1 : y ∈ image f s) (H2 : s ⊆ t) : y ∈ image f t := obtain x (H3: x ∈ s) (H4 : f x = y), from exists_of_mem_image H1, have H5 : x ∈ t, from mem_of_subset_of_mem H2 H3, show y ∈ image f t, from mem_image H5 H4 theorem image_insert [h' : decidable_eq A] (f : A → B) (s : finset A) (a : A) : image f (insert a s) = insert (f a) (image f s) := ext (take y, iff.intro (assume H : y ∈ image f (insert a s), obtain x (H1l : x ∈ insert a s) (H1r :f x = y), from exists_of_mem_image H, have x = a ∨ x ∈ s, from eq_or_mem_of_mem_insert H1l, or.elim this (suppose x = a, have f a = y, from eq.subst this H1r, show y ∈ insert (f a) (image f s), from eq.subst this !mem_insert) (suppose x ∈ s, have f x ∈ image f s, from mem_image_of_mem f this, show y ∈ insert (f a) (image f s), from eq.subst H1r (mem_insert_of_mem _ this))) (suppose y ∈ insert (f a) (image f s), have y = f a ∨ y ∈ image f s, from eq_or_mem_of_mem_insert this, or.elim this (suppose y = f a, have f a ∈ image f (insert a s), from mem_image_of_mem f !mem_insert, show y ∈ image f (insert a s), from eq.subst (eq.symm `y = f a`) this) (suppose y ∈ image f s, show y ∈ image f (insert a s), from mem_image_of_mem_image_of_subset this !subset_insert))) lemma image_comp {C : Type} [deceqC : decidable_eq C] {f : B → C} {g : A → B} {s : finset A} : image (f∘g) s = image f (image g s) := ext (take z, iff.intro (suppose z ∈ image (f∘g) s, obtain x (Hx : x ∈ s) (Hgfx : f (g x) = z), from exists_of_mem_image this, by rewrite -Hgfx; apply mem_image_of_mem _ (mem_image_of_mem _ Hx)) (suppose z ∈ image f (image g s), obtain y (Hy : y ∈ image g s) (Hfy : f y = z), from exists_of_mem_image this, obtain x (Hx : x ∈ s) (Hgx : g x = y), from exists_of_mem_image Hy, mem_image Hx (by esimp; rewrite [Hgx, Hfy]))) lemma image_subset {a b : finset A} (f : A → B) (H : a ⊆ b) : f ' a ⊆ f ' b := subset_of_forall (take y, assume Hy : y ∈ f ' a, obtain x (Hx₁ : x ∈ a) (Hx₂ : f x = y), from exists_of_mem_image Hy, mem_image (mem_of_subset_of_mem H Hx₁) Hx₂) theorem image_union [h' : decidable_eq A] (f : A → B) (s t : finset A) : image f (s ∪ t) = image f s ∪ image f t := ext (take y, iff.intro (assume H : y ∈ image f (s ∪ t), obtain x [(xst : x ∈ s ∪ t) (fxy : f x = y)], from exists_of_mem_image H, or.elim (mem_or_mem_of_mem_union xst) (assume xs, mem_union_l (mem_image xs fxy)) (assume xt, mem_union_r (mem_image xt fxy))) (assume H : y ∈ image f s ∪ image f t, or.elim (mem_or_mem_of_mem_union H) (assume yifs : y ∈ image f s, obtain x [(xs : x ∈ s) (fxy : f x = y)], from exists_of_mem_image yifs, mem_image (mem_union_l xs) fxy) (assume yift : y ∈ image f t, obtain x [(xt : x ∈ t) (fxy : f x = y)], from exists_of_mem_image yift, mem_image (mem_union_r xt) fxy))) end image /- separation and set-builder notation -/ section sep variables {A : Type} [deceq : decidable_eq A] include deceq variables (p : A → Prop) [decp : decidable_pred p] (s : finset A) {x : A} include decp definition sep : finset A := quot.lift_on s (λl, to_finset_of_nodup (list.filter p (subtype.elt_of l)) (list.nodup_filter p (subtype.has_property l))) (λ l₁ l₂ u, quot.sound (perm.perm_filter u)) notation [priority finset.prio] `{` binder ` ∈ ` s ` | ` r:(scoped:1 p, sep p s) `}` := r theorem sep_empty : sep p ∅ = ∅ := rfl variables {p s} theorem of_mem_sep : x ∈ sep p s → p x := quot.induction_on s (take l, list.of_mem_filter) theorem mem_of_mem_sep : x ∈ sep p s → x ∈ s := quot.induction_on s (take l, list.mem_of_mem_filter) theorem mem_sep_of_mem {x : A} : x ∈ s → p x → x ∈ sep p s := quot.induction_on s (take l, list.mem_filter_of_mem) variables (p s) theorem mem_sep_iff : x ∈ sep p s ↔ x ∈ s ∧ p x := iff.intro (assume H, and.intro (mem_of_mem_sep H) (of_mem_sep H)) (assume H, mem_sep_of_mem (and.left H) (and.right H)) theorem mem_sep_eq : x ∈ sep p s = (x ∈ s ∧ p x) := propext !mem_sep_iff variable t : finset A theorem mem_sep_union_iff : x ∈ sep p (s ∪ t) ↔ x ∈ sep p s ∨ x ∈ sep p t := by rewrite [*mem_sep_iff, mem_union_iff, and.right_distrib] end sep section variables {A : Type} [deceqA : decidable_eq A] include deceqA theorem eq_sep_of_subset {s t : finset A} (ssubt : s ⊆ t) : s = {x ∈ t | x ∈ s} := ext (take x, iff.intro (suppose x ∈ s, mem_sep_of_mem (mem_of_subset_of_mem ssubt this) this) (suppose x ∈ {x ∈ t | x ∈ s}, of_mem_sep this)) end /- set difference -/ section diff variables {A : Type} [deceq : decidable_eq A] include deceq definition diff (s t : finset A) : finset A := {x ∈ s | x ∉ t} infix [priority finset.prio] ` \ `:70 := diff theorem mem_of_mem_diff {s t : finset A} {x : A} (H : x ∈ s \ t) : x ∈ s := mem_of_mem_sep H theorem not_mem_of_mem_diff {s t : finset A} {x : A} (H : x ∈ s \ t) : x ∉ t := of_mem_sep H theorem mem_diff {s t : finset A} {x : A} (H1 : x ∈ s) (H2 : x ∉ t) : x ∈ s \ t := mem_sep_of_mem H1 H2 theorem mem_diff_iff (s t : finset A) (x : A) : x ∈ s \ t ↔ x ∈ s ∧ x ∉ t := iff.intro (assume H, and.intro (mem_of_mem_diff H) (not_mem_of_mem_diff H)) (assume H, mem_diff (and.left H) (and.right H)) theorem mem_diff_eq (s t : finset A) (x : A) : x ∈ s \ t = (x ∈ s ∧ x ∉ t) := propext !mem_diff_iff theorem union_diff_cancel {s t : finset A} (H : s ⊆ t) : s ∪ (t \ s) = t := ext (take x, iff.intro (suppose x ∈ s ∪ (t \ s), or.elim (mem_or_mem_of_mem_union this) (suppose x ∈ s, mem_of_subset_of_mem H this) (suppose x ∈ t \ s, mem_of_mem_diff this)) (suppose x ∈ t, decidable.by_cases (suppose x ∈ s, mem_union_left _ this) (suppose x ∉ s, mem_union_right _ (mem_diff `x ∈ t` this)))) theorem diff_union_cancel {s t : finset A} (H : s ⊆ t) : (t \ s) ∪ s = t := eq.subst !union_comm (!union_diff_cancel H) end diff /- set complement -/ section complement variables {A : Type} [deceqA : decidable_eq A] [h : fintype A] include deceqA h definition compl (s : finset A) : finset A := univ \ s prefix [priority finset.prio] - := compl theorem mem_compl {s : finset A} {x : A} (H : x ∉ s) : x ∈ -s := mem_diff !mem_univ H theorem not_mem_of_mem_compl {s : finset A} {x : A} (H : x ∈ -s) : x ∉ s := not_mem_of_mem_diff H theorem mem_compl_iff (s : finset A) (x : A) : x ∈ -s ↔ x ∉ s := iff.intro not_mem_of_mem_compl mem_compl section open classical theorem union_eq_compl_compl_inter_compl (s t : finset A) : s ∪ t = -(-s ∩ -t) := ext (take x, by rewrite [mem_union_iff, mem_compl_iff, mem_inter_iff, *mem_compl_iff, or_iff_not_and_not]) theorem inter_eq_compl_compl_union_compl (s t : finset A) : s ∩ t = -(-s ∪ -t) := ext (take x, by rewrite [mem_inter_iff, mem_compl_iff, mem_union_iff, *mem_compl_iff, and_iff_not_or_not]) end end complement /- all -/ section all variables {A : Type} definition all (s : finset A) (p : A → Prop) : Prop := quot.lift_on s (λ l, all (elt_of l) p) (λ l₁ l₂ p, foldr_eq_of_perm (λ a₁ a₂ q, propext !and.left_comm) p true) theorem all_empty (p : A → Prop) : all ∅ p = true := rfl theorem of_mem_of_all {p : A → Prop} {a : A} {s : finset A} : a ∈ s → all s p → p a := quot.induction_on s (λ l i h, list.of_mem_of_all i h) theorem forall_of_all {p : A → Prop} {s : finset A} (H : all s p) : ∀{a}, a ∈ s → p a := λ a H', of_mem_of_all H' H theorem all_of_forall {p : A → Prop} {s : finset A} : (∀a, a ∈ s → p a) → all s p := quot.induction_on s (λ l H, list.all_of_forall H) theorem all_iff_forall (p : A → Prop) (s : finset A) : all s p ↔ (∀a, a ∈ s → p a) := iff.intro forall_of_all all_of_forall definition decidable_all [instance] (p : A → Prop) [h : decidable_pred p] (s : finset A) : decidable (all s p) := quot.rec_on_subsingleton s (λ l, list.decidable_all p (elt_of l)) theorem all_implies {p q : A → Prop} {s : finset A} : all s p → (∀ x, p x → q x) → all s q := quot.induction_on s (λ l h₁ h₂, list.all_implies h₁ h₂) variable [h : decidable_eq A] include h theorem all_union {p : A → Prop} {s₁ s₂ : finset A} : all s₁ p → all s₂ p → all (s₁ ∪ s₂) p := quot.induction_on₂ s₁ s₂ (λ l₁ l₂ a₁ a₂, all_union a₁ a₂) theorem all_of_all_union_left {p : A → Prop} {s₁ s₂ : finset A} : all (s₁ ∪ s₂) p → all s₁ p := quot.induction_on₂ s₁ s₂ (λ l₁ l₂ a, list.all_of_all_union_left a) theorem all_of_all_union_right {p : A → Prop} {s₁ s₂ : finset A} : all (s₁ ∪ s₂) p → all s₂ p := quot.induction_on₂ s₁ s₂ (λ l₁ l₂ a, list.all_of_all_union_right a) theorem all_insert_of_all {p : A → Prop} {a : A} {s : finset A} : p a → all s p → all (insert a s) p := quot.induction_on s (λ l h₁ h₂, list.all_insert_of_all h₁ h₂) theorem all_erase_of_all {p : A → Prop} (a : A) {s : finset A}: all s p → all (erase a s) p := quot.induction_on s (λ l h, list.all_erase_of_all a h) theorem all_inter_of_all_left {p : A → Prop} {s₁ : finset A} (s₂ : finset A) : all s₁ p → all (s₁ ∩ s₂) p := quot.induction_on₂ s₁ s₂ (λ l₁ l₂ h, list.all_inter_of_all_left _ h) theorem all_inter_of_all_right {p : A → Prop} {s₁ : finset A} (s₂ : finset A) : all s₂ p → all (s₁ ∩ s₂) p := quot.induction_on₂ s₁ s₂ (λ l₁ l₂ h, list.all_inter_of_all_right _ h) theorem subset_iff_all (s t : finset A) : s ⊆ t ↔ all s (λ x, x ∈ t) := iff.intro (suppose s ⊆ t, all_of_forall (take x, suppose x ∈ s, mem_of_subset_of_mem `s ⊆ t` `x ∈ s`)) (suppose all s (λ x, x ∈ t), subset_of_forall (take x, suppose x ∈ s, of_mem_of_all `x ∈ s` `all s (λ x, x ∈ t)`)) definition decidable_subset [instance] (s t : finset A) : decidable (s ⊆ t) := decidable_of_decidable_of_iff _ (iff.symm !subset_iff_all) end all /- any -/ section any variables {A : Type} definition any (s : finset A) (p : A → Prop) : Prop := quot.lift_on s (λ l, any (elt_of l) p) (λ l₁ l₂ p, foldr_eq_of_perm (λ a₁ a₂ q, propext !or.left_comm) p false) theorem any_empty (p : A → Prop) : any ∅ p = false := rfl theorem exists_of_any {p : A → Prop} {s : finset A} : any s p → ∃a, a ∈ s ∧ p a := quot.induction_on s (λ l H, list.exists_of_any H) theorem any_of_mem {p : A → Prop} {s : finset A} {a : A} : a ∈ s → p a → any s p := quot.induction_on s (λ l H1 H2, list.any_of_mem H1 H2) theorem any_of_exists {p : A → Prop} {s : finset A} (H : ∃a, a ∈ s ∧ p a) : any s p := obtain a H₁ H₂, from H, any_of_mem H₁ H₂ theorem any_iff_exists (p : A → Prop) (s : finset A) : any s p ↔ (∃a, a ∈ s ∧ p a) := iff.intro exists_of_any any_of_exists theorem any_of_insert [h : decidable_eq A] {p : A → Prop} (s : finset A) {a : A} (H : p a) : any (insert a s) p := any_of_mem (mem_insert a s) H theorem any_of_insert_right [h : decidable_eq A] {p : A → Prop} {s : finset A} (a : A) (H : any s p) : any (insert a s) p := obtain b (H₁ : b ∈ s) (H₂ : p b), from exists_of_any H, any_of_mem (mem_insert_of_mem a H₁) H₂ definition decidable_any [instance] (p : A → Prop) [h : decidable_pred p] (s : finset A) : decidable (any s p) := quot.rec_on_subsingleton s (λ l, list.decidable_any p (elt_of l)) end any section product variables {A B : Type} definition product (s₁ : finset A) (s₂ : finset B) : finset (A × B) := quot.lift_on₂ s₁ s₂ (λ l₁ l₂, to_finset_of_nodup (product (elt_of l₁) (elt_of l₂)) (nodup_product (has_property l₁) (has_property l₂))) (λ v₁ v₂ w₁ w₂ p₁ p₂, begin apply @quot.sound, apply perm_product p₁ p₂ end) infix [priority finset.prio] * := product theorem empty_product (s : finset B) : @empty A * s = ∅ := quot.induction_on s (λ l, rfl) theorem mem_product {a : A} {b : B} {s₁ : finset A} {s₂ : finset B} : a ∈ s₁ → b ∈ s₂ → (a, b) ∈ s₁ * s₂ := quot.induction_on₂ s₁ s₂ (λ l₁ l₂ i₁ i₂, list.mem_product i₁ i₂) theorem mem_of_mem_product_left {a : A} {b : B} {s₁ : finset A} {s₂ : finset B} : (a, b) ∈ s₁ * s₂ → a ∈ s₁ := quot.induction_on₂ s₁ s₂ (λ l₁ l₂ i, list.mem_of_mem_product_left i) theorem mem_of_mem_product_right {a : A} {b : B} {s₁ : finset A} {s₂ : finset B} : (a, b) ∈ s₁ * s₂ → b ∈ s₂ := quot.induction_on₂ s₁ s₂ (λ l₁ l₂ i, list.mem_of_mem_product_right i) theorem product_empty (s : finset A) : s * @empty B = ∅ := ext (λ p, match p with | (a, b) := iff.intro (λ i, absurd (mem_of_mem_product_right i) !not_mem_empty) (λ i, absurd i !not_mem_empty) end) end product /- powerset -/ section powerset variables {A : Type} [deceqA : decidable_eq A] include deceqA section list_powerset open list definition list_powerset : list A → finset (finset A) | [] := '{∅} | (a :: l) := list_powerset l ∪ image (insert a) (list_powerset l) end list_powerset private theorem image_insert_comm (a b : A) (s : finset (finset A)) : image (insert a) (image (insert b) s) = image (insert b) (image (insert a) s) := have aux' : ∀ a b : A, ∀ x : finset A, x ∈ image (insert a) (image (insert b) s) → x ∈ image (insert b) (image (insert a) s), from begin intros [a, b, x, H], cases (exists_of_mem_image H) with [y, Hy], cases Hy with [Hy1, Hy2], cases (exists_of_mem_image Hy1) with [z, Hz], cases Hz with [Hz1, Hz2], substvars, rewrite insert.comm, repeat (apply mem_image_of_mem), assumption end, ext (take x, iff.intro (aux' a b x) (aux' b a x)) theorem list_powerset_eq_list_powerset_of_perm {l₁ l₂ : list A} (p : l₁ ~ l₂) : list_powerset l₁ = list_powerset l₂ := perm.induction_on p rfl (λ x l₁ l₂ p ih, by rewrite [↑list_powerset, ih]) (λ x y l, by rewrite [↑list_powerset, ↑list_powerset, *image_union, image_insert_comm, *union_assoc, union_left_comm (finset.image (finset.insert x) _)]) (λ l₁ l₂ l₃ p₁ p₂ r₁ r₂, eq.trans r₁ r₂) definition powerset (s : finset A) : finset (finset A) := quot.lift_on s (λ l, list_powerset (elt_of l)) (λ l₁ l₂ p, list_powerset_eq_list_powerset_of_perm p) prefix [priority finset.prio] `𝒫`:100 := powerset theorem powerset_empty : 𝒫 (∅ : finset A) = '{∅} := rfl theorem powerset_insert {a : A} {s : finset A} : a ∉ s → 𝒫 (insert a s) = 𝒫 s ∪ image (insert a) (𝒫 s) := quot.induction_on s (λ l, assume H : a ∉ quot.mk l, calc 𝒫 (insert a (quot.mk l)) = list_powerset (list.insert a (elt_of l)) : rfl ... = list_powerset (#list a :: elt_of l) : by rewrite [list.insert_eq_of_not_mem H] ... = 𝒫 (quot.mk l) ∪ image (insert a) (𝒫 (quot.mk l)) : rfl) theorem mem_powerset_iff_subset (s : finset A) : ∀ x, x ∈ 𝒫 s ↔ x ⊆ s := begin induction s with a s nains ih, intro x, rewrite powerset_empty, show x ∈ '{∅} ↔ x ⊆ ∅, by rewrite [mem_singleton_iff, subset_empty_iff], intro x, rewrite [powerset_insert nains, mem_union_iff, ih, mem_image_iff], exact (iff.intro (assume H, or.elim H (suppose x ⊆ s, subset.trans this !subset_insert) (suppose ∃ y, y ∈ 𝒫 s ∧ insert a y = x, obtain y [yps iay], from this, show x ⊆ insert a s, begin rewrite [-iay], apply insert_subset_insert, rewrite -ih, apply yps end)) (assume H : x ⊆ insert a s, assert H' : erase a x ⊆ s, from erase_subset_of_subset_insert H, decidable.by_cases (suppose a ∈ x, or.inr (exists.intro (erase a x) (and.intro (show erase a x ∈ 𝒫 s, by rewrite ih; apply H') (show insert a (erase a x) = x, from insert_erase this)))) (suppose a ∉ x, or.inl (show x ⊆ s, by rewrite [(erase_eq_of_not_mem this) at H']; apply H')))) end theorem subset_of_mem_powerset {s t : finset A} (H : s ∈ 𝒫 t) : s ⊆ t := iff.mp (mem_powerset_iff_subset t s) H theorem mem_powerset_of_subset {s t : finset A} (H : s ⊆ t) : s ∈ 𝒫 t := iff.mpr (mem_powerset_iff_subset t s) H theorem empty_mem_powerset (s : finset A) : ∅ ∈ 𝒫 s := mem_powerset_of_subset (empty_subset s) end powerset end finset
69254f884cdd60e4b3a3529d0837d694ad815a43
63abd62053d479eae5abf4951554e1064a4c45b4
/src/category_theory/limits/fubini.lean
858026bbeb8757695102a3da232e3d4ac0b8d3d4
[ "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,048
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 category_theory.limits.limits import category_theory.products.basic import category_theory.currying /-! # A Fubini theorem for categorical limits We prove that $lim_{J × K} G = lim_J (lim_K G(j, -))$ for a functor `G : J × K ⥤ C`, when all the appropriate limits exist. We begin working with a functor `F : J ⥤ K ⥤ C`. We'll write `G : J × K ⥤ C` for the associated "uncurried" functor. In the first part, given a coherent family `D` of limit cones over the functors `F.obj j`, and a cone `c` over `G`, we construct a cone over the cone points of `D`. We then show that if `c` is a limit cone, the constructed cone is also a limit cone. In the second part, we state the Fubini theorem in the setting where limits are provided by suitable `has_limit` classes. We construct `limit_uncurry_iso_limit_comp_lim F : limit (uncurry.obj F) ≅ limit (F ⋙ lim)` and give simp lemmas characterising it. For convenience, we also provide `limit_iso_limit_curry_comp_lim G : limit G ≅ limit ((curry.obj G) ⋙ lim)` in terms of the uncurried functor. ## Future work The dual statement. -/ universes v u open category_theory namespace category_theory.limits variables {J K : Type v} [small_category J] [small_category K] variables {C : Type u} [category.{v} C] variables (F : J ⥤ K ⥤ C) /-- A structure carrying a diagram of cones over the the functors `F.obj j`. -/ -- We could try introducing a "dependent functor type" to handle this? structure diagram_of_cones := (obj : Π j : J, cone (F.obj j)) (map : Π {j j' : J} (f : j ⟶ j'), (cones.postcompose (F.map f)).obj (obj j) ⟶ obj j') (id : ∀ j : J, (map (𝟙 j)).hom = 𝟙 _ . obviously) (comp : ∀ {j₁ j₂ j₃ : J} (f : j₁ ⟶ j₂) (g : j₂ ⟶ j₃), (map (f ≫ g)).hom = (map f).hom ≫ (map g).hom . obviously) variables {F} /-- Extract the functor `J ⥤ C` consisting of the cone points and the maps between them, from a `diagram_of_cones`. -/ @[simps] def diagram_of_cones.cone_points (D : diagram_of_cones F) : J ⥤ C := { obj := λ j, (D.obj j).X, map := λ j j' f, (D.map f).hom, map_id' := λ j, D.id j, map_comp' := λ j₁ j₂ j₃ f g, D.comp f g, } /-- Given a diagram `D` of limit cones over the `F.obj j`, and a cone over `uncurry.obj F`, we can construct a cone over the diagram consisting of the cone points from `D`. -/ @[simps] def cone_of_cone_uncurry {D : diagram_of_cones F} (Q : Π j, is_limit (D.obj j)) (c : cone (uncurry.obj F)) : cone (D.cone_points) := { X := c.X, π := { app := λ j, (Q j).lift { X := c.X, π := { app := λ k, c.π.app (j, k), naturality' := λ k k' f, begin dsimp, simp only [category.id_comp], have := @nat_trans.naturality _ _ _ _ _ _ c.π (j, k) (j, k') (𝟙 j, f), dsimp at this, simp only [category.id_comp, category_theory.functor.map_id, nat_trans.id_app] at this, exact this, end } }, naturality' := λ j j' f, (Q j').hom_ext begin dsimp, intro k, simp only [limits.cone_morphism.w, limits.cones.postcompose_obj_π, limits.is_limit.fac_assoc, limits.is_limit.fac, nat_trans.comp_app, category.id_comp, category.assoc], have := @nat_trans.naturality _ _ _ _ _ _ c.π (j, k) (j', k) (f, 𝟙 k), dsimp at this, simp only [category.id_comp, category.comp_id, category_theory.functor.map_id, nat_trans.id_app] at this, exact this, end, } }. /-- `cone_of_cone_uncurry Q c` is a limit cone when `c` is a limit cone.` -/ def cone_of_cone_uncurry_is_limit {D : diagram_of_cones F} (Q : Π j, is_limit (D.obj j)) {c : cone (uncurry.obj F)} (P : is_limit c) : is_limit (cone_of_cone_uncurry Q c) := { lift := λ s, P.lift { X := s.X, π := { app := λ p, s.π.app p.1 ≫ (D.obj p.1).π.app p.2, naturality' := λ p p' f, begin dsimp, simp only [category.id_comp, category.assoc], rcases p with ⟨j, k⟩, rcases p' with ⟨j', k'⟩, rcases f with ⟨fj, fk⟩, dsimp, slice_rhs 3 4 { rw ←nat_trans.naturality, }, slice_rhs 2 3 { rw ←(D.obj j).π.naturality, }, simp only [functor.const.obj_map, category.id_comp, category.assoc], have w := (D.map fj).w k', dsimp at w, rw ←w, have n := s.π.naturality fj, dsimp at n, simp only [category.id_comp] at n, rw n, simp, end, } }, fac' := λ s j, begin apply (Q j).hom_ext, intro k, simp, end, uniq' := λ s m w, begin refine P.uniq { X := s.X, π := _, } m _, rintro ⟨j, k⟩, dsimp, rw [←w j], simp, end, } section variables (F) variables [has_limits_of_shape K C] /-- Given a functor `F : J ⥤ K ⥤ C`, with all needed limits, we can construct a diagram consisting of the limit cone over each functor `F.obj j`, and the universal cone morphisms between these. -/ @[simps] noncomputable def diagram_of_cones.mk_of_has_limits : diagram_of_cones F := { obj := λ j, limit.cone (F.obj j), map := λ j j' f, { hom := lim.map (F.map f), }, } -- Satisfying the inhabited linter. noncomputable instance diagram_of_cones_inhabited : inhabited (diagram_of_cones F) := ⟨diagram_of_cones.mk_of_has_limits F⟩ @[simp] lemma diagram_of_cones.mk_of_has_limits_cone_points : (diagram_of_cones.mk_of_has_limits F).cone_points = (F ⋙ lim) := rfl variables [has_limit (uncurry.obj F)] variables [has_limit (F ⋙ lim)] /-- The Fubini theorem for a functor `F : J ⥤ K ⥤ C`, showing that the limit of `uncurry.obj F` can be computed as the limit of the limits of the functors `F.obj j`. -/ noncomputable def limit_uncurry_iso_limit_comp_lim : limit (uncurry.obj F) ≅ limit (F ⋙ lim) := begin let c := limit.cone (uncurry.obj F), let P : is_limit c := limit.is_limit _, let G := diagram_of_cones.mk_of_has_limits F, let Q : Π j, is_limit (G.obj j) := λ j, limit.is_limit _, have Q' := cone_of_cone_uncurry_is_limit Q P, have Q'' := (limit.is_limit (F ⋙ lim)), exact is_limit.cone_point_unique_up_to_iso Q' Q'', end @[simp] lemma limit_uncurry_iso_limit_comp_lim_hom_π_π {j} {k} : (limit_uncurry_iso_limit_comp_lim F).hom ≫ limit.π _ j ≫ limit.π _ k = limit.π _ (j, k) := begin dsimp [limit_uncurry_iso_limit_comp_lim, is_limit.cone_point_unique_up_to_iso, is_limit.unique_up_to_iso], simp, end @[simp] lemma limit_uncurry_iso_limit_comp_lim_inv_π {j} {k} : (limit_uncurry_iso_limit_comp_lim F).inv ≫ limit.π _ (j, k) = limit.π _ j ≫ limit.π _ k := begin rw [←cancel_epi (limit_uncurry_iso_limit_comp_lim F).hom], simp, end end section variables (G : J × K ⥤ C) section variables [has_limits_of_shape K C] variables [has_limit G] variables [has_limit ((curry.obj G) ⋙ lim)] /-- The Fubini theorem for a functor `G : J × K ⥤ C`, showing that the limit of `G` can be computed as the limit of the limits of the functors `G.obj (j, _)`. -/ noncomputable def limit_iso_limit_curry_comp_lim : limit G ≅ limit ((curry.obj G) ⋙ lim) := begin have i : G ≅ uncurry.obj ((@curry J _ K _ C _).obj G) := currying.symm.unit_iso.app G, haveI : limits.has_limit (uncurry.obj ((@curry J _ K _ C _).obj G)) := has_limit_of_iso i, transitivity limit (uncurry.obj ((@curry J _ K _ C _).obj G)), apply has_limit.iso_of_nat_iso i, exact limit_uncurry_iso_limit_comp_lim ((@curry J _ K _ C _).obj G), end @[simp,reassoc] lemma limit_iso_limit_curry_comp_lim_hom_π_π {j} {k} : (limit_iso_limit_curry_comp_lim G).hom ≫ limit.π _ j ≫ limit.π _ k = limit.π _ (j, k) := begin dsimp [limit_iso_limit_curry_comp_lim, is_limit.cone_point_unique_up_to_iso, is_limit.unique_up_to_iso], simp, dsimp, simp, -- See note [dsimp, simp]. end @[simp,reassoc] lemma limit_iso_limit_curry_comp_lim_inv_π {j} {k} : (limit_iso_limit_curry_comp_lim G).inv ≫ limit.π _ (j, k) = limit.π _ j ≫ limit.π _ k := begin rw [←cancel_epi (limit_iso_limit_curry_comp_lim G).hom], simp, end end section variables [has_limits C] -- Certainly one could weaken the hypotheses here. open category_theory.prod /-- A variant of the Fubini theorem for a functor `G : J × K ⥤ C`, showing that $\lim_k \lim_j G(j,k) ≅ \lim_j \lim_k G(j,k)$. -/ noncomputable def limit_curry_swap_comp_lim_iso_limit_curry_comp_lim : limit ((curry.obj (swap K J ⋙ G)) ⋙ lim) ≅ limit ((curry.obj G) ⋙ lim) := calc limit ((curry.obj (swap K J ⋙ G)) ⋙ lim) ≅ limit (swap K J ⋙ G) : (limit_iso_limit_curry_comp_lim _).symm ... ≅ limit G : has_limit.iso_of_equivalence (braiding K J) (iso.refl _) ... ≅ limit ((curry.obj G) ⋙ lim) : limit_iso_limit_curry_comp_lim _ @[simp] lemma limit_curry_swap_comp_lim_iso_limit_curry_comp_lim_hom_π_π {j} {k} : (limit_curry_swap_comp_lim_iso_limit_curry_comp_lim G).hom ≫ limit.π _ j ≫ limit.π _ k = limit.π _ k ≫ limit.π _ j := begin dsimp [limit_curry_swap_comp_lim_iso_limit_curry_comp_lim], simp only [iso.refl_hom, braiding_counit_iso_hom_app, limits.has_limit.iso_of_equivalence_hom_π, iso.refl_inv, limit_iso_limit_curry_comp_lim_hom_π_π, eq_to_iso_refl, category.assoc], erw [nat_trans.id_app], -- Why can't `simp` do this`? dsimp, simp, end @[simp] lemma limit_curry_swap_comp_lim_iso_limit_curry_comp_lim_inv_π_π {j} {k} : (limit_curry_swap_comp_lim_iso_limit_curry_comp_lim G).inv ≫ limit.π _ k ≫ limit.π _ j = limit.π _ j ≫ limit.π _ k := begin dsimp [limit_curry_swap_comp_lim_iso_limit_curry_comp_lim], simp only [iso.refl_hom, braiding_counit_iso_hom_app, limits.has_limit.iso_of_equivalence_inv_π, iso.refl_inv, limit_iso_limit_curry_comp_lim_hom_π_π, eq_to_iso_refl, category.assoc], erw [nat_trans.id_app], -- Why can't `simp` do this`? dsimp, simp, end end end end category_theory.limits
b01f16bee8571649d5ba36f1f3ac6932f2a7cb76
4727251e0cd73359b15b664c3170e5d754078599
/src/analysis/inner_product_space/rayleigh.lean
c90384af7aea6487515c1019d655ac5f2081723f
[ "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
12,730
lean
/- Copyright (c) 2021 Heather Macbeth. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Heather Macbeth, Frédéric Dupuis -/ import analysis.inner_product_space.calculus import analysis.inner_product_space.dual import analysis.calculus.lagrange_multipliers import linear_algebra.eigenspace /-! # The Rayleigh quotient The Rayleigh quotient of a self-adjoint operator `T` on an inner product space `E` is the function `λ x, ⟪T x, x⟫ / ∥x∥ ^ 2`. The main results of this file are `is_self_adjoint.has_eigenvector_of_is_max_on` and `is_self_adjoint.has_eigenvector_of_is_min_on`, which state that if `E` is complete, and if the Rayleigh quotient attains its global maximum/minimum over some sphere at the point `x₀`, then `x₀` is an eigenvector of `T`, and the `supr`/`infi` of `λ x, ⟪T x, x⟫ / ∥x∥ ^ 2` is the corresponding eigenvalue. The corollaries `is_self_adjoint.has_eigenvalue_supr_of_finite_dimensional` and `is_self_adjoint.has_eigenvalue_supr_of_finite_dimensional` state that if `E` is finite-dimensional and nontrivial, then `T` has some (nonzero) eigenvectors with eigenvalue the `supr`/`infi` of `λ x, ⟪T x, x⟫ / ∥x∥ ^ 2`. ## TODO A slightly more elaborate corollary is that if `E` is complete and `T` is a compact operator, then `T` has some (nonzero) eigenvector with eigenvalue either `⨆ x, ⟪T x, x⟫ / ∥x∥ ^ 2` or `⨅ x, ⟪T x, x⟫ / ∥x∥ ^ 2` (not necessarily both). -/ variables {𝕜 : Type*} [is_R_or_C 𝕜] variables {E : Type*} [inner_product_space 𝕜 E] local notation `⟪`x`, `y`⟫` := @inner 𝕜 _ _ x y open_locale nnreal open module.End metric namespace continuous_linear_map variables (T : E →L[𝕜] E) local notation `rayleigh_quotient` := λ x : E, T.re_apply_inner_self x / ∥(x:E)∥ ^ 2 lemma rayleigh_smul (x : E) {c : 𝕜} (hc : c ≠ 0) : rayleigh_quotient (c • x) = rayleigh_quotient x := begin by_cases hx : x = 0, { simp [hx] }, have : ∥c∥ ≠ 0 := by simp [hc], have : ∥x∥ ≠ 0 := by simp [hx], field_simp [norm_smul, T.re_apply_inner_self_smul], ring end lemma image_rayleigh_eq_image_rayleigh_sphere {r : ℝ} (hr : 0 < r) : rayleigh_quotient '' {0}ᶜ = rayleigh_quotient '' (sphere 0 r) := begin ext a, split, { rintros ⟨x, (hx : x ≠ 0), hxT⟩, have : ∥x∥ ≠ 0 := by simp [hx], let c : 𝕜 := ↑∥x∥⁻¹ * r, have : c ≠ 0 := by simp [c, hx, hr.ne'], refine ⟨c • x, _, _⟩, { field_simp [norm_smul, is_R_or_C.norm_eq_abs, abs_of_nonneg hr.le] }, { rw T.rayleigh_smul x this, exact hxT } }, { rintros ⟨x, hx, hxT⟩, exact ⟨x, ne_zero_of_mem_sphere hr.ne' ⟨x, hx⟩, hxT⟩ }, end lemma supr_rayleigh_eq_supr_rayleigh_sphere {r : ℝ} (hr : 0 < r) : (⨆ x : {x : E // x ≠ 0}, rayleigh_quotient x) = ⨆ x : sphere (0:E) r, rayleigh_quotient x := show (⨆ x : ({0} : set E)ᶜ, rayleigh_quotient x) = _, by simp only [@csupr_set _ _ _ _ rayleigh_quotient, T.image_rayleigh_eq_image_rayleigh_sphere hr] lemma infi_rayleigh_eq_infi_rayleigh_sphere {r : ℝ} (hr : 0 < r) : (⨅ x : {x : E // x ≠ 0}, rayleigh_quotient x) = ⨅ x : sphere (0:E) r, rayleigh_quotient x := show (⨅ x : ({0} : set E)ᶜ, rayleigh_quotient x) = _, by simp only [@cinfi_set _ _ _ _ rayleigh_quotient, T.image_rayleigh_eq_image_rayleigh_sphere hr] end continuous_linear_map namespace inner_product_space namespace is_self_adjoint section real variables {F : Type*} [inner_product_space ℝ F] lemma has_strict_fderiv_at_re_apply_inner_self {T : F →L[ℝ] F} (hT : is_self_adjoint (T : F →ₗ[ℝ] F)) (x₀ : F) : has_strict_fderiv_at T.re_apply_inner_self (bit0 (innerSL (T x₀))) x₀ := begin convert T.has_strict_fderiv_at.inner (has_strict_fderiv_at_id x₀), ext y, simp [bit0, hT.apply_clm x₀ y, real_inner_comm x₀] end variables [complete_space F] {T : F →L[ℝ] F} local notation `rayleigh_quotient` := λ x : F, T.re_apply_inner_self x / ∥(x:F)∥ ^ 2 lemma linearly_dependent_of_is_local_extr_on (hT : is_self_adjoint (T : F →ₗ[ℝ] F)) {x₀ : F} (hextr : is_local_extr_on T.re_apply_inner_self (sphere (0:F) ∥x₀∥) x₀) : ∃ a b : ℝ, (a, b) ≠ 0 ∧ a • x₀ + b • T x₀ = 0 := begin have H : is_local_extr_on T.re_apply_inner_self {x : F | ∥x∥ ^ 2 = ∥x₀∥ ^ 2} x₀, { convert hextr, ext x, simp [dist_eq_norm] }, -- find Lagrange multipliers for the function `T.re_apply_inner_self` and the -- hypersurface-defining function `λ x, ∥x∥ ^ 2` obtain ⟨a, b, h₁, h₂⟩ := is_local_extr_on.exists_multipliers_of_has_strict_fderiv_at_1d H (has_strict_fderiv_at_norm_sq x₀) (hT.has_strict_fderiv_at_re_apply_inner_self x₀), refine ⟨a, b, h₁, _⟩, apply (inner_product_space.to_dual_map ℝ F).injective, simp only [linear_isometry.map_add, linear_isometry.map_smul, linear_isometry.map_zero], change a • innerSL x₀ + b • innerSL (T x₀) = 0, apply smul_right_injective (F →L[ℝ] ℝ) (two_ne_zero : (2:ℝ) ≠ 0), simpa only [bit0, add_smul, smul_add, one_smul, add_zero] using h₂ end lemma eq_smul_self_of_is_local_extr_on_real (hT : is_self_adjoint (T : F →ₗ[ℝ] F)) {x₀ : F} (hextr : is_local_extr_on T.re_apply_inner_self (sphere (0:F) ∥x₀∥) x₀) : T x₀ = (rayleigh_quotient x₀) • x₀ := begin obtain ⟨a, b, h₁, h₂⟩ := hT.linearly_dependent_of_is_local_extr_on hextr, by_cases hx₀ : x₀ = 0, { simp [hx₀] }, by_cases hb : b = 0, { have : a ≠ 0 := by simpa [hb] using h₁, refine absurd _ hx₀, apply smul_right_injective F this, simpa [hb] using h₂ }, let c : ℝ := - b⁻¹ * a, have hc : T x₀ = c • x₀, { have : b * (b⁻¹ * a) = a := by field_simp [mul_comm], apply smul_right_injective F hb, simp [c, eq_neg_of_add_eq_zero_left h₂, ← mul_smul, this] }, convert hc, have : ∥x₀∥ ≠ 0 := by simp [hx₀], field_simp, simpa [inner_smul_left, real_inner_self_eq_norm_mul_norm, sq] using congr_arg (λ x, ⟪x, x₀⟫_ℝ) hc, end end real section complete_space variables [complete_space E] {T : E →L[𝕜] E} local notation `rayleigh_quotient` := λ x : E, T.re_apply_inner_self x / ∥(x:E)∥ ^ 2 lemma eq_smul_self_of_is_local_extr_on (hT : is_self_adjoint (T : E →ₗ[𝕜] E)) {x₀ : E} (hextr : is_local_extr_on T.re_apply_inner_self (sphere (0:E) ∥x₀∥) x₀) : T x₀ = (↑(rayleigh_quotient x₀) : 𝕜) • x₀ := begin letI := inner_product_space.is_R_or_C_to_real 𝕜 E, let S : E →L[ℝ] E := @continuous_linear_map.restrict_scalars 𝕜 E E _ _ _ _ _ _ _ ℝ _ _ _ _ T, have hSA : is_self_adjoint (S : E →ₗ[ℝ] E) := λ x y, by { have := hT x y, simp only [continuous_linear_map.coe_coe] at this, simp only [real_inner_eq_re_inner, this, continuous_linear_map.coe_restrict_scalars, continuous_linear_map.coe_coe, linear_map.coe_restrict_scalars_eq_coe] }, exact eq_smul_self_of_is_local_extr_on_real hSA hextr, end /-- For a self-adjoint operator `T`, a local extremum of the Rayleigh quotient of `T` on a sphere centred at the origin is an eigenvector of `T`. -/ lemma has_eigenvector_of_is_local_extr_on (hT : is_self_adjoint (T : E →ₗ[𝕜] E)) {x₀ : E} (hx₀ : x₀ ≠ 0) (hextr : is_local_extr_on T.re_apply_inner_self (sphere (0:E) ∥x₀∥) x₀) : has_eigenvector (T : E →ₗ[𝕜] E) ↑(rayleigh_quotient x₀) x₀ := begin refine ⟨_, hx₀⟩, rw module.End.mem_eigenspace_iff, exact hT.eq_smul_self_of_is_local_extr_on hextr end /-- For a self-adjoint operator `T`, a maximum of the Rayleigh quotient of `T` on a sphere centred at the origin is an eigenvector of `T`, with eigenvalue the global supremum of the Rayleigh quotient. -/ lemma has_eigenvector_of_is_max_on (hT : is_self_adjoint (T : E →ₗ[𝕜] E)) {x₀ : E} (hx₀ : x₀ ≠ 0) (hextr : is_max_on T.re_apply_inner_self (sphere (0:E) ∥x₀∥) x₀) : has_eigenvector (T : E →ₗ[𝕜] E) ↑(⨆ x : {x : E // x ≠ 0}, rayleigh_quotient x) x₀ := begin convert hT.has_eigenvector_of_is_local_extr_on hx₀ (or.inr hextr.localize), have hx₀' : 0 < ∥x₀∥ := by simp [hx₀], have hx₀'' : x₀ ∈ sphere (0:E) (∥x₀∥) := by simp, rw T.supr_rayleigh_eq_supr_rayleigh_sphere hx₀', refine is_max_on.supr_eq hx₀'' _, intros x hx, dsimp, have : ∥x∥ = ∥x₀∥ := by simpa using hx, rw this, exact div_le_div_of_le (sq_nonneg ∥x₀∥) (hextr hx) end /-- For a self-adjoint operator `T`, a minimum of the Rayleigh quotient of `T` on a sphere centred at the origin is an eigenvector of `T`, with eigenvalue the global infimum of the Rayleigh quotient. -/ lemma has_eigenvector_of_is_min_on (hT : is_self_adjoint (T : E →ₗ[𝕜] E)) {x₀ : E} (hx₀ : x₀ ≠ 0) (hextr : is_min_on T.re_apply_inner_self (sphere (0:E) ∥x₀∥) x₀) : has_eigenvector (T : E →ₗ[𝕜] E) ↑(⨅ x : {x : E // x ≠ 0}, rayleigh_quotient x) x₀ := begin convert hT.has_eigenvector_of_is_local_extr_on hx₀ (or.inl hextr.localize), have hx₀' : 0 < ∥x₀∥ := by simp [hx₀], have hx₀'' : x₀ ∈ sphere (0:E) (∥x₀∥) := by simp, rw T.infi_rayleigh_eq_infi_rayleigh_sphere hx₀', refine is_min_on.infi_eq hx₀'' _, intros x hx, dsimp, have : ∥x∥ = ∥x₀∥ := by simpa using hx, rw this, exact div_le_div_of_le (sq_nonneg ∥x₀∥) (hextr hx) end end complete_space section finite_dimensional variables [finite_dimensional 𝕜 E] [_i : nontrivial E] {T : E →ₗ[𝕜] E} include _i /-- The supremum of the Rayleigh quotient of a self-adjoint operator `T` on a nontrivial finite-dimensional vector space is an eigenvalue for that operator. -/ lemma has_eigenvalue_supr_of_finite_dimensional (hT : is_self_adjoint T) : has_eigenvalue T ↑(⨆ x : {x : E // x ≠ 0}, is_R_or_C.re ⟪T x, x⟫ / ∥(x:E)∥ ^ 2) := begin haveI := finite_dimensional.proper_is_R_or_C 𝕜 E, let T' : E →L[𝕜] E := T.to_continuous_linear_map, have hT' : is_self_adjoint (T' : E →ₗ[𝕜] E) := hT, obtain ⟨x, hx⟩ : ∃ x : E, x ≠ 0 := exists_ne 0, have H₁ : is_compact (sphere (0:E) ∥x∥) := is_compact_sphere _ _, have H₂ : (sphere (0:E) ∥x∥).nonempty := ⟨x, by simp⟩, -- key point: in finite dimension, a continuous function on the sphere has a max obtain ⟨x₀, hx₀', hTx₀⟩ := H₁.exists_forall_ge H₂ T'.re_apply_inner_self_continuous.continuous_on, have hx₀ : ∥x₀∥ = ∥x∥ := by simpa using hx₀', have : is_max_on T'.re_apply_inner_self (sphere 0 ∥x₀∥) x₀, { simpa only [← hx₀] using hTx₀ }, have hx₀_ne : x₀ ≠ 0, { have : ∥x₀∥ ≠ 0 := by simp only [hx₀, norm_eq_zero, hx, ne.def, not_false_iff], simpa [← norm_eq_zero, ne.def] }, exact has_eigenvalue_of_has_eigenvector (hT'.has_eigenvector_of_is_max_on hx₀_ne this) end /-- The infimum of the Rayleigh quotient of a self-adjoint operator `T` on a nontrivial finite-dimensional vector space is an eigenvalue for that operator. -/ lemma has_eigenvalue_infi_of_finite_dimensional (hT : is_self_adjoint T) : has_eigenvalue T ↑(⨅ x : {x : E // x ≠ 0}, is_R_or_C.re ⟪T x, x⟫ / ∥(x:E)∥ ^ 2) := begin haveI := finite_dimensional.proper_is_R_or_C 𝕜 E, let T' : E →L[𝕜] E := T.to_continuous_linear_map, have hT' : is_self_adjoint (T' : E →ₗ[𝕜] E) := hT, obtain ⟨x, hx⟩ : ∃ x : E, x ≠ 0 := exists_ne 0, have H₁ : is_compact (sphere (0:E) ∥x∥) := is_compact_sphere _ _, have H₂ : (sphere (0:E) ∥x∥).nonempty := ⟨x, by simp⟩, -- key point: in finite dimension, a continuous function on the sphere has a min obtain ⟨x₀, hx₀', hTx₀⟩ := H₁.exists_forall_le H₂ T'.re_apply_inner_self_continuous.continuous_on, have hx₀ : ∥x₀∥ = ∥x∥ := by simpa using hx₀', have : is_min_on T'.re_apply_inner_self (sphere 0 ∥x₀∥) x₀, { simpa only [← hx₀] using hTx₀ }, have hx₀_ne : x₀ ≠ 0, { have : ∥x₀∥ ≠ 0 := by simp only [hx₀, norm_eq_zero, hx, ne.def, not_false_iff], simpa [← norm_eq_zero, ne.def] }, exact has_eigenvalue_of_has_eigenvector (hT'.has_eigenvector_of_is_min_on hx₀_ne this) end omit _i lemma subsingleton_of_no_eigenvalue_finite_dimensional (hT : is_self_adjoint T) (hT' : ∀ μ : 𝕜, module.End.eigenspace (T : E →ₗ[𝕜] E) μ = ⊥) : subsingleton E := (subsingleton_or_nontrivial E).resolve_right (λ h, by exactI absurd (hT' _) hT.has_eigenvalue_supr_of_finite_dimensional) end finite_dimensional end is_self_adjoint end inner_product_space
480a7e9675641996b0ab7aa224f0d29562dd6a01
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/topology/algebra/ring/basic.lean
c3aa31b2889f23811eaccf33ebe182a17e016813
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
17,411
lean
/- Copyright (c) 2018 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Johannes Hölzl -/ import algebra.ring.prod import ring_theory.subring.basic import topology.algebra.group.basic /-! # Topological (semi)rings > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. A topological (semi)ring is a (semi)ring equipped with a topology such that all operations are continuous. Besides this definition, this file proves that the topological closure of a subring (resp. an ideal) is a subring (resp. an ideal) and defines products and quotients of topological (semi)rings. ## Main Results - `subring.topological_closure`/`subsemiring.topological_closure`: the topological closure of a `subring`/`subsemiring` is itself a `sub(semi)ring`. - `prod.topological_semiring`/`prod.topological_ring`: The product of two topological (semi)rings. - `pi.topological_semiring`/`pi.topological_ring`: The arbitrary product of topological (semi)rings. -/ open classical set filter topological_space function open_locale classical topology filter section topological_semiring variables (α : Type*) /-- a topological semiring is a semiring `R` where addition and multiplication are continuous. We allow for non-unital and non-associative semirings as well. The `topological_semiring` class should *only* be instantiated in the presence of a `non_unital_non_assoc_semiring` instance; if there is an instance of `non_unital_non_assoc_ring`, then `topological_ring` should be used. Note: in the presence of `non_assoc_ring`, these classes are mathematically equivalent (see `topological_semiring.has_continuous_neg_of_mul` or `topological_semiring.to_topological_ring`). -/ class topological_semiring [topological_space α] [non_unital_non_assoc_semiring α] extends has_continuous_add α, has_continuous_mul α : Prop /-- A topological ring is a ring `R` where addition, multiplication and negation are continuous. If `R` is a (unital) ring, then continuity of negation can be derived from continuity of multiplication as it is multiplication with `-1`. (See `topological_semiring.has_continuous_neg_of_mul` and `topological_semiring.to_topological_add_group`) -/ class topological_ring [topological_space α] [non_unital_non_assoc_ring α] extends topological_semiring α, has_continuous_neg α : Prop variables {α} /-- If `R` is a ring with a continuous multiplication, then negation is continuous as well since it is just multiplication with `-1`. -/ lemma topological_semiring.has_continuous_neg_of_mul [topological_space α] [non_assoc_ring α] [has_continuous_mul α] : has_continuous_neg α := { continuous_neg := by simpa using (continuous_const.mul continuous_id : continuous (λ x : α, (-1) * x)) } /-- If `R` is a ring which is a topological semiring, then it is automatically a topological ring. This exists so that one can place a topological ring structure on `R` without explicitly proving `continuous_neg`. -/ lemma topological_semiring.to_topological_ring [topological_space α] [non_assoc_ring α] (h : topological_semiring α) : topological_ring α := { ..h, ..(by { haveI := h.to_has_continuous_mul, exact topological_semiring.has_continuous_neg_of_mul } : has_continuous_neg α) } @[priority 100] -- See note [lower instance priority] instance topological_ring.to_topological_add_group [non_unital_non_assoc_ring α] [topological_space α] [topological_ring α] : topological_add_group α := { ..topological_ring.to_topological_semiring.to_has_continuous_add, ..topological_ring.to_has_continuous_neg } @[priority 50] instance discrete_topology.topological_semiring [topological_space α] [non_unital_non_assoc_semiring α] [discrete_topology α] : topological_semiring α := ⟨⟩ @[priority 50] instance discrete_topology.topological_ring [topological_space α] [non_unital_non_assoc_ring α] [discrete_topology α] : topological_ring α := ⟨⟩ section variables [topological_space α] [semiring α] [topological_semiring α] namespace subsemiring instance (S : subsemiring α) : topological_semiring S := { ..S.to_submonoid.has_continuous_mul, ..S.to_add_submonoid.has_continuous_add } end subsemiring /-- The (topological-space) closure of a subsemiring of a topological semiring is itself a subsemiring. -/ def subsemiring.topological_closure (s : subsemiring α) : subsemiring α := { carrier := closure (s : set α), ..(s.to_submonoid.topological_closure), ..(s.to_add_submonoid.topological_closure ) } @[simp] lemma subsemiring.topological_closure_coe (s : subsemiring α) : (s.topological_closure : set α) = closure (s : set α) := rfl lemma subsemiring.le_topological_closure (s : subsemiring α) : s ≤ s.topological_closure := subset_closure lemma subsemiring.is_closed_topological_closure (s : subsemiring α) : is_closed (s.topological_closure : set α) := by convert is_closed_closure lemma subsemiring.topological_closure_minimal (s : subsemiring α) {t : subsemiring α} (h : s ≤ t) (ht : is_closed (t : set α)) : s.topological_closure ≤ t := closure_minimal h ht /-- If a subsemiring of a topological semiring is commutative, then so is its topological closure. -/ def subsemiring.comm_semiring_topological_closure [t2_space α] (s : subsemiring α) (hs : ∀ (x y : s), x * y = y * x) : comm_semiring s.topological_closure := { ..s.topological_closure.to_semiring, ..s.to_submonoid.comm_monoid_topological_closure hs } end section variables {β : Type*} [topological_space α] [topological_space β] /-- The product topology on the cartesian product of two topological semirings makes the product into a topological semiring. -/ instance [non_unital_non_assoc_semiring α] [non_unital_non_assoc_semiring β] [topological_semiring α] [topological_semiring β] : topological_semiring (α × β) := {} /-- The product topology on the cartesian product of two topological rings makes the product into a topological ring. -/ instance [non_unital_non_assoc_ring α] [non_unital_non_assoc_ring β] [topological_ring α] [topological_ring β] : topological_ring (α × β) := {} end instance {β : Type*} {C : β → Type*} [∀ b, topological_space (C b)] [Π b, non_unital_non_assoc_semiring (C b)] [Π b, topological_semiring (C b)] : topological_semiring (Π b, C b) := {} instance {β : Type*} {C : β → Type*} [∀ b, topological_space (C b)] [Π b, non_unital_non_assoc_ring (C b)] [Π b, topological_ring (C b)] : topological_ring (Π b, C b) := {} section mul_opposite open mul_opposite instance [non_unital_non_assoc_semiring α] [topological_space α] [has_continuous_add α] : has_continuous_add αᵐᵒᵖ := { continuous_add := continuous_induced_rng.2 $ (@continuous_add α _ _ _).comp (continuous_unop.prod_map continuous_unop) } instance [non_unital_non_assoc_semiring α] [topological_space α] [topological_semiring α] : topological_semiring αᵐᵒᵖ := {} instance [non_unital_non_assoc_ring α] [topological_space α] [has_continuous_neg α] : has_continuous_neg αᵐᵒᵖ := { continuous_neg := continuous_induced_rng.2 $ (@continuous_neg α _ _ _).comp continuous_unop } instance [non_unital_non_assoc_ring α] [topological_space α] [topological_ring α] : topological_ring αᵐᵒᵖ := {} end mul_opposite section add_opposite open add_opposite instance [non_unital_non_assoc_semiring α] [topological_space α] [has_continuous_mul α] : has_continuous_mul αᵃᵒᵖ := { continuous_mul := by convert (continuous_op.comp $ (@continuous_mul α _ _ _).comp $ continuous_unop.prod_map continuous_unop) } instance [non_unital_non_assoc_semiring α] [topological_space α] [topological_semiring α] : topological_semiring αᵃᵒᵖ := {} instance [non_unital_non_assoc_ring α] [topological_space α] [topological_ring α] : topological_ring αᵃᵒᵖ := {} end add_opposite section variables {R : Type*} [non_unital_non_assoc_ring R] [topological_space R] lemma topological_ring.of_add_group_of_nhds_zero [topological_add_group R] (hmul : tendsto (uncurry ((*) : R → R → R)) ((𝓝 0) ×ᶠ (𝓝 0)) $ 𝓝 0) (hmul_left : ∀ (x₀ : R), tendsto (λ x : R, x₀ * x) (𝓝 0) $ 𝓝 0) (hmul_right : ∀ (x₀ : R), tendsto (λ x : R, x * x₀) (𝓝 0) $ 𝓝 0) : topological_ring R := begin refine {..‹topological_add_group R›, ..}, have hleft : ∀ x₀ : R, 𝓝 x₀ = map (λ x, x₀ + x) (𝓝 0), by simp, have hadd : tendsto (uncurry ((+) : R → R → R)) ((𝓝 0) ×ᶠ (𝓝 0)) (𝓝 0), { rw ← nhds_prod_eq, convert continuous_add.tendsto ((0 : R), (0 : R)), rw zero_add }, rw continuous_iff_continuous_at, rintro ⟨x₀, y₀⟩, rw [continuous_at, nhds_prod_eq, hleft x₀, hleft y₀, hleft (x₀*y₀), filter.prod_map_map_eq, tendsto_map'_iff], suffices : tendsto ((λ (x : R), x + x₀ * y₀) ∘ (λ (p : R × R), p.1 + p.2) ∘ (λ (p : R × R), (p.1*y₀ + x₀*p.2, p.1*p.2))) ((𝓝 0) ×ᶠ (𝓝 0)) (map (λ (x : R), x + x₀ * y₀) $ 𝓝 0), { convert this using 1, { ext, simp only [comp_app, mul_add, add_mul], abel }, { simp only [add_comm] } }, refine tendsto_map.comp (hadd.comp (tendsto.prod_mk _ hmul)), exact hadd.comp (((hmul_right y₀).comp tendsto_fst).prod_mk ((hmul_left x₀).comp tendsto_snd)) end lemma topological_ring.of_nhds_zero (hadd : tendsto (uncurry ((+) : R → R → R)) ((𝓝 0) ×ᶠ (𝓝 0)) $ 𝓝 0) (hneg : tendsto (λ x, -x : R → R) (𝓝 0) (𝓝 0)) (hmul : tendsto (uncurry ((*) : R → R → R)) ((𝓝 0) ×ᶠ (𝓝 0)) $ 𝓝 0) (hmul_left : ∀ (x₀ : R), tendsto (λ x : R, x₀ * x) (𝓝 0) $ 𝓝 0) (hmul_right : ∀ (x₀ : R), tendsto (λ x : R, x * x₀) (𝓝 0) $ 𝓝 0) (hleft : ∀ x₀ : R, 𝓝 x₀ = map (λ x, x₀ + x) (𝓝 0)) : topological_ring R := begin haveI := topological_add_group.of_comm_of_nhds_zero hadd hneg hleft, exact topological_ring.of_add_group_of_nhds_zero hmul hmul_left hmul_right end end variables {α} [topological_space α] section variables [non_unital_non_assoc_ring α] [topological_ring α] /-- In a topological semiring, the left-multiplication `add_monoid_hom` is continuous. -/ lemma mul_left_continuous (x : α) : continuous (add_monoid_hom.mul_left x) := continuous_const.mul continuous_id /-- In a topological semiring, the right-multiplication `add_monoid_hom` is continuous. -/ lemma mul_right_continuous (x : α) : continuous (add_monoid_hom.mul_right x) := continuous_id.mul continuous_const end variables [ring α] [topological_ring α] namespace subring instance (S : subring α) : topological_ring S := topological_semiring.to_topological_ring S.to_subsemiring.topological_semiring end subring /-- The (topological-space) closure of a subring of a topological ring is itself a subring. -/ def subring.topological_closure (S : subring α) : subring α := { carrier := closure (S : set α), ..S.to_submonoid.topological_closure, ..S.to_add_subgroup.topological_closure } lemma subring.le_topological_closure (s : subring α) : s ≤ s.topological_closure := subset_closure lemma subring.is_closed_topological_closure (s : subring α) : is_closed (s.topological_closure : set α) := by convert is_closed_closure lemma subring.topological_closure_minimal (s : subring α) {t : subring α} (h : s ≤ t) (ht : is_closed (t : set α)) : s.topological_closure ≤ t := closure_minimal h ht /-- If a subring of a topological ring is commutative, then so is its topological closure. -/ def subring.comm_ring_topological_closure [t2_space α] (s : subring α) (hs : ∀ (x y : s), x * y = y * x) : comm_ring s.topological_closure := { ..s.topological_closure.to_ring, ..s.to_submonoid.comm_monoid_topological_closure hs } end topological_semiring /-! ### Lattice of ring topologies We define a type class `ring_topology α` which endows a ring `α` with a topology such that all ring operations are continuous. Ring topologies on a fixed ring `α` are ordered, by reverse inclusion. They form a complete lattice, with `⊥` the discrete topology and `⊤` the indiscrete topology. Any function `f : α → β` induces `coinduced f : topological_space α → ring_topology β`. -/ universes u v /-- A ring topology on a ring `α` is a topology for which addition, negation and multiplication are continuous. -/ @[ext] structure ring_topology (α : Type u) [ring α] extends topological_space α, topological_ring α : Type u namespace ring_topology variables {α : Type*} [ring α] instance inhabited {α : Type u} [ring α] : inhabited (ring_topology α) := ⟨{to_topological_space := ⊤, continuous_add := continuous_top, continuous_mul := continuous_top, continuous_neg := continuous_top}⟩ @[ext] lemma ext' {f g : ring_topology α} (h : f.is_open = g.is_open) : f = g := by { ext : 2, exact h } /-- The ordering on ring topologies on the ring `α`. `t ≤ s` if every set open in `s` is also open in `t` (`t` is finer than `s`). -/ instance : partial_order (ring_topology α) := partial_order.lift ring_topology.to_topological_space $ ext local notation `cont` := @continuous _ _ private def def_Inf (S : set (ring_topology α)) : ring_topology α := let Inf_S' := Inf (to_topological_space '' S) in { to_topological_space := Inf_S', continuous_add := begin apply continuous_Inf_rng.2, rintros _ ⟨⟨t, tr⟩, haS, rfl⟩, resetI, have h := continuous_Inf_dom (set.mem_image_of_mem to_topological_space haS) continuous_id, have h_continuous_id := @continuous.prod_map _ _ _ _ t t Inf_S' Inf_S' _ _ h h, exact @continuous.comp _ _ _ (id _) (id _) t _ _ continuous_add h_continuous_id, end, continuous_mul := begin apply continuous_Inf_rng.2, rintros _ ⟨⟨t, tr⟩, haS, rfl⟩, resetI, have h := continuous_Inf_dom (set.mem_image_of_mem to_topological_space haS) continuous_id, have h_continuous_id := @continuous.prod_map _ _ _ _ t t Inf_S' Inf_S' _ _ h h, exact @continuous.comp _ _ _ (id _) (id _) t _ _ continuous_mul h_continuous_id, end, continuous_neg := begin apply continuous_Inf_rng.2, rintros _ ⟨⟨t, tr⟩, haS, rfl⟩, resetI, have h := continuous_Inf_dom (set.mem_image_of_mem to_topological_space haS) continuous_id, exact @continuous.comp _ _ _ (id _) (id _) t _ _ continuous_neg h, end } /-- Ring topologies on `α` form a complete lattice, with `⊥` the discrete topology and `⊤` the indiscrete topology. The infimum of a collection of ring topologies is the topology generated by all their open sets (which is a ring topology). The supremum of two ring topologies `s` and `t` is the infimum of the family of all ring topologies contained in the intersection of `s` and `t`. -/ instance : complete_semilattice_Inf (ring_topology α) := { Inf := def_Inf, Inf_le := λ S a haS, by { apply topological_space.complete_lattice.Inf_le, use [a, ⟨ haS, rfl⟩] }, le_Inf := begin intros S a hab, apply topological_space.complete_lattice.le_Inf, rintros _ ⟨b, hbS, rfl⟩, exact hab b hbS, end, ..ring_topology.partial_order } instance : complete_lattice (ring_topology α) := complete_lattice_of_complete_semilattice_Inf _ /-- Given `f : α → β` and a topology on `α`, the coinduced ring topology on `β` is the finest topology such that `f` is continuous and `β` is a topological ring. -/ def coinduced {α β : Type*} [t : topological_space α] [ring β] (f : α → β) : ring_topology β := Inf {b : ring_topology β | (topological_space.coinduced f t) ≤ b.to_topological_space} lemma coinduced_continuous {α β : Type*} [t : topological_space α] [ring β] (f : α → β) : cont t (coinduced f).to_topological_space f := begin rw continuous_iff_coinduced_le, refine le_Inf _, rintros _ ⟨t', ht', rfl⟩, exact ht', end /-- The forgetful functor from ring topologies on `a` to additive group topologies on `a`. -/ def to_add_group_topology (t : ring_topology α) : add_group_topology α := { to_topological_space := t.to_topological_space, to_topological_add_group := @topological_ring.to_topological_add_group _ _ t.to_topological_space t.to_topological_ring } /-- The order embedding from ring topologies on `a` to additive group topologies on `a`. -/ def to_add_group_topology.order_embedding : order_embedding (ring_topology α) (add_group_topology α) := order_embedding.of_map_le_iff to_add_group_topology $ λ _ _, iff.rfl end ring_topology section absolute_value /-- Construct an absolute value on a semiring `T` from an absolute value on a semiring `R` and an injective ring homomorphism `f : T →+* R` -/ def absolute_value.comp {R S T : Type*} [semiring T] [semiring R] [ordered_semiring S] (v : absolute_value R S) {f : T →+* R} (hf : function.injective f) : absolute_value T S := { to_fun := v ∘ f, map_mul' := by simp only [function.comp_app, map_mul, eq_self_iff_true, forall_const], nonneg' := by simp only [v.nonneg, forall_const], eq_zero' := by simp only [map_eq_zero_iff f hf, v.eq_zero, forall_const, iff_self], add_le' := by simp only [function.comp_app, map_add, v.add_le, forall_const], } end absolute_value
6cf376d2c70062bf24e2a87cc79650ba57423529
38bf3fd2bb651ab70511408fcf70e2029e2ba310
/src/linear_algebra/basis.lean
927b51be849f2c518a6241dd5bb5bf8101002505
[ "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
47,906
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, Alexander Bentkamp -/ import linear_algebra.basic linear_algebra.finsupp order.zorn /-! # Linear independence and bases This file defines linear independence and bases in a module or vector space. It is inspired by Isabelle/HOL's linear algebra, and hence indirectly by HOL Light. ## Main definitions All definitions are given for families of vectors, i.e. `v : ι → M` where M is the module or vectorspace and `ι : Type*` is an arbitrary indexing type. * `linear_independent R v` states that the elements of the family `v` are linear independent * `linear_independent.repr hv x` returns the linear combination representing `x : span R (range v)` on the linear independent vectors `v`, given `hv : linear_independent R v` (using classical choice). `linear_independent.repr hv` is provided as a linear map. * `is_basis R v` states that the vector family `v` is a basis, i.e. it is linear independent and spans the entire space * `is_basis.repr hv x` is the basis version of `linear_independent.repr hv x`. It returns the linear combination representing `x : M` on a basis `v` of `M` (using classical choice). The argument `hv` must be a proof that `is_basis R v`. `is_basis.repr hv` is given as a linear map as well. * `is_basis.constr hv f` constructs a linear map `M₁ →ₗ[R] M₂` given the values `f : ι → M₂` at the basis `v : ι → M₁`, given `hv : is_basis R v`. ## Main statements * `is_basis.ext` states that two linear maps are equal if they coincide on a basis. * `exists_is_basis` states that every vector space has a basis. ## Implementation notes We use families instead of sets because it allows us to say that two identical vectors are linearly dependent. For bases, this is useful as well because we can easily derive ordered bases by using an ordered index type ι. If you want to use sets, use the family `(λ x, x : s → M)` given a set `s : set M`. The lemmas `linear_independent.to_subtype_range` and `linear_independent.of_subtype_range` connect those two worlds. ## Tags linearly dependent, linear dependence, linearly independent, linear independence, basis -/ noncomputable theory open function lattice set submodule open_locale classical variables {ι : Type*} {ι' : Type*} {R : Type*} {K : Type*} {M : Type*} {M' : Type*} {V : Type*} {V' : Type*} section module variables {v : ι → M} variables [ring R] [add_comm_group M] [add_comm_group M'] variables [module R M] [module R M'] variables {a b : R} {x y : M} include R variables (R) (v) /-- Linearly independent family of vectors -/ def linear_independent : Prop := (finsupp.total ι M R v).ker = ⊥ variables {R} {v} theorem linear_independent_iff : linear_independent R v ↔ ∀l, finsupp.total ι M R v l = 0 → l = 0 := by simp [linear_independent, linear_map.ker_eq_bot'] lemma linear_independent_empty_type (h : ¬ nonempty ι) : linear_independent R v := begin rw [linear_independent_iff], intros, ext i, exact false.elim (not_nonempty_iff_imp_false.1 h i) end lemma ne_zero_of_linear_independent {i : ι} (ne : 0 ≠ (1:R)) (hv : linear_independent R v) : v i ≠ 0 := λ h, ne $ eq.symm begin suffices : (finsupp.single i 1 : ι →₀ R) i = 0, {simpa}, rw linear_independent_iff.1 hv (finsupp.single i 1), {simp}, {simp [h]} end lemma linear_independent.comp (h : linear_independent R v) (f : ι' → ι) (hf : injective f) : linear_independent R (v ∘ f) := begin rw [linear_independent_iff, finsupp.total_comp], intros l hl, have h_map_domain : ∀ x, (finsupp.map_domain f l) (f x) = 0, by rw linear_independent_iff.1 h (finsupp.map_domain f l) hl; simp, ext, convert h_map_domain a, simp only [finsupp.map_domain_apply hf], end lemma linear_independent_of_zero_eq_one (zero_eq_one : (0 : R) = 1) : linear_independent R v := linear_independent_iff.2 (λ l hl, finsupp.eq_zero_of_zero_eq_one zero_eq_one _) lemma linear_independent.unique (hv : linear_independent R v) {l₁ l₂ : ι →₀ R} : finsupp.total ι M R v l₁ = finsupp.total ι M R v l₂ → l₁ = l₂ := by apply linear_map.ker_eq_bot.1 hv lemma linear_independent.injective (zero_ne_one : (0 : R) ≠ 1) (hv : linear_independent R v) : injective v := begin intros i j hij, let l : ι →₀ R := finsupp.single i (1 : R) - finsupp.single j 1, have h_total : finsupp.total ι M R v l = 0, { rw finsupp.total_apply, rw finsupp.sum_sub_index, { simp [finsupp.sum_single_index, hij] }, { intros, apply sub_smul } }, have h_single_eq : finsupp.single i (1 : R) = finsupp.single j 1, { rw linear_independent_iff at hv, simp [eq_add_of_sub_eq' (hv l h_total)] }, show i = j, { apply or.elim ((finsupp.single_eq_single_iff _ _ _ _).1 h_single_eq), simp, exact λ h, false.elim (zero_ne_one.symm h.1) } end lemma linear_independent_span (hs : linear_independent R v) : @linear_independent ι R (span R (range v)) (λ i : ι, ⟨v i, subset_span (mem_range_self i)⟩) _ _ _ := begin rw linear_independent_iff at *, intros l hl, apply hs l, have := congr_arg (submodule.subtype (span R (range v))) hl, convert this, rw [finsupp.total_apply, finsupp.total_apply], unfold finsupp.sum, rw linear_map.map_sum (submodule.subtype (span R (range v))), simp end section subtype /- The following lemmas use the subtype defined by a set in M as the index set ι. -/ theorem linear_independent_comp_subtype {s : set ι} : linear_independent R (v ∘ subtype.val : s → M) ↔ ∀ l ∈ (finsupp.supported R R s), (finsupp.total ι M R v) l = 0 → l = 0 := begin rw [linear_independent_iff, finsupp.total_comp], simp only [linear_map.comp_apply], split, { intros h l hl₁ hl₂, have h_bij : bij_on subtype.val (subtype.val ⁻¹' l.support.to_set : set s) l.support.to_set, { apply bij_on.mk, { unfold maps_to }, { apply set.inj_on_of_injective _ subtype.val_injective }, intros i hi, rw mem_image, use subtype.mk i (((finsupp.mem_supported _ _).1 hl₁ : ↑(l.support) ⊆ s) hi), rw mem_preimage, exact ⟨hi, rfl⟩ }, show l = 0, { apply finsupp.eq_zero_of_comap_domain_eq_zero (subtype.val : s → ι) _ h_bij, apply h, convert hl₂, rw [finsupp.lmap_domain_apply, finsupp.map_domain_comap_domain], apply subtype.val_injective, rw subtype.range_val, exact (finsupp.mem_supported _ _).1 hl₁ } }, { intros h l hl, have hl' : finsupp.total ι M R v (finsupp.emb_domain ⟨subtype.val, subtype.val_injective⟩ l) = 0, { rw finsupp.emb_domain_eq_map_domain ⟨subtype.val, subtype.val_injective⟩ l, apply hl }, apply finsupp.emb_domain_inj.1, rw [h (finsupp.emb_domain ⟨subtype.val, subtype.val_injective⟩ l) _ hl', finsupp.emb_domain_zero], rw [finsupp.mem_supported, finsupp.support_emb_domain], intros x hx, rw [finset.mem_coe, finset.mem_map] at hx, rcases hx with ⟨i, x', hx'⟩, rw ←hx', simp } end theorem linear_independent_subtype {s : set M} : linear_independent R (λ x, x : s → M) ↔ ∀ l ∈ (finsupp.supported R R s), (finsupp.total M M R id) l = 0 → l = 0 := by apply @linear_independent_comp_subtype _ _ _ id theorem linear_independent_comp_subtype_disjoint {s : set ι} : linear_independent R (v ∘ subtype.val : s → M) ↔ disjoint (finsupp.supported R R s) (finsupp.total ι M R v).ker := by rw [linear_independent_comp_subtype, linear_map.disjoint_ker] theorem linear_independent_subtype_disjoint {s : set M} : linear_independent R (λ x, x : s → M) ↔ disjoint (finsupp.supported R R s) (finsupp.total M M R id).ker := by apply @linear_independent_comp_subtype_disjoint _ _ _ id theorem linear_independent_iff_total_on {s : set M} : linear_independent R (λ x, x : s → M) ↔ (finsupp.total_on M M R id s).ker = ⊥ := by rw [finsupp.total_on, linear_map.ker, linear_map.comap_cod_restrict, map_bot, comap_bot, linear_map.ker_comp, linear_independent_subtype_disjoint, disjoint, ← map_comap_subtype, map_le_iff_le_comap, comap_bot, ker_subtype, le_bot_iff] lemma linear_independent.to_subtype_range (hv : linear_independent R v) : linear_independent R (λ x, x : range v → M) := begin by_cases zero_eq_one : (0 : R) = 1, { apply linear_independent_of_zero_eq_one zero_eq_one }, rw linear_independent_subtype, intros l hl₁ hl₂, have h_bij : bij_on v (v ⁻¹' finset.to_set (l.support)) (finset.to_set (l.support)), { apply bij_on.mk, { unfold maps_to }, { apply set.inj_on_of_injective _ (linear_independent.injective zero_eq_one hv) }, intros x hx, rcases mem_range.1 (((finsupp.mem_supported _ _).1 hl₁ : ↑(l.support) ⊆ range v) hx) with ⟨i, hi⟩, rw mem_image, use i, rw [mem_preimage, hi], exact ⟨hx, rfl⟩ }, apply finsupp.eq_zero_of_comap_domain_eq_zero v l, apply linear_independent_iff.1 hv, rw [finsupp.total_comap_domain, finset.sum_preimage v l.support h_bij (λ (x : M), l x • x)], rw [finsupp.total_apply, finsupp.sum] at hl₂, apply hl₂ end lemma linear_independent.of_subtype_range (hv : injective v) (h : linear_independent R (λ x, x : range v → M)) : linear_independent R v := begin rw linear_independent_iff, intros l hl, apply finsupp.injective_map_domain hv, apply linear_independent_subtype.1 h (l.map_domain v), { rw finsupp.mem_supported, intros x hx, have := finset.mem_coe.2 (finsupp.map_domain_support hx), rw finset.coe_image at this, apply set.image_subset_range _ _ this, }, { rwa [finsupp.total_map_domain _ _ hv, left_id] } end lemma linear_independent.restrict_of_comp_subtype {s : set ι} (hs : linear_independent R (v ∘ subtype.val : s → M)) : linear_independent R (function.restrict v s) := begin have h_restrict : restrict v s = v ∘ (λ x, x.val) := rfl, rw [linear_independent_iff, h_restrict, finsupp.total_comp], intros l hl, have h_map_domain_subtype_eq_0 : l.map_domain subtype.val = 0, { rw linear_independent_comp_subtype at hs, apply hs (finsupp.lmap_domain R R (λ x : subtype s, x.val) l) _ hl, rw finsupp.mem_supported, simp, intros x hx, have := finset.mem_coe.2 (finsupp.map_domain_support (finset.mem_coe.1 hx)), rw finset.coe_image at this, exact subtype.val_image_subset _ _ this }, apply @finsupp.injective_map_domain _ (subtype s) ι, { apply subtype.val_injective }, { simpa }, end lemma linear_independent_empty : linear_independent R (λ x, x : (∅ : set M) → M) := by simp [linear_independent_subtype_disjoint] lemma linear_independent.mono {t s : set M} (h : t ⊆ s) : linear_independent R (λ x, x : s → M) → linear_independent R (λ x, x : t → M) := begin simp only [linear_independent_subtype_disjoint], exact (disjoint_mono_left (finsupp.supported_mono h)) end lemma linear_independent_union {s t : set M} (hs : linear_independent R (λ x, x : s → M)) (ht : linear_independent R (λ x, x : t → M)) (hst : disjoint (span R s) (span R t)) : linear_independent R (λ x, x : (s ∪ t) → M) := begin rw [linear_independent_subtype_disjoint, disjoint_def, finsupp.supported_union], intros l h₁ h₂, rw mem_sup at h₁, rcases h₁ with ⟨ls, hls, lt, hlt, rfl⟩, have h_ls_mem_t : finsupp.total M M R id ls ∈ span R t, { rw [← image_id t, finsupp.span_eq_map_total], apply (add_mem_iff_left (map _ _) (mem_image_of_mem _ hlt)).1, rw [← linear_map.map_add, linear_map.mem_ker.1 h₂], apply zero_mem }, have h_lt_mem_s : finsupp.total M M R id lt ∈ span R s, { rw [← image_id s, finsupp.span_eq_map_total], apply (add_mem_iff_left (map _ _) (mem_image_of_mem _ hls)).1, rw [← linear_map.map_add, add_comm, linear_map.mem_ker.1 h₂], apply zero_mem }, have h_ls_mem_s : (finsupp.total M M R id) ls ∈ span R s, { rw ← image_id s, apply (finsupp.mem_span_iff_total _).2 ⟨ls, hls, rfl⟩ }, have h_lt_mem_t : (finsupp.total M M R id) lt ∈ span R t, { rw ← image_id t, apply (finsupp.mem_span_iff_total _).2 ⟨lt, hlt, rfl⟩ }, have h_ls_0 : ls = 0 := disjoint_def.1 (linear_independent_subtype_disjoint.1 hs) _ hls (linear_map.mem_ker.2 $ disjoint_def.1 hst (finsupp.total M M R id ls) h_ls_mem_s h_ls_mem_t), have h_lt_0 : lt = 0 := disjoint_def.1 (linear_independent_subtype_disjoint.1 ht) _ hlt (linear_map.mem_ker.2 $ disjoint_def.1 hst (finsupp.total M M R id lt) h_lt_mem_s h_lt_mem_t), show ls + lt = 0, by simp [h_ls_0, h_lt_0], end lemma linear_independent_of_finite (s : set M) (H : ∀ t ⊆ s, finite t → linear_independent R (λ x, x : t → M)) : linear_independent R (λ x, x : s → M) := linear_independent_subtype.2 $ λ l hl, linear_independent_subtype.1 (H _ hl (finset.finite_to_set _)) l (subset.refl _) lemma linear_independent_Union_of_directed {η : Type*} {s : η → set M} (hs : directed (⊆) s) (h : ∀ i, linear_independent R (λ x, x : s i → M)) : linear_independent R (λ x, x : (⋃ i, s i) → M) := begin haveI := classical.dec (nonempty η), by_cases hη : nonempty η, { refine linear_independent_of_finite (⋃ i, s i) (λ t ht ft, _), rcases finite_subset_Union ft ht with ⟨I, fi, hI⟩, rcases hs.finset_le hη fi.to_finset with ⟨i, hi⟩, exact (h i).mono (subset.trans hI $ bUnion_subset $ λ j hj, hi j (finite.mem_to_finset.2 hj)) }, { refine linear_independent_empty.mono _, rintro _ ⟨_, ⟨i, _⟩, _⟩, exact hη ⟨i⟩ } end lemma linear_independent_sUnion_of_directed {s : set (set M)} (hs : directed_on (⊆) s) (h : ∀ a ∈ s, linear_independent R (λ x, x : (a : set M) → M)) : linear_independent R (λ x, x : (⋃₀ s) → M) := by rw sUnion_eq_Union; exact linear_independent_Union_of_directed ((directed_on_iff_directed _).1 hs) (by simpa using h) lemma linear_independent_bUnion_of_directed {η} {s : set η} {t : η → set M} (hs : directed_on (t ⁻¹'o (⊆)) s) (h : ∀a∈s, linear_independent R (λ x, x : t a → M)) : linear_independent R (λ x, x : (⋃a∈s, t a) → M) := by rw bUnion_eq_Union; exact linear_independent_Union_of_directed ((directed_comp _ _ _).2 $ (directed_on_iff_directed _).1 hs) (by simpa using h) lemma linear_independent_Union_finite_subtype {ι : Type*} {f : ι → set M} (hl : ∀i, linear_independent R (λ x, x : f i → M)) (hd : ∀i, ∀t:set ι, finite t → i ∉ t → disjoint (span R (f i)) (⨆i∈t, span R (f i))) : linear_independent R (λ x, x : (⋃i, f i) → M) := begin rw [Union_eq_Union_finset f], apply linear_independent_Union_of_directed, apply directed_of_sup, exact (assume t₁ t₂ ht, Union_subset_Union $ assume i, Union_subset_Union_const $ assume h, ht h), assume t, rw [set.Union, ← finset.sup_eq_supr], refine t.induction_on _ _, { rw finset.sup_empty, apply linear_independent_empty_type (not_nonempty_iff_imp_false.2 _), exact λ x, set.not_mem_empty x (subtype.mem x) }, { rintros ⟨i⟩ s his ih, rw [finset.sup_insert], apply linear_independent_union, { apply hl }, { apply ih }, rw [finset.sup_eq_supr], refine disjoint_mono (le_refl _) _ (hd i _ _ his), { simp only [(span_Union _).symm], refine span_mono (@supr_le_supr2 (set M) _ _ _ _ _ _), rintros ⟨i⟩, exact ⟨i, le_refl _⟩ }, { change finite (plift.up ⁻¹' s.to_set), exact finite_preimage (inj_on_of_injective _ (assume i j, plift.up.inj)) s.finite_to_set } } end lemma linear_independent_Union_finite {η : Type*} {ιs : η → Type*} {f : Π j : η, ιs j → M} (hindep : ∀j, linear_independent R (f j)) (hd : ∀i, ∀t:set η, finite t → i ∉ t → disjoint (span R (range (f i))) (⨆i∈t, span R (range (f i)))) : linear_independent R (λ ji : Σ j, ιs j, f ji.1 ji.2) := begin by_cases zero_eq_one : (0 : R) = 1, { apply linear_independent_of_zero_eq_one zero_eq_one }, apply linear_independent.of_subtype_range, { rintros ⟨x₁, x₂⟩ ⟨y₁, y₂⟩ hxy, by_cases h_cases : x₁ = y₁, subst h_cases, { apply sigma.eq, rw linear_independent.injective zero_eq_one (hindep _) hxy, refl }, { have h0 : f x₁ x₂ = 0, { apply disjoint_def.1 (hd x₁ {y₁} (finite_singleton y₁) (λ h, h_cases (eq_of_mem_singleton h))) (f x₁ x₂) (subset_span (mem_range_self _)), rw supr_singleton, simp only [] at hxy, rw hxy, exact (subset_span (mem_range_self y₂)) }, exact false.elim (ne_zero_of_linear_independent zero_eq_one (hindep x₁) h0) } }, rw range_sigma_eq_Union_range, apply linear_independent_Union_finite_subtype (λ j, (hindep j).to_subtype_range) hd, end end subtype section repr variables (hv : linear_independent R v) /-- Canonical isomorphism between linear combinations and the span of linearly independent vectors. -/ def linear_independent.total_equiv (hv : linear_independent R v) : (ι →₀ R) ≃ₗ[R] span R (range v) := begin apply linear_equiv.of_bijective (linear_map.cod_restrict (span R (range v)) (finsupp.total ι M R v) _), { rw linear_map.ker_cod_restrict, apply hv }, { rw [linear_map.range, linear_map.map_cod_restrict, ← linear_map.range_le_iff_comap, range_subtype, map_top], rw finsupp.range_total, apply le_refl (span R (range v)) }, { intro l, rw ← finsupp.range_total, rw linear_map.mem_range, apply mem_range_self l } end /-- Linear combination representing a vector in the span of linearly independent vectors. Given a family of linearly independent vectors, we can represent any vector in their span as a linear combination of these vectors. These are provided by this linear map. It is simply one direction of `linear_independent.total_equiv` -/ def linear_independent.repr (hv : linear_independent R v) : span R (range v) →ₗ[R] ι →₀ R := hv.total_equiv.symm lemma linear_independent.total_repr (x) : finsupp.total ι M R v (hv.repr x) = x := subtype.coe_ext.1 (linear_equiv.apply_symm_apply hv.total_equiv x) lemma linear_independent.total_comp_repr : (finsupp.total ι M R v).comp hv.repr = submodule.subtype _ := linear_map.ext $ hv.total_repr lemma linear_independent.repr_ker : hv.repr.ker = ⊥ := by rw [linear_independent.repr, linear_equiv.ker] lemma linear_independent.repr_range : hv.repr.range = ⊤ := by rw [linear_independent.repr, linear_equiv.range] lemma linear_independent.repr_eq {l : ι →₀ R} {x} (eq : finsupp.total ι M R v l = ↑x) : hv.repr x = l := begin have : ↑((linear_independent.total_equiv hv : (ι →₀ R) →ₗ[R] span R (range v)) l) = finsupp.total ι M R v l := rfl, have : (linear_independent.total_equiv hv : (ι →₀ R) →ₗ[R] span R (range v)) l = x, { rw eq at this, exact subtype.coe_ext.2 this }, rw ←linear_equiv.symm_apply_apply hv.total_equiv l, rw ←this, refl, end lemma linear_independent.repr_eq_single (i) (x) (hx : ↑x = v i) : hv.repr x = finsupp.single i 1 := begin apply hv.repr_eq, simp [finsupp.total_single, hx] end lemma linear_independent_iff_not_smul_mem_span : linear_independent R v ↔ (∀ (i : ι) (a : R), a • (v i) ∈ span R (v '' (univ \ {i})) → a = 0) := ⟨ λ hv i a ha, begin rw [finsupp.span_eq_map_total, mem_map] at ha, rcases ha with ⟨l, hl, e⟩, rw sub_eq_zero.1 (linear_independent_iff.1 hv (l - finsupp.single i a) (by simp [e])) at hl, by_contra hn, exact (not_mem_of_mem_diff (hl $ by simp [hn])) (mem_singleton _), end, λ H, linear_independent_iff.2 $ λ l hl, begin ext i, simp, by_contra hn, refine hn (H i _ _), refine (finsupp.mem_span_iff_total _).2 ⟨finsupp.single i (l i) - l, _, _⟩, { rw finsupp.mem_supported', intros j hj, have hij : j = i := classical.not_not.1 (λ hij : j ≠ i, hj ((mem_diff _).2 ⟨mem_univ _, λ h, hij (eq_of_mem_singleton h)⟩)), simp [hij] }, { simp [hl] } end⟩ end repr lemma surjective_of_linear_independent_of_span (hv : linear_independent R v) (f : ι' ↪ ι) (hss : range v ⊆ span R (range (v ∘ f))) (zero_ne_one : 0 ≠ (1 : R)): surjective f := begin intros i, let repr : (span R (range (v ∘ f)) : Type*) → ι' →₀ R := (hv.comp f f.inj).repr, let l := (repr ⟨v i, hss (mem_range_self i)⟩).map_domain f, have h_total_l : finsupp.total ι M R v l = v i, { dsimp only [l], rw finsupp.total_map_domain, rw (hv.comp f f.inj).total_repr, { refl }, { exact f.inj } }, have h_total_eq : (finsupp.total ι M R v) l = (finsupp.total ι M R v) (finsupp.single i 1), by rw [h_total_l, finsupp.total_single, one_smul], have l_eq : l = _ := linear_map.ker_eq_bot.1 hv h_total_eq, dsimp only [l] at l_eq, rw ←finsupp.emb_domain_eq_map_domain at l_eq, rcases finsupp.single_of_emb_domain_single (repr ⟨v i, _⟩) f i (1 : R) zero_ne_one.symm l_eq with ⟨i', hi'⟩, use i', exact hi'.2 end lemma eq_of_linear_independent_of_span_subtype {s t : set M} (zero_ne_one : (0 : R) ≠ 1) (hs : linear_independent R (λ x, x : s → M)) (h : t ⊆ s) (hst : s ⊆ span R t) : s = t := begin let f : t ↪ s := ⟨λ x, ⟨x.1, h x.2⟩, λ a b hab, subtype.val_injective (subtype.mk.inj hab)⟩, have h_surj : surjective f, { apply surjective_of_linear_independent_of_span hs f _ zero_ne_one, convert hst; simp [f, comp], }, show s = t, { apply subset.antisymm _ h, intros x hx, rcases h_surj ⟨x, hx⟩ with ⟨y, hy⟩, convert y.mem, rw ← subtype.mk.inj hy, refl } end open linear_map lemma linear_independent.image (hv : linear_independent R v) {f : M →ₗ M'} (hf_inj : disjoint (span R (range v)) f.ker) : linear_independent R (f ∘ v) := begin rw [disjoint, ← set.image_univ, finsupp.span_eq_map_total, map_inf_eq_map_inf_comap, map_le_iff_le_comap, comap_bot, finsupp.supported_univ, top_inf_eq] at hf_inj, unfold linear_independent at hv, rw hv at hf_inj, haveI : inhabited M := ⟨0⟩, rw [linear_independent, finsupp.total_comp], rw [@finsupp.lmap_domain_total _ _ R _ _ _ _ _ _ _ _ _ _ f, ker_comp, eq_bot_iff], apply hf_inj, exact λ _, rfl, end lemma linear_independent.image_subtype {s : set M} {f : M →ₗ M'} (hs : linear_independent R (λ x, x : s → M)) (hf_inj : disjoint (span R s) f.ker) : linear_independent R (λ x, x : f '' s → M') := begin rw [disjoint, ← set.image_id s, finsupp.span_eq_map_total, map_inf_eq_map_inf_comap, map_le_iff_le_comap, comap_bot] at hf_inj, haveI : inhabited M := ⟨0⟩, rw [linear_independent_subtype_disjoint, disjoint, ← finsupp.lmap_domain_supported _ _ f, map_inf_eq_map_inf_comap, map_le_iff_le_comap, ← ker_comp], rw [@finsupp.lmap_domain_total _ _ R _ _ _, ker_comp], { exact le_trans (le_inf inf_le_left hf_inj) (le_trans (linear_independent_subtype_disjoint.1 hs) bot_le) }, { simp } end lemma linear_independent_inl_union_inr {s : set M} {t : set M'} (hs : linear_independent R (λ x, x : s → M)) (ht : linear_independent R (λ x, x : t → M')) : linear_independent R (λ x, x : inl R M M' '' s ∪ inr R M M' '' t → M × M') := begin apply linear_independent_union, exact (hs.image_subtype $ by simp), exact (ht.image_subtype $ by simp), rw [span_image, span_image]; simp [disjoint_iff, prod_inf_prod] end lemma linear_independent_inl_union_inr' {v : ι → M} {v' : ι' → M'} (hv : linear_independent R v) (hv' : linear_independent R v') : linear_independent R (sum.elim (inl R M M' ∘ v) (inr R M M' ∘ v')) := begin by_cases zero_eq_one : (0 : R) = 1, { apply linear_independent_of_zero_eq_one zero_eq_one }, have inj_v : injective v := (linear_independent.injective zero_eq_one hv), have inj_v' : injective v' := (linear_independent.injective zero_eq_one hv'), apply linear_independent.of_subtype_range, { apply sum.elim_injective, { exact injective_comp prod.injective_inl inj_v }, { exact injective_comp prod.injective_inr inj_v' }, { intros, simp [ne_zero_of_linear_independent zero_eq_one hv] } }, { rw sum.elim_range, apply linear_independent_union, { apply linear_independent.to_subtype_range, apply linear_independent.image hv, simp [ker_inl] }, { apply linear_independent.to_subtype_range, apply linear_independent.image hv', simp [ker_inr] }, { apply disjoint_mono _ _ disjoint_inl_inr, { rw [set.range_comp, span_image], apply linear_map.map_le_range }, { rw [set.range_comp, span_image], apply linear_map.map_le_range } } } end lemma le_of_span_le_span {s t u: set M} (zero_ne_one : (0 : R) ≠ 1) (hl : linear_independent R (subtype.val : u → M )) (hsu : s ⊆ u) (htu : t ⊆ u) (hst : span R s ≤ span R t) : s ⊆ t := begin have := eq_of_linear_independent_of_span_subtype zero_ne_one (hl.mono (set.union_subset hsu htu)) (set.subset_union_right _ _) (set.union_subset (set.subset.trans subset_span hst) subset_span), rw ← this, apply set.subset_union_left end lemma span_le_span_iff {s t u: set M} (zero_ne_one : (0 : R) ≠ 1) (hl : linear_independent R (subtype.val : u → M )) (hsu : s ⊆ u) (htu : t ⊆ u) : span R s ≤ span R t ↔ s ⊆ t := ⟨le_of_span_le_span zero_ne_one hl hsu htu, span_mono⟩ variables (R) (v) /-- A family of vectors is a basis if it is linearly independent and all vectors are in the span. -/ def is_basis := linear_independent R v ∧ span R (range v) = ⊤ variables {R} {v} section is_basis variables {s t : set M} (hv : is_basis R v) lemma is_basis.mem_span (hv : is_basis R v) : ∀ x, x ∈ span R (range v) := eq_top_iff'.1 hv.2 lemma is_basis.comp (hv : is_basis R v) (f : ι' → ι) (hf : bijective f) : is_basis R (v ∘ f) := begin split, { apply hv.1.comp f hf.1 }, { rw[set.range_comp, range_iff_surjective.2 hf.2, image_univ, hv.2] } end lemma is_basis.injective (hv : is_basis R v) (zero_ne_one : (0 : R) ≠ 1) : injective v := λ x y h, linear_independent.injective zero_ne_one hv.1 h /- Given a basis, any vector can be written as a linear combination of the basis vectors. They are given by this linear map. This is one direction of `module_equiv_finsupp` -/ def is_basis.repr : M →ₗ (ι →₀ R) := (hv.1.repr).comp (linear_map.id.cod_restrict _ hv.mem_span) lemma is_basis.total_repr (x) : finsupp.total ι M R v (hv.repr x) = x := hv.1.total_repr ⟨x, _⟩ lemma is_basis.total_comp_repr : (finsupp.total ι M R v).comp hv.repr = linear_map.id := linear_map.ext hv.total_repr lemma is_basis.repr_ker : hv.repr.ker = ⊥ := linear_map.ker_eq_bot.2 $ injective_of_left_inverse hv.total_repr lemma is_basis.repr_range : hv.repr.range = finsupp.supported R R univ := by rw [is_basis.repr, linear_map.range, submodule.map_comp, linear_map.map_cod_restrict, submodule.map_id, comap_top, map_top, hv.1.repr_range, finsupp.supported_univ] lemma is_basis.repr_total (x : ι →₀ R) (hx : x ∈ finsupp.supported R R (univ : set ι)) : hv.repr (finsupp.total ι M R v x) = x := begin rw [← hv.repr_range, linear_map.mem_range] at hx, cases hx with w hw, rw [← hw, hv.total_repr], end lemma is_basis.repr_eq_single {i} : hv.repr (v i) = finsupp.single i 1 := by apply hv.1.repr_eq_single; simp /-- Construct a linear map given the value at the basis. -/ def is_basis.constr (f : ι → M') : M →ₗ[R] M' := (finsupp.total M' M' R id).comp $ (finsupp.lmap_domain R R f).comp hv.repr theorem is_basis.constr_apply (f : ι → M') (x : M) : (hv.constr f : M → M') x = (hv.repr x).sum (λb a, a • f b) := by dsimp [is_basis.constr]; rw [finsupp.total_apply, finsupp.sum_map_domain_index]; simp [add_smul] lemma is_basis.ext {f g : M →ₗ[R] M'} (hv : is_basis R v) (h : ∀i, f (v i) = g (v i)) : f = g := begin apply linear_map.ext (λ x, linear_eq_on (range v) _ (hv.mem_span x)), exact (λ y hy, exists.elim (set.mem_range.1 hy) (λ i hi, by rw ←hi; exact h i)) end lemma constr_basis {f : ι → M'} {i : ι} (hv : is_basis R v) : (hv.constr f : M → M') (v i) = f i := by simp [is_basis.constr_apply, hv.repr_eq_single, finsupp.sum_single_index] lemma constr_eq {g : ι → M'} {f : M →ₗ[R] M'} (hv : is_basis R v) (h : ∀i, g i = f (v i)) : hv.constr g = f := hv.ext $ λ i, (constr_basis hv).trans (h i) lemma constr_self (f : M →ₗ[R] M') : hv.constr (λ i, f (v i)) = f := constr_eq hv $ λ x, rfl lemma constr_zero (hv : is_basis R v) : hv.constr (λi, (0 : M')) = 0 := constr_eq hv $ λ x, rfl lemma constr_add {g f : ι → M'} (hv : is_basis R v) : hv.constr (λi, f i + g i) = hv.constr f + hv.constr g := constr_eq hv $ by simp [constr_basis hv] {contextual := tt} lemma constr_neg {f : ι → M'} (hv : is_basis R v) : hv.constr (λi, - f i) = - hv.constr f := constr_eq hv $ by simp [constr_basis hv] {contextual := tt} lemma constr_sub {g f : ι → M'} (hs : is_basis R v) : hv.constr (λi, f i - g i) = hs.constr f - hs.constr g := by simp [constr_add, constr_neg] -- this only works on functions if `R` is a commutative ring lemma constr_smul {ι R M M'} [comm_ring R] [add_comm_group M] [add_comm_group M'] [module R M] [module R M'] {v : ι → R} {f : ι → M'} {a : R} (hv : is_basis R v) {b : M} : hv.constr (λb, a • f b) = a • hv.constr f := constr_eq hv $ by simp [constr_basis hv] {contextual := tt} lemma constr_range [inhabited ι] (hv : is_basis R v) {f : ι → M'} : (hv.constr f).range = span R (range f) := by rw [is_basis.constr, linear_map.range_comp, linear_map.range_comp, is_basis.repr_range, finsupp.lmap_domain_supported, ←set.image_univ, ←finsupp.span_eq_map_total, image_id] /-- Canonical equivalence between a module and the linear combinations of basis vectors. -/ def module_equiv_finsupp (hv : is_basis R v) : M ≃ₗ[R] ι →₀ R := (hv.1.total_equiv.trans (linear_equiv.of_top _ hv.2)).symm /-- Isomorphism between the two modules, given two modules M and M' with respective bases v and v' and a bijection between the two bases. -/ def equiv_of_is_basis {v : ι → M} {v' : ι' → M'} {f : M → M'} {g : M' → M} (hv : is_basis R v) (hv' : is_basis R v') (hf : ∀i, f (v i) ∈ range v') (hg : ∀i, g (v' i) ∈ range v) (hgf : ∀i, g (f (v i)) = v i) (hfg : ∀i, f (g (v' i)) = v' i) : M ≃ₗ M' := { inv_fun := hv'.constr (g ∘ v'), left_inv := have (hv'.constr (g ∘ v')).comp (hv.constr (f ∘ v)) = linear_map.id, from hv.ext $ λ i, exists.elim (hf i) (λ i' hi', by simp [constr_basis, hi'.symm]; rw [hi', hgf]), λ x, congr_arg (λ h:M →ₗ[R] M, h x) this, right_inv := have (hv.constr (f ∘ v)).comp (hv'.constr (g ∘ v')) = linear_map.id, from hv'.ext $ λ i', exists.elim (hg i') (λ i hi, by simp [constr_basis, hi.symm]; rw [hi, hfg]), λ y, congr_arg (λ h:M' →ₗ[R] M', h y) this, ..hv.constr (f ∘ v) } lemma is_basis_inl_union_inr {v : ι → M} {v' : ι' → M'} (hv : is_basis R v) (hv' : is_basis R v') : is_basis R (sum.elim (inl R M M' ∘ v) (inr R M M' ∘ v')) := begin split, apply linear_independent_inl_union_inr' hv.1 hv'.1, rw [sum.elim_range, span_union, set.range_comp, span_image (inl R M M'), hv.2, map_top, set.range_comp, span_image (inr R M M'), hv'.2, map_top], exact linear_map.sup_range_inl_inr end end is_basis lemma is_basis_singleton_one (R : Type*) [unique ι] [ring R] : is_basis R (λ (_ : ι), (1 : R)) := begin split, { refine linear_independent_iff.2 (λ l, _), rw [finsupp.unique_single l, finsupp.total_single, smul_eq_mul, mul_one], intro hi, simp [hi] }, { refine top_unique (λ _ _, _), simp [submodule.mem_span_singleton] } end lemma linear_equiv.is_basis (hs : is_basis R v) (f : M ≃ₗ[R] M') : is_basis R (f ∘ v) := begin split, { apply @linear_independent.image _ _ _ _ _ _ _ _ _ _ hs.1 (f : M →ₗ[R] M'), simp [linear_equiv.ker f] }, { rw set.range_comp, have : span R ((f : M →ₗ[R] M') '' range v) = ⊤, { rw [span_image (f : M →ₗ[R] M'), hs.2], simp }, exact this } end lemma is_basis_span (hs : linear_independent R v) : @is_basis ι R (span R (range v)) (λ i : ι, ⟨v i, subset_span (mem_range_self _)⟩) _ _ _ := begin split, { apply linear_independent_span hs }, { rw eq_top_iff', intro x, have h₁ : subtype.val '' set.range (λ i, subtype.mk (v i) _) = range v, by rw ←set.range_comp, have h₂ : map (submodule.subtype _) (span R (set.range (λ i, subtype.mk (v i) _))) = span R (range v), by rw [←span_image, submodule.subtype_eq_val, h₁], have h₃ : (x : M) ∈ map (submodule.subtype _) (span R (set.range (λ i, subtype.mk (v i) _))), by rw h₂; apply subtype.mem x, rcases mem_map.1 h₃ with ⟨y, hy₁, hy₂⟩, have h_x_eq_y : x = y, by rw [subtype.coe_ext, ← hy₂]; simp, rw h_x_eq_y, exact hy₁ } end lemma is_basis_empty (h_empty : ¬ nonempty ι) (h : ∀x:M, x = 0) : is_basis R (λ x : ι, (0 : M)) := ⟨ linear_independent_empty_type h_empty, eq_top_iff'.2 $ assume x, (h x).symm ▸ submodule.zero_mem _ ⟩ lemma is_basis_empty_bot (h_empty : ¬ nonempty ι) : is_basis R (λ _ : ι, (0 : (⊥ : submodule R M))) := begin apply is_basis_empty h_empty, intro x, apply subtype.ext.2, exact (submodule.mem_bot R).1 (subtype.mem x), end open fintype variables [fintype ι] (h : is_basis R v) /-- A module over R with a finite basis is linearly equivalent to functions from its basis to R. -/ def equiv_fun_basis : M ≃ₗ[R] (ι → R) := linear_equiv.trans (module_equiv_finsupp h) { to_fun := finsupp.to_fun, add := λ x y, by ext; exact finsupp.add_apply, smul := λ x y, by ext; exact finsupp.smul_apply, ..finsupp.equiv_fun_on_fintype } theorem module.card_fintype [fintype R] [fintype M] : card M = (card R) ^ (card ι) := calc card M = card (ι → R) : card_congr (equiv_fun_basis h).to_equiv ... = card R ^ card ι : card_fun end module section vector_space variables {v : ι → V} [discrete_field K] [add_comm_group V] [add_comm_group V'] [vector_space K V] [vector_space K V'] {s t : set V} {x y z : V} include K open submodule /- TODO: some of the following proofs can generalized with a zero_ne_one predicate type class (instead of a data containing type class) -/ section set_option class.instance_max_depth 36 lemma mem_span_insert_exchange : x ∈ span K (insert y s) → x ∉ span K s → y ∈ span K (insert x s) := begin simp [mem_span_insert], rintro a z hz rfl h, refine ⟨a⁻¹, -a⁻¹ • z, smul_mem _ _ hz, _⟩, have a0 : a ≠ 0, {rintro rfl, simp * at *}, simp [a0, smul_add, smul_smul] end end lemma linear_independent_iff_not_mem_span : linear_independent K v ↔ (∀i, v i ∉ span K (v '' (univ \ {i}))) := begin apply linear_independent_iff_not_smul_mem_span.trans, split, { intros h i h_in_span, apply one_ne_zero (h i 1 (by simp [h_in_span])) }, { intros h i a ha, by_contradiction ha', exact false.elim (h _ ((smul_mem_iff _ ha').1 ha)) } end lemma linear_independent_unique [unique ι] (h : v (default ι) ≠ 0): linear_independent K v := begin rw linear_independent_iff, intros l hl, ext i, rw [unique.eq_default i, finsupp.zero_apply], by_contra hc, have := smul_smul _ (l (default ι))⁻¹ (l (default ι)) (v (default ι)), rw [finsupp.unique_single l, finsupp.total_single] at hl, rw [hl, inv_mul_cancel hc, smul_zero, one_smul] at this, exact h this.symm end lemma linear_independent_singleton {x : V} (hx : x ≠ 0) : linear_independent K (λ x, x : ({x} : set V) → V) := begin apply @linear_independent_unique _ _ _ _ _ _ _ _ _, apply set.unique_singleton, apply hx, end lemma disjoint_span_singleton {p : submodule K V} {x : V} (x0 : x ≠ 0) : disjoint p (span K {x}) ↔ x ∉ p := ⟨λ H xp, x0 (disjoint_def.1 H _ xp (singleton_subset_iff.1 subset_span:_)), begin simp [disjoint_def, mem_span_singleton], rintro xp y yp a rfl, by_cases a0 : a = 0, {simp [a0]}, exact xp.elim ((smul_mem_iff p a0).1 yp), end⟩ lemma linear_independent.insert (hs : linear_independent K (λ b, b : s → V)) (hx : x ∉ span K s) : linear_independent K (λ b, b : insert x s → V) := begin rw ← union_singleton, have x0 : x ≠ 0 := mt (by rintro rfl; apply zero_mem _) hx, apply linear_independent_union hs (linear_independent_singleton x0), rwa [disjoint_span_singleton x0] end lemma exists_linear_independent (hs : linear_independent K (λ x, x : s → V)) (hst : s ⊆ t) : ∃b⊆t, s ⊆ b ∧ t ⊆ span K b ∧ linear_independent K (λ x, x : b → V) := begin rcases zorn.zorn_subset₀ {b | b ⊆ t ∧ linear_independent K (λ x, x : b → V)} _ _ ⟨hst, hs⟩ with ⟨b, ⟨bt, bi⟩, sb, h⟩, { refine ⟨b, bt, sb, λ x xt, _, bi⟩, haveI := classical.dec (x ∈ span K b), by_contra hn, apply hn, rw ← h _ ⟨insert_subset.2 ⟨xt, bt⟩, bi.insert hn⟩ (subset_insert _ _), exact subset_span (mem_insert _ _) }, { refine λ c hc cc c0, ⟨⋃₀ c, ⟨_, _⟩, λ x, _⟩, { exact sUnion_subset (λ x xc, (hc xc).1) }, { exact linear_independent_sUnion_of_directed cc.directed_on (λ x xc, (hc xc).2) }, { exact subset_sUnion_of_mem } } end lemma exists_subset_is_basis (hs : linear_independent K (λ x, x : s → V)) : ∃b, s ⊆ b ∧ is_basis K (λ i : b, i.val) := let ⟨b, hb₀, hx, hb₂, hb₃⟩ := exists_linear_independent hs (@subset_univ _ _) in ⟨ b, hx, @linear_independent.restrict_of_comp_subtype _ _ _ id _ _ _ _ hb₃, by simp; exact eq_top_iff.2 hb₂⟩ variables (K V) lemma exists_is_basis : ∃b : set V, is_basis K (λ i : b, i.val) := let ⟨b, _, hb⟩ := exists_subset_is_basis linear_independent_empty in ⟨b, hb⟩ variables {K V} -- TODO(Mario): rewrite? lemma exists_of_linear_independent_of_finite_span {t : finset V} (hs : linear_independent K (λ x, x : s → V)) (hst : s ⊆ (span K ↑t : submodule K V)) : ∃t':finset V, ↑t' ⊆ s ∪ ↑t ∧ s ⊆ ↑t' ∧ t'.card = t.card := have ∀t, ∀(s' : finset V), ↑s' ⊆ s → s ∩ ↑t = ∅ → s ⊆ (span K ↑(s' ∪ t) : submodule K V) → ∃t':finset V, ↑t' ⊆ s ∪ ↑t ∧ s ⊆ ↑t' ∧ t'.card = (s' ∪ t).card := assume t, finset.induction_on t (assume s' hs' _ hss', have s = ↑s', from eq_of_linear_independent_of_span_subtype (@zero_ne_one K _) hs hs' $ by simpa using hss', ⟨s', by simp [this]⟩) (assume b₁ t hb₁t ih s' hs' hst hss', have hb₁s : b₁ ∉ s, from assume h, have b₁ ∈ s ∩ ↑(insert b₁ t), from ⟨h, finset.mem_insert_self _ _⟩, by rwa [hst] at this, have hb₁s' : b₁ ∉ s', from assume h, hb₁s $ hs' h, have hst : s ∩ ↑t = ∅, from eq_empty_of_subset_empty $ subset.trans (by simp [inter_subset_inter, subset.refl]) (le_of_eq hst), classical.by_cases (assume : s ⊆ (span K ↑(s' ∪ t) : submodule K V), let ⟨u, hust, hsu, eq⟩ := ih _ hs' hst this in have hb₁u : b₁ ∉ u, from assume h, (hust h).elim hb₁s hb₁t, ⟨insert b₁ u, by simp [insert_subset_insert hust], subset.trans hsu (by simp), by simp [eq, hb₁t, hb₁s', hb₁u]⟩) (assume : ¬ s ⊆ (span K ↑(s' ∪ t) : submodule K V), let ⟨b₂, hb₂s, hb₂t⟩ := not_subset.mp this in have hb₂t' : b₂ ∉ s' ∪ t, from assume h, hb₂t $ subset_span h, have s ⊆ (span K ↑(insert b₂ s' ∪ t) : submodule K V), from assume b₃ hb₃, have ↑(s' ∪ insert b₁ t) ⊆ insert b₁ (insert b₂ ↑(s' ∪ t) : set V), by simp [insert_eq, -singleton_union, -union_singleton, union_subset_union, subset.refl, subset_union_right], have hb₃ : b₃ ∈ span K (insert b₁ (insert b₂ ↑(s' ∪ t) : set V)), from span_mono this (hss' hb₃), have s ⊆ (span K (insert b₁ ↑(s' ∪ t)) : submodule K V), by simpa [insert_eq, -singleton_union, -union_singleton] using hss', have hb₁ : b₁ ∈ span K (insert b₂ ↑(s' ∪ t)), from mem_span_insert_exchange (this hb₂s) hb₂t, by rw [span_insert_eq_span hb₁] at hb₃; simpa using hb₃, let ⟨u, hust, hsu, eq⟩ := ih _ (by simp [insert_subset, hb₂s, hs']) hst this in ⟨u, subset.trans hust $ union_subset_union (subset.refl _) (by simp [subset_insert]), hsu, by rw [finset.union_comm] at hb₂t'; simp [eq, hb₂t', hb₁t, hb₁s']⟩)), begin letI := classical.dec_pred (λx, x ∈ s), have eq : t.filter (λx, x ∈ s) ∪ t.filter (λx, x ∉ s) = t, { apply finset.ext.mpr, intro x, by_cases x ∈ s; simp *, finish }, apply exists.elim (this (t.filter (λx, x ∉ s)) (t.filter (λx, x ∈ s)) (by simp [set.subset_def]) (by simp [set.ext_iff] {contextual := tt}) (by rwa [eq])), intros u h, exact ⟨u, subset.trans h.1 (by simp [subset_def, and_imp, or_imp_distrib] {contextual:=tt}), h.2.1, by simp only [h.2.2, eq]⟩ end lemma exists_finite_card_le_of_finite_of_linear_independent_of_span (ht : finite t) (hs : linear_independent K (λ x, x : s → V)) (hst : s ⊆ span K t) : ∃h : finite s, h.to_finset.card ≤ ht.to_finset.card := have s ⊆ (span K ↑(ht.to_finset) : submodule K V), by simp; assumption, let ⟨u, hust, hsu, eq⟩ := exists_of_linear_independent_of_finite_span hs this in have finite s, from finite_subset u.finite_to_set hsu, ⟨this, by rw [←eq]; exact (finset.card_le_of_subset $ finset.coe_subset.mp $ by simp [hsu])⟩ lemma exists_left_inverse_linear_map_of_injective {f : V →ₗ[K] V'} (hf_inj : f.ker = ⊥) : ∃g:V' →ₗ V, g.comp f = linear_map.id := begin rcases exists_is_basis K V with ⟨B, hB⟩, have hB₀ : _ := hB.1.to_subtype_range, have : linear_independent K (λ x, x : f '' B → V'), { have h₁ := hB₀.image_subtype (show disjoint (span K (range (λ i : B, i.val))) (linear_map.ker f), by simp [hf_inj]), have h₂ : range (λ (i : B), i.val) = B := subtype.range_val B, rwa h₂ at h₁ }, rcases exists_subset_is_basis this with ⟨C, BC, hC⟩, haveI : inhabited V := ⟨0⟩, use hC.constr (function.restrict (inv_fun f) C : C → V), apply @is_basis.ext _ _ _ _ _ _ _ _ _ _ _ _ hB, intros b, rw image_subset_iff at BC, simp, have := BC (subtype.mem b), rw mem_preimage at this, have : f (b.val) = (subtype.mk (f ↑b) (begin rw ←mem_preimage, exact BC (subtype.mem b) end) : C).val, by simp; unfold_coes, rw this, rw [constr_basis hC], exact left_inverse_inv_fun (linear_map.ker_eq_bot.1 hf_inj) _, end lemma exists_right_inverse_linear_map_of_surjective {f : V →ₗ[K] V'} (hf_surj : f.range = ⊤) : ∃g:V' →ₗ V, f.comp g = linear_map.id := begin rcases exists_is_basis K V' with ⟨C, hC⟩, haveI : inhabited V := ⟨0⟩, use hC.constr (function.restrict (inv_fun f) C : C → V), apply @is_basis.ext _ _ _ _ _ _ _ _ _ _ _ _ hC, intros c, simp [constr_basis hC], exact right_inverse_inv_fun (linear_map.range_eq_top.1 hf_surj) _ end set_option class.instance_max_depth 49 open submodule linear_map theorem quotient_prod_linear_equiv (p : submodule K V) : nonempty ((p.quotient × p) ≃ₗ[K] V) := begin haveI := classical.dec_eq (quotient p), rcases exists_right_inverse_linear_map_of_surjective p.range_mkq with ⟨f, hf⟩, have mkf : ∀ x, submodule.quotient.mk (f x) = x := linear_map.ext_iff.1 hf, have fp : ∀ x, x - f (p.mkq x) ∈ p := λ x, (submodule.quotient.eq p).1 (mkf (p.mkq x)).symm, refine ⟨linear_equiv.of_linear (f.copair p.subtype) (p.mkq.pair (cod_restrict p (linear_map.id - f.comp p.mkq) fp)) (by ext; simp) _⟩, ext ⟨⟨x⟩, y, hy⟩; simp, { apply (submodule.quotient.eq p).2, simpa using sub_mem p hy (fp x) }, { refine subtype.coe_ext.2 _, simp [mkf, (submodule.quotient.mk_eq_zero p).2 hy] } end open fintype theorem vector_space.card_fintype [fintype K] [fintype V] : ∃ n : ℕ, card V = (card K) ^ n := begin apply exists.elim (exists_is_basis K V), intros b hb, haveI := classical.dec_pred (λ x, x ∈ b), use card b, exact module.card_fintype hb, end end vector_space namespace pi open set linear_map section module variables {η : Type*} {ιs : η → Type*} {Ms : η → Type*} variables [ring R] [∀i, add_comm_group (Ms i)] [∀i, module R (Ms i)] [fintype η] lemma linear_independent_std_basis (v : Πj, ιs j → (Ms j)) (hs : ∀i, linear_independent R (v i)) : linear_independent R (λ (ji : Σ j, ιs j), std_basis R Ms ji.1 (v ji.1 ji.2)) := begin have hs' : ∀j : η, linear_independent R (λ i : ιs j, std_basis R Ms j (v j i)), { intro j, apply linear_independent.image (hs j), simp [ker_std_basis] }, apply linear_independent_Union_finite hs', { assume j J _ hiJ, simp [(set.Union.equations._eqn_1 _).symm, submodule.span_image, submodule.span_Union], have h₀ : ∀ j, span R (range (λ (i : ιs j), std_basis R Ms j (v j i))) ≤ range (std_basis R Ms j), { intro j, rw [span_le, linear_map.range_coe], apply range_comp_subset_range }, have h₁ : span R (range (λ (i : ιs j), std_basis R Ms j (v j i))) ≤ ⨆ i ∈ {j}, range (std_basis R Ms i), { rw @supr_singleton _ _ _ (λ i, linear_map.range (std_basis R (λ (j : η), Ms j) i)), apply h₀ }, have h₂ : (⨆ j ∈ J, span R (range (λ (i : ιs j), std_basis R Ms j (v j i)))) ≤ ⨆ j ∈ J, range (std_basis R (λ (j : η), Ms j) j) := supr_le_supr (λ i, supr_le_supr (λ H, h₀ i)), have h₃ : disjoint (λ (i : η), i ∈ {j}) J, { convert set.disjoint_singleton_left.2 hiJ, rw ←@set_of_mem_eq _ {j}, refl }, refine disjoint_mono h₁ h₂ (disjoint_std_basis_std_basis _ _ _ _ h₃), } end lemma is_basis_std_basis (s : Πj, ιs j → (Ms j)) (hs : ∀j, is_basis R (s j)) : is_basis R (λ (ji : Σ j, ιs j), std_basis R Ms ji.1 (s ji.1 ji.2)) := begin split, { apply linear_independent_std_basis _ (assume i, (hs i).1) }, have h₁ : Union (λ j, set.range (std_basis R Ms j ∘ s j)) ⊆ range (λ (ji : Σ (j : η), ιs j), (std_basis R Ms (ji.fst)) (s (ji.fst) (ji.snd))), { apply Union_subset, intro i, apply range_comp_subset_range (λ x : ιs i, (⟨i, x⟩ : Σ (j : η), ιs j)) (λ (ji : Σ (j : η), ιs j), std_basis R Ms (ji.fst) (s (ji.fst) (ji.snd))) }, have h₂ : ∀ i, span R (range (std_basis R Ms i ∘ s i)) = range (std_basis R Ms i), { intro i, rw [set.range_comp, submodule.span_image, (assume i, (hs i).2), submodule.map_top] }, apply eq_top_mono, apply span_mono h₁, rw span_Union, simp only [h₂], apply supr_range_std_basis end section variables (R ι) lemma is_basis_fun₀ : is_basis R (λ (ji : Σ (j : η), (λ _, unit) j), (std_basis R (λ (i : η), R) (ji.fst)) 1) := begin haveI := classical.dec_eq, apply @is_basis_std_basis R η (λi:η, unit) (λi:η, R) _ _ _ _ (λ _ _, (1 : R)) (assume i, @is_basis_singleton_one _ _ _ _), end lemma is_basis_fun : is_basis R (λ i, std_basis R (λi:η, R) i 1) := begin apply is_basis.comp (is_basis_fun₀ R) (λ i, ⟨i, punit.star⟩) , { apply bijective_iff_has_inverse.2, use (λ x, x.1), simp [function.left_inverse, function.right_inverse], intros _ b, rw [unique.eq_default b, unique.eq_default punit.star] }, apply_instance end end end module end pi
bdcdab00629dd88e50c4357f18069475e0d25860
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/category_theory/closed/zero.lean
ae9c89c07b3332552db3b33ee62518354cd8670b
[ "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
2,131
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.closed.cartesian import category_theory.limits.shapes.zero import category_theory.punit import category_theory.conj /-! # A cartesian closed category with zero object is trivial A cartesian closed category with zero object is trivial: it is equivalent to the category with one object and one morphism. ## References * https://mathoverflow.net/a/136480 -/ universes v u noncomputable theory namespace category_theory open category limits variables {C : Type u} [category.{v} C] variables [has_finite_products C] [cartesian_closed C] /-- If a cartesian closed category has an initial object which is isomorphic to the terminal object, then each homset has exactly one element. -/ def unique_homset_of_initial_iso_terminal [has_initial C] (i : ⊥_ C ≅ ⊤_ C) (X Y : C) : unique (X ⟶ Y) := equiv.unique $ calc (X ⟶ Y) ≃ (X ⨯ ⊤_ C ⟶ Y) : iso.hom_congr (prod.right_unitor _).symm (iso.refl _) ... ≃ (X ⨯ ⊥_ C ⟶ Y) : iso.hom_congr (prod.map_iso (iso.refl _) i.symm) (iso.refl _) ... ≃ (⊥_ C ⟶ Y ^^ X) : (exp.adjunction _).hom_equiv _ _ open_locale zero_object /-- If a cartesian closed category has a zero object, each homset has exactly one element. -/ def unique_homset_of_zero [has_zero_object C] (X Y : C) : unique (X ⟶ Y) := begin haveI : has_initial C := has_zero_object.has_initial, apply unique_homset_of_initial_iso_terminal _ X Y, refine ⟨default _, default (⊤_ C ⟶ 0) ≫ default _, _, _⟩; simp, end local attribute [instance] unique_homset_of_zero /-- A cartesian closed category with a zero object is equivalent to the category with one object and one morphism. -/ def equiv_punit [has_zero_object C] : C ≌ discrete punit := equivalence.mk (functor.star C) (functor.from_punit 0) (nat_iso.of_components (λ X, { hom := default (X ⟶ 0), inv := default (0 ⟶ X) }) (λ X Y f, dec_trivial)) (functor.punit_ext _ _) end category_theory
c07f0bd54742547c45218ab7eff3989364ef7bfb
32025d5c2d6e33ad3b6dd8a3c91e1e838066a7f7
/tests/lean/run/recInfo1.lean
6451f5786a741716d44c4ab344686f05a76cade6
[ "Apache-2.0" ]
permissive
walterhu1015/lean4
b2c71b688975177402758924eaa513475ed6ce72
2214d81e84646a905d0b20b032c89caf89c737ad
refs/heads/master
1,671,342,096,906
1,599,695,985,000
1,599,695,985,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
522
lean
import Lean.Meta open Lean open Lean.Meta def print (msg : MessageData) : MetaM Unit := trace! `Meta.debug msg def showRecInfo (declName : Name) (majorPos? : Option Nat := none) : MetaM Unit := do info ← mkRecursorInfo declName majorPos?; print (toString info) set_option trace.Meta true set_option trace.Meta.isDefEq false #eval showRecInfo `Acc.recOn #eval showRecInfo `Prod.casesOn #eval showRecInfo `List.recOn #eval showRecInfo `List.casesOn #eval showRecInfo `List.brecOn #eval showRecInfo `Iff.elim (some 4)
d2a1fcd3a7796d36466cfb388e8f1f08ece1c87c
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/stage0/src/Lean/ResolveName.lean
abdbe3e026c990fe94356dfa8dcd2b7996fa37c0
[ "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
12,427
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Sebastian Ullrich -/ import Lean.Data.OpenDecl import Lean.Hygiene import Lean.Modifiers import Lean.Exception namespace Lean /-! We use aliases to implement the `export <id> (<id>+)` command. An `export A (x)` in the namespace `B` produces an alias `B.x ~> A.x`. -/ abbrev AliasState := SMap Name (List Name) abbrev AliasEntry := Name × Name def addAliasEntry (s : AliasState) (e : AliasEntry) : AliasState := match s.find? e.1 with | none => s.insert e.1 [e.2] | some es => if es.elem e.2 then s else s.insert e.1 (e.2 :: es) builtin_initialize aliasExtension : SimplePersistentEnvExtension AliasEntry AliasState ← registerSimplePersistentEnvExtension { name := `aliasesExt, addEntryFn := addAliasEntry, addImportedFn := fun es => mkStateFromImportedEntries addAliasEntry {} es |>.switch } /-- Add alias `a` for `e` -/ @[export lean_add_alias] def addAlias (env : Environment) (a : Name) (e : Name) : Environment := aliasExtension.addEntry env (a, e) def getAliasState (env : Environment) : AliasState := aliasExtension.getState env /-- Retrieve aliases for `a`. If `skipProtected` is `true`, then the resulting list only includes declarations that are not marked as `proctected`. -/ def getAliases (env : Environment) (a : Name) (skipProtected : Bool) : List Name := match aliasExtension.getState env |>.find? a with | none => [] | some es => if skipProtected then es.filter (!isProtected env ·) else es -- slower, but only used in the pretty printer def getRevAliases (env : Environment) (e : Name) : List Name := (aliasExtension.getState env).fold (fun as a es => if List.contains es e then a :: as else as) [] /-! # Global name resolution -/ namespace ResolveName /-- Check whether `ns ++ id` is a valid namepace name and/or there are aliases names `ns ++ id`. -/ private def resolveQualifiedName (env : Environment) (ns : Name) (id : Name) : List Name := let resolvedId := ns ++ id -- We ignore protected aliases if `id` is atomic. let resolvedIds := getAliases env resolvedId (skipProtected := id.isAtomic) if env.contains resolvedId && (!id.isAtomic || !isProtected env resolvedId) then resolvedId :: resolvedIds else -- Check whether environment contains the private version. That is, `_private.<module_name>.ns.id`. let resolvedIdPrv := mkPrivateName env resolvedId if env.contains resolvedIdPrv then resolvedIdPrv :: resolvedIds else resolvedIds /-- Check surrounding namespaces -/ private def resolveUsingNamespace (env : Environment) (id : Name) : Name → List Name | ns@(.str p _) => match resolveQualifiedName env ns id with | [] => resolveUsingNamespace env id p | resolvedIds => resolvedIds | _ => [] /-- Check exact name -/ private def resolveExact (env : Environment) (id : Name) : Option Name := if id.isAtomic then none else let resolvedId := id.replacePrefix rootNamespace Name.anonymous if env.contains resolvedId then some resolvedId else -- We also allow `_root` when accessing private declarations. -- If we change our minds, we should just replace `resolvedId` with `id` let resolvedIdPrv := mkPrivateName env resolvedId if env.contains resolvedIdPrv then some resolvedIdPrv else none /-- Check `OpenDecl`s -/ private def resolveOpenDecls (env : Environment) (id : Name) : List OpenDecl → List Name → List Name | [], resolvedIds => resolvedIds | OpenDecl.simple ns exs :: openDecls, resolvedIds => if exs.elem id then resolveOpenDecls env id openDecls resolvedIds else let newResolvedIds := resolveQualifiedName env ns id resolveOpenDecls env id openDecls (newResolvedIds ++ resolvedIds) | OpenDecl.explicit openedId resolvedId :: openDecls, resolvedIds => let resolvedIds := if openedId == id then resolvedId :: resolvedIds else if openedId.isPrefixOf id then let candidate := id.replacePrefix openedId resolvedId if env.contains candidate then candidate :: resolvedIds else resolvedIds else resolvedIds resolveOpenDecls env id openDecls resolvedIds def resolveGlobalName (env : Environment) (ns : Name) (openDecls : List OpenDecl) (id : Name) : List (Name × List String) := -- decode macro scopes from name before recursion let extractionResult := extractMacroScopes id let rec loop (id : Name) (projs : List String) : List (Name × List String) := match id with | .str p s => -- NOTE: we assume that macro scopes always belong to the projected constant, not the projections let id := { extractionResult with name := id }.review match resolveUsingNamespace env id ns with | resolvedIds@(_ :: _) => resolvedIds.eraseDups.map fun id => (id, projs) | [] => match resolveExact env id with | some newId => [(newId, projs)] | none => let resolvedIds := if env.contains id then [id] else [] let idPrv := mkPrivateName env id let resolvedIds := if env.contains idPrv then [idPrv] ++ resolvedIds else resolvedIds let resolvedIds := resolveOpenDecls env id openDecls resolvedIds let resolvedIds := getAliases env id (skipProtected := id.isAtomic) ++ resolvedIds match resolvedIds with | _ :: _ => resolvedIds.eraseDups.map fun id => (id, projs) | [] => loop p (s::projs) | _ => [] loop extractionResult.name [] /-! # Namespace resolution -/ def resolveNamespaceUsingScope? (env : Environment) (n : Name) : Name → Option Name | .anonymous => if env.isNamespace n then some n else none | ns@(.str p _) => if env.isNamespace (ns ++ n) then some (ns ++ n) else resolveNamespaceUsingScope? env n p | _ => unreachable! def resolveNamespaceUsingOpenDecls (env : Environment) (n : Name) : List OpenDecl → List Name | [] => [] | OpenDecl.simple ns [] :: ds => if env.isNamespace (ns ++ n) then (ns ++ n) :: resolveNamespaceUsingOpenDecls env n ds else resolveNamespaceUsingOpenDecls env n ds | _ :: ds => resolveNamespaceUsingOpenDecls env n ds /-- Given a name `id` try to find namespaces it may refer to. The resolution procedure works as follows 1- If `id` is in the scope of `namespace` commands the namespace `s_1. ... . s_n`, then we include `s_1 . ... . s_i ++ n` in the result if it is the name of an existing namespace. We search "backwards", and include at most one of the in the list of resulting namespaces. 2- If `id` is the extact name of an existing namespace, then include `id` 3- Finally, for each command `open N`, include in the result `N ++ n` if it is the name of an existing namespace. We only consider simple `open` commands. -/ def resolveNamespace (env : Environment) (ns : Name) (openDecls : List OpenDecl) (id : Name) : List Name := match resolveNamespaceUsingScope? env id ns with | some ns => ns :: resolveNamespaceUsingOpenDecls env id openDecls | none => resolveNamespaceUsingOpenDecls env id openDecls end ResolveName class MonadResolveName (m : Type → Type) where getCurrNamespace : m Name getOpenDecls : m (List OpenDecl) export MonadResolveName (getCurrNamespace getOpenDecls) instance (m n) [MonadLift m n] [MonadResolveName m] : MonadResolveName n where getCurrNamespace := liftM (m:=m) getCurrNamespace getOpenDecls := liftM (m:=m) getOpenDecls /-- Given a name `n`, return a list of possible interpretations. Each interpretation is a pair `(declName, fieldList)`, where `declName` is the name of a declaration in the current environment, and `fieldList` are (potential) field names. The pair is needed because in Lean `.` may be part of a qualified name or a field (aka dot-notation). As an example, consider the following definitions ``` def Boo.x := 1 def Foo.x := 2 def Foo.x.y := 3 ``` After `open Foo`, we have - `resolveGlobalName x` => `[(Foo.x, [])]` - `resolveGlobalName x.y` => `[(Foo.x.y, [])]` - `resolveGlobalName x.z.w` => `[(Foo.x, [z, w])]` After `open Foo open Boo`, we have - `resolveGlobalName x` => `[(Foo.x, []), (Boo.x, [])]` - `resolveGlobalName x.y` => `[(Foo.x.y, [])]` - `resolveGlobalName x.z.w` => `[(Foo.x, [z, w]), (Boo.x, [z, w])]` -/ def resolveGlobalName [Monad m] [MonadResolveName m] [MonadEnv m] (id : Name) : m (List (Name × List String)) := do return ResolveName.resolveGlobalName (← getEnv) (← getCurrNamespace) (← getOpenDecls) id def resolveNamespace [Monad m] [MonadResolveName m] [MonadEnv m] [MonadError m] (id : Name) : m (List Name) := do match ResolveName.resolveNamespace (← getEnv) (← getCurrNamespace) (← getOpenDecls) id with | [] => throwError s!"unknown namespace '{id}'" | nss => return nss def resolveUniqueNamespace [Monad m] [MonadResolveName m] [MonadEnv m] [MonadError m] (id : Name) : m Name := do match (← resolveNamespace id) with | [ns] => return ns | nss => throwError s!"ambiguous namespace '{id}', possible interpretations: '{nss}'" /-- Given a name `n`, return a list of possible interpretations for global constants. Similar to `resolveGlobalName`, but discard any candidate whose `fieldList` is not empty. For identifiers taken from syntax, use `resolveGlobalConst` instead, which respects preresolved names. -/ def resolveGlobalConstCore [Monad m] [MonadResolveName m] [MonadEnv m] [MonadError m] (n : Name) : m (List Name) := do let cs ← resolveGlobalName n let cs := cs.filter fun (_, fieldList) => fieldList.isEmpty if cs.isEmpty then throwUnknownConstant n return cs.map (·.1) /-- For identifiers taken from syntax, use `resolveGlobalConstNoOverload` instead, which respects preresolved names. -/ def resolveGlobalConstNoOverloadCore [Monad m] [MonadResolveName m] [MonadEnv m] [MonadError m] (n : Name) : m Name := do let cs ← resolveGlobalConstCore n match cs with | [c] => pure c | _ => throwError s!"ambiguous identifier '{mkConst n}', possible interpretations: {cs.map mkConst}" /-- Interpret the syntax `n` as an identifier for a global constant, and return a list of resolved constant names that it could be refering to based on the currently open namespaces. This should be used instead of `resolveGlobalConstCore` for identifiers taken from syntax because `Syntax` objects may have names that have already been resolved. ## Example: ``` def Boo.x := 1 def Foo.x := 2 def Foo.x.y := 3 ``` After `open Foo`, we have - `resolveGlobalConst x` => `[Foo.x]` - `resolveGlobalConst x.y` => `[Foo.x.y]` - `resolveGlobalConst x.z.w` => error: unknown constant After `open Foo open Boo`, we have - `resolveGlobalConst x` => `[Foo.x, Boo.x]` - `resolveGlobalConst x.y` => `[Foo.x.y]` - `resolveGlobalConst x.z.w` => error: unknown constant -/ def resolveGlobalConst [Monad m] [MonadResolveName m] [MonadEnv m] [MonadError m] : Syntax → m (List Name) | stx@(Syntax.ident _ _ n pre) => do let pre := pre.filterMap fun (n, fields) => if fields.isEmpty then some n else none if pre.isEmpty then withRef stx <| resolveGlobalConstCore n else return pre | stx => throwErrorAt stx s!"expected identifier" /-- Interpret the syntax `n` as an identifier for a global constant, and return a resolved constant name. If there are multiple possible interpretations it will throw. ## Example: ``` def Boo.x := 1 def Foo.x := 2 def Foo.x.y := 3 ``` After `open Foo`, we have - `resolveGlobalConstNoOverload x` => `Foo.x` - `resolveGlobalConstNoOverload x.y` => `Foo.x.y` - `resolveGlobalConstNoOverload x.z.w` => error: unknown constant After `open Foo open Boo`, we have - `resolveGlobalConstNoOverload x` => error: ambiguous identifier - `resolveGlobalConstNoOverload x.y` => `Foo.x.y` - `resolveGlobalConstNoOverload x.z.w` => error: unknown constant -/ def resolveGlobalConstNoOverload [Monad m] [MonadResolveName m] [MonadEnv m] [MonadError m] (id : Syntax) : m Name := do let cs ← resolveGlobalConst id match cs with | [c] => pure c | _ => throwErrorAt id s!"ambiguous identifier '{id}', possible interpretations: {cs.map mkConst}" end Lean
f10f15ab1cd3c005d0b843a4d61c53f94d31fced
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/tactic/dec_trivial_auto.lean
64cbf233ee50ecedff998a0f00bbf0e97ba6a22a
[]
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
941
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 Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.tactic.interactive import Mathlib.PostPort namespace Mathlib /-! # `dec_trivial` tactic The `dec_trivial` tactic tries to use decidability to prove a goal. It is basically a glorified wrapper around `exact dec_trivial`. There is an extra option to make it a little bit smarter: `dec_trivial!` will revert all hypotheses on which the target depends, before it tries `exact dec_trivial`. -/ /-- `dec_trivial` tries to use decidability to prove a goal (i.e., using `exact dec_trivial`). The variant `dec_trivial!` will revert all hypotheses on which the target depends, before it tries `exact dec_trivial`. Example: ```lean example (n : ℕ) (h : n < 2) : n = 0 ∨ n = 1 := by dec_trivial! ``` -/ end Mathlib
428a4ab626aa2e9d4761b4a13d47a8221044646c
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/ring_theory/principal_ideal_domain.lean
b69eb9ce9b1c63c10f8b46c9ef2a0aca8db8a348
[ "Apache-2.0" ]
permissive
agjftucker/mathlib
d634cd0d5256b6325e3c55bb7fb2403548371707
87fe50de17b00af533f72a102d0adefe4a2285e8
refs/heads/master
1,625,378,131,941
1,599,166,526,000
1,599,166,526,000
160,748,509
0
0
Apache-2.0
1,544,141,789,000
1,544,141,789,000
null
UTF-8
Lean
false
false
9,158
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: 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_domain`: a noncomputable definition, putting a UFD structure on a PID. Note that the definition of a UFD is currently not a predicate, as it contains data of factorizations of non-zero elements. # 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 the `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] end submodule.is_principal namespace is_prime open submodule.is_principal ideal -- TODO -- for a non-ID should prove that if p < q then q maximal; 0 isn't prime in a non-ID 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.2 (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 ▸ ideal.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 ▸ ideal.add_mem S (ideal.mul_mem_right S hy) hxy, λ hx, (mod_eq_sub_mul_div x y).symm ▸ ideal.sub_mem S hx (ideal.mul_mem_right S 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 ▸ ideal.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 := ⟨assume s : ideal R, begin rcases (is_principal_ideal_ring.principal s).principal with ⟨a, rfl⟩, rw [← finset.coe_singleton], exact ⟨{a}, submodule.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 (is_noetherian_ring.exists_factors a h) lemma factors_spec (a : R) (h : a ≠ 0) : (∀b∈factors a, irreducible b) ∧ associated a (factors a).prod := begin unfold factors, rw [dif_neg h], exact classical.some_spec (is_noetherian_ring.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).symm 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 /-- The unique factorization domain structure given by the principal ideal domain. This is not added as type class instance, since the `factors` might be computed in a different way. E.g. factors could return normalized values. -/ noncomputable def to_unique_factorization_domain : unique_factorization_domain R := { factors := factors, factors_prod := assume a ha, associated.symm (factors_spec a ha).2, prime_factors := assume a ha, by simpa [irreducible_iff_prime] using (factors_spec a ha).1 } end end principal_ideal_ring
d23c1d56a312c5cedc0f8f85063fd338967c6fbf
f09e92753b1d3d2eb3ce2cfb5288a7f5d1d4bd89
/src/for_mathlib/option_inj.lean
d25b263119c1d6050104bca860f934c4430eb74c
[ "Apache-2.0" ]
permissive
PatrickMassot/lean-perfectoid-spaces
7f63c581db26461b5a92d968e7563247e96a5597
5f70b2020b3c6d508431192b18457fa988afa50d
refs/heads/master
1,625,797,721,782
1,547,308,357,000
1,547,309,364,000
136,658,414
0
1
Apache-2.0
1,528,486,100,000
1,528,486,100,000
null
UTF-8
Lean
false
false
317
lean
universes u v open function theorem option.map_inj {α : Type u} {β : Type v} {f : α → β} (Hf : injective f) : injective (option.map f) := λ a₁ a₂ H, begin cases h₁ : a₁;cases h₂ : a₂;rw [h₁,h₂] at H; try {exact option.no_confusion H}, congr,apply Hf,apply option.some.inj,exact H end
937a5d94f520123ee167bf96dd655303a2c86094
b73bd2854495d87ad5ce4f247cfcd6faa7e71c7e
/src/game/world4/level2.lean
ab89fca677b0bb9df9d0ff8b8fee7476643a02c0
[]
no_license
agusakov/category-theory-game
20db0b26270e0c95a3d5605498570273d72f731d
652dd7e90ae706643b2a597e2c938403653e167d
refs/heads/master
1,669,201,216,310
1,595,740,057,000
1,595,740,057,000
280,895,295
12
0
null
null
null
null
UTF-8
Lean
false
false
1,665
lean
import category_theory.category.default import category_theory.functor import category_theory.isomorphism universes v₁ v₂ u₁ u₂ -- The order in this declaration matters: v often needs to be explicitly specified while u often can be omitted namespace category_theory variables (C : Type u₁) [category.{v₁} C] variables (D : Type u₂) [category.{v₂} D] /- # Functor world ## Level 1: Definition of functor A functor `F : C ⥤ D` between categories `C` and `D` consists of * an object `F.obj X ∈ D` for all objects `X ∈ C` * a morphism `Ff : F.obj X ⟶ F.obj Y` for each morphism `f : X ⟶ Y`, where the domain and codomain of `Ff` are, respectively, equal to `F` applied to the domain and codomain of `f`. The assignments are required to satisfy the following two functoriality axioms: * for any composable pair of morphisms `f, g` in `C`, `F.map f ≫ F.map g = F.map (f ≫ g)`. * for each object `X` in `C`, `F.map (𝟙 X) : 𝟙 (F.obj X)`. In other words, a functor consists of a mapping on objects and a mapping on morphisms that preserves all of the structure of a category, namely domains and codomains, composition, and identities. -/ /- Axiom : F.map f ≫ F.map g = F.map (f ≫ g)-/ /- Axiom: F.map (𝟙 X) : 𝟙 (F.obj X)-/ /-- A functor `F : C ⥤ D` sends isomorphisms `i : X ≅ Y` to isomorphisms `F.obj X ≅ F.obj Y` -/ def map_iso (F : C ⥤ D) {X Y : C} (i : X ≅ Y) : F.obj X ≅ F.obj Y := { hom := F.map i.hom, inv := F.map i.inv, hom_inv_id' := by rw [←map_comp, iso.hom_inv_id, ←map_id], inv_hom_id' := by rw [←map_comp, iso.inv_hom_id, ←map_id] } end category_theory
19461dd22f5643160f97911cc76ab2804d35b14f
26ac254ecb57ffcb886ff709cf018390161a9225
/src/data/real/cardinality.lean
86a9578d6daf5a9f89f62bfc6e293f2b1ce19d7a
[ "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
7,818
lean
/- Copyright (c) 2019 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn The cardinality of the reals. -/ import set_theory.ordinal import analysis.specific_limits import data.rat.denumerable import data.set.intervals.image_preimage open nat set noncomputable theory namespace cardinal variables {c : ℝ} {f g : ℕ → bool} {n : ℕ} def cantor_function_aux (c : ℝ) (f : ℕ → bool) (n : ℕ) : ℝ := cond (f n) (c ^ n) 0 @[simp] lemma cantor_function_aux_tt (h : f n = tt) : cantor_function_aux c f n = c ^ n := by simp [cantor_function_aux, h] @[simp] lemma cantor_function_aux_ff (h : f n = ff) : cantor_function_aux c f n = 0 := by simp [cantor_function_aux, h] lemma cantor_function_aux_nonneg (h : 0 ≤ c) : 0 ≤ cantor_function_aux c f n := by { cases h' : f n; simp [h'], apply pow_nonneg h } lemma cantor_function_aux_eq (h : f n = g n) : cantor_function_aux c f n = cantor_function_aux c g n := by simp [cantor_function_aux, h] lemma cantor_function_aux_succ (f : ℕ → bool) : (λ n, cantor_function_aux c f (n + 1)) = λ n, c * cantor_function_aux c (λ n, f (n + 1)) n := by { ext n, cases h : f (n + 1); simp [h, pow_succ] } lemma summable_cantor_function (f : ℕ → bool) (h1 : 0 ≤ c) (h2 : c < 1) : summable (cantor_function_aux c f) := begin apply (summable_geometric_of_lt_1 h1 h2).summable_of_eq_zero_or_self, intro n, cases h : f n; simp [h] end def cantor_function (c : ℝ) (f : ℕ → bool) : ℝ := ∑' n, cantor_function_aux c f n lemma cantor_function_le (h1 : 0 ≤ c) (h2 : c < 1) (h3 : ∀ n, f n → g n) : cantor_function c f ≤ cantor_function c g := begin apply tsum_le_tsum _ (summable_cantor_function f h1 h2) (summable_cantor_function g h1 h2), intro n, cases h : f n, simp [h, cantor_function_aux_nonneg h1], replace h3 : g n = tt := h3 n h, simp [h, h3] end lemma cantor_function_succ (f : ℕ → bool) (h1 : 0 ≤ c) (h2 : c < 1) : cantor_function c f = cond (f 0) 1 0 + c * cantor_function c (λ n, f (n+1)) := begin rw [cantor_function, tsum_eq_zero_add (summable_cantor_function f h1 h2)], rw [cantor_function_aux_succ, tsum_mul_left _ (summable_cantor_function _ h1 h2)], refl end lemma increasing_cantor_function (h1 : 0 < c) (h2 : c < 1 / 2) {n : ℕ} {f g : ℕ → bool} (hn : ∀(k < n), f k = g k) (fn : f n = ff) (gn : g n = tt) : cantor_function c f < cantor_function c g := begin have h3 : c < 1, { apply lt_trans h2, norm_num }, induction n with n ih generalizing f g, { let f_max : ℕ → bool := λ n, nat.rec ff (λ _ _, tt) n, have hf_max : ∀n, f n → f_max n, { intros n hn, cases n, rw [fn] at hn, contradiction, apply rfl }, let g_min : ℕ → bool := λ n, nat.rec tt (λ _ _, ff) n, have hg_min : ∀n, g_min n → g n, { intros n hn, cases n, rw [gn], apply rfl, contradiction }, apply lt_of_le_of_lt (cantor_function_le (le_of_lt h1) h3 hf_max), apply lt_of_lt_of_le _ (cantor_function_le (le_of_lt h1) h3 hg_min), have : c / (1 - c) < 1, { rw [div_lt_one_iff_lt, lt_sub_iff_add_lt], { convert add_lt_add h2 h2, norm_num }, rwa sub_pos }, convert this, { rw [cantor_function_succ _ (le_of_lt h1) h3, div_eq_mul_inv, ←tsum_geometric_of_lt_1 (le_of_lt h1) h3], apply zero_add }, { apply tsum_eq_single 0, intros n hn, cases n, contradiction, refl, apply_instance }}, rw [cantor_function_succ f (le_of_lt h1) h3, cantor_function_succ g (le_of_lt h1) h3], rw [hn 0 $ zero_lt_succ n], apply add_lt_add_left, rw mul_lt_mul_left h1, exact ih (λ k hk, hn _ $ succ_lt_succ hk) fn gn end lemma cantor_function_injective (h1 : 0 < c) (h2 : c < 1 / 2) : function.injective (cantor_function c) := begin intros f g hfg, classical, by_contra h, revert hfg, have : ∃n, f n ≠ g n, { rw [←not_forall], intro h', apply h, ext, apply h' }, let n := nat.find this, have hn : ∀ (k : ℕ), k < n → f k = g k, { intros k hk, apply of_not_not, exact nat.find_min this hk }, cases fn : f n, { apply ne_of_lt, refine increasing_cantor_function h1 h2 hn fn _, apply eq_tt_of_not_eq_ff, rw [←fn], apply ne.symm, exact nat.find_spec this }, { apply ne_of_gt, refine increasing_cantor_function h1 h2 (λ k hk, (hn k hk).symm) _ fn, apply eq_ff_of_not_eq_tt, rw [←fn], apply ne.symm, exact nat.find_spec this } end /-- The cardinality of the reals, as a type. -/ lemma mk_real : mk ℝ = 2 ^ omega.{0} := begin apply le_antisymm, { dsimp [real], apply le_trans mk_quotient_le, apply le_trans (mk_subtype_le _), rw [←power_def, mk_nat, mk_rat, power_self_eq (le_refl _)] }, { convert mk_le_of_injective (cantor_function_injective _ _), rw [←power_def, mk_bool, mk_nat], exact 1 / 3, norm_num, norm_num } end /-- The cardinality of the reals, as a set. -/ lemma mk_univ_real : mk (set.univ : set ℝ) = 2 ^ omega.{0} := by rw [mk_univ, mk_real] /-- The reals are not countable. -/ lemma not_countable_real : ¬ countable (set.univ : set ℝ) := by { rw [countable_iff, not_le, mk_univ_real], apply cantor } /-- The cardinality of the interval (a, ∞). -/ lemma mk_Ioi_real (a : ℝ) : mk (Ioi a) = 2 ^ omega.{0} := begin refine le_antisymm (mk_real ▸ mk_set_le _) _, by_contradiction h, rw not_le at h, refine ne_of_lt _ mk_univ_real, have hu : Iio a ∪ {a} ∪ Ioi a = set.univ, { convert Iic_union_Ioi, exact Iio_union_right }, rw ←hu, refine lt_of_le_of_lt (mk_union_le _ _) _, refine lt_of_le_of_lt (add_le_add_right _ (mk_union_le _ _)) _, have h2 : (λ x, a + a - x) '' Ioi a = Iio a, { convert image_const_sub_Ioi _ _, simp }, rw ←h2, refine add_lt_of_lt (le_of_lt (cantor _)) _ h, refine add_lt_of_lt (le_of_lt (cantor _)) (lt_of_le_of_lt mk_image_le h) _, rw mk_singleton, exact lt_trans one_lt_omega (cantor _) end /-- The cardinality of the interval [a, ∞). -/ lemma mk_Ici_real (a : ℝ) : mk (Ici a) = 2 ^ omega.{0} := le_antisymm (mk_real ▸ mk_set_le _) (mk_Ioi_real a ▸ mk_le_mk_of_subset Ioi_subset_Ici_self) /-- The cardinality of the interval (-∞, a). -/ lemma mk_Iio_real (a : ℝ) : mk (Iio a) = 2 ^ omega.{0} := begin refine le_antisymm (mk_real ▸ mk_set_le _) _, have h2 : (λ x, a + a - x) '' Iio a = Ioi a, { convert image_const_sub_Iio _ _, simp }, exact mk_Ioi_real a ▸ h2 ▸ mk_image_le end /-- The cardinality of the interval (-∞, a]. -/ lemma mk_Iic_real (a : ℝ) : mk (Iic a) = 2 ^ omega.{0} := le_antisymm (mk_real ▸ mk_set_le _) (mk_Iio_real a ▸ mk_le_mk_of_subset Iio_subset_Iic_self) /-- The cardinality of the interval (a, b). -/ lemma mk_Ioo_real {a b : ℝ} (h : a < b) : mk (Ioo a b) = 2 ^ omega.{0} := begin refine le_antisymm (mk_real ▸ mk_set_le _) _, have h1 : mk ((λ x, x - a) '' Ioo a b) ≤ mk (Ioo a b) := mk_image_le, refine le_trans _ h1, rw [image_sub_const_Ioo, sub_self], replace h := sub_pos_of_lt h, have h2 : mk (has_inv.inv '' Ioo 0 (b - a)) ≤ mk (Ioo 0 (b - a)) := mk_image_le, refine le_trans _ h2, rw [image_inv_Ioo_0_left h, mk_Ioi_real] end /-- The cardinality of the interval [a, b). -/ lemma mk_Ico_real {a b : ℝ} (h : a < b) : mk (Ico a b) = 2 ^ omega.{0} := le_antisymm (mk_real ▸ mk_set_le _) (mk_Ioo_real h ▸ mk_le_mk_of_subset Ioo_subset_Ico_self) /-- The cardinality of the interval [a, b]. -/ lemma mk_Icc_real {a b : ℝ} (h : a < b) : mk (Icc a b) = 2 ^ omega.{0} := le_antisymm (mk_real ▸ mk_set_le _) (mk_Ioo_real h ▸ mk_le_mk_of_subset Ioo_subset_Icc_self) /-- The cardinality of the interval (a, b]. -/ lemma mk_Ioc_real {a b : ℝ} (h : a < b) : mk (Ioc a b) = 2 ^ omega.{0} := le_antisymm (mk_real ▸ mk_set_le _) (mk_Ioo_real h ▸ mk_le_mk_of_subset Ioo_subset_Ioc_self) end cardinal
f659189c35d6f682635a03dc03f6bbc059c59e01
5c7fe6c4a9d4079b5457ffa5f061797d42a1cd65
/src/exercises/src_31_function_surjective_injective_bijective.lean
7e50e79e24b65a9c1bd10ea52043811f74968e4e
[]
no_license
gihanmarasingha/mth1001_tutorial
8e0817feeb96e7c1bb3bac49b63e3c9a3a329061
bb277eebd5013766e1418365b91416b406275130
refs/heads/master
1,675,008,746,310
1,607,993,443,000
1,607,993,443,000
321,511,270
3
0
null
null
null
null
UTF-8
Lean
false
false
3,224
lean
import tactic.linarith import .src_17_even_odd_further open function open int namespace mth1001 /- We define a functions `p₁` and `p₂` so that `p₁ x = x + 3` and `p₂ x = 2 * x`, for every `x : ℤ`. -/ def p₁ (x : ℤ) : ℤ := x + 3 def p₂ (x : ℤ) : ℤ := 2 * x #eval p₁ 10 -- `p₁ 10` evaluates to `13`. #eval p₂ 7 -- `p₂ 7` evaluates to `14`. section surjective /- Let `α` and `β` be types. For a function `f : α → β` to be *surjective* means `∀ b : β, ∃ a : α, f a = b` -/ #print surjective -- We'll show that `p₁` is surjective. lemma sur_p1 : surjective p₁ := begin intro b, -- Assume `b : ℤ`. We must show `∃ a, p₁ a = b`. unfold p₁, -- By definition of `p₁`, the goal is `∃ a, a + 3 = b`. use (b-3), -- By `∃` intro. on `b-3`, it suffices to show `(b-3) + 3 = b`. linarith, -- This is true by linear arithmetic. end -- We'll show `p₂` is not surjective. example : ¬(surjective p₂) := begin unfold surjective, -- By definition, we must show `¬(∀ b, ∃ a, p₂ a = b)`. push_neg, -- Pushing in the negation, the goal is `∃ b, ∀ a, p₂ a ≠ b`. unfold p₂, -- By defition of `p₂`, this is `∃ b, ∀ a, 2 * a ≠ b`. use 1, -- By `∃` intro. on `1`, it suffices to show `∀ a, 2 * a ≠ 1`. intros a h, -- For a contradiction, assume `a : ℤ` and `h : 2 * a = 1`. -- For the remainder of the proof, we'll get a contradiction by -- showing `1` is both odd and not odd. have h₂ : odd 1, -- `h₂ : odd 1` as { use 0, norm_num, }, -- `1 = 2 * 0 + 1`. have h₃ : even 1, -- `h₃ : even 1` as { use a, rw h, }, -- `1 = 2 * a`, using `h`. have h₄ : ¬(odd 1), -- So `h₄ : ¬(odd 1)` as a number is even iff { rw ←even_iff_not_odd, exact h₃, }, -- it is not odd. exact h₄ h₂, -- We have `⊥` by false intro. on `h₄` and `h₂`. end end surjective section injective /- Let `α` and `β` be types. For a function `f : α → β` to be *injective* means `∀ a₁ a₂ : α, f a₁ = f a₂ → a₁ = a₂` -/ #print injective -- We'll show `p₂` is injective. example : injective p₂ := begin unfold injective, -- By definions of injective and `p₂`, it suffices to prove unfold p₂, -- `∀ a₁ a₂ : ℤ, 2 * a₁ = 2 * a₂ → a₁ = a₂`. intros a₁ a₂ h, -- Assume `a₁ a₂ : ℤ`. Assume `h : 2 * a₁ = 2 * a₂`. linarith, -- By linear arithmetic, we have `a₁ = a₂`. end -- Now we'll show `p₁` is injective. lemma inj_p1 : injective p₁ := begin unfold injective, -- By definions of injective and `p₂`, it suffices to prove unfold p₁, -- `∀ a₁ a₂ : ℤ, a₁ + 3 = a₂ + 3 → a₁ = a₂`. intros a₁ a₂ h, -- Assume `a₁ a₂ : ℤ`. Assume `h : a₁ + 3 = a₂ + 3`. linarith, -- By linear arithmetic, we have `a₁ = a₂`. end end injective section bijective -- A function is bijective if it is both injective and surjective. #print bijective example : bijective p₁ := begin unfold bijective, -- It suffices to prove `injective p₁ ∧ sujective p₁`. exact and.intro inj_p1 sur_p1, -- This follows by and intro. on `inj_p1` and `sur_p1`. end end bijective end mth1001
d82a9f22fe0f98b961a830424d796b8cb26d019d
63abd62053d479eae5abf4951554e1064a4c45b4
/src/category_theory/natural_isomorphism.lean
1f9632e1757b8ddc9d1f513741f3c4974d32fa0d
[ "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
7,247
lean
/- Copyright (c) 2017 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Tim Baumann, Stephen Morgan, Scott Morrison, Floris van Doorn -/ import category_theory.functor_category import category_theory.isomorphism /-! # Natural isomorphisms For the most part, natural isomorphisms are just another sort of isomorphism. We provide some special support for extracting components: * if `α : F ≅ G`, then `a.app X : F.obj X ≅ G.obj X`, and building natural isomorphisms from components: * ``` nat_iso.of_components (app : ∀ X : C, F.obj X ≅ G.obj X) (naturality : ∀ {X Y : C} (f : X ⟶ Y), F.map f ≫ (app Y).hom = (app X).hom ≫ G.map f) : F ≅ G ``` only needing to check naturality in one direction. ## Implementation Note that `nat_iso` is a namespace without a corresponding definition; we put some declarations that are specifically about natural isomorphisms in the `iso` namespace so that they are available using dot notation. -/ open category_theory -- declare the `v`'s first; see `category_theory.category` for an explanation universes v₁ v₂ v₃ v₄ u₁ u₂ u₃ u₄ namespace category_theory open nat_trans variables {C : Type u₁} [category.{v₁} C] {D : Type u₂} [category.{v₂} D] {E : Type u₃} [category.{v₃} E] namespace iso /-- The application of a natural isomorphism to an object. We put this definition in a different namespace, so that we can use `α.app` -/ @[simps] def app {F G : C ⥤ D} (α : F ≅ G) (X : C) : F.obj X ≅ G.obj X := { hom := α.hom.app X, inv := α.inv.app X, hom_inv_id' := begin rw [← comp_app, iso.hom_inv_id], refl end, inv_hom_id' := begin rw [← comp_app, iso.inv_hom_id], refl end } @[simp, reassoc] lemma hom_inv_id_app {F G : C ⥤ D} (α : F ≅ G) (X : C) : α.hom.app X ≫ α.inv.app X = 𝟙 (F.obj X) := congr_fun (congr_arg nat_trans.app α.hom_inv_id) X @[simp, reassoc] lemma inv_hom_id_app {F G : C ⥤ D} (α : F ≅ G) (X : C) : α.inv.app X ≫ α.hom.app X = 𝟙 (G.obj X) := congr_fun (congr_arg nat_trans.app α.inv_hom_id) X end iso namespace nat_iso open category_theory.category category_theory.functor @[simp] lemma trans_app {F G H : C ⥤ D} (α : F ≅ G) (β : G ≅ H) (X : C) : (α ≪≫ β).app X = α.app X ≪≫ β.app X := rfl lemma app_hom {F G : C ⥤ D} (α : F ≅ G) (X : C) : (α.app X).hom = α.hom.app X := rfl lemma app_inv {F G : C ⥤ D} (α : F ≅ G) (X : C) : (α.app X).inv = α.inv.app X := rfl variables {F G : C ⥤ D} instance hom_app_is_iso (α : F ≅ G) (X : C) : is_iso (α.hom.app X) := { inv := α.inv.app X, hom_inv_id' := begin rw [←comp_app, iso.hom_inv_id, ←id_app] end, inv_hom_id' := begin rw [←comp_app, iso.inv_hom_id, ←id_app] end } instance inv_app_is_iso (α : F ≅ G) (X : C) : is_iso (α.inv.app X) := { inv := α.hom.app X, hom_inv_id' := begin rw [←comp_app, iso.inv_hom_id, ←id_app] end, inv_hom_id' := begin rw [←comp_app, iso.hom_inv_id, ←id_app] end } section /-! Unfortunately we need a separate set of cancellation lemmas for components of natural isomorphisms, because the `simp` normal form is `α.hom.app X`, rather than `α.app.hom X`. (With the later, the morphism would be visibly part of an isomorphism, so general lemmas about isomorphisms would apply.) In the future, we should consider a redesign that changes this simp norm form, but for now it breaks too many proofs. -/ variables (α : F ≅ G) @[simp] lemma cancel_nat_iso_hom_left {X : C} {Z : D} (g g' : G.obj X ⟶ Z) : α.hom.app X ≫ g = α.hom.app X ≫ g' ↔ g = g' := by simp only [cancel_epi] @[simp] lemma cancel_nat_iso_inv_left {X : C} {Z : D} (g g' : F.obj X ⟶ Z) : α.inv.app X ≫ g = α.inv.app X ≫ g' ↔ g = g' := by simp only [cancel_epi] @[simp] lemma cancel_nat_iso_hom_right {X : D} {Y : C} (f f' : X ⟶ F.obj Y) : f ≫ α.hom.app Y = f' ≫ α.hom.app Y ↔ f = f' := by simp only [cancel_mono] @[simp] lemma cancel_nat_iso_inv_right {X : D} {Y : C} (f f' : X ⟶ G.obj Y) : f ≫ α.inv.app Y = f' ≫ α.inv.app Y ↔ f = f' := by simp only [cancel_mono] @[simp] lemma cancel_nat_iso_hom_right_assoc {W X X' : D} {Y : C} (f : W ⟶ X) (g : X ⟶ F.obj Y) (f' : W ⟶ X') (g' : X' ⟶ F.obj Y) : f ≫ g ≫ α.hom.app Y = f' ≫ g' ≫ α.hom.app Y ↔ f ≫ g = f' ≫ g' := by simp only [←category.assoc, cancel_mono] @[simp] lemma cancel_nat_iso_inv_right_assoc {W X X' : D} {Y : C} (f : W ⟶ X) (g : X ⟶ G.obj Y) (f' : W ⟶ X') (g' : X' ⟶ G.obj Y) : f ≫ g ≫ α.inv.app Y = f' ≫ g' ≫ α.inv.app Y ↔ f ≫ g = f' ≫ g' := by simp only [←category.assoc, cancel_mono] end variables {X Y : C} lemma naturality_1 (α : F ≅ G) (f : X ⟶ Y) : (α.inv.app X) ≫ (F.map f) ≫ (α.hom.app Y) = G.map f := begin erw [naturality, ←category.assoc, is_iso.hom_inv_id, category.id_comp] end lemma naturality_2 (α : F ≅ G) (f : X ⟶ Y) : (α.hom.app X) ≫ (G.map f) ≫ (α.inv.app Y) = F.map f := begin erw [naturality, ←category.assoc, is_iso.hom_inv_id, category.id_comp] end /-- A natural transformation is an isomorphism if all its components are isomorphisms. -/ -- Making this an instance would cause a typeclass inference loop with `is_iso_app_of_is_iso`. def is_iso_of_is_iso_app (α : F ⟶ G) [∀ X : C, is_iso (α.app X)] : is_iso α := { inv := { app := λ X, inv (α.app X), naturality' := λ X Y f, begin have h := congr_arg (λ f, inv (α.app X) ≫ (f ≫ inv (α.app Y))) (α.naturality f).symm, simp only [is_iso.inv_hom_id_assoc, is_iso.hom_inv_id, assoc, comp_id, cancel_mono] at h, exact h end } } /-- The components of a natural isomorphism are isomorphisms. -/ instance is_iso_app_of_is_iso (α : F ⟶ G) [is_iso α] (X) : is_iso (α.app X) := { inv := (inv α).app X, hom_inv_id' := congr_fun (congr_arg nat_trans.app (is_iso.hom_inv_id α)) X, inv_hom_id' := congr_fun (congr_arg nat_trans.app (is_iso.inv_hom_id α)) X } /-- Construct a natural isomorphism between functors by giving object level isomorphisms, and checking naturality only in the forward direction. -/ def of_components (app : ∀ X : C, F.obj X ≅ G.obj X) (naturality : ∀ {X Y : C} (f : X ⟶ Y), F.map f ≫ (app Y).hom = (app X).hom ≫ G.map f) : F ≅ G := { hom := { app := λ X, (app X).hom }, ..is_iso_of_is_iso_app _ } @[simp] lemma of_components.app (app' : ∀ X : C, F.obj X ≅ G.obj X) (naturality) (X) : (of_components app' naturality).app X = app' X := by tidy @[simp] lemma of_components.hom_app (app : ∀ X : C, F.obj X ≅ G.obj X) (naturality) (X) : (of_components app naturality).hom.app X = (app X).hom := rfl @[simp] lemma of_components.inv_app (app : ∀ X : C, F.obj X ≅ G.obj X) (naturality) (X) : (of_components app naturality).inv.app X = (app X).inv := rfl /-- Horizontal composition of natural isomorphisms. -/ def hcomp {F G : C ⥤ D} {H I : D ⥤ E} (α : F ≅ G) (β : H ≅ I) : F ⋙ H ≅ G ⋙ I := begin refine ⟨α.hom ◫ β.hom, α.inv ◫ β.inv, _, _⟩, { ext, rw [←nat_trans.exchange], simp, refl }, ext, rw [←nat_trans.exchange], simp, refl end end nat_iso end category_theory
6289a81e93bb344a6401c632d8fcb0d351d6adac
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/nat_mod_defeq.lean
c36d59e87d308a2048a315a965840f78db1d402c
[ "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
447
lean
import Init.Data.Nat.Div /-! This tests that `0 : Fin (n + 1)` unfolds to `0 : Nat`, which is a property kept for backwards compatibility with mathlib in Lean 3. Some Zulip discussion is available [here](https://leanprover.zulipchat.com/#narrow/stream/287929-mathlib4/topic/Nat.2Emod.200.20n.20.3D.200.20no.20longer.20true.20by.20rfl/near/319683008). -/ example (n : Nat) : 0 % n = 0 := rfl example (n : Nat) : (0 : Fin (n + 1)).val = 0 := rfl
76b4f209ebf214bdfc889335f652532ebc65e528
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/newfrontend3.lean
d2a80068b3ff3c1e547bd402a02acaecfa135b4d
[ "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
762
lean
-- structure S := (g {α} : α → α) def f (h : Nat → ({α : Type} → α → α) × Bool) : Nat := (h 0).1 1 def tst : Nat := f fun n => (fun x => x, true) theorem ex : id (Nat → Nat) := by { intro; assumption } def g (i j k : Nat) (a : Array Nat) (h₁ : i < k) (h₂ : k < j) (h₃ : j < a.size) : Nat := let vj := a.get ⟨j, h₃⟩; let vi := a.get ⟨i, Nat.lt_trans h₁ (Nat.lt_trans h₂ h₃)⟩; vi + vj set_option pp.all true in #print g #check g.proof_1 theorem ex1 {p q r s : Prop} : p ∧ q ∧ r ∧ s → r ∧ s ∧ q ∧ p := fun ⟨hp, hq, hr, hs⟩ => ⟨hr, hs, hq, hp⟩ theorem ex2 {p q r s : Prop} : p ∧ q ∧ r ∧ s → r ∧ s ∧ q ∧ p := by intro ⟨hp, hq, hr, hs⟩ exact ⟨hr, hs, hq, hp⟩
21c38120ab5a68f310db87f1e7bdb2175181284c
6065973b1fa7bbacba932011c9e2f32bf7bdd6c1
/src/measure_theory/lp_space.lean
af60735e5b6dbf3ca408a68d77b4188a3591e478
[ "Apache-2.0" ]
permissive
khmacdonald/mathlib
90a0fa2222369fa69ed2fbfb841b74d2bdfd66cb
3669cb35c578441812ad30fd967d21a94b6f387e
refs/heads/master
1,675,863,801,090
1,609,761,876,000
1,609,761,876,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
11,923
lean
/- Copyright (c) 2020 Rémy Degenne. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Rémy Degenne. -/ import measure_theory.l1_space import analysis.mean_inequalities /-! # ℒp space This file describes properties of measurable functions with finite seminorm `(∫ ∥f a∥^p ∂μ) ^ (1/p)` for `p:ℝ` with `1 ≤ p`. ## Main definitions * `mem_ℒp f p μ` : the function `f` has finite p-seminorm for measure `μ`, for `p:ℝ` such that `hp1 : 1 ≤ p`, ## Notation * `snorm f p μ` : `(∫ ∥f a∥^p ∂μ) ^ (1/p)` for `f : α → F`, where `α` is a measurable space and `F` is a normed group. -/ open measure_theory noncomputable theory namespace ℒp_space variables {α E F : Type*} [measurable_space α] {μ : measure α} [measurable_space E] [normed_group E] [normed_group F] {p : ℝ} section ℒp_space_definition /-- The property that `f:α→E` is measurable and `∫ ∥f a∥^p ∂μ` is finite -/ def mem_ℒp (f : α → E) (p : ℝ) (μ : measure α) : Prop := measurable f ∧ ∫⁻ a, (nnnorm (f a)) ^ p ∂μ < ⊤ /-- `(∫ ∥f a∥^p ∂μ) ^ (1/p)`, which is a seminorm on the space of measurable functions for which this quantity is finite -/ def snorm (f : α → F) (p : ℝ) (μ : measure α) : ennreal := (∫⁻ a, (nnnorm (f a))^p ∂μ) ^ (1/p) lemma lintegral_rpow_nnnorm_eq_rpow_snorm {f : α → F} (hp0_lt : 0 < p) : ∫⁻ a, (nnnorm (f a)) ^ p ∂μ = (snorm f p μ) ^ p := begin rw [snorm, ←ennreal.rpow_mul, one_div, inv_mul_cancel, ennreal.rpow_one], exact (ne_of_lt hp0_lt).symm, end end ℒp_space_definition lemma mem_ℒp_one_iff_integrable {f : α → E} : mem_ℒp f 1 μ ↔ integrable f μ := by simp only [integrable, has_finite_integral, mem_ℒp, ennreal.rpow_one, nnreal.coe_one] section top lemma mem_ℒp.snorm_lt_top {f : α → E} (hp0 : 0 ≤ p) (hfp : mem_ℒp f p μ) : snorm f p μ < ⊤ := begin refine ennreal.rpow_lt_top_of_nonneg _ (ne_of_lt hfp.right), rw [one_div, inv_nonneg], exact hp0, end lemma mem_ℒp.snorm_ne_top {f : α → E} (hp0 : 0 ≤ p) (hfp : mem_ℒp f p μ) : snorm f p μ ≠ ⊤ := ne_of_lt (hfp.snorm_lt_top hp0) lemma lintegral_rpow_nnnorm_lt_top_of_snorm_lt_top {f : α → F} (hp0_lt : 0 < p) (hfp : snorm f p μ < ⊤) : ∫⁻ a, (nnnorm (f a)) ^ p ∂μ < ⊤ := begin rw lintegral_rpow_nnnorm_eq_rpow_snorm hp0_lt, exact ennreal.rpow_lt_top_of_nonneg (le_of_lt hp0_lt) (ne_of_lt hfp), end lemma mem_ℒp_of_snorm_lt_top {f : α → E} (hp0_lt : 0 < p) (hfm : measurable f) (hfp : snorm f p μ < ⊤) : mem_ℒp f p μ := ⟨hfm, lintegral_rpow_nnnorm_lt_top_of_snorm_lt_top hp0_lt hfp⟩ end top section zero lemma zero_mem_ℒp (hp0_lt : 0 < p) : mem_ℒp (0 : α → E) p μ := ⟨measurable_zero, by simp [hp0_lt]⟩ @[simp] lemma snorm_zero (hp0_lt : 0 < p) : snorm (0 : α → F) p μ = 0 := by simp [snorm, hp0_lt] /-- When `μ = 0`, we have `∫ f^p ∂μ = 0`. `snorm f p μ` is then `0`, `1` or `⊤` depending on `p`. -/ lemma snorm_measure_zero_of_pos {f : α → F} (hp_pos : 0 < p) : snorm f p 0 = 0 := by simp [snorm, hp_pos] /-- When `μ = 0`, we have `∫ f^p ∂μ = 0`. `snorm f p μ` is then `0`, `1` or `⊤` depending on `p`. -/ lemma snorm_measure_zero_of_exponent_zero {f : α → F} : snorm f 0 0 = 1 := by simp [snorm] /-- When `μ = 0`, we have `∫ f^p ∂μ = 0`. `snorm f p μ` is then `0`, `1` or `⊤` depending on `p`. -/ lemma snorm_measure_zero_of_neg {f : α → F} (hp_neg : p < 0) : snorm f p 0 = ⊤ := by simp [snorm, hp_neg] end zero @[simp] lemma snorm_neg {f : α → F} : snorm (-f) p μ = snorm f p μ := by simp [snorm] section opens_measurable_space variable [opens_measurable_space E] lemma snorm_eq_zero_of_ae_zero {f : α → E} (hp0_lt : 0 < p) (hf : measurable f) (hf_zero : f =ᵐ[μ] 0) : snorm f p μ = 0 := begin rw [snorm, ennreal.rpow_eq_zero_iff], left, split, { rw lintegral_eq_zero_iff hf.nnnorm.ennreal_coe.ennreal_rpow_const, refine filter.eventually.mp hf_zero (filter.eventually_of_forall (λ x hx, _)), simp_rw ennreal.coe_rpow_of_nonneg _ (le_of_lt hp0_lt), simpa [pi.zero_apply, hx, (ne_of_lt hp0_lt).symm] using hx, }, { rwa [one_div, inv_pos], }, end lemma snorm_eq_zero_of_ae_zero' (hp0_ne : p ≠ 0) (hμ : μ ≠ 0) {f : α → E} (hf : measurable f) (hf_zero : f =ᵐ[μ] 0) : snorm f p μ = 0 := begin cases le_or_lt 0 p with hp0 hp_neg, { exact snorm_eq_zero_of_ae_zero (lt_of_le_of_ne hp0 hp0_ne.symm) hf hf_zero, }, { rw [snorm, ennreal.rpow_eq_zero_iff], right, split, { have h_lintegral_const : ∫⁻ (a : α), ↑(nnnorm (f a)) ^ p ∂μ = ∫⁻ (a : α), ⊤ ∂μ, { refine lintegral_congr_ae _, refine filter.eventually.mp hf_zero (filter.eventually_of_forall (λ x hx, _)), rw pi.zero_apply at hx, simp [hx, hp_neg], }, rw [h_lintegral_const], simp [hμ], }, { simp [hp_neg], },}, end lemma ae_eq_zero_of_snorm_eq_zero {f : α → E} (hp0 : 0 ≤ p) (hf : measurable f) (h : snorm f p μ = 0) : f =ᵐ[μ] 0 := begin rw [snorm, ennreal.rpow_eq_zero_iff] at h, cases h, { rw lintegral_eq_zero_iff hf.nnnorm.ennreal_coe.ennreal_rpow_const at h, refine filter.eventually.mp h.left (filter.eventually_of_forall (λ x hx, _)), rw [pi.zero_apply, ennreal.rpow_eq_zero_iff] at hx, cases hx, { cases hx with hx _, rwa [←ennreal.coe_zero, ennreal.coe_eq_coe, nnnorm_eq_zero] at hx, }, { exfalso, exact ennreal.coe_ne_top hx.left, }, }, { exfalso, rw [one_div, inv_lt_zero] at h, linarith, }, end lemma snorm_eq_zero_iff (hp0_lt : 0 < p) {f : α → E} (hf : measurable f) : snorm f p μ = 0 ↔ f =ᵐ[μ] 0 := ⟨ae_eq_zero_of_snorm_eq_zero (le_of_lt hp0_lt) hf, snorm_eq_zero_of_ae_zero hp0_lt hf⟩ end opens_measurable_space section borel_space variable [borel_space E] lemma mem_ℒp.neg {f : α → E} (hf : mem_ℒp f p μ) : mem_ℒp (-f) p μ := ⟨measurable.neg hf.1, by simp [hf.right]⟩ lemma snorm_le_snorm_mul_rpow_measure_univ {p q : ℝ} (hp0_lt : 0 < p) (hpq : p ≤ q) (μ : measure α) {f : α → E} (hf : measurable f) : snorm f p μ ≤ snorm f q μ * (μ set.univ) ^ (1/p - 1/q) := begin have hq0_lt : 0 < q, from lt_of_lt_of_le hp0_lt hpq, by_cases hpq_eq : p = q, { rw [hpq_eq, sub_self, ennreal.rpow_zero, mul_one], exact le_refl _, }, have hpq : p < q, from lt_of_le_of_ne hpq hpq_eq, let g := λ a : α, (1 : ennreal), have h_rw : ∫⁻ a, ↑(nnnorm (f a))^p ∂ μ = ∫⁻ a, (nnnorm (f a) * (g a))^p ∂ μ, from lintegral_congr (λ a, by simp), repeat {rw snorm}, rw h_rw, let r := p * q / (q - p), have hpqr : 1/p = 1/q + 1/r, { field_simp [(ne_of_lt hp0_lt).symm, (ne_of_lt hq0_lt).symm], ring, }, calc (∫⁻ (a : α), (↑(nnnorm (f a)) * g a) ^ p ∂μ) ^ (1/p) ≤ (∫⁻ (a : α), ↑(nnnorm (f a)) ^ q ∂μ) ^ (1/q) * (∫⁻ (a : α), (g a) ^ r ∂μ) ^ (1/r) : ennreal.lintegral_Lp_mul_le_Lq_mul_Lr hp0_lt hpq hpqr μ hf.nnnorm.ennreal_coe measurable_const ... = (∫⁻ (a : α), ↑(nnnorm (f a)) ^ q ∂μ) ^ (1/q) * μ set.univ ^ (1/p - 1/q) : by simp [hpqr], end lemma snorm_le_snorm_of_exponent_le {p q : ℝ} (hp0_lt : 0 < p) (hpq : p ≤ q) (μ : measure α) [probability_measure μ] {f : α → E} (hf : measurable f) : snorm f p μ ≤ snorm f q μ := begin have h_le_μ := snorm_le_snorm_mul_rpow_measure_univ hp0_lt hpq μ hf, rwa [measure_univ, ennreal.one_rpow, mul_one] at h_le_μ, end lemma mem_ℒp.mem_ℒp_of_exponent_le {p q : ℝ} {μ : measure α} [finite_measure μ] {f : α → E} (hfq : mem_ℒp f q μ) (hp_pos : 0 < p) (hpq : p ≤ q) : mem_ℒp f p μ := begin cases hfq with hfq_m hfq_lt_top, split, { exact hfq_m, }, have hq_pos : 0 < q, from lt_of_lt_of_le hp_pos hpq, suffices h_snorm : snorm f p μ < ⊤, { have h_top_eq : (⊤ : ennreal) = ⊤ ^ (1/p), by simp [hp_pos], rw [snorm, h_top_eq] at h_snorm, have h_snorm_pow : ((∫⁻ (a : α), ↑(nnnorm (f a)) ^ p ∂μ) ^ (1/p)) ^ p < (⊤ ^ (1/p)) ^ p, from ennreal.rpow_lt_rpow h_snorm hp_pos, rw [←ennreal.rpow_mul, ←ennreal.rpow_mul] at h_snorm_pow, simpa [(ne_of_lt hp_pos).symm] using h_snorm_pow, }, calc snorm f p μ ≤ snorm f q μ * (μ set.univ) ^ (1/p - 1/q) : snorm_le_snorm_mul_rpow_measure_univ hp_pos hpq μ hfq_m ... < ⊤ : begin rw ennreal.mul_lt_top_iff, left, split, { exact mem_ℒp.snorm_lt_top (le_of_lt hq_pos) ⟨hfq_m, hfq_lt_top⟩, }, { refine ennreal.rpow_lt_top_of_nonneg _ (measure_ne_top μ set.univ), rwa [le_sub, sub_zero, one_div, one_div, inv_le_inv hq_pos hp_pos], }, end end lemma mem_ℒp.integrable (hp1 : 1 ≤ p) {f : α → E} [finite_measure μ] (hfp : mem_ℒp f p μ) : integrable f μ := begin rw ←mem_ℒp_one_iff_integrable, exact hfp.mem_ℒp_of_exponent_le zero_lt_one hp1, end lemma snorm_add_le {f g : α → E} (hf : measurable f) (hg : measurable g) (hp1 : 1 ≤ p) : snorm (f + g) p μ ≤ snorm f p μ + snorm g p μ := calc (∫⁻ a, ↑(nnnorm ((f + g) a)) ^ p ∂μ) ^ (1 / p) ≤ (∫⁻ a, (((λ a, (nnnorm (f a) : ennreal)) + (λ a, (nnnorm (g a) : ennreal))) a) ^ p ∂μ) ^ (1 / p) : begin refine @ennreal.rpow_le_rpow _ _ (1/p) _ (by simp [le_trans zero_le_one hp1]), refine lintegral_mono (λ a, ennreal.rpow_le_rpow _ (le_trans zero_le_one hp1)), simp [←ennreal.coe_add, nnnorm_add_le], end ... ≤ snorm f p μ + snorm g p μ : ennreal.lintegral_Lp_add_le hf.nnnorm.ennreal_coe hg.nnnorm.ennreal_coe hp1 section second_countable_topology variable [topological_space.second_countable_topology E] lemma mem_ℒp.add {f g : α → E} (hf : mem_ℒp f p μ) (hg : mem_ℒp g p μ) (hp1 : 1 ≤ p) : mem_ℒp (f+g) p μ := begin have hp0_lt : 0 < p, from lt_of_lt_of_le zero_lt_one hp1, have hp0 : 0 ≤ p, from le_of_lt hp0_lt, split, { exact measurable.add hf.1 hg.1, }, simp_rw [pi.add_apply, ennreal.coe_rpow_of_nonneg _ hp0], have h_nnnorm_add_le : ∫⁻ (a : α), ↑(nnnorm (f a + g a) ^ p) ∂μ ≤ ∫⁻ a, ↑((nnnorm (f a) + nnnorm (g a)) ^ p) ∂μ, { refine lintegral_mono_nnreal (λ a, _), exact nnreal.rpow_le_rpow (nnnorm_add_le (f a) (g a)) (le_of_lt hp0_lt), }, refine lt_of_le_of_lt h_nnnorm_add_le _, simp_rw [←ennreal.coe_rpow_of_nonneg _ hp0, ennreal.coe_add], let f_nnnorm := (λ a : α, (nnnorm (f a) : ennreal)), let g_nnnorm := (λ a : α, (nnnorm (g a) : ennreal)), change ∫⁻ (a : α), ((f_nnnorm + g_nnnorm) a) ^ p ∂μ < ⊤, exact ennreal.lintegral_rpow_add_lt_top_of_lintegral_rpow_lt_top hf.1.nnnorm.ennreal_coe hf.2 hg.1.nnnorm.ennreal_coe hg.2 hp1, end end second_countable_topology section normed_space variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 E] lemma mem_ℒp.const_smul {f : α → E} (hfp : mem_ℒp f p μ) (c : 𝕜) (hp0 : 0 ≤ p) : mem_ℒp (c • f) p μ := begin split, { exact measurable.const_smul hfp.1 c, }, simp_rw [pi.smul_apply, nnnorm_smul, ennreal.coe_mul, ennreal.mul_rpow_of_nonneg _ _ hp0], rw lintegral_const_mul _ hfp.1.nnnorm.ennreal_coe.ennreal_rpow_const, exact ennreal.mul_lt_top (ennreal.rpow_lt_top_of_nonneg hp0 ennreal.coe_ne_top) hfp.2, end lemma snorm_smul_le_mul_snorm [measurable_space 𝕜] [opens_measurable_space 𝕜] {q r : ℝ} {f : α → E} (hf : measurable f) {φ : α → 𝕜} (hφ : measurable φ) (hp0_lt : 0 < p) (hpq : p < q) (hpqr : 1/p = 1/q + 1/r) : snorm (φ • f) p μ ≤ snorm φ q μ * snorm f r μ := begin rw snorm, simp_rw [pi.smul_apply', nnnorm_smul, ennreal.coe_mul], exact ennreal.lintegral_Lp_mul_le_Lq_mul_Lr hp0_lt hpq hpqr μ hφ.nnnorm.ennreal_coe hf.nnnorm.ennreal_coe, end end normed_space end borel_space end ℒp_space
05a5794cb005695c02ed09456d1d8e4e109b5376
649957717d58c43b5d8d200da34bf374293fe739
/src/data/polynomial.lean
d79d91b7f928aa29c95a7e7dcef95cb07a960e86
[ "Apache-2.0" ]
permissive
Vtec234/mathlib
b50c7b21edea438df7497e5ed6a45f61527f0370
fb1848bbbfce46152f58e219dc0712f3289d2b20
refs/heads/master
1,592,463,095,113
1,562,737,749,000
1,562,737,749,000
196,202,858
0
0
Apache-2.0
1,562,762,338,000
1,562,762,337,000
null
UTF-8
Lean
false
false
97,974
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Johannes Hölzl, Jens Wagemaker Theory of univariate polynomials, represented as `ℕ →₀ α`, where α is a commutative semiring. -/ import data.finsupp algebra.gcd_domain ring_theory.euclidean_domain tactic.ring ring_theory.multiplicity /-- `polynomial α` is the type of univariate polynomials over `α`. Polynomials should be seen as (semi-)rings with the additional constructor `X`. The embedding from α is called `C`. -/ def polynomial (α : Type*) [comm_semiring α] := ℕ →₀ α open finsupp finset lattice namespace polynomial universes u v variables {α : Type u} {β : Type v} {a b : α} {m n : ℕ} section comm_semiring variables [comm_semiring α] [decidable_eq α] {p q r : polynomial α} instance : has_zero (polynomial α) := finsupp.has_zero instance : has_one (polynomial α) := finsupp.has_one instance : has_add (polynomial α) := finsupp.has_add instance : has_mul (polynomial α) := finsupp.has_mul instance : comm_semiring (polynomial α) := finsupp.comm_semiring instance : decidable_eq (polynomial α) := finsupp.decidable_eq def polynomial.has_coe_to_fun : has_coe_to_fun (polynomial α) := finsupp.has_coe_to_fun local attribute [instance] finsupp.comm_semiring polynomial.has_coe_to_fun @[simp] lemma support_zero : (0 : polynomial α).support = ∅ := rfl /-- `C a` is the constant polynomial `a`. -/ def C (a : α) : polynomial α := single 0 a /-- `X` is the polynomial variable (aka indeterminant). -/ def X : polynomial α := single 1 1 /-- coeff p n is the coefficient of X^n in p -/ def coeff (p : polynomial α) := p.to_fun @[simp] lemma coeff_mk (s) (f) (h) : coeff (finsupp.mk s f h : polynomial α) = f := rfl instance [has_repr α] : has_repr (polynomial α) := ⟨λ p, if p = 0 then "0" else (p.support.sort (≤)).foldr (λ n a, a ++ (if a = "" then "" else " + ") ++ if n = 0 then "C (" ++ repr (coeff p n) ++ ")" else if n = 1 then if (coeff p n) = 1 then "X" else "C (" ++ repr (coeff p n) ++ ") * X" else if (coeff p n) = 1 then "X ^ " ++ repr n else "C (" ++ repr (coeff p n) ++ ") * X ^ " ++ repr n) ""⟩ theorem ext {p q : polynomial α} : p = q ↔ ∀ n, coeff p n = coeff q n := ⟨λ h n, h ▸ rfl, finsupp.ext⟩ /-- `degree p` is the degree of the polynomial `p`, i.e. the largest `X`-exponent in `p`. `degree p = some n` when `p ≠ 0` and `n` is the highest power of `X` that appears in `p`, otherwise `degree 0 = ⊥`. -/ def degree (p : polynomial α) : with_bot ℕ := p.support.sup some def degree_lt_wf : well_founded (λp q : polynomial α, degree p < degree q) := inv_image.wf degree (with_bot.well_founded_lt nat.lt_wf) instance : has_well_founded (polynomial α) := ⟨_, degree_lt_wf⟩ /-- `nat_degree p` forces `degree p` to ℕ, by defining nat_degree 0 = 0. -/ def nat_degree (p : polynomial α) : ℕ := (degree p).get_or_else 0 lemma single_eq_C_mul_X : ∀{n}, single n a = C a * X^n | 0 := (mul_one _).symm | (n+1) := calc single (n + 1) a = single n a * X : by rw [X, single_mul_single, mul_one] ... = (C a * X^n) * X : by rw [single_eq_C_mul_X] ... = C a * X^(n+1) : by simp only [pow_add, mul_assoc, pow_one] lemma sum_C_mul_X_eq (p : polynomial α) : p.sum (λn a, C a * X^n) = p := eq.trans (sum_congr rfl $ assume n hn, single_eq_C_mul_X.symm) (finsupp.sum_single _) @[elab_as_eliminator] protected lemma induction_on {M : polynomial α → Prop} (p : polynomial α) (h_C : ∀a, M (C a)) (h_add : ∀p q, M p → M q → M (p + q)) (h_monomial : ∀(n : ℕ) (a : α), M (C a * X^n) → M (C a * X^(n+1))) : M p := have ∀{n:ℕ} {a}, M (C a * X^n), begin assume n a, induction n with n ih, { simp only [pow_zero, mul_one, h_C] }, { exact h_monomial _ _ ih } end, finsupp.induction p (suffices M (C 0), by simpa only [C, single_zero], h_C 0) (assume n a p _ _ hp, suffices M (C a * X^n + p), by rwa [single_eq_C_mul_X], h_add _ _ this hp) @[simp] lemma C_0 : C (0 : α) = 0 := single_zero @[simp] lemma C_1 : C (1 : α) = 1 := rfl @[simp] lemma C_mul : C (a * b) = C a * C b := (@single_mul_single _ _ _ _ _ _ 0 0 a b).symm @[simp] lemma C_add : C (a + b) = C a + C b := finsupp.single_add instance C.is_semiring_hom : is_semiring_hom (C : α → polynomial α) := ⟨C_0, C_1, λ _ _, C_add, λ _ _, C_mul⟩ @[simp] lemma C_pow : C (a ^ n) = C a ^ n := is_semiring_hom.map_pow _ _ _ lemma nat_cast_eq_C (n : ℕ) : (n : polynomial α) = C n := by refine (nat.eq_cast (λ n, C (n : α)) _ _ _ n).symm; simp section coeff lemma apply_eq_coeff : p n = coeff p n := rfl @[simp] lemma coeff_zero (n : ℕ) : coeff (0 : polynomial α) n = 0 := rfl @[simp] lemma coeff_one_zero (n : ℕ) : coeff (1 : polynomial α) 0 = 1 := rfl @[simp] lemma coeff_add (p q : polynomial α) (n : ℕ) : coeff (p + q) n = coeff p n + coeff q n := rfl lemma coeff_C : coeff (C a) n = ite (n = 0) a 0 := by simp [coeff, eq_comm, C, single]; congr @[simp] lemma coeff_C_zero : coeff (C a) 0 = a := rfl @[simp] lemma coeff_X_one : coeff (X : polynomial α) 1 = 1 := rfl @[simp] lemma coeff_X_zero : coeff (X : polynomial α) 0 = 0 := rfl lemma coeff_X : coeff (X : polynomial α) n = if 1 = n then 1 else 0 := rfl @[simp] lemma coeff_C_mul_X (x : α) (k n : ℕ) : coeff (C x * X^k : polynomial α) n = if n = k then x else 0 := by rw [← single_eq_C_mul_X]; simp [single, eq_comm, coeff]; congr lemma coeff_sum [comm_semiring β] [decidable_eq β] (n : ℕ) (f : ℕ → α → polynomial β) : coeff (p.sum f) n = p.sum (λ a b, coeff (f a b) n) := finsupp.sum_apply lemma coeff_single : coeff (single n a) m = if n = m then a else 0 := rfl @[simp] lemma coeff_C_mul (p : polynomial α) : coeff (C a * p) n = a * coeff p n := begin conv in (a * _) { rw [← @sum_single _ _ _ _ _ p, coeff_sum] }, rw [mul_def, C, sum_single_index], { simp [coeff_single, finsupp.mul_sum, coeff_sum], apply sum_congr rfl, assume i hi, by_cases i = n; simp [h] }, simp end @[simp] lemma coeff_one (n : ℕ) : coeff (1 : polynomial α) n = if 0 = n then 1 else 0 := rfl @[simp] lemma coeff_X_pow (k n : ℕ) : coeff (X^k : polynomial α) n = if n = k then 1 else 0 := by simpa only [C_1, one_mul] using coeff_C_mul_X (1:α) k n lemma coeff_mul_left (p q : polynomial α) (n : ℕ) : coeff (p * q) n = (range (n+1)).sum (λ k, coeff p k * coeff q (n-k)) := have hite : ∀ a : ℕ × ℕ, ite (a.1 + a.2 = n) (coeff p (a.fst) * coeff q (a.snd)) 0 ≠ 0 → a.1 + a.2 = n, from λ a ha, by_contradiction (λ h, absurd (eq.refl (0 : α)) (by rwa if_neg h at ha)), calc coeff (p * q) n = sum (p.support) (λ a, sum (q.support) (λ b, ite (a + b = n) (coeff p a * coeff q b) 0)) : by simp only [finsupp.mul_def, coeff_sum, coeff_single]; refl ... = (p.support.product q.support).sum (λ v : ℕ × ℕ, ite (v.1 + v.2 = n) (coeff p v.1 * coeff q v.2) 0) : by rw sum_product ... = (range (n+1)).sum (λ k, coeff p k * coeff q (n-k)) : sum_bij_ne_zero (λ a _ _, a.1) (λ a _ ha, mem_range.2 (nat.lt_succ_of_le (hite a ha ▸ le_add_right (le_refl _)))) (λ a₁ a₂ _ h₁ _ h₂ h, prod.ext h ((add_left_inj a₁.1).1 (by rw [hite a₁ h₁, h, hite a₂ h₂]))) (λ a h₁ h₂, ⟨(a, n - a), mem_product.2 ⟨mem_support_iff.2 (ne_zero_of_mul_ne_zero_right h₂), mem_support_iff.2 (ne_zero_of_mul_ne_zero_left h₂)⟩, by simpa [nat.add_sub_cancel' (nat.le_of_lt_succ (mem_range.1 h₁))], rfl⟩) (λ a _ ha, by rw [← hite a ha, if_pos rfl, nat.add_sub_cancel_left]) lemma coeff_mul_right (p q : polynomial α) (n : ℕ) : coeff (p * q) n = (range (n+1)).sum (λ k, coeff p (n-k) * coeff q k) := by rw [mul_comm, coeff_mul_left]; simp only [mul_comm] theorem coeff_mul_X_pow (p : polynomial α) (n d : ℕ) : coeff (p * polynomial.X ^ n) (d + n) = coeff p d := begin rw [coeff_mul_right, sum_eq_single n, coeff_X_pow, if_pos rfl, mul_one, nat.add_sub_cancel], { intros b h1 h2, rw [coeff_X_pow, if_neg h2, mul_zero] }, { exact λ h1, (h1 (mem_range.2 (nat.le_add_left _ _))).elim } end theorem coeff_mul_X (p : polynomial α) (n : ℕ) : coeff (p * X) (n + 1) = coeff p n := by simpa only [pow_one] using coeff_mul_X_pow p 1 n theorem mul_X_pow_eq_zero {p : polynomial α} {n : ℕ} (H : p * X ^ n = 0) : p = 0 := ext.2 $ λ k, (coeff_mul_X_pow p n k).symm.trans $ ext.1 H (k+n) end coeff lemma C_inj : C a = C b ↔ a = b := ⟨λ h, coeff_C_zero.symm.trans (h.symm ▸ coeff_C_zero), congr_arg C⟩ section eval₂ variables [semiring β] variables (f : α → β) (x : β) open is_semiring_hom /-- Evaluate a polynomial `p` given a ring hom `f` from the scalar ring to the target and a value `x` for the variable in the target -/ def eval₂ (p : polynomial α) : β := p.sum (λ e a, f a * x ^ e) variables [is_semiring_hom f] @[simp] lemma eval₂_C : (C a).eval₂ f x = f a := (sum_single_index $ by rw [map_zero f, zero_mul]).trans $ by rw [pow_zero, mul_one] @[simp] lemma eval₂_X : X.eval₂ f x = x := (sum_single_index $ by rw [map_zero f, zero_mul]).trans $ by rw [map_one f, one_mul, pow_one] @[simp] lemma eval₂_zero : (0 : polynomial α).eval₂ f x = 0 := finsupp.sum_zero_index @[simp] lemma eval₂_add : (p + q).eval₂ f x = p.eval₂ f x + q.eval₂ f x := finsupp.sum_add_index (λ _, by rw [map_zero f, zero_mul]) (λ _ _ _, by rw [map_add f, add_mul]) @[simp] lemma eval₂_one : (1 : polynomial α).eval₂ f x = 1 := by rw [← C_1, eval₂_C, map_one f] instance eval₂.is_add_monoid_hom : is_add_monoid_hom (eval₂ f x) := { map_zero := eval₂_zero _ _, map_add := λ _ _, eval₂_add _ _ } end eval₂ section eval₂ variables [comm_semiring β] variables (f : α → β) [is_semiring_hom f] (x : β) open is_semiring_hom @[simp] lemma eval₂_mul : (p * q).eval₂ f x = p.eval₂ f x * q.eval₂ f x := begin dunfold eval₂, rw [mul_def, finsupp.sum_mul _ p], simp only [finsupp.mul_sum _ q], rw [sum_sum_index], { apply sum_congr rfl, assume i hi, dsimp only, rw [sum_sum_index], { apply sum_congr rfl, assume j hj, dsimp only, rw [sum_single_index, map_mul f, pow_add], { simp only [mul_assoc, mul_left_comm] }, { rw [map_zero f, zero_mul] } }, { intro, rw [map_zero f, zero_mul] }, { intros, rw [map_add f, add_mul] } }, { intro, rw [map_zero f, zero_mul] }, { intros, rw [map_add f, add_mul] } end instance eval₂.is_semiring_hom : is_semiring_hom (eval₂ f x) := ⟨eval₂_zero _ _, eval₂_one _ _, λ _ _, eval₂_add _ _, λ _ _, eval₂_mul _ _⟩ lemma eval₂_pow (n : ℕ) : (p ^ n).eval₂ f x = p.eval₂ f x ^ n := map_pow _ _ _ lemma eval₂_sum (p : polynomial α) (g : ℕ → α → polynomial α) (x : β) : (p.sum g).eval₂ f x = p.sum (λ n a, (g n a).eval₂ f x) := finsupp.sum_sum_index (by simp [is_add_monoid_hom.map_zero f]) (by intros; simp [right_distrib, is_add_monoid_hom.map_add f]) end eval₂ section eval variable {x : α} /-- `eval x p` is the evaluation of the polynomial `p` at `x` -/ def eval : α → polynomial α → α := eval₂ id @[simp] lemma eval_C : (C a).eval x = a := eval₂_C _ _ @[simp] lemma eval_X : X.eval x = x := eval₂_X _ _ @[simp] lemma eval_zero : (0 : polynomial α).eval x = 0 := eval₂_zero _ _ @[simp] lemma eval_add : (p + q).eval x = p.eval x + q.eval x := eval₂_add _ _ @[simp] lemma eval_one : (1 : polynomial α).eval x = 1 := eval₂_one _ _ @[simp] lemma eval_mul : (p * q).eval x = p.eval x * q.eval x := eval₂_mul _ _ instance eval.is_semiring_hom : is_semiring_hom (eval x) := eval₂.is_semiring_hom _ _ @[simp] lemma eval_pow (n : ℕ) : (p ^ n).eval x = p.eval x ^ n := eval₂_pow _ _ _ lemma eval_sum (p : polynomial α) (f : ℕ → α → polynomial α) (x : α) : (p.sum f).eval x = p.sum (λ n a, (f n a).eval x) := eval₂_sum _ _ _ _ lemma eval₂_hom [comm_semiring β] (f : α → β) [is_semiring_hom f] (x : α) : p.eval₂ f (f x) = f (p.eval x) := polynomial.induction_on p (by simp) (by simp [is_semiring_hom.map_add f] {contextual := tt}) (by simp [is_semiring_hom.map_mul f, eval_pow, is_semiring_hom.map_pow f, pow_succ', (mul_assoc _ _ _).symm] {contextual := tt}) /-- `is_root p x` implies `x` is a root of `p`. The evaluation of `p` at `x` is zero -/ def is_root (p : polynomial α) (a : α) : Prop := p.eval a = 0 instance : decidable (is_root p a) := by unfold is_root; apply_instance @[simp] lemma is_root.def : is_root p a ↔ p.eval a = 0 := iff.rfl lemma root_mul_left_of_is_root (p : polynomial α) {q : polynomial α} : is_root q a → is_root (p * q) a := λ H, by rw [is_root, eval_mul, is_root.def.1 H, mul_zero] lemma root_mul_right_of_is_root {p : polynomial α} (q : polynomial α) : is_root p a → is_root (p * q) a := λ H, by rw [is_root, eval_mul, is_root.def.1 H, zero_mul] lemma coeff_zero_eq_eval_zero (p : polynomial α) : coeff p 0 = p.eval 0 := calc coeff p 0 = coeff p 0 * 0 ^ 0 : by simp ... = p.eval 0 : eq.symm $ finset.sum_eq_single _ (λ b _ hb, by simp [zero_pow (nat.pos_of_ne_zero hb)]) (by simp) end eval section comp def comp (p q : polynomial α) : polynomial α := p.eval₂ C q lemma eval₂_comp [comm_semiring β] (f : α → β) [is_semiring_hom f] {x : β} : (p.comp q).eval₂ f x = p.eval₂ f (q.eval₂ f x) := show (p.sum (λ e a, C a * q ^ e)).eval₂ f x = p.eval₂ f (eval₂ f x q), by simp only [eval₂_mul, eval₂_C, eval₂_pow, eval₂_sum]; refl lemma eval_comp : (p.comp q).eval a = p.eval (q.eval a) := eval₂_comp _ @[simp] lemma comp_X : p.comp X = p := begin refine polynomial.ext.2 (λ n, _), rw [comp, eval₂], conv in (C _ * _) { rw ← single_eq_C_mul_X }, rw finsupp.sum_single end @[simp] lemma X_comp : X.comp p = p := eval₂_X _ _ @[simp] lemma comp_C : p.comp (C a) = C (p.eval a) := begin dsimp [comp, eval₂, eval, finsupp.sum], rw [← sum_hom (@C α _ _)], apply finset.sum_congr rfl; simp end @[simp] lemma C_comp : (C a).comp p = C a := eval₂_C _ _ @[simp] lemma comp_zero : p.comp (0 : polynomial α) = C (p.eval 0) := by rw [← C_0, comp_C] @[simp] lemma zero_comp : comp (0 : polynomial α) p = 0 := by rw [← C_0, C_comp] @[simp] lemma comp_one : p.comp 1 = C (p.eval 1) := by rw [← C_1, comp_C] @[simp] lemma one_comp : comp (1 : polynomial α) p = 1 := by rw [← C_1, C_comp] instance : is_semiring_hom (λ q : polynomial α, q.comp p) := by unfold comp; apply_instance @[simp] lemma add_comp : (p + q).comp r = p.comp r + q.comp r := eval₂_add _ _ @[simp] lemma mul_comp : (p * q).comp r = p.comp r * q.comp r := eval₂_mul _ _ end comp section map variables [comm_semiring β] [decidable_eq β] variables (f : α → β) /-- `map f p` maps a polynomial `p` across a ring hom `f` -/ def map : polynomial α → polynomial β := eval₂ (C ∘ f) X variables [is_semiring_hom f] @[simp] lemma map_C : (C a).map f = C (f a) := eval₂_C _ _ @[simp] lemma map_X : X.map f = X := eval₂_X _ _ @[simp] lemma map_zero : (0 : polynomial α).map f = 0 := eval₂_zero _ _ @[simp] lemma map_add : (p + q).map f = p.map f + q.map f := eval₂_add _ _ @[simp] lemma map_one : (1 : polynomial α).map f = 1 := eval₂_one _ _ @[simp] lemma map_mul : (p * q).map f = p.map f * q.map f := eval₂_mul _ _ instance map.is_semiring_hom : is_semiring_hom (map f) := eval₂.is_semiring_hom _ _ lemma map_pow (n : ℕ) : (p ^ n).map f = p.map f ^ n := eval₂_pow _ _ _ lemma coeff_map (n : ℕ) : coeff (p.map f) n = f (coeff p n) := begin rw [map, eval₂, coeff_sum], conv_rhs { rw [← sum_C_mul_X_eq p, coeff_sum, finsupp.sum, ← finset.sum_hom f], }, refine finset.sum_congr rfl (λ x hx, _), simp [function.comp, coeff_C_mul_X, is_semiring_hom.map_mul f], split_ifs; simp [is_semiring_hom.map_zero f], end lemma map_map {γ : Type*} [comm_semiring γ] [decidable_eq γ] (g : β → γ) [is_semiring_hom g] (p : polynomial α) : (p.map f).map g = p.map (λ x, g (f x)) := polynomial.ext.2 (by simp [coeff_map]) lemma eval₂_map {γ : Type*} [comm_semiring γ] (g : β → γ) [is_semiring_hom g] (x : γ) : (p.map f).eval₂ g x = p.eval₂ (λ y, g (f y)) x := polynomial.induction_on p (by simp) (by simp [is_semiring_hom.map_add f] {contextual := tt}) (by simp [is_semiring_hom.map_mul f, is_semiring_hom.map_pow f, pow_succ', (mul_assoc _ _ _).symm] {contextual := tt}) lemma eval_map (x : β) : (p.map f).eval x = p.eval₂ f x := eval₂_map _ _ _ @[simp] lemma map_id : p.map id = p := by simp [id, polynomial.ext, coeff_map] end map /-- `leading_coeff p` gives the coefficient of the highest power of `X` in `p`-/ def leading_coeff (p : polynomial α) : α := coeff p (nat_degree p) /-- a polynomial is `monic` if its leading coefficient is 1 -/ def monic (p : polynomial α) := leading_coeff p = (1 : α) lemma monic.def : monic p ↔ leading_coeff p = 1 := iff.rfl instance monic.decidable : decidable (monic p) := by unfold monic; apply_instance @[simp] lemma degree_zero : degree (0 : polynomial α) = ⊥ := rfl @[simp] lemma nat_degree_zero : nat_degree (0 : polynomial α) = 0 := rfl @[simp] lemma degree_C (ha : a ≠ 0) : degree (C a) = (0 : with_bot ℕ) := show sup (ite (a = 0) ∅ {0}) some = 0, by rw if_neg ha; refl lemma degree_C_le : degree (C a) ≤ (0 : with_bot ℕ) := by by_cases h : a = 0; [rw [h, C_0], rw [degree_C h]]; [exact bot_le, exact le_refl _] lemma degree_one_le : degree (1 : polynomial α) ≤ (0 : with_bot ℕ) := by rw [← C_1]; exact degree_C_le lemma degree_eq_bot : degree p = ⊥ ↔ p = 0 := ⟨λ h, by rw [degree, ← max_eq_sup_with_bot] at h; exact support_eq_empty.1 (max_eq_none.1 h), λ h, h.symm ▸ rfl⟩ lemma degree_eq_nat_degree (hp : p ≠ 0) : degree p = (nat_degree p : with_bot ℕ) := let ⟨n, hn⟩ := classical.not_forall.1 (mt option.eq_none_iff_forall_not_mem.2 (mt degree_eq_bot.1 hp)) in have hn : degree p = some n := not_not.1 hn, by rw [nat_degree, hn]; refl lemma nat_degree_eq_of_degree_eq_some {p : polynomial α} {n : ℕ} (h : degree p = n) : nat_degree p = n := have hp0 : p ≠ 0, from λ hp0, by rw hp0 at h; exact option.no_confusion h, option.some_inj.1 $ show (nat_degree p : with_bot ℕ) = n, by rwa [← degree_eq_nat_degree hp0] @[simp] lemma degree_le_nat_degree : degree p ≤ nat_degree p := begin by_cases hp : p = 0, { rw hp, exact bot_le }, rw [degree_eq_nat_degree hp], exact le_refl _ end lemma nat_degree_eq_of_degree_eq [comm_semiring β] [decidable_eq β] {q : polynomial β} (h : degree p = degree q) : nat_degree p = nat_degree q := by unfold nat_degree; rw h lemma le_degree_of_ne_zero (h : coeff p n ≠ 0) : (n : with_bot ℕ) ≤ degree p := show @has_le.le (with_bot ℕ) _ (some n : with_bot ℕ) (p.support.sup some : with_bot ℕ), from finset.le_sup (finsupp.mem_support_iff.2 h) lemma le_nat_degree_of_ne_zero (h : coeff p n ≠ 0) : n ≤ nat_degree p := begin rw [← with_bot.coe_le_coe, ← degree_eq_nat_degree], exact le_degree_of_ne_zero h, { assume h, subst h, exact h rfl } end lemma degree_le_degree (h : coeff q (nat_degree p) ≠ 0) : degree p ≤ degree q := begin by_cases hp : p = 0, { rw hp, exact bot_le }, { rw degree_eq_nat_degree hp, exact le_degree_of_ne_zero h } end @[simp] lemma nat_degree_C (a : α) : nat_degree (C a) = 0 := begin by_cases ha : a = 0, { have : C a = 0, { rw [ha, C_0] }, rw [nat_degree, degree_eq_bot.2 this], refl }, { rw [nat_degree, degree_C ha], refl } end @[simp] lemma nat_degree_one : nat_degree (1 : polynomial α) = 0 := nat_degree_C 1 @[simp] lemma nat_degree_nat_cast (n : ℕ) : nat_degree (n : polynomial α) = 0 := by simp [nat_cast_eq_C] @[simp] lemma degree_monomial (n : ℕ) (ha : a ≠ 0) : degree (C a * X ^ n) = n := by rw [← single_eq_C_mul_X, degree, support_single_ne_zero ha]; refl lemma degree_monomial_le (n : ℕ) (a : α) : degree (C a * X ^ n) ≤ n := if h : a = 0 then by rw [h, C_0, zero_mul]; exact bot_le else le_of_eq (degree_monomial n h) lemma coeff_eq_zero_of_degree_lt (h : degree p < n) : coeff p n = 0 := not_not.1 (mt le_degree_of_ne_zero (not_le_of_gt h)) lemma coeff_nat_degree_eq_zero_of_degree_lt (h : degree p < degree q) : coeff p (nat_degree q) = 0 := coeff_eq_zero_of_degree_lt (lt_of_lt_of_le h degree_le_nat_degree) lemma ne_zero_of_degree_gt {n : with_bot ℕ} (h : n < degree p) : p ≠ 0 := mt degree_eq_bot.2 (ne.symm (ne_of_lt (lt_of_le_of_lt bot_le h))) lemma eq_C_of_degree_le_zero (h : degree p ≤ 0) : p = C (coeff p 0) := begin refine polynomial.ext.2 (λ n, _), cases n, { refl }, { have : degree p < ↑(nat.succ n) := lt_of_le_of_lt h (with_bot.some_lt_some.2 (nat.succ_pos _)), rw [coeff_C, if_neg (nat.succ_ne_zero _), coeff_eq_zero_of_degree_lt this] } end lemma eq_C_of_degree_eq_zero (h : degree p = 0) : p = C (coeff p 0) := eq_C_of_degree_le_zero (h ▸ le_refl _) lemma degree_le_zero_iff : degree p ≤ 0 ↔ p = C (coeff p 0) := ⟨eq_C_of_degree_le_zero, λ h, h.symm ▸ degree_C_le⟩ lemma degree_add_le (p q : polynomial α) : degree (p + q) ≤ max (degree p) (degree q) := calc degree (p + q) = ((p + q).support).sup some : rfl ... ≤ (p.support ∪ q.support).sup some : sup_mono support_add ... = p.support.sup some ⊔ q.support.sup some : sup_union ... = _ : with_bot.sup_eq_max _ _ @[simp] lemma leading_coeff_zero : leading_coeff (0 : polynomial α) = 0 := rfl @[simp] lemma leading_coeff_eq_zero : leading_coeff p = 0 ↔ p = 0 := ⟨λ h, by_contradiction $ λ hp, mt mem_support_iff.1 (not_not.2 h) (mem_of_max (degree_eq_nat_degree hp)), λ h, h.symm ▸ leading_coeff_zero⟩ lemma leading_coeff_eq_zero_iff_deg_eq_bot : leading_coeff p = 0 ↔ degree p = ⊥ := by rw [leading_coeff_eq_zero, degree_eq_bot] lemma degree_add_eq_of_degree_lt (h : degree p < degree q) : degree (p + q) = degree q := le_antisymm (max_eq_right_of_lt h ▸ degree_add_le _ _) $ degree_le_degree $ begin rw [coeff_add, coeff_nat_degree_eq_zero_of_degree_lt h, zero_add], exact mt leading_coeff_eq_zero.1 (ne_zero_of_degree_gt h) end lemma degree_add_eq_of_leading_coeff_add_ne_zero (h : leading_coeff p + leading_coeff q ≠ 0) : degree (p + q) = max p.degree q.degree := le_antisymm (degree_add_le _ _) $ match lt_trichotomy (degree p) (degree q) with | or.inl hlt := by rw [degree_add_eq_of_degree_lt hlt, max_eq_right_of_lt hlt]; exact le_refl _ | or.inr (or.inl heq) := le_of_not_gt $ assume hlt : max (degree p) (degree q) > degree (p + q), h $ show leading_coeff p + leading_coeff q = 0, begin rw [heq, max_self] at hlt, rw [leading_coeff, leading_coeff, nat_degree_eq_of_degree_eq heq, ← coeff_add], exact coeff_nat_degree_eq_zero_of_degree_lt hlt end | or.inr (or.inr hlt) := by rw [add_comm, degree_add_eq_of_degree_lt hlt, max_eq_left_of_lt hlt]; exact le_refl _ end lemma degree_erase_le (p : polynomial α) (n : ℕ) : degree (p.erase n) ≤ degree p := sup_mono (erase_subset _ _) lemma degree_erase_lt (hp : p ≠ 0) : degree (p.erase (nat_degree p)) < degree p := lt_of_le_of_ne (degree_erase_le _ _) $ (degree_eq_nat_degree hp).symm ▸ λ h, not_mem_erase _ _ (mem_of_max h) lemma degree_sum_le [decidable_eq β] (s : finset β) (f : β → polynomial α) : degree (s.sum f) ≤ s.sup (λ b, degree (f b)) := finset.induction_on s (by simp only [sum_empty, sup_empty, degree_zero, le_refl]) $ assume a s has ih, calc degree (sum (insert a s) f) ≤ max (degree (f a)) (degree (s.sum f)) : by rw sum_insert has; exact degree_add_le _ _ ... ≤ _ : by rw [sup_insert, with_bot.sup_eq_max]; exact max_le_max (le_refl _) ih lemma degree_mul_le (p q : polynomial α) : degree (p * q) ≤ degree p + degree q := calc degree (p * q) ≤ (p.support).sup (λi, degree (sum q (λj a, C (coeff p i * a) * X ^ (i + j)))) : by simp only [single_eq_C_mul_X.symm]; exact degree_sum_le _ _ ... ≤ p.support.sup (λi, q.support.sup (λj, degree (C (coeff p i * coeff q j) * X ^ (i + j)))) : finset.sup_mono_fun (assume i hi, degree_sum_le _ _) ... ≤ degree p + degree q : begin refine finset.sup_le (λ a ha, finset.sup_le (λ b hb, le_trans (degree_monomial_le _ _) _)), rw [with_bot.coe_add], rw mem_support_iff at ha hb, exact add_le_add' (le_degree_of_ne_zero ha) (le_degree_of_ne_zero hb) end lemma degree_pow_le (p : polynomial α) : ∀ n, degree (p ^ n) ≤ add_monoid.smul n (degree p) | 0 := by rw [pow_zero, add_monoid.zero_smul]; exact degree_one_le | (n+1) := calc degree (p ^ (n + 1)) ≤ degree p + degree (p ^ n) : by rw pow_succ; exact degree_mul_le _ _ ... ≤ _ : by rw succ_smul; exact add_le_add' (le_refl _) (degree_pow_le _) @[simp] lemma leading_coeff_monomial (a : α) (n : ℕ) : leading_coeff (C a * X ^ n) = a := begin by_cases ha : a = 0, { simp only [ha, C_0, zero_mul, leading_coeff_zero] }, { rw [leading_coeff, nat_degree, degree_monomial _ ha, ← single_eq_C_mul_X], exact @finsupp.single_eq_same _ _ _ _ _ n a } end @[simp] lemma leading_coeff_C (a : α) : leading_coeff (C a) = a := suffices leading_coeff (C a * X^0) = a, by rwa [pow_zero, mul_one] at this, leading_coeff_monomial a 0 @[simp] lemma leading_coeff_X : leading_coeff (X : polynomial α) = 1 := suffices leading_coeff (C (1:α) * X^1) = 1, by rwa [C_1, pow_one, one_mul] at this, leading_coeff_monomial 1 1 @[simp] lemma monic_X : monic (X : polynomial α) := leading_coeff_X @[simp] lemma leading_coeff_one : leading_coeff (1 : polynomial α) = 1 := suffices leading_coeff (C (1:α) * X^0) = 1, by rwa [C_1, pow_zero, mul_one] at this, leading_coeff_monomial 1 0 @[simp] lemma monic_one : monic (1 : polynomial α) := leading_coeff_C _ lemma leading_coeff_add_of_degree_lt (h : degree p < degree q) : leading_coeff (p + q) = leading_coeff q := have coeff p (nat_degree q) = 0, from coeff_nat_degree_eq_zero_of_degree_lt h, by simp only [leading_coeff, nat_degree_eq_of_degree_eq (degree_add_eq_of_degree_lt h), this, coeff_add, zero_add] lemma leading_coeff_add_of_degree_eq (h : degree p = degree q) (hlc : leading_coeff p + leading_coeff q ≠ 0) : leading_coeff (p + q) = leading_coeff p + leading_coeff q := have nat_degree (p + q) = nat_degree p, by apply nat_degree_eq_of_degree_eq; rw [degree_add_eq_of_leading_coeff_add_ne_zero hlc, h, max_self], by simp only [leading_coeff, this, nat_degree_eq_of_degree_eq h, coeff_add] @[simp] lemma coeff_mul_degree_add_degree (p q : polynomial α) : coeff (p * q) (nat_degree p + nat_degree q) = leading_coeff p * leading_coeff q := calc coeff (p * q) (nat_degree p + nat_degree q) = (range (nat_degree p + nat_degree q + 1)).sum (λ k, coeff p k * coeff q (nat_degree p + nat_degree q - k)) : coeff_mul_left _ _ _ ... = coeff p (nat_degree p) * coeff q (nat_degree p + nat_degree q - nat_degree p) : finset.sum_eq_single _ (λ n hn₁ hn₂, (le_total n (nat_degree p)).elim (λ h, have degree q < (nat_degree p + nat_degree q - n : ℕ), from lt_of_le_of_lt degree_le_nat_degree (with_bot.coe_lt_coe.2 (nat.lt_sub_left_iff_add_lt.2 (add_lt_add_right (lt_of_le_of_ne h hn₂) _))), by simp [coeff_eq_zero_of_degree_lt this]) (λ h, have degree p < n, from lt_of_le_of_lt degree_le_nat_degree (with_bot.coe_lt_coe.2 (lt_of_le_of_ne h hn₂.symm)), by simp [coeff_eq_zero_of_degree_lt this])) (λ h, false.elim (h (mem_range.2 (lt_of_le_of_lt (nat.le_add_right _ _) (nat.lt_succ_self _))))) ... = _ : by simp [leading_coeff, nat.add_sub_cancel_left] lemma degree_mul_eq' (h : leading_coeff p * leading_coeff q ≠ 0) : degree (p * q) = degree p + degree q := have hp : p ≠ 0 := by refine mt _ h; exact λ hp, by rw [hp, leading_coeff_zero, zero_mul], have hq : q ≠ 0 := by refine mt _ h; exact λ hq, by rw [hq, leading_coeff_zero, mul_zero], le_antisymm (degree_mul_le _ _) begin rw [degree_eq_nat_degree hp, degree_eq_nat_degree hq], refine le_degree_of_ne_zero _, rwa coeff_mul_degree_add_degree end lemma nat_degree_mul_eq' (h : leading_coeff p * leading_coeff q ≠ 0) : nat_degree (p * q) = nat_degree p + nat_degree q := have hp : p ≠ 0 := mt leading_coeff_eq_zero.2 (λ h₁, h $ by rw [h₁, zero_mul]), have hq : q ≠ 0 := mt leading_coeff_eq_zero.2 (λ h₁, h $ by rw [h₁, mul_zero]), have hpq : p * q ≠ 0 := λ hpq, by rw [← coeff_mul_degree_add_degree, hpq, coeff_zero] at h; exact h rfl, option.some_inj.1 (show (nat_degree (p * q) : with_bot ℕ) = nat_degree p + nat_degree q, by rw [← degree_eq_nat_degree hpq, degree_mul_eq' h, degree_eq_nat_degree hp, degree_eq_nat_degree hq]) lemma leading_coeff_mul' (h : leading_coeff p * leading_coeff q ≠ 0) : leading_coeff (p * q) = leading_coeff p * leading_coeff q := begin unfold leading_coeff, rw [nat_degree_mul_eq' h, coeff_mul_degree_add_degree], refl end lemma leading_coeff_pow' : leading_coeff p ^ n ≠ 0 → leading_coeff (p ^ n) = leading_coeff p ^ n := nat.rec_on n (by simp) $ λ n ih h, have h₁ : leading_coeff p ^ n ≠ 0 := λ h₁, h $ by rw [pow_succ, h₁, mul_zero], have h₂ : leading_coeff p * leading_coeff (p ^ n) ≠ 0 := by rwa [pow_succ, ← ih h₁] at h, by rw [pow_succ, pow_succ, leading_coeff_mul' h₂, ih h₁] lemma degree_pow_eq' : ∀ {n}, leading_coeff p ^ n ≠ 0 → degree (p ^ n) = add_monoid.smul n (degree p) | 0 := λ h, by rw [pow_zero, ← C_1] at *; rw [degree_C h, add_monoid.zero_smul] | (n+1) := λ h, have h₁ : leading_coeff p ^ n ≠ 0 := λ h₁, h $ by rw [pow_succ, h₁, mul_zero], have h₂ : leading_coeff p * leading_coeff (p ^ n) ≠ 0 := by rwa [pow_succ, ← leading_coeff_pow' h₁] at h, by rw [pow_succ, degree_mul_eq' h₂, succ_smul, degree_pow_eq' h₁] lemma nat_degree_pow_eq' {n : ℕ} (h : leading_coeff p ^ n ≠ 0) : nat_degree (p ^ n) = n * nat_degree p := if hp0 : p = 0 then if hn0 : n = 0 then by simp * else by rw [hp0, zero_pow (nat.pos_of_ne_zero hn0)]; simp else have hpn : p ^ n ≠ 0, from λ hpn0, have h1 : _ := h, by rw [← leading_coeff_pow' h1, hpn0, leading_coeff_zero] at h; exact h rfl, option.some_inj.1 $ show (nat_degree (p ^ n) : with_bot ℕ) = (n * nat_degree p : ℕ), by rw [← degree_eq_nat_degree hpn, degree_pow_eq' h, degree_eq_nat_degree hp0, ← with_bot.coe_smul]; simp @[simp] lemma leading_coeff_X_pow : ∀ n : ℕ, leading_coeff ((X : polynomial α) ^ n) = 1 | 0 := by simp | (n+1) := if h10 : (1 : α) = 0 then by rw [pow_succ, ← one_mul X, ← C_1, h10]; simp else have h : leading_coeff (X : polynomial α) * leading_coeff (X ^ n) ≠ 0, by rw [leading_coeff_X, leading_coeff_X_pow n, one_mul]; exact h10, by rw [pow_succ, leading_coeff_mul' h, leading_coeff_X, leading_coeff_X_pow, one_mul] lemma nat_degree_comp_le : nat_degree (p.comp q) ≤ nat_degree p * nat_degree q := if h0 : p.comp q = 0 then by rw [h0, nat_degree_zero]; exact nat.zero_le _ else with_bot.coe_le_coe.1 $ calc ↑(nat_degree (p.comp q)) = degree (p.comp q) : (degree_eq_nat_degree h0).symm ... ≤ _ : degree_sum_le _ _ ... ≤ _ : sup_le (λ n hn, calc degree (C (coeff p n) * q ^ n) ≤ degree (C (coeff p n)) + degree (q ^ n) : degree_mul_le _ _ ... ≤ nat_degree (C (coeff p n)) + add_monoid.smul n (degree q) : add_le_add' degree_le_nat_degree (degree_pow_le _ _) ... ≤ nat_degree (C (coeff p n)) + add_monoid.smul n (nat_degree q) : add_le_add_left' (add_monoid.smul_le_smul_of_le_right (@degree_le_nat_degree _ _ _ q) n) ... = (n * nat_degree q : ℕ) : by rw [nat_degree_C, with_bot.coe_zero, zero_add, ← with_bot.coe_smul, add_monoid.smul_eq_mul]; simp ... ≤ (nat_degree p * nat_degree q : ℕ) : with_bot.coe_le_coe.2 $ mul_le_mul_of_nonneg_right (le_nat_degree_of_ne_zero (finsupp.mem_support_iff.1 hn)) (nat.zero_le _)) lemma degree_map_le [comm_semiring β] [decidable_eq β] (f : α → β) [is_semiring_hom f] : degree (p.map f) ≤ degree p := if h : p.map f = 0 then by simp [h] else begin rw [degree_eq_nat_degree h], refine le_degree_of_ne_zero (mt (congr_arg f) _), rw [← coeff_map f, is_semiring_hom.map_zero f], exact mt leading_coeff_eq_zero.1 h end lemma subsingleton_of_monic_zero (h : monic (0 : polynomial α)) : (∀ p q : polynomial α, p = q) ∧ (∀ a b : α, a = b) := by rw [monic.def, leading_coeff_zero] at h; exact ⟨λ p q, by rw [← mul_one p, ← mul_one q, ← C_1, ← h, C_0, mul_zero, mul_zero], λ a b, by rw [← mul_one a, ← mul_one b, ← h, mul_zero, mul_zero]⟩ lemma degree_map_eq_of_leading_coeff_ne_zero [comm_semiring β] [decidable_eq β] (f : α → β) [is_semiring_hom f] (hf : f (leading_coeff p) ≠ 0) : degree (p.map f) = degree p := le_antisymm (degree_map_le f) $ have hp0 : p ≠ 0, from λ hp0, by simpa [hp0, is_semiring_hom.map_zero f] using hf, begin rw [degree_eq_nat_degree hp0], refine le_degree_of_ne_zero _, rw [coeff_map], exact hf end lemma degree_map_eq_of_injective [comm_semiring β] [decidable_eq β] (f : α → β) [is_semiring_hom f] (hf : function.injective f) : degree (p.map f) = degree p := if h : p = 0 then by simp [h] else degree_map_eq_of_leading_coeff_ne_zero _ (by rw [← is_semiring_hom.map_zero f]; exact mt hf.eq_iff.1 (mt leading_coeff_eq_zero.1 h)) lemma monic_map [comm_semiring β] [decidable_eq β] (f : α → β) [is_semiring_hom f] (hp : monic p) : monic (p.map f) := if h : (0 : β) = 1 then by haveI := subsingleton_of_zero_eq_one β h; exact subsingleton.elim _ _ else have f (leading_coeff p) ≠ 0, by rwa [show _ = _, from hp, is_semiring_hom.map_one f, ne.def, eq_comm], by erw [monic, leading_coeff, nat_degree_eq_of_degree_eq (degree_map_eq_of_leading_coeff_ne_zero f this), coeff_map, ← leading_coeff, show _ = _, from hp, is_semiring_hom.map_one f] lemma zero_le_degree_iff {p : polynomial α} : 0 ≤ degree p ↔ p ≠ 0 := by rw [ne.def, ← degree_eq_bot]; cases degree p; exact dec_trivial @[simp] lemma coeff_mul_X_zero (p : polynomial α) : coeff (p * X) 0 = 0 := by rw [coeff_mul_left, sum_range_succ]; simp end comm_semiring instance subsingleton [subsingleton α] [comm_semiring α] : subsingleton (polynomial α) := ⟨λ _ _, polynomial.ext.2 (λ _, subsingleton.elim _ _)⟩ section comm_semiring variables [decidable_eq α] [comm_semiring α] {p q r : polynomial α} lemma ne_zero_of_monic_of_zero_ne_one (hp : monic p) (h : (0 : α) ≠ 1) : p ≠ 0 := mt (congr_arg leading_coeff) $ by rw [monic.def.1 hp, leading_coeff_zero]; cc lemma eq_X_add_C_of_degree_le_one (h : degree p ≤ 1) : p = C (p.coeff 1) * X + C (p.coeff 0) := polynomial.ext.2 (λ n, nat.cases_on n (by simp) (λ n, nat.cases_on n (by simp [coeff_C]) (λ m, have degree p < m.succ.succ, from lt_of_le_of_lt h dec_trivial, by simp [coeff_eq_zero_of_degree_lt this, coeff_C, nat.succ_ne_zero, coeff_X, nat.succ_inj', @eq_comm ℕ 0]))) lemma eq_X_add_C_of_degree_eq_one (h : degree p = 1) : p = C (p.leading_coeff) * X + C (p.coeff 0) := (eq_X_add_C_of_degree_le_one (show degree p ≤ 1, from h ▸ le_refl _)).trans (by simp [leading_coeff, nat_degree_eq_of_degree_eq_some h]) theorem degree_C_mul_X_pow_le (r : α) (n : ℕ) : degree (C r * X^n) ≤ n := begin rw [← single_eq_C_mul_X], refine finset.sup_le (λ b hb, _), rw list.eq_of_mem_singleton (finsupp.support_single_subset hb), exact le_refl _ end theorem degree_X_pow_le (n : ℕ) : degree (X^n : polynomial α) ≤ n := by simpa only [C_1, one_mul] using degree_C_mul_X_pow_le (1:α) n theorem degree_X_le : degree (X : polynomial α) ≤ 1 := by simpa only [C_1, one_mul, pow_one] using degree_C_mul_X_pow_le (1:α) 1 lemma degree_map' [comm_semiring β] [decidable_eq β] (p : polynomial α) {f : α → β} [is_semiring_hom f] (hf : function.injective f) : degree (p.map f) = degree p := degree_map_eq_of_injective _ hf lemma nat_degree_map' [comm_semiring β] [decidable_eq β] (p : polynomial α) {f : α → β} [is_semiring_hom f] (hf : function.injective f) : nat_degree (p.map f) = nat_degree p := nat_degree_eq_of_degree_eq (degree_map' _ hf) theorem monic_of_degree_le (n : ℕ) (H1 : degree p ≤ n) (H2 : coeff p n = 1) : monic p := decidable.by_cases (assume H : degree p < n, @subsingleton.elim _ (subsingleton_of_zero_eq_one α $ H2 ▸ (coeff_eq_zero_of_degree_lt H).symm) _ _) (assume H : ¬degree p < n, by rwa [monic, leading_coeff, nat_degree, (lt_or_eq_of_le H1).resolve_left H]) theorem monic_X_pow_add {n : ℕ} (H : degree p ≤ n) : monic (X ^ (n+1) + p) := have H1 : degree p < n+1, from lt_of_le_of_lt H (with_bot.coe_lt_coe.2 (nat.lt_succ_self n)), monic_of_degree_le (n+1) (le_trans (degree_add_le _ _) (max_le (degree_X_pow_le _) (le_of_lt H1))) (by rw [coeff_add, coeff_X_pow, if_pos rfl, coeff_eq_zero_of_degree_lt H1, add_zero]) theorem monic_X_add_C (x : α) : monic (X + C x) := pow_one (X : polynomial α) ▸ monic_X_pow_add degree_C_le theorem degree_le_iff_coeff_zero (f : polynomial α) (n : with_bot ℕ) : degree f ≤ n ↔ ∀ m : ℕ, n < m → coeff f m = 0 := ⟨λ (H : finset.sup (f.support) some ≤ n) m (Hm : n < (m : with_bot ℕ)), decidable.of_not_not $ λ H4, have H1 : m ∉ f.support, from λ H2, not_lt_of_ge ((finset.sup_le_iff.1 H) m H2 : ((m : with_bot ℕ) ≤ n)) Hm, H1 $ (finsupp.mem_support_to_fun f m).2 H4, λ H, finset.sup_le $ λ b Hb, decidable.of_not_not $ λ Hn, (finsupp.mem_support_to_fun f b).1 Hb $ H b $ lt_of_not_ge Hn⟩ theorem nat_degree_le_of_degree_le {p : polynomial α} {n : ℕ} (H : degree p ≤ n) : nat_degree p ≤ n := show option.get_or_else (degree p) 0 ≤ n, from match degree p, H with | none, H := zero_le _ | (some d), H := with_bot.coe_le_coe.1 H end theorem leading_coeff_mul_X_pow {p : polynomial α} {n : ℕ} : leading_coeff (p * X ^ n) = leading_coeff p := decidable.by_cases (assume H : leading_coeff p = 0, by rw [H, leading_coeff_eq_zero.1 H, zero_mul, leading_coeff_zero]) (assume H : leading_coeff p ≠ 0, by rw [leading_coeff_mul', leading_coeff_X_pow, mul_one]; rwa [leading_coeff_X_pow, mul_one]) lemma monic_mul (hp : monic p) (hq : monic q) : monic (p * q) := if h0 : (0 : α) = 1 then by haveI := subsingleton_of_zero_eq_one _ h0; exact subsingleton.elim _ _ else have leading_coeff p * leading_coeff q ≠ 0, by simp [monic.def.1 hp, monic.def.1 hq, ne.symm h0], by rw [monic.def, leading_coeff_mul' this, monic.def.1 hp, monic.def.1 hq, one_mul] lemma monic_pow (hp : monic p) : ∀ (n : ℕ), monic (p ^ n) | 0 := monic_one | (n+1) := monic_mul hp (monic_pow n) lemma multiplicity_finite_of_degree_pos_of_monic (hp : (0 : with_bot ℕ) < degree p) (hmp : monic p) (hq : q ≠ 0) : multiplicity.finite p q := have zn0 : (0 : α) ≠ 1, from λ h, by haveI := subsingleton_of_zero_eq_one _ h; exact hq (subsingleton.elim _ _), ⟨nat_degree q, λ ⟨r, hr⟩, have hp0 : p ≠ 0, from λ hp0, by simp [hp0] at hp; contradiction, have hr0 : r ≠ 0, from λ hr0, by simp * at *, have hpn1 : leading_coeff p ^ (nat_degree q + 1) = 1, by simp [show _ = _, from hmp], have hpn0' : leading_coeff p ^ (nat_degree q + 1) ≠ 0, from hpn1.symm ▸ zn0.symm, have hpnr0 : leading_coeff (p ^ (nat_degree q + 1)) * leading_coeff r ≠ 0, by simp only [leading_coeff_pow' hpn0', leading_coeff_eq_zero, hpn1, one_pow, one_mul, ne.def, hr0]; simp, have hpn0 : p ^ (nat_degree q + 1) ≠ 0, from mt leading_coeff_eq_zero.2 $ by rw [leading_coeff_pow' hpn0', show _ = _, from hmp, one_pow]; exact zn0.symm, have hnp : 0 < nat_degree p, by rw [← with_bot.coe_lt_coe, ← degree_eq_nat_degree hp0]; exact hp, begin have := congr_arg nat_degree hr, rw [nat_degree_mul_eq' hpnr0, nat_degree_pow_eq' hpn0', add_mul, add_assoc] at this, exact ne_of_lt (lt_add_of_le_of_pos (le_mul_of_ge_one_right' (nat.zero_le _) hnp) (add_pos_of_pos_of_nonneg (by rwa one_mul) (nat.zero_le _))) this end⟩ end comm_semiring section nonzero_comm_semiring variables [nonzero_comm_semiring α] [decidable_eq α] {p q : polynomial α} instance : nonzero_comm_semiring (polynomial α) := { zero_ne_one := λ (h : (0 : polynomial α) = 1), @zero_ne_one α _ $ calc (0 : α) = eval 0 0 : eval_zero.symm ... = eval 0 1 : congr_arg _ h ... = 1 : eval_C, ..polynomial.comm_semiring } @[simp] lemma degree_one : degree (1 : polynomial α) = (0 : with_bot ℕ) := degree_C (show (1 : α) ≠ 0, from zero_ne_one.symm) @[simp] lemma degree_X : degree (X : polynomial α) = 1 := begin unfold X degree single finsupp.support, rw if_neg (zero_ne_one).symm, refl end lemma X_ne_zero : (X : polynomial α) ≠ 0 := mt (congr_arg (λ p, coeff p 1)) (by simp) @[simp] lemma degree_X_pow : ∀ (n : ℕ), degree ((X : polynomial α) ^ n) = n | 0 := by simp only [pow_zero, degree_one]; refl | (n+1) := have h : leading_coeff (X : polynomial α) * leading_coeff (X ^ n) ≠ 0, by rw [leading_coeff_X, leading_coeff_X_pow n, one_mul]; exact zero_ne_one.symm, by rw [pow_succ, degree_mul_eq' h, degree_X, degree_X_pow, add_comm]; refl @[simp] lemma not_monic_zero : ¬monic (0 : polynomial α) := by simpa only [monic, leading_coeff_zero] using zero_ne_one lemma ne_zero_of_monic (h : monic p) : p ≠ 0 := λ h₁, @not_monic_zero α _ _ (h₁ ▸ h) end nonzero_comm_semiring section comm_semiring variables [decidable_eq α] [comm_semiring α] {p q : polynomial α} /-- `dix_X p` return a polynomial `q` such that `q * X + C (p.coeff 0) = p`. It can be used in a semiring where the usual division algorithm is not possible -/ def div_X (p : polynomial α) : polynomial α := { to_fun := λ n, p.coeff (n + 1), support := ⟨(p.support.filter (> 0)).1.map (λ n, n - 1), multiset.nodup_map_on begin simp only [finset.mem_def.symm, finset.mem_erase, finset.mem_filter], assume x hx y hy hxy, rwa [← @add_right_cancel_iff _ _ 1, nat.sub_add_cancel hx.2, nat.sub_add_cancel hy.2] at hxy end (p.support.filter (> 0)).2⟩, mem_support_to_fun := λ n, suffices (∃ (a : ℕ), (¬coeff p a = 0 ∧ a > 0) ∧ a - 1 = n) ↔ ¬coeff p (n + 1) = 0, by simpa [finset.mem_def.symm, apply_eq_coeff], ⟨λ ⟨a, ha⟩, by rw [← ha.2, nat.sub_add_cancel ha.1.2]; exact ha.1.1, λ h, ⟨n + 1, ⟨h, nat.succ_pos _⟩, nat.succ_sub_one _⟩⟩ } lemma div_X_mul_X_add (p : polynomial α) : div_X p * X + C (p.coeff 0) = p := polynomial.ext.2 $ λ n, nat.cases_on n (by simp) (by simp [coeff_C, nat.succ_ne_zero, coeff_mul_X, div_X]) @[simp] lemma div_X_C (a : α) : div_X (C a) = 0 := polynomial.ext.2 $ λ n, by cases n; simp [div_X, coeff_C]; simp [coeff] lemma div_X_eq_zero_iff : div_X p = 0 ↔ p = C (p.coeff 0) := ⟨λ h, by simpa [eq_comm, h] using div_X_mul_X_add p, λ h, by rw [h, div_X_C]⟩ lemma div_X_add : div_X (p + q) = div_X p + div_X q := polynomial.ext.2 $ by simp [div_X] def nonzero_comm_semiring.of_polynomial_ne (h : p ≠ q) : nonzero_comm_semiring α := { zero_ne_one := λ h01 : 0 = 1, h $ by rw [← mul_one p, ← mul_one q, ← C_1, ← h01, C_0, mul_zero, mul_zero], ..show comm_semiring α, by apply_instance } lemma degree_lt_degree_mul_X (hp : p ≠ 0) : p.degree < (p * X).degree := by letI := nonzero_comm_semiring.of_polynomial_ne hp; exact have leading_coeff p * leading_coeff X ≠ 0, by simpa, by erw [degree_mul_eq' this, degree_eq_nat_degree hp, degree_X, ← with_bot.coe_one, ← with_bot.coe_add, with_bot.coe_lt_coe]; exact nat.lt_succ_self _ lemma degree_div_X_lt (hp0 : p ≠ 0) : (div_X p).degree < p.degree := by letI := nonzero_comm_semiring.of_polynomial_ne hp0; exact calc (div_X p).degree < (div_X p * X + C (p.coeff 0)).degree : if h : degree p ≤ 0 then begin have h' : C (p.coeff 0) ≠ 0, by rwa [← eq_C_of_degree_le_zero h], rw [eq_C_of_degree_le_zero h, div_X_C, degree_zero, zero_mul, zero_add], exact lt_of_le_of_ne lattice.bot_le (ne.symm (mt degree_eq_bot.1 $ by simp [h'])), end else have hXp0 : div_X p ≠ 0, by simpa [div_X_eq_zero_iff, -not_le, degree_le_zero_iff] using h, have leading_coeff (div_X p) * leading_coeff X ≠ 0, by simpa, have degree (C (p.coeff 0)) < degree (div_X p * X), from calc degree (C (p.coeff 0)) ≤ 0 : degree_C_le ... < 1 : dec_trivial ... = degree (X : polynomial α) : degree_X.symm ... ≤ degree (div_X p * X) : by rw [← zero_add (degree X), degree_mul_eq' this]; exact add_le_add' (by rw [zero_le_degree_iff, ne.def, div_X_eq_zero_iff]; exact λ h0, h (h0.symm ▸ degree_C_le)) (le_refl _), by rw [add_comm, degree_add_eq_of_degree_lt this]; exact degree_lt_degree_mul_X hXp0 ... = p.degree : by rw div_X_mul_X_add @[elab_as_eliminator] def rec_on_horner {M : polynomial α → Sort*} : Π (p : polynomial α), M 0 → (Π p a, coeff p 0 = 0 → a ≠ 0 → M p → M (p + C a)) → (Π p, p ≠ 0 → M p → M (p * X)) → M p | p := λ M0 MC MX, if hp : p = 0 then eq.rec_on hp.symm M0 else have wf : degree (div_X p) < degree p, from degree_div_X_lt hp, by rw [← div_X_mul_X_add p] at *; exact if hcp0 : coeff p 0 = 0 then by rw [hcp0, C_0, add_zero]; exact MX _ (λ h : div_X p = 0, by simpa [h, hcp0] using hp) (rec_on_horner _ M0 MC MX) else MC _ _ (coeff_mul_X_zero _) hcp0 (if hpX0 : div_X p = 0 then show M (div_X p * X), by rw [hpX0, zero_mul]; exact M0 else MX (div_X p) hpX0 (rec_on_horner _ M0 MC MX)) using_well_founded {dec_tac := tactic.assumption} @[elab_as_eliminator] lemma degree_pos_induction_on {P : polynomial α → Prop} (p : polynomial α) (h0 : 0 < degree p) (hC : ∀ {a}, a ≠ 0 → P (C a * X)) (hX : ∀ {p}, 0 < degree p → P p → P (p * X)) (hadd : ∀ {p} {a}, 0 < degree p → P p → P (p + C a)) : P p := rec_on_horner p (λ h, by rw degree_zero at h; exact absurd h dec_trivial) (λ p a _ _ ih h0, have 0 < degree p, from lt_of_not_ge (λ h, (not_lt_of_ge degree_C_le) $ by rwa [eq_C_of_degree_le_zero h, ← C_add] at h0), hadd this (ih this)) (λ p _ ih h0', if h0 : 0 < degree p then hX h0 (ih h0) else by rw [eq_C_of_degree_le_zero (le_of_not_gt h0)] at *; exact hC (λ h : coeff p 0 = 0, by simpa [h, not_lt.2 (@lattice.bot_le ( ℕ) _ _)] using h0')) h0 end comm_semiring section comm_ring variables [comm_ring α] [decidable_eq α] {p q : polynomial α} instance : comm_ring (polynomial α) := finsupp.comm_ring instance : has_scalar α (polynomial α) := finsupp.has_scalar -- TODO if this becomes a semimodule then the below lemma could be proved for semimodules instance : module α (polynomial α) := finsupp.module ℕ α -- TODO -- this is OK for semimodules @[simp] lemma coeff_smul (p : polynomial α) (r : α) (n : ℕ) : coeff (r • p) n = r * coeff p n := finsupp.smul_apply -- TODO -- this is OK for semimodules lemma C_mul' (a : α) (f : polynomial α) : C a * f = a • f := ext.2 $ λ n, coeff_C_mul f variable (α) def lcoeff (n : ℕ) : polynomial α →ₗ α := { to_fun := λ f, coeff f n, add := λ f g, coeff_add f g n, smul := λ r p, coeff_smul p r n } variable {α} @[simp] lemma lcoeff_apply (n : ℕ) (f : polynomial α) : lcoeff α n f = coeff f n := rfl instance C.is_ring_hom : is_ring_hom (@C α _ _) := by apply is_ring_hom.of_semiring lemma int_cast_eq_C (n : ℤ) : (n : polynomial α) = C n := congr_fun (int.eq_cast' _).symm n @[simp] lemma C_neg : C (-a) = -C a := is_ring_hom.map_neg C @[simp] lemma C_sub : C (a - b) = C a - C b := is_ring_hom.map_sub C instance eval₂.is_ring_hom {β} [comm_ring β] (f : α → β) [is_ring_hom f] {x : β} : is_ring_hom (eval₂ f x) := by apply is_ring_hom.of_semiring instance eval.is_ring_hom {x : α} : is_ring_hom (eval x) := eval₂.is_ring_hom _ instance map.is_ring_hom {β} [comm_ring β] [decidable_eq β] (f : α → β) [is_ring_hom f] : is_ring_hom (map f) := eval₂.is_ring_hom (C ∘ f) @[simp] lemma map_sub {β} [comm_ring β] [decidable_eq β] (f : α → β) [is_ring_hom f] : (p - q).map f = p.map f - q.map f := is_ring_hom.map_sub _ @[simp] lemma map_neg {β} [comm_ring β] [decidable_eq β] (f : α → β) [is_ring_hom f] : (-p).map f = -(p.map f) := is_ring_hom.map_neg _ @[simp] lemma degree_neg (p : polynomial α) : degree (-p) = degree p := by unfold degree; rw support_neg @[simp] lemma nat_degree_int_cast (n : ℤ) : nat_degree (n : polynomial α) = 0 := by simp [int_cast_eq_C] @[simp] lemma coeff_neg (p : polynomial α) (n : ℕ) : coeff (-p) n = -coeff p n := rfl @[simp] lemma coeff_sub (p q : polynomial α) (n : ℕ) : coeff (p - q) n = coeff p n - coeff q n := rfl @[simp] lemma eval₂_neg {β} [comm_ring β] (f : α → β) [is_ring_hom f] {x : β} : (-p).eval₂ f x = -p.eval₂ f x := is_ring_hom.map_neg _ @[simp] lemma eval₂_sub {β} [comm_ring β] (f : α → β) [is_ring_hom f] {x : β} : (p - q).eval₂ f x = p.eval₂ f x - q.eval₂ f x := is_ring_hom.map_sub _ @[simp] lemma eval_neg (p : polynomial α) (x : α) : (-p).eval x = -p.eval x := is_ring_hom.map_neg _ @[simp] lemma eval_sub (p q : polynomial α) (x : α) : (p - q).eval x = p.eval x - q.eval x := is_ring_hom.map_sub _ lemma degree_sub_lt (hd : degree p = degree q) (hp0 : p ≠ 0) (hlc : leading_coeff p = leading_coeff q) : degree (p - q) < degree p := have hp : single (nat_degree p) (leading_coeff p) + p.erase (nat_degree p) = p := finsupp.single_add_erase, have hq : single (nat_degree q) (leading_coeff q) + q.erase (nat_degree q) = q := finsupp.single_add_erase, have hd' : nat_degree p = nat_degree q := by unfold nat_degree; rw hd, have hq0 : q ≠ 0 := mt degree_eq_bot.2 (hd ▸ mt degree_eq_bot.1 hp0), calc degree (p - q) = degree (erase (nat_degree q) p + -erase (nat_degree q) q) : by conv {to_lhs, rw [← hp, ← hq, hlc, hd', add_sub_add_left_eq_sub, sub_eq_add_neg]} ... ≤ max (degree (erase (nat_degree q) p)) (degree (erase (nat_degree q) q)) : degree_neg (erase (nat_degree q) q) ▸ degree_add_le _ _ ... < degree p : max_lt_iff.2 ⟨hd' ▸ degree_erase_lt hp0, hd.symm ▸ degree_erase_lt hq0⟩ lemma ne_zero_of_ne_zero_of_monic (hp : p ≠ 0) (hq : monic q) : q ≠ 0 | h := begin rw [h, monic.def, leading_coeff_zero] at hq, rw [← mul_one p, ← C_1, ← hq, C_0, mul_zero] at hp, exact hp rfl end lemma div_wf_lemma (h : degree q ≤ degree p ∧ p ≠ 0) (hq : monic q) : degree (p - C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q) < degree p := have hp : leading_coeff p ≠ 0 := mt leading_coeff_eq_zero.1 h.2, have hpq : leading_coeff (C (leading_coeff p) * X ^ (nat_degree p - nat_degree q)) * leading_coeff q ≠ 0, by rwa [leading_coeff_monomial, monic.def.1 hq, mul_one], if h0 : p - C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q = 0 then h0.symm ▸ (lt_of_not_ge $ mt le_bot_iff.1 (mt degree_eq_bot.1 h.2)) else have hq0 : q ≠ 0 := ne_zero_of_ne_zero_of_monic h.2 hq, have hlt : nat_degree q ≤ nat_degree p := with_bot.coe_le_coe.1 (by rw [← degree_eq_nat_degree h.2, ← degree_eq_nat_degree hq0]; exact h.1), degree_sub_lt (by rw [degree_mul_eq' hpq, degree_monomial _ hp, degree_eq_nat_degree h.2, degree_eq_nat_degree hq0, ← with_bot.coe_add, nat.sub_add_cancel hlt]) h.2 (by rw [leading_coeff_mul' hpq, leading_coeff_monomial, monic.def.1 hq, mul_one]) def div_mod_by_monic_aux : Π (p : polynomial α) {q : polynomial α}, monic q → polynomial α × polynomial α | p := λ q hq, if h : degree q ≤ degree p ∧ p ≠ 0 then let z := C (leading_coeff p) * X^(nat_degree p - nat_degree q) in have wf : _ := div_wf_lemma h hq, let dm := div_mod_by_monic_aux (p - z * q) hq in ⟨z + dm.1, dm.2⟩ else ⟨0, p⟩ using_well_founded {dec_tac := tactic.assumption} /-- `div_by_monic` gives the quotient of `p` by a monic polynomial `q`. -/ def div_by_monic (p q : polynomial α) : polynomial α := if hq : monic q then (div_mod_by_monic_aux p hq).1 else 0 /-- `mod_by_monic` gives the remainder of `p` by a monic polynomial `q`. -/ def mod_by_monic (p q : polynomial α) : polynomial α := if hq : monic q then (div_mod_by_monic_aux p hq).2 else p infixl ` /ₘ ` : 70 := div_by_monic infixl ` %ₘ ` : 70 := mod_by_monic lemma degree_mod_by_monic_lt : ∀ (p : polynomial α) {q : polynomial α} (hq : monic q) (hq0 : q ≠ 0), degree (p %ₘ q) < degree q | p := λ q hq hq0, if h : degree q ≤ degree p ∧ p ≠ 0 then have wf : _ := div_wf_lemma ⟨h.1, h.2⟩ hq, have degree ((p - C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q) %ₘ q) < degree q := degree_mod_by_monic_lt (p - C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q) hq hq0, begin unfold mod_by_monic at this ⊢, unfold div_mod_by_monic_aux, rw dif_pos hq at this ⊢, rw if_pos h, exact this end else or.cases_on (not_and_distrib.1 h) begin unfold mod_by_monic div_mod_by_monic_aux, rw [dif_pos hq, if_neg h], exact lt_of_not_ge, end begin assume hp, unfold mod_by_monic div_mod_by_monic_aux, rw [dif_pos hq, if_neg h, not_not.1 hp], exact lt_of_le_of_ne bot_le (ne.symm (mt degree_eq_bot.1 hq0)), end using_well_founded {dec_tac := tactic.assumption} lemma mod_by_monic_eq_sub_mul_div : ∀ (p : polynomial α) {q : polynomial α} (hq : monic q), p %ₘ q = p - q * (p /ₘ q) | p := λ q hq, if h : degree q ≤ degree p ∧ p ≠ 0 then have wf : _ := div_wf_lemma h hq, have ih : _ := mod_by_monic_eq_sub_mul_div (p - C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q) hq, begin unfold mod_by_monic div_by_monic div_mod_by_monic_aux, rw [dif_pos hq, if_pos h], rw [mod_by_monic, dif_pos hq] at ih, refine ih.trans _, unfold div_by_monic, rw [dif_pos hq, dif_pos hq, if_pos h, mul_add, sub_add_eq_sub_sub, mul_comm] end else begin unfold mod_by_monic div_by_monic div_mod_by_monic_aux, rw [dif_pos hq, if_neg h, dif_pos hq, if_neg h, mul_zero, sub_zero] end using_well_founded {dec_tac := tactic.assumption} lemma mod_by_monic_add_div (p : polynomial α) {q : polynomial α} (hq : monic q) : p %ₘ q + q * (p /ₘ q) = p := eq_sub_iff_add_eq.1 (mod_by_monic_eq_sub_mul_div p hq) @[simp] lemma zero_mod_by_monic (p : polynomial α) : 0 %ₘ p = 0 := begin unfold mod_by_monic div_mod_by_monic_aux, by_cases hp : monic p, { rw [dif_pos hp, if_neg (mt and.right (not_not_intro rfl))] }, { rw [dif_neg hp] } end @[simp] lemma zero_div_by_monic (p : polynomial α) : 0 /ₘ p = 0 := begin unfold div_by_monic div_mod_by_monic_aux, by_cases hp : monic p, { rw [dif_pos hp, if_neg (mt and.right (not_not_intro rfl))] }, { rw [dif_neg hp] } end @[simp] lemma mod_by_monic_zero (p : polynomial α) : p %ₘ 0 = p := if h : monic (0 : polynomial α) then (subsingleton_of_monic_zero h).1 _ _ else by unfold mod_by_monic div_mod_by_monic_aux; rw dif_neg h @[simp] lemma div_by_monic_zero (p : polynomial α) : p /ₘ 0 = 0 := if h : monic (0 : polynomial α) then (subsingleton_of_monic_zero h).1 _ _ else by unfold div_by_monic div_mod_by_monic_aux; rw dif_neg h lemma div_by_monic_eq_of_not_monic (p : polynomial α) (hq : ¬monic q) : p /ₘ q = 0 := dif_neg hq lemma mod_by_monic_eq_of_not_monic (p : polynomial α) (hq : ¬monic q) : p %ₘ q = p := dif_neg hq lemma mod_by_monic_eq_self_iff (hq : monic q) (hq0 : q ≠ 0) : p %ₘ q = p ↔ degree p < degree q := ⟨λ h, h ▸ degree_mod_by_monic_lt _ hq hq0, λ h, have ¬ degree q ≤ degree p := not_le_of_gt h, by unfold mod_by_monic div_mod_by_monic_aux; rw [dif_pos hq, if_neg (mt and.left this)]⟩ lemma div_by_monic_eq_zero_iff (hq : monic q) (hq0 : q ≠ 0) : p /ₘ q = 0 ↔ degree p < degree q := ⟨λ h, by have := mod_by_monic_add_div p hq; rwa [h, mul_zero, add_zero, mod_by_monic_eq_self_iff hq hq0] at this, λ h, have ¬ degree q ≤ degree p := not_le_of_gt h, by unfold div_by_monic div_mod_by_monic_aux; rw [dif_pos hq, if_neg (mt and.left this)]⟩ lemma degree_add_div_by_monic (hq : monic q) (h : degree q ≤ degree p) : degree q + degree (p /ₘ q) = degree p := if hq0 : q = 0 then have ∀ (p : polynomial α), p = 0, from λ p, (@subsingleton_of_monic_zero α _ _ (hq0 ▸ hq)).1 _ _, by rw [this (p /ₘ q), this p, this q]; refl else have hdiv0 : p /ₘ q ≠ 0 := by rwa [(≠), div_by_monic_eq_zero_iff hq hq0, not_lt], have hlc : leading_coeff q * leading_coeff (p /ₘ q) ≠ 0 := by rwa [monic.def.1 hq, one_mul, (≠), leading_coeff_eq_zero], have hmod : degree (p %ₘ q) < degree (q * (p /ₘ q)) := calc degree (p %ₘ q) < degree q : degree_mod_by_monic_lt _ hq hq0 ... ≤ _ : by rw [degree_mul_eq' hlc, degree_eq_nat_degree hq0, degree_eq_nat_degree hdiv0, ← with_bot.coe_add, with_bot.coe_le_coe]; exact nat.le_add_right _ _, calc degree q + degree (p /ₘ q) = degree (q * (p /ₘ q)) : eq.symm (degree_mul_eq' hlc) ... = degree (p %ₘ q + q * (p /ₘ q)) : (degree_add_eq_of_degree_lt hmod).symm ... = _ : congr_arg _ (mod_by_monic_add_div _ hq) lemma degree_div_by_monic_le (p q : polynomial α) : degree (p /ₘ q) ≤ degree p := if hp0 : p = 0 then by simp only [hp0, zero_div_by_monic, le_refl] else if hq : monic q then have hq0 : q ≠ 0 := ne_zero_of_ne_zero_of_monic hp0 hq, if h : degree q ≤ degree p then by rw [← degree_add_div_by_monic hq h, degree_eq_nat_degree hq0, degree_eq_nat_degree (mt (div_by_monic_eq_zero_iff hq hq0).1 (not_lt.2 h))]; exact with_bot.coe_le_coe.2 (nat.le_add_left _ _) else by unfold div_by_monic div_mod_by_monic_aux; simp only [dif_pos hq, h, false_and, if_false, degree_zero, bot_le] else (div_by_monic_eq_of_not_monic p hq).symm ▸ bot_le lemma degree_div_by_monic_lt (p : polynomial α) {q : polynomial α} (hq : monic q) (hp0 : p ≠ 0) (h0q : 0 < degree q) : degree (p /ₘ q) < degree p := have hq0 : q ≠ 0 := ne_zero_of_ne_zero_of_monic hp0 hq, if hpq : degree p < degree q then begin rw [(div_by_monic_eq_zero_iff hq hq0).2 hpq, degree_eq_nat_degree hp0], exact with_bot.bot_lt_some _ end else begin rw [← degree_add_div_by_monic hq (not_lt.1 hpq), degree_eq_nat_degree hq0, degree_eq_nat_degree (mt (div_by_monic_eq_zero_iff hq hq0).1 hpq)], exact with_bot.coe_lt_coe.2 (nat.lt_add_of_pos_left (with_bot.coe_lt_coe.1 $ (degree_eq_nat_degree hq0) ▸ h0q)) end lemma div_mod_by_monic_unique {f g} (q r : polynomial α) (hg : monic g) (h : r + g * q = f ∧ degree r < degree g) : f /ₘ g = q ∧ f %ₘ g = r := if hg0 : g = 0 then by split; exact (subsingleton_of_monic_zero (hg0 ▸ hg : monic (0 : polynomial α))).1 _ _ else have h₁ : r - f %ₘ g = -g * (q - f /ₘ g), from eq_of_sub_eq_zero (by rw [← sub_eq_zero_of_eq (h.1.trans (mod_by_monic_add_div f hg).symm)]; simp [mul_add, mul_comm]), have h₂ : degree (r - f %ₘ g) = degree (g * (q - f /ₘ g)), by simp [h₁], have h₄ : degree (r - f %ₘ g) < degree g, from calc degree (r - f %ₘ g) ≤ max (degree r) (degree (-(f %ₘ g))) : degree_add_le _ _ ... < degree g : max_lt_iff.2 ⟨h.2, by rw degree_neg; exact degree_mod_by_monic_lt _ hg hg0⟩, have h₅ : q - (f /ₘ g) = 0, from by_contradiction (λ hqf, not_le_of_gt h₄ $ calc degree g ≤ degree g + degree (q - f /ₘ g) : by erw [degree_eq_nat_degree hg0, degree_eq_nat_degree hqf, with_bot.coe_le_coe]; exact nat.le_add_right _ _ ... = degree (r - f %ₘ g) : by rw [h₂, degree_mul_eq']; simpa [monic.def.1 hg]), ⟨eq.symm $ eq_of_sub_eq_zero h₅, eq.symm $ eq_of_sub_eq_zero $ by simpa [h₅] using h₁⟩ lemma map_mod_div_by_monic [comm_ring β] [decidable_eq β] (f : α → β) [is_semiring_hom f] (hq : monic q) : (p /ₘ q).map f = p.map f /ₘ q.map f ∧ (p %ₘ q).map f = p.map f %ₘ q.map f := if h01 : (0 : β) = 1 then by haveI := subsingleton_of_zero_eq_one β h01; exact ⟨subsingleton.elim _ _, subsingleton.elim _ _⟩ else have h01α : (0 : α) ≠ 1, from mt (congr_arg f) (by rwa [is_semiring_hom.map_one f, is_semiring_hom.map_zero f]), have map f p /ₘ map f q = map f (p /ₘ q) ∧ map f p %ₘ map f q = map f (p %ₘ q), from (div_mod_by_monic_unique ((p /ₘ q).map f) _ (monic_map f hq) ⟨eq.symm $ by rw [← map_mul, ← map_add, mod_by_monic_add_div _ hq], calc _ ≤ degree (p %ₘ q) : degree_map_le _ ... < degree q : degree_mod_by_monic_lt _ hq $ (ne_zero_of_monic_of_zero_ne_one hq h01α) ... = _ : eq.symm $ degree_map_eq_of_leading_coeff_ne_zero _ (by rw [monic.def.1 hq, is_semiring_hom.map_one f]; exact ne.symm h01)⟩), ⟨this.1.symm, this.2.symm⟩ lemma map_div_by_monic [comm_ring β] [decidable_eq β] (f : α → β) [is_semiring_hom f] (hq : monic q) : (p /ₘ q).map f = p.map f /ₘ q.map f := (map_mod_div_by_monic f hq).1 lemma map_mod_by_monic [comm_ring β] [decidable_eq β] (f : α → β) [is_semiring_hom f] (hq : monic q) : (p %ₘ q).map f = p.map f %ₘ q.map f := (map_mod_div_by_monic f hq).2 lemma dvd_iff_mod_by_monic_eq_zero (hq : monic q) : p %ₘ q = 0 ↔ q ∣ p := ⟨λ h, by rw [← mod_by_monic_add_div p hq, h, zero_add]; exact dvd_mul_right _ _, λ h, if hq0 : q = 0 then by rw hq0 at hq; exact (subsingleton_of_monic_zero hq).1 _ _ else let ⟨r, hr⟩ := exists_eq_mul_right_of_dvd h in by_contradiction (λ hpq0, have hmod : p %ₘ q = q * (r - p /ₘ q) := by rw [mod_by_monic_eq_sub_mul_div _ hq, mul_sub, ← hr], have degree (q * (r - p /ₘ q)) < degree q := hmod ▸ degree_mod_by_monic_lt _ hq hq0, have hrpq0 : leading_coeff (r - p /ₘ q) ≠ 0 := λ h, hpq0 $ leading_coeff_eq_zero.1 (by rw [hmod, leading_coeff_eq_zero.1 h, mul_zero, leading_coeff_zero]), have hlc : leading_coeff q * leading_coeff (r - p /ₘ q) ≠ 0 := by rwa [monic.def.1 hq, one_mul], by rw [degree_mul_eq' hlc, degree_eq_nat_degree hq0, degree_eq_nat_degree (mt leading_coeff_eq_zero.2 hrpq0)] at this; exact not_lt_of_ge (nat.le_add_right _ _) (with_bot.some_lt_some.1 this))⟩ @[simp] lemma mod_by_monic_one (p : polynomial α) : p %ₘ 1 = 0 := (dvd_iff_mod_by_monic_eq_zero monic_one).2 (one_dvd _) @[simp] lemma div_by_monic_one (p : polynomial α) : p /ₘ 1 = p := by conv_rhs { rw [← mod_by_monic_add_div p monic_one] }; simp lemma degree_pos_of_root (hp : p ≠ 0) (h : is_root p a) : 0 < degree p := lt_of_not_ge $ λ hlt, begin have := eq_C_of_degree_le_zero hlt, rw [is_root, this, eval_C] at h, exact hp (finsupp.ext (λ n, show coeff p n = 0, from nat.cases_on n h (λ _, coeff_eq_zero_of_degree_lt (lt_of_le_of_lt hlt (with_bot.coe_lt_coe.2 (nat.succ_pos _)))))), end theorem monic_X_sub_C (x : α) : monic (X - C x) := by simpa only [C_neg] using monic_X_add_C (-x) theorem monic_X_pow_sub {n : ℕ} (H : degree p ≤ n) : monic (X ^ (n+1) - p) := monic_X_pow_add ((degree_neg p).symm ▸ H) theorem degree_mod_by_monic_le (p : polynomial α) {q : polynomial α} (hq : monic q) : degree (p %ₘ q) ≤ degree q := decidable.by_cases (assume H : q = 0, by rw [monic, H, leading_coeff_zero] at hq; have : (0:polynomial α) = 1 := (by rw [← C_0, ← C_1, hq]); rw [eq_zero_of_zero_eq_one _ this (p %ₘ q), eq_zero_of_zero_eq_one _ this q]; exact le_refl _) (assume H : q ≠ 0, le_of_lt $ degree_mod_by_monic_lt _ hq H) lemma root_X_sub_C : is_root (X - C a) b ↔ a = b := by rw [is_root.def, eval_sub, eval_X, eval_C, sub_eq_zero_iff_eq, eq_comm] def nonzero_comm_ring.of_polynomial_ne (h : p ≠ q) : nonzero_comm_ring α := { zero := 0, one := 1, zero_ne_one := λ h01, h $ by rw [← one_mul p, ← one_mul q, ← C_1, ← h01, C_0, zero_mul, zero_mul], ..show comm_ring α, by apply_instance } end comm_ring section nonzero_comm_ring variables [nonzero_comm_ring α] [decidable_eq α] {p q : polynomial α} instance : nonzero_comm_ring (polynomial α) := { ..polynomial.nonzero_comm_semiring, ..polynomial.comm_ring } @[simp] lemma degree_X_sub_C (a : α) : degree (X - C a) = 1 := begin rw [sub_eq_add_neg, add_comm, ← @degree_X α], by_cases ha : a = 0, { simp only [ha, C_0, neg_zero, zero_add] }, exact degree_add_eq_of_degree_lt (by rw [degree_X, degree_neg, degree_C ha]; exact dec_trivial) end lemma degree_X_pow_sub_C {n : ℕ} (hn : 0 < n) (a : α) : degree ((X : polynomial α) ^ n - C a) = n := have degree (-C a) < degree ((X : polynomial α) ^ n), from calc degree (-C a) ≤ 0 : by rw degree_neg; exact degree_C_le ... < degree ((X : polynomial α) ^ n) : by rwa [degree_X_pow]; exact with_bot.coe_lt_coe.2 hn, by rw [sub_eq_add_neg, add_comm, degree_add_eq_of_degree_lt this, degree_X_pow] lemma X_pow_sub_C_ne_zero {n : ℕ} (hn : 0 < n) (a : α) : (X : polynomial α) ^ n - C a ≠ 0 := mt degree_eq_bot.2 (show degree ((X : polynomial α) ^ n - C a) ≠ ⊥, by rw degree_X_pow_sub_C hn; exact dec_trivial) end nonzero_comm_ring section comm_ring variables [comm_ring α] [decidable_eq α] {p q : polynomial α} @[simp] lemma mod_by_monic_X_sub_C_eq_C_eval (p : polynomial α) (a : α) : p %ₘ (X - C a) = C (p.eval a) := if h0 : (0 : α) = 1 then by letI := subsingleton_of_zero_eq_one α h0; exact subsingleton.elim _ _ else by letI : nonzero_comm_ring α := nonzero_comm_ring.of_ne h0; exact have h : (p %ₘ (X - C a)).eval a = p.eval a := by rw [mod_by_monic_eq_sub_mul_div _ (monic_X_sub_C a), eval_sub, eval_mul, eval_sub, eval_X, eval_C, sub_self, zero_mul, sub_zero], have degree (p %ₘ (X - C a)) < 1 := degree_X_sub_C a ▸ degree_mod_by_monic_lt p (monic_X_sub_C a) ((degree_X_sub_C a).symm ▸ ne_zero_of_monic (monic_X_sub_C _)), have degree (p %ₘ (X - C a)) ≤ 0 := begin cases (degree (p %ₘ (X - C a))), { exact bot_le }, { exact with_bot.some_le_some.2 (nat.le_of_lt_succ (with_bot.some_lt_some.1 this)) } end, begin rw [eq_C_of_degree_le_zero this, eval_C] at h, rw [eq_C_of_degree_le_zero this, h] end lemma mul_div_by_monic_eq_iff_is_root : (X - C a) * (p /ₘ (X - C a)) = p ↔ is_root p a := ⟨λ h, by rw [← h, is_root.def, eval_mul, eval_sub, eval_X, eval_C, sub_self, zero_mul], λ h : p.eval a = 0, by conv {to_rhs, rw ← mod_by_monic_add_div p (monic_X_sub_C a)}; rw [mod_by_monic_X_sub_C_eq_C_eval, h, C_0, zero_add]⟩ lemma dvd_iff_is_root : (X - C a) ∣ p ↔ is_root p a := ⟨λ h, by rwa [← dvd_iff_mod_by_monic_eq_zero (monic_X_sub_C _), mod_by_monic_X_sub_C_eq_C_eval, ← C_0, C_inj] at h, λ h, ⟨(p /ₘ (X - C a)), by rw mul_div_by_monic_eq_iff_is_root.2 h⟩⟩ lemma mod_by_monic_X (p : polynomial α) : p %ₘ X = C (p.eval 0) := by rw [← mod_by_monic_X_sub_C_eq_C_eval, C_0, sub_zero] section multiplicity def decidable_dvd_monic (p : polynomial α) (hq : monic q) : decidable (q ∣ p) := decidable_of_iff (p %ₘ q = 0) (dvd_iff_mod_by_monic_eq_zero hq) local attribute [instance, priority 0] classical.dec lemma multiplicity_X_sub_C_finite (a : α) (h0 : p ≠ 0) : multiplicity.finite (X - C a) p := multiplicity_finite_of_degree_pos_of_monic (have (0 : α) ≠ 1, from (λ h, by haveI := subsingleton_of_zero_eq_one _ h; exact h0 (subsingleton.elim _ _)), by letI : nonzero_comm_ring α := { zero_ne_one := this, ..show comm_ring α, by apply_instance }; rw degree_X_sub_C; exact dec_trivial) (monic_X_sub_C _) h0 def root_multiplicity (a : α) (p : polynomial α) : ℕ := if h0 : p = 0 then 0 else let I : decidable_pred (λ n : ℕ, ¬(X - C a) ^ (n + 1) ∣ p) := λ n, @not.decidable _ (decidable_dvd_monic p (monic_pow (monic_X_sub_C a) (n + 1))) in by exactI nat.find (multiplicity_X_sub_C_finite a h0) lemma root_multiplicity_eq_multiplicity (p : polynomial α) (a : α) : root_multiplicity a p = if h0 : p = 0 then 0 else (multiplicity (X - C a) p).get (multiplicity_X_sub_C_finite a h0) := by simp [multiplicity, root_multiplicity, roption.dom]; congr; funext; congr lemma pow_root_multiplicity_dvd (p : polynomial α) (a : α) : (X - C a) ^ root_multiplicity a p ∣ p := if h : p = 0 then by simp [h] else by rw [root_multiplicity_eq_multiplicity, dif_neg h]; exact multiplicity.pow_multiplicity_dvd _ lemma div_by_monic_mul_pow_root_multiplicity_eq (p : polynomial α) (a : α) : p /ₘ ((X - C a) ^ root_multiplicity a p) * (X - C a) ^ root_multiplicity a p = p := have monic ((X - C a) ^ root_multiplicity a p), from monic_pow (monic_X_sub_C _) _, by conv_rhs { rw [← mod_by_monic_add_div p this, (dvd_iff_mod_by_monic_eq_zero this).2 (pow_root_multiplicity_dvd _ _)] }; simp [mul_comm] lemma eval_div_by_monic_pow_root_multiplicity_ne_zero {p : polynomial α} (a : α) (hp : p ≠ 0) : (p /ₘ ((X - C a) ^ root_multiplicity a p)).eval a ≠ 0 := begin letI : nonzero_comm_ring α := nonzero_comm_ring.of_polynomial_ne hp, rw [ne.def, ← is_root.def, ← dvd_iff_is_root], rintros ⟨q, hq⟩, have := div_by_monic_mul_pow_root_multiplicity_eq p a, rw [mul_comm, hq, ← mul_assoc, ← pow_succ', root_multiplicity_eq_multiplicity, dif_neg hp] at this, exact multiplicity.is_greatest' (multiplicity_finite_of_degree_pos_of_monic (show (0 : with_bot ℕ) < degree (X - C a), by rw degree_X_sub_C; exact dec_trivial) _ hp) (nat.lt_succ_self _) (dvd_of_mul_right_eq _ this) end end multiplicity end comm_ring section integral_domain variables [integral_domain α] [decidable_eq α] {p q : polynomial α} @[simp] lemma degree_mul_eq : degree (p * q) = degree p + degree q := if hp0 : p = 0 then by simp only [hp0, degree_zero, zero_mul, with_bot.bot_add] else if hq0 : q = 0 then by simp only [hq0, degree_zero, mul_zero, with_bot.add_bot] else degree_mul_eq' $ mul_ne_zero (mt leading_coeff_eq_zero.1 hp0) (mt leading_coeff_eq_zero.1 hq0) @[simp] lemma degree_pow_eq (p : polynomial α) (n : ℕ) : degree (p ^ n) = add_monoid.smul n (degree p) := by induction n; [simp only [pow_zero, degree_one, add_monoid.zero_smul], simp only [*, pow_succ, succ_smul, degree_mul_eq]] @[simp] lemma leading_coeff_mul (p q : polynomial α) : leading_coeff (p * q) = leading_coeff p * leading_coeff q := begin by_cases hp : p = 0, { simp only [hp, zero_mul, leading_coeff_zero] }, { by_cases hq : q = 0, { simp only [hq, mul_zero, leading_coeff_zero] }, { rw [leading_coeff_mul'], exact mul_ne_zero (mt leading_coeff_eq_zero.1 hp) (mt leading_coeff_eq_zero.1 hq) } } end @[simp] lemma leading_coeff_pow (p : polynomial α) (n : ℕ) : leading_coeff (p ^ n) = leading_coeff p ^ n := by induction n; [simp only [pow_zero, leading_coeff_one], simp only [*, pow_succ, leading_coeff_mul]] instance : integral_domain (polynomial α) := { eq_zero_or_eq_zero_of_mul_eq_zero := λ a b h, begin have : leading_coeff 0 = leading_coeff a * leading_coeff b := h ▸ leading_coeff_mul a b, rw [leading_coeff_zero, eq_comm] at this, rw [← leading_coeff_eq_zero, ← leading_coeff_eq_zero], exact eq_zero_or_eq_zero_of_mul_eq_zero this end, ..polynomial.nonzero_comm_ring } lemma nat_degree_mul_eq (hp : p ≠ 0) (hq : q ≠ 0) : nat_degree (p * q) = nat_degree p + nat_degree q := by rw [← with_bot.coe_eq_coe, ← degree_eq_nat_degree (mul_ne_zero hp hq), with_bot.coe_add, ← degree_eq_nat_degree hp, ← degree_eq_nat_degree hq, degree_mul_eq] @[simp] lemma nat_degree_pow_eq (p : polynomial α) (n : ℕ) : nat_degree (p ^ n) = n * nat_degree p := if hp0 : p = 0 then if hn0 : n = 0 then by simp [hp0, hn0] else by rw [hp0, zero_pow (nat.pos_of_ne_zero hn0)]; simp else nat_degree_pow_eq' (by rw [← leading_coeff_pow, ne.def, leading_coeff_eq_zero]; exact pow_ne_zero _ hp0) lemma root_or_root_of_root_mul (h : is_root (p * q) a) : is_root p a ∨ is_root q a := by rw [is_root, eval_mul] at h; exact eq_zero_or_eq_zero_of_mul_eq_zero h lemma degree_le_mul_left (p : polynomial α) (hq : q ≠ 0) : degree p ≤ degree (p * q) := if hp : p = 0 then by simp only [hp, zero_mul, le_refl] else by rw [degree_mul_eq, degree_eq_nat_degree hp, degree_eq_nat_degree hq]; exact with_bot.coe_le_coe.2 (nat.le_add_right _ _) lemma exists_finset_roots : ∀ {p : polynomial α} (hp : p ≠ 0), ∃ s : finset α, (s.card : with_bot ℕ) ≤ degree p ∧ ∀ x, x ∈ s ↔ is_root p x | p := λ hp, by haveI := classical.prop_decidable (∃ x, is_root p x); exact if h : ∃ x, is_root p x then let ⟨x, hx⟩ := h in have hpd : 0 < degree p := degree_pos_of_root hp hx, have hd0 : p /ₘ (X - C x) ≠ 0 := λ h, by rw [← mul_div_by_monic_eq_iff_is_root.2 hx, h, mul_zero] at hp; exact hp rfl, have wf : degree (p /ₘ _) < degree p := degree_div_by_monic_lt _ (monic_X_sub_C x) hp ((degree_X_sub_C x).symm ▸ dec_trivial), let ⟨t, htd, htr⟩ := @exists_finset_roots (p /ₘ (X - C x)) hd0 in have hdeg : degree (X - C x) ≤ degree p := begin rw [degree_X_sub_C, degree_eq_nat_degree hp], rw degree_eq_nat_degree hp at hpd, exact with_bot.coe_le_coe.2 (with_bot.coe_lt_coe.1 hpd) end, have hdiv0 : p /ₘ (X - C x) ≠ 0 := mt (div_by_monic_eq_zero_iff (monic_X_sub_C x) (ne_zero_of_monic (monic_X_sub_C x))).1 $ not_lt.2 hdeg, ⟨insert x t, calc (card (insert x t) : with_bot ℕ) ≤ card t + 1 : with_bot.coe_le_coe.2 $ finset.card_insert_le _ _ ... ≤ degree p : by rw [← degree_add_div_by_monic (monic_X_sub_C x) hdeg, degree_X_sub_C, add_comm]; exact add_le_add' (le_refl (1 : with_bot ℕ)) htd, begin assume y, rw [mem_insert, htr, eq_comm, ← root_X_sub_C], conv {to_rhs, rw ← mul_div_by_monic_eq_iff_is_root.2 hx}, exact ⟨λ h, or.cases_on h (root_mul_right_of_is_root _) (root_mul_left_of_is_root _), root_or_root_of_root_mul⟩ end⟩ else ⟨∅, (degree_eq_nat_degree hp).symm ▸ with_bot.coe_le_coe.2 (nat.zero_le _), by simpa only [not_mem_empty, false_iff, not_exists] using h⟩ using_well_founded {dec_tac := tactic.assumption} /-- `roots p` noncomputably gives a finset containing all the roots of `p` -/ noncomputable def roots (p : polynomial α) : finset α := if h : p = 0 then ∅ else classical.some (exists_finset_roots h) lemma card_roots (hp0 : p ≠ 0) : ((roots p).card : with_bot ℕ) ≤ degree p := begin unfold roots, rw dif_neg hp0, exact (classical.some_spec (exists_finset_roots hp0)).1 end @[simp] lemma mem_roots (hp : p ≠ 0) : a ∈ p.roots ↔ is_root p a := by unfold roots; rw dif_neg hp; exact (classical.some_spec (exists_finset_roots hp)).2 _ lemma card_roots_X_pow_sub_C {n : ℕ} (hn : 0 < n) (a : α) : (roots ((X : polynomial α) ^ n - C a)).card ≤ n := with_bot.coe_le_coe.1 $ calc ((roots ((X : polynomial α) ^ n - C a)).card : with_bot ℕ) ≤ degree ((X : polynomial α) ^ n - C a) : card_roots (X_pow_sub_C_ne_zero hn a) ... = n : degree_X_pow_sub_C hn a /-- `nth_roots n a` noncomputably returns the solutions to `x ^ n = a`-/ noncomputable def nth_roots {α : Type*} [integral_domain α] (n : ℕ) (a : α) : finset α := by letI := classical.prop_decidable; exact roots ((X : polynomial α) ^ n - C a) @[simp] lemma mem_nth_roots {α : Type*} [integral_domain α] {n : ℕ} (hn : 0 < n) {a x : α} : x ∈ nth_roots n a ↔ x ^ n = a := by letI := classical.prop_decidable; rw [nth_roots, mem_roots (X_pow_sub_C_ne_zero hn a), is_root.def, eval_sub, eval_C, eval_pow, eval_X, sub_eq_zero_iff_eq] lemma card_nth_roots {α : Type*} [integral_domain α] (n : ℕ) (a : α) : (nth_roots n a).card ≤ n := by letI := classical.prop_decidable; exact if hn : n = 0 then if h : (X : polynomial α) ^ n - C a = 0 then by simp only [nat.zero_le, nth_roots, roots, h, dif_pos rfl, card_empty] else with_bot.coe_le_coe.1 (le_trans (card_roots h) (by rw [hn, pow_zero, ← @C_1 α _ _, ← @is_ring_hom.map_sub _ _ _ _ (@C α _ _)]; exact degree_C_le)) else by rw [← with_bot.coe_le_coe, ← degree_X_pow_sub_C (nat.pos_of_ne_zero hn) a]; exact card_roots (X_pow_sub_C_ne_zero (nat.pos_of_ne_zero hn) a) lemma coeff_comp_degree_mul_degree (hqd0 : nat_degree q ≠ 0) : coeff (p.comp q) (nat_degree p * nat_degree q) = leading_coeff p * leading_coeff q ^ nat_degree p := if hp0 : p = 0 then by simp [hp0] else calc coeff (p.comp q) (nat_degree p * nat_degree q) = p.sum (λ n a, coeff (C a * q ^ n) (nat_degree p * nat_degree q)) : by rw [comp, eval₂, coeff_sum] ... = coeff (C (leading_coeff p) * q ^ nat_degree p) (nat_degree p * nat_degree q) : finset.sum_eq_single _ begin assume b hbs hbp, have hq0 : q ≠ 0, from λ hq0, hqd0 (by rw [hq0, nat_degree_zero]), have : coeff p b ≠ 0, rwa [← apply_eq_coeff, ← finsupp.mem_support_iff], dsimp [apply_eq_coeff], refine coeff_eq_zero_of_degree_lt _, rw [degree_mul_eq, degree_C this, degree_pow_eq, zero_add, degree_eq_nat_degree hq0, ← with_bot.coe_smul, add_monoid.smul_eq_mul, with_bot.coe_lt_coe, nat.cast_id], exact (mul_lt_mul_right (nat.pos_of_ne_zero hqd0)).2 (lt_of_le_of_ne (with_bot.coe_le_coe.1 (by rw ← degree_eq_nat_degree hp0; exact le_sup hbs)) hbp) end (by rw [finsupp.mem_support_iff, apply_eq_coeff, ← leading_coeff, ne.def, leading_coeff_eq_zero, classical.not_not]; simp {contextual := tt}) ... = _ : have coeff (q ^ nat_degree p) (nat_degree p * nat_degree q) = leading_coeff (q ^ nat_degree p), by rw [leading_coeff, nat_degree_pow_eq], by rw [coeff_C_mul, this, leading_coeff_pow] lemma nat_degree_comp : nat_degree (p.comp q) = nat_degree p * nat_degree q := le_antisymm nat_degree_comp_le (if hp0 : p = 0 then by rw [hp0, zero_comp, nat_degree_zero, zero_mul] else if hqd0 : nat_degree q = 0 then have degree q ≤ 0, by rw [← with_bot.coe_zero, ← hqd0]; exact degree_le_nat_degree, by rw [eq_C_of_degree_le_zero this]; simp else le_nat_degree_of_ne_zero $ have hq0 : q ≠ 0, from λ hq0, hqd0 $ by rw [hq0, nat_degree_zero], calc coeff (p.comp q) (nat_degree p * nat_degree q) = leading_coeff p * leading_coeff q ^ nat_degree p : coeff_comp_degree_mul_degree hqd0 ... ≠ 0 : mul_ne_zero (mt leading_coeff_eq_zero.1 hp0) (pow_ne_zero _ (mt leading_coeff_eq_zero.1 hq0))) lemma leading_coeff_comp (hq : nat_degree q ≠ 0) : leading_coeff (p.comp q) = leading_coeff p * leading_coeff q ^ nat_degree p := by rw [← coeff_comp_degree_mul_degree hq, ← nat_degree_comp]; refl lemma degree_eq_zero_of_is_unit (h : is_unit p) : degree p = 0 := let ⟨q, hq⟩ := is_unit_iff_dvd_one.1 h in have hp0 : p ≠ 0, from λ hp0, by simpa [hp0] using hq, have hq0 : q ≠ 0, from λ hp0, by simpa [hp0] using hq, have nat_degree (1 : polynomial α) = nat_degree (p * q), from congr_arg _ hq, by rw [nat_degree_one, nat_degree_mul_eq hp0 hq0, eq_comm, add_eq_zero_iff, ← with_bot.coe_eq_coe, ← degree_eq_nat_degree hp0] at this; exact this.1 @[simp] lemma degree_coe_units (u : units (polynomial α)) : degree (u : polynomial α) = 0 := degree_eq_zero_of_is_unit ⟨u, rfl⟩ @[simp] lemma nat_degree_coe_units (u : units (polynomial α)) : nat_degree (u : polynomial α) = 0 := nat_degree_eq_of_degree_eq_some (degree_coe_units u) lemma coeff_coe_units_zero_ne_zero (u : units (polynomial α)) : coeff (u : polynomial α) 0 ≠ 0 := begin conv in (0) {rw [← nat_degree_coe_units u]}, rw [← leading_coeff, ne.def, leading_coeff_eq_zero], exact units.coe_ne_zero _ end lemma degree_eq_degree_of_associated (h : associated p q) : degree p = degree q := let ⟨u, hu⟩ := h in by simp [hu.symm] lemma degree_eq_one_of_irreducible_of_root (hi : irreducible p) {x : α} (hx : is_root p x) : degree p = 1 := let ⟨g, hg⟩ := dvd_iff_is_root.2 hx in have is_unit (X - C x) ∨ is_unit g, from hi.2 _ _ hg, this.elim (λ h, have h₁ : degree (X - C x) = 1, from degree_X_sub_C x, have h₂ : degree (X - C x) = 0, from degree_eq_zero_of_is_unit h, by rw h₁ at h₂; exact absurd h₂ dec_trivial) (λ hgu, by rw [hg, degree_mul_eq, degree_X_sub_C, degree_eq_zero_of_is_unit hgu, add_zero]) end integral_domain section field variables [discrete_field α] {p q : polynomial α} instance : vector_space α (polynomial α) := finsupp.vector_space _ _ lemma is_unit_iff_degree_eq_zero : is_unit p ↔ degree p = 0 := ⟨degree_eq_zero_of_is_unit, λ h, have degree p ≤ 0, by simp [*, le_refl], have hc : coeff p 0 ≠ 0, from λ hc, by rw [eq_C_of_degree_le_zero this, hc] at h; simpa using h, is_unit_iff_dvd_one.2 ⟨C (coeff p 0)⁻¹, begin conv in p { rw eq_C_of_degree_le_zero this }, rw [← C_mul, _root_.mul_inv_cancel hc, C_1] end⟩⟩ lemma degree_pos_of_ne_zero_of_nonunit (hp0 : p ≠ 0) (hp : ¬is_unit p) : 0 < degree p := lt_of_not_ge (λ h, by rw [eq_C_of_degree_le_zero h] at hp0 hp; exact hp ⟨units.map C (units.mk0 (coeff p 0) (mt C_inj.2 (by simpa using hp0))), rfl⟩) lemma irreducible_of_degree_eq_one (hp1 : degree p = 1) : irreducible p := ⟨mt is_unit_iff_dvd_one.1 (λ ⟨q, hq⟩, absurd (congr_arg degree hq) (λ h, have degree q = 0, by rw [degree_one, degree_mul_eq, hp1, eq_comm, nat.with_bot.add_eq_zero_iff] at h; exact h.2, by simp [degree_mul_eq, this, degree_one, hp1] at h; exact absurd h dec_trivial)), λ q r hpqr, begin have := congr_arg degree hpqr, rw [hp1, degree_mul_eq, eq_comm, nat.with_bot.add_eq_one_iff] at this, rw [is_unit_iff_degree_eq_zero, is_unit_iff_degree_eq_zero]; tautology end⟩ lemma monic_mul_leading_coeff_inv (h : p ≠ 0) : monic (p * C (leading_coeff p)⁻¹) := by rw [monic, leading_coeff_mul, leading_coeff_C, mul_inv_cancel (show leading_coeff p ≠ 0, from mt leading_coeff_eq_zero.1 h)] lemma degree_mul_leading_coeff_inv (p : polynomial α) (h : q ≠ 0) : degree (p * C (leading_coeff q)⁻¹) = degree p := have h₁ : (leading_coeff q)⁻¹ ≠ 0 := inv_ne_zero (mt leading_coeff_eq_zero.1 h), by rw [degree_mul_eq, degree_C h₁, add_zero] def div (p q : polynomial α) := C (leading_coeff q)⁻¹ * (p /ₘ (q * C (leading_coeff q)⁻¹)) def mod (p q : polynomial α) := p %ₘ (q * C (leading_coeff q)⁻¹) private lemma quotient_mul_add_remainder_eq_aux (p q : polynomial α) : q * div p q + mod p q = p := if h : q = 0 then by simp only [h, zero_mul, mod, mod_by_monic_zero, zero_add] else begin conv {to_rhs, rw ← mod_by_monic_add_div p (monic_mul_leading_coeff_inv h)}, rw [div, mod, add_comm, mul_assoc] end private lemma remainder_lt_aux (p : polynomial α) (hq : q ≠ 0) : degree (mod p q) < degree q := by rw ← degree_mul_leading_coeff_inv q hq; exact degree_mod_by_monic_lt p (monic_mul_leading_coeff_inv hq) (mul_ne_zero hq (mt leading_coeff_eq_zero.2 (by rw leading_coeff_C; exact inv_ne_zero (mt leading_coeff_eq_zero.1 hq)))) instance : has_div (polynomial α) := ⟨div⟩ instance : has_mod (polynomial α) := ⟨mod⟩ lemma div_def : p / q = C (leading_coeff q)⁻¹ * (p /ₘ (q * C (leading_coeff q)⁻¹)) := rfl lemma mod_def : p % q = p %ₘ (q * C (leading_coeff q)⁻¹) := rfl lemma mod_by_monic_eq_mod (p : polynomial α) (hq : monic q) : p %ₘ q = p % q := show p %ₘ q = p %ₘ (q * C (leading_coeff q)⁻¹), by simp only [monic.def.1 hq, inv_one, mul_one, C_1] lemma div_by_monic_eq_div (p : polynomial α) (hq : monic q) : p /ₘ q = p / q := show p /ₘ q = C (leading_coeff q)⁻¹ * (p /ₘ (q * C (leading_coeff q)⁻¹)), by simp only [monic.def.1 hq, inv_one, C_1, one_mul, mul_one] lemma mod_X_sub_C_eq_C_eval (p : polynomial α) (a : α) : p % (X - C a) = C (p.eval a) := mod_by_monic_eq_mod p (monic_X_sub_C a) ▸ mod_by_monic_X_sub_C_eq_C_eval _ _ lemma mul_div_eq_iff_is_root : (X - C a) * (p / (X - C a)) = p ↔ is_root p a := div_by_monic_eq_div p (monic_X_sub_C a) ▸ mul_div_by_monic_eq_iff_is_root instance : euclidean_domain (polynomial α) := { quotient := (/), quotient_zero := by simp [div_def], remainder := (%), r := _, r_well_founded := degree_lt_wf, quotient_mul_add_remainder_eq := quotient_mul_add_remainder_eq_aux, remainder_lt := λ p q hq, remainder_lt_aux _ hq, mul_left_not_lt := λ p q hq, not_lt_of_ge (degree_le_mul_left _ hq) } lemma mod_eq_self_iff (hq0 : q ≠ 0) : p % q = p ↔ degree p < degree q := ⟨λ h, h ▸ euclidean_domain.mod_lt _ hq0, λ h, have ¬degree (q * C (leading_coeff q)⁻¹) ≤ degree p := not_le_of_gt $ by rwa degree_mul_leading_coeff_inv q hq0, begin rw [mod_def, mod_by_monic, dif_pos (monic_mul_leading_coeff_inv hq0)], unfold div_mod_by_monic_aux, simp only [this, false_and, if_false] end⟩ lemma div_eq_zero_iff (hq0 : q ≠ 0) : p / q = 0 ↔ degree p < degree q := ⟨λ h, by have := euclidean_domain.div_add_mod p q; rwa [h, mul_zero, zero_add, mod_eq_self_iff hq0] at this, λ h, have hlt : degree p < degree (q * C (leading_coeff q)⁻¹), by rwa degree_mul_leading_coeff_inv q hq0, have hm : monic (q * C (leading_coeff q)⁻¹) := monic_mul_leading_coeff_inv hq0, by rw [div_def, (div_by_monic_eq_zero_iff hm (ne_zero_of_monic hm)).2 hlt, mul_zero]⟩ lemma degree_add_div (hq0 : q ≠ 0) (hpq : degree q ≤ degree p) : degree q + degree (p / q) = degree p := have degree (p % q) < degree (q * (p / q)) := calc degree (p % q) < degree q : euclidean_domain.mod_lt _ hq0 ... ≤ _ : degree_le_mul_left _ (mt (div_eq_zero_iff hq0).1 (not_lt_of_ge hpq)), by conv {to_rhs, rw [← euclidean_domain.div_add_mod p q, add_comm, degree_add_eq_of_degree_lt this, degree_mul_eq]} lemma degree_div_le (p q : polynomial α) : degree (p / q) ≤ degree p := if hq : q = 0 then by simp [hq] else by rw [div_def, mul_comm, degree_mul_leading_coeff_inv _ hq]; exact degree_div_by_monic_le _ _ lemma degree_div_lt (hp : p ≠ 0) (hq : 0 < degree q) : degree (p / q) < degree p := have hq0 : q ≠ 0, from λ hq0, by simpa [hq0] using hq, by rw [div_def, mul_comm, degree_mul_leading_coeff_inv _ hq0]; exact degree_div_by_monic_lt _ (monic_mul_leading_coeff_inv hq0) hp (by rw degree_mul_leading_coeff_inv _ hq0; exact hq) @[simp] lemma degree_map [discrete_field β] (p : polynomial α) (f : α → β) [is_field_hom f] : degree (p.map f) = degree p := degree_map_eq_of_injective _ (is_field_hom.injective f) @[simp] lemma nat_degree_map [discrete_field β] (f : α → β) [is_field_hom f] : nat_degree (p.map f) = nat_degree p := nat_degree_eq_of_degree_eq (degree_map _ f) @[simp] lemma leading_coeff_map [discrete_field β] (f : α → β) [is_field_hom f] : leading_coeff (p.map f) = f (leading_coeff p) := by simp [leading_coeff, coeff_map f] lemma map_div [discrete_field β] (f : α → β) [is_field_hom f] : (p / q).map f = p.map f / q.map f := if hq0 : q = 0 then by simp [hq0] else by rw [div_def, div_def, map_mul, map_div_by_monic f (monic_mul_leading_coeff_inv hq0)]; simp [is_field_hom.map_inv f, leading_coeff, coeff_map f] lemma map_mod [discrete_field β] (f : α → β) [is_field_hom f] : (p % q).map f = p.map f % q.map f := if hq0 : q = 0 then by simp [hq0] else by rw [mod_def, mod_def, leading_coeff_map f, ← is_field_hom.map_inv f, ← map_C f, ← map_mul f, map_mod_by_monic f (monic_mul_leading_coeff_inv hq0)] @[simp] lemma map_eq_zero [discrete_field β] (f : α → β) [is_field_hom f] : p.map f = 0 ↔ p = 0 := by simp [polynomial.ext, is_field_hom.map_eq_zero f, coeff_map] lemma exists_root_of_degree_eq_one (h : degree p = 1) : ∃ x, is_root p x := ⟨-(p.coeff 0 / p.coeff 1), have p.coeff 1 ≠ 0, by rw ← nat_degree_eq_of_degree_eq_some h; exact mt leading_coeff_eq_zero.1 (λ h0, by simpa [h0] using h), by conv in p { rw [eq_X_add_C_of_degree_le_one (show degree p ≤ 1, by rw h; exact le_refl _)] }; simp [is_root, mul_div_cancel' _ this]⟩ lemma coeff_inv_units (u : units (polynomial α)) (n : ℕ) : ((↑u : polynomial α).coeff n)⁻¹ = ((↑u⁻¹ : polynomial α).coeff n) := begin rw [eq_C_of_degree_eq_zero (degree_coe_units u), eq_C_of_degree_eq_zero (degree_coe_units u⁻¹), coeff_C, coeff_C, inv_eq_one_div], split_ifs, { rw [div_eq_iff_mul_eq (coeff_coe_units_zero_ne_zero u), coeff_zero_eq_eval_zero, coeff_zero_eq_eval_zero, ← eval_mul, ← units.coe_mul, inv_mul_self]; simp }, { simp } end instance : normalization_domain (polynomial α) := { norm_unit := λ p, if hp0 : p = 0 then 1 else ⟨C p.leading_coeff⁻¹, C p.leading_coeff, by rw [← C_mul, inv_mul_cancel, C_1]; exact mt leading_coeff_eq_zero.1 hp0, by rw [← C_mul, mul_inv_cancel, C_1]; exact mt leading_coeff_eq_zero.1 hp0,⟩, norm_unit_zero := dif_pos rfl, norm_unit_mul := λ p q hp0 hq0, begin rw [dif_neg hp0, dif_neg hq0, dif_neg (mul_ne_zero hp0 hq0)], apply units.ext, show C (leading_coeff (p * q))⁻¹ = C (leading_coeff p)⁻¹ * C (leading_coeff q)⁻¹, rw [leading_coeff_mul, mul_inv', C_mul, mul_comm] end, norm_unit_coe_units := λ u, have hu : degree ↑u⁻¹ = 0, from degree_eq_zero_of_is_unit ⟨u⁻¹, rfl⟩, begin apply units.ext, rw [dif_neg (units.coe_ne_zero u)], conv_rhs {rw eq_C_of_degree_eq_zero hu}, refine C_inj.2 _, rw [← nat_degree_eq_of_degree_eq_some hu, leading_coeff, coeff_inv_units], simp end, ..polynomial.integral_domain } lemma monic_normalize (hp0 : p ≠ 0) : monic (normalize p) := show leading_coeff (p * ↑(dite _ _ _)) = 1, by rw dif_neg hp0; exact monic_mul_leading_coeff_inv hp0 lemma coe_norm_unit (hp : p ≠ 0) : (norm_unit p : polynomial α) = C p.leading_coeff⁻¹ := show ↑(dite _ _ _) = C p.leading_coeff⁻¹, by rw dif_neg hp; refl end field section derivative variables [comm_semiring α] [decidable_eq α] /-- `derivative p` formal derivative of the polynomial `p` -/ def derivative (p : polynomial α) : polynomial α := p.sum (λn a, C (a * n) * X^(n - 1)) lemma coeff_derivative (p : polynomial α) (n : ℕ) : coeff (derivative p) n = coeff p (n + 1) * (n + 1) := begin rw [derivative], simp only [coeff_X_pow, coeff_sum, coeff_C_mul], rw [finsupp.sum, finset.sum_eq_single (n + 1), apply_eq_coeff], { rw [if_pos (nat.add_sub_cancel _ _).symm, mul_one, nat.cast_add, nat.cast_one] }, { assume b, cases b, { intros, rw [nat.cast_zero, mul_zero, zero_mul] }, { intros _ H, rw [nat.succ_sub_one b, if_neg (mt (congr_arg nat.succ) H.symm), mul_zero] } }, { intro H, rw [not_mem_support_iff.1 H, zero_mul, zero_mul] } end @[simp] lemma derivative_zero : derivative (0 : polynomial α) = 0 := finsupp.sum_zero_index lemma derivative_monomial (a : α) (n : ℕ) : derivative (C a * X ^ n) = C (a * n) * X^(n - 1) := by rw [← single_eq_C_mul_X, ← single_eq_C_mul_X, derivative, sum_single_index, single_eq_C_mul_X]; simp only [zero_mul, C_0]; refl @[simp] lemma derivative_C {a : α} : derivative (C a) = 0 := suffices derivative (C a * X^0) = C (a * 0:α) * X ^ 0, by simpa only [mul_one, zero_mul, C_0, mul_zero, pow_zero], derivative_monomial a 0 @[simp] lemma derivative_X : derivative (X : polynomial α) = 1 := suffices derivative (C (1:α) * X^1) = C (1 * (1:ℕ)) * X ^ 0, by simpa only [mul_one, one_mul, C_1, pow_one, nat.cast_one, pow_zero], derivative_monomial 1 1 @[simp] lemma derivative_one : derivative (1 : polynomial α) = 0 := derivative_C @[simp] lemma derivative_add {f g : polynomial α} : derivative (f + g) = derivative f + derivative g := by refine finsupp.sum_add_index _ _; intros; simp only [add_mul, zero_mul, C_0, C_add, C_mul] instance : is_add_monoid_hom (derivative : polynomial α → polynomial α) := { map_add := λ _ _, derivative_add, map_zero := derivative_zero } @[simp] lemma derivative_sum {s : finset β} {f : β → polynomial α} : derivative (s.sum f) = s.sum (λb, derivative (f b)) := (finset.sum_hom derivative).symm @[simp] lemma derivative_mul {f g : polynomial α} : derivative (f * g) = derivative f * g + f * derivative g := calc derivative (f * g) = f.sum (λn a, g.sum (λm b, C ((a * b) * (n + m : ℕ)) * X^((n + m) - 1))) : begin transitivity, exact derivative_sum, transitivity, { apply finset.sum_congr rfl, assume x hx, exact derivative_sum }, apply finset.sum_congr rfl, assume n hn, apply finset.sum_congr rfl, assume m hm, transitivity, { apply congr_arg, exact single_eq_C_mul_X }, exact derivative_monomial _ _ end ... = f.sum (λn a, g.sum (λm b, (C (a * n) * X^(n - 1)) * (C b * X^m) + (C a * X^n) * (C (b * m) * X^(m - 1)))) : sum_congr rfl $ assume n hn, sum_congr rfl $ assume m hm, by simp only [nat.cast_add, mul_add, add_mul, C_add, C_mul]; cases n; simp only [nat.succ_sub_succ, pow_zero]; cases m; simp only [nat.cast_zero, C_0, nat.succ_sub_succ, zero_mul, mul_zero, nat.sub_zero, pow_zero, pow_add, one_mul, pow_succ, mul_comm, mul_left_comm] ... = derivative f * g + f * derivative g : begin conv { to_rhs, congr, { rw [← sum_C_mul_X_eq g] }, { rw [← sum_C_mul_X_eq f] } }, unfold derivative finsupp.sum, simp only [sum_add_distrib, finset.mul_sum, finset.sum_mul] end lemma derivative_eval (p : polynomial α) (x : α) : p.derivative.eval x = p.sum (λ n a, (a * n)*x^(n-1)) := by simp [derivative, eval_sum, eval_pow] end derivative section domain variables [integral_domain α] [decidable_eq α] lemma mem_support_derivative [char_zero α] (p : polynomial α) (n : ℕ) : n ∈ (derivative p).support ↔ n + 1 ∈ p.support := suffices (¬(coeff p (n + 1) = 0 ∨ ((n + 1:ℕ) : α) = 0)) ↔ coeff p (n + 1) ≠ 0, by simpa only [coeff_derivative, apply_eq_coeff, mem_support_iff, ne.def, mul_eq_zero], by rw [nat.cast_eq_zero]; simp only [nat.succ_ne_zero, or_false] @[simp] lemma degree_derivative_eq [char_zero α] (p : polynomial α) (hp : 0 < nat_degree p) : degree (derivative p) = (nat_degree p - 1 : ℕ) := le_antisymm (le_trans (degree_sum_le _ _) $ sup_le $ assume n hn, have n ≤ nat_degree p, begin rw [← with_bot.coe_le_coe, ← degree_eq_nat_degree], { refine le_degree_of_ne_zero _, simpa only [mem_support_iff] using hn }, { assume h, simpa only [h, support_zero] using hn } end, le_trans (degree_monomial_le _ _) $ with_bot.coe_le_coe.2 $ nat.sub_le_sub_right this _) begin refine le_sup _, rw [mem_support_derivative, nat.sub_add_cancel, mem_support_iff], { show ¬ leading_coeff p = 0, rw [leading_coeff_eq_zero], assume h, rw [h, nat_degree_zero] at hp, exact lt_irrefl 0 (lt_of_le_of_lt (zero_le _) hp), }, exact hp end end domain section identities /- @TODO: pow_add_expansion and pow_sub_pow_factor are not specific to polynomials. These belong somewhere else. But not in group_power because they depend on tactic.ring Maybe use data.nat.choose to prove it. -/ def pow_add_expansion {α : Type*} [comm_semiring α] (x y : α) : ∀ (n : ℕ), {k // (x + y)^n = x^n + n*x^(n-1)*y + k * y^2} | 0 := ⟨0, by simp⟩ | 1 := ⟨0, by simp⟩ | (n+2) := begin cases pow_add_expansion (n+1) with z hz, rw [_root_.pow_succ, hz], existsi (x*z + (n+1)*x^n+z*y), simp [_root_.pow_succ], ring end variables [comm_ring α] [decidable_eq α] private def poly_binom_aux1 (x y : α) (e : ℕ) (a : α) : {k : α // a * (x + y)^e = a * (x^e + e*x^(e-1)*y + k*y^2)} := begin existsi (pow_add_expansion x y e).val, congr, apply (pow_add_expansion _ _ _).property end private lemma poly_binom_aux2 (f : polynomial α) (x y : α) : f.eval (x + y) = f.sum (λ e a, a * (x^e + e*x^(e-1)*y + (poly_binom_aux1 x y e a).val*y^2)) := begin unfold eval eval₂, congr, ext, apply (poly_binom_aux1 x y _ _).property end private lemma poly_binom_aux3 (f : polynomial α) (x y : α) : f.eval (x + y) = f.sum (λ e a, a * x^e) + f.sum (λ e a, (a * e * x^(e-1)) * y) + f.sum (λ e a, (a *(poly_binom_aux1 x y e a).val)*y^2) := by rw poly_binom_aux2; simp [left_distrib, finsupp.sum_add, mul_assoc] def binom_expansion (f : polynomial α) (x y : α) : {k : α // f.eval (x + y) = f.eval x + (f.derivative.eval x) * y + k * y^2} := begin existsi f.sum (λ e a, a *((poly_binom_aux1 x y e a).val)), rw poly_binom_aux3, congr, { rw derivative_eval, symmetry, apply finsupp.sum_mul }, { symmetry, apply finsupp.sum_mul } end def pow_sub_pow_factor (x y : α) : Π {i : ℕ},{z : α // x^i - y^i = z*(x - y)} | 0 := ⟨0, by simp⟩ | 1 := ⟨1, by simp⟩ | (k+2) := begin cases pow_sub_pow_factor with z hz, existsi z*x + y^(k+1), rw [_root_.pow_succ x, _root_.pow_succ y, ←sub_add_sub_cancel (x*x^(k+1)) (x*y^(k+1)), ←mul_sub x, hz], simp only [_root_.pow_succ], ring end def eval_sub_factor (f : polynomial α) (x y : α) : {z : α // f.eval x - f.eval y = z*(x - y)} := begin existsi f.sum (λ a b, b * (pow_sub_pow_factor x y).val), unfold eval eval₂, rw [←finsupp.sum_sub], have : finsupp.sum f (λ (a : ℕ) (b : α), b * (pow_sub_pow_factor x y).val) * (x - y) = finsupp.sum f (λ (a : ℕ) (b : α), b * (pow_sub_pow_factor x y).val * (x - y)), { apply finsupp.sum_mul }, rw this, congr, ext e a, rw [mul_assoc, ←(pow_sub_pow_factor x y).property], simp [left_distrib] end end identities end polynomial
d8e9fbcba3d0a08c917aaaf02459323fb0d16e96
f22a91842f18b5e855075b9becd55d2233756c6a
/src/ch03_01.lean
0489bfb1a0f6fc9a6d1fa32801feb0a071e617a7
[]
no_license
kckennylau/tao-analysis-one
48cef1ee896d6703fcaf47ce5548e44f88901a0e
2bd2d14c3c722bb36526c5a4e6b87618b2c081b1
refs/heads/master
1,621,002,517,963
1,514,151,057,000
1,514,151,057,000
115,971,702
0
0
null
1,514,864,495,000
1,514,864,495,000
null
UTF-8
Lean
false
false
10,839
lean
-------------------------------------------------------------------------------- -- Chapter 3 - Set theory -- Section 1 - Fundamentals -- Analysis 1, Third Edition, Tao -------------------------------------------------------------------------------- import data.set.basic open set variable {α : Type} -- Exercise 3.1.1. Show that the definition of set equality is reflexive, -- symmetric, and transitive. example (A : set α) : ∀ x, x ∈ A ↔ x ∈ A := λ x, iff_of_eq rfl example (A B : set α) : ∀ x, (x ∈ A ↔ x ∈ B) → (x ∈ B ↔ x ∈ A) := λ x ⟨h₁, h₂⟩, ⟨h₂, h₁⟩ example (A B C : set α) : ∀ x, (x ∈ A ↔ x ∈ B) → (x ∈ B ↔ x ∈ C) → (x ∈ A ↔ x ∈ C) := λ x ⟨h₁, h₂⟩ ⟨h₃, h₄⟩, ⟨λ h₅, h₃ $ h₁ h₅, λ h₅, h₂ $ h₄ h₅⟩ -- Exercise 3.1.2. Skipped. Type inequality is trivial in type theory. -- Exercise 3.1.3. Prove the remaining claims in Lemma 3.1.13. lemma eq_or_eq_of_mem_pair {a b y : α} : y ∈ ({a, b}:set α) → y = a ∨ y = b := by finish -- Tao axiom 3.3 lemma mem_pair_of_eq_or_eq {a b y : α} : y = a ∨ y = b → y ∈ ({a, b}:set α) := by finish -- Tao axiom 3.3 example (a b : α) : ({a, b} : set α) = ({a} ∪ {b}) := ext (λ x, iff.intro (λ h₁, or.elim (eq_or_eq_of_mem_pair h₁) (λ h₂, mem_union_left {b} $ mem_singleton_of_eq h₂) (λ h₂, mem_union_right {a} $ mem_singleton_of_eq h₂)) (λ h₁, or.elim (mem_or_mem_of_mem_union h₁) (λ h₂, mem_pair_of_eq_or_eq $ or.inl $ eq_of_mem_singleton h₂) (λ h₂, mem_pair_of_eq_or_eq $ or.inr $ eq_of_mem_singleton h₂))) example (A B C : set α) : A ∪ B = B ∪ A := ext (λ x, or.comm) example (A : set α) : A ∪ A = A ∪ ∅ ∧ A ∪ ∅ = ∅ ∪ A ∧ ∅ ∪ A = A := and.intro (ext (λ x, iff.intro (λ h₁, mem_union_left ∅ $ union_self A ▸ h₁) (λ h₁, or.elim (mem_or_mem_of_mem_union h₁) (λ h₂, or.inl h₂) (λ h₂, absurd h₂ $ not_mem_empty x)))) (and.intro (union_comm _ _) (ext (λ x, false_or _))) -- Exercise 3.1.4. Prove the remaining claims in Proposition 3.1.18. example (A B C : set α) : A ⊆ B → B ⊆ A → A = B := λ (h₁ : ∀ x, x ∈ A → x ∈ B) (h₂ : ∀ x, x ∈ B → x ∈ A), ext (λ x, {mp := h₁ x, mpr := h₂ x}) example (A B C : set α) : A ⊂ B → B ⊂ C → A ⊂ C := λ ⟨h₁, h₂⟩ ⟨h₃, h₄⟩, and.intro (subset.trans h₁ h₃) (λ h₅, h₂ $ subset.antisymm h₁ $ h₅.symm ▸ h₃) -- Exercise 3.1.5. Let A, B be sets. Show that the three statements -- A ⊆ B, A ∪ B = B, and A ∩ B = A are logically equivalent. example (A B : set α) : (A ⊆ B ↔ A ∪ B = B) ∧ (A ∪ B = B ↔ A ∩ B = A) := and.intro (iff.intro (λ h₁ : ∀ x, x ∈ A → x ∈ B, ext $ λ x, iff.intro (λ h₂, or.elim h₂ (λ h₃, h₁ x h₃) id) (λ h₂, or.inr h₂)) (λ h₁ x h₂, let ⟨h₃, h₄⟩ := set_eq_def (A ∪ B) B, h₅ := h₃ h₁ x in h₅.mp $ or.inl h₂)) (iff.intro (λ h₁, ext (λ x, iff.intro (λ ⟨h₂, _⟩, h₂) (λ h₂, and.intro (h₂) (let ⟨h₃, h₄⟩ := set_eq_def (A ∪ B) B, h₅ := h₃ h₁ x in h₅.mp $ or.inl h₂)))) (λ h₁, ext (λ x, iff.intro (λ h₂, or.elim h₂ (λ h₃, let ⟨h₄, h₅⟩ := set_eq_def (A ∩ B) A, ⟨h₆, h₇⟩ := h₄ h₁ x, ⟨h₈, h₉⟩ := h₇ h₃ in h₉) (id)) (λ h₂, or.inr h₂)))) -- Exercise 3.1.6. Prove Proposition 3.1.28. section variables A B C X : set α variables (AsubX : A ⊆ X) example : A ∪ ∅ = A := ext $ λ x, iff.intro (λ h₁, or.elim h₁ id (λ h₂, absurd h₂ (not_mem_empty x))) (λ h₁, or.inl h₁) example : A ∩ ∅ = ∅ := ext $ λ x, iff.intro (λ ⟨h₁, h₂⟩, h₂) (λ h₁, and.intro (absurd h₁ (not_mem_empty x)) h₁) example : A ∪ X = X := ext $ λ x, iff.intro (λ h₁, or.elim h₁ (λ h₂, AsubX h₂) id) (λ h₁, or.inr h₁) example : A ∩ X = A := ext $ λ x, iff.intro (λ ⟨h₁, h₂⟩, h₁) (λ h₁, and.intro h₁ (AsubX h₁)) example : A ∩ A = A := ext $ λ x, iff.intro (λ ⟨h₁, h₂⟩, h₁) (λ h₁, and.intro h₁ h₁) example : A ∪ A = A := ext $ λ x, iff.intro (λ h₁, or.elim h₁ id id) (λ h₁, or.inl h₁) example : A ∪ B = B ∪ A := ext $ λ x, iff.intro (λ h₁, or.elim h₁ (λ h₂, or.inr h₂) (λ h₂, or.inl h₂)) (λ h₁, or.elim h₁ (λ h₂, or.inr h₂) (λ h₂, or.inl h₂)) example : A ∩ B = B ∩ A := ext $ λ x, iff.intro (λ ⟨h₁, h₂⟩, and.intro h₂ h₁) (λ ⟨h₁, h₂⟩, and.intro h₂ h₁) example : (A ∪ B) ∪ C = A ∪ (B ∪ C) := ext $ λ x, iff.intro (λ h₁, or.elim h₁ (λ h₂, or.elim h₂ (λ h₃, or.inl h₃) (λ h₃, or.inr $ or.inl h₃)) (λ h₃, or.inr $ or.inr h₃)) (λ h₁, or.elim h₁ (λ h₂, or.inl $ or.inl h₂) (λ h₂, or.elim h₂ (λ h₃, or.inl $ or.inr h₃) (λ h₃, or.inr h₃))) example : (A ∩ B) ∩ C = A ∩ (B ∩ C) := ext $ λ x, iff.intro (λ ⟨⟨h₁, h₂⟩, h₃⟩, ⟨h₁, h₂, h₃⟩) (λ ⟨h₁, ⟨h₂, h₃⟩⟩, ⟨⟨h₁, h₂⟩, h₃⟩) example : A ∩ (B ∪ C) = (A ∩ B) ∪ (A ∩ C) := ext $ λ x, iff.intro (λ ⟨h₁, h₂⟩, or.elim h₂ (λ h₃, or.inl ⟨h₁, h₃⟩) (λ h₃, or.inr ⟨h₁, h₃⟩)) (λ h₁, or.elim h₁ (λ ⟨h₂, h₃⟩, ⟨h₂, or.inl h₃⟩) (λ ⟨h₂, h₃⟩, ⟨h₂, or.inr h₃⟩)) example : A ∪ (B ∩ C) = (A ∪ B) ∩ (A ∪ C) := ext $ λ x, iff.intro (λ h₁, or.elim h₁ (λ h₂, ⟨or.inl h₂, or.inl h₂⟩) (λ ⟨h₂, h₃⟩, ⟨or.inr h₂, or.inr h₃⟩)) (λ ⟨h₁, h₂⟩, or.elim h₁ (λ h₃, or.inl h₃) (λ h₃, or.elim h₂ (λ h₄, or.inl h₄) (λ h₄, or.inr ⟨h₃, h₄⟩))) example : A ∪ (X \ A) = X := ext $ λ x, iff.intro (λ h₁, or.elim h₁ (λ h₂, AsubX h₂) (λ ⟨h₂, h₃⟩, h₂)) (λ h₁, or.elim (classical.em (x ∈ A)) (λ h₂, or.inl h₂) (λ h₂, or.inr ⟨h₁, h₂⟩)) example : A ∩ (X \ A) = ∅ := ext $ λ x, iff.intro (λ ⟨h₁, ⟨h₂, h₃⟩⟩, absurd h₁ h₃) (λ h₁, absurd h₁ (not_mem_empty x)) example : X \ (A ∪ B) = (X \ A) ∩ (X \ B) := ext $ λ x, iff.intro (λ ⟨h₁, h₂⟩, ⟨⟨h₁, λ h₃, h₂ $ or.inl h₃⟩, ⟨h₁, λ h₃, h₂ $ or.inr h₃⟩⟩) (λ ⟨⟨h₁, h₂⟩, ⟨h₃, h₄⟩⟩, ⟨h₁, λ h₅, or.elim h₅ (λ h₆, absurd h₆ h₂) (λ h₆, absurd h₆ h₄)⟩) example : X \ (A ∩ B) = (X \ A) ∪ (X \ B) := ext $ λ x, iff.intro (λ ⟨h₁, (h₂ : x ∈ A ∧ x ∈ B → false)⟩, or.elim (classical.em (x ∈ A)) (or.elim (classical.em (x ∈ B)) (λ h₃ h₄, or.inl ⟨h₁, λ h₅, h₂ ⟨h₄, h₃⟩⟩) (λ h₃ h₄, or.inr ⟨h₁, h₃⟩)) (λ h₃, or.inl ⟨h₁, h₃⟩)) (λ h₁, or.elim h₁ (λ ⟨h₂, h₃⟩, ⟨h₂, λ ⟨h₄, h₅⟩, h₃ h₄⟩) (λ ⟨h₂, h₃⟩, ⟨h₂, λ ⟨h₄, h₅⟩, h₃ h₅⟩)) end -- Exercise 3.1.7. Let A, B, and C be sets. Show that A ∩ B ⊆ A and A ∩ B ⊆ B. -- Furthermore, show that C ⊆ A and C ⊆ B if and only if C ⊆ A ∩ B. In a similar -- spirit, show that A ⊆ A ∪ B and B ⊆ A ∪ B, and furthermore that A ⊆ C and -- B ⊆ C if and only if A ∪ B ⊆ C. section variables (A B C : set α) example : A ∩ B ⊆ A := λ x (h₁ : x ∈ A ∧ x ∈ B), h₁.left example : A ∩ B ⊆ B := λ x (h₁ : x ∈ A ∧ x ∈ B), h₁.right example : C ⊆ A ∧ C ⊆ B ↔ C ⊆ (A ∩ B) := iff.intro (λ ⟨h₁, h₂⟩ x h₃, (mem_inter_iff x A B).mpr $ and.intro (subset.trans h₁ (subset.refl A) h₃) (subset.trans h₂ (subset.refl B) h₃)) (λ h₁, and.intro (by simp at h₁; exact h₁.left) (by simp at h₁; exact h₁.right)) example : A ⊆ A ∪ B := λ x h, or.inl h example : B ⊆ A ∪ B := λ x h, or.inr h example : A ⊆ C ∧ B ⊆ C ↔ A ∪ B ⊆ C := iff.intro (λ ⟨h1, h2⟩, λ x h3, or.elim h3 (λ h4, h1 h4) (λ h4, h2 h4)) (λ h1 : ∀ {x}, x ∈ (A ∪ B) → x ∈ C, and.intro (λ x h2, h1 (or.inl h2)) (λ x h2, h1 (or.inr h2))) end -- Exercise 3.1.8. Let A and B bet sets. Prove the absorption laws -- A ∩ (A ∪ B) = A and A ∪ (A ∩ B) = A. section variables {A B : set α} example : A ∩ (A ∪ B) = A := ext $ λ x, iff.intro (λ ⟨h₁, h₂⟩, h₁) (λ h₁, and.intro h₁ (or.inl h₁)) example : A ∪ (A ∩ B) = A := ext $ λ x, iff.intro (λ h₁, let h₂ := mem_or_mem_of_mem_union h₁ in or.elim h₂ id (λ ⟨h₂, h₃⟩, h₂)) (λ h₁, mem_union_left _ h₁) -- Exercise 3.1.9. Let A, B, and X be sets such that A ∪ B = X and A ∩ B = ∅. -- Show that A = X ∖ B and B = X ∖ A. example (A B X : set α) (h₁ : A ∪ B = X) (h₂ : A ∩ B = ∅) : A = X \ B := ext $ λ x, iff.intro (λ h₃, mem_diff (let h₄ := iff.mp (((set_eq_def (A ∪ B) X).mp $ h₁) x) in h₄ $ or.inl h₃) (λ h₄, let h₅ := (iff.mp (set_eq_def (A ∩ B) ∅) h₂ x).mp in h₅ $ and.intro h₃ h₄)) (λ ⟨h₃, h₄⟩, let h₅ := ((set_eq_def (A ∪ B) X).mp h₁ x).mpr h₃ in or.elim h₅ id (λ h₆, absurd h₆ h₄)) example (A B X : set α) (h₁ : A ∪ B = X) (h₃ : A ∩ B = ∅) : B = X \ A := ext $ λ x, have h₄ : x ∈ A ∨ x ∈ B ↔ x ∈ X, by finish, have h₅ : x ∈ A ∧ x ∈ B ↔ x ∈ (∅ : set α), from iff.mp ((set_eq_def (A ∩ B) ∅)) h₃ x, iff.intro (λ h₆, ⟨h₄.mp $ or.inr h₆, λ h₇, h₅.mp $ ⟨h₇, h₆⟩⟩) (λ ⟨h₅, h₆⟩, or.elim (h₄.mpr h₅) (λ h₇, absurd h₇ h₆) id) -- Exercise 3.1.10. Let A and B be sets. Show that the three sets A \ B, A ∩ B -- and B \ A are disjoint, and that their union is A ∪ B. example (A B : set α) : (A \ B) ∩ (A ∩ B) = ∅ := ext $ λ x, iff.intro (λ ⟨⟨h₁, h₂⟩, ⟨h₃, h₄⟩⟩, h₂ h₄) (λ h₁, absurd h₁ (not_mem_empty x)) example (A B : set α) : (A ∩ B) ∩ (B \ A) = ∅ := ext $ λ x, iff.intro (λ ⟨⟨h₁, h₂⟩, ⟨h₃, h₄⟩⟩, h₄ h₁) (λ h₁, absurd h₁ (not_mem_empty x)) example (A B : set α) : (A \ B) ∩ (B \ A) = ∅ := ext $ λ x, iff.intro (λ ⟨⟨h₁, h₂⟩, ⟨h₃, h₄⟩⟩, h₂ h₃) (λ h₁, absurd h₁ (not_mem_empty x)) -- Exercise 3.1.11. Show that the axiom of replacement implies the axiom of -- specification. Skipped since we don't have set-theory axioms in type theory. end
feb5df35579807feaaac5a9b1ed83e6cfa32a4ed
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/matchNoPostponing.lean
af7f62e1dc7a0b3580cb2e5ac04a2e50ae109953
[ "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
623
lean
/- In the following example, type of `x` and `y` could be any type `α` s.t. `[OfNat α]`. It relies on `SyntheticMVarKind.withDefault` to set `α := Nat`. Moreover, we must commit to `α := Nat` before we try to build de `matcher` since `mkMatcher` assumes `matchType` does not contain metavariables. We accomplish that by invoking `synthesizeSyntheticMVarsNoPostponing` at `elabMatch`. -/ def foo : IO Unit := do let (x, y) ← pure (0, 0); IO.println x private def f (x : Nat) : Option Nat := none private def g (xs : List (Nat × Nat)) : IO Unit := xs.forM fun x => match f x.fst with | _ => pure ()
b436db9c14c6002b98fec508f72818057a2bcb2b
1abd1ed12aa68b375cdef28959f39531c6e95b84
/src/data/set/equitable.lean
665a804098b181b3040a585807103118504b57a8
[ "Apache-2.0" ]
permissive
jumpy4/mathlib
d3829e75173012833e9f15ac16e481e17596de0f
af36f1a35f279f0e5b3c2a77647c6bf2cfd51a13
refs/heads/master
1,693,508,842,818
1,636,203,271,000
1,636,203,271,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,382
lean
/- Copyright (c) 2021 Yaël Dillies, Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies, Bhavik Mehta -/ import algebra.big_operators.order import data.nat.basic /-! # Equitable functions This file defines equitable functions. A function `f` is equitable on a set `s` if `f a₁ ≤ f a₂ + 1` for all `a₁, a₂ ∈ s`. This is mostly useful when the domain of `f` is `ℕ` or `ℤ` (or more generally a successor order). ## TODO `ℕ` can be replaced by any `succ_order` + `conditionally_complete_monoid`, but we don't have either of those yet. -/ open_locale big_operators variables {α β : Type*} namespace set /-- A set is equitable if no element value is more than one bigger than another. -/ def equitable_on [has_le β] [has_add β] [has_one β] (s : set α) (f : α → β) : Prop := ∀ ⦃a₁ a₂⦄, a₁ ∈ s → a₂ ∈ s → f a₁ ≤ f a₂ + 1 @[simp] lemma equitable_on_empty [has_le β] [has_add β] [has_one β] (f : α → β) : equitable_on ∅ f := λ a _ ha, (set.not_mem_empty _ ha).elim lemma equitable_on_iff_exists_le_le_add_one {s : set α} {f : α → ℕ} : s.equitable_on f ↔ ∃ b, ∀ a ∈ s, b ≤ f a ∧ f a ≤ b + 1 := begin refine ⟨_, λ ⟨b, hb⟩ x y hx hy, (hb x hx).2.trans (add_le_add_right (hb y hy).1 _)⟩, obtain rfl | ⟨x, hx⟩ := s.eq_empty_or_nonempty, { simp }, intros hs, by_cases h : ∀ y ∈ s, f x ≤ f y, { exact ⟨f x, λ y hy, ⟨h _ hy, hs hy hx⟩⟩ }, push_neg at h, obtain ⟨w, hw, hwx⟩ := h, refine ⟨f w, λ y hy, ⟨nat.le_of_succ_le_succ _, hs hy hw⟩⟩, rw (nat.succ_le_of_lt hwx).antisymm (hs hx hw), exact hs hx hy, end lemma equitable_on_iff_exists_image_subset_Icc {s : set α} {f : α → ℕ} : s.equitable_on f ↔ ∃ b, f '' s ⊆ Icc b (b + 1) := by simpa only [image_subset_iff] using equitable_on_iff_exists_le_le_add_one lemma equitable_on_iff_exists_eq_eq_add_one {s : set α} {f : α → ℕ} : s.equitable_on f ↔ ∃ b, ∀ a ∈ s, f a = b ∨ f a = b + 1 := by simp_rw [equitable_on_iff_exists_le_le_add_one, nat.le_and_le_add_one_iff] end set open set namespace finset lemma equitable_on_iff_le_le_add_one {s : finset α} {f : α → ℕ} : equitable_on (s : set α) f ↔ ∀ a ∈ s, (∑ i in s, f i) / s.card ≤ f a ∧ f a ≤ (∑ i in s, f i) / s.card + 1 := begin rw set.equitable_on_iff_exists_le_le_add_one, refine ⟨_, λ h, ⟨_, h⟩ ⟩, rintro ⟨b, hb⟩, by_cases h : ∀ a ∈ s, f a = b + 1, { intros a ha, rw [h _ ha, sum_const_nat h, nat.mul_div_cancel_left _ (card_pos.2 ⟨a, ha⟩)], exact ⟨le_rfl, nat.le_succ _⟩ }, push_neg at h, obtain ⟨x, hx₁, hx₂⟩ := h, suffices h : b = (∑ i in s, f i) / s.card, { simp_rw ←h, apply hb }, symmetry, refine nat.div_eq_of_lt_le (le_trans (by simp [mul_comm]) (sum_le_sum (λ a ha, (hb a ha).1))) ((sum_lt_sum (λ a ha, (hb a ha).2) ⟨_, hx₁, (hb _ hx₁).2.lt_of_ne hx₂⟩).trans_le _), rw [mul_comm, sum_const_nat], exact λ _ _, rfl, end lemma equitable_on_iff {s : finset α} {f : α → ℕ} : equitable_on (s : set α) f ↔ ∀ a ∈ s, f a = (∑ i in s, f i) / s.card ∨ f a = (∑ i in s, f i) / s.card + 1 := by simp_rw [equitable_on_iff_le_le_add_one, nat.le_and_le_add_one_iff] end finset
17ad28ea070bf6d7439b7c5882288231828f8549
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/doc/monads/except.lean
75da8cf24cfbbc8766eb5b450486f77570903a42
[ "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
7,038
lean
/-! # Except The `Except` Monad adds exception handling behavior to your functions. Exception handling in other languages like Python or Java is done with a built in `throw` method that you can use anywhere. In `Lean` you can only `throw` an exception when your function is executing in the context of an `Except` monad. -/ def divide (x y: Float): Except String Float := if y == 0 then throw "can't divide by zero" else pure (x / y) #eval divide 5 2 -- Except.ok 2.500000 #eval divide 5 0 -- Except.error "can't divide by zero" /-! Just as the `read` operation was available from the `ReaderM` monad and the `get` and `set` operations came with the `StateM` monad, here you can see a `throw` operation is provided by the `Except` monad. So in Lean, `throw` is not available everywhere like it is in most imperative programming languages. You have to declare your function can throw by changing the type signature to `Except String Float`. This creates a function that might return an error of type `String` or it might return a value of type `Float` in the non-error case. Once your function is monadic you also need to use the `pure` constructor of the `Except` monad to convert the pure non-monadic value `x / y` into the required `Except` object. See [Applicatives](applicatives.lean.md) for details on `pure`. Now this return typing would get tedious if you had to include it everywhere that you call this function, however, Lean type inference can clean this up. For example, you can define a test function can calls the `divide` function and you don't need to say anything here about the fact that it might throw an error, because that is inferred: -/ def test := divide 5 0 #check test -- Except String Float /-! Notice the Lean compiler infers the required `Except String Float` type information for you. And now you can run this test and get the expected exception: -/ #eval test -- Except.error "can't divide by zero" /-! ## Chaining Now as before you can build a chain of monadic actions that can be composed together using `bind (>>=)`: -/ def square (x : Float) : Except String Float := if x >= 100 then throw "it's absolutely huge" else pure (x * x) #eval divide 6 2 >>= square -- Except.ok 9.000000 #eval divide 6 0 >>= square -- Except.error "can't divide by zero" #eval divide 100 1 >>= square -- Except.error "it's absolutely huge" def chainUsingDoNotation := do let r ← divide 6 0 square r #eval chainUsingDoNotation -- Except.error "can't divide by zero" /-! Notice in the second `divide 6 0` the exception from that division was nicely propagated along to the final result and the square function was ignored in that case. You can see why the `square` function was ignored if you look at the implementation of `Except.bind`: -/ def bind (ma : Except ε α) (f : α → Except ε β) : Except ε β := match ma with | Except.error err => Except.error err | Except.ok v => f v /-! Specifically notice that it only calls the next function `f v` in the `Except.ok`, and in the error case it simply passes the same error along. Remember also that you can chain the actions with implicit binding by using the `do` notation as you see in the `chainUsingDoNotation` function above. ## Try/Catch Now with all good exception handling you also want to be able to catch exceptions so your program can continue on or do some error recovery task, which you can do like this: -/ def testCatch := try let r ← divide 8 0 -- 'r' is type Float pure (toString r) catch e => pure s!"Caught exception: {e}" #check testCatch -- Except String String /-! Note that the type inferred by Lean for this function is `Except String String` so unlike the `test` function earlier, this time Lean type inference has figured out that since the pure value `(toString r)` is of type `String`, then this function must have type `Except String String` so you don't have to explicitly state this. You can always hover your mouse over `testCatch` or use `#check testCatch` to query Lean interactively to figure out what type inference has decided. Lean type inference makes life easy for you, so it's good to use it when you can. You can now see the try/catch working in this eval: -/ #eval testCatch -- Except.ok "Caught exception: can't divide by zero" /-! Notice the `Caught exception:` wrapped message is returned, and that it is returned as an `Except.ok` value, meaning `testCatch` eliminated the error result as expected. So you've interleaved a new concept into your functions (exception handling) and the compiler is still able to type check everything just as well as it does for pure functions and it's been able to infer some things along the way to make it even easier to manage. Now you might be wondering why `testCatch` doesn't infer the return type `String`? Lean does this as a convenience since you could have a rethrow in or after the catch block. If you really want to stop the `Except` type from bubbling up you can unwrap it like this: -/ def testUnwrap : String := Id.run do let r ← divide 8 0 -- r is type Except String Float match r with | .ok a => toString a -- 'a' is type Float | .error e => s!"Caught exception: {e}" #check testUnwrap -- String #eval testUnwrap -- "Caught exception: can't divide by zero" /-! The `Id.run` function is a helper function that executes the `do` block and returns the result where `Id` is the _identity monad_. So `Id.run do` is a pattern you can use to execute monads in a function that is not itself monadic. This works for all monads except `IO` which, as stated earlier, you cannot invent out of thin air, you must use the `IO` monad given to your `main` function. ## Monadic functions You can also write functions that are designed to operate in the context of a monad. These functions typically end in upper case M like `List.forM` used below: -/ def validateList (x : List Nat) (max : Nat): Except String Unit := do x.forM fun a => do if a > max then throw "illegal value found in list" #eval validateList [1, 2, 5, 3, 8] 10 -- Except.ok () #eval validateList [1, 2, 5, 3, 8] 5 -- Except.error "illegal value found in list" /-! Notice here that the `List.forM` function passes the monadic context through to the inner function so it can use the `throw` function from the `Except` monad. The `List.forM` function is defined like this where `[Monad m]` means "in the context of a monad `m`": -/ def forM [Monad m] (as : List α) (f : α → m PUnit) : m PUnit := match as with | [] => pure ⟨⟩ | a :: as => do f a; List.forM as f /-! ## Summary Now that you know all these different monad constructs, you might be wondering how you can combine them. What if there was some part of your state that you wanted to be able to modify (using the State monad), but you also needed exception handling. How can you get multiple monadic capabilities in the same function. To learn the answer, head to [Monad Transformers](transformers.lean.md). -/
49763182a7b097c3bd84312a5d39077824782439
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/module/hom.lean
81b6c29f0738e5eae07447365a221d69bc7d6d90
[ "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,926
lean
/- Copyright (c) 2021 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import algebra.module.pi /-! # Bundled hom instances for module and multiplicative actions > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines instances for module, mul_action and related structures on bundled `_hom` types. These are analogous to the instances in `algebra.module.pi`, but for bundled instead of unbundled functions. -/ variables {R S A B : Type*} namespace add_monoid_hom section variables [monoid R] [monoid S] [add_monoid A] [add_comm_monoid B] variables [distrib_mul_action R B] [distrib_mul_action S B] instance : distrib_mul_action R (A →+ B) := { smul := λ r f, { to_fun := r • f, map_zero' := by simp, map_add' := λ x y, by simp [smul_add] }, one_smul := λ f, by simp, mul_smul := λ r s f, by simp [mul_smul], smul_add := λ r f g, ext $ λ x, by simp [smul_add], smul_zero := λ r, ext $ λ x, by simp [smul_zero] } @[simp] lemma coe_smul (r : R) (f : A →+ B) : ⇑(r • f) = r • f := rfl lemma smul_apply (r : R) (f : A →+ B) (x : A) : (r • f) x = r • f x := rfl instance [smul_comm_class R S B] : smul_comm_class R S (A →+ B) := ⟨λ a b f, ext $ λ x, smul_comm _ _ _⟩ instance [has_smul R S] [is_scalar_tower R S B] : is_scalar_tower R S (A →+ B) := ⟨λ a b f, ext $ λ x, smul_assoc _ _ _⟩ instance [distrib_mul_action Rᵐᵒᵖ B] [is_central_scalar R B] : is_central_scalar R (A →+ B) := ⟨λ a b, ext $ λ x, op_smul_eq_smul _ _⟩ end instance [semiring R] [add_monoid A] [add_comm_monoid B] [module R B] : module R (A →+ B) := { add_smul := λ r s x, ext $ λ y, by simp [add_smul], zero_smul := λ x, ext $ λ y, by simp [zero_smul], ..add_monoid_hom.distrib_mul_action } end add_monoid_hom
52ce5322f28abffafca5b002cded030958398ab3
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/pkg/builtin_attr/UserAttr/Tst.lean
76870872c46d508ef0e5c0acd53dac931f76e6cf
[ "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
89
lean
import UserAttr.BlaAttr @[bar] def f (x : Nat) := x + 2 @[bar] def g (x : Nat) := x + 1
40f617012145b60e44758e5bda0daeccc28b2d81
22e97a5d648fc451e25a06c668dc03ac7ed7bc25
/src/algebra/group/hom.lean
33f5f41032bc6bfb0adc0a60d6923677b5f3e1cf
[ "Apache-2.0" ]
permissive
keeferrowan/mathlib
f2818da875dbc7780830d09bd4c526b0764a4e50
aad2dfc40e8e6a7e258287a7c1580318e865817e
refs/heads/master
1,661,736,426,952
1,590,438,032,000
1,590,438,032,000
266,892,663
0
0
Apache-2.0
1,590,445,835,000
1,590,445,835,000
null
UTF-8
Lean
false
false
10,534
lean
/- Copyright (c) 2018 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Kevin Buzzard, Scott Morrison, Johan Commelin, Chris Hughes, Johannes Hölzl, Yury Kudryashov -/ import algebra.group.basic import tactic.ext /-! # monoid and group homomorphisms This file defines the bundled structures for monoid and group homomorphisms. Namely, we define `monoid_hom` (resp., `add_monoid_hom`) to be bundled homomorphisms between multiplicative (resp., additive) monoids or groups. We also define coercion to a function, and usual operations: composition, identity homomorphism, pointwise multiplication and pointwise inversion. ## Notations * `→*` for bundled monoid homs (also use for group homs) * `→+` for bundled add_monoid homs (also use for add_group homs) ## implementation notes There's a coercion from bundled homs to fun, and the canonical notation is to use the bundled hom as a function via this coercion. There is no `group_hom` -- the idea is that `monoid_hom` is used. The constructor for `monoid_hom` needs a proof of `map_one` as well as `map_mul`; a separate constructor `monoid_hom.mk'` will construct group homs (i.e. monoid homs between groups) given only a proof that multiplication is preserved, Implicit `{}` brackets are often used instead of type class `[]` brackets. This is done when the instances can be inferred because they are implicit arguments to the type `monoid_hom`. When they can be inferred from the type it is faster to use this method than to use type class inference. Historically this file also included definitions of unbundled homomorphism classes; they were deprecated and moved to `deprecated/group`. ## Tags monoid_hom, add_monoid_hom -/ variables {M : Type*} {N : Type*} {P : Type*} -- monoids {G : Type*} {H : Type*} -- groups /-- Bundled add_monoid homomorphisms; use this for bundled add_group homomorphisms too. -/ structure add_monoid_hom (M : Type*) (N : Type*) [add_monoid M] [add_monoid N] := (to_fun : M → N) (map_zero' : to_fun 0 = 0) (map_add' : ∀ x y, to_fun (x + y) = to_fun x + to_fun y) infixr ` →+ `:25 := add_monoid_hom /-- Bundled monoid homomorphisms; use this for bundled group homomorphisms too. -/ @[to_additive add_monoid_hom] structure monoid_hom (M : Type*) (N : Type*) [monoid M] [monoid N] := (to_fun : M → N) (map_one' : to_fun 1 = 1) (map_mul' : ∀ x y, to_fun (x * y) = to_fun x * to_fun y) infixr ` →* `:25 := monoid_hom @[to_additive] instance {M : Type*} {N : Type*} {mM : monoid M} {mN : monoid N} : has_coe_to_fun (M →* N) := ⟨_, monoid_hom.to_fun⟩ namespace monoid_hom variables {mM : monoid M} {mN : monoid N} {mP : monoid P} variables [group G] [comm_group H] include mM mN @[simp, to_additive] lemma to_fun_eq_coe (f : M →* N) : f.to_fun = f := rfl @[simp, to_additive] lemma coe_mk (f : M → N) (h1 hmul) : ⇑(monoid_hom.mk f h1 hmul) = f := rfl @[to_additive] lemma coe_inj ⦃f g : M →* N⦄ (h : (f : M → N) = g) : f = g := by cases f; cases g; cases h; refl @[ext, to_additive] lemma ext ⦃f g : M →* N⦄ (h : ∀ x, f x = g x) : f = g := coe_inj (funext h) attribute [ext] _root_.add_monoid_hom.ext @[to_additive] lemma ext_iff {f g : M →* N} : f = g ↔ ∀ x, f x = g x := ⟨λ h x, h ▸ rfl, λ h, ext h⟩ /-- If f is a monoid homomorphism then f 1 = 1. -/ @[simp, to_additive] lemma map_one (f : M →* N) : f 1 = 1 := f.map_one' /-- If f is a monoid homomorphism then f (a * b) = f a * f b. -/ @[simp, to_additive] lemma map_mul (f : M →* N) (a b : M) : f (a * b) = f a * f b := f.map_mul' a b @[to_additive] lemma map_mul_eq_one (f : M →* N) {a b : M} (h : a * b = 1) : f a * f b = 1 := by rw [← f.map_mul, h, f.map_one] /-- Given a monoid homomorphism `f : M →* N` and an element `x : M`, if `x` has a right inverse, then `f x` has a right inverse too. For elements invertible on both sides see `is_unit.map`. -/ @[to_additive "Given an add_monoid homomorphism `f : M →+ N` and an element `x : M`, if `x` has a right inverse, then `f x` has a right inverse too."] lemma map_exists_right_inv (f : M →* N) {x : M} (hx : ∃ y, x * y = 1) : ∃ y, f x * y = 1 := let ⟨y, hy⟩ := hx in ⟨f y, f.map_mul_eq_one hy⟩ /-- Given a monoid homomorphism `f : M →* N` and an element `x : M`, if `x` has a left inverse, then `f x` has a left inverse too. For elements invertible on both sides see `is_unit.map`. -/ @[to_additive "Given an add_monoid homomorphism `f : M →+ N` and an element `x : M`, if `x` has a left inverse, then `f x` has a left inverse too. For elements invertible on both sides see `is_add_unit.map`."] lemma map_exists_left_inv (f : M →* N) {x : M} (hx : ∃ y, y * x = 1) : ∃ y, y * f x = 1 := let ⟨y, hy⟩ := hx in ⟨f y, f.map_mul_eq_one hy⟩ omit mN mM /-- The identity map from a monoid to itself. -/ @[to_additive] def id (M : Type*) [monoid M] : M →* M := { to_fun := id, map_one' := rfl, map_mul' := λ _ _, rfl } @[simp, to_additive] lemma id_apply {M : Type*} [monoid M] (x : M) : id M x = x := rfl include mM mN mP /-- Composition of monoid morphisms is a monoid morphism. -/ @[to_additive] def comp (hnp : N →* P) (hmn : M →* N) : M →* P := { to_fun := hnp ∘ hmn, map_one' := by simp, map_mul' := by simp } @[simp, to_additive] lemma comp_apply (g : N →* P) (f : M →* N) (x : M) : g.comp f x = g (f x) := rfl /-- Composition of monoid homomorphisms is associative. -/ @[to_additive] lemma comp_assoc {Q : Type*} [monoid Q] (f : M →* N) (g : N →* P) (h : P →* Q) : (h.comp g).comp f = h.comp (g.comp f) := rfl @[to_additive] lemma cancel_right {g₁ g₂ : N →* P} {f : M →* N} (hf : function.surjective f) : g₁.comp f = g₂.comp f ↔ g₁ = g₂ := ⟨λ h, monoid_hom.ext $ (forall_iff_forall_surj hf).1 (ext_iff.1 h), λ h, h ▸ rfl⟩ @[to_additive] lemma cancel_left {g : N →* P} {f₁ f₂ : M →* N} (hg : function.injective g) : g.comp f₁ = g.comp f₂ ↔ f₁ = f₂ := ⟨λ h, monoid_hom.ext $ λ x, hg $ by rw [← comp_apply, h, comp_apply], λ h, h ▸ rfl⟩ omit mP @[simp, to_additive] lemma comp_id (f : M →* N) : f.comp (id M) = f := ext $ λ x, rfl @[simp, to_additive] lemma id_comp (f : M →* N) : (id N).comp f = f := ext $ λ x, rfl variables [mM] [mN] @[to_additive] protected def one : M →* N := { to_fun := λ _, 1, map_one' := rfl, map_mul' := λ _ _, (one_mul 1).symm } @[to_additive] instance : has_one (M →* N) := ⟨monoid_hom.one⟩ @[simp, to_additive] lemma one_apply (x : M) : (1 : M →* N) x = 1 := rfl @[to_additive] instance : inhabited (M →* N) := ⟨1⟩ omit mM mN /-- The product of two monoid morphisms is a monoid morphism if the target is commutative. -/ @[to_additive] protected def mul {M N} {mM : monoid M} [comm_monoid N] (f g : M →* N) : M →* N := { to_fun := λ m, f m * g m, map_one' := show f 1 * g 1 = 1, by simp, map_mul' := begin intros, show f (x * y) * g (x * y) = f x * g x * (f y * g y), rw [f.map_mul, g.map_mul, ←mul_assoc, ←mul_assoc, mul_right_comm (f x)], end } @[to_additive] instance {M N} {mM : monoid M} [comm_monoid N] : has_mul (M →* N) := ⟨monoid_hom.mul⟩ @[simp, to_additive] lemma mul_apply {M N} {mM : monoid M} {mN : comm_monoid N} (f g : M →* N) (x : M) : (f * g) x = f x * g x := rfl /-- (M →* N) is a comm_monoid if N is commutative. -/ @[to_additive add_comm_monoid] instance {M N} [monoid M] [comm_monoid N] : comm_monoid (M →* N) := { mul := (*), mul_assoc := by intros; ext; apply mul_assoc, one := 1, one_mul := by intros; ext; apply one_mul, mul_one := by intros; ext; apply mul_one, mul_comm := by intros; ext; apply mul_comm } /-- `flip` arguments of `f : M →* N →* P` -/ @[to_additive "`flip` arguments of `f : M →+ N →+ P`"] def flip {mM : monoid M} {mN : monoid N} {mP : comm_monoid P} (f : M →* N →* P) : N →* M →* P := { to_fun := λ y, ⟨λ x, f x y, by rw [f.map_one, one_apply], λ x₁ x₂, by rw [f.map_mul, mul_apply]⟩, map_one' := ext $ λ x, (f x).map_one, map_mul' := λ y₁ y₂, ext $ λ x, (f x).map_mul y₁ y₂ } @[simp, to_additive] lemma flip_apply {mM : monoid M} {mN : monoid N} {mP : comm_monoid P} (f : M →* N →* P) (x : M) (y : N) : f.flip y x = f x y := rfl /-- Group homomorphisms preserve inverse. -/ @[simp, to_additive] theorem map_inv {G H} [group G] [group H] (f : G →* H) (g : G) : f g⁻¹ = (f g)⁻¹ := eq_inv_of_mul_eq_one $ by rw [←f.map_mul, inv_mul_self, f.map_one] /-- Group homomorphisms preserve division. -/ @[simp, to_additive] theorem map_mul_inv {G H} [group G] [group H] (f : G →* H) (g h : G) : f (g * h⁻¹) = (f g) * (f h)⁻¹ := by rw [f.map_mul, f.map_inv] /-- A group homomorphism is injective iff its kernel is trivial. -/ @[to_additive] lemma injective_iff {G H} [group G] [group H] (f : G →* H) : function.injective f ↔ (∀ a, f a = 1 → a = 1) := ⟨λ h _, by rw ← f.map_one; exact @h _ _, λ h x y hxy, by rw [← inv_inv (f x), inv_eq_iff_mul_eq_one, ← f.map_inv, ← f.map_mul] at hxy; simpa using inv_eq_of_mul_eq_one (h _ hxy)⟩ include mM /-- Makes a group homomomorphism from a proof that the map preserves multiplication. -/ @[to_additive] def mk' (f : M → G) (map_mul : ∀ a b : M, f (a * b) = f a * f b) : M →* G := { to_fun := f, map_mul' := map_mul, map_one' := mul_self_iff_eq_one.1 $ by rw [←map_mul, mul_one] } omit mM /-- The inverse of a monoid homomorphism is a monoid homomorphism if the target is a commutative group.-/ @[to_additive] protected def inv {M G} {mM : monoid M} [comm_group G] (f : M →* G) : M →* G := mk' (λ g, (f g)⁻¹) $ λ a b, by rw [←mul_inv, f.map_mul] @[to_additive] instance {M G} [monoid M] [comm_group G] : has_inv (M →* G) := ⟨monoid_hom.inv⟩ @[simp, to_additive] lemma inv_apply {M G} {mM : monoid M} {gG : comm_group G} (f : M →* G) (x : M) : f⁻¹ x = (f x)⁻¹ := rfl /-- (M →* G) is a comm_group if G is a comm_group -/ @[to_additive add_comm_group] instance {M G} [monoid M] [comm_group G] : comm_group (M →* G) := { inv := has_inv.inv, mul_left_inv := by intros; ext; apply mul_left_inv, ..monoid_hom.comm_monoid } end monoid_hom namespace add_monoid_hom /-- Additive group homomorphisms preserve subtraction. -/ @[simp] theorem map_sub {G H} [add_group G] [add_group H] (f : G →+ H) (g h : G) : f (g - h) = (f g) - (f h) := f.map_add_neg g h end add_monoid_hom
895da6e683c1b58f727b9baf7b3c85c455a5c93b
c777c32c8e484e195053731103c5e52af26a25d1
/src/measure_theory/measure/stieltjes.lean
9911b118cab9220a6d45cda2da9c5db05b3bead0
[ "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
24,107
lean
/- Copyright (c) 2021 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Yury Kudryashov, Sébastien Gouëzel -/ import measure_theory.constructions.borel_space import topology.algebra.order.left_right_lim /-! # Stieltjes measures on the real line Consider a function `f : ℝ → ℝ` which is monotone and right-continuous. Then one can define a corrresponding measure, giving mass `f b - f a` to the interval `(a, b]`. ## Main definitions * `stieltjes_function` is a structure containing a function from `ℝ → ℝ`, together with the assertions that it is monotone and right-continuous. To `f : stieltjes_function`, one associates a Borel measure `f.measure`. * `f.measure_Ioc` asserts that `f.measure (Ioc a b) = of_real (f b - f a)` * `f.measure_Ioo` asserts that `f.measure (Ioo a b) = of_real (left_lim f b - f a)`. * `f.measure_Icc` and `f.measure_Ico` are analogous. -/ section move_this -- this section contains lemmas that should be moved to appropriate places after the port to lean 4 open filter set open_locale topology -- todo after the port: move to order/filter/at_top_bot lemma exists_seq_monotone_tendsto_at_top_at_top (α : Type*) [semilattice_sup α] [nonempty α] [(at_top : filter α).is_countably_generated] : ∃ xs : ℕ → α, monotone xs ∧ tendsto xs at_top at_top := begin haveI h_ne_bot : (at_top : filter α).ne_bot := at_top_ne_bot, obtain ⟨ys, h⟩ := exists_seq_tendsto (at_top : filter α), let xs : ℕ → α := λ n, finset.sup' (finset.range (n + 1)) finset.nonempty_range_succ ys, have h_mono : monotone xs, { intros i j hij, rw finset.sup'_le_iff, intros k hk, refine finset.le_sup'_of_le _ _ le_rfl, rw finset.mem_range at hk ⊢, exact hk.trans_le (add_le_add_right hij _), }, refine ⟨xs, h_mono, _⟩, { refine tendsto_at_top_at_top_of_monotone h_mono _, have : ∀ (a : α), ∃ (n : ℕ), a ≤ ys n, { rw tendsto_at_top_at_top at h, intro a, obtain ⟨i, hi⟩ := h a, exact ⟨i, hi i le_rfl⟩, }, intro a, obtain ⟨i, hi⟩ := this a, refine ⟨i, hi.trans _⟩, refine finset.le_sup'_of_le _ _ le_rfl, rw finset.mem_range_succ_iff, }, end lemma exists_seq_antitone_tendsto_at_top_at_bot (α : Type*) [semilattice_inf α] [nonempty α] [h2 : (at_bot : filter α).is_countably_generated] : ∃ xs : ℕ → α, antitone xs ∧ tendsto xs at_top at_bot := @exists_seq_monotone_tendsto_at_top_at_top αᵒᵈ _ _ h2 -- todo after the port: move to topology/algebra/order/monotone_convergence lemma supr_eq_supr_subseq_of_antitone {ι₁ ι₂ α : Type*} [preorder ι₂] [complete_lattice α] {l : filter ι₁} [l.ne_bot] {f : ι₂ → α} {φ : ι₁ → ι₂} (hf : antitone f) (hφ : tendsto φ l at_bot) : (⨆ i, f i) = (⨆ i, f (φ i)) := le_antisymm (supr_mono' (λ i, exists_imp_exists (λ j (hj : φ j ≤ i), hf hj) (hφ.eventually $ eventually_le_at_bot i).exists)) (supr_mono' (λ i, ⟨φ i, le_rfl⟩)) namespace measure_theory -- todo after the port: move these lemmas to measure_theory/measure/measure_space? variables {α : Type*} {mα : measurable_space α} include mα lemma tendsto_measure_Ico_at_top [semilattice_sup α] [no_max_order α] [(at_top : filter α).is_countably_generated] (μ : measure α) (a : α) : tendsto (λ x, μ (Ico a x)) at_top (𝓝 (μ (Ici a))) := begin haveI : nonempty α := ⟨a⟩, have h_mono : monotone (λ x, μ (Ico a x)) := λ i j hij, measure_mono (Ico_subset_Ico_right hij), convert tendsto_at_top_supr h_mono, obtain ⟨xs, hxs_mono, hxs_tendsto⟩ := exists_seq_monotone_tendsto_at_top_at_top α, have h_Ici : Ici a = ⋃ n, Ico a (xs n), { ext1 x, simp only [mem_Ici, mem_Union, mem_Ico, exists_and_distrib_left, iff_self_and], intro _, obtain ⟨y, hxy⟩ := no_max_order.exists_gt x, obtain ⟨n, hn⟩ := tendsto_at_top_at_top.mp hxs_tendsto y, exact ⟨n, hxy.trans_le (hn n le_rfl)⟩, }, rw [h_Ici, measure_Union_eq_supr, supr_eq_supr_subseq_of_monotone h_mono hxs_tendsto], exact monotone.directed_le (λ i j hij, Ico_subset_Ico_right (hxs_mono hij)), end lemma tendsto_measure_Ioc_at_bot [semilattice_inf α] [no_min_order α] [(at_bot : filter α).is_countably_generated] (μ : measure α) (a : α) : tendsto (λ x, μ (Ioc x a)) at_bot (𝓝 (μ (Iic a))) := begin haveI : nonempty α := ⟨a⟩, have h_mono : antitone (λ x, μ (Ioc x a)) := λ i j hij, measure_mono (Ioc_subset_Ioc_left hij), convert tendsto_at_bot_supr h_mono, obtain ⟨xs, hxs_mono, hxs_tendsto⟩ := exists_seq_antitone_tendsto_at_top_at_bot α, have h_Iic : Iic a = ⋃ n, Ioc (xs n) a, { ext1 x, simp only [mem_Iic, mem_Union, mem_Ioc, exists_and_distrib_right, iff_and_self], intro _, obtain ⟨y, hxy⟩ := no_min_order.exists_lt x, obtain ⟨n, hn⟩ := tendsto_at_top_at_bot.mp hxs_tendsto y, exact ⟨n, (hn n le_rfl).trans_lt hxy⟩, }, rw [h_Iic, measure_Union_eq_supr, supr_eq_supr_subseq_of_antitone h_mono hxs_tendsto], exact monotone.directed_le (λ i j hij, Ioc_subset_Ioc_left (hxs_mono hij)), end lemma tendsto_measure_Iic_at_top [semilattice_sup α] [(at_top : filter α).is_countably_generated] (μ : measure α) : tendsto (λ x, μ (Iic x)) at_top (𝓝 (μ univ)) := begin casesI is_empty_or_nonempty α, { have h1 : ∀ x : α, Iic x = ∅ := λ x, subsingleton.elim _ _, have h2 : (univ : set α) = ∅ := subsingleton.elim _ _, simp_rw [h1, h2], exact tendsto_const_nhds, }, have h_mono : monotone (λ x, μ (Iic x)) := λ i j hij, measure_mono (Iic_subset_Iic.mpr hij), convert tendsto_at_top_supr h_mono, obtain ⟨xs, hxs_mono, hxs_tendsto⟩ := exists_seq_monotone_tendsto_at_top_at_top α, have h_univ : (univ : set α) = ⋃ n, Iic (xs n), { ext1 x, simp only [mem_univ, mem_Union, mem_Iic, true_iff], obtain ⟨n, hn⟩ := tendsto_at_top_at_top.mp hxs_tendsto x, exact ⟨n, hn n le_rfl⟩, }, rw [h_univ, measure_Union_eq_supr, supr_eq_supr_subseq_of_monotone h_mono hxs_tendsto], exact monotone.directed_le (λ i j hij, Iic_subset_Iic.mpr (hxs_mono hij)), end lemma tendsto_measure_Ici_at_bot [semilattice_inf α] [h : (at_bot : filter α).is_countably_generated] (μ : measure α) : tendsto (λ x, μ (Ici x)) at_bot (𝓝 (μ univ)) := @tendsto_measure_Iic_at_top αᵒᵈ _ _ h μ end measure_theory end move_this noncomputable theory open classical set filter function open ennreal (of_real) open_locale big_operators ennreal nnreal topology measure_theory /-! ### Basic properties of Stieltjes functions -/ /-- Bundled monotone right-continuous real functions, used to construct Stieltjes measures. -/ structure stieltjes_function := (to_fun : ℝ → ℝ) (mono' : monotone to_fun) (right_continuous' : ∀ x, continuous_within_at to_fun (Ici x) x) namespace stieltjes_function instance : has_coe_to_fun stieltjes_function (λ _, ℝ → ℝ) := ⟨to_fun⟩ initialize_simps_projections stieltjes_function (to_fun → apply) variable (f : stieltjes_function) lemma mono : monotone f := f.mono' lemma right_continuous (x : ℝ) : continuous_within_at f (Ici x) x := f.right_continuous' x /-- The identity of `ℝ` as a Stieltjes function, used to construct Lebesgue measure. -/ @[simps] protected def id : stieltjes_function := { to_fun := id, mono' := λ x y, id, right_continuous' := λ x, continuous_within_at_id } @[simp] lemma id_left_lim (x : ℝ) : left_lim stieltjes_function.id x = x := tendsto_nhds_unique (stieltjes_function.id.mono.tendsto_left_lim x) $ (continuous_at_id).tendsto.mono_left nhds_within_le_nhds instance : inhabited stieltjes_function := ⟨stieltjes_function.id⟩ /-- If a function `f : ℝ → ℝ` is monotone, then the function mapping `x` to the right limit of `f` at `x` is a Stieltjes function, i.e., it is monotone and right-continuous. -/ noncomputable def _root_.monotone.stieltjes_function {f : ℝ → ℝ} (hf : monotone f) : stieltjes_function := { to_fun := right_lim f, mono' := λ x y hxy, hf.right_lim hxy, right_continuous' := begin assume x s hs, obtain ⟨l, u, hlu, lus⟩ : ∃ (l u : ℝ), right_lim f x ∈ Ioo l u ∧ Ioo l u ⊆ s := mem_nhds_iff_exists_Ioo_subset.1 hs, obtain ⟨y, xy, h'y⟩ : ∃ (y : ℝ) (H : x < y), Ioc x y ⊆ f ⁻¹' (Ioo l u) := mem_nhds_within_Ioi_iff_exists_Ioc_subset.1 (hf.tendsto_right_lim x (Ioo_mem_nhds hlu.1 hlu.2)), change ∀ᶠ y in 𝓝[≥] x, right_lim f y ∈ s, filter_upwards [Ico_mem_nhds_within_Ici ⟨le_refl x, xy⟩] with z hz, apply lus, refine ⟨hlu.1.trans_le (hf.right_lim hz.1), _⟩, obtain ⟨a, za, ay⟩ : ∃ (a : ℝ), z < a ∧ a < y := exists_between hz.2, calc right_lim f z ≤ f a : hf.right_lim_le za ... < u : (h'y ⟨hz.1.trans_lt za, ay.le⟩).2, end } lemma _root_.monotone.stieltjes_function_eq {f : ℝ → ℝ} (hf : monotone f) (x : ℝ) : hf.stieltjes_function x = right_lim f x := rfl lemma countable_left_lim_ne (f : stieltjes_function) : set.countable {x | left_lim f x ≠ f x} := begin apply countable.mono _ (f.mono.countable_not_continuous_at), assume x hx h'x, apply hx, exact tendsto_nhds_unique (f.mono.tendsto_left_lim x) (h'x.tendsto.mono_left nhds_within_le_nhds), end /-! ### The outer measure associated to a Stieltjes function -/ /-- Length of an interval. This is the largest monotone function which correctly measures all intervals. -/ def length (s : set ℝ) : ℝ≥0∞ := ⨅a b (h : s ⊆ Ioc a b), of_real (f b - f a) @[simp] lemma length_empty : f.length ∅ = 0 := nonpos_iff_eq_zero.1 $ infi_le_of_le 0 $ infi_le_of_le 0 $ by simp @[simp] lemma length_Ioc (a b : ℝ) : f.length (Ioc a b) = of_real (f b - f a) := begin refine le_antisymm (infi_le_of_le a $ infi₂_le b subset.rfl) (le_infi $ λ a', le_infi $ λ b', le_infi $ λ h, ennreal.coe_le_coe.2 _), cases le_or_lt b a with ab ab, { rw real.to_nnreal_of_nonpos (sub_nonpos.2 (f.mono ab)), apply zero_le, }, cases (Ioc_subset_Ioc_iff ab).1 h with h₁ h₂, exact real.to_nnreal_le_to_nnreal (sub_le_sub (f.mono h₁) (f.mono h₂)) end lemma length_mono {s₁ s₂ : set ℝ} (h : s₁ ⊆ s₂) : f.length s₁ ≤ f.length s₂ := infi_mono $ λ a, binfi_mono $ λ b, h.trans open measure_theory /-- The Stieltjes outer measure associated to a Stieltjes function. -/ protected def outer : outer_measure ℝ := outer_measure.of_function f.length f.length_empty lemma outer_le_length (s : set ℝ) : f.outer s ≤ f.length s := outer_measure.of_function_le _ /-- If a compact interval `[a, b]` is covered by a union of open interval `(c i, d i)`, then `f b - f a ≤ ∑ f (d i) - f (c i)`. This is an auxiliary technical statement to prove the same statement for half-open intervals, the point of the current statement being that one can use compactness to reduce it to a finite sum, and argue by induction on the size of the covering set. -/ lemma length_subadditive_Icc_Ioo {a b : ℝ} {c d : ℕ → ℝ} (ss : Icc a b ⊆ ⋃ i, Ioo (c i) (d i)) : of_real (f b - f a) ≤ ∑' i, of_real (f (d i) - f (c i)) := begin suffices : ∀ (s:finset ℕ) b (cv : Icc a b ⊆ ⋃ i ∈ (↑s:set ℕ), Ioo (c i) (d i)), (of_real (f b - f a) : ℝ≥0∞) ≤ ∑ i in s, of_real (f (d i) - f (c i)), { rcases is_compact_Icc.elim_finite_subcover_image (λ (i : ℕ) (_ : i ∈ univ), @is_open_Ioo _ _ _ _ (c i) (d i)) (by simpa using ss) with ⟨s, su, hf, hs⟩, have e : (⋃ i ∈ (↑hf.to_finset:set ℕ), Ioo (c i) (d i)) = (⋃ i ∈ s, Ioo (c i) (d i)), by simp only [ext_iff, exists_prop, finset.set_bUnion_coe, mem_Union, forall_const, iff_self, finite.mem_to_finset], rw ennreal.tsum_eq_supr_sum, refine le_trans _ (le_supr _ hf.to_finset), exact this hf.to_finset _ (by simpa only [e]) }, clear ss b, refine λ s, finset.strong_induction_on s (λ s IH b cv, _), cases le_total b a with ab ab, { rw ennreal.of_real_eq_zero.2 (sub_nonpos.2 (f.mono ab)), exact zero_le _, }, have := cv ⟨ab, le_rfl⟩, simp at this, rcases this with ⟨i, is, cb, bd⟩, rw [← finset.insert_erase is] at cv ⊢, rw [finset.coe_insert, bUnion_insert] at cv, rw [finset.sum_insert (finset.not_mem_erase _ _)], refine le_trans _ (add_le_add_left (IH _ (finset.erase_ssubset is) (c i) _) _), { refine le_trans (ennreal.of_real_le_of_real _) ennreal.of_real_add_le, rw sub_add_sub_cancel, exact sub_le_sub_right (f.mono bd.le) _ }, { rintro x ⟨h₁, h₂⟩, refine (cv ⟨h₁, le_trans h₂ (le_of_lt cb)⟩).resolve_left (mt and.left (not_lt_of_le h₂)) } end @[simp] lemma outer_Ioc (a b : ℝ) : f.outer (Ioc a b) = of_real (f b - f a) := begin /- It suffices to show that, if `(a, b]` is covered by sets `s i`, then `f b - f a` is bounded by `∑ f.length (s i) + ε`. The difficulty is that `f.length` is expressed in terms of half-open intervals, while we would like to have a compact interval covered by open intervals to use compactness and finite sums, as provided by `length_subadditive_Icc_Ioo`. The trick is to use the right-continuity of `f`. If `a'` is close enough to `a` on its right, then `[a', b]` is still covered by the sets `s i` and moreover `f b - f a'` is very close to `f b - f a` (up to `ε/2`). Also, by definition one can cover `s i` by a half-closed interval `(p i, q i]` with `f`-length very close to that of `s i` (within a suitably small `ε' i`, say). If one moves `q i` very slightly to the right, then the `f`-length will change very little by right continuity, and we will get an open interval `(p i, q' i)` covering `s i` with `f (q' i) - f (p i)` within `ε' i` of the `f`-length of `s i`. -/ refine le_antisymm (by { rw ← f.length_Ioc, apply outer_le_length }) (le_infi₂ $ λ s hs, ennreal.le_of_forall_pos_le_add $ λ ε εpos h, _), let δ := ε / 2, have δpos : 0 < (δ : ℝ≥0∞), by simpa using εpos.ne', rcases ennreal.exists_pos_sum_of_countable δpos.ne' ℕ with ⟨ε', ε'0, hε⟩, obtain ⟨a', ha', aa'⟩ : ∃ a', f a' - f a < δ ∧ a < a', { have A : continuous_within_at (λ r, f r - f a) (Ioi a) a, { refine continuous_within_at.sub _ continuous_within_at_const, exact (f.right_continuous a).mono Ioi_subset_Ici_self }, have B : f a - f a < δ, by rwa [sub_self, nnreal.coe_pos, ← ennreal.coe_pos], exact (((tendsto_order.1 A).2 _ B).and self_mem_nhds_within).exists }, have : ∀ i, ∃ p:ℝ×ℝ, s i ⊆ Ioo p.1 p.2 ∧ (of_real (f p.2 - f p.1) : ℝ≥0∞) < f.length (s i) + ε' i, { intro i, have := (ennreal.lt_add_right ((ennreal.le_tsum i).trans_lt h).ne (ennreal.coe_ne_zero.2 (ε'0 i).ne')), conv at this { to_lhs, rw length }, simp only [infi_lt_iff, exists_prop] at this, rcases this with ⟨p, q', spq, hq'⟩, have : continuous_within_at (λ r, of_real (f r - f p)) (Ioi q') q', { apply ennreal.continuous_of_real.continuous_at.comp_continuous_within_at, refine continuous_within_at.sub _ continuous_within_at_const, exact (f.right_continuous q').mono Ioi_subset_Ici_self }, rcases (((tendsto_order.1 this).2 _ hq').and self_mem_nhds_within).exists with ⟨q, hq, q'q⟩, exact ⟨⟨p, q⟩, spq.trans (Ioc_subset_Ioo_right q'q), hq⟩ }, choose g hg using this, have I_subset : Icc a' b ⊆ ⋃ i, Ioo (g i).1 (g i).2 := calc Icc a' b ⊆ Ioc a b : λ x hx, ⟨aa'.trans_le hx.1, hx.2⟩ ... ⊆ ⋃ i, s i : hs ... ⊆ ⋃ i, Ioo (g i).1 (g i).2 : Union_mono (λ i, (hg i).1), calc of_real (f b - f a) = of_real ((f b - f a') + (f a' - f a)) : by rw sub_add_sub_cancel ... ≤ of_real (f b - f a') + of_real (f a' - f a) : ennreal.of_real_add_le ... ≤ (∑' i, of_real (f (g i).2 - f (g i).1)) + of_real δ : add_le_add (f.length_subadditive_Icc_Ioo I_subset) (ennreal.of_real_le_of_real ha'.le) ... ≤ (∑' i, (f.length (s i) + ε' i)) + δ : add_le_add (ennreal.tsum_le_tsum (λ i, (hg i).2.le)) (by simp only [ennreal.of_real_coe_nnreal, le_rfl]) ... = (∑' i, f.length (s i)) + (∑' i, ε' i) + δ : by rw [ennreal.tsum_add] ... ≤ (∑' i, f.length (s i)) + δ + δ : add_le_add (add_le_add le_rfl hε.le) le_rfl ... = ∑' (i : ℕ), f.length (s i) + ε : by simp [add_assoc, ennreal.add_halves] end lemma measurable_set_Ioi {c : ℝ} : measurable_set[f.outer.caratheodory] (Ioi c) := begin apply outer_measure.of_function_caratheodory (λ t, _), refine le_infi (λ a, le_infi (λ b, le_infi (λ h, _))), refine le_trans (add_le_add (f.length_mono $ inter_subset_inter_left _ h) (f.length_mono $ diff_subset_diff_left h)) _, cases le_total a c with hac hac; cases le_total b c with hbc hbc, { simp only [Ioc_inter_Ioi, f.length_Ioc, hac, sup_eq_max, hbc, le_refl, Ioc_eq_empty, max_eq_right, min_eq_left, Ioc_diff_Ioi, f.length_empty, zero_add, not_lt] }, { simp only [hac, hbc, Ioc_inter_Ioi, Ioc_diff_Ioi, f.length_Ioc, min_eq_right, sup_eq_max, ←ennreal.of_real_add, f.mono hac, f.mono hbc, sub_nonneg, sub_add_sub_cancel, le_refl, max_eq_right] }, { simp only [hbc, le_refl, Ioc_eq_empty, Ioc_inter_Ioi, min_eq_left, Ioc_diff_Ioi, f.length_empty, zero_add, or_true, le_sup_iff, f.length_Ioc, not_lt] }, { simp only [hac, hbc, Ioc_inter_Ioi, Ioc_diff_Ioi, f.length_Ioc, min_eq_right, sup_eq_max, le_refl, Ioc_eq_empty, add_zero, max_eq_left, f.length_empty, not_lt] } end theorem outer_trim : f.outer.trim = f.outer := begin refine le_antisymm (λ s, _) (outer_measure.le_trim _), rw outer_measure.trim_eq_infi, refine le_infi (λ t, le_infi $ λ ht, ennreal.le_of_forall_pos_le_add $ λ ε ε0 h, _), rcases ennreal.exists_pos_sum_of_countable (ennreal.coe_pos.2 ε0).ne' ℕ with ⟨ε', ε'0, hε⟩, refine le_trans _ (add_le_add_left (le_of_lt hε) _), rw ← ennreal.tsum_add, choose g hg using show ∀ i, ∃ s, t i ⊆ s ∧ measurable_set s ∧ f.outer s ≤ f.length (t i) + of_real (ε' i), { intro i, have := (ennreal.lt_add_right ((ennreal.le_tsum i).trans_lt h).ne (ennreal.coe_pos.2 (ε'0 i)).ne'), conv at this {to_lhs, rw length}, simp only [infi_lt_iff] at this, rcases this with ⟨a, b, h₁, h₂⟩, rw ← f.outer_Ioc at h₂, exact ⟨_, h₁, measurable_set_Ioc, le_of_lt $ by simpa using h₂⟩ }, simp at hg, apply infi_le_of_le (Union g) _, apply infi_le_of_le (ht.trans $ Union_mono (λ i, (hg i).1)) _, apply infi_le_of_le (measurable_set.Union (λ i, (hg i).2.1)) _, exact le_trans (f.outer.Union _) (ennreal.tsum_le_tsum $ λ i, (hg i).2.2) end lemma borel_le_measurable : borel ℝ ≤ f.outer.caratheodory := begin rw borel_eq_generate_from_Ioi, refine measurable_space.generate_from_le _, simp [f.measurable_set_Ioi] { contextual := tt } end /-! ### The measure associated to a Stieltjes function -/ /-- The measure associated to a Stieltjes function, giving mass `f b - f a` to the interval `(a, b]`. -/ @[irreducible] protected def measure : measure ℝ := { to_outer_measure := f.outer, m_Union := λ s hs, f.outer.Union_eq_of_caratheodory $ λ i, f.borel_le_measurable _ (hs i), trimmed := f.outer_trim } @[simp] lemma measure_Ioc (a b : ℝ) : f.measure (Ioc a b) = of_real (f b - f a) := by { rw stieltjes_function.measure, exact f.outer_Ioc a b } @[simp] lemma measure_singleton (a : ℝ) : f.measure {a} = of_real (f a - left_lim f a) := begin obtain ⟨u, u_mono, u_lt_a, u_lim⟩ : ∃ (u : ℕ → ℝ), strict_mono u ∧ (∀ (n : ℕ), u n < a) ∧ tendsto u at_top (𝓝 a) := exists_seq_strict_mono_tendsto a, have A : {a} = ⋂ n, Ioc (u n) a, { refine subset.antisymm (λ x hx, by simp [mem_singleton_iff.1 hx, u_lt_a]) (λ x hx, _), simp at hx, have : a ≤ x := le_of_tendsto' u_lim (λ n, (hx n).1.le), simp [le_antisymm this (hx 0).2] }, have L1 : tendsto (λ n, f.measure (Ioc (u n) a)) at_top (𝓝 (f.measure {a})), { rw A, refine tendsto_measure_Inter (λ n, measurable_set_Ioc) (λ m n hmn, _) _, { exact Ioc_subset_Ioc (u_mono.monotone hmn) le_rfl }, { exact ⟨0, by simpa only [measure_Ioc] using ennreal.of_real_ne_top⟩ } }, have L2 : tendsto (λ n, f.measure (Ioc (u n) a)) at_top (𝓝 (of_real (f a - left_lim f a))), { simp only [measure_Ioc], have : tendsto (λ n, f (u n)) at_top (𝓝 (left_lim f a)), { apply (f.mono.tendsto_left_lim a).comp, exact tendsto_nhds_within_of_tendsto_nhds_of_eventually_within _ u_lim (eventually_of_forall (λ n, u_lt_a n)) }, exact ennreal.continuous_of_real.continuous_at.tendsto.comp (tendsto_const_nhds.sub this) }, exact tendsto_nhds_unique L1 L2 end @[simp] lemma measure_Icc (a b : ℝ) : f.measure (Icc a b) = of_real (f b - left_lim f a) := begin rcases le_or_lt a b with hab|hab, { have A : disjoint {a} (Ioc a b), by simp, simp [← Icc_union_Ioc_eq_Icc le_rfl hab, -singleton_union, ← ennreal.of_real_add, f.mono.left_lim_le, measure_union A measurable_set_Ioc, f.mono hab] }, { simp only [hab, measure_empty, Icc_eq_empty, not_le], symmetry, simp [ennreal.of_real_eq_zero, f.mono.le_left_lim hab] } end @[simp] lemma measure_Ioo {a b : ℝ} : f.measure (Ioo a b) = of_real (left_lim f b - f a) := begin rcases le_or_lt b a with hab|hab, { simp only [hab, measure_empty, Ioo_eq_empty, not_lt], symmetry, simp [ennreal.of_real_eq_zero, f.mono.left_lim_le hab] }, { have A : disjoint (Ioo a b) {b}, by simp, have D : f b - f a = (f b - left_lim f b) + (left_lim f b - f a), by abel, have := f.measure_Ioc a b, simp only [←Ioo_union_Icc_eq_Ioc hab le_rfl, measure_singleton, measure_union A (measurable_set_singleton b), Icc_self] at this, rw [D, ennreal.of_real_add, add_comm] at this, { simpa only [ennreal.add_right_inj ennreal.of_real_ne_top] }, { simp only [f.mono.left_lim_le, sub_nonneg] }, { simp only [f.mono.le_left_lim hab, sub_nonneg] } }, end @[simp] lemma measure_Ico (a b : ℝ) : f.measure (Ico a b) = of_real (left_lim f b - left_lim f a) := begin rcases le_or_lt b a with hab|hab, { simp only [hab, measure_empty, Ico_eq_empty, not_lt], symmetry, simp [ennreal.of_real_eq_zero, f.mono.left_lim hab] }, { have A : disjoint {a} (Ioo a b) := by simp, simp [← Icc_union_Ioo_eq_Ico le_rfl hab, -singleton_union, hab.ne, f.mono.left_lim_le, measure_union A measurable_set_Ioo, f.mono.le_left_lim hab, ← ennreal.of_real_add] } end lemma measure_Iic {l : ℝ} (hf : tendsto f at_bot (𝓝 l)) (x : ℝ) : f.measure (Iic x) = of_real (f x - l) := begin refine tendsto_nhds_unique (tendsto_measure_Ioc_at_bot _ _) _, simp_rw measure_Ioc, exact ennreal.tendsto_of_real (tendsto.const_sub _ hf), end lemma measure_Ici {l : ℝ} (hf : tendsto f at_top (𝓝 l)) (x : ℝ) : f.measure (Ici x) = of_real (l - left_lim f x) := begin refine tendsto_nhds_unique (tendsto_measure_Ico_at_top _ _) _, simp_rw measure_Ico, refine ennreal.tendsto_of_real (tendsto.sub_const _ _), have h_le1 : ∀ x, f (x - 1) ≤ left_lim f x := λ x, monotone.le_left_lim f.mono (sub_one_lt x), have h_le2 : ∀ x, left_lim f x ≤ f x := λ x, monotone.left_lim_le f.mono le_rfl, refine tendsto_of_tendsto_of_tendsto_of_le_of_le (hf.comp _) hf h_le1 h_le2, rw tendsto_at_top_at_top, exact λ y, ⟨y + 1, λ z hyz, by rwa le_sub_iff_add_le⟩, end lemma measure_univ {l u : ℝ} (hfl : tendsto f at_bot (𝓝 l)) (hfu : tendsto f at_top (𝓝 u)) : f.measure univ = of_real (u - l) := begin refine tendsto_nhds_unique (tendsto_measure_Iic_at_top _) _, simp_rw measure_Iic f hfl, exact ennreal.tendsto_of_real (tendsto.sub_const hfu _), end instance : is_locally_finite_measure f.measure := ⟨λ x, ⟨Ioo (x-1) (x+1), Ioo_mem_nhds (by linarith) (by linarith), by simp⟩⟩ end stieltjes_function
66e0cc2e40335c069f3984ad31ef67f246f6c198
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/331.lean
32004add7e1b0ac4092a28ce1499611fe908bca9
[ "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
310
lean
namespace nat inductive less (a : nat) : nat → Prop | base : less (succ a) | step : Π {b}, less b → less (succ b) end nat open nat #check less.rec_on namespace foo1 protected definition foo2.bar : nat := 10 end foo1 example : foo1.foo2.bar = 10 := rfl open foo1 example : foo2.bar = 10 := rfl
a15d8526cb8bf429f93c540bfe16e63bf3b0bb40
d6124c8dbe5661dcc5b8c9da0a56fbf1f0480ad6
/Papyrus/IR/TypeRefs.lean
3f70132f25521017a0ba9b6297fa3baa3e6b29df
[ "Apache-2.0" ]
permissive
xubaiw/lean4-papyrus
c3fbbf8ba162eb5f210155ae4e20feb2d32c8182
02e82973a5badda26fc0f9fd15b3d37e2eb309e0
refs/heads/master
1,691,425,756,824
1,632,122,825,000
1,632,123,075,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
20,779
lean
import Papyrus.Context import Papyrus.IR.TypeRef import Papyrus.IR.AddressSpace namespace Papyrus -------------------------------------------------------------------------------- -- Singleton Type References -------------------------------------------------------------------------------- -- # Special Types /-- A reference to an external LLVM `void` type. -/ structure VoidTypeRef extends TypeRef where is_void_type : toTypeRef.typeID = TypeID.void instance : Coe VoidTypeRef TypeRef := ⟨(·.toTypeRef)⟩ /-- Get a reference to the `void` type of the current context. -/ @[extern "papyrus_get_void_type"] constant VoidTypeRef.get : LlvmM VoidTypeRef /-- A reference to an external LLVM `label` type. -/ structure LabelTypeRef extends TypeRef where is_label_type : toTypeRef.typeID = TypeID.void instance : Coe LabelTypeRef TypeRef := ⟨(·.toTypeRef)⟩ /-- Get a reference to the `label` type of the current context. -/ @[extern "papyrus_get_label_type"] constant LabelTypeRef.get : LlvmM LabelTypeRef /-- A reference to an external LLVM `metadata` type. -/ structure MetadataTypeRef extends TypeRef where is_metadata_type : toTypeRef.typeID = TypeID.metadata instance : Coe MetadataTypeRef TypeRef := ⟨(·.toTypeRef)⟩ /-- Get a reference to the `metadata` type of the current context. -/ @[extern "papyrus_get_metadata_type"] constant MetadataTypeRef.get : LlvmM MetadataTypeRef /-- A reference to an external LLVM `token` type. -/ structure TokenTypeRef extends TypeRef where is_token_type : toTypeRef.typeID = TypeID.token instance : Coe TokenTypeRef TypeRef := ⟨(·.toTypeRef)⟩ /-- Get a reference to the `token` type of the current context. -/ @[extern "papyrus_get_token_type"] constant TokenTypeRef.get : LlvmM TokenTypeRef /-- A reference to an external LLVM `x86_mmx` type, which is a 64-bit X86 MMX vector type. -/ structure X86MMXTypeRef extends TypeRef where is_x86MMX_type : toTypeRef.typeID = TypeID.x86MMX instance : Coe X86MMXTypeRef TypeRef := ⟨(·.toTypeRef)⟩ /-- Get a reference to the `x86_mmx` type of the current context. -/ @[extern "papyrus_get_x86_mmx_type"] constant X86MMXTypeRef.get : LlvmM X86MMXTypeRef /-- A reference to an external LLVM `x86_mmx` type, which is a 8192-bit X86 AMX vector type. -/ structure X86AMXTypeRef extends TypeRef where is_x86AMX_type : toTypeRef.typeID = TypeID.x86AMX instance : Coe X86AMXTypeRef TypeRef := ⟨(·.toTypeRef)⟩ /-- Get a reference to the `x86_mmx` type of the current context. -/ @[extern "papyrus_get_x86_amx_type"] constant X86AMXTypeRef.get : LlvmM X86AMXTypeRef -- # Floating Point Types /-- A reference to an external LLVM `half` type, which is an IEEE half-precision (16-bit) floating point type. -/ structure HalfTypeRef extends TypeRef where is_half_type : toTypeRef.typeID = TypeID.half instance : Coe HalfTypeRef TypeRef := ⟨(·.toTypeRef)⟩ /-- Get a reference to the `half` type of the current context. -/ @[extern "papyrus_get_half_type"] constant HalfTypeRef.get : LlvmM HalfTypeRef /-- A reference to an external LLVM `bfloat` type, which is a brain floating point type (16-bits with a 7-bit significand). -/ structure BFloatTypeRef extends TypeRef where is_bfloat_type : toTypeRef.typeID = TypeID.bfloat instance : Coe BFloatTypeRef TypeRef := ⟨(·.toTypeRef)⟩ /-- Get a reference to the `bfloat` type of the current context. -/ @[extern "papyrus_get_bfloat_type"] constant BFloatTypeRef.get : LlvmM BFloatTypeRef /-- A reference to an external LLVM `float` type, which is an IEEE single-precision (32-bit) floating point type. -/ structure FloatTypeRef extends TypeRef where is_float_type : toTypeRef.typeID = TypeID.float instance : Coe FloatTypeRef TypeRef := ⟨(·.toTypeRef)⟩ /-- Get a reference to the `float` type of the current context. -/ @[extern "papyrus_get_float_type"] constant FloatTypeRef.get : LlvmM FloatTypeRef /-- A reference to an external LLVM `float` type, which is an IEEE double-precision (64-bit) floating point type. -/ structure DoubleTypeRef extends TypeRef where is_double_type : toTypeRef.typeID = TypeID.double instance : Coe DoubleTypeRef TypeRef := ⟨(·.toTypeRef)⟩ /-- Get a reference to the `double` type of the current context. -/ @[extern "papyrus_get_double_type"] constant DoubleTypeRef.get : LlvmM DoubleTypeRef /-- A reference to an external LLVM `x86_fp80` type, which is an Intel X87 80-bit floating point type. -/ structure X86FP80TypeRef extends TypeRef where is_x86FP80_type : toTypeRef.typeID = TypeID.x86FP80 instance : Coe X86FP80TypeRef TypeRef := ⟨(·.toTypeRef)⟩ /-- Get a reference to the `x86_fp80` type of the current context. -/ @[extern "papyrus_get_x86_fp80_type"] constant X86FP80TypeRef.get : LlvmM X86FP80TypeRef /-- A reference to an external LLVM `fp128` type, which is an IEEE quadruple-precision (128-bit) floating point type. -/ structure FP128TypeRef extends TypeRef where is_fp128_type : toTypeRef.typeID = TypeID.fp128 instance : Coe FP128TypeRef TypeRef := ⟨(·.toTypeRef)⟩ /-- Get a reference to the `fp128` type of the current context. -/ @[extern "papyrus_get_fp128_type"] constant FP128TypeRef.get : LlvmM FP128TypeRef /-- A reference to an external LLVM `ppc_fp128` type, which is a PowerPC 128-bit floating point type. -/ structure PPCFP128TypeRef extends TypeRef where is_ppcFP128_type : toTypeRef.typeID = TypeID.ppcFP128 instance : Coe PPCFP128TypeRef TypeRef := ⟨(·.toTypeRef)⟩ /-- Get a reference to the `ppc_fp128` type of the current context. -/ @[extern "papyrus_get_ppc_fp128_type"] constant PPCFP128TypeRef.get : LlvmM PPCFP128TypeRef -------------------------------------------------------------------------------- -- Integer Type References -------------------------------------------------------------------------------- /-- A reference to an external LLVM [IntegerType](https://llvm.org/doxygen/classllvm_1_1IntegerType.html). -/ structure IntegerTypeRef extends TypeRef where is_integer_type : toTypeRef.typeID = TypeID.integer instance : Coe IntegerTypeRef TypeRef := ⟨(·.toTypeRef)⟩ namespace IntegerTypeRef /-- Cast a general `TypeRef` to a `IntegerTypeRef` given proof it is one. -/ def cast (type : TypeRef) (h : type.typeID = TypeID.integer) := mk type h /-- Minimum bit width of an LLVM integer type. -/ def MIN_INT_BITS : UInt32 := 1 /-- Maximum bit width of an LLVM integer type. -/ def MAX_INT_BITS : UInt32 := 16777215 -- (1 <<< 24) - 1 /-- Holds if the given bit width is valid for an LLVM integer type. -/ def isValidBitWidth (bitWidth : UInt32) : Prop := bitWidth ≥ MIN_INT_BITS ∧ bitWidth ≤ MAX_INT_BITS /-- Get a reference to the LLVM integer type of the given width. It is the user's responsible to ensure that the bit width of the type falls within LLVM's requirements (i.e., that `isValidBitWidth numBits` holds). -/ @[extern "papyrus_get_integer_type"] constant get (numBits : @& UInt32) : LlvmM IntegerTypeRef /-- Get the width in bits of this type. -/ @[extern "papyrus_integer_type_get_bit_width"] constant getBitWidth (self : @& IntegerTypeRef) : IO UInt32 end IntegerTypeRef -------------------------------------------------------------------------------- -- Function Type References -------------------------------------------------------------------------------- /-- A reference to an external LLVM [FunctionType](https://llvm.org/doxygen/classllvm_1_1FunctionType.html). -/ structure FunctionTypeRef extends TypeRef where is_function_type : toTypeRef.typeID = TypeID.function instance : Coe FunctionTypeRef TypeRef := ⟨(·.toTypeRef)⟩ namespace FunctionTypeRef /-- Cast a general `TypeRef` to a `FunctionTypeRef` given proof it is one. -/ def cast (type : TypeRef) (h : type.typeID = TypeID.function) : FunctionTypeRef := {toTypeRef := type, is_function_type := h} /-- Get a reference to the LLVM function type with the given result and parameter types. It is the user's responsibility to ensure that they are valid. -/ @[extern "papyrus_get_function_type"] constant get (result : @& TypeRef) (params : @& Array TypeRef) (isVarArg := false) : IO FunctionTypeRef /-- Get a reference to the return type of this function type. -/ @[extern "papyrus_function_type_get_return_type"] constant getReturnType (self : @& FunctionTypeRef) : IO TypeRef /-- Get an array of references to the parameter types of this function type. -/ @[extern "papyrus_function_type_get_parameter_types"] constant getParameterTypes (self : @& FunctionTypeRef) : IO (Array TypeRef) /-- Get whether this function type accepts variable arguments. -/ @[extern "papyrus_function_type_is_var_arg"] constant isVarArg (self : @& FunctionTypeRef) : IO Bool end FunctionTypeRef -------------------------------------------------------------------------------- -- Pointer Type References -------------------------------------------------------------------------------- /-- A reference to an external LLVM [PointerType](https://llvm.org/doxygen/classllvm_1_1PointerType.html). -/ structure PointerTypeRef extends TypeRef where is_pointer_type : toTypeRef.typeID = TypeID.pointer instance : Coe PointerTypeRef TypeRef := ⟨(·.toTypeRef)⟩ namespace PointerTypeRef /-- Cast a general `TypeRef` to a `FunctionTypeRef` given proof it is one. -/ def cast (type : TypeRef) (h : type.typeID = TypeID.pointer) := mk type h /-- Get a reference to the LLVM pointer type of the given pointee type in the given address space. It is the user's responsibility to ensure they are valid. -/ @[extern "papyrus_get_pointer_type"] constant get (pointeeType : @& TypeRef) (addrSpace := AddressSpace.default) : IO PointerTypeRef /-- Get a reference to the type pointed to by this type. -/ @[extern "papyrus_pointer_type_get_pointee_type"] constant getPointeeType (self : @& PointerTypeRef) : IO TypeRef /-- Get the address space of this pointer type. -/ @[extern "papyrus_pointer_type_get_address_space"] constant getAddressSpace (self : @& PointerTypeRef) : IO AddressSpace end PointerTypeRef -------------------------------------------------------------------------------- -- Struct Type References -------------------------------------------------------------------------------- /-- A reference to an external LLVM [StructType](https://llvm.org/doxygen/classllvm_1_1StructType.html). -/ structure StructTypeRef extends TypeRef where is_struct_type : toTypeRef.typeID = TypeID.struct instance : Coe StructTypeRef TypeRef := ⟨(·.toTypeRef)⟩ namespace StructTypeRef /-- Cast a general `TypeRef` to a `StructTypeRef` given proof it is one. -/ def cast (type : TypeRef) (h : type.typeID = TypeID.struct) := mk type h /-- Get whether this struct type is literal. -/ @[extern "papyrus_struct_type_is_literal"] constant isLiteral (self : @& StructTypeRef) : Bool /-- Get whether this struct type is non-literal and opaque. -/ @[extern "papyrus_struct_type_is_opaque"] constant isOpaque (self : @& StructTypeRef) : IO Bool /-- Get an array of references to the element types of this *non-opaque* struct type. -/ @[extern "papyrus_struct_type_get_element_types"] constant getElementTypes (self : @& StructTypeRef) : IO (Array TypeRef) /-- Get whether this struct type is non-opaque and packed. -/ @[extern "papyrus_struct_type_is_packed"] constant isPacked (self : @& StructTypeRef) : IO Bool end StructTypeRef -- # Literal Struct Types /-- A reference to an external LLVM literal [StructType](https://llvm.org/doxygen/classllvm_1_1StructType.html). Literal struct types (e.g., `{ i32, i32 }`) are uniqued structurally, and must always have a body when created. -/ structure LiteralStructTypeRef extends StructTypeRef where is_literal : toStructTypeRef.isLiteral = true instance : Coe LiteralStructTypeRef StructTypeRef := ⟨(·.toStructTypeRef)⟩ namespace LiteralStructTypeRef /-- Cast a general `StructTypeRef` to a `LiteralStructTypeRef` given proof it is one. -/ def cast (type : StructTypeRef) (h : type.isLiteral = true) := mk type h /-- Get a reference to the LLVM literal struct type of with the given element types and packing. It is the user's responsibility to ensure they are valid. -/ @[extern "papyrus_get_literal_struct_type"] constant get (elemTypes : @& Array TypeRef) (isPacked := false) : LlvmM LiteralStructTypeRef end LiteralStructTypeRef -- # Identified Struct Types /-- A reference to an external LLVM identified [StructType](https://llvm.org/doxygen/classllvm_1_1StructType.html). Identified structs may optionally have a name and are not uniqued. The names for identified structs are managed at the context level, so there can only be a single identified struct with a given name in a particular context. Identified structs may also optionally be opaque (have no body specified). -/ structure IdentifiedStructTypeRef extends StructTypeRef where is_identified : toStructTypeRef.isLiteral ≠ true instance : Coe IdentifiedStructTypeRef StructTypeRef := ⟨(·.toStructTypeRef)⟩ namespace IdentifiedStructTypeRef /-- Cast a general `StructTypeRef` to a `IdentifiedStructTypeRef` given proof it is one. -/ def cast (type : StructTypeRef) (h : type.isLiteral ≠ true) := mk type h /-- Get the struct type with the given name (if it exists). -/ @[extern "papyrus_struct_type_get_type_by_name"] constant getTypeByName? (name : String) : LlvmM (Option IdentifiedStructTypeRef) /-- Create a new struct type with the given name, element types, and packing. It is the user's responsibility to ensure they are valid. Passing the empty name string will leave the type unnamed. -/ @[extern "papyrus_struct_type_create"] constant create (name : @& String) (elementTypes : @& Array TypeRef) (packed := false) : LlvmM IdentifiedStructTypeRef /-- Get the struct type with the given name or create one if none exists. If one exists, it will *NOT* be verified to have the provided structure. -/ def getOrCreate (name : String) (elementTypes : @& Array TypeRef) (packed := false) : LlvmM IdentifiedStructTypeRef := do match (← getTypeByName? name) with | none => create name elementTypes packed | some ty => ty /-- Create a new opaque struct type with the given name (or none if the name string is empty). -/ @[extern "papyrus_opaque_struct_type_create"] constant createOpaque (name : @& String) : LlvmM IdentifiedStructTypeRef /-- Get the struct type with the given name or create a new opaque one if none exists. If one exists, it will *NOT* be verified to be opaque. -/ def getOrCreateOpaque (name : String) : LlvmM IdentifiedStructTypeRef := do match (← getTypeByName? name) with | none => createOpaque name | some ty => ty /-- Get the name of this struct type (or the empty string if none). -/ @[extern "papyrus_struct_type_get_name"] constant getName (self : @& IdentifiedStructTypeRef) : IO String /-- Set the name of this struct type. Passing the empty string will remove the type's name. The name may also have a suffix appended if it a collides with another in the same context. -/ @[extern "papyrus_struct_type_set_name"] constant setName (name : @& String) (self : @& IdentifiedStructTypeRef) : IO PUnit /-- Removes the name of this struct type. -/ def removeName (self : IdentifiedStructTypeRef) := setName "" self /-- Set the body of this *opaque* struct type, making it a now a complete struct type. -/ @[extern "papyrus_opaque_struct_type_set_body"] constant setBody (elemTypes : @& Array TypeRef) (self : @& IdentifiedStructTypeRef) (isPacked := false) : IO PUnit end IdentifiedStructTypeRef -------------------------------------------------------------------------------- -- Array Type Reference -------------------------------------------------------------------------------- /-- A reference to an external LLVM [ArrayType](https://llvm.org/doxygen/classllvm_1_1ArrayType.html). -/ structure ArrayTypeRef extends TypeRef where is_array_type : toTypeRef.typeID = TypeID.array instance : Coe ArrayTypeRef TypeRef := ⟨(·.toTypeRef)⟩ namespace ArrayTypeRef /-- Cast a general `TypeRef` to a `ArrayTypeRef` given proof it is one. -/ def cast (type : TypeRef) (h : type.typeID = TypeID.array) := mk type h /-- Get a reference to the LLVM array type of the given element type with the given number of elements. It is the user's responsibility to ensure they are valid. -/ @[extern "papyrus_get_array_type"] constant get (elemType : @& TypeRef) (numElems : UInt64) : IO ArrayTypeRef /-- Get a reference to the element type of this array type. -/ @[extern "papyrus_array_type_get_element_type"] constant getElementType (self : @& ArrayTypeRef) : IO TypeRef /-- Get the number of elements in this array type . -/ @[extern "papyrus_array_type_get_num_elements"] constant getSize (self : @& ArrayTypeRef) : IO UInt64 end ArrayTypeRef -------------------------------------------------------------------------------- -- Vector Type References -------------------------------------------------------------------------------- /-- A reference to an external LLVM [VectorType](https://llvm.org/doxygen/classllvm_1_1VectorType.html). -/ structure VectorTypeRef extends TypeRef where is_vector_type : toTypeRef.typeID = TypeID.fixedVector ∨ toTypeRef.typeID = TypeID.scalableVector instance : Coe VectorTypeRef TypeRef := ⟨(·.toTypeRef)⟩ namespace VectorTypeRef /-- Cast a general `TypeRef` to a `VectorTypeRef` given proof it is one. -/ def cast (type : TypeRef) (h) := mk type h /-- Get a reference to the element type of this vector type. -/ @[extern "papyrus_vector_type_get_element_type"] constant getElementType (self : @& VectorTypeRef) : IO TypeRef /-- Get the minimum number of elements of this vector type. For non-scalable vectors, this is exactly this number of elements. For scalable vectors, there is a runtime multiple of this number. -/ @[extern "papyrus_vector_type_get_element_quantity"] constant getMinSize (self : @& VectorTypeRef) : IO UInt32 /-- Get whether this vector type is scalable. -/ def isScalable (self : @& VectorTypeRef) : Bool := self.typeID = TypeID.scalableVector end VectorTypeRef -- # Fixed Vector Types /-- A reference to an external LLVM [FixedVectorType](https://llvm.org/doxygen/classllvm_1_1FixedVectorType.html). -/ structure FixedVectorTypeRef extends VectorTypeRef where is_fixed_vector_type : toTypeRef.typeID = TypeID.fixedVector is_vector_type := Or.inl is_fixed_vector_type instance : Coe FixedVectorTypeRef VectorTypeRef := ⟨(·.toVectorTypeRef)⟩ namespace FixedVectorTypeRef /-- Cast a general `TypeRef` to a `FixedVectorTypeRef` given proof it is one. -/ def cast (type : TypeRef) (h : type.typeID = TypeID.fixedVector) : FixedVectorTypeRef := {toTypeRef := type, is_fixed_vector_type := h} /-- Get a reference to the fixed LLVM vector type of the given element type and number of elements. It is the user's responsibility to ensure they are valid. -/ @[extern "papyrus_get_fixed_vector_type"] constant get (elemType : TypeRef) (numElems : UInt32) : IO FixedVectorTypeRef /-- Get the number of elements in this vector type. -/ def getSize (self : @& FixedVectorTypeRef) := VectorTypeRef.getMinSize self end FixedVectorTypeRef -- # Scalable Vector Types /-- A reference to an external LLVM [ScalableVectorType](https://llvm.org/doxygen/classllvm_1_1ScalableVectorType.html). -/ structure ScalableVectorTypeRef extends VectorTypeRef where is_scalable_vector_type : toTypeRef.typeID = TypeID.scalableVector is_vector_type := Or.inr is_scalable_vector_type instance : Coe ScalableVectorTypeRef VectorTypeRef := ⟨(·.toVectorTypeRef)⟩ namespace ScalableVectorTypeRef /-- Cast a general `TypeRef` to a `ScalableVectorTypeRef` given proof it is one. -/ def cast (type : TypeRef) (h : type.typeID = TypeID.scalableVector) : ScalableVectorTypeRef := {toTypeRef := type, is_scalable_vector_type := h} /-- Get a reference to the scalable LLVM vector type of the given element type and minimum number of elements. It is the user's responsibility to ensure they are valid. -/ @[extern "papyrus_get_scalable_vector_type"] constant get (elemType : TypeRef) (minNumElems : UInt32) : IO ScalableVectorTypeRef end ScalableVectorTypeRef namespace VectorTypeRef /-- Get a reference to the LLVM vector type of the given element type, element quantity, and scalability. It is the user's responsibility to ensure they are valid. -/ def get (elemType : @& TypeRef) (elemQuant : UInt32) (isScalable := false) : IO VectorTypeRef := if isScalable then ScalableVectorTypeRef.get elemType elemQuant else FixedVectorTypeRef.get elemType elemQuant end VectorTypeRef
aa162aa4d79480cc83beaac2d4ef4f941c4df4ef
9dc8cecdf3c4634764a18254e94d43da07142918
/src/data/nat/basic.lean
e1eaeba817a194b28fa0fe4114143116f3e6c41f
[ "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
66,697
lean
/- Copyright (c) 2014 Floris van Doorn (c) 2016 Microsoft Corporation. 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 algebra.order.ring import algebra.order.with_zero /-! # Basic operations on the natural numbers This file contains: - instances on the natural numbers - some basic lemmas about natural numbers - extra recursors: * `le_rec_on`, `le_induction`: recursion and induction principles starting at non-zero numbers * `decreasing_induction`: recursion growing downwards * `le_rec_on'`, `decreasing_induction'`: versions with slightly weaker assumptions * `strong_rec'`: recursion based on strong inequalities - decidability instances on predicates about the natural numbers -/ universes u v /-! ### instances -/ instance : nontrivial ℕ := ⟨⟨0, 1, nat.zero_ne_one⟩⟩ instance : comm_semiring ℕ := { 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, nat_cast := λ n, n, nat_cast_zero := rfl, nat_cast_succ := λ n, rfl, nsmul := λ m n, m * n, nsmul_zero' := nat.zero_mul, nsmul_succ' := λ n x, by rw [nat.succ_eq_add_one, nat.add_comm, nat.right_distrib, nat.one_mul] } instance : linear_ordered_comm_semiring ℕ := { lt := nat.lt, add_le_add_left := @nat.add_le_add_left, le_of_add_le_add_left := @nat.le_of_add_le_add_left, zero_le_one := nat.le_of_lt (nat.zero_lt_succ 0), 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_eq := nat.decidable_eq, exists_pair_ne := ⟨0, 1, ne_of_lt nat.zero_lt_one⟩, ..nat.comm_semiring, ..nat.linear_order } instance : linear_ordered_comm_monoid_with_zero ℕ := { mul_le_mul_left := λ a b h c, nat.mul_le_mul_left c h, ..nat.linear_ordered_comm_semiring, ..(infer_instance : comm_monoid_with_zero ℕ)} /-! Extra instances to short-circuit type class resolution -/ instance : add_comm_monoid ℕ := infer_instance instance : add_monoid ℕ := infer_instance instance : monoid ℕ := infer_instance instance : comm_monoid ℕ := infer_instance instance : comm_semigroup ℕ := infer_instance instance : semigroup ℕ := infer_instance instance : add_comm_semigroup ℕ := infer_instance instance : add_semigroup ℕ := infer_instance instance : distrib ℕ := infer_instance instance : semiring ℕ := infer_instance instance : ordered_semiring ℕ := infer_instance instance : ordered_comm_semiring ℕ := infer_instance instance : linear_ordered_cancel_add_comm_monoid ℕ := infer_instance instance nat.order_bot : order_bot ℕ := { bot := 0, bot_le := nat.zero_le } instance : canonically_ordered_comm_semiring ℕ := { exists_add_of_le := λ a b h, (nat.le.dest h).imp $ λ _, eq.symm, le_self_add := nat.le_add_right, eq_zero_or_eq_zero_of_mul_eq_zero := λ a b, nat.eq_zero_of_mul_eq_zero, .. nat.nontrivial, .. nat.order_bot, .. (infer_instance : ordered_add_comm_monoid ℕ), .. (infer_instance : linear_ordered_semiring ℕ), .. (infer_instance : comm_semiring ℕ) } instance : canonically_linear_ordered_add_monoid ℕ := { .. (infer_instance : canonically_ordered_add_monoid ℕ), .. nat.linear_order } instance nat.subtype.order_bot (s : set ℕ) [decidable_pred (∈ s)] [h : nonempty s] : order_bot s := { bot := ⟨nat.find (nonempty_subtype.1 h), nat.find_spec (nonempty_subtype.1 h)⟩, bot_le := λ x, nat.find_min' _ x.2 } instance nat.subtype.semilattice_sup (s : set ℕ) : semilattice_sup s := { ..subtype.linear_order s, ..linear_order.to_lattice } lemma nat.subtype.coe_bot {s : set ℕ} [decidable_pred (∈ s)] [h : nonempty s] : ((⊥ : s) : ℕ) = nat.find (nonempty_subtype.1 h) := rfl protected lemma nat.nsmul_eq_mul (m n : ℕ) : m • n = m * n := rfl theorem nat.eq_of_mul_eq_mul_right {n m k : ℕ} (Hm : 0 < m) (H : n * m = k * m) : n = k := by rw [mul_comm n m, mul_comm k m] at H; exact nat.eq_of_mul_eq_mul_left Hm H instance nat.cancel_comm_monoid_with_zero : cancel_comm_monoid_with_zero ℕ := { mul_left_cancel_of_ne_zero := λ _ _ _ h1 h2, nat.eq_of_mul_eq_mul_left (nat.pos_of_ne_zero h1) h2, mul_right_cancel_of_ne_zero := λ _ _ _ h1 h2, nat.eq_of_mul_eq_mul_right (nat.pos_of_ne_zero h1) h2, .. (infer_instance : comm_monoid_with_zero ℕ) } attribute [simp] nat.not_lt_zero nat.succ_ne_zero nat.succ_ne_self nat.zero_ne_one nat.one_ne_zero nat.zero_ne_bit1 nat.bit1_ne_zero nat.bit0_ne_one nat.one_ne_bit0 nat.bit0_ne_bit1 nat.bit1_ne_bit0 variables {m n k : ℕ} namespace nat /-! ### Recursion and `set.range` -/ section set open set theorem zero_union_range_succ : {0} ∪ range succ = univ := by { ext n, cases n; simp } variables {α : Type*} theorem range_of_succ (f : ℕ → α) : {f 0} ∪ range (f ∘ succ) = range f := by rw [← image_singleton, range_comp, ← image_union, zero_union_range_succ, image_univ] theorem range_rec {α : Type*} (x : α) (f : ℕ → α → α) : (set.range (λ n, nat.rec x f n) : set α) = {x} ∪ set.range (λ n, nat.rec (f 0 x) (f ∘ succ) n) := begin convert (range_of_succ _).symm, ext n, induction n with n ihn, { refl }, { dsimp at ihn ⊢, rw ihn } end theorem range_cases_on {α : Type*} (x : α) (f : ℕ → α) : (set.range (λ n, nat.cases_on n x f) : set α) = {x} ∪ set.range f := (range_of_succ _).symm end set /-! ### The units of the natural numbers as a `monoid` and `add_monoid` -/ theorem units_eq_one (u : ℕˣ) : u = 1 := units.ext $ nat.eq_one_of_dvd_one ⟨u.inv, u.val_inv.symm⟩ theorem add_units_eq_zero (u : add_units ℕ) : u = 0 := add_units.ext $ (nat.eq_zero_of_add_eq_zero u.val_neg).1 @[simp] protected theorem is_unit_iff {n : ℕ} : is_unit n ↔ n = 1 := iff.intro (λ ⟨u, hu⟩, match n, u, hu, nat.units_eq_one u with _, _, rfl, rfl := rfl end) (λ h, h.symm ▸ ⟨1, rfl⟩) instance unique_units : unique ℕˣ := { default := 1, uniq := nat.units_eq_one } instance unique_add_units : unique (add_units ℕ) := { default := 0, uniq := nat.add_units_eq_zero } /-! ### Equalities and inequalities involving zero and one -/ lemma one_le_iff_ne_zero {n : ℕ} : 1 ≤ n ↔ n ≠ 0 := (show 1 ≤ n ↔ 0 < n, from iff.rfl).trans pos_iff_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 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 := add_right_eq_self.mp $ le_antisymm ((two_mul a).symm.trans_le h) le_add_self 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 zero_max {m : ℕ} : max 0 m = m := max_eq_right (zero_le _) @[simp] lemma min_eq_zero_iff {m n : ℕ} : min m n = 0 ↔ m = 0 ∨ n = 0 := begin split, { intro h, cases le_total n m with H H, { simpa [H] using or.inr h }, { simpa [H] using or.inl h } }, { rintro (rfl|rfl); simp } end @[simp] lemma max_eq_zero_iff {m n : ℕ} : max m n = 0 ↔ m = 0 ∧ n = 0 := begin split, { intro h, cases le_total n m with H H, { simp only [H, max_eq_left] at h, exact ⟨h, le_antisymm (H.trans h.le) (zero_le _)⟩ }, { simp only [H, max_eq_right] at h, exact ⟨le_antisymm (H.trans h.le) (zero_le _), h⟩ } }, { rintro ⟨rfl, rfl⟩, simp } end lemma add_eq_max_iff {n m : ℕ} : n + m = max n m ↔ n = 0 ∨ m = 0 := begin rw ←min_eq_zero_iff, cases le_total n m with H H; simp [H] end lemma add_eq_min_iff {n m : ℕ} : n + m = min n m ↔ n = 0 ∧ m = 0 := begin rw ←max_eq_zero_iff, cases le_total n m with H H; simp [H] end lemma one_le_of_lt {n m : ℕ} (h : n < m) : 1 ≤ m := lt_of_le_of_lt (nat.zero_le _) h theorem eq_one_of_mul_eq_one_right {m n : ℕ} (H : m * n = 1) : m = 1 := eq_one_of_dvd_one ⟨n, H.symm⟩ theorem eq_one_of_mul_eq_one_left {m n : ℕ} (H : m * n = 1) : n = 1 := eq_one_of_mul_eq_one_right (by rwa mul_comm) /-! ### `succ` -/ lemma _root_.has_lt.lt.nat_succ_le {n m : ℕ} (h : n < m) : succ n ≤ m := succ_le_of_lt h lemma succ_eq_one_add (n : ℕ) : n.succ = 1 + n := by rw [nat.succ_eq_add_one, nat.add_comm] 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)) lemma eq_of_le_of_lt_succ {n m : ℕ} (h₁ : n ≤ m) (h₂ : m < n + 1) : m = n := nat.le_antisymm (le_of_succ_le_succ h₂) h₁ theorem one_add (n : ℕ) : 1 + n = succ n := by simp [add_comm] @[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_injective : function.injective nat.succ := λ x y, succ.inj lemma succ_ne_succ {n m : ℕ} : succ n ≠ succ m ↔ n ≠ m := succ_injective.ne_iff @[simp] lemma succ_succ_ne_one (n : ℕ) : n.succ.succ ≠ 1 := succ_ne_succ.mpr n.succ_ne_zero @[simp] lemma one_lt_succ_succ (n : ℕ) : 1 < n.succ.succ := succ_lt_succ $ succ_pos n lemma two_le_iff : ∀ n, 2 ≤ n ↔ n ≠ 0 ∧ n ≠ 1 | 0 := by simp | 1 := by simp | (n+2) := by simp theorem succ_le_succ_iff {m n : ℕ} : succ m ≤ succ n ↔ m ≤ n := ⟨le_of_succ_le_succ, succ_le_succ⟩ 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 := ⟨le_of_lt_succ, lt_succ_of_le⟩ 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 := H.lt_or_eq_dec.imp le_of_lt_succ id lemma succ_lt_succ_iff {m n : ℕ} : succ m < succ n ↔ m < n := ⟨lt_of_succ_lt_succ, succ_lt_succ⟩ @[simp] lemma lt_one_iff {n : ℕ} : n < 1 ↔ n = 0 := lt_succ_iff.trans le_zero_iff lemma div_le_iff_le_mul_add_pred {m n k : ℕ} (n0 : 0 < n) : m / n ≤ k ↔ m ≤ n * k + (n - 1) := begin rw [← lt_succ_iff, div_lt_iff_lt_mul n0, succ_mul, mul_comm], cases n, {cases n0}, exact lt_succ_iff, end lemma two_lt_of_ne : ∀ {n}, n ≠ 0 → n ≠ 1 → n ≠ 2 → 2 < n | 0 h _ _ := (h rfl).elim | 1 _ h _ := (h rfl).elim | 2 _ _ h := (h rfl).elim | (n+3) _ _ _ := dec_trivial theorem forall_lt_succ {P : ℕ → Prop} {n : ℕ} : (∀ m < n.succ, P m) ↔ (∀ m < n, P m) ∧ P n := ⟨λ H, ⟨λ m hm, H m (lt_succ_iff.2 hm.le), H n (lt_succ_self n)⟩, begin rintro ⟨H, hn⟩ m hm, rcases eq_or_lt_of_le (lt_succ_iff.1 hm) with rfl | hmn, { exact hn }, { exact H m hmn } end⟩ theorem exists_lt_succ {P : ℕ → Prop} {n : ℕ} : (∃ m < n.succ, P m) ↔ (∃ m < n, P m) ∨ P n := by { rw ←not_iff_not, push_neg, exact forall_lt_succ } /-! ### `add` -/ -- 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 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]⟩ 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 | 1 0 := dec_trivial | (a+2) _ := by rw add_right_comm; exact dec_trivial | _ (b+1) := by rw [← add_assoc]; simp only [nat.succ_inj', nat.succ_ne_zero]; simp theorem le_add_one_iff {i j : ℕ} : i ≤ j + 1 ↔ (i ≤ j ∨ i = j + 1) := ⟨λ 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 (λ h, le_trans h $ nat.le_add_right _ _) le_of_eq⟩ lemma le_and_le_add_one_iff {x a : ℕ} : a ≤ x ∧ x ≤ a + 1 ↔ x = a ∨ x = a + 1 := begin rw [le_add_one_iff, and_or_distrib_left, ←le_antisymm_iff, eq_comm, and_iff_right_of_imp], rintro rfl, exact a.le_succ, end lemma add_succ_lt_add {a b c d : ℕ} (hab : a < b) (hcd : c < d) : a + c + 1 < b + d := begin rw add_assoc, exact add_lt_add_of_lt_of_le hab (nat.succ_le_iff.2 hcd) end /-! ### `pred` -/ @[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 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 [← nat.sub_one, nat.sub_sub, one_add, sub_succ] 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] lemma pred_le_iff {n m : ℕ} : pred n ≤ m ↔ n ≤ succ m := ⟨le_succ_of_pred_le, by { cases n, { exact λ h, zero_le m }, exact le_of_succ_le_succ }⟩ /-! ### `sub` Most lemmas come from the `has_ordered_sub` instance on `ℕ`. -/ instance : has_ordered_sub ℕ := begin constructor, intros m n k, induction n with n ih generalizing k, { simp }, { simp only [sub_succ, add_succ, succ_add, ih, pred_le_iff] } end lemma lt_pred_iff {n m : ℕ} : n < pred m ↔ succ n < m := show n < m - 1 ↔ n + 1 < m, from lt_tsub_iff_right lemma lt_of_lt_pred {a b : ℕ} (h : a < b - 1) : a < b := lt_of_succ_lt (lt_pred_iff.1 h) lemma le_or_le_of_add_eq_add_pred {a b c d : ℕ} (h : c + d = a + b - 1) : a ≤ c ∨ b ≤ d := begin cases le_or_lt a c with h' h'; [left, right], { exact h', }, { replace h' := add_lt_add_right h' d, rw h at h', cases b.eq_zero_or_pos with hb hb, { rw hb, exact zero_le d, }, rw [a.add_sub_assoc hb, add_lt_add_iff_left] at h', exact nat.le_of_pred_lt h', }, end /-- A version of `nat.sub_succ` in the form `_ - 1` instead of `nat.pred _`. -/ lemma sub_succ' (a b : ℕ) : a - b.succ = a - b - 1 := rfl /-! ### `mul` -/ lemma succ_mul_pos (m : ℕ) (hn : 0 < n) : 0 < (succ m) * n := mul_pos (succ_pos m) hn theorem mul_self_le_mul_self {n m : ℕ} (h : n ≤ m) : n * n ≤ m * m := decidable.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 := decidable.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, le_imp_le_of_lt_imp_lt mul_self_lt_mul_self⟩ theorem mul_self_lt_mul_self_iff {n m : ℕ} : n < m ↔ n * n < m * m := le_iff_le_iff_lt_iff_lt.1 mul_self_le_mul_self_iff theorem le_mul_self : Π (n : ℕ), n ≤ n * n | 0 := le_rfl | (n+1) := by simp lemma le_mul_of_pos_left {m n : ℕ} (h : 0 < n) : m ≤ n * m := begin conv {to_lhs, rw [← one_mul(m)]}, exact decidable.mul_le_mul_of_nonneg_right h.nat_succ_le 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 decidable.mul_le_mul_of_nonneg_left h.nat_succ_le 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, mod_eq_of_lt]; 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], λ h, by simp only [h, mul_one]⟩ protected theorem mul_left_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_right_inj {a b c : ℕ} (ha : 0 < a) : a * b = a * c ↔ b = c := ⟨nat.eq_of_mul_eq_mul_left ha, λ e, e ▸ rfl⟩ lemma mul_left_injective {a : ℕ} (ha : 0 < a) : function.injective (λ x, x * a) := λ _ _, eq_of_mul_eq_mul_right ha lemma mul_right_injective {a : ℕ} (ha : 0 < a) : function.injective (λ x, a * x) := λ _ _, nat.eq_of_mul_eq_mul_left ha lemma mul_ne_mul_left {a b c : ℕ} (ha : 0 < a) : b * a ≠ c * a ↔ b ≠ c := (mul_left_injective ha).ne_iff lemma mul_ne_mul_right {a b c : ℕ} (ha : 0 < a) : a * b ≠ a * c ↔ b ≠ c := (mul_right_injective ha).ne_iff 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_right_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 decidable.le_iff_lt_or_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 lemma le_add_pred_of_pos (n : ℕ) {i : ℕ} (hi : i ≠ 0) : n ≤ i + (n - 1) := begin refine le_trans _ (add_tsub_le_assoc), simp [add_comm, nat.add_sub_assoc, one_le_iff_ne_zero.2 hi] end /-! ### Recursion and induction principles This section is here due to dependencies -- the lemmas here require some of the lemmas proved above, and some of the results in later sections depend on the definitions in this section. -/ @[simp] lemma rec_zero {C : ℕ → Sort u} (h0 : C 0) (h : ∀ n, C n → C (n + 1)) : (nat.rec h0 h : Π n, C n) 0 = h0 := rfl @[simp] lemma rec_add_one {C : ℕ → Sort u} (h0 : C 0) (h : ∀ n, C n → C (n + 1)) (n : ℕ) : (nat.rec h0 h : Π n, C n) (n + 1) = h n ((nat.rec h0 h : Π n, C n) n) := rfl /-- 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`. For a version where the assumption is only made when `k ≥ n`, see `le_rec_on'`. -/ @[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 (nat.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] 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 /-- 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) /-- Recursion principle based on `<` applied to some natural number. -/ @[elab_as_eliminator] def strong_rec_on' {P : ℕ → Sort*} (n : ℕ) (h : ∀ n, (∀ m, m < n → P m) → P n) : P n := nat.strong_rec' h n theorem strong_rec_on_beta' {P : ℕ → Sort*} {h} {n : ℕ} : (strong_rec_on' n h : P n) = h n (λ m hmn, (strong_rec_on' m h : P m)) := by { simp only [strong_rec_on'], rw nat.strong_rec' } /-- 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*`. For a version assuming only the assumption for `k < n`, see `decreasing_induction'`. -/ @[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'] } /-- Recursion principle on even and odd numbers: if we have `P 0`, and for all `i : ℕ` we can extend from `P i` to both `P (2 * i)` and `P (2 * i + 1)`, then we have `P n` for all `n : ℕ`. This is nothing more than a wrapper around `nat.binary_rec`, to avoid having to switch to dealing with `bit0` and `bit1`. -/ @[elab_as_eliminator] def even_odd_rec (n : ℕ) (P : ℕ → Sort*) (h0 : P 0) (h_even : ∀ i, P i → P (2 * i)) (h_odd : ∀ i, P i → P (2 * i + 1)) : P n := begin refine @binary_rec P h0 (λ b i hi, _) n, cases b, { simpa [bit, bit0_val i] using h_even i hi }, { simpa [bit, bit1_val i] using h_odd i hi }, end @[simp] lemma even_odd_rec_zero (P : ℕ → Sort*) (h0 : P 0) (h_even : ∀ i, P i → P (2 * i)) (h_odd : ∀ i, P i → P (2 * i + 1)) : @even_odd_rec 0 P h0 h_even h_odd = h0 := binary_rec_zero _ _ @[simp] lemma even_odd_rec_even (n : ℕ) (P : ℕ → Sort*) (h0 : P 0) (h_even : ∀ i, P i → P (2 * i)) (h_odd : ∀ i, P i → P (2 * i + 1)) (H : h_even 0 h0 = h0) : @even_odd_rec (2 * n) P h0 h_even h_odd = h_even n (even_odd_rec n P h0 h_even h_odd) := begin convert binary_rec_eq _ ff n, { exact (bit0_eq_two_mul _).symm }, { exact (bit0_eq_two_mul _).symm }, { apply heq_of_cast_eq, refl }, { exact H } end @[simp] lemma even_odd_rec_odd (n : ℕ) (P : ℕ → Sort*) (h0 : P 0) (h_even : ∀ i, P i → P (2 * i)) (h_odd : ∀ i, P i → P (2 * i + 1)) (H : h_even 0 h0 = h0) : @even_odd_rec (2 * n + 1) P h0 h_even h_odd = h_odd n (even_odd_rec n P h0 h_even h_odd) := begin convert binary_rec_eq _ tt n, { exact (bit0_eq_two_mul _).symm }, { exact (bit0_eq_two_mul _).symm }, { apply heq_of_cast_eq, refl }, { exact H } end /-- Given a predicate on two naturals `P : ℕ → ℕ → Prop`, `P a b` is true for all `a < b` if `P (a + 1) (a + 1)` is true for all `a`, `P 0 (b + 1)` is true for all `b` and for all `a < b`, `P (a + 1) b` is true and `P a (b + 1)` is true implies `P (a + 1) (b + 1)` is true. -/ @[elab_as_eliminator] lemma diag_induction (P : ℕ → ℕ → Prop) (ha : ∀ a, P (a + 1) (a + 1)) (hb : ∀ b, P 0 (b + 1)) (hd : ∀ a b, a < b → P (a + 1) b → P a (b + 1) → P (a + 1) (b + 1)) : ∀ a b, a < b → P a b | 0 (b + 1) h := hb _ | (a + 1) (b + 1) h := begin apply hd _ _ ((add_lt_add_iff_right _).1 h), { have : a + 1 = b ∨ a + 1 < b, { rwa [← le_iff_eq_or_lt, ← nat.lt_succ_iff] }, rcases this with rfl | _, { exact ha _ }, apply diag_induction (a + 1) b this }, apply diag_induction a (b + 1), apply lt_of_le_of_lt (nat.le_succ _) h, end using_well_founded { rel_tac := λ _ _, `[exact ⟨_, measure_wf (λ p, p.1 + p.2.1)⟩] } /-- Given `P : ℕ → ℕ → Sort*`, if for all `a b : ℕ` we can extend `P` from the rectangle strictly below `(a,b)` to `P a b`, then we have `P n m` for all `n m : ℕ`. Note that for non-`Prop` output it is preferable to use the equation compiler directly if possible, since this produces equation lemmas. -/ @[elab_as_eliminator] def strong_sub_recursion {P : ℕ → ℕ → Sort*} (H : ∀ a b, (∀ x y, x < a → y < b → P x y) → P a b) : Π (n m : ℕ), P n m | n m := H n m (λ x y hx hy, strong_sub_recursion x y) /-- Given `P : ℕ → ℕ → Sort*`, if we have `P i 0` and `P 0 i` for all `i : ℕ`, and for any `x y : ℕ` we can extend `P` from `(x,y+1)` and `(x+1,y)` to `(x+1,y+1)` then we have `P n m` for all `n m : ℕ`. Note that for non-`Prop` output it is preferable to use the equation compiler directly if possible, since this produces equation lemmas. -/ @[elab_as_eliminator] def pincer_recursion {P : ℕ → ℕ → Sort*} (Ha0 : ∀ a : ℕ, P a 0) (H0b : ∀ b : ℕ, P 0 b) (H : ∀ x y : ℕ, P x y.succ → P x.succ y → P x.succ y.succ) : ∀ (n m : ℕ), P n m | a 0 := Ha0 a | 0 b := H0b b | (nat.succ a) (nat.succ b) := H _ _ (pincer_recursion _ _) (pincer_recursion _ _) /-- Recursion starting at a non-zero number: given a map `C k → C (k+1)` for each `k ≥ n`, there is a map from `C n` to each `C m`, `n ≤ m`. -/ @[elab_as_eliminator] def le_rec_on' {C : ℕ → Sort*} {n : ℕ} : Π {m : ℕ}, n ≤ m → (Π ⦃k⦄, n ≤ k → C k → C (k+1)) → C n → C m | 0 H next x := eq.rec_on (nat.eq_zero_of_le_zero H) x | (m+1) H next x := or.by_cases (of_le_succ H) (λ h : n ≤ m, next h $ le_rec_on' h next x) (λ h : n = m + 1, eq.rec_on h x) /-- Decreasing induction: if `P (k+1)` implies `P k` for all `m ≤ k < n`, then `P n` implies `P m`. Also works for functions to `Sort*`. Weakens the assumptions of `decreasing_induction`. -/ @[elab_as_eliminator] def decreasing_induction' {P : ℕ → Sort*} {m n : ℕ} (h : ∀ k < n, m ≤ k → P (k+1) → P k) (mn : m ≤ n) (hP : P n) : P m := begin -- induction mn using nat.le_rec_on' generalizing h hP -- this doesn't work unfortunately refine le_rec_on' mn _ _ h hP; clear h hP mn n, { intros n mn ih h hP, apply ih, { exact λ k hk, h k hk.step }, { exact h n (lt_succ_self n) mn hP } }, { intros h hP, exact hP } end /-- A subset of `ℕ` containing `b : ℕ` and closed under `nat.succ` contains every `n ≥ b`. -/ lemma set_induction_bounded {b : ℕ} {S : set ℕ} (hb : b ∈ S) (h_ind: ∀ k : ℕ, k ∈ S → k + 1 ∈ S) {n : ℕ} (hbn : b ≤ n) : n ∈ S := @le_rec_on (λ n, n ∈ S) b n hbn h_ind hb /-- A subset of `ℕ` containing zero and closed under `nat.succ` contains all of `ℕ`. -/ lemma set_induction {S : set ℕ} (hb : 0 ∈ S) (h_ind: ∀ k : ℕ, k ∈ S → k + 1 ∈ S) (n : ℕ) : n ∈ S := set_induction_bounded hb h_ind (zero_le n) lemma set_eq_univ {S : set ℕ} : S = set.univ ↔ 0 ∈ S ∧ ∀ k : ℕ, k ∈ S → k + 1 ∈ S := ⟨by rintro rfl; simp, λ ⟨h0, hs⟩, set.eq_univ_of_forall (set_induction h0 hs)⟩ /-! ### `div` -/ attribute [simp] nat.div_self protected lemma div_le_of_le_mul' {m n : ℕ} {k} (h : m ≤ k * n) : m / k ≤ n := (nat.eq_zero_or_pos k).elim (λ k0, by rw [k0, nat.div_zero]; apply zero_le) (λ k0, (mul_le_mul_left k0).1 $ calc k * (m / k) ≤ m % k + k * (m / k) : nat.le_add_left _ _ ... = m : mod_add_div _ _ ... ≤ k * n : h) protected lemma div_le_self' (m n : ℕ) : m / n ≤ m := (nat.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 : nat.mul_le_mul_right _ n0) /-- A version of `nat.div_lt_self` using successors, rather than additional hypotheses. -/ lemma div_lt_self' (n b : ℕ) : (n+1)/(b+2) < n+1 := nat.div_lt_self (nat.succ_pos n) (nat.succ_lt_succ (nat.succ_pos _)) theorem le_div_iff_mul_le' {x y : ℕ} {k : ℕ} (k0 : 0 < k) : x ≤ y / k ↔ x * k ≤ y := le_div_iff_mul_le k0 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 lemma one_le_div_iff {a b : ℕ} (hb : 0 < b) : 1 ≤ a / b ↔ b ≤ a := by rw [le_div_iff_mul_le hb, one_mul] lemma div_lt_one_iff {a b : ℕ} (hb : 0 < b) : a / b < 1 ↔ a < b := lt_iff_lt_of_le_iff_le $ one_le_div_iff hb 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 : ℕ} : m / k < n / k → m < n := lt_imp_lt_of_le_imp_le $ λ h, nat.div_le_div_right h 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 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_right_inj hb, ← @add_left_cancel_iff _ _ (a % b), mod_add_div, mod_eq_of_lt h, mul_zero, add_zero]⟩ protected lemma div_eq_zero {a b : ℕ} (hb : a < b) : a / b = 0 := (nat.div_eq_zero_iff $ (zero_le a).trans_lt hb).mpr hb 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 nat.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_rfl 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 lemma lt_div_iff_mul_lt {n d : ℕ} (hnd : d ∣ n) (a : ℕ) : a < n / d ↔ d * a < n := begin rcases d.eq_zero_or_pos with rfl | hd0, { simp [zero_dvd_iff.mp hnd] }, rw [←mul_lt_mul_left hd0, ←nat.eq_mul_of_div_eq_right hnd rfl], end protected theorem mul_div_cancel_left' {a b : ℕ} (Hd : a ∣ b) : a * (b / a) = b := by rw [mul_comm,nat.div_mul_cancel Hd] /-- Alias of `nat.mul_div_mul` -/ --TODO: Update `nat.mul_div_mul` in the core? protected lemma mul_div_mul_left (a b : ℕ) {c : ℕ} (hc : 0 < c) : c * a / (c * b) = a / b := nat.mul_div_mul a b hc protected lemma mul_div_mul_right (a b : ℕ) {c : ℕ} (hc : 0 < c) : a * c / (b * c) = a / b := by rw [mul_comm, mul_comm b, a.mul_div_mul_left b hc] lemma lt_div_mul_add {a b : ℕ} (hb : 0 < b) : a < a/b*b + b := begin rw [←nat.succ_mul, ←nat.div_lt_iff_lt_mul hb], exact nat.lt_succ_self _, end lemma div_eq_iff_eq_of_dvd_dvd {n x y : ℕ} (hn : n ≠ 0) (hx : x ∣ n) (hy : y ∣ n) : n / x = n / y ↔ x = y := begin split, { intros h, rw ←mul_right_inj' hn, apply nat.eq_mul_of_div_eq_left (dvd_mul_of_dvd_left hy x), rw [eq_comm, mul_comm, nat.mul_div_assoc _ hy], exact nat.eq_mul_of_div_eq_right hx h }, { intros h, rw h }, end lemma mul_div_mul_comm_of_dvd_dvd {a b c d : ℕ} (hac : c ∣ a) (hbd : d ∣ b) : a * b / (c * d) = a / c * (b / d) := begin rcases c.eq_zero_or_pos with rfl | hc0, { simp }, rcases d.eq_zero_or_pos with rfl | hd0, { simp }, obtain ⟨k1, rfl⟩ := hac, obtain ⟨k2, rfl⟩ := hbd, rw [mul_mul_mul_comm, nat.mul_div_cancel_left _ hc0, nat.mul_div_cancel_left _ hd0, nat.mul_div_cancel_left _ (mul_pos hc0 hd0)], end @[simp] protected lemma div_left_inj {a b d : ℕ} (hda : d ∣ a) (hdb : d ∣ b) : a / d = b / d ↔ a = b := begin refine ⟨λ h, _, congr_arg _⟩, rw [←nat.mul_div_cancel' hda, ←nat.mul_div_cancel' hdb, h], end /-! ### `mod`, `dvd` -/ lemma mod_eq_iff_lt {a b : ℕ} (h : b ≠ 0) : a % b = a ↔ a < b := begin cases b, contradiction, exact ⟨λ h, h.ge.trans_lt (mod_lt _ (succ_pos _)), mod_eq_of_lt⟩, end @[simp] lemma mod_succ_eq_iff_lt {a b : ℕ} : a % b.succ = a ↔ a < b.succ := mod_eq_iff_lt (succ_ne_zero _) lemma div_add_mod (m k : ℕ) : k * (m / k) + m % k = m := (nat.add_comm _ _).trans (mod_add_div _ _) lemma mod_add_div' (m k : ℕ) : m % k + (m / k) * k = m := by { rw mul_comm, exact mod_add_div _ _ } lemma div_add_mod' (m k : ℕ) : (m / k) * k + m % k = m := by { rw mul_comm, exact div_add_mod _ _ } 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, add_tsub_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_div_self : ∀ {a b : ℕ}, b ∣ a → 0 < a → a / (a / b) = b | a 0 h₁ h₂ := by rw [eq_zero_of_zero_dvd h₁, nat.div_zero, nat.div_zero] | 0 b h₁ h₂ := absurd h₂ dec_trivial | (a+1) (b+1) h₁ h₂ := (nat.mul_left_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₁] lemma mod_mul_right_div_self (a b c : ℕ) : a % (b * c) / b = (a / b) % c := begin rcases nat.eq_zero_or_pos b with rfl|hb, { simp }, rcases nat.eq_zero_or_pos c with rfl|hc, { simp }, conv_rhs { rw ← mod_add_div a (b * c) }, rw [mul_assoc, nat.add_mul_div_left _ _ hb, add_mul_mod_self_left, mod_eq_of_lt (nat.div_lt_of_lt_mul (mod_lt _ (mul_pos hb hc)))] end 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] @[simp] protected theorem dvd_one {n : ℕ} : n ∣ 1 ↔ n = 1 := ⟨eq_one_of_dvd_one, λ e, e.symm ▸ dvd_rfl⟩ 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 @[simp] protected theorem not_two_dvd_bit1 (n : ℕ) : ¬ 2 ∣ bit1 n := by { rw [bit1, nat.dvd_add_right two_dvd_bit0, nat.dvd_one], cc } /-- A natural number `m` divides the sum `m + n` if and only if `m` divides `n`.-/ @[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 `n`.-/ @[simp] protected lemma dvd_add_self_right {m n : ℕ} : m ∣ n + m ↔ m ∣ n := nat.dvd_add_left (dvd_refl m) -- TODO: update `nat.dvd_sub` in core lemma dvd_sub' {k m n : ℕ} (h₁ : k ∣ m) (h₂ : k ∣ n) : k ∣ m - n := begin cases le_total n m with H H, { exact dvd_sub H h₁ h₂ }, { rw tsub_eq_zero_iff_le.mpr H, exact dvd_zero k }, end lemma not_dvd_of_pos_of_lt {a b : ℕ} (h1 : 0 < b) (h2 : b < a) : ¬ a ∣ b := begin rintros ⟨c, rfl⟩, rcases nat.eq_zero_or_pos c with (rfl | hc), { exact lt_irrefl 0 h1 }, { exact not_lt.2 (le_mul_of_pos_right hc) h2 }, end 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_right_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_left_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 := by simp | 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)), ← add_tsub_add_eq_tsub_right a 1 b, add_comm (_ - _), add_assoc, tsub_add_cancel_of_le (succ_le_succ hb_le_a), add_comm 1] }, have wf : a - b < a + 1, from lt_succ_of_le tsub_le_self, rw [if_pos h₁, if_pos h₂, add_tsub_add_eq_tsub_right, ← tsub_add_eq_add_tsub hb_le_a, by exact have _ := wf, succ_div (a - b), add_tsub_add_eq_tsub_right], simp [dvd_iff, succ_eq_add_one, add_comm 1, add_assoc] }, { 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] lemma dvd_iff_div_mul_eq (n d : ℕ) : d ∣ n ↔ n / d * d = n := ⟨λ h, nat.div_mul_cancel h, λ h, dvd.intro_left (n / d) h⟩ lemma dvd_iff_le_div_mul (n d : ℕ) : d ∣ n ↔ n ≤ n / d * d := ((dvd_iff_div_mul_eq _ _).trans le_antisymm_iff).trans (and_iff_right (div_mul_le_self n d)) lemma dvd_iff_dvd_dvd (n d : ℕ) : d ∣ n ↔ ∀ k : ℕ, k ∣ d → k ∣ n := ⟨λ h k hkd, dvd_trans hkd h, λ h, h _ dvd_rfl⟩ @[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 := (nat.eq_zero_or_pos n).elim (λ n0, by simp [n0]) (λ npos, mod_eq_of_lt (mod_lt _ npos)) /-- If `a` and `b` are equal mod `c`, `a - b` is zero mod `c`. -/ lemma sub_mod_eq_zero_of_mod_eq {a b c : ℕ} (h : a % c = b % c) : (a - b) % c = 0 := by rw [←nat.mod_add_div a c, ←nat.mod_add_div b c, ←h, tsub_add_eq_tsub_tsub, add_tsub_cancel_left, ←mul_tsub, nat.mul_mod_right] @[simp] lemma one_mod (n : ℕ) : 1 % (n + 2) = 1 := nat.mod_eq_of_lt (add_lt_add_right n.succ_pos 1) lemma dvd_sub_mod (k : ℕ) : n ∣ (k - (k % n)) := ⟨k / n, tsub_eq_of_eq_add_rev (nat.mod_add_div k n).symm⟩ @[simp] theorem mod_add_mod (m n k : ℕ) : (m % n + k) % n = (m + k) % n := by have := (add_mul_mod_self_left (m % n + k) n (m / n)).symm; rwa [add_right_comm, mod_add_div] at this @[simp] theorem add_mod_mod (m n k : ℕ) : (m + n % k) % k = (m + n) % k := by rw [add_comm, mod_add_mod, add_comm] lemma add_mod (a b n : ℕ) : (a + b) % n = ((a % n) + (b % n)) % n := by rw [add_mod_mod, mod_add_mod] theorem add_mod_eq_add_mod_right {m n k : ℕ} (i : ℕ) (H : m % n = k % n) : (m + i) % n = (k + i) % n := by rw [← mod_add_mod, ← mod_add_mod k, H] theorem add_mod_eq_add_mod_left {m n k : ℕ} (i : ℕ) (H : m % n = k % n) : (i + m) % n = (i + k) % n := by rw [add_comm, add_mod_eq_add_mod_right _ H, add_comm] lemma add_mod_eq_ite {a b n : ℕ} : (a + b) % n = if n ≤ a % n + b % n then a % n + b % n - n else a % n + b % n := begin cases n, { simp }, rw nat.add_mod, split_ifs with h, { rw [nat.mod_eq_sub_mod h, nat.mod_eq_of_lt], exact (tsub_lt_iff_right h).mpr (nat.add_lt_add (a.mod_lt n.zero_lt_succ) (b.mod_lt n.zero_lt_succ)) }, { exact nat.mod_eq_of_lt (lt_of_not_ge h) } end lemma mul_mod (a b n : ℕ) : (a * b) % n = ((a % n) * (b % n)) % n := begin conv_lhs { rw [←mod_add_div a n, ←mod_add_div' b n, right_distrib, left_distrib, left_distrib, mul_assoc, mul_assoc, ←left_distrib n _ _, add_mul_mod_self_left, ← mul_assoc, add_mul_mod_self_right] } end 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 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⟩ @[simp] lemma dvd_div_iff {a b c : ℕ} (hbc : c ∣ b) : a ∣ b / c ↔ c * a ∣ b := ⟨λ h, mul_dvd_of_dvd_div hbc h, λ h, dvd_div_of_mul_dvd h⟩ lemma div_mul_div_comm {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 @[simp] lemma div_div_div_eq_div : ∀ {a b c : ℕ} (dvd : b ∣ a) (dvd2 : a ∣ c), (c / (a / b)) / b = c / a | 0 _ := by simp | (a + 1) 0 := λ _ dvd _, by simpa using dvd | (a + 1) (c + 1) := have a_split : a + 1 ≠ 0 := succ_ne_zero a, have c_split : c + 1 ≠ 0 := succ_ne_zero c, λ b dvd dvd2, begin rcases dvd2 with ⟨k, rfl⟩, rcases dvd with ⟨k2, pr⟩, have k2_nonzero : k2 ≠ 0 := λ k2_zero, by simpa [k2_zero] using pr, rw [nat.mul_div_cancel_left k (nat.pos_of_ne_zero a_split), pr, nat.mul_div_cancel_left k2 (nat.pos_of_ne_zero c_split), nat.mul_comm ((c + 1) * k2) k, ←nat.mul_assoc k (c + 1) k2, nat.mul_div_cancel _ (nat.pos_of_ne_zero k2_nonzero), nat.mul_div_cancel _ (nat.pos_of_ne_zero c_split)], end 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] /-- If a small natural number is divisible by a larger natural number, the small number is zero. -/ lemma eq_zero_of_dvd_of_lt {a b : ℕ} (w : a ∣ b) (h : b < a) : b = 0 := nat.eq_zero_of_dvd_of_div_eq_zero w ((nat.div_eq_zero_iff (lt_of_le_of_lt (zero_le b) h)).elim_right h) 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 (nat.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 lemma lt_iff_le_pred : ∀ {m n : ℕ}, 0 < n → (m < n ↔ m ≤ n - 1) | m (n+1) _ := lt_succ_iff lemma div_eq_sub_mod_div {m n : ℕ} : m / n = (m - m % n) / n := begin by_cases n0 : n = 0, { rw [n0, nat.div_zero, nat.div_zero] }, { rw [← mod_add_div m n] { occs := occurrences.pos [2] }, rw [add_tsub_cancel_left, mul_div_right _ (nat.pos_of_ne_zero n0)] } end lemma mul_div_le (m n : ℕ) : n * (m / n) ≤ m := begin cases nat.eq_zero_or_pos n with n0 h, { rw [n0, zero_mul], exact m.zero_le }, { rw [mul_comm, ← nat.le_div_iff_mul_le' h] }, end lemma lt_mul_div_succ (m : ℕ) {n : ℕ} (n0 : 0 < n) : m < n * ((m / n) + 1) := begin rw [mul_comm, ← nat.div_lt_iff_lt_mul' n0], exact lt_succ_self _ end @[simp] lemma mod_div_self (m n : ℕ) : m % n / n = 0 := begin cases n, { exact (m % 0).div_zero }, { exact nat.div_eq_zero (m.mod_lt n.succ_pos) } end /-- `n` is not divisible by `a` if it is between `a * k` and `a * (k + 1)` for some `k`. -/ lemma not_dvd_of_between_consec_multiples {n a k : ℕ} (h1 : a * k < n) (h2 : n < a * (k + 1)) : ¬ a ∣ n := begin rintro ⟨d, rfl⟩, exact monotone.ne_of_lt_of_lt_nat (covariant.monotone_of_const a) k h1 h2 d rfl, end /-- `n` is not divisible by `a` iff it is between `a * k` and `a * (k + 1)` for some `k`. -/ lemma not_dvd_iff_between_consec_multiples (n : ℕ) {a : ℕ} (ha : 0 < a) : (∃ k : ℕ, a * k < n ∧ n < a * (k + 1)) ↔ ¬ a ∣ n := begin refine ⟨λ ⟨k, hk1, hk2⟩, not_dvd_of_between_consec_multiples hk1 hk2, λ han, ⟨n/a, ⟨lt_of_le_of_ne (mul_div_le n a) _, lt_mul_div_succ _ ha⟩⟩⟩, exact mt (dvd.intro (n/a)) han, end /-- Two natural numbers are equal if and only if they have the same multiples. -/ lemma dvd_right_iff_eq {m n : ℕ} : (∀ a : ℕ, m ∣ a ↔ n ∣ a) ↔ m = n := ⟨λ h, dvd_antisymm ((h _).mpr dvd_rfl) ((h _).mp dvd_rfl), λ h n, by rw h⟩ /-- Two natural numbers are equal if and only if they have the same divisors. -/ lemma dvd_left_iff_eq {m n : ℕ} : (∀ a : ℕ, a ∣ m ↔ a ∣ n) ↔ m = n := ⟨λ h, dvd_antisymm ((h _).mp dvd_rfl) ((h _).mpr dvd_rfl), λ h n, by rw h⟩ /-- `dvd` is injective in the left argument -/ lemma dvd_left_injective : function.injective ((∣) : ℕ → ℕ → Prop) := λ m n h, dvd_right_iff_eq.mp $ λ a, iff_of_eq (congr_fun h a) lemma div_lt_div_of_lt_of_dvd {a b d : ℕ} (hdb : d ∣ b) (h : a < b) : a / d < b / d := by { rw nat.lt_div_iff_mul_lt hdb, exact lt_of_le_of_lt (mul_div_le a d) h } lemma mul_add_mod (a b c : ℕ) : (a * b + c) % b = c % b := by simp [nat.add_mod] lemma mul_add_mod_of_lt {a b c : ℕ} (h : c < b) : (a * b + c) % b = c := by rw [nat.mul_add_mod, nat.mod_eq_of_lt h] lemma pred_eq_self_iff {n : ℕ} : n.pred = n ↔ n = 0 := by { cases n; simp [(nat.succ_ne_self _).symm] } /-! ### `find` -/ section find variables {p q : ℕ → Prop} [decidable_pred p] [decidable_pred q] lemma find_eq_iff (h : ∃ n : ℕ, p n) : nat.find h = m ↔ p m ∧ ∀ n < m, ¬ p n := begin split, { rintro rfl, exact ⟨nat.find_spec h, λ _, nat.find_min h⟩ }, { rintro ⟨hm, hlt⟩, exact le_antisymm (nat.find_min' h hm) (not_lt.1 $ imp_not_comm.1 (hlt _) $ nat.find_spec h) } end @[simp] lemma find_lt_iff (h : ∃ n : ℕ, p n) (n : ℕ) : nat.find h < n ↔ ∃ m < n, p m := ⟨λ h2, ⟨nat.find h, h2, nat.find_spec h⟩, λ ⟨m, hmn, hm⟩, (nat.find_min' h hm).trans_lt hmn⟩ @[simp] lemma find_le_iff (h : ∃ n : ℕ, p n) (n : ℕ) : nat.find h ≤ n ↔ ∃ m ≤ n, p m := by simp only [exists_prop, ← lt_succ_iff, find_lt_iff] @[simp] lemma le_find_iff (h : ∃ (n : ℕ), p n) (n : ℕ) : n ≤ nat.find h ↔ ∀ m < n, ¬ p m := by simp_rw [← not_lt, find_lt_iff, not_exists] @[simp] lemma lt_find_iff (h : ∃ n : ℕ, p n) (n : ℕ) : n < nat.find h ↔ ∀ m ≤ n, ¬ p m := by simp only [← succ_le_iff, le_find_iff, succ_le_succ_iff] @[simp] lemma find_eq_zero (h : ∃ n : ℕ, p n) : nat.find h = 0 ↔ p 0 := by simp [find_eq_iff] @[simp] lemma find_pos (h : ∃ n : ℕ, p n) : 0 < nat.find h ↔ ¬ p 0 := by rw [pos_iff_ne_zero, ne, nat.find_eq_zero] theorem find_mono (h : ∀ n, q n → p n) {hp : ∃ n, p n} {hq : ∃ n, q n} : nat.find hp ≤ nat.find hq := nat.find_min' _ (h _ (nat.find_spec hq)) lemma find_le {h : ∃ n, p n} (hn : p n) : nat.find h ≤ n := (nat.find_le_iff _ _).2 ⟨n, le_rfl, hn⟩ lemma find_add {hₘ : ∃ m, p (m + n)} {hₙ : ∃ n, p n} (hn : n ≤ nat.find hₙ) : nat.find hₘ + n = nat.find hₙ := begin refine ((le_find_iff _ _).2 (λ m hm hpm, hm.not_le _)).antisymm _, { have hnm : n ≤ m := hn.trans (find_le hpm), refine add_le_of_le_tsub_right_of_le hnm (find_le _), rwa tsub_add_cancel_of_le hnm }, { rw ←tsub_le_iff_right, refine (le_find_iff _ _).2 (λ m hm hpm, hm.not_le _), rw tsub_le_iff_right, exact find_le hpm } end lemma find_comp_succ (h₁ : ∃ n, p n) (h₂ : ∃ n, p (n + 1)) (h0 : ¬ p 0) : nat.find h₁ = nat.find h₂ + 1 := begin refine (find_eq_iff _).2 ⟨nat.find_spec h₂, λ n hn, _⟩, cases n with n, exacts [h0, @nat.find_min (λ n, p (n + 1)) _ h₂ _ (succ_lt_succ_iff.1 hn)] end end find /-! ### `find_greatest` -/ 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 Q : ℕ → Prop} [decidable_pred P] {b : ℕ} @[simp] lemma find_greatest_zero : nat.find_greatest P 0 = 0 := rfl lemma find_greatest_succ (n : ℕ) : nat.find_greatest P (n + 1) = if P (n + 1) then n + 1 else nat.find_greatest P n := 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 (h : ¬ P (b + 1)) : nat.find_greatest P (b + 1) = nat.find_greatest P b := by simp [nat.find_greatest, h] lemma find_greatest_eq_iff : nat.find_greatest P b = m ↔ m ≤ b ∧ (m ≠ 0 → P m) ∧ (∀ ⦃n⦄, m < n → n ≤ b → ¬P n) := begin induction b with b ihb generalizing m, { rw [eq_comm, iff.comm], simp only [nonpos_iff_eq_zero, ne.def, and_iff_left_iff_imp, find_greatest_zero], rintro rfl, exact ⟨λ h, (h rfl).elim, λ n hlt heq, (hlt.ne heq.symm).elim⟩ }, { by_cases hb : P (b + 1), { rw [find_greatest_eq hb], split, { rintro rfl, exact ⟨le_rfl, λ _, hb, λ n hlt hle, (hlt.not_le hle).elim⟩ }, { rintros ⟨hle, h0, hm⟩, rcases decidable.eq_or_lt_of_le hle with rfl|hlt, exacts [rfl, (hm hlt le_rfl hb).elim] } }, { rw [find_greatest_of_not hb, ihb], split, { rintros ⟨hle, hP, hm⟩, refine ⟨hle.trans b.le_succ, hP, λ n hlt hle, _⟩, rcases decidable.eq_or_lt_of_le hle with rfl|hlt', exacts [hb, hm hlt $ lt_succ_iff.1 hlt'] }, { rintros ⟨hle, hP, hm⟩, refine ⟨lt_succ_iff.1 (hle.lt_of_ne _), hP, λ n hlt hle, hm hlt (hle.trans b.le_succ)⟩, rintro rfl, exact hb (hP b.succ_ne_zero) } } } end lemma find_greatest_eq_zero_iff : nat.find_greatest P b = 0 ↔ ∀ ⦃n⦄, 0 < n → n ≤ b → ¬P n := by simp [find_greatest_eq_iff] lemma find_greatest_spec (hmb : m ≤ b) (hm : P m) : P (nat.find_greatest P b) := begin by_cases h : nat.find_greatest P b = 0, { cases m, { rwa h }, exact ((find_greatest_eq_zero_iff.1 h) m.zero_lt_succ hmb hm).elim }, { exact (find_greatest_eq_iff.1 rfl).2.1 h } end lemma find_greatest_le (n : ℕ) : nat.find_greatest P n ≤ n := (find_greatest_eq_iff.1 rfl).1 lemma le_find_greatest (hmb : m ≤ b) (hm : P m) : m ≤ nat.find_greatest P b := le_of_not_lt $ λ hlt, (find_greatest_eq_iff.1 rfl).2.2 hlt hmb hm lemma find_greatest_mono_right (P : ℕ → Prop) [decidable_pred P] : monotone (nat.find_greatest P) := begin refine monotone_nat_of_le_succ (λ n, _), rw [find_greatest_succ], split_ifs, { exact (find_greatest_le n).trans (le_succ _) }, { refl } end lemma find_greatest_mono_left [decidable_pred Q] (hPQ : P ≤ Q) : nat.find_greatest P ≤ nat.find_greatest Q := begin intro n, induction n with n hn, { refl }, by_cases P (n + 1), { rw [find_greatest_eq h, find_greatest_eq (hPQ _ h)] }, { rw find_greatest_of_not h, exact hn.trans (nat.find_greatest_mono_right _ $ le_succ _) } end lemma find_greatest_mono {a b : ℕ} [decidable_pred Q] (hPQ : P ≤ Q) (hab : a ≤ b) : nat.find_greatest P a ≤ nat.find_greatest Q b := (nat.find_greatest_mono_right _ hab).trans $ find_greatest_mono_left hPQ _ lemma find_greatest_is_greatest (hk : nat.find_greatest P b < k) (hkb : k ≤ b) : ¬ P k := (find_greatest_eq_iff.1 rfl).2.2 hk hkb lemma find_greatest_of_ne_zero (h : nat.find_greatest P b = m) (h0 : m ≠ 0) : P m := (find_greatest_eq_iff.1 h).2.1 h0 end find_greatest /-! ### `bodd_div2` and `bodd` -/ @[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 /-! ### `bit0` and `bit1` -/ -- There is no need to prove `bit0_eq_zero : bit0 n = 0 ↔ n = 0` -- as this is true for any `[semiring R] [no_zero_divisors R] [char_zero R]` -- However the lemmas `bit0_eq_bit0`, `bit1_eq_bit1`, `bit1_eq_one`, `one_eq_bit1` -- need `[ring R] [no_zero_divisors R] [char_zero R]` in general, -- so we prove `ℕ` specialized versions here. @[simp] lemma bit0_eq_bit0 {m n : ℕ} : bit0 m = bit0 n ↔ m = n := ⟨nat.bit0_inj, λ h, by subst h⟩ @[simp] lemma bit1_eq_bit1 {m n : ℕ} : bit1 m = bit1 n ↔ m = n := ⟨nat.bit1_inj, λ h, by subst h⟩ @[simp] lemma bit1_eq_one {n : ℕ} : bit1 n = 1 ↔ n = 0 := ⟨@nat.bit1_inj n 0, λ h, by subst h⟩ @[simp] lemma one_eq_bit1 {n : ℕ} : 1 = bit1 n ↔ n = 0 := ⟨λ h, (@nat.bit1_inj 0 n h).symm, λ h, by subst h⟩ theorem bit_add : ∀ (b : bool) (n m : ℕ), bit b (n + m) = bit ff n + bit b m | tt := bit1_add | ff := bit0_add theorem bit_add' : ∀ (b : bool) (n m : ℕ), bit b (n + m) = bit b n + bit ff m | tt := bit1_add' | ff := bit0_add 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_rfl) @[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 bit0_mod_two : bit0 n % 2 = 0 := by { rw nat.mod_two_of_bodd, simp } lemma bit1_mod_two : bit1 n % 2 = 1 := by { rw nat.mod_two_of_bodd, simp } lemma pos_of_bit0_pos {n : ℕ} (h : 0 < bit0 n) : 0 < n := by { cases n, cases h, apply succ_pos, } @[simp] lemma bit_cases_on_bit {C : ℕ → Sort u} (H : Π b n, C (bit b n)) (b : bool) (n : ℕ) : bit_cases_on (bit b n) H = H b n := eq_of_heq $ (eq_rec_heq _ _).trans $ by rw [bodd_bit, div2_bit] @[simp] lemma bit_cases_on_bit0 {C : ℕ → Sort u} (H : Π b n, C (bit b n)) (n : ℕ) : bit_cases_on (bit0 n) H = H ff n := bit_cases_on_bit H ff n @[simp] lemma bit_cases_on_bit1 {C : ℕ → Sort u} (H : Π b n, C (bit b n)) (n : ℕ) : bit_cases_on (bit1 n) H = H tt n := bit_cases_on_bit H tt n lemma bit_cases_on_injective {C : ℕ → Sort u} : function.injective (λ H : Π b n, C (bit b n), λ n, bit_cases_on n H) := begin intros H₁ H₂ h, ext b n, simpa only [bit_cases_on_bit] using congr_fun h (bit b n) end @[simp] lemma bit_cases_on_inj {C : ℕ → Sort u} (H₁ H₂ : Π b n, C (bit b n)) : (λ n, bit_cases_on n H₁) = (λ n, bit_cases_on n H₂) ↔ H₁ = H₂ := bit_cases_on_injective.eq_iff /-! ### decidability of predicates -/ 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', (le_of_lt_succ h').lt_or_eq_dec.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) ((tsub_lt_tsub_iff_right hl).mpr hh), rwa [add_tsub_cancel_of_le hl] at this, }, λal x h, al _ (nat.le_add_right _ _) (lt_tsub_iff_left.mp 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 instance decidable_exists_lt {P : ℕ → Prop} [h : decidable_pred P] : decidable_pred (λ n, ∃ (m : ℕ), m < n ∧ P m) | 0 := is_false (by simp) | (n + 1) := decidable_of_decidable_of_iff (@or.decidable _ _ (decidable_exists_lt n) (h n)) (by simp only [lt_succ_iff_lt_or_eq, or_and_distrib_right, exists_or_distrib, exists_eq_left]) instance decidable_exists_le {P : ℕ → Prop} [h : decidable_pred P] : decidable_pred (λ n, ∃ (m : ℕ), m ≤ n ∧ P m) := λ n, decidable_of_iff (∃ m, m < n + 1 ∧ P m) (exists_congr (λ x, and_congr_left' lt_succ_iff)) end nat
83c308a48c82457d35e381b16f3ea9cd3b326e01
6dc0c8ce7a76229dd81e73ed4474f15f88a9e294
/tests/lean/run/genindices.lean
b39c35f71837b757033c0084cef771c9d725c12e
[ "Apache-2.0" ]
permissive
williamdemeo/lean4
72161c58fe65c3ad955d6a3050bb7d37c04c0d54
6d00fcf1d6d873e195f9220c668ef9c58e9c4a35
refs/heads/master
1,678,305,356,877
1,614,708,995,000
1,614,708,995,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
742
lean
import Lean universe u inductive Pred : ∀ (α : Type u), List α → Type (u+1) | foo {α : Type u} (l1 : List α) (l2 : List (Option α)) : Pred (Option α) l2 → Pred α l1 axiom goal : forall (α : Type u) (xs : List (List α)) (h : Pred (List α) xs), xs ≠ [] → xs = xs open Lean open Lean.Meta def tst1 : MetaM Unit := do let cinfo ← getConstInfo `goal; let type := cinfo.type; let mvar ← mkFreshExprMVar type; trace! `Elab (MessageData.ofGoal mvar.mvarId!); let (_, mvarId) ← introN mvar.mvarId! 2; let (fvarId, mvarId) ← intro1 mvarId; trace! `Elab (MessageData.ofGoal mvarId); let s ← generalizeIndices mvarId fvarId; trace! `Elab (MessageData.ofGoal s.mvarId); pure () set_option trace.Elab true #eval tst1
bde25c89b5cf75e229864e80190489e63cc0cacd
42610cc2e5db9c90269470365e6056df0122eaa0
/library/theories/finite_group_theory/cyclic.lean
8b326798ab500505ce85ba2c98ecee90090faf75
[ "Apache-2.0" ]
permissive
tomsib2001/lean
2ab59bfaebd24a62109f800dcf4a7139ebd73858
eb639a7d53fb40175bea5c8da86b51d14bb91f76
refs/heads/master
1,586,128,387,740
1,468,968,950,000
1,468,968,950,000
61,027,234
0
0
null
1,465,813,585,000
1,465,813,585,000
null
UTF-8
Lean
false
false
15,834
lean
/- Copyright (c) 2015 Haitao Zhang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author : Haitao Zhang -/ import data algebra.group algebra.group_power .finsubg .hom .perm open function finset open eq.ops namespace group_theory section cyclic open nat fin list local attribute madd [reducible] variable {A : Type} variable [ambG : group A] include ambG lemma pow_mod {a : A} {n m : nat} : a ^ m = 1 → a ^ n = a ^ (n % m) := assume Pid, have a ^ (n / m * m) = 1, from calc a ^ (n / m * m) = a ^ (m * (n / m)) : by rewrite (mul.comm (n / m) m) ... = (a ^ m) ^ (n / m) : by rewrite pow_mul ... = 1 ^ (n / m) : by rewrite Pid ... = 1 : one_pow (n / m), calc a ^ n = a ^ (n / m * m + n % m) : by rewrite -(eq_div_mul_add_mod n m) ... = a ^ (n / m * m) * a ^ (n % m) : by rewrite pow_add ... = 1 * a ^ (n % m) : by rewrite this ... = a ^ (n % m) : by rewrite one_mul lemma pow_sub_eq_one_of_pow_eq {a : A} {i j : nat} : a^i = a^j → a^(i - j) = 1 := assume Pe, or.elim (lt_or_ge i j) (assume Piltj, begin rewrite [sub_eq_zero_of_le (nat.le_of_lt Piltj)] end) (assume Pigej, begin rewrite [pow_sub a Pigej, Pe, mul.right_inv] end) lemma pow_dist_eq_one_of_pow_eq {a : A} {i j : nat} : a^i = a^j → a^(dist i j) = 1 := assume Pe, or.elim (lt_or_ge i j) (suppose i < j, by rewrite [dist_eq_sub_of_lt this]; exact pow_sub_eq_one_of_pow_eq (eq.symm Pe)) (suppose i ≥ j, by rewrite [dist_eq_sub_of_ge this]; exact pow_sub_eq_one_of_pow_eq Pe) lemma pow_madd {a : A} {n : nat} {i j : fin (succ n)} : a^(succ n) = 1 → a^(val (i + j)) = a^i * a^j := assume Pe, calc a^(val (i + j)) = a^((i + j) % (succ n)) : rfl ... = a^(val i + val j) : by rewrite [-pow_mod Pe] ... = a^i * a^j : by rewrite pow_add lemma mk_pow_mod {a : A} {n m : nat} : a ^ (succ m) = 1 → a ^ n = a ^ (mk_mod m n) := assume Pe, pow_mod Pe variable [finA : fintype A] include finA open fintype variable [deceqA : decidable_eq A] include deceqA lemma exists_pow_eq_one (a : A) : ∃ n, n < card A ∧ a ^ (succ n) = 1 := let f := (λ i : fin (succ (card A)), a ^ i) in have Pninj : ¬(injective f), from assume Pinj, absurd (card_le_of_inj _ _ (exists.intro f Pinj)) (begin rewrite [card_fin], apply not_succ_le_self end), obtain i₁ P₁, from exists_not_of_not_forall Pninj, obtain i₂ P₂, from exists_not_of_not_forall P₁, obtain Pfe Pne, from and_not_of_not_implies P₂, have Pvne : val i₁ ≠ val i₂, from assume Pveq, absurd (eq_of_veq Pveq) Pne, exists.intro (pred (dist i₁ i₂)) (begin rewrite [succ_pred_of_pos (dist_pos_of_ne Pvne)], apply and.intro, apply lt_of_succ_lt_succ, rewrite [succ_pred_of_pos (dist_pos_of_ne Pvne)], apply nat.lt_of_le_of_lt dist_le_max (max_lt i₁ i₂), apply pow_dist_eq_one_of_pow_eq Pfe end) -- Another possibility is to generate a list of powers and use find to get the first -- unity. -- The bound on bex is arbitrary as long as it is large enough (at least card A). Making -- it larger simplifies some proofs, such as a ∈ cyc a. definition cyc (a : A) : finset A := {x ∈ univ | bex (succ (card A)) (λ n, a ^ n = x)} definition order (a : A) := card (cyc a) definition pow_fin (a : A) (n : nat) (i : fin (order a)) := a ^ (i + n) definition cyc_pow_fin (a : A) (n : nat) : finset A := image (pow_fin a n) univ lemma order_le_group_order {a : A} : order a ≤ card A := card_le_card_of_subset !subset_univ lemma cyc_has_one (a : A) : 1 ∈ cyc a := begin apply mem_sep_of_mem !mem_univ, existsi 0, apply and.intro, apply zero_lt_succ, apply pow_zero end lemma order_pos (a : A) : 0 < order a := length_pos_of_mem (cyc_has_one a) lemma cyc_mul_closed (a : A) : finset_mul_closed_on (cyc a) := take g h, assume Pgin Phin, obtain n Plt Pe, from exists_pow_eq_one a, obtain i Pilt Pig, from of_mem_sep Pgin, obtain j Pjlt Pjh, from of_mem_sep Phin, begin rewrite [-Pig, -Pjh, -pow_add, pow_mod Pe], apply mem_sep_of_mem !mem_univ, existsi ((i + j) % (succ n)), apply and.intro, apply nat.lt_trans (mod_lt (i+j) !zero_lt_succ) (succ_lt_succ Plt), apply rfl end lemma cyc_has_inv (a : A) : finset_has_inv (cyc a) := take g, assume Pgin, obtain n Plt Pe, from exists_pow_eq_one a, obtain i Pilt Pig, from of_mem_sep Pgin, let ni := -(mk_mod n i) in have Pinv : g*a^ni = 1, by rewrite [-Pig, mk_pow_mod Pe, -(pow_madd Pe), add.right_inv], begin rewrite [inv_eq_of_mul_eq_one Pinv], apply mem_sep_of_mem !mem_univ, existsi ni, apply and.intro, apply nat.lt_trans (is_lt ni) (succ_lt_succ Plt), apply rfl end lemma self_mem_cyc (a : A) : a ∈ cyc a := mem_sep_of_mem !mem_univ (exists.intro (1 : nat) (and.intro (succ_lt_succ card_pos) !pow_one)) lemma mem_cyc (a : A) : ∀ {n : nat}, a^n ∈ cyc a | 0 := cyc_has_one a | (succ n) := begin rewrite pow_succ', apply cyc_mul_closed a, exact mem_cyc, apply self_mem_cyc end lemma order_le {a : A} {n : nat} : a^(succ n) = 1 → order a ≤ succ n := assume Pe, let s := image (pow_nat a) (upto (succ n)) in have Psub: cyc a ⊆ s, from subset_of_forall (take g, assume Pgin, obtain i Pilt Pig, from of_mem_sep Pgin, begin rewrite [-Pig, pow_mod Pe], apply mem_image, apply mem_upto_of_lt (mod_lt i !zero_lt_succ), exact rfl end), #nat calc order a ≤ card s : card_le_card_of_subset Psub ... ≤ card (upto (succ n)) : !card_image_le ... = succ n : card_upto (succ n) lemma pow_ne_of_lt_order {a : A} {n : nat} : succ n < order a → a^(succ n) ≠ 1 := assume Plt, not_imp_not_of_imp order_le (not_le_of_gt Plt) lemma eq_zero_of_pow_eq_one {a : A} : ∀ {n : nat}, a^n = 1 → n < order a → n = 0 | 0 := assume Pe Plt, rfl | (succ n) := assume Pe Plt, absurd Pe (pow_ne_of_lt_order Plt) lemma pow_fin_inj (a : A) (n : nat) : injective (pow_fin a n) := take i j : fin (order a), suppose a^(i + n) = a^(j + n), have a^(dist i j) = 1, begin apply !dist_add_add_right ▸ (pow_dist_eq_one_of_pow_eq this) end, have dist i j = 0, from eq_zero_of_pow_eq_one this (nat.lt_of_le_of_lt dist_le_max (max_lt i j)), eq_of_veq (eq_of_dist_eq_zero this) lemma cyc_eq_cyc (a : A) (n : nat) : cyc_pow_fin a n = cyc a := have Psub : cyc_pow_fin a n ⊆ cyc a, from subset_of_forall (take g, assume Pgin, obtain i Pin Pig, from exists_of_mem_image Pgin, by rewrite [-Pig]; apply mem_cyc), eq_of_card_eq_of_subset (begin apply eq.trans, apply card_image_eq_of_inj_on, rewrite [to_set_univ, -set.injective_iff_inj_on_univ], exact pow_fin_inj a n, rewrite [card_fin] end) Psub lemma pow_order (a : A) : a^(order a) = 1 := obtain i Pin Pone, from exists_of_mem_image (eq.symm (cyc_eq_cyc a 1) ▸ cyc_has_one a), or.elim (eq_or_lt_of_le (succ_le_of_lt (is_lt i))) (assume P, P ▸ Pone) (assume P, absurd Pone (pow_ne_of_lt_order P)) lemma eq_one_of_order_eq_one {a : A} : order a = 1 → a = 1 := assume Porder, calc a = a^1 : by rewrite (pow_one a) ... = a^(order a) : by rewrite Porder ... = 1 : by rewrite pow_order lemma order_of_min_pow {a : A} {n : nat} (Pone : a^(succ n) = 1) (Pmin : ∀ i, i < n → a^(succ i) ≠ 1) : order a = succ n := or.elim (eq_or_lt_of_le (order_le Pone)) (λ P, P) (λ P : order a < succ n, begin have Pn : a^(order a) ≠ 1, begin rewrite [-(succ_pred_of_pos (order_pos a))], apply Pmin, apply nat.lt_of_succ_lt_succ, rewrite [succ_pred_of_pos !order_pos], assumption end, exact absurd (pow_order a) Pn end) lemma order_dvd_of_pow_eq_one {a : A} {n : nat} (Pone : a^n = 1) : order a ∣ n := have Pe : a^(n % order a) = 1, from begin revert Pone, rewrite [eq_div_mul_add_mod n (order a) at {1}, pow_add, mul.comm _ (order a), pow_mul, pow_order, one_pow, one_mul], intros, assumption end, dvd_of_mod_eq_zero (eq_zero_of_pow_eq_one Pe (mod_lt n !order_pos)) definition cyc_is_finsubg [instance] (a : A) : is_finsubg (cyc a) := is_finsubg.mk (cyc_has_one a) (cyc_mul_closed a) (cyc_has_inv a) lemma order_dvd_group_order (a : A) : order a ∣ card A := dvd.intro (eq.symm (!mul.comm ▸ lagrange_theorem (subset_univ (cyc a)))) definition pow_fin' (a : A) (i : fin (succ (pred (order a)))) := pow_nat a i local attribute group_of_add_group [instance] lemma pow_fin_hom (a : A) : homomorphic (pow_fin' a) := take i j : fin (succ (pred (order a))), begin rewrite [↑pow_fin'], apply pow_madd, rewrite [succ_pred_of_pos !order_pos], exact pow_order a end definition pow_fin_is_iso (a : A) : is_iso_class (pow_fin' a) := is_iso_class.mk (pow_fin_hom a) (have H : injective (λ (i : fin (order a)), a ^ (val i + 0)), from pow_fin_inj a 0, begin rewrite [↑pow_fin', succ_pred_of_pos !order_pos]; exact H end) end cyclic section rot open nat list open fin fintype list section local attribute group_of_add_group [instance] lemma pow_eq_mul {n : nat} {i : fin (succ n)} : ∀ {k : nat}, i^k = mk_mod n (i*k) | 0 := by rewrite [pow_zero] | (succ k) := begin have Psucc : i^(succ k) = madd (i^k) i, by apply pow_succ', rewrite [Psucc, pow_eq_mul], apply eq_of_veq, rewrite [mul_succ, val_madd, ↑mk_mod, mod_add_mod] end end definition rotl : ∀ {n : nat} m : nat, fin n → fin n | 0 := take m i, elim0 i | (succ n) := take m, madd (mk_mod n (n*m)) definition rotr : ∀ {n : nat} m : nat, fin n → fin n | (0:nat) := take m i, elim0 i | (nat.succ n) := take m, madd (-(mk_mod n (n*m))) lemma rotl_succ' {n m : nat} : rotl m = madd (mk_mod n (n*m)) := rfl lemma rotl_zero : ∀ {n : nat}, @rotl n 0 = id | 0 := funext take i, elim0 i | (nat.succ n) := funext take i, begin rewrite [↑rotl, mul_zero, mk_mod_zero_eq, zero_madd] end lemma rotl_id : ∀ {n : nat}, @rotl n n = id | 0 := funext take i, elim0 i | (nat.succ n) := have P : mk_mod n (n * succ n) = mk_mod n 0, from eq_of_veq (by rewrite [↑mk_mod, mul_mod_left]), begin rewrite [rotl_succ', P], apply rotl_zero end lemma rotl_to_zero {n i : nat} : rotl i (mk_mod n i) = 0 := eq_of_veq begin rewrite [↑rotl, val_madd], esimp [mk_mod], rewrite [ mod_add_mod, add_mod_mod, -succ_mul, mul_mod_right] end lemma rotl_compose : ∀ {n : nat} {j k : nat}, (@rotl n j) ∘ (rotl k) = rotl (j + k) | 0 := take j k, funext take i, elim0 i | (succ n) := take j k, funext take i, eq.symm begin rewrite [*rotl_succ', left_distrib, -(@madd_mk_mod n (n*j)), madd_assoc], end lemma rotr_rotl : ∀ {n : nat} (m : nat) {i : fin n}, rotr m (rotl m i) = i | 0 := take m i, elim0 i | (nat.succ n) := take m i, calc (-(mk_mod n (n*m))) + ((mk_mod n (n*m)) + i) = i : by rewrite neg_add_cancel_left lemma rotl_rotr : ∀ {n : nat} (m : nat), (@rotl n m) ∘ (rotr m) = id | 0 := take m, funext take i, elim0 i | (nat.succ n) := take m, funext take i, calc (mk_mod n (n*m)) + (-(mk_mod n (n*m)) + i) = i : add_neg_cancel_left lemma rotl_succ {n : nat} : (rotl 1) ∘ (@succ n) = lift_succ := funext (take i, eq_of_veq (begin rewrite [↑comp, ↑rotl, ↑madd, mul_one n, ↑mk_mod, mod_add_mod, ↑lift_succ, val_succ, -succ_add_eq_succ_add, add_mod_self_left, mod_eq_of_lt (lt.trans (is_lt i) !lt_succ_self), -val_lift] end)) definition list.rotl {A : Type} : ∀ l : list A, list A | [] := [] | (a::l) := l++[a] lemma rotl_cons {A : Type} {a : A} {l} : list.rotl (a::l) = l++[a] := rfl lemma rotl_map {A B : Type} {f : A → B} : ∀ {l : list A}, list.rotl (map f l) = map f (list.rotl l) | [] := rfl | (a::l) := begin rewrite [map_cons, *rotl_cons, map_append] end lemma rotl_eq_rotl : ∀ {n : nat}, map (rotl 1) (upto n) = list.rotl (upto n) | 0 := rfl | (succ n) := begin rewrite [upto_step at {1}, fin.upto_succ, rotl_cons, map_append], congruence, rewrite [map_map], congruence, exact rotl_succ, rewrite [map_singleton], congruence, rewrite [↑rotl, mul_one n, ↑mk_mod, ↑maxi, ↑madd], congruence, rewrite [ mod_add_mod, val_zero, add_zero, mod_eq_of_lt !lt_succ_self ] end definition seq [reducible] (A : Type) (n : nat) := fin n → A variable {A : Type} definition rotl_fun {n : nat} (m : nat) (f : seq A n) : seq A n := f ∘ (rotl m) definition rotr_fun {n : nat} (m : nat) (f : seq A n) : seq A n := f ∘ (rotr m) lemma rotl_seq_zero {n : nat} : rotl_fun 0 = @id (seq A n) := funext take f, begin rewrite [↑rotl_fun, rotl_zero] end lemma rotl_seq_ne_id : ∀ {n : nat}, (∃ a b : A, a ≠ b) → ∀ i, i < n → rotl_fun (succ i) ≠ (@id (seq A (succ n))) | 0 := assume Pex, take i, assume Piltn, absurd Piltn !not_lt_zero | (nat.succ n) := assume Pex, obtain a b Pne, from Pex, take i, assume Pilt, let f := (λ j : fin (succ (succ n)), if j = 0 then a else b), fi := mk_mod (succ n) (succ i) in have Pfne : rotl_fun (succ i) f fi ≠ f fi, from begin rewrite [↑rotl_fun, rotl_to_zero, mk_mod_of_lt (succ_lt_succ Pilt), if_pos rfl, if_neg mk_succ_ne_zero], assumption end, have P : rotl_fun (succ i) f ≠ f, from assume Peq, absurd (congr_fun Peq fi) Pfne, assume Peq, absurd (congr_fun Peq f) P lemma rotr_rotl_fun {n : nat} (m : nat) (f : seq A n) : rotr_fun m (rotl_fun m f) = f := calc f ∘ (rotl m) ∘ (rotr m) = f ∘ ((rotl m) ∘ (rotr m)) : by rewrite -comp.assoc ... = f ∘ id : by rewrite (rotl_rotr m) lemma rotl_fun_inj {n : nat} {m : nat} : @injective (seq A n) (seq A n) (rotl_fun m) := injective_of_has_left_inverse (exists.intro (rotr_fun m) (rotr_rotl_fun m)) lemma seq_rotl_eq_list_rotl {n : nat} (f : seq A n) : fun_to_list (rotl_fun 1 f) = list.rotl (fun_to_list f) := begin rewrite [↑fun_to_list, ↑rotl_fun, -map_map, rotl_map], congruence, exact rotl_eq_rotl end end rot section rotg open nat fin fintype definition rotl_perm [reducible] (A : Type) [finA : fintype A] [deceqA : decidable_eq A] (n : nat) (m : nat) : perm (seq A n) := perm.mk (rotl_fun m) rotl_fun_inj variable {A : Type} variable [finA : fintype A] variable [deceqA : decidable_eq A] variable {n : nat} include finA deceqA lemma rotl_perm_mul {i j : nat} : (rotl_perm A n i) * (rotl_perm A n j) = rotl_perm A n (j+i) := eq_of_feq (funext take f, calc f ∘ (rotl j) ∘ (rotl i) = f ∘ ((rotl j) ∘ (rotl i)) : by rewrite -comp.assoc ... = f ∘ (rotl (j+i)) : by rewrite rotl_compose) lemma rotl_perm_pow_eq : ∀ {i : nat}, (rotl_perm A n 1) ^ i = rotl_perm A n i | 0 := begin rewrite [pow_zero, ↑rotl_perm, perm_one, -eq_iff_feq], esimp, rewrite rotl_seq_zero end | (succ i) := begin rewrite [pow_succ', rotl_perm_pow_eq, rotl_perm_mul, one_add] end lemma rotl_perm_pow_eq_one : (rotl_perm A n 1) ^ n = 1 := eq.trans rotl_perm_pow_eq (eq_of_feq begin esimp [rotl_perm], rewrite [↑rotl_fun, rotl_id] end) lemma rotl_perm_mod {i : nat} : rotl_perm A n i = rotl_perm A n (i % n) := calc rotl_perm A n i = (rotl_perm A n 1) ^ i : by rewrite rotl_perm_pow_eq ... = (rotl_perm A n 1) ^ (i % n) : by rewrite (pow_mod rotl_perm_pow_eq_one) ... = rotl_perm A n (i % n) : by rewrite rotl_perm_pow_eq -- needs A to have at least two elements! lemma rotl_perm_pow_ne_one (Pex : ∃ a b : A, a ≠ b) : ∀ i, i < n → (rotl_perm A (succ n) 1)^(succ i) ≠ 1 := take i, assume Piltn, begin intro P, revert P, rewrite [rotl_perm_pow_eq, -eq_iff_feq, perm_one, *perm.f_mk], intro P, exact absurd P (rotl_seq_ne_id Pex i Piltn) end lemma rotl_perm_order (Pex : ∃ a b : A, a ≠ b) : order (rotl_perm A (succ n) 1) = (succ n) := order_of_min_pow rotl_perm_pow_eq_one (rotl_perm_pow_ne_one Pex) end rotg end group_theory
757ea1b1f0cec83c703d5539e90422d06a6bf2b1
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/pnat/prime.lean
4db050a84b83c58ff852d527b3a49c27442e78bd
[ "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,672
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Neil Strickland -/ import data.nat.prime import data.pnat.basic /-! # Primality and GCD on pnat > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file extends the theory of `ℕ+` with `gcd`, `lcm` and `prime` functions, analogous to those on `nat`. -/ namespace nat.primes instance coe_pnat : has_coe nat.primes ℕ+ := ⟨λ p, ⟨(p : ℕ), p.property.pos⟩⟩ @[norm_cast] theorem coe_pnat_nat (p : nat.primes) : ((p : ℕ+) : ℕ) = p := rfl theorem coe_pnat_injective : function.injective (coe : nat.primes → ℕ+) := λ p q h, subtype.ext (congr_arg subtype.val h : _) @[norm_cast] theorem coe_pnat_inj (p q : nat.primes) : (p : ℕ+) = (q : ℕ+) ↔ p = q := coe_pnat_injective.eq_iff end nat.primes namespace pnat open _root_.nat /-- The greatest common divisor (gcd) of two positive natural numbers, viewed as positive natural number. -/ def gcd (n m : ℕ+) : ℕ+ := ⟨nat.gcd (n : ℕ) (m : ℕ), nat.gcd_pos_of_pos_left (m : ℕ) n.pos⟩ /-- The least common multiple (lcm) of two positive natural numbers, viewed as positive natural number. -/ def lcm (n m : ℕ+) : ℕ+ := ⟨nat.lcm (n : ℕ) (m : ℕ), by { let h := mul_pos n.pos m.pos, rw [← gcd_mul_lcm (n : ℕ) (m : ℕ), mul_comm] at h, exact pos_of_dvd_of_pos (dvd.intro (nat.gcd (n : ℕ) (m : ℕ)) rfl) h }⟩ @[simp, norm_cast] theorem gcd_coe (n m : ℕ+) : ((gcd n m) : ℕ) = nat.gcd n m := rfl @[simp, norm_cast] theorem lcm_coe (n m : ℕ+) : ((lcm n m) : ℕ) = nat.lcm n m := rfl theorem gcd_dvd_left (n m : ℕ+) : (gcd n m) ∣ n := dvd_iff.2 (nat.gcd_dvd_left (n : ℕ) (m : ℕ)) theorem gcd_dvd_right (n m : ℕ+) : (gcd n m) ∣ m := dvd_iff.2 (nat.gcd_dvd_right (n : ℕ) (m : ℕ)) theorem dvd_gcd {m n k : ℕ+} (hm : k ∣ m) (hn : k ∣ n) : k ∣ gcd m n := dvd_iff.2 (@nat.dvd_gcd (m : ℕ) (n : ℕ) (k : ℕ) (dvd_iff.1 hm) (dvd_iff.1 hn)) theorem dvd_lcm_left (n m : ℕ+) : n ∣ lcm n m := dvd_iff.2 (nat.dvd_lcm_left (n : ℕ) (m : ℕ)) theorem dvd_lcm_right (n m : ℕ+) : m ∣ lcm n m := dvd_iff.2 (nat.dvd_lcm_right (n : ℕ) (m : ℕ)) theorem lcm_dvd {m n k : ℕ+} (hm : m ∣ k) (hn : n ∣ k) : lcm m n ∣ k := dvd_iff.2 (@nat.lcm_dvd (m : ℕ) (n : ℕ) (k : ℕ) (dvd_iff.1 hm) (dvd_iff.1 hn)) theorem gcd_mul_lcm (n m : ℕ+) : (gcd n m) * (lcm n m) = n * m := subtype.eq (nat.gcd_mul_lcm (n : ℕ) (m : ℕ)) lemma eq_one_of_lt_two {n : ℕ+} : n < 2 → n = 1 := begin intro h, apply le_antisymm, swap, apply pnat.one_le, change n < 1 + 1 at h, rw pnat.lt_add_one_iff at h, apply h end section prime /-! ### Prime numbers -/ /-- Primality predicate for `ℕ+`, defined in terms of `nat.prime`. -/ def prime (p : ℕ+) : Prop := (p : ℕ).prime lemma prime.one_lt {p : ℕ+} : p.prime → 1 < p := nat.prime.one_lt lemma prime_two : (2 : ℕ+).prime := nat.prime_two lemma dvd_prime {p m : ℕ+} (pp : p.prime) : (m ∣ p ↔ m = 1 ∨ m = p) := by { rw pnat.dvd_iff, rw nat.dvd_prime pp, simp } lemma prime.ne_one {p : ℕ+} : p.prime → p ≠ 1 := by { intro pp, intro contra, apply nat.prime.ne_one pp, rw pnat.coe_eq_one_iff, apply contra } @[simp] lemma not_prime_one : ¬ (1: ℕ+).prime := nat.not_prime_one lemma prime.not_dvd_one {p : ℕ+} : p.prime → ¬ p ∣ 1 := λ pp : p.prime, by {rw dvd_iff, apply nat.prime.not_dvd_one pp} lemma exists_prime_and_dvd {n : ℕ+} (hn : n ≠ 1) : (∃ (p : ℕ+), p.prime ∧ p ∣ n) := begin obtain ⟨p, hp⟩ := nat.exists_prime_and_dvd (mt coe_eq_one_iff.mp hn), existsi (⟨p, nat.prime.pos hp.left⟩ : ℕ+), rw dvd_iff, apply hp end end prime section coprime /-! ### Coprime numbers and gcd -/ /-- Two pnats are coprime if their gcd is 1. -/ def coprime (m n : ℕ+) : Prop := m.gcd n = 1 @[simp, norm_cast] lemma coprime_coe {m n : ℕ+} : nat.coprime ↑m ↑n ↔ m.coprime n := by { unfold coprime, unfold nat.coprime, rw ← coe_inj, simp } lemma coprime.mul {k m n : ℕ+} : m.coprime k → n.coprime k → (m * n).coprime k := by { repeat {rw ← coprime_coe}, rw mul_coe, apply nat.coprime.mul } lemma coprime.mul_right {k m n : ℕ+} : k.coprime m → k.coprime n → k.coprime (m * n) := by { repeat {rw ← coprime_coe}, rw mul_coe, apply nat.coprime.mul_right } lemma gcd_comm {m n : ℕ+} : m.gcd n = n.gcd m := by { apply eq, simp only [gcd_coe], apply nat.gcd_comm } lemma gcd_eq_left_iff_dvd {m n : ℕ+} : m ∣ n ↔ m.gcd n = m := by { rw dvd_iff, rw nat.gcd_eq_left_iff_dvd, rw ← coe_inj, simp } lemma gcd_eq_right_iff_dvd {m n : ℕ+} : m ∣ n ↔ n.gcd m = m := by { rw gcd_comm, apply gcd_eq_left_iff_dvd, } lemma coprime.gcd_mul_left_cancel (m : ℕ+) {n k : ℕ+} : k.coprime n → (k * m).gcd n = m.gcd n := begin intro h, apply eq, simp only [gcd_coe, mul_coe], apply nat.coprime.gcd_mul_left_cancel, simpa end lemma coprime.gcd_mul_right_cancel (m : ℕ+) {n k : ℕ+} : k.coprime n → (m * k).gcd n = m.gcd n := begin rw mul_comm, apply coprime.gcd_mul_left_cancel, end lemma coprime.gcd_mul_left_cancel_right (m : ℕ+) {n k : ℕ+} : k.coprime m → m.gcd (k * n) = m.gcd n := begin intro h, iterate 2 {rw gcd_comm, symmetry}, apply coprime.gcd_mul_left_cancel _ h, end lemma coprime.gcd_mul_right_cancel_right (m : ℕ+) {n k : ℕ+} : k.coprime m → m.gcd (n * k) = m.gcd n := begin rw mul_comm, apply coprime.gcd_mul_left_cancel_right, end @[simp] lemma one_gcd {n : ℕ+} : gcd 1 n = 1 := by { rw ← gcd_eq_left_iff_dvd, apply one_dvd } @[simp] lemma gcd_one {n : ℕ+} : gcd n 1 = 1 := by { rw gcd_comm, apply one_gcd } @[symm] lemma coprime.symm {m n : ℕ+} : m.coprime n → n.coprime m := by { unfold coprime, rw gcd_comm, simp } @[simp] lemma one_coprime {n : ℕ+} : (1 : ℕ+).coprime n := one_gcd @[simp] lemma coprime_one {n : ℕ+} : n.coprime 1 := coprime.symm one_coprime lemma coprime.coprime_dvd_left {m k n : ℕ+} : m ∣ k → k.coprime n → m.coprime n := by { rw dvd_iff, repeat {rw ← coprime_coe}, apply nat.coprime.coprime_dvd_left } lemma coprime.factor_eq_gcd_left {a b m n : ℕ+} (cop : m.coprime n) (am : a ∣ m) (bn : b ∣ n) : a = (a * b).gcd m := begin rw gcd_eq_left_iff_dvd at am, conv_lhs {rw ← am}, symmetry, apply coprime.gcd_mul_right_cancel a, apply coprime.coprime_dvd_left bn cop.symm, end lemma coprime.factor_eq_gcd_right {a b m n : ℕ+} (cop : m.coprime n) (am : a ∣ m) (bn : b ∣ n) : a = (b * a).gcd m := begin rw mul_comm, apply coprime.factor_eq_gcd_left cop am bn, end lemma coprime.factor_eq_gcd_left_right {a b m n : ℕ+} (cop : m.coprime n) (am : a ∣ m) (bn : b ∣ n) : a = m.gcd (a * b) := begin rw gcd_comm, apply coprime.factor_eq_gcd_left cop am bn, end lemma coprime.factor_eq_gcd_right_right {a b m n : ℕ+} (cop : m.coprime n) (am : a ∣ m) (bn : b ∣ n) : a = m.gcd (b * a) := begin rw gcd_comm, apply coprime.factor_eq_gcd_right cop am bn, end lemma coprime.gcd_mul (k : ℕ+) {m n : ℕ+} (h: m.coprime n) : k.gcd (m * n) = k.gcd m * k.gcd n := begin rw ← coprime_coe at h, apply eq, simp only [gcd_coe, mul_coe], apply nat.coprime.gcd_mul k h end lemma gcd_eq_left {m n : ℕ+} : m ∣ n → m.gcd n = m := by { rw dvd_iff, intro h, apply eq, simp only [gcd_coe], apply nat.gcd_eq_left h } lemma coprime.pow {m n : ℕ+} (k l : ℕ) (h : m.coprime n) : (m ^ k).coprime (n ^ l) := begin rw ← coprime_coe at *, simp only [pow_coe], apply nat.coprime.pow, apply h end end coprime end pnat
4767f955bb8d39f32fb59bb6295ce909f609615f
4d3f29a7b2eff44af8fd0d3176232e039acb9ee3
/LAMR/Examples/using_lean/examples2.lean
8b4f50d2cdac0ade8b3a2c5638104ac7d1632660
[]
no_license
marijnheule/lamr
5fc5d69d326ff92e321242cfd7f72e78d7f99d7e
28cc4114c7361059bb54f407fa312bf38b48728b
refs/heads/main
1,689,338,013,620
1,630,359,632,000
1,630,359,632,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,332
lean
-- textbook: defining functions def foo n := 3 * n + 7 #eval foo 3 #eval foo (foo 3) def bar n := foo (foo n) + 3 #eval bar 3 #eval bar (bar 3) -- end textbook: defining functions -- textbook: hello world def printExample : IO Unit:= do IO.println "hello" IO.println "world" #eval printExample -- end textbook: hello world -- textbook: factorial def factorial : Nat → Nat | 0 => 1 | (n + 1) => (n + 1) * factorial n #eval factorial 10 #eval factorial 100 -- end textbook: factorial -- textbook: hanoi def hanoi (numPegs start finish aux : Nat) : IO Unit := match numPegs with | 0 => pure () | n + 1 => do hanoi n start aux finish IO.println s!"Move disk {n + 1} from peg {start} to peg {finish}" hanoi n aux finish start #eval hanoi 7 1 2 3 -- end textbook: hanoi -- textbook: recursion on lists def addNums : List Nat → Nat | [] => 0 | a::as => a + addNums as #eval addNums [0, 1, 2, 3, 4, 5, 6] -- end textbook: recursion on lists -- textbook: list functions #eval List.range 7 section open List #eval range 7 #eval addNums $ range 7 #eval map (fun x => x + 3) $ range 7 #eval foldl (. + .) 0 $ range 7 end -- end textbook: list functions -- textbook: projection notation def myRange := List.range 7 #eval myRange.map fun x => x + 3 -- end textbook: projection notation -- textbook: reverse and append namespace hidden def reverseAux : List α → List α → List α | [], r => r | a::l, r => reverseAux l (a::r) def reverse (as : List α) :List α := reverseAux as [] protected def append (as bs : List α) : List α := reverseAux as.reverse bs end hidden -- end textbook: reverse and append -- textbook: gcd partial def gcd m n := if n = 0 then m else gcd n (m % n) #eval gcd 45 30 #eval gcd 37252 49824 -- end textbook: gcd -- textbook: bad definition partial def bad (n : Nat) : Nat := bad (n + 1) -- end textbook: bad definition -- textbook: inefficient Fibonacci def fib' : Nat → Nat | 0 => 0 | 1 => 1 | n + 2 => fib' (n + 1) + fib' n -- end textbook: inefficient Fibonacci -- textbook: efficient Fibonacci def fibAux : Nat → Nat × Nat | 0 => (0, 1) | n + 1 => let p := fibAux n (p.2, p.1 + p.2) def fib n := (fibAux n).1 #eval (List.range 20).map fib -- end textbook: efficient Fibonacci
e3de929ac2ec83cef90298fbd7077bdef770d411
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/control/uliftable.lean
104ed8c3b5399d9dd7737f4d10736ca88ef5b871
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
5,692
lean
/- Copyright (c) 2020 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import control.monad.basic import control.monad.cont import control.monad.writer import logic.equiv.basic import tactic.interactive /-! # Universe lifting for type families > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. Some functors such as `option` and `list` are universe polymorphic. Unlike type polymorphism where `option α` is a function application and reasoning and generalizations that apply to functions can be used, `option.{u}` and `option.{v}` are not one function applied to two universe names but one polymorphic definition instantiated twice. This means that whatever works on `option.{u}` is hard to transport over to `option.{v}`. `uliftable` is an attempt at improving the situation. `uliftable option.{u} option.{v}` gives us a generic and composable way to use `option.{u}` in a context that requires `option.{v}`. It is often used in tandem with `ulift` but the two are purposefully decoupled. ## Main definitions * `uliftable` class ## Tags universe polymorphism functor -/ universes u₀ u₁ v₀ v₁ v₂ w w₀ w₁ variables {s : Type u₀} {s' : Type u₁} {r r' w w' : Type*} /-- Given a universe polymorphic type family `M.{u} : Type u₁ → Type u₂`, this class convert between instantiations, from `M.{u} : Type u₁ → Type u₂` to `M.{v} : Type v₁ → Type v₂` and back -/ class uliftable (f : Type u₀ → Type u₁) (g : Type v₀ → Type v₁) := (congr [] {α β} : α ≃ β → f α ≃ g β) namespace uliftable /-- The most common practical use `uliftable` (together with `up`), this function takes `x : M.{u} α` and lifts it to M.{max u v} (ulift.{v} α) -/ @[reducible] def up {f : Type u₀ → Type u₁} {g : Type (max u₀ v₀) → Type v₁} [uliftable f g] {α} : f α → g (ulift α) := (uliftable.congr f g equiv.ulift.symm).to_fun /-- The most common practical use of `uliftable` (together with `up`), this function takes `x : M.{max u v} (ulift.{v} α)` and lowers it to `M.{u} α` -/ @[reducible] def down {f : Type u₀ → Type u₁} {g : Type (max u₀ v₀) → Type v₁} [uliftable f g] {α} : g (ulift α) → f α := (uliftable.congr f g equiv.ulift.symm).inv_fun /-- convenient shortcut to avoid manipulating `ulift` -/ def adapt_up (F : Type v₀ → Type v₁) (G : Type (max v₀ u₀) → Type u₁) [uliftable F G] [monad G] {α β} (x : F α) (f : α → G β) : G β := up x >>= f ∘ ulift.down /-- convenient shortcut to avoid manipulating `ulift` -/ def adapt_down {F : Type (max u₀ v₀) → Type u₁} {G : Type v₀ → Type v₁} [L : uliftable G F] [monad F] {α β} (x : F α) (f : α → G β) : G β := @down.{v₀ v₁ (max u₀ v₀)} G F L β $ x >>= @up.{v₀ v₁ (max u₀ v₀)} G F L β ∘ f /-- map function that moves up universes -/ def up_map {F : Type u₀ → Type u₁} {G : Type.{max u₀ v₀} → Type v₁} [inst : uliftable F G] [functor G] {α β} (f : α → β) (x : F α) : G β := functor.map (f ∘ ulift.down) (up x) /-- map function that moves down universes -/ def down_map {F : Type.{max u₀ v₀} → Type u₁} {G : Type u₀ → Type v₁} [inst : uliftable G F] [functor F] {α β} (f : α → β) (x : F α) : G β := down (functor.map (ulift.up ∘ f) x : F (ulift β)) @[simp] lemma up_down {f : Type u₀ → Type u₁} {g : Type (max u₀ v₀) → Type v₁} [uliftable f g] {α} (x : g (ulift α)) : up (down x : f α) = x := (uliftable.congr f g equiv.ulift.symm).right_inv _ @[simp] lemma down_up {f : Type u₀ → Type u₁} {g : Type (max u₀ v₀) → Type v₁} [uliftable f g] {α} (x : f α) : down (up x : g _) = x := (uliftable.congr f g equiv.ulift.symm).left_inv _ end uliftable open ulift instance : uliftable id id := { congr := λ α β F, F } /-- for specific state types, this function helps to create a uliftable instance -/ def state_t.uliftable' {m : Type u₀ → Type v₀} {m' : Type u₁ → Type v₁} [uliftable m m'] (F : s ≃ s') : uliftable (state_t s m) (state_t s' m') := { congr := λ α β G, state_t.equiv $ equiv.Pi_congr F $ λ _, uliftable.congr _ _ $ equiv.prod_congr G F } instance {m m'} [uliftable m m'] : uliftable (state_t s m) (state_t (ulift s) m') := state_t.uliftable' equiv.ulift.symm /-- for specific reader monads, this function helps to create a uliftable instance -/ def reader_t.uliftable' {m m'} [uliftable m m'] (F : s ≃ s') : uliftable (reader_t s m) (reader_t s' m') := { congr := λ α β G, reader_t.equiv $ equiv.Pi_congr F $ λ _, uliftable.congr _ _ G } instance {m m'} [uliftable m m'] : uliftable (reader_t s m) (reader_t (ulift s) m') := reader_t.uliftable' equiv.ulift.symm /-- for specific continuation passing monads, this function helps to create a uliftable instance -/ def cont_t.uliftable' {m m'} [uliftable m m'] (F : r ≃ r') : uliftable (cont_t r m) (cont_t r' m') := { congr := λ α β, cont_t.equiv (uliftable.congr _ _ F) } instance {s m m'} [uliftable m m'] : uliftable (cont_t s m) (cont_t (ulift s) m') := cont_t.uliftable' equiv.ulift.symm /-- for specific writer monads, this function helps to create a uliftable instance -/ def writer_t.uliftable' {m m'} [uliftable m m'] (F : w ≃ w') : uliftable (writer_t w m) (writer_t w' m') := { congr := λ α β G, writer_t.equiv $ uliftable.congr _ _ $ equiv.prod_congr G F } instance {m m'} [uliftable m m'] : uliftable (writer_t s m) (writer_t (ulift s) m') := writer_t.uliftable' equiv.ulift.symm
c9ec40e7e9bd40511a52ba9577ec8aaeff7da324
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/rat/cast.lean
b98a704e023766243d852a73b81330782dac867a
[]
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
8,462
lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.rat.order import Mathlib.data.int.char_zero import Mathlib.PostPort universes u_1 u_2 namespace Mathlib /-! # Casts for Rational Numbers ## Summary We define the canonical injection from ℚ into an arbitrary division ring and prove various casting lemmas showing the well-behavedness of this injection. ## Notations - `/.` is infix notation for `rat.mk`. ## Tags rat, rationals, field, ℚ, numerator, denominator, num, denom, cast, coercion, casting -/ namespace rat /-- Construct the canonical injection from `ℚ` into an arbitrary division ring. If the field has positive characteristic `p`, we define `1 / p = 1 / 0 = 0` for consistency with our division by zero convention. -/ -- see Note [coercion into rings] protected instance cast_coe {α : Type u_1} [division_ring α] : has_coe_t ℚ α := has_coe_t.mk fun (r : ℚ) => ↑(num r) / ↑(denom r) @[simp] theorem cast_of_int {α : Type u_1} [division_ring α] (n : ℤ) : ↑(of_int n) = ↑n := (fun (this : ↑n / ↑1 = ↑n) => this) (eq.mpr (id (Eq._oldrec (Eq.refl (↑n / ↑1 = ↑n)) nat.cast_one)) (eq.mpr (id (Eq._oldrec (Eq.refl (↑n / 1 = ↑n)) (div_one ↑n))) (Eq.refl ↑n))) @[simp] theorem cast_coe_int {α : Type u_1} [division_ring α] (n : ℤ) : ↑↑n = ↑n := eq.mpr (id (Eq._oldrec (Eq.refl (↑↑n = ↑n)) (coe_int_eq_of_int n))) (eq.mpr (id (Eq._oldrec (Eq.refl (↑(of_int n) = ↑n)) (cast_of_int n))) (Eq.refl ↑n)) @[simp] theorem cast_coe_nat {α : Type u_1} [division_ring α] (n : ℕ) : ↑↑n = ↑n := cast_coe_int ↑n @[simp] theorem cast_zero {α : Type u_1} [division_ring α] : ↑0 = 0 := Eq.trans (cast_of_int 0) int.cast_zero @[simp] theorem cast_one {α : Type u_1} [division_ring α] : ↑1 = 1 := Eq.trans (cast_of_int 1) int.cast_one theorem cast_commute {α : Type u_1} [division_ring α] (r : ℚ) (a : α) : commute (↑r) a := commute.div_left (int.cast_commute (num r) a) (nat.cast_commute (denom r) a) theorem commute_cast {α : Type u_1} [division_ring α] (a : α) (r : ℚ) : commute a ↑r := commute.symm (cast_commute r a) theorem cast_mk_of_ne_zero {α : Type u_1} [division_ring α] (a : ℤ) (b : ℤ) (b0 : ↑b ≠ 0) : ↑(mk a b) = ↑a / ↑b := sorry theorem cast_add_of_ne_zero {α : Type u_1} [division_ring α] {m : ℚ} {n : ℚ} : ↑(denom m) ≠ 0 → ↑(denom n) ≠ 0 → ↑(m + n) = ↑m + ↑n := sorry @[simp] theorem cast_neg {α : Type u_1} [division_ring α] (n : ℚ) : ↑(-n) = -↑n := sorry theorem cast_sub_of_ne_zero {α : Type u_1} [division_ring α] {m : ℚ} {n : ℚ} (m0 : ↑(denom m) ≠ 0) (n0 : ↑(denom n) ≠ 0) : ↑(m - n) = ↑m - ↑n := sorry theorem cast_mul_of_ne_zero {α : Type u_1} [division_ring α] {m : ℚ} {n : ℚ} : ↑(denom m) ≠ 0 → ↑(denom n) ≠ 0 → ↑(m * n) = ↑m * ↑n := sorry theorem cast_inv_of_ne_zero {α : Type u_1} [division_ring α] {n : ℚ} : ↑(num n) ≠ 0 → ↑(denom n) ≠ 0 → ↑(n⁻¹) = (↑n⁻¹) := sorry theorem cast_div_of_ne_zero {α : Type u_1} [division_ring α] {m : ℚ} {n : ℚ} (md : ↑(denom m) ≠ 0) (nn : ↑(num n) ≠ 0) (nd : ↑(denom n) ≠ 0) : ↑(m / n) = ↑m / ↑n := sorry @[simp] theorem cast_inj {α : Type u_1} [division_ring α] [char_zero α] {m : ℚ} {n : ℚ} : ↑m = ↑n ↔ m = n := sorry theorem cast_injective {α : Type u_1} [division_ring α] [char_zero α] : function.injective coe := fun {a₁ a₂ : ℚ} => idRhs (↑a₁ = ↑a₂ → a₁ = a₂) (iff.mp cast_inj) @[simp] theorem cast_eq_zero {α : Type u_1} [division_ring α] [char_zero α] {n : ℚ} : ↑n = 0 ↔ n = 0 := eq.mpr (id (Eq._oldrec (Eq.refl (↑n = 0 ↔ n = 0)) (Eq.symm cast_zero))) (eq.mpr (id (Eq._oldrec (Eq.refl (↑n = ↑0 ↔ n = 0)) (propext cast_inj))) (iff.refl (n = 0))) theorem cast_ne_zero {α : Type u_1} [division_ring α] [char_zero α] {n : ℚ} : ↑n ≠ 0 ↔ n ≠ 0 := not_congr cast_eq_zero @[simp] theorem cast_add {α : Type u_1} [division_ring α] [char_zero α] (m : ℚ) (n : ℚ) : ↑(m + n) = ↑m + ↑n := cast_add_of_ne_zero (iff.mpr nat.cast_ne_zero (ne_of_gt (pos m))) (iff.mpr nat.cast_ne_zero (ne_of_gt (pos n))) @[simp] theorem cast_sub {α : Type u_1} [division_ring α] [char_zero α] (m : ℚ) (n : ℚ) : ↑(m - n) = ↑m - ↑n := cast_sub_of_ne_zero (iff.mpr nat.cast_ne_zero (ne_of_gt (pos m))) (iff.mpr nat.cast_ne_zero (ne_of_gt (pos n))) @[simp] theorem cast_mul {α : Type u_1} [division_ring α] [char_zero α] (m : ℚ) (n : ℚ) : ↑(m * n) = ↑m * ↑n := cast_mul_of_ne_zero (iff.mpr nat.cast_ne_zero (ne_of_gt (pos m))) (iff.mpr nat.cast_ne_zero (ne_of_gt (pos n))) @[simp] theorem cast_bit0 {α : Type u_1} [division_ring α] [char_zero α] (n : ℚ) : ↑(bit0 n) = bit0 ↑n := cast_add n n @[simp] theorem cast_bit1 {α : Type u_1} [division_ring α] [char_zero α] (n : ℚ) : ↑(bit1 n) = bit1 ↑n := sorry /-- Coercion `ℚ → α` as a `ring_hom`. -/ def cast_hom (α : Type u_1) [division_ring α] [char_zero α] : ℚ →+* α := ring_hom.mk coe cast_one cast_mul cast_zero cast_add @[simp] theorem coe_cast_hom {α : Type u_1} [division_ring α] [char_zero α] : ⇑(cast_hom α) = coe := rfl @[simp] theorem cast_inv {α : Type u_1} [division_ring α] [char_zero α] (n : ℚ) : ↑(n⁻¹) = (↑n⁻¹) := ring_hom.map_inv (cast_hom α) n @[simp] theorem cast_div {α : Type u_1} [division_ring α] [char_zero α] (m : ℚ) (n : ℚ) : ↑(m / n) = ↑m / ↑n := ring_hom.map_div (cast_hom α) m n theorem cast_mk {α : Type u_1} [division_ring α] [char_zero α] (a : ℤ) (b : ℤ) : ↑(mk a b) = ↑a / ↑b := sorry @[simp] theorem cast_pow {α : Type u_1} [division_ring α] [char_zero α] (q : ℚ) (k : ℕ) : ↑(q ^ k) = ↑q ^ k := ring_hom.map_pow (cast_hom α) q k @[simp] theorem cast_nonneg {α : Type u_1} [linear_ordered_field α] {n : ℚ} : 0 ≤ ↑n ↔ 0 ≤ n := sorry @[simp] theorem cast_le {α : Type u_1} [linear_ordered_field α] {m : ℚ} {n : ℚ} : ↑m ≤ ↑n ↔ m ≤ n := sorry @[simp] theorem cast_lt {α : Type u_1} [linear_ordered_field α] {m : ℚ} {n : ℚ} : ↑m < ↑n ↔ m < n := sorry @[simp] theorem cast_nonpos {α : Type u_1} [linear_ordered_field α] {n : ℚ} : ↑n ≤ 0 ↔ n ≤ 0 := eq.mpr (id (Eq._oldrec (Eq.refl (↑n ≤ 0 ↔ n ≤ 0)) (Eq.symm cast_zero))) (eq.mpr (id (Eq._oldrec (Eq.refl (↑n ≤ ↑0 ↔ n ≤ 0)) (propext cast_le))) (iff.refl (n ≤ 0))) @[simp] theorem cast_pos {α : Type u_1} [linear_ordered_field α] {n : ℚ} : 0 < ↑n ↔ 0 < n := eq.mpr (id (Eq._oldrec (Eq.refl (0 < ↑n ↔ 0 < n)) (Eq.symm cast_zero))) (eq.mpr (id (Eq._oldrec (Eq.refl (↑0 < ↑n ↔ 0 < n)) (propext cast_lt))) (iff.refl (0 < n))) @[simp] theorem cast_lt_zero {α : Type u_1} [linear_ordered_field α] {n : ℚ} : ↑n < 0 ↔ n < 0 := eq.mpr (id (Eq._oldrec (Eq.refl (↑n < 0 ↔ n < 0)) (Eq.symm cast_zero))) (eq.mpr (id (Eq._oldrec (Eq.refl (↑n < ↑0 ↔ n < 0)) (propext cast_lt))) (iff.refl (n < 0))) @[simp] theorem cast_id (n : ℚ) : ↑n = n := sorry @[simp] theorem cast_min {α : Type u_1} [linear_ordered_field α] {a : ℚ} {b : ℚ} : ↑(min a b) = min ↑a ↑b := sorry @[simp] theorem cast_max {α : Type u_1} [linear_ordered_field α] {a : ℚ} {b : ℚ} : ↑(max a b) = max ↑a ↑b := sorry @[simp] theorem cast_abs {α : Type u_1} [linear_ordered_field α] {q : ℚ} : ↑(abs q) = abs ↑q := sorry end rat theorem ring_hom.eq_rat_cast {k : Type u_1} [division_ring k] (f : ℚ →+* k) (r : ℚ) : coe_fn f r = ↑r := sorry -- This seems to be true for a `[char_p k]` too because `k'` must have the same characteristic -- but the proof would be much longer theorem ring_hom.map_rat_cast {k : Type u_1} {k' : Type u_2} [division_ring k] [char_zero k] [division_ring k'] (f : k →+* k') (r : ℚ) : coe_fn f ↑r = ↑r := ring_hom.eq_rat_cast (ring_hom.comp f (rat.cast_hom k)) r theorem ring_hom.ext_rat {R : Type u_1} [semiring R] (f : ℚ →+* R) (g : ℚ →+* R) : f = g := sorry protected instance rat.subsingleton_ring_hom {R : Type u_1} [semiring R] : subsingleton (ℚ →+* R) := subsingleton.intro ring_hom.ext_rat
1c80399e58e919826781be3c5cdbe3dfbf37c4ca
367134ba5a65885e863bdc4507601606690974c1
/src/linear_algebra/unitary_group.lean
5eb311d4bac8d8dd10a712893c872412084ccd6d
[ "Apache-2.0" ]
permissive
kodyvajjha/mathlib
9bead00e90f68269a313f45f5561766cfd8d5cad
b98af5dd79e13a38d84438b850a2e8858ec21284
refs/heads/master
1,624,350,366,310
1,615,563,062,000
1,615,563,062,000
162,666,963
0
0
Apache-2.0
1,545,367,651,000
1,545,367,651,000
null
UTF-8
Lean
false
false
6,375
lean
/- Copyright (c) 2021 Shing Tak Lam. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Shing Tak Lam -/ import linear_algebra.matrix import linear_algebra.nonsingular_inverse import data.complex.basic /-! # The Unitary Group This file defines elements of the unitary group `unitary_group n α`, where `α` is a `star_ring`. This consists of all `n` by `n` matrices with entries in `α` such that the star-transpose is its inverse. In addition, we define the group structure on `unitary_group n α`, and the embedding into the general linear group `general_linear_group α (n → α)`. We also define the orthogonal group `orthogonal_group n β`, where `β` is a `comm_ring`. ## Main Definitions * `matrix.unitary_group` is the type of matrices where the star-transpose is the inverse * `matrix.unitary_group.group` is the group structure (under multiplication) * `matrix.unitary_group.embedding_GL` is the embedding `unitary_group n α → GLₙ(α)` * `matrix.orthogonal_group` is the type of matrices where the transpose is the inverse ## References * https://en.wikipedia.org/wiki/Unitary_group ## Tags matrix group, group, unitary group, orthogonal group -/ universes u v section variables (M : Type v) [monoid M] [star_monoid M] /-- In a `star_monoid M`, `unitary_submonoid M` is the submonoid consisting of all the elements of `M` such that `star A * A = 1`. -/ def unitary_submonoid : submonoid M := { carrier := {A | star A * A = 1}, one_mem' := by simp, mul_mem' := λ A B (hA : star A * A = 1) (hB : star B * B = 1), show star (A * B) * (A * B) = 1, by rwa [star_mul, ←mul_assoc, mul_assoc _ _ A, hA, mul_one] } end namespace matrix open linear_map open_locale matrix section variables (n : Type u) [decidable_eq n] [fintype n] variables (α : Type v) [comm_ring α] [star_ring α] /-- `unitary_group n` is the group of `n` by `n` matrices where the star-transpose is the inverse. -/ @[derive monoid] def unitary_group : Type* := unitary_submonoid (matrix n n α) end variables {n : Type u} [decidable_eq n] [fintype n] variables {α : Type v} [comm_ring α] [star_ring α] namespace unitary_submonoid lemma star_mem {A : matrix n n α} (h : A ∈ unitary_submonoid (matrix n n α)) : star A ∈ unitary_submonoid (matrix n n α) := matrix.nonsing_inv_left_right _ _ $ (star_star A).symm ▸ h @[simp] lemma star_mem_iff {A : matrix n n α} : star A ∈ unitary_submonoid (matrix n n α) ↔ A ∈ unitary_submonoid (matrix n n α) := ⟨λ ha, star_star A ▸ star_mem ha, star_mem⟩ end unitary_submonoid namespace unitary_group instance coe_matrix : has_coe (unitary_group n α) (matrix n n α) := ⟨subtype.val⟩ instance coe_fun : has_coe_to_fun (unitary_group n α) := { F := λ _, n → n → α, coe := λ A, A.val } /-- `to_lin' A` is matrix multiplication of vectors by `A`, as a linear map. After the group structure on `unitary_group n` is defined, we show in `to_linear_equiv` that this gives a linear equivalence. -/ def to_lin' (A : unitary_group n α) := matrix.to_lin' A lemma ext_iff (A B : unitary_group n α) : A = B ↔ ∀ i j, A i j = B i j := subtype.ext_iff_val.trans ⟨(λ h i j, congr_fun (congr_fun h i) j), matrix.ext⟩ @[ext] lemma ext (A B : unitary_group n α) : (∀ i j, A i j = B i j) → A = B := (unitary_group.ext_iff A B).mpr instance : has_inv (unitary_group n α) := ⟨λ A, ⟨star A.1, unitary_submonoid.star_mem_iff.mpr A.2⟩⟩ instance : star_monoid (unitary_group n α) := { star := λ A, ⟨star A.1, unitary_submonoid.star_mem A.2⟩, star_involutive := λ A, subtype.ext $ star_star A.1, star_mul := λ A B, subtype.ext $ star_mul A.1 B.1 } @[simp] lemma star_mul_self (A : unitary_group n α) : star A ⬝ A = 1 := A.2 instance : inhabited (unitary_group n α) := ⟨1⟩ section coe_lemmas variables (A B : unitary_group n α) @[simp] lemma inv_val : ↑(A⁻¹) = (star A : matrix n n α) := rfl @[simp] lemma inv_apply : ⇑(A⁻¹) = (star A : matrix n n α) := rfl @[simp] lemma mul_val : ↑(A * B) = A ⬝ B := rfl @[simp] lemma mul_apply : ⇑(A * B) = (A ⬝ B) := rfl @[simp] lemma one_val : ↑(1 : unitary_group n α) = (1 : matrix n n α) := rfl @[simp] lemma one_apply : ⇑(1 : unitary_group n α) = (1 : matrix n n α) := rfl @[simp] lemma to_lin'_mul : to_lin' (A * B) = (to_lin' A).comp (to_lin' B) := matrix.to_lin'_mul A B @[simp] lemma to_lin'_one : to_lin' (1 : unitary_group n α) = linear_map.id := matrix.to_lin'_one end coe_lemmas instance : group (unitary_group n α) := { mul_left_inv := λ A, subtype.eq A.2, ..unitary_group.has_inv, ..unitary_group.monoid n α } /-- `to_linear_equiv A` is matrix multiplication of vectors by `A`, as a linear equivalence. -/ def to_linear_equiv (A : unitary_group n α) : (n → α) ≃ₗ[α] (n → α) := { inv_fun := A⁻¹.to_lin', left_inv := λ x, calc A⁻¹.to_lin'.comp A.to_lin' x = (A⁻¹ * A).to_lin' x : by rw [←to_lin'_mul] ... = x : by rw [mul_left_inv, to_lin'_one, id_apply], right_inv := λ x, calc A.to_lin'.comp A⁻¹.to_lin' x = (A * A⁻¹).to_lin' x : by rw [←to_lin'_mul] ... = x : by rw [mul_right_inv, to_lin'_one, id_apply], ..matrix.to_lin' A } /-- `to_GL` is the map from the unitary group to the general linear group -/ def to_GL (A : unitary_group n α) : general_linear_group α (n → α) := general_linear_group.of_linear_equiv (to_linear_equiv A) lemma coe_to_GL (A : unitary_group n α) : ↑(to_GL A) = A.to_lin' := rfl @[simp] lemma to_GL_one : to_GL (1 : unitary_group n α) = 1 := by { ext1 v i, rw [coe_to_GL, to_lin'_one], refl } @[simp] lemma to_GL_mul (A B : unitary_group n α) : to_GL (A * B) = to_GL A * to_GL B := by { ext1 v i, rw [coe_to_GL, to_lin'_mul], refl } /-- `unitary_group.embedding_GL` is the embedding from `unitary_group n α` to `general_linear_group n α`. -/ def embedding_GL : unitary_group n α →* general_linear_group α (n → α) := ⟨λ A, to_GL A, by simp, by simp⟩ end unitary_group section orthogonal_group variables (β : Type v) [comm_ring β] local attribute [instance] star_ring_of_comm /-- `orthogonal_group n` is the group of `n` by `n` matrices where the transpose is the inverse. -/ abbreviation orthogonal_group := unitary_group n β end orthogonal_group end matrix
60404d9fc463b5cb110781c13ef2ec2c459e6d7d
8c02fed42525b65813b55c064afe2484758d6d09
/src/lang.lean
fd6634e345dd3d84be841ec36908c84d088eb612
[ "LicenseRef-scancode-generic-cla", "MIT" ]
permissive
microsoft/AliveInLean
3eac351a34154efedd3ffc4fe2fa4ec01b219e0d
4b739dd6e4266b26a045613849df221374119871
refs/heads/master
1,691,419,737,939
1,689,365,567,000
1,689,365,568,000
131,156,103
23
18
NOASSERTION
1,660,342,040,000
1,524,747,538,000
Lean
UTF-8
Lean
false
false
3,398
lean
-- Copyright (c) Microsoft Corporation. All rights reserved. -- Licensed under the MIT license. -- constant value inductive const : Type | int : ℤ → const -- register -- Design choice: Let reg store its name, but not -- its type. Reason is that, if reg contains type, -- modifying register's type should track all -- def-use chains. inductive reg : Type | r : string → reg -- value inductive operand : Type | reg : reg → operand | const : const → operand -- type inductive ty : Type | int : ℕ → ty | arbitrary_int : ty -- for (t1:ty) (t2:ty), t1 = t2 is decidable. instance : decidable_eq ty := by tactic.mk_dec_eq_instance -- binary operation inductive bopcode : Type | add | sub | mul | udiv | urem | sdiv | srem | and | or | xor | shl | lshr | ashr instance : decidable_eq bopcode := by tactic.mk_dec_eq_instance -- Returns true if given bopcode is div or rem @[reducible, simp] def bop_isdiv : bopcode → bool | bopcode.udiv := tt | bopcode.urem := tt | bopcode.sdiv := tt | bopcode.srem := tt | _ := ff inductive bopflag : Type | nsw | nuw | exact @[reducible] def bop_availflags : bopcode → list bopflag | bopcode.add := [bopflag.nsw, bopflag.nuw] | bopcode.sub := [bopflag.nsw, bopflag.nuw] | bopcode.mul := [bopflag.nsw, bopflag.nuw] | bopcode.shl := [bopflag.nsw, bopflag.nuw] | bopcode.udiv := [bopflag.exact] | bopcode.sdiv := [bopflag.exact] | bopcode.urem := [] | bopcode.srem := [] | bopcode.lshr := [bopflag.exact] | bopcode.ashr := [bopflag.exact] | bopcode.and := [] | bopcode.or := [] | bopcode.xor := [] -- icmp operation inductive icmpcond : Type | eq | ne | ugt | uge | ult | ule | sgt | sge | slt | sle -- unary operation inductive uopcode : Type | freeze | zext | sext | trunc -- instruction -- TODO: the order of parameters should be consistent inductive instruction : Type -- binop: operations in https://github.com/nunoplopes/alive/blob/newsema/language.py#L278 | binop : ty → reg → bopcode → list bopflag → operand → operand → instruction | icmpop : ty → reg → icmpcond → operand → -- opty, lhs, cond, op1, op2 operand → instruction | selectop : reg → ty → operand → ty → operand → -- condty, opty operand → instruction | unaryop : reg → uopcode → ty → operand → ty → instruction -- fromty, toty -- program structure program : Type := (insts: list instruction) -- transformation structure transformation : Type := (name:string) (src:program) (tgt:program) -- precondition mutual inductive precond_fun, precond_exp with precond_fun : Type -- isPower2(x): returns true if x is guaranteed to -- be power of 2, returns false otherwise | is_power2 : precond_exp → precond_fun -- mayAlias(p, q): returns true if p and q may alias. -- If p and q are guaranteed not to alias, -- it returns false. | may_alias : precond_exp → precond_exp → precond_fun with precond_exp : Type -- E1 && E2, E1 & E2 -- E1 and E2 may be either bool or int type. | and : precond_exp → precond_exp → precond_exp -- E1 || E2, E1 | E2 -- E1 and E2 may be either bool or int type. | or : precond_exp → precond_exp → precond_exp -- ~E -- E may be either bool or int type. | not : precond_exp → precond_exp -- Value (register or constant) | v : operand → precond_exp -- Function call | fcall : precond_fun → precond_exp
1ba1c564092d0b29ac4784e4b7781daa273e6aba
5d76f062116fa5bd22eda20d6fd74da58dba65bb
/src/snarks/sonic/vars.lean
bb1b17e4a67965e76abf0bfbf4649c549bba7b08
[]
no_license
brando90/formal_baby_snark
59e4732dfb43f97776a3643f2731262f58d2bb81
4732da237784bd461ff949729cc011db83917907
refs/heads/master
1,682,650,246,414
1,621,103,975,000
1,621,103,975,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
105
lean
section @[derive decidable_eq] inductive vars : Type | x : vars | y : vars | z : vars | α : vars end
cc583086adaf2058e4db26c1934ec083f974015d
c61b91f85121053c627318ad8fcde30dfb8637d2
/Chapter5/5-1to3.lean
ecd4e2abed706ddec22edce1a2bb988067ff7bf4
[]
no_license
robkorn/theorem-proving-in-lean-exercises
9e2256360eaf6f8df6cdd8fd656e63dfb04c8cdb
9c51da587105ee047a9db55d52709d881a39be7a
refs/heads/master
1,585,403,341,988
1,540,142,619,000
1,540,142,619,000
148,431,678
2
0
null
null
null
null
UTF-8
Lean
false
false
2,365
lean
theorem test (p q : Prop) (hp : p) (hq : q) : p ∧ q ∧ p := begin apply and.intro hp, exact and.intro hq hp end theorem test' (p q : Prop) (hp : p) (hq : q) : p ∧ q ∧ p := by exact and.intro hp (and.intro hq hp) #print test example (p q r : Prop) : p ∧ (q ∨ r) ↔ (p ∧ q) ∨ (p ∧ r) := begin apply iff.intro, intro h, apply or.elim (and.right h), intro hq, apply or.inl, apply and.intro, exact h.left, exact hq, intro hr, apply or.inr, apply and.intro, exact h.left, exact hr, intro h, apply or.elim h, intro hpq, apply and.intro, exact hpq.left, apply or.inl, exact hpq.right, intro hpr, apply and.intro, exact hpr.left, apply or.inr, exact hpr.right end example : ∀ a b c : ℕ, a = b → a = c → c = b := begin intros a b c h1 h2, exact eq.trans (eq.symm h2) h1, end variables x y z w : ℕ example (h1 : x = y) (h2 : y = z) (h3 : z = w) : x = w := begin apply eq.trans h1, apply eq.trans h2, assumption end example : ∀ a b c : ℕ, a = b → a = c → c = b := begin intros, transitivity a, symmetry, repeat { assumption}, end example : ∃ a : ℕ, 5 = a := begin apply exists.intro, reflexivity, end example : ∃ a : ℕ, a = a := begin fapply exists.intro, exact 0, reflexivity end example (x : ℕ) : x = x := begin revert x, intro y, refl, end example (p q : Prop) : p ∨ q → q ∨ p := begin intro h, cases h with hp hq, right, exact hp, left, exact hq, end example (p q : Prop) : p ∧ q → q ∧ p := begin intro h, cases h with hp hq, constructor, exact hq, exact hp, end example (p q : ℕ → Prop) : (∃ x, p x) → ∃ x, p x ∨ q x := begin intro h, cases h with x px, constructor, left, exact px, end universes u v def swap_pair {α : Type u} {β : Type v} : α × β → β × α := begin intro p, cases p with ha hb, constructor, exact hb, exact ha end def swap_sum {α : Type u} {β : Type v} : α ⊕ β → β ⊕ α := begin intro p, cases p with ha hb, right, exact ha, left, exact hb end open nat example (P : ℕ → Prop) (h0 : P 0) (h1 : ∀ n, P (succ n)) (m : ℕ) : P m := begin cases m with m', exact h0, exact h1 m', end example (p q : Prop) : p ∧ ¬ p → q := begin intro h, cases h, contradiction end
b7e6ee3e0d7d28218b69a1f3f49aeb7b943a5f4e
1b8f093752ba748c5ca0083afef2959aaa7dace5
/src/category_theory/universal/uniqueness.lean
5276ad39aa468df3b8a280ab1ae61ce024817d64
[]
no_license
khoek/lean-category-theory
7ec4cda9cc64a5a4ffeb84712ac7d020dbbba386
63dcb598e9270a3e8b56d1769eb4f825a177cd95
refs/heads/master
1,585,251,725,759
1,539,344,445,000
1,539,344,445,000
145,281,070
0
0
null
1,534,662,376,000
1,534,662,376,000
null
UTF-8
Lean
false
false
2,056
lean
import category_theory.limits universes u v open category_theory namespace category_theory.limits variables {C : Type u} [𝒞 : category.{u v} C] include 𝒞 section @[extensionality] lemma homs_to_terminal_ext (X' : C) (X : C) (h : is_terminal.{u v} X) (f g : X' ⟶ X) : f = g := begin rw h.uniq X' f, rw h.uniq X' g, end def terminals_iso (A B : C) (h_A : is_terminal.{u v} A) (h_B : is_terminal.{u v} B) : A ≅ B := { hom := is_terminal.lift.{u v} h_B A, inv := is_terminal.lift.{u v} h_A B } end section def binary_products_iso {Y Z : C} (A B : span.{u v} Y Z) (h_A : is_binary_product A) (h_B : is_binary_product B) : A.X ≅ B.X := { hom := is_binary_product.lift h_B A, inv := is_binary_product.lift h_A B, hom_inv_id' := sorry, inv_hom_id' := sorry } end section def equalizers_iso {Y Z : C} {f g : Y ⟶ Z} (A B : fork.{u v} f g) (A_w : is_equalizer A) (B_w : is_equalizer B) : A.X ≅ B.X := { hom := B_w.lift A, inv := A_w.lift B, hom_inv_id' := sorry, inv_hom_id' := sorry } end section def pullbacks_iso {Y₁ Y₂ Z : C} {r₁ : Y₁ ⟶ Z} {r₂ : Y₂ ⟶ Z} (A B : square.{u v} r₁ r₂) (A_w : is_pullback A) (B_w : is_pullback B): A.X ≅ B.X := { hom := B_w.lift A, inv := A_w.lift B, hom_inv_id' := sorry, inv_hom_id' := sorry } end variables {J : Type v} [𝒥 : small_category J] include 𝒥 -- section -- FIXME this is a horrible formulation -- lemma homs_to_limit_ext {F : J ⥤ C} (c : cone.{u v} F) [is_limit c] {X : C} (f g : X ⟶ c.X) (w : ∀ j, f ≫ c.π j = g ≫ c.π j) : f = g := -- begin -- let s : cone F := ⟨ ⟨ X ⟩, λ j, f ≫ c.π j, by obviously ⟩, -- have q := is_limit.uniq _ s f, -- have p := is_limit.uniq _ s g, -- rw [q, ←p], -- intros, -- rw ← w j, -- intros, -- refl -- end -- local attribute [back] homs_to_limit_ext -- def limits_iso {F : J ⥤ C} (A B : cone.{u v} F) (h_A : is_limit A) (h_B : is_limit B) : A.X ≅ B.X := -- { hom := is_limit.lift h_B A, -- inv := is_limit.lift h_A B } -- end end category_theory.limits
69e45e76d6105e7eb0d520f5310173e008000fe6
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/library/data/set/map.lean
f313d8bb73818c13957bc47e649bd1e5d7032c89
[ "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
6,148
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad, Andrew Zipperer Functions between subsets of finite types, bundled with the domain and range. -/ import data.set.function open eq.ops namespace set record map {X Y : Type} (a : set X) (b : set Y) := (func : X → Y) (mapsto : maps_to func a b) -- attribute map.func [coercion] namespace map variables {X Y Z: Type} variables {a : set X} {b : set Y} {c : set Z} /- the equivalence relation -/ attribute [reducible] protected definition equiv (f1 f2 : map a b) : Prop := eq_on f1 f2 a namespace equiv_notation infix `~` := map.equiv end equiv_notation open equiv_notation protected theorem equiv.refl (f : map a b) : f ~ f := take x, assume H, rfl protected theorem equiv.symm {f₁ f₂ : map a b} : f₁ ~ f₂ → f₂ ~ f₁ := assume H : f₁ ~ f₂, take x, assume Ha : x ∈ a, eq.symm (H Ha) protected theorem equiv.trans {f₁ f₂ f₃ : map a b} : f₁ ~ f₂ → f₂ ~ f₃ → f₁ ~ f₃ := assume H₁ : f₁ ~ f₂, assume H₂ : f₂ ~ f₃, take x, assume Ha : x ∈ a, eq.trans (H₁ Ha) (H₂ Ha) protected theorem equiv.is_equivalence {X Y : Type} (a : set X) (b : set Y) : equivalence (@map.equiv X Y a b) := mk_equivalence (@map.equiv X Y a b) (@equiv.refl X Y a b) (@equiv.symm X Y a b) (@equiv.trans X Y a b) /- compose -/ protected definition comp (g : map b c) (f : map a b) : map a c := map.mk (#function g ∘ f) (maps_to_comp (mapsto g) (mapsto f)) notation g ∘ f := map.comp g f /- range -/ protected definition range (f : map a b) : set Y := image f a theorem range_eq_range_of_equiv {f1 f2 : map a b} (H : f1 ~ f2) : map.range f1 = map.range f2 := image_eq_image_of_eq_on H /- injective -/ protected definition injective (f : map a b) : Prop := inj_on f a theorem injective_of_equiv {f1 f2 : map a b} (H1 : f1 ~ f2) (H2 : map.injective f1) : map.injective f2 := inj_on_of_eq_on H1 H2 theorem injective_comp {g : map b c} {f : map a b} (Hg : map.injective g) (Hf: map.injective f) : map.injective (g ∘ f) := inj_on_comp (mapsto f) Hg Hf /- surjective -/ protected definition surjective (f : map a b) : Prop := surj_on f a b theorem surjective_of_equiv {f1 f2 : map a b} (H1 : f1 ~ f2) (H2 : map.surjective f1) : map.surjective f2 := surj_on_of_eq_on H1 H2 theorem surjective_comp {g : map b c} {f : map a b} (Hg : map.surjective g) (Hf: map.surjective f) : map.surjective (g ∘ f) := surj_on_comp Hg Hf theorem image_eq_of_surjective {f : map a b} (H : map.surjective f) : f ' a = b := image_eq_of_maps_to_of_surj_on (map.mapsto f) H /- bijective -/ protected definition bijective (f : map a b) : Prop := map.injective f ∧ map.surjective f theorem bijective_of_equiv {f1 f2 : map a b} (H1 : f1 ~ f2) (H2 : map.bijective f1) : map.bijective f2 := and.intro (injective_of_equiv H1 (and.left H2)) (surjective_of_equiv H1 (and.right H2)) theorem bijective_comp {g : map b c} {f : map a b} (Hg : map.bijective g) (Hf: map.bijective f) : map.bijective (g ∘ f) := obtain Hg₁ Hg₂, from Hg, obtain Hf₁ Hf₂, from Hf, and.intro (injective_comp Hg₁ Hf₁) (surjective_comp Hg₂ Hf₂) theorem image_eq_of_bijective {f : map a b} (H : map.bijective f) : f ' a = b := image_eq_of_surjective (proof and.right H qed) /- left inverse -/ -- g is a left inverse to f protected definition left_inverse (g : map b a) (f : map a b) : Prop := left_inv_on g f a theorem left_inverse_of_equiv_left {g1 g2 : map b a} {f : map a b} (eqg : g1 ~ g2) (H : map.left_inverse g1 f) : map.left_inverse g2 f := left_inv_on_of_eq_on_left (mapsto f) eqg H theorem left_inverse_of_equiv_right {g : map b a} {f1 f2 : map a b} (eqf : f1 ~ f2) (H : map.left_inverse g f1) : map.left_inverse g f2 := left_inv_on_of_eq_on_right eqf H theorem injective_of_left_inverse {g : map b a} {f : map a b} (H : map.left_inverse g f) : map.injective f := inj_on_of_left_inv_on H theorem left_inverse_comp {f' : map b a} {g' : map c b} {g : map b c} {f : map a b} (Hf : map.left_inverse f' f) (Hg : map.left_inverse g' g) : map.left_inverse (f' ∘ g') (g ∘ f) := left_inv_on_comp (mapsto f) Hf Hg /- right inverse -/ -- g is a right inverse to f protected definition right_inverse (g : map b a) (f : map a b) : Prop := map.left_inverse f g theorem right_inverse_of_equiv_left {g1 g2 : map b a} {f : map a b} (eqg : g1 ~ g2) (H : map.right_inverse g1 f) : map.right_inverse g2 f := map.left_inverse_of_equiv_right eqg H theorem right_inverse_of_equiv_right {g : map b a} {f1 f2 : map a b} (eqf : f1 ~ f2) (H : map.right_inverse g f1) : map.right_inverse g f2 := map.left_inverse_of_equiv_left eqf H theorem right_inverse_of_injective_of_left_inverse {f : map a b} {g : map b a} (injf : map.injective f) (lfg : map.left_inverse f g) : map.right_inverse f g := right_inv_on_of_inj_on_of_left_inv_on (mapsto f) (mapsto g) injf lfg theorem surjective_of_right_inverse {g : map b a} {f : map a b} (H : map.right_inverse g f) : map.surjective f := surj_on_of_right_inv_on (mapsto g) H theorem left_inverse_of_surjective_of_right_inverse {f : map a b} {g : map b a} (surjf : map.surjective f) (rfg : map.right_inverse f g) : map.left_inverse f g := left_inv_on_of_surj_on_right_inv_on surjf rfg theorem right_inverse_comp {f' : map b a} {g' : map c b} {g : map b c} {f : map a b} (Hf : map.right_inverse f' f) (Hg : map.right_inverse g' g) : map.right_inverse (f' ∘ g') (g ∘ f) := map.left_inverse_comp Hg Hf theorem equiv_of_map.left_inverse_of_right_inverse {g1 g2 : map b a} {f : map a b} (H1 : map.left_inverse g1 f) (H2 : map.right_inverse g2 f) : g1 ~ g2 := eq_on_of_left_inv_of_right_inv (mapsto g2) H1 H2 /- inverse -/ -- g is an inverse to f protected definition is_inverse (g : map b a) (f : map a b) : Prop := map.left_inverse g f ∧ map.right_inverse g f theorem bijective_of_is_inverse {g : map b a} {f : map a b} (H : map.is_inverse g f) : map.bijective f := and.intro (injective_of_left_inverse (and.left H)) (surjective_of_right_inverse (and.right H)) end map end set
b8540d87ccf369cbb6ece1e55a49586bde0b5c3c
e09201d437062e1f95e6e5360aab0c9f947901aa
/src/automata/epsnfa_triv.lean
dd54126264038bff381b62e285e421720ea0d226
[]
no_license
VArtem/lean-regular-languages
34f4b093f28ef2f09ba7e684e642a0f97c901560
e877243188253d0ac17ccf0ae2da7bf608686ff0
refs/heads/master
1,683,590,111,306
1,622,307,234,000
1,622,307,234,000
284,232,653
7
0
null
null
null
null
UTF-8
Lean
false
false
2,950
lean
import data.set.basic import data.finset.basic import automata.epsnfa import languages.basic import languages.star open set epsnfa languages namespace epsnfa.triv variables {S : Type} [fintype S] [decidable_eq S] def epsnfa_empty : epsNFA S bool := { start := ff, term := tt, next := λ q c, ∅, eps := λ q, ∅, } theorem epsnfa_empty_eq : lang_of_epsnfa (epsnfa_empty : epsNFA S _) = ∅ := begin rw eq_empty_iff_forall_not_mem, rintro x (_ | ⟨_, _, _, _, _, hnxt, _⟩ | ⟨_, _, _, _, hnxt, _⟩); simpa [epsnfa_empty] using hnxt, end theorem empty_is_epsnfa_lang : epsnfa_lang (∅ : set (list S)) := by exactI ⟨bool, _, _, epsnfa_empty, epsnfa_empty_eq⟩ def epsnfa_eps : epsNFA S bool := { start := ff, term := tt, next := λ q c, ∅, eps := bool.rec {tt} ∅ } theorem epsnfa_eps_eq : lang_of_epsnfa (epsnfa_eps : epsNFA S _) = {[]} := begin ext w, split, { rintro hw, cases hw, case epsnfa.go.step : { exfalso; simpa [epsnfa_eps] using hw_h, }, case epsnfa.go.eps : _ _ h_nxt h_go { simp [epsnfa_eps] at h_nxt, subst h_nxt, cases h_go, simp only [mem_singleton], simpa only [mem_singleton_iff] using h_go_h, simpa only [epsnfa_eps, mem_empty_eq] using h_go_h, } }, { rintro hw, rw [mem_singleton_iff] at hw, subst hw, refine go.eps _ (go.finish), simp only [epsnfa_eps, mem_singleton], } end theorem eps_is_epsnfa_lang : epsnfa_lang ({[]} : set (list S)) := by exactI ⟨bool, _, _, epsnfa_eps, epsnfa_eps_eq⟩ def epsnfa_one (char : S) : epsNFA S bool := { start := ff, term := tt, next := λ q c, bool.rec_on q (if (c = char) then {tt} else ∅) ∅, eps := λ q, ∅ } theorem epsnfa_one_eq {char : S} : lang_of_epsnfa (epsnfa_one char) = {[char]} := begin ext w, split, { rintro hw, cases hw, case epsnfa.go.step : _ _ _ h_nxt h_go { simp only [epsnfa_one, dite_eq_ite] at h_nxt, split_ifs at h_nxt, { simp [epsnfa_one, h] at h_nxt, substs h_nxt h, cases h_go, simp only [mem_singleton], simpa only [mem_singleton_iff, and_false], simpa only [epsnfa_one, mem_empty_eq] using h_go_h, }, { simpa only [mem_empty_eq] using h_nxt, } }, { simpa [epsnfa_one] using hw_h, } }, { rintro hw, rw [mem_singleton_iff] at hw, subst hw, refine go.step _ go.finish, simp [epsnfa_one], simp only [if_true, eq_self_iff_true, mem_singleton], } end theorem one_is_epsnfa_lang {char : S} : epsnfa_lang ({[char]} : set (list S)) := by exactI ⟨bool, _, _, epsnfa_one char, epsnfa_one_eq⟩ end epsnfa.triv
748913abc48bcddb60b4d44e4cb6a34560fcb235
205f0fc16279a69ea36e9fd158e3a97b06834ce2
/HOMEWORK/HW3.lean
cf1fc48defc9228195f275dc872e7c40a9f7f83a
[]
no_license
kevinsullivan/cs-dm-lean
b21d3ca1a9b2a0751ba13fcb4e7b258010a5d124
a06a94e98be77170ca1df486c8189338b16cf6c6
refs/heads/master
1,585,948,743,595
1,544,339,346,000
1,544,339,346,000
155,570,767
1
3
null
1,541,540,372,000
1,540,995,993,000
Lean
UTF-8
Lean
false
false
5,789
lean
/- This homework assignment will be due in class on Thursday, September. Edit your answers into this file and save your answers. Know where the file is in your file system so that you can submit it to Collab during class. To be ready for this homework, you should be sure to have read all of the class material up to and including 03_Conjunction, and you should have (on your own or in class) done all of the exercises in those units. -/ /- 1. Produce a proof, pf1, of the proposition that 0 = 0 ∧ (1 = 1 ∧ 2 = 2). -/ -- WRITE ANSWER HERE /- 2. Produce a proof, pf2, of the proposition that (0 = 0 ∧ 1 = 1) ∧ 2 = 2 -/ -- WRITE ANSWER HERE /- 3. Produce a proof, pf3, of the proposition that 0 = 0 ∧ 1 = 1 ∧ 2 = 2. Hint, one of the two preceding proofs can be used to prove this proposition; there's no need to type out a whole new proof. -/ -- WRITE ANSWER HERE /- 4. An operator, *, is "right associative" if X * Y * Z means X * (Y * Z), and is "left associative" if X * Y * Z means (X * Y) * Y. Is the logical connective, ∧, left or right associative? Explain. -/ -- WRITE ANSWER HERE /- 5. Use Lean to produce a proof, pf4, that 0 = 0 ∧ 1 = 1 ∧ 2 = 2 is exactly the same proposition as one of the two parenthesized forms. It will be a proof that two propositions are equal. Put parentheses around each of the propositions. -/ -- WRITE ANSWER HERE /- 6. Given arbitrary propositions, P, Q and R it should be possible to produce a proof, pf5, showing that if P ∧ (Q ∧ R) is true then so is (P ∧ Q) ∧ R. Written in inference rule form, this would say the following: { P Q R: Prop }, p_qr: P ∧ (Q ∧ R) ---------------------------------- ∧.assoc_l pq_r : (P ∧ Q) ∧ R Proving that this is a valid rule can be done by defining a function, let's call it and_assoc_l, that when given any propositions, P, Q, and R (implicitly), and when given a proof of P ∧ (Q ∧ R), constructs and returns a proof of (P ∧ Q) ∧ R. Here we give you this function, and we explain each part in comments. You will then apply what you learn by studying this example to solve the same problem but going in the other direction. Here's the solution. -/ -- define the function name def and_assoc_l -- specify the arguments and their types {P Q R: Prop} (pf: P ∧ (Q ∧ R)) : -- note colon -- the return type (P ∧ Q) ∧ R /- What we've given so far is what we call the function signature: its name, the names and types of the arguments that it takes, and the type of the return value. In this case, the return value is of type (P ∧ Q) ∧ R, and will thus serve as a proof of this proposition. This is a function that takes a proof and returns a (different) proof. It thus provides a general recipe for turning any proof of P ∧ (Q ∧ R) into a proof of (P ∧ Q) ∧ R. -/ := -- now give function body /- Usually we'd expect to see an expression here, involving multiple, nested and.elim and and.intro expressions. We could write the function body that way, but it's a bit tricky to get all the nested expressions right. Here's a revelation: We can use a tactic script to produce the same result. Open your Messages window, put your cursor on begin, study carefully the tactic state, notice that the arguments are given in the context to the left of the turnstile and the goal remaining to be proved is to the right. You can use the context values as arguments to tactics. Now click through each line of the script and study very carefully how it changes the context. By the end of the script, you should see how we've been able to use elimination rules take apart the proof that was given as an argument, giving names to the parts, and how we can then further take apart those parts, giving names to the subparts, and finally how we can intro rules to put all these pieces together again into the proof we need. -/ begin have pfP := and.elim_left pf, have pfQR := and.elim_right pf, have pfQ := and.elim_left pfQR, have pfR := and.elim_right pfQR, have pfPQ := and.intro pfP pfQ, have pfPQ_R := and.intro pfPQ pfR, exact pfPQ_R end /- Define another function, and_assoc_r, that goes the other direction: given a proof of (P ∧ Q) ∧ R it derives and returns a proof of P ∧ (Q ∧ R). Write the entire solution yourself. -/ -- WRITE ANSWER HERE /- 7. It's important to learn how you would give such proofs in natural langage. Let's take our first example. Here is a natural language version. "Given arbitrary propositions, P, Q, and R, and the assumption that P ∧ (Q ∧ R) is true, we are to show that (P ∧ Q) ∧ R is true. Given that P ∧ (Q ∧ R) is true, it must be that P is true and that Q ∧ R is also true. Given that Q ∧ R is true, it must be that Q is true, and R is also true. So we have that P, Q, and R are all true. From these conclusions we can in turn deduce that P ∧ Q must be true. And so we now have that P ∧ Q is true and so is R, from which, finally we can deduce that (P ∧ Q) ∧ R must be true as well. QED." Now it's your turn: write an English language proof for the theorem in the other direction. -/ -- WRITE ANSWER HERE /- 8. Use Lean to produce a proof, tnott, of the proposition that truth isn't truth. I.e., true is not true. We'll write this is Lean like this: theorem tnott: true ≠ true := _. To make it a little easier to solve this otherwise difficult problem, we allow you to stipulate one "axiom" of your choice, which you can then use to produce the required proof. -/ -- WRITE ANSWER HERE -- You can introduce an axiom here -- Now prove the theorem here /- What did you have to accept to be able to prove that truth isn't truth? -/ -- YOUR ANSWER HERE
eea654f21e93d862de6263e446d94ea39ae57923
22e97a5d648fc451e25a06c668dc03ac7ed7bc25
/src/init_/data/nat/lemmas.lean
0b50fa3b9aa353be9bffb0cf6e871cc6310373de
[ "Apache-2.0" ]
permissive
keeferrowan/mathlib
f2818da875dbc7780830d09bd4c526b0764a4e50
aad2dfc40e8e6a7e258287a7c1580318e865817e
refs/heads/master
1,661,736,426,952
1,590,438,032,000
1,590,438,032,000
266,892,663
0
0
Apache-2.0
1,590,445,835,000
1,590,445,835,000
null
UTF-8
Lean
false
false
3,545
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 -/ import algebra.ordered_ring /- Results copied from the core library to mathlib by Johan Commelin -/ namespace nat instance : zero_ne_one_class ℕ := { zero := 0, one := 1, zero_ne_one := nat.zero_ne_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 } instance : decidable_linear_ordered_semiring nat := { add_left_cancel := @nat.add_left_cancel, add_right_cancel := @nat.add_right_cancel, lt := nat.lt, 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_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_eq := nat.decidable_eq, ..nat.comm_semiring, ..nat.decidable_linear_order } -- all the fields are already included in the decidable_linear_ordered_semiring instance instance : decidable_linear_ordered_cancel_add_comm_monoid ℕ := { add_left_cancel := @nat.add_left_cancel, ..nat.decidable_linear_ordered_semiring } /- 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 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 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 theorem one_add (n : ℕ) : 1 + n = succ n := by simp [add_comm] end nat
767e97c7ad7a14afb7752744341b07db3b99646b
e61a235b8468b03aee0120bf26ec615c045005d2
/stage0/src/Init/Control/Except.lean
117492c9872487501d03a528d161a9b712806b27
[ "Apache-2.0" ]
permissive
SCKelemen/lean4
140dc63a80539f7c61c8e43e1c174d8500ec3230
e10507e6615ddbef73d67b0b6c7f1e4cecdd82bc
refs/heads/master
1,660,973,595,917
1,590,278,033,000
1,590,278,033,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,082
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)
2a66f6bf0677cebfcd791a99fe948637ee79cce9
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/order/category/PartialOrder.lean
b3991e433bbb9b609ceed7b83736337cb29d7a1e
[ "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
2,097
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 order.category.Preorder /-! # Category of partial orders This defines `PartialOrder`, the category of partial orders with monotone maps. -/ open category_theory universe u /-- The category of partially ordered types. -/ def PartialOrder := bundled partial_order namespace PartialOrder instance : bundled_hom.parent_projection @partial_order.to_preorder := ⟨⟩ attribute [derive [large_category, concrete_category]] PartialOrder instance : has_coe_to_sort PartialOrder Type* := bundled.has_coe_to_sort /-- Construct a bundled PartialOrder from the underlying type and typeclass. -/ def of (α : Type*) [partial_order α] : PartialOrder := bundled.of α instance : inhabited PartialOrder := ⟨of punit⟩ instance (α : PartialOrder) : partial_order α := α.str instance has_forget_to_Preorder : has_forget₂ PartialOrder Preorder := bundled_hom.forget₂ _ _ /-- Constructs an equivalence between partial orders from an order isomorphism between them. -/ @[simps] def iso.mk {α β : PartialOrder.{u}} (e : α ≃o β) : α ≅ β := { hom := e, inv := e.symm, hom_inv_id' := by { ext, exact e.symm_apply_apply x }, inv_hom_id' := by { ext, exact e.apply_symm_apply x } } /-- `order_dual` as a functor. -/ @[simps] def to_dual : PartialOrder ⥤ PartialOrder := { obj := λ X, of (order_dual X), map := λ X Y, order_hom.dual } /-- The equivalence between `PartialOrder` and itself induced by `order_dual` both ways. -/ @[simps functor inverse] def dual_equiv : PartialOrder ≌ PartialOrder := equivalence.mk to_dual to_dual (nat_iso.of_components (λ X, iso.mk $ order_iso.dual_dual X) $ λ X Y f, rfl) (nat_iso.of_components (λ X, iso.mk $ order_iso.dual_dual X) $ λ X Y f, rfl) end PartialOrder lemma PartialOrder_dual_equiv_comp_forget_to_Preorder : PartialOrder.dual_equiv.functor ⋙ forget₂ PartialOrder Preorder = forget₂ PartialOrder Preorder ⋙ Preorder.dual_equiv.functor := rfl
260f07e610d74cd1a9e42612e268b56acc7e1356
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/analysis/convex/intrinsic.lean
f3e91c330fe29949b36b4ae620327e734b0ec138
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
14,197
lean
/- Copyright (c) 2023 Paul Reichert. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Paul Reichert, Yaël Dillies -/ import analysis.normed_space.add_torsor_bases /-! # Intrinsic frontier and interior > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines the intrinsic frontier, interior and closure of a set in a normed additive torsor. These are also known as relative frontier, interior, closure. The intrinsic frontier/interior/closure of a set `s` is the frontier/interior/closure of `s` considered as a set in its affine span. The intrinsic interior is in general greater than the topological interior, the intrinsic frontier in general less than the topological frontier, and the intrinsic closure in cases of interest the same as the topological closure. ## Definitions * `intrinsic_interior`: Intrinsic interior * `intrinsic_frontier`: Intrinsic frontier * `intrinsic_closure`: Intrinsic closure ## Results The main results are: * `affine_isometry.image_intrinsic_interior`/`affine_isometry.image_intrinsic_frontier`/ `affine_isometry.image_intrinsic_closure`: Intrinsic interiors/frontiers/closures commute with taking the image under an affine isometry. * `set.nonempty.intrinsic_interior`: The intrinsic interior of a nonempty convex set is nonempty. ## References * Chapter 8 of [Barry Simon, *Convexity*][simon2011] * Chapter 1 of [Rolf Schneider, *Convex Bodies: The Brunn-Minkowski theory*][schneider2013]. ## TODO * `is_closed s → is_extreme 𝕜 s (intrinsic_frontier 𝕜 s)` * `x ∈ s → y ∈ intrinsic_interior 𝕜 s → open_segment 𝕜 x y ⊆ intrinsic_interior 𝕜 s` -/ open affine_subspace set open_locale pointwise variables {𝕜 V W Q P : Type*} section add_torsor variables (𝕜) [ring 𝕜] [add_comm_group V] [module 𝕜 V] [topological_space P] [add_torsor V P] {s t : set P} {x : P} include V /-- The intrinsic interior of a set is its interior considered as a set in its affine span. -/ def intrinsic_interior (s : set P) : set P := coe '' interior (coe ⁻¹' s : set $ affine_span 𝕜 s) /-- The intrinsic frontier of a set is its frontier considered as a set in its affine span. -/ def intrinsic_frontier (s : set P) : set P := coe '' frontier (coe ⁻¹' s : set $ affine_span 𝕜 s) /-- The intrinsic closure of a set is its closure considered as a set in its affine span. -/ def intrinsic_closure (s : set P) : set P := coe '' closure (coe ⁻¹' s : set $ affine_span 𝕜 s) variables {𝕜} @[simp] lemma mem_intrinsic_interior : x ∈ intrinsic_interior 𝕜 s ↔ ∃ y, y ∈ interior (coe ⁻¹' s : set $ affine_span 𝕜 s) ∧ ↑y = x := mem_image _ _ _ @[simp] lemma mem_intrinsic_frontier : x ∈ intrinsic_frontier 𝕜 s ↔ ∃ y, y ∈ frontier (coe ⁻¹' s : set $ affine_span 𝕜 s) ∧ ↑y = x := mem_image _ _ _ @[simp] lemma mem_intrinsic_closure : x ∈ intrinsic_closure 𝕜 s ↔ ∃ y, y ∈ closure (coe ⁻¹' s : set $ affine_span 𝕜 s) ∧ ↑y = x := mem_image _ _ _ lemma intrinsic_interior_subset : intrinsic_interior 𝕜 s ⊆ s := image_subset_iff.2 interior_subset lemma intrinsic_frontier_subset (hs : is_closed s) : intrinsic_frontier 𝕜 s ⊆ s := image_subset_iff.2 (hs.preimage continuous_induced_dom).frontier_subset lemma intrinsic_frontier_subset_intrinsic_closure : intrinsic_frontier 𝕜 s ⊆ intrinsic_closure 𝕜 s := image_subset _ frontier_subset_closure lemma subset_intrinsic_closure : s ⊆ intrinsic_closure 𝕜 s := λ x hx, ⟨⟨x, subset_affine_span _ _ hx⟩, subset_closure hx, rfl⟩ @[simp] lemma intrinsic_interior_empty : intrinsic_interior 𝕜 (∅ : set P) = ∅ := by simp [intrinsic_interior] @[simp] lemma intrinsic_frontier_empty : intrinsic_frontier 𝕜 (∅ : set P) = ∅ := by simp [intrinsic_frontier] @[simp] lemma intrinsic_closure_empty : intrinsic_closure 𝕜 (∅ : set P) = ∅ := by simp [intrinsic_closure] @[simp] lemma intrinsic_closure_nonempty : (intrinsic_closure 𝕜 s).nonempty ↔ s.nonempty := ⟨by { simp_rw nonempty_iff_ne_empty, rintro h rfl, exact h intrinsic_closure_empty }, nonempty.mono subset_intrinsic_closure⟩ alias intrinsic_closure_nonempty ↔ set.nonempty.of_intrinsic_closure set.nonempty.intrinsic_closure attribute [protected] set.nonempty.intrinsic_closure @[simp] lemma intrinsic_interior_singleton (x : P) : intrinsic_interior 𝕜 ({x} : set P) = {x} := by simpa only [intrinsic_interior, preimage_coe_affine_span_singleton, interior_univ, image_univ, subtype.range_coe] using coe_affine_span_singleton _ _ _ @[simp] lemma intrinsic_frontier_singleton (x : P) : intrinsic_frontier 𝕜 ({x} : set P) = ∅ := by rw [intrinsic_frontier, preimage_coe_affine_span_singleton, frontier_univ, image_empty] @[simp] lemma intrinsic_closure_singleton (x : P) : intrinsic_closure 𝕜 ({x} : set P) = {x} := by simpa only [intrinsic_closure, preimage_coe_affine_span_singleton, closure_univ, image_univ, subtype.range_coe] using coe_affine_span_singleton _ _ _ /-! Note that neither `intrinsic_interior` nor `intrinsic_frontier` is monotone. -/ lemma intrinsic_closure_mono (h : s ⊆ t) : intrinsic_closure 𝕜 s ⊆ intrinsic_closure 𝕜 t := begin refine image_subset_iff.2 (λ x hx, ⟨set.inclusion (affine_span_mono _ h) x, (continuous_inclusion _).closure_preimage_subset _ $ closure_mono _ hx, rfl⟩), exact λ y hy, h hy, end lemma interior_subset_intrinsic_interior : interior s ⊆ intrinsic_interior 𝕜 s := λ x hx, ⟨⟨x, subset_affine_span _ _ $ interior_subset hx⟩, preimage_interior_subset_interior_preimage continuous_subtype_coe hx, rfl⟩ lemma intrinsic_closure_subset_closure : intrinsic_closure 𝕜 s ⊆ closure s := image_subset_iff.2 $ continuous_subtype_coe.closure_preimage_subset _ lemma intrinsic_frontier_subset_frontier : intrinsic_frontier 𝕜 s ⊆ frontier s := image_subset_iff.2 $ continuous_subtype_coe.frontier_preimage_subset _ lemma intrinsic_closure_subset_affine_span : intrinsic_closure 𝕜 s ⊆ affine_span 𝕜 s := (image_subset_range _ _).trans subtype.range_coe.subset @[simp] lemma intrinsic_closure_diff_intrinsic_frontier (s : set P) : intrinsic_closure 𝕜 s \ intrinsic_frontier 𝕜 s = intrinsic_interior 𝕜 s := (image_diff subtype.coe_injective _ _).symm.trans $ by rw [closure_diff_frontier, intrinsic_interior] @[simp] lemma intrinsic_closure_diff_intrinsic_interior (s : set P) : intrinsic_closure 𝕜 s \ intrinsic_interior 𝕜 s = intrinsic_frontier 𝕜 s := (image_diff subtype.coe_injective _ _).symm @[simp] lemma intrinsic_interior_union_intrinsic_frontier (s : set P) : intrinsic_interior 𝕜 s ∪ intrinsic_frontier 𝕜 s = intrinsic_closure 𝕜 s := by simp [intrinsic_closure, intrinsic_interior, intrinsic_frontier, closure_eq_interior_union_frontier, image_union] @[simp] lemma intrinsic_frontier_union_intrinsic_interior (s : set P) : intrinsic_frontier 𝕜 s ∪ intrinsic_interior 𝕜 s = intrinsic_closure 𝕜 s := by rw [union_comm, intrinsic_interior_union_intrinsic_frontier] lemma is_closed_intrinsic_closure (hs : is_closed (affine_span 𝕜 s : set P)) : is_closed (intrinsic_closure 𝕜 s) := (closed_embedding_subtype_coe hs).is_closed_map _ is_closed_closure lemma is_closed_intrinsic_frontier (hs : is_closed (affine_span 𝕜 s : set P)) : is_closed (intrinsic_frontier 𝕜 s) := (closed_embedding_subtype_coe hs).is_closed_map _ is_closed_frontier @[simp] lemma affine_span_intrinsic_closure (s : set P) : affine_span 𝕜 (intrinsic_closure 𝕜 s) = affine_span 𝕜 s := (affine_span_le.2 intrinsic_closure_subset_affine_span).antisymm $ affine_span_mono _ subset_intrinsic_closure protected lemma is_closed.intrinsic_closure (hs : is_closed (coe ⁻¹' s : set $ affine_span 𝕜 s)) : intrinsic_closure 𝕜 s = s := begin rw [intrinsic_closure, hs.closure_eq, image_preimage_eq_of_subset], exact (subset_affine_span _ _).trans subtype.range_coe.superset, end @[simp] lemma intrinsic_closure_idem (s : set P) : intrinsic_closure 𝕜 (intrinsic_closure 𝕜 s) = intrinsic_closure 𝕜 s := begin refine is_closed.intrinsic_closure _, set t := affine_span 𝕜 (intrinsic_closure 𝕜 s) with ht, clear_value t, obtain rfl := ht.trans (affine_span_intrinsic_closure _), rw [intrinsic_closure, preimage_image_eq _ subtype.coe_injective], exact is_closed_closure, end end add_torsor namespace affine_isometry variables [normed_field 𝕜] [seminormed_add_comm_group V] [seminormed_add_comm_group W] [normed_space 𝕜 V] [normed_space 𝕜 W] [metric_space P] [pseudo_metric_space Q] [normed_add_torsor V P] [normed_add_torsor W Q] include V W local attribute [instance, nolint fails_quickly] affine_subspace.to_normed_add_torsor affine_subspace.nonempty_map @[simp] lemma image_intrinsic_interior (φ : P →ᵃⁱ[𝕜] Q) (s : set P) : intrinsic_interior 𝕜 (φ '' s) = φ '' intrinsic_interior 𝕜 s := begin obtain rfl | hs := s.eq_empty_or_nonempty, { simp only [intrinsic_interior_empty, image_empty] }, haveI : nonempty s := hs.to_subtype, let f := ((affine_span 𝕜 s).isometry_equiv_map φ).to_homeomorph, have : φ.to_affine_map ∘ coe ∘ f.symm = coe := funext isometry_equiv_map.apply_symm_apply, rw [intrinsic_interior, intrinsic_interior, ←φ.coe_to_affine_map, ←map_span φ.to_affine_map s, ←this, ←function.comp.assoc, image_comp, image_comp, f.symm.image_interior, f.image_symm, ←preimage_comp, function.comp.assoc, f.symm_comp_self, affine_isometry.coe_to_affine_map, function.comp.right_id, preimage_comp, φ.injective.preimage_image], end @[simp] lemma image_intrinsic_frontier (φ : P →ᵃⁱ[𝕜] Q) (s : set P) : intrinsic_frontier 𝕜 (φ '' s) = φ '' intrinsic_frontier 𝕜 s := begin obtain rfl | hs := s.eq_empty_or_nonempty, { simp }, haveI : nonempty s := hs.to_subtype, let f := ((affine_span 𝕜 s).isometry_equiv_map φ).to_homeomorph, have : φ.to_affine_map ∘ coe ∘ f.symm = coe := funext isometry_equiv_map.apply_symm_apply, rw [intrinsic_frontier, intrinsic_frontier, ←φ.coe_to_affine_map, ←map_span φ.to_affine_map s, ←this, ←function.comp.assoc, image_comp, image_comp, f.symm.image_frontier, f.image_symm, ←preimage_comp, function.comp.assoc, f.symm_comp_self, affine_isometry.coe_to_affine_map, function.comp.right_id, preimage_comp, φ.injective.preimage_image], end @[simp] lemma image_intrinsic_closure (φ : P →ᵃⁱ[𝕜] Q) (s : set P) : intrinsic_closure 𝕜 (φ '' s) = φ '' intrinsic_closure 𝕜 s := begin obtain rfl | hs := s.eq_empty_or_nonempty, { simp }, haveI : nonempty s := hs.to_subtype, let f := ((affine_span 𝕜 s).isometry_equiv_map φ).to_homeomorph, have : φ.to_affine_map ∘ coe ∘ f.symm = coe := funext isometry_equiv_map.apply_symm_apply, rw [intrinsic_closure, intrinsic_closure, ←φ.coe_to_affine_map, ←map_span φ.to_affine_map s, ←this, ←function.comp.assoc, image_comp, image_comp, f.symm.image_closure, f.image_symm, ←preimage_comp, function.comp.assoc, f.symm_comp_self, affine_isometry.coe_to_affine_map, function.comp.right_id, preimage_comp, φ.injective.preimage_image], end end affine_isometry section normed_add_torsor variables (𝕜) [nontrivially_normed_field 𝕜] [complete_space 𝕜] [normed_add_comm_group V] [normed_space 𝕜 V] [finite_dimensional 𝕜 V] [metric_space P] [normed_add_torsor V P] (s : set P) include V @[simp] lemma intrinsic_closure_eq_closure : intrinsic_closure 𝕜 s = closure s := begin ext x, simp only [mem_closure_iff, mem_intrinsic_closure], refine ⟨_, λ h, ⟨⟨x, _⟩, _, subtype.coe_mk _ _⟩⟩, { rintro ⟨x, h, rfl⟩ t ht hx, obtain ⟨z, hz₁, hz₂⟩ := h _ (continuous_induced_dom.is_open_preimage t ht) hx, exact ⟨z, hz₁, hz₂⟩ }, { by_contradiction hc, obtain ⟨z, hz₁, hz₂⟩ := h _ (affine_span 𝕜 s).closed_of_finite_dimensional.is_open_compl hc, exact hz₁ (subset_affine_span 𝕜 s hz₂) }, { rintro _ ⟨t, ht, rfl⟩ hx, obtain ⟨y, hyt, hys⟩ := h _ ht hx, exact ⟨⟨_, subset_affine_span 𝕜 s hys⟩, hyt, hys⟩ } end variables {𝕜} @[simp] lemma closure_diff_intrinsic_interior (s : set P) : closure s \ intrinsic_interior 𝕜 s = intrinsic_frontier 𝕜 s := intrinsic_closure_eq_closure 𝕜 s ▸ intrinsic_closure_diff_intrinsic_interior s @[simp] lemma closure_diff_intrinsic_frontier (s : set P) : closure s \ intrinsic_frontier 𝕜 s = intrinsic_interior 𝕜 s := intrinsic_closure_eq_closure 𝕜 s ▸ intrinsic_closure_diff_intrinsic_frontier s end normed_add_torsor private lemma aux {α β : Type*} [topological_space α] [topological_space β] (φ : α ≃ₜ β) (s : set β) : (interior s).nonempty ↔ (interior (φ ⁻¹' s)).nonempty := by rw [←φ.image_symm, ←φ.symm.image_interior, nonempty_image_iff] variables [normed_add_comm_group V] [normed_space ℝ V] [finite_dimensional ℝ V] {s : set V} /-- The intrinsic interior of a nonempty convex set is nonempty. -/ protected lemma set.nonempty.intrinsic_interior (hscv : convex ℝ s) (hsne : s.nonempty) : (intrinsic_interior ℝ s).nonempty := begin haveI := hsne.coe_sort, obtain ⟨p, hp⟩ := hsne, let p' : affine_span ℝ s := ⟨p, subset_affine_span _ _ hp⟩, rw [intrinsic_interior, nonempty_image_iff, aux (affine_isometry_equiv.const_vsub ℝ p').symm.to_homeomorph, convex.interior_nonempty_iff_affine_span_eq_top, affine_isometry_equiv.coe_to_homeomorph, ←affine_isometry_equiv.coe_to_affine_equiv, ←comap_span, affine_span_coe_preimage_eq_top, comap_top], exact hscv.affine_preimage ((affine_span ℝ s).subtype.comp (affine_isometry_equiv.const_vsub ℝ p').symm.to_affine_equiv.to_affine_map), end lemma intrinsic_interior_nonempty (hs : convex ℝ s) : (intrinsic_interior ℝ s).nonempty ↔ s.nonempty := ⟨by { simp_rw nonempty_iff_ne_empty, rintro h rfl, exact h intrinsic_interior_empty }, set.nonempty.intrinsic_interior hs⟩
3835c736df3040d4cbaea7b6682c98bd324f5f57
367134ba5a65885e863bdc4507601606690974c1
/src/data/pnat/basic.lean
3aaba579670835bdc1e000693e260d68151f8e6e
[ "Apache-2.0" ]
permissive
kodyvajjha/mathlib
9bead00e90f68269a313f45f5561766cfd8d5cad
b98af5dd79e13a38d84438b850a2e8858ec21284
refs/heads/master
1,624,350,366,310
1,615,563,062,000
1,615,563,062,000
162,666,963
0
0
Apache-2.0
1,545,367,651,000
1,545,367,651,000
null
UTF-8
Lean
false
false
15,581
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro, Neil Strickland -/ import data.nat.basic /-! # The positive natural numbers This file defines the type `ℕ+` or `pnat`, the subtype of natural numbers that are positive. -/ /-- `ℕ+` is the type of positive natural numbers. It is defined as a subtype, and the VM representation of `ℕ+` is the same as `ℕ` because the proof is not stored. -/ def pnat := {n : ℕ // 0 < n} notation `ℕ+` := pnat instance coe_pnat_nat : has_coe ℕ+ ℕ := ⟨subtype.val⟩ instance : has_repr ℕ+ := ⟨λ n, repr n.1⟩ /-- Predecessor of a `ℕ+`, as a `ℕ`. -/ def pnat.nat_pred (i : ℕ+) : ℕ := i - 1 namespace nat /-- Convert a natural number to a positive natural number. The positivity assumption is inferred by `dec_trivial`. -/ def to_pnat (n : ℕ) (h : 0 < n . tactic.exact_dec_trivial) : ℕ+ := ⟨n, h⟩ /-- Write a successor as an element of `ℕ+`. -/ def succ_pnat (n : ℕ) : ℕ+ := ⟨succ n, succ_pos n⟩ @[simp] theorem succ_pnat_coe (n : ℕ) : (succ_pnat n : ℕ) = succ n := rfl theorem succ_pnat_inj {n m : ℕ} : succ_pnat n = succ_pnat m → n = m := λ h, by { let h' := congr_arg (coe : ℕ+ → ℕ) h, exact nat.succ.inj h' } /-- Convert a natural number to a pnat. `n+1` is mapped to itself, and `0` becomes `1`. -/ def to_pnat' (n : ℕ) : ℕ+ := succ_pnat (pred n) @[simp] theorem to_pnat'_coe : ∀ (n : ℕ), ((to_pnat' n) : ℕ) = ite (0 < n) n 1 | 0 := rfl | (m + 1) := by {rw [if_pos (succ_pos m)], refl} end nat namespace pnat open nat /-- We now define a long list of structures on ℕ+ induced by similar structures on ℕ. Most of these behave in a completely obvious way, but there are a few things to be said about subtraction, division and powers. -/ instance : decidable_eq ℕ+ := λ (a b : ℕ+), by apply_instance instance : linear_order ℕ+ := subtype.linear_order _ @[simp] lemma mk_le_mk (n k : ℕ) (hn : 0 < n) (hk : 0 < k) : (⟨n, hn⟩ : ℕ+) ≤ ⟨k, hk⟩ ↔ n ≤ k := iff.rfl @[simp] lemma mk_lt_mk (n k : ℕ) (hn : 0 < n) (hk : 0 < k) : (⟨n, hn⟩ : ℕ+) < ⟨k, hk⟩ ↔ n < k := iff.rfl @[simp, norm_cast] lemma coe_le_coe (n k : ℕ+) : (n:ℕ) ≤ k ↔ n ≤ k := iff.rfl @[simp, norm_cast] lemma coe_lt_coe (n k : ℕ+) : (n:ℕ) < k ↔ n < k := iff.rfl @[simp] theorem pos (n : ℕ+) : 0 < (n : ℕ) := n.2 theorem eq {m n : ℕ+} : (m : ℕ) = n → m = n := subtype.eq @[simp] lemma coe_inj {m n : ℕ+} : (m : ℕ) = n ↔ m = n := set_coe.ext_iff @[simp] theorem mk_coe (n h) : ((⟨n, h⟩ : ℕ+) : ℕ) = n := rfl instance : add_comm_semigroup ℕ+ := { add := λ a b, ⟨(a + b : ℕ), add_pos a.pos b.pos⟩, add_comm := λ a b, subtype.eq (add_comm a b), add_assoc := λ a b c, subtype.eq (add_assoc a b c) } @[simp] theorem add_coe (m n : ℕ+) : ((m + n : ℕ+) : ℕ) = m + n := rfl instance coe_add_hom : is_add_hom (coe : ℕ+ → ℕ) := ⟨add_coe⟩ instance : add_left_cancel_semigroup ℕ+ := { add_left_cancel := λ a b c h, by { replace h := congr_arg (coe : ℕ+ → ℕ) h, rw [add_coe, add_coe] at h, exact eq ((add_right_inj (a : ℕ)).mp h)}, .. (pnat.add_comm_semigroup) } instance : add_right_cancel_semigroup ℕ+ := { add_right_cancel := λ a b c h, by { replace h := congr_arg (coe : ℕ+ → ℕ) h, rw [add_coe, add_coe] at h, exact eq ((add_left_inj (b : ℕ)).mp h)}, .. (pnat.add_comm_semigroup) } @[simp] theorem ne_zero (n : ℕ+) : (n : ℕ) ≠ 0 := ne_of_gt n.2 theorem to_pnat'_coe {n : ℕ} : 0 < n → (n.to_pnat' : ℕ) = n := succ_pred_eq_of_pos @[simp] theorem coe_to_pnat' (n : ℕ+) : (n : ℕ).to_pnat' = n := eq (to_pnat'_coe n.pos) instance : comm_monoid ℕ+ := { mul := λ m n, ⟨m.1 * n.1, mul_pos m.2 n.2⟩, mul_assoc := λ a b c, subtype.eq (mul_assoc _ _ _), one := succ_pnat 0, one_mul := λ a, subtype.eq (one_mul _), mul_one := λ a, subtype.eq (mul_one _), mul_comm := λ a b, subtype.eq (mul_comm _ _) } theorem lt_add_one_iff : ∀ {a b : ℕ+}, a < b + 1 ↔ a ≤ b := λ a b, nat.lt_add_one_iff theorem add_one_le_iff : ∀ {a b : ℕ+}, a + 1 ≤ b ↔ a < b := λ a b, nat.add_one_le_iff @[simp] lemma one_le (n : ℕ+) : (1 : ℕ+) ≤ n := n.2 instance : order_bot ℕ+ := { bot := 1, bot_le := λ a, a.property, ..(by apply_instance : partial_order ℕ+) } @[simp] lemma bot_eq_zero : (⊥ : ℕ+) = 1 := rfl instance : inhabited ℕ+ := ⟨1⟩ -- Some lemmas that rewrite `pnat.mk n h`, for `n` an explicit numeral, into explicit numerals. @[simp] lemma mk_one {h} : (⟨1, h⟩ : ℕ+) = (1 : ℕ+) := rfl @[simp] lemma mk_bit0 (n) {h} : (⟨bit0 n, h⟩ : ℕ+) = (bit0 ⟨n, pos_of_bit0_pos h⟩ : ℕ+) := rfl @[simp] lemma mk_bit1 (n) {h} {k} : (⟨bit1 n, h⟩ : ℕ+) = (bit1 ⟨n, k⟩ : ℕ+) := rfl -- Some lemmas that rewrite inequalities between explicit numerals in `pnat` -- into the corresponding inequalities in `nat`. -- TODO: perhaps this should not be attempted by `simp`, -- and instead we should expect `norm_num` to take care of these directly? -- TODO: these lemmas are perhaps incomplete: -- * 1 is not represented as a bit0 or bit1 -- * strict inequalities? @[simp] lemma bit0_le_bit0 (n m : ℕ+) : (bit0 n) ≤ (bit0 m) ↔ (bit0 (n : ℕ)) ≤ (bit0 (m : ℕ)) := iff.rfl @[simp] lemma bit0_le_bit1 (n m : ℕ+) : (bit0 n) ≤ (bit1 m) ↔ (bit0 (n : ℕ)) ≤ (bit1 (m : ℕ)) := iff.rfl @[simp] lemma bit1_le_bit0 (n m : ℕ+) : (bit1 n) ≤ (bit0 m) ↔ (bit1 (n : ℕ)) ≤ (bit0 (m : ℕ)) := iff.rfl @[simp] lemma bit1_le_bit1 (n m : ℕ+) : (bit1 n) ≤ (bit1 m) ↔ (bit1 (n : ℕ)) ≤ (bit1 (m : ℕ)) := iff.rfl @[simp] theorem one_coe : ((1 : ℕ+) : ℕ) = 1 := rfl @[simp] theorem mul_coe (m n : ℕ+) : ((m * n : ℕ+) : ℕ) = m * n := rfl instance coe_mul_hom : is_monoid_hom (coe : ℕ+ → ℕ) := {map_one := one_coe, map_mul := mul_coe} @[simp] lemma coe_eq_one_iff {m : ℕ+} : (m : ℕ) = 1 ↔ m = 1 := by { split; intro h; try { apply pnat.eq}; rw h; simp } @[simp] lemma coe_bit0 (a : ℕ+) : ((bit0 a : ℕ+) : ℕ) = bit0 (a : ℕ) := rfl @[simp] lemma coe_bit1 (a : ℕ+) : ((bit1 a : ℕ+) : ℕ) = bit1 (a : ℕ) := rfl @[simp] theorem pow_coe (m : ℕ+) (n : ℕ) : ((m ^ n : ℕ+) : ℕ) = (m : ℕ) ^ n := by induction n with n ih; [refl, rw [pow_succ', pow_succ, mul_coe, mul_comm, ih]] instance : left_cancel_semigroup ℕ+ := { mul_left_cancel := λ a b c h, by { replace h := congr_arg (coe : ℕ+ → ℕ) h, exact eq ((nat.mul_right_inj a.pos).mp h)}, .. (pnat.comm_monoid) } instance : right_cancel_semigroup ℕ+ := { mul_right_cancel := λ a b c h, by { replace h := congr_arg (coe : ℕ+ → ℕ) h, exact eq ((nat.mul_left_inj b.pos).mp h)}, .. (pnat.comm_monoid) } instance : ordered_cancel_comm_monoid ℕ+ := { mul_le_mul_left := by { intros, apply nat.mul_le_mul_left, assumption }, le_of_mul_le_mul_left := by { intros a b c h, apply nat.le_of_mul_le_mul_left h a.property, }, .. (pnat.left_cancel_semigroup), .. (pnat.right_cancel_semigroup), .. (pnat.linear_order), .. (pnat.comm_monoid)} instance : distrib ℕ+ := { left_distrib := λ a b c, eq (mul_add a b c), right_distrib := λ a b c, eq (add_mul a b c), ..(pnat.add_comm_semigroup), ..(pnat.comm_monoid) } /-- Subtraction a - b is defined in the obvious way when a > b, and by a - b = 1 if a ≤ b. -/ instance : has_sub ℕ+ := ⟨λ a b, to_pnat' (a - b : ℕ)⟩ theorem sub_coe (a b : ℕ+) : ((a - b : ℕ+) : ℕ) = ite (b < a) (a - b : ℕ) 1 := begin change ((to_pnat' ((a : ℕ) - (b : ℕ)) : ℕ)) = ite ((a : ℕ) > (b : ℕ)) ((a : ℕ) - (b : ℕ)) 1, split_ifs with h, { exact to_pnat'_coe (nat.sub_pos_of_lt h) }, { rw [nat.sub_eq_zero_iff_le.mpr (le_of_not_gt h)], refl } end theorem add_sub_of_lt {a b : ℕ+} : a < b → a + (b - a) = b := λ h, eq $ by { rw [add_coe, sub_coe, if_pos h], exact nat.add_sub_of_le (le_of_lt h) } instance : has_well_founded ℕ+ := ⟨(<), measure_wf coe⟩ /-- Strong induction on `pnat`. -/ lemma strong_induction_on {p : pnat → Prop} : ∀ (n : pnat) (h : ∀ k, (∀ m, m < k → p m) → p k), p n | n := λ IH, IH _ (λ a h, strong_induction_on a IH) using_well_founded { dec_tac := `[assumption] } /-- If `(n : pnat)` is different from `1`, then it is the successor of some `(k : pnat)`. -/ lemma exists_eq_succ_of_ne_one : ∀ {n : pnat} (h1 : n ≠ 1), ∃ (k : pnat), n = k + 1 | ⟨1, _⟩ h1 := false.elim $ h1 rfl | ⟨n+2, _⟩ _ := ⟨⟨n+1, by simp⟩, rfl⟩ lemma case_strong_induction_on {p : pnat → Prop} (a : pnat) (hz : p 1) (hi : ∀ n, (∀ m, m ≤ n → p m) → p (n + 1)) : p a := begin apply strong_induction_on a, intros k hk, by_cases h1 : k = 1, { rwa h1 }, obtain ⟨b, rfl⟩ := exists_eq_succ_of_ne_one h1, simp only [lt_add_one_iff] at hk, exact hi b hk end /-- An induction principle for `pnat`: it takes values in `Sort*`, so it applies also to Types, not only to `Prop`. -/ @[elab_as_eliminator] def rec_on (n : pnat) {p : pnat → Sort*} (p1 : p 1) (hp : ∀ n, p n → p (n + 1)) : p n := begin rcases n with ⟨n, h⟩, induction n with n IH, { exact absurd h dec_trivial }, { cases n with n, { exact p1 }, { exact hp _ (IH n.succ_pos) } } end @[simp] theorem rec_on_one {p} (p1 hp) : @pnat.rec_on 1 p p1 hp = p1 := rfl @[simp] theorem rec_on_succ (n : pnat) {p : pnat → Sort*} (p1 hp) : @pnat.rec_on (n + 1) p p1 hp = hp n (@pnat.rec_on n p p1 hp) := by { cases n with n h, cases n; [exact absurd h dec_trivial, refl] } /-- We define `m % k` and `m / k` in the same way as for `ℕ` except that when `m = n * k` we take `m % k = k` and `m / k = n - 1`. This ensures that `m % k` is always positive and `m = (m % k) + k * (m / k)` in all cases. Later we define a function `div_exact` which gives the usual `m / k` in the case where `k` divides `m`. -/ def mod_div_aux : ℕ+ → ℕ → ℕ → ℕ+ × ℕ | k 0 q := ⟨k, q.pred⟩ | k (r + 1) q := ⟨⟨r + 1, nat.succ_pos r⟩, q⟩ lemma mod_div_aux_spec : ∀ (k : ℕ+) (r q : ℕ) (h : ¬ (r = 0 ∧ q = 0)), (((mod_div_aux k r q).1 : ℕ) + k * (mod_div_aux k r q).2 = (r + k * q)) | k 0 0 h := (h ⟨rfl, rfl⟩).elim | k 0 (q + 1) h := by { change (k : ℕ) + (k : ℕ) * (q + 1).pred = 0 + (k : ℕ) * (q + 1), rw [nat.pred_succ, nat.mul_succ, zero_add, add_comm]} | k (r + 1) q h := rfl /-- `mod_div m k = (m % k, m / k)`. We define `m % k` and `m / k` in the same way as for `ℕ` except that when `m = n * k` we take `m % k = k` and `m / k = n - 1`. This ensures that `m % k` is always positive and `m = (m % k) + k * (m / k)` in all cases. Later we define a function `div_exact` which gives the usual `m / k` in the case where `k` divides `m`. -/ def mod_div (m k : ℕ+) : ℕ+ × ℕ := mod_div_aux k ((m : ℕ) % (k : ℕ)) ((m : ℕ) / (k : ℕ)) /-- We define `m % k` in the same way as for `ℕ` except that when `m = n * k` we take `m % k = k` This ensures that `m % k` is always positive. -/ def mod (m k : ℕ+) : ℕ+ := (mod_div m k).1 /-- We define `m / k` in the same way as for `ℕ` except that when `m = n * k` we take `m / k = n - 1`. This ensures that `m = (m % k) + k * (m / k)` in all cases. Later we define a function `div_exact` which gives the usual `m / k` in the case where `k` divides `m`. -/ def div (m k : ℕ+) : ℕ := (mod_div m k).2 theorem mod_add_div (m k : ℕ+) : ((mod m k) + k * (div m k) : ℕ) = m := begin let h₀ := nat.mod_add_div (m : ℕ) (k : ℕ), have : ¬ ((m : ℕ) % (k : ℕ) = 0 ∧ (m : ℕ) / (k : ℕ) = 0), by { rintro ⟨hr, hq⟩, rw [hr, hq, mul_zero, zero_add] at h₀, exact (m.ne_zero h₀.symm).elim }, have := mod_div_aux_spec k ((m : ℕ) % (k : ℕ)) ((m : ℕ) / (k : ℕ)) this, exact (this.trans h₀), end theorem div_add_mod (m k : ℕ+) : (k * (div m k) + mod m k : ℕ) = m := (add_comm _ _).trans (mod_add_div _ _) lemma mod_add_div' (m k : ℕ+) : ((mod m k) + (div m k) * k : ℕ) = m := by { rw mul_comm, exact mod_add_div _ _ } lemma div_add_mod' (m k : ℕ+) : ((div m k) * k + mod m k : ℕ) = m := by { rw mul_comm, exact div_add_mod _ _ } theorem mod_coe (m k : ℕ+) : ((mod m k) : ℕ) = ite ((m : ℕ) % (k : ℕ) = 0) (k : ℕ) ((m : ℕ) % (k : ℕ)) := begin dsimp [mod, mod_div], cases (m : ℕ) % (k : ℕ), { rw [if_pos rfl], refl }, { rw [if_neg n.succ_ne_zero], refl } end theorem div_coe (m k : ℕ+) : ((div m k) : ℕ) = ite ((m : ℕ) % (k : ℕ) = 0) ((m : ℕ) / (k : ℕ)).pred ((m : ℕ) / (k : ℕ)) := begin dsimp [div, mod_div], cases (m : ℕ) % (k : ℕ), { rw [if_pos rfl], refl }, { rw [if_neg n.succ_ne_zero], refl } end theorem mod_le (m k : ℕ+) : mod m k ≤ m ∧ mod m k ≤ k := begin change ((mod m k) : ℕ) ≤ (m : ℕ) ∧ ((mod m k) : ℕ) ≤ (k : ℕ), rw [mod_coe], split_ifs, { have hm : (m : ℕ) > 0 := m.pos, rw [← nat.mod_add_div (m : ℕ) (k : ℕ), h, zero_add] at hm ⊢, by_cases h' : ((m : ℕ) / (k : ℕ)) = 0, { rw [h', mul_zero] at hm, exact (lt_irrefl _ hm).elim}, { let h' := nat.mul_le_mul_left (k : ℕ) (nat.succ_le_of_lt (nat.pos_of_ne_zero h')), rw [mul_one] at h', exact ⟨h', le_refl (k : ℕ)⟩ } }, { exact ⟨nat.mod_le (m : ℕ) (k : ℕ), le_of_lt (nat.mod_lt (m : ℕ) k.pos)⟩ } end theorem dvd_iff {k m : ℕ+} : k ∣ m ↔ (k : ℕ) ∣ (m : ℕ) := begin split; intro h, rcases h with ⟨_, rfl⟩, apply dvd_mul_right, rcases h with ⟨a, h⟩, cases a, { contrapose h, apply ne_zero, }, use a.succ, apply nat.succ_pos, rw [← coe_inj, h, mul_coe, mk_coe], end theorem dvd_iff' {k m : ℕ+} : k ∣ m ↔ mod m k = k := begin rw dvd_iff, rw [nat.dvd_iff_mod_eq_zero], split, { intro h, apply eq, rw [mod_coe, if_pos h] }, { intro h, by_cases h' : (m : ℕ) % (k : ℕ) = 0, { exact h'}, { replace h : ((mod m k) : ℕ) = (k : ℕ) := congr_arg _ h, rw [mod_coe, if_neg h'] at h, exact (ne_of_lt (nat.mod_lt (m : ℕ) k.pos) h).elim } } end lemma le_of_dvd {m n : ℕ+} : m ∣ n → m ≤ n := by { rw dvd_iff', intro h, rw ← h, apply (mod_le n m).left } /-- If `h : k | m`, then `k * (div_exact m k) = m`. Note that this is not equal to `m / k`. -/ def div_exact (m k : ℕ+) : ℕ+ := ⟨(div m k).succ, nat.succ_pos _⟩ theorem mul_div_exact {m k : ℕ+} (h : k ∣ m) : k * (div_exact m k) = m := begin apply eq, rw [mul_coe], change (k : ℕ) * (div m k).succ = m, rw [← div_add_mod m k, dvd_iff'.mp h, nat.mul_succ] end theorem dvd_antisymm {m n : ℕ+} : m ∣ n → n ∣ m → m = n := λ hmn hnm, le_antisymm (le_of_dvd hmn) (le_of_dvd hnm) theorem dvd_one_iff (n : ℕ+) : n ∣ 1 ↔ n = 1 := ⟨λ h, dvd_antisymm h (one_dvd n), λ h, h.symm ▸ (dvd_refl 1)⟩ lemma pos_of_div_pos {n : ℕ+} {a : ℕ} (h : a ∣ n) : 0 < a := begin apply pos_iff_ne_zero.2, intro hzero, rw hzero at h, exact pnat.ne_zero n (eq_zero_of_zero_dvd h) end end pnat section can_lift instance nat.can_lift_pnat : can_lift ℕ ℕ+ := ⟨coe, λ n, 0 < n, λ n hn, ⟨nat.to_pnat' n, pnat.to_pnat'_coe hn⟩⟩ instance int.can_lift_pnat : can_lift ℤ ℕ+ := ⟨coe, λ n, 0 < n, λ n hn, ⟨nat.to_pnat' (int.nat_abs n), by rw [coe_coe, nat.to_pnat'_coe, if_pos (int.nat_abs_pos_of_ne_zero (ne_of_gt hn)), int.nat_abs_of_nonneg hn.le]⟩⟩ end can_lift
bcf3845c195f0377d3447a66798e9b727a7352b5
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/nat/multiplicity_auto.lean
b7bea78c6dee0b1bde57fe714f6f494167279fe1
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
4,971
lean
/- Copyright (c) 2019 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.nat.bitwise import Mathlib.data.nat.parity import Mathlib.ring_theory.int.basic import Mathlib.algebra.big_operators.intervals import Mathlib.PostPort namespace Mathlib /-! # Natural number multiplicity This file contains lemmas about the multiplicity function (the maximum prime power divding a number). # Main results There are natural number versions of some basic lemmas about multiplicity. There are also lemmas about the multiplicity of primes in factorials and in binomial coefficients. -/ namespace nat /-- The multiplicity of a divisor `m` of `n`, is the cardinality of the set of positive natural numbers `i` such that `p ^ i` divides `n`. The set is expressed by filtering `Ico 1 b` where `b` is any bound at least `n` -/ theorem multiplicity_eq_card_pow_dvd {m : ℕ} {n : ℕ} {b : ℕ} (hm1 : m ≠ 1) (hn0 : 0 < n) (hb : n ≤ b) : multiplicity m n = ↑(finset.card (finset.filter (fun (i : ℕ) => m ^ i ∣ n) (finset.Ico 1 b))) := sorry namespace prime theorem multiplicity_one {p : ℕ} (hp : prime p) : multiplicity p 1 = 0 := multiplicity.one_right (prime.not_unit (iff.mp prime_iff_prime hp)) theorem multiplicity_mul {p : ℕ} {m : ℕ} {n : ℕ} (hp : prime p) : multiplicity p (m * n) = multiplicity p m + multiplicity p n := multiplicity.mul (iff.mp prime_iff_prime hp) theorem multiplicity_pow {p : ℕ} {m : ℕ} {n : ℕ} (hp : prime p) : multiplicity p (m ^ n) = n •ℕ multiplicity p m := multiplicity.pow (iff.mp prime_iff_prime hp) theorem multiplicity_self {p : ℕ} (hp : prime p) : multiplicity p p = 1 := multiplicity.multiplicity_self (prime.not_unit (iff.mp prime_iff_prime hp)) (ne_zero hp) theorem multiplicity_pow_self {p : ℕ} {n : ℕ} (hp : prime p) : multiplicity p (p ^ n) = ↑n := multiplicity.multiplicity_pow_self (ne_zero hp) (prime.not_unit (iff.mp prime_iff_prime hp)) n /-- The multiplicity of a prime in `n!` is the sum of the quotients `n / p ^ i`. This sum is expressed over the set `Ico 1 b` where `b` is any bound at least `n` -/ theorem multiplicity_factorial {p : ℕ} (hp : prime p) {n : ℕ} {b : ℕ} : n ≤ b → multiplicity p (factorial n) = ↑(finset.sum (finset.Ico 1 b) fun (i : ℕ) => n / p ^ i) := sorry /-- The multiplicity of `p` in `(p(n+1))!` is one more than the sum of the multiplicities of `p` in `(p * n)!` and `n + 1`. -/ theorem multiplicity_factorial_mul_succ {n : ℕ} {p : ℕ} (hp : prime p) : multiplicity p (factorial (p * (n + 1))) = multiplicity p (factorial (p * n)) + multiplicity p (n + 1) + 1 := sorry /-- The multiplicity of `p` in `(pn)!` is `n` more than that of `n!`. -/ theorem multiplicity_factorial_mul {n : ℕ} {p : ℕ} (hp : prime p) : multiplicity p (factorial (p * n)) = multiplicity p (factorial n) + ↑n := sorry /-- A prime power divides `n!` iff it is at most the sum of the quotients `n / p ^ i`. This sum is expressed over the set `Ico 1 b` where `b` is any bound at least `n` -/ theorem pow_dvd_factorial_iff {p : ℕ} {n : ℕ} {r : ℕ} {b : ℕ} (hp : prime p) (hbn : n ≤ b) : p ^ r ∣ factorial n ↔ r ≤ finset.sum (finset.Ico 1 b) fun (i : ℕ) => n / p ^ i := sorry theorem multiplicity_choose_aux {p : ℕ} {n : ℕ} {b : ℕ} {k : ℕ} (hp : prime p) (hkn : k ≤ n) : (finset.sum (finset.Ico 1 b) fun (i : ℕ) => n / p ^ i) = ((finset.sum (finset.Ico 1 b) fun (i : ℕ) => k / p ^ i) + finset.sum (finset.Ico 1 b) fun (i : ℕ) => (n - k) / p ^ i) + finset.card (finset.filter (fun (i : ℕ) => p ^ i ≤ k % p ^ i + (n - k) % p ^ i) (finset.Ico 1 b)) := sorry /-- The multiplity of `p` in `choose n k` is the number of carries when `k` and `n - k` are added in base `p`. The set is expressed by filtering `Ico 1 b` where `b` is any bound at least `n`. -/ theorem multiplicity_choose {p : ℕ} {n : ℕ} {k : ℕ} {b : ℕ} (hp : prime p) (hkn : k ≤ n) (hnb : n ≤ b) : multiplicity p (choose n k) = ↑(finset.card (finset.filter (fun (i : ℕ) => p ^ i ≤ k % p ^ i + (n - k) % p ^ i) (finset.Ico 1 b))) := sorry /-- A lower bound on the multiplicity of `p` in `choose n k`. -/ theorem multiplicity_le_multiplicity_choose_add {p : ℕ} (hp : prime p) (n : ℕ) (k : ℕ) : multiplicity p n ≤ multiplicity p (choose n k) + multiplicity p k := sorry theorem multiplicity_choose_prime_pow {p : ℕ} {n : ℕ} {k : ℕ} (hp : prime p) (hkn : k ≤ p ^ n) (hk0 : 0 < k) : multiplicity p (choose (p ^ n) k) + multiplicity p k = ↑n := sorry end prime theorem multiplicity_two_factorial_lt {n : ℕ} (h : n ≠ 0) : multiplicity (bit0 1) (factorial n) < ↑n := sorry end Mathlib
8176493e2718bc00c8971c85a576755a98a29ea6
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/blast_flat.lean
c16b6eea211f6b3f0c6a443e8e6151135c8d7c91
[ "Apache-2.0" ]
permissive
soonhokong/lean
cb8aa01055ffe2af0fb99a16b4cda8463b882cd1
38607e3eb57f57f77c0ac114ad169e9e4262e24f
refs/heads/master
1,611,187,284,081
1,450,766,737,000
1,476,122,547,000
11,513,992
2
0
null
1,401,763,102,000
1,374,182,235,000
C++
UTF-8
Lean
false
false
645
lean
open nat subtype definition f (x : nat) (y : {n : nat | n > x}) : nat := x + elt_of y definition f_flat (x : nat) (y : nat) (H : y > x) : nat := f x (tag y H) lemma f_flat_simp [forward] (x : nat) (y : nat) (H : y > x) : f x (tag y H) = f_flat x y H := rfl set_option trace.simplifier true set_option trace.blast true set_option blast.strategy "ematch" example (a b c d : nat) (Ha : c > a) (Hb : d > b) : a = b → c = d → f a (tag c Ha) = f b (tag d Hb) := by blast example (h : nat → nat) (a b c d : nat) (Ha : h c > h a) (Hb : h d > h b) : h a = h b → c = d → f (h a) (tag (h c) Ha) = f (h b) (tag (h d) Hb) := by blast
d4757643b0fe3627e98c1e626bb6b865cbfa073d
dc253be9829b840f15d96d986e0c13520b085033
/heq.hlean
d99aeedf9ee79ffe04e5ff95ee50e94fd743c0eb
[ "Apache-2.0" ]
permissive
cmu-phil/Spectral
4ce68e5c1ef2a812ffda5260e9f09f41b85ae0ea
3b078f5f1de251637decf04bd3fc8aa01930a6b3
refs/heads/master
1,685,119,195,535
1,684,169,772,000
1,684,169,772,000
46,450,197
42
13
null
1,505,516,767,000
1,447,883,921,000
Lean
UTF-8
Lean
false
false
1,815
hlean
-- Author: Floris van Doorn open eq is_trunc variables {I : Type} [is_set I] {P : I → Type} {i j k : I} {x x₁ x₂ : P i} {y y₁ y₂ : P j} {z : P k} {Q : Π⦃i⦄, P i → Type} structure heq (x : P i) (y : P j) : Type := (p : i = j) (q : x =[p] y) namespace eq notation x ` ==[`:50 P:0 `] `:0 y:50 := @heq _ _ P _ _ x y infix ` == `:50 := heq -- mostly for printing, since it will be almost always ambiguous what P is definition pathover_of_heq {p : i = j} (q : x ==[P] y) : x =[p] y := change_path !is_set.elim (heq.q q) definition eq_of_heq (p : x₁ ==[P] x₂) : x₁ = x₂ := eq_of_pathover_idp (pathover_of_heq p) definition heq.elim (p : x ==[P] y) (q : Q x) : Q y := begin induction p with p r, induction r, exact q end definition heq.refl [refl] (x : P i) : x ==[P] x := heq.mk idp idpo definition heq.rfl : x ==[P] x := heq.refl x definition heq.symm [symm] (p : x ==[P] y) : y ==[P] x := begin induction p with p q, constructor, exact q⁻¹ᵒ end definition heq_of_eq (p : x₁ = x₂) : x₁ ==[P] x₂ := heq.mk idp (pathover_idp_of_eq p) definition heq.trans [trans] (p : x ==[P] y) (p₂ : y ==[P] z) : x ==[P] z := begin induction p with p q, induction p₂ with p₂ q₂, constructor, exact q ⬝o q₂ end infix ` ⬝he `:72 := heq.trans postfix `⁻¹ʰᵉ`:(max+10) := heq.symm definition heq_of_heq_of_eq (p : x ==[P] y) (p₂ : y = y₂) : x ==[P] y₂ := p ⬝he heq_of_eq p₂ definition heq_of_eq_of_heq (p : x = x₂) (p₂ : x₂ ==[P] y) : x ==[P] y := heq_of_eq p ⬝he p₂ infix ` ⬝hep `:73 := concato_eq infix ` ⬝phe `:74 := eq_concato definition heq_tr (p : i = j) (x : P i) : x ==[P] transport P p x := heq.mk p !pathover_tr definition tr_heq (p : i = j) (x : P i) : transport P p x ==[P] x := (heq_tr p x)⁻¹ʰᵉ end eq
e09fa00ce236851280bff7464c8c6c97217939c4
5ca7b1b12d14c4742e29366312ba2c2ef8201b21
/src/game/world7/level9.lean
4f39d63ea85ed5fea1899c2ffb5601a1b16979ab
[ "Apache-2.0" ]
permissive
MatthiasHu/natural_number_game
2e464482ef3001863430b0336133b6697b275ba3
2d764f72669ae30861f6a1057fce0257f3e466c4
refs/heads/master
1,609,719,110,419
1,576,345,737,000
1,576,345,737,000
240,296,314
0
0
Apache-2.0
1,581,608,357,000
1,581,608,356,000
null
UTF-8
Lean
false
false
3,023
lean
import game.world7.level8 -- hide import tactic.tauto -- useful high-powered tactic local attribute [instance, priority 10] classical.prop_decidable -- we are mathematicians /- # Advanced proposition world. You already know enough to embark on advanced addition world. But here are just a couple more things. ## Level 9: the law of the excluded middle. We proved earlier that `(P → Q) → (¬ Q → ¬ P)`. The converse, that `(¬ Q → ¬ P) → (P → Q)` is certainly true, but trying to prove it using what we've learnt so far is impossible (because it is not provable in constructive logic). For example, after ``` intro h, intro p, repeat {rw not_iff_imp_false at h}, ``` in the below, you are left with ``` P Q : Prop, h : (Q → false) → P → false p : P ⊢ Q ``` The tools you have are not sufficient to continue. But you can just prove this, and any other basic lemmas of this form like `¬ ¬ P → P`, using the `by_cases` tactic. Instead of starting with all the `intro`s, try this instead: `by_cases p : P; by_cases q : Q,` **Note the semicolon**! It means "do the next tactic to all the goals, not just the top one". After it, there are four goals, one for each of the four possibilities PQ=TT, TF, FT, TF. You can see that `p` is a proof of `P` in some of the goals, and a proof of `¬ P` in others. Similar comments apply to `q`. `repeat {cc}` then finishes the job. This approach assumed that `P ∨ ¬ P` was true; the `by_cases` tactic just does `cases` on this result. This is called the law of the excluded middle, and it cannot be proved just using tactics such as `intro` and `apply`. -/ /- Lemma : no-side-bar If $P$ and $Q$ are true/false statements, then $$(\lnot Q\implies \lnot P)\implies(P\implies Q).$$ -/ lemma contrapositive2 (P Q : Prop) : (¬ Q → ¬ P) → (P → Q) := begin by_cases p : P; by_cases q : Q, repeat {cc}, end /- ## Pro tip In fact the tactic `tauto` just kills this goal immediately. -/ /- Tactic : by_cases ## Summary `by_cases h : P` does a cases split on whether `P` is true or false. ## Details Some logic goals cannot be proved with `intro` and `apply` and `exact`. The simplest example is the law of the excluded middle `¬ ¬ P → P`. You can prove this using truth tables but not with `intro`, `apply` etc. To do a truth table proof, the tactic `by_cases h : P` will turn a goal of `⊢ ¬ ¬ P → P` into two goals ``` P : Prop, h : P ⊢ ¬¬P → P P : Prop, h : ¬P ⊢ ¬¬P → P ``` Each of these can now be proved using `intro`, `apply`, `exact` and `exfalso`. Remember though that in these simple logic cases, high-powered logic tactics like `cc` and `tauto` will just prove everything. -/ /- Tactic : tauto ## Summary The `tauto` tactic (and its variant `tauto!`) will close various logic goals. ## Details `tauto` is an all-purpose logic tactic which will try to solve goals using pure logical reasoning -- for example it will close the following goal: ``` P Q : Prop, hP : P, hQ : Q ⊢ P ∧ Q ``` -/
57f4b3755b96110f6feb7b4e3fcec5dae161e5da
9d2e3d5a2e2342a283affd97eead310c3b528a24
/src/exercises_sources/wednesday/afternoon/algebraic_hierarchy.lean
ba5efbbb4cad4db0754460e078b3c5e7ccd7df6e
[]
permissive
Vtec234/lftcm2020
ad2610ab614beefe44acc5622bb4a7fff9a5ea46
bbbd4c8162f8c2ef602300ab8fdeca231886375d
refs/heads/master
1,668,808,098,623
1,594,989,081,000
1,594,990,079,000
280,423,039
0
0
MIT
1,594,990,209,000
1,594,990,209,000
null
UTF-8
Lean
false
false
19,968
lean
/- This is a sorry-free file covering the material on Wednesday afternoon at LFTCM2020. It's how to build some algebraic structures in Lean -/ import data.rat.basic -- we'll need the rationals at the end of this file /- As a mathematician I essentially always start my Lean files with the following line: -/ import tactic /- That gives me access to all Lean's tactics (see https://leanprover-community.github.io/mathlib_docs/tactics.html) -/ /- ## The point of this file The idea of this file is to show how to build in Lean what the computer scientists call "an algebraic heirarchy", and what mathematicians call "groups, rings, fields, modules etc". Firstly, we will define groups, and develop a basic interface for groups. Then we will define rings, fields, modules, vector spaces, and just demonstrate that they are usable, rather than making a complete interface for all of them. Let's start with the theory of groups. Unfortunately Lean has groups already, so we will have to do everything in a namespace -/ namespace lftcm /- ... which means that now when we define `group`, it will actually be called `lftcm.group`. ## Notation typeclasses To make a term of type `has_mul G`, you need to give a map G^2 → G (or more precisely, a map `has_mul.mul : G → G → G`. Lean's notation `g * h` is notation for `has_mul.mul g h`. Furthermore, `has_mul` is a class. In short, this means that if you write `[has_mul G]` then `G` will magically have a multiplication called `*` (satisfying no axioms). Similarly `[has_one G]` gives you `has_one.one : G` with notation `1 : G`, and `[has_inv G]` gives you `has_inv.inv : G → G` with notation `g⁻¹ : G` ## Definition of a group If `G` is a type, equipped with `* : G^2 → G`, `1 : G` and `⁻¹ : G → G` then it's a group if it satisfies the group axioms. -/ -- `group G` is the type of group structures on a type `G`. -- first we ask for the structure class group (G : Type) extends has_mul G, has_one G, has_inv G := -- and then we ask for the axioms (mul_assoc : ∀ (a b c : G), a * b * c = a * (b * c)) (one_mul : ∀ (a : G), 1 * a = a) (mul_left_inv : ∀ (a : G), a⁻¹ * a = 1) /- Advantages of this approach: axioms look lovely. Disadvantage: what if I want the group law to be `+`?? I have embedded `has_mul` in the definition. Lean's solution: develop a `to_additive` metaprogram which translates all theorems about `group`s (with group law `*`) to theorems about `add_group`s (with group law `+`). We will not go into details here. -/ namespace group -- let G be a group variables {G : Type} [group G] /- Lemmas about groups are proved in this namespace. We already have some! All the group axioms are theorems in this namespace. Indeed we have just defined `group.mul_assoc : ∀ (a b c : G), a * b * c = a * (b * c)` `group.one_mul : ∀ (a : G), 1 * a = a` `group.mul_left_inv : ∀ (a : G), a⁻¹ * a = 1` Because we are in the `group` namespace, we don't need to write `group.` everywhere. Let's put some more theorems into the `group` namespace. We definitely need `mul_one` and `mul_right_inv`, and it's a fun exercise to get them. Here is a route: `mul_left_cancel : ∀ (a b c : G), a * b = a * c → b = c` `mul_eq_of_eq_inv_mul {a x y : G} : x = a⁻¹ * y → a * x = y` `mul_one (a : G) : a * 1 = a` `mul_right_inv (a : G) : a * a⁻¹ = 1` -/ lemma mul_left_cancel (a b c : G) (Habac : a * b = a * c) : b = c := calc b = 1 * b : by rw one_mul ... = (a⁻¹ * a) * b : by rw mul_left_inv ... = a⁻¹ * (a * b) : by rw mul_assoc ... = a⁻¹ * (a * c) : by rw Habac ... = (a⁻¹ * a) * c : by rw mul_assoc ... = 1 * c : by rw mul_left_inv ... = c : by rw one_mul -- more mathlib-ish proof: lemma mul_left_cancel' (a b c : G) (Habac : a * b = a * c) : b = c := begin rw [←one_mul b, ←mul_left_inv a, mul_assoc, Habac, ←mul_assoc, mul_left_inv, one_mul], end lemma mul_eq_of_eq_inv_mul {a x y : G} (h : x = a⁻¹ * y) : a * x = y := begin apply mul_left_cancel a⁻¹, -- ⊢ a⁻¹ * (a * x) = a⁻¹ * y rw ←mul_assoc, -- ⊢ a⁻¹ * a * x = a⁻¹ * y (remember this means (a⁻¹ * a) * x = ...) rw mul_left_inv, -- ⊢ 1 * x = a⁻¹ * y rw one_mul, -- ⊢ x = a⁻¹ * y exact h end -- The same proof lemma mul_eq_of_eq_inv_mul' {a x y : G} (h : x = a⁻¹ * y) : a * x = y := mul_left_cancel a⁻¹ _ _ $ by rwa [←mul_assoc, mul_left_inv, one_mul] /- So now we can finally prove `mul_one` and `mul_right_inv`. But before we start, let's learn a little bit about the simplifier. ## The `simp` tactic -- Lean's simplifier We have the theorems (axioms) `one_mul g : 1 * g = g` and `mul_left_inv g : g⁻¹ * g = 1`. Both of these theorems are of the form `A = B`, with `A` more complicated than `B`. This means that they are *perfect* theorems for the simplifier. Let's teach those theorems to the simplifier, by adding the `@[simp]` attribute to them. An "attribute" is just a tag which we attach to a theorem (or definition). -/ attribute [simp] one_mul mul_left_inv /- Now let's prove `mul_one` using the simplifier. This also a perfect `simp` lemma, so let's also add the `simp` tag to it. -/ @[simp] theorem mul_one (a : G) : a * 1 = a := begin apply mul_eq_of_eq_inv_mul, -- ⊢ 1 = a⁻¹ * a simp, end /- The simplifier solved `1 = a⁻¹ * a` because it knew `mul_left_inv`. Feel free to comment out the `attribute [simp] one_mul mul_left_inv` line above, and observe that the proof breaks. -/ -- term mode proof theorem mul_one' (a : G) : a * 1 = a := mul_eq_of_eq_inv_mul $ by simp -- see if you can get the simplifier to do this one too @[simp] theorem mul_right_inv (a : G) : a * a⁻¹ = 1 := begin apply mul_eq_of_eq_inv_mul, -- ⊢ a⁻¹ = a⁻¹ * 1 simp end -- Now here's a question. Can we train the simplifier to solve the following problem: --example (a b c d : G) : -- ((a * b)⁻¹ * a * 1⁻¹⁻¹⁻¹ * b⁻¹ * b * b * 1 * 1⁻¹)⁻¹ = (c⁻¹⁻¹ * d * d⁻¹ * 1⁻¹⁻¹ * c⁻¹⁻¹⁻¹)⁻¹⁻¹ := --by simp -- Remove the --'s and see that it fails. Let's see if we can get it to work. -- We start with two very natural `simp` lemmas. @[simp] lemma one_inv : (1 : G)⁻¹ = 1 := begin apply mul_left_cancel (1 : G), simp, end @[simp] lemma inv_inv (a : G) : a⁻¹⁻¹ = a := begin apply mul_left_cancel a⁻¹, simp, end -- Here is a riskier looking `[simp]` lemma. attribute [simp] mul_assoc -- recall this says (a * b) * c = a * (b * c) -- The simplifier will now push all brackets to the right, which means -- that it's worth proving the following two lemmas and tagging -- them `[simp]`, so that we can still cancel a with a⁻¹ in these situations. @[simp] lemma inv_mul_cancel_left (a b : G) : a⁻¹ * (a * b) = b := begin rw ←mul_assoc, simp, end @[simp] lemma mul_inv_cancel_left (a b : G) : a * (a⁻¹ * b) = b := begin rw ←mul_assoc, simp end -- Finally, let's make a `simp` lemma which enables us to -- reduce all inverses to inverses of variables @[simp] lemma mul_inv_rev (a b : G) : (a * b)⁻¹ = b⁻¹ * a⁻¹ := begin apply mul_left_cancel (a * b), rw mul_right_inv, simp, end /- If you solved them all -- congratulations! You have just turned Lean's simplifier into a normalising confluent rewriting system for groups, following Knuth-Bendix. https://en.wikipedia.org/wiki/Confluence_(abstract_rewriting)#Motivating_examples In other words, the simplifier will now put any element of a free group into a canonical normal form, and can hence solve the word problem for free groups. -/ example (a b c d : G) : ((a * b)⁻¹ * a * 1⁻¹⁻¹⁻¹ * b⁻¹ * b * b * 1 * 1⁻¹)⁻¹ = (c⁻¹⁻¹ * d * d⁻¹ * 1⁻¹⁻¹ * c⁻¹⁻¹⁻¹)⁻¹⁻¹ := by simp -- Abstract example of the power of classes: we can define products of groups with instances instance (G : Type) [group G] (H : Type) [group H] : group (G × H) := { mul := λ k l, (k.1*l.1, k.2*l.2), one := (1,1), inv := λ k, (k.1⁻¹, k.2⁻¹), mul_assoc := begin intros a b c, cases a, cases b, cases c, ext; simp, end, one_mul := begin intro a, cases a, ext; simp, end, mul_left_inv := begin intro a, cases a, ext; simp end } -- the type class inference system now knows that products of groups are groups example (G H K : Type) [group G] [group H] [group K] : group (G × H × K) := by apply_instance end group -- let's make a group of order two. -- First the elements {+1, -1} inductive mu2 | p1 : mu2 | m1 : mu2 namespace mu2 -- Now let's do some CS stuff: -- 1) prove it has decidable equality attribute [derive decidable_eq] mu2 -- 2) prove it is finite instance : fintype mu2 := ⟨⟨[mu2.p1, mu2.m1], by simp⟩, λ x, by cases x; simp⟩ -- now back to the maths. -- Define multiplication by doing all cases def mul : mu2 → mu2 → mu2 | p1 p1 := p1 | p1 m1 := m1 | m1 p1 := m1 | m1 m1 := p1 instance : has_mul mu2 := ⟨mul⟩ -- identity def one : mu2 := p1 -- notation instance : has_one mu2 := ⟨one⟩ -- inverse def inv : mu2 → mu2 := id -- notation instance : has_inv mu2 := ⟨inv⟩ -- currently we have notation but no axioms example : p1 * m1 * m1 = p1⁻¹ * p1 := rfl -- all true by definition -- now let's make it a group instance : group mu2 := begin -- first define the structure refine_struct { mul := mul, one := one, inv := inv }, -- now we have three goals (the axioms) all_goals {exact dec_trivial} end end mu2 -- Now let's build rings and modules and stuff (via monoids and add_comm_groups) -- a monoid is a group without inverses class monoid (M : Type) extends has_mul M, has_one M := (mul_assoc : ∀ (a b c : M), a * b * c = a * (b * c)) (one_mul : ∀ (a : M), 1 * a = a) (mul_one : ∀ (a : M), a * 1 = a) -- additive commutative groups from first principles class add_comm_group (A : Type) extends has_add A, has_zero A, has_neg A := (add_assoc : ∀ (a b c : A), a + b + c = a + (b + c)) (zero_add : ∀ (a : A), 0 + a = a) (add_left_neg : ∀ (a : A), -a + a = 0) (add_comm : ∀ a b : A, a + b = b + a) -- Notation for subtraction is handy to have; define a - b to be a + (-b) instance (A : Type) [add_comm_group A] : has_sub A := ⟨λ a b, a + -b⟩ -- rings are additive abelian groups and multiplicative monoids, -- with distributivity class ring (R : Type) extends monoid R, add_comm_group R := (mul_add : ∀ (a b c : R), a * (b + c) = a * b + a * c) (add_mul : ∀ (a b c : R), (a + b) * c = a * c + b * c) -- for commutative rings, add commutativity of multiplication class comm_ring (R : Type) extends ring R := (mul_comm : ∀ a b : R, a * b = b * a) /-- Typeclass for types with a scalar multiplication operation, denoted `•` (`\bu`) -/ class has_scalar (R : Type) (M : Type) := (smul : R → M → M) infixr ` • `:73 := has_scalar.smul -- modules for a ring class module (R : Type) [ring R] (M : Type) [add_comm_group M] extends has_scalar R M := (smul_add : ∀(r : R) (x y : M), r • (x + y) = r • x + r • y) (add_smul : ∀(r s : R) (x : M), (r + s) • x = r • x + s • x) (mul_smul : ∀ (r s : R) (x : M), (r * s) • x = r • s • x) (one_smul : ∀ x : M, (1 : R) • x = x) -- for fields we let ⁻¹ be defined on the entire field, and demand 0⁻¹ = 0 -- and that a⁻¹ * a = 1 for non-zero a. This is merely for convenience; -- one can easily check that it's mathematically equivalent to the usual -- definition of a field. class field (K : Type) extends comm_ring K, has_inv K := (zero_ne_one : (0 : K) ≠ 1) (mul_inv_cancel : ∀ {a : K}, a ≠ 0 → a * a⁻¹ = 1) (inv_zero : (0 : K)⁻¹ = 0) -- the type of vector spaces def vector_space (K : Type) [field K] (V : Type) [add_comm_group V] := module K V /- Exercise for the reader: define manifolds, schemes, perfectoid spaces in Lean. All have been done! As you can see, it is clearly *feasible*, although it does sometimes take time to get it right. It is all very much work in progress. The extraordinary thing is that although these computer theorem provers have been around for about 50 years, there has never been a serious effort to make the standard definitions used all over modern mathematics in one of them, and this is why these systems are rarely used in mathematics departments. Changing this is one of the goals of the Leanprover community. -/ /- Let's check that we can make the rational numbers into a field. Of course they are already a field in Lean, but remember that when we say `field` below, we mean our just-defined structure `lftcm.field`. -/ -- the rationals are a field (easy because all the work is done in the import) instance : field ℚ := { mul := (*), one := 1, mul_assoc := rat.mul_assoc, one_mul := rat.one_mul, mul_one := rat.mul_one, add := (+), zero := 0, neg := has_neg.neg, -- no () trickery for unary operators add_assoc := rat.add_assoc, zero_add := rat.zero_add, add_left_neg := rat.add_left_neg, add_comm := rat.add_comm, mul_add := rat.mul_add, add_mul := rat.add_mul, mul_comm := rat.mul_comm, inv := has_inv.inv, -- see neg zero_ne_one := rat.zero_ne_one, mul_inv_cancel := rat.mul_inv_cancel, inv_zero := inv_zero -- I don't know why rat.inv_zero was never explicitly defined } /- Below is evidence that we can prove basic theorems about these structures. Note however that it is a *complete pain* because we are *re-implementing* everything; `add_comm` defaults to Lean's version for Lean's `add_comm_group`s, so we have to explicitly write `add_comm_group.add_comm` to use our own version. The mathlib versions of these proofs are less ugly. -/ variables {A : Type} [add_comm_group A] lemma add_comm_group.add_left_cancel (a b c : A) (Habac : a + b = a + c) : b = c := begin rw ←add_comm_group.zero_add b, rw ←add_comm_group.add_left_neg a, rw add_comm_group.add_assoc, rw Habac, rw ←add_comm_group.add_assoc, rw add_comm_group.add_left_neg, rw add_comm_group.zero_add, end lemma add_comm_group.add_right_neg (a : A) : a + -a = 0 := begin rw add_comm_group.add_comm, rw add_comm_group.add_left_neg, end lemma add_comm_group.sub_eq_add_neg (a b : A) : a - b = a + -b := begin -- this is just our definition of subtraction refl end lemma add_comm_group.sub_self (a : A) : a - a = 0 := begin rw add_comm_group.sub_eq_add_neg, rw add_comm_group.add_comm, rw add_comm_group.add_left_neg, end lemma add_comm_group.neg_eq_of_add_eq_zero (a b : A) (h : a + b = 0) : -a = b := begin apply add_comm_group.add_left_cancel a, rw h, rw add_comm_group.add_right_neg, end lemma add_comm_group.add_zero (a : A) : a + 0 = a := begin rw add_comm_group.add_comm, rw add_comm_group.zero_add, end variables {R : Type} [ring R] lemma ring.mul_zero (r : R) : r * 0 = 0 := begin apply add_comm_group.add_left_cancel (r * 0), rw ←ring.mul_add, rw add_comm_group.add_zero, rw add_comm_group.add_zero, end lemma ring.mul_neg (a b : R) : a * -b = -(a * b) := begin symmetry, apply add_comm_group.neg_eq_of_add_eq_zero, rw ←ring.mul_add, rw add_comm_group.add_right_neg, rw ring.mul_zero end lemma ring.mul_sub (R : Type) [comm_ring R] (r a b : R) : r * (a - b) = r * a - r * b := begin rw add_comm_group.sub_eq_add_neg, rw ring.mul_add, rw ring.mul_neg, refl, end lemma comm_ring.sub_mul (R : Type) [comm_ring R] (r a b : R) : (a - b) * r = a * r - b * r := begin rw comm_ring.mul_comm (a - b), rw comm_ring.mul_comm a, rw comm_ring.mul_comm b, apply ring.mul_sub end -- etc etc, for thousands of lines of mathlib, which develop the interface -- abelian groups, rings, commutative rings, modules, fields, vector spaces etc. end lftcm /- ## Advertisement Finished the natural number game? Have Lean installed? Want more games/exercises? Take a look at the following projects, many of which are ongoing but the first three of which are pretty much ready: *) The complex number game (complete, needs to be played within VS Code) https://github.com/ImperialCollegeLondon/complex-number-game To install, type `leanproject get ImperialCollegeLondon/complex-number-game` and then just open the levels in `src/complex`. *) Undergraduate level mathematics Lean puzzles (plenty of stuff here, and more appearing over the summer): https://github.com/ImperialCollegeLondon/Example-Lean-Projects `leanproject get ImperialCollegeLondon/Example-Lean-Projects` *) The max mini-game (a simple browser game like the natural number game) http://wwwf.imperial.ac.uk/~buzzard/xena/max_minigame/ (this is part of what will become the real number game, a game to teach series, sequences and limits etc like the natural number game): `leanproject get ImperialCollegeLondon/real-number-game` *) Some commutative algebra experiments (ongoing work to prove the Nullstellensatz, going slowly because I'm busy): https://github.com/ImperialCollegeLondon/M4P33/blob/1a179372db71ad6802d11eacbc1f02f327d55f8f/src/for_mathlib/commutative_algebra/Zariski_lemma.lean#L80-L81 `leanproject get ImperialCollegeLondon/M4P33` *) The group theory game (work in progress, expect more progress over the summer, as a couple of undergraduates are working on it) https://github.com/ImperialCollegeLondon/group-theory-game `leanproject get ImperialCollegeLondon/group-theory-game` *) Galois theory experiments https://github.com/ImperialCollegeLondon/P11-Galois-Theory `leanproject get ImperialCollegeLondon/P11-Galois-Theory` *) Beginnings of the theory of condensed sets (currently on hold because we need a good interface for abelian categories in mathlib) https://github.com/ImperialCollegeLondon/condensed-sets `leanproject get ImperialCollegeLondon/condensed-sets` ## The Xena Project Why do these projects exist? I (Kevin Buzzard) am interested in teaching undergraduates how to use Lean. I have been running a club at Imperial College London called the Xena Project for the last three years, I am proud that many Imperial mathematics undegraduates have contributed to Lean's maths library, and three of them (Chris Hughes, Kenny Lau, Amelia Livingston) have each contributed over 5,000 lines of code. It is non-trivial to get your work into such a polished state that it is acceptable to the mathlib maintainers. It is also very good practice. I am running Lean summer projects this summer, on a Discord server. If you know of any undergraduates who you think might be interested in Lean, please direct them to the Xena Project Discord! https://discord.gg/BgyVYgJ Undergraduates use Discord for lots of things, and seem to be more likely to use a Discord server than the Zulip chat. The Discord server is chaotic and full of off-topic material -- quite unlike the Lean Zulip server, which is professional and focussed. If you have a serious question about Lean, ask it on the Zulip chat! But if you know an undergraduate who is interested in Lean, they might be interested in the Discord server. We have meetings every Thursday evening (UK time), with live Lean coding and streaming, speedruns, there is music, people posting pictures of cats, Haikus, and so on. To a large extent it is run by undergraduates and PhD students. Over the summer (July and August 2020) there are also live Twitch talks at https://www.twitch.tv/kbuzzard , on Tuesdays 10am and Thursdays 4pm UK time (UTC+1), aimed at mathematics undergraduates. It is an informal place for undergraduates to hang out and meet other undergraduates who are interested in Lean. I believe that it is crucial to make undergraduates aware of computer proof verification systems, because one day (possibly a long time in the future, but one day) these things will cause a paradigm shift in the way mathematics is done, and the sooner young mathematicians learn about them, the sooner it will happen. Prove a theorem. Write a function. @XenaProject https://twitter.com/XenaProject -/
e4947a8ec83caf92b5085972839b1d70083bc211
d1a52c3f208fa42c41df8278c3d280f075eb020c
/stage0/src/Lean/Meta/Basic.lean
52f0dd45263fb91c30afff6f4061b89c7a6fd23e
[ "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
56,525
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.Data.LOption import Lean.Environment import Lean.Class import Lean.ReducibilityAttrs import Lean.Util.Trace import Lean.Util.RecDepth import Lean.Util.PPExt import Lean.Util.ReplaceExpr import Lean.Util.OccursCheck import Lean.Util.MonadBacktrack import Lean.Compiler.InlineAttrs import Lean.Meta.TransparencyMode import Lean.Meta.DiscrTreeTypes import Lean.Eval import Lean.CoreM /- This module provides four (mutually dependent) goodies that are needed for building the elaborator and tactic frameworks. 1- Weak head normal form computation with support for metavariables and transparency modes. 2- Definitionally equality checking with support for metavariables (aka unification modulo definitional equality). 3- Type inference. 4- Type class resolution. They are packed into the MetaM monad. -/ namespace Lean.Meta builtin_initialize isDefEqStuckExceptionId : InternalExceptionId ← registerInternalExceptionId `isDefEqStuck structure Config where foApprox : Bool := false ctxApprox : Bool := false quasiPatternApprox : Bool := false /-- When `constApprox` is set to true, we solve `?m t =?= c` using `?m := fun _ => c` when `?m t` is not a higher-order pattern and `c` is not an application as -/ constApprox : Bool := false /-- When the following flag is set, `isDefEq` throws the exeption `Exeption.isDefEqStuck` whenever it encounters a constraint `?m ... =?= t` where `?m` is read only. This feature is useful for type class resolution where we may want to notify the caller that the TC problem may be solveable later after it assigns `?m`. -/ isDefEqStuckEx : Bool := false transparency : TransparencyMode := TransparencyMode.default /-- If zetaNonDep == false, then non dependent let-decls are not zeta expanded. -/ zetaNonDep : Bool := true /-- When `trackZeta == true`, we store zetaFVarIds all free variables that have been zeta-expanded. -/ trackZeta : Bool := false unificationHints : Bool := true /-- Enables proof irrelevance at `isDefEq` -/ proofIrrelevance : Bool := true /-- By default synthetic opaque metavariables are not assigned by `isDefEq`. Motivation: we want to make sure typing constraints resolved during elaboration should not "fill" holes that are supposed to be filled using tactics. However, this restriction is too restrictive for tactics such as `exact t`. When elaborating `t`, we dot not fill named holes when solving typing constraints or TC resolution. But, we ignore the restriction when we try to unify the type of `t` with the goal target type. We claim this is not a hack and is defensible behavior because this last unification step is not really part of the term elaboration. -/ assignSyntheticOpaque : Bool := false /-- When `ignoreLevelDepth` is `false`, only universe level metavariables with depth == metavariable context depth can be assigned. We used to have `ignoreLevelDepth == false` always, but this setting produced counterintuitive behavior in a few cases. Recall that universe levels are often ignored by users, they may not even be aware they exist. We still use this restriction for regular metavariables. See discussion at the beginning of `MetavarContext.lean`. We claim it is reasonable to ignore this restriction for universe metavariables because their values are often contrained by the terms is instances and simp theorems. TODO: we should delete this configuration option and the method `isReadOnlyLevelMVar` after we have more tests. -/ ignoreLevelMVarDepth : Bool := true /-- Enable/Disable support for offset constraints such as `?x + 1 =?= e` -/ offsetCnstrs : Bool := true /-- Enable/Disable support for eta-structures. -/ etaStruct : Bool := true structure ParamInfo where binderInfo : BinderInfo := BinderInfo.default hasFwdDeps : Bool := false backDeps : Array Nat := #[] deriving Inhabited def ParamInfo.isImplicit (p : ParamInfo) : Bool := p.binderInfo == BinderInfo.implicit def ParamInfo.isInstImplicit (p : ParamInfo) : Bool := p.binderInfo == BinderInfo.instImplicit def ParamInfo.isStrictImplicit (p : ParamInfo) : Bool := p.binderInfo == BinderInfo.strictImplicit def ParamInfo.isExplicit (p : ParamInfo) : Bool := p.binderInfo == BinderInfo.default || p.binderInfo == BinderInfo.auxDecl structure FunInfo where paramInfo : Array ParamInfo := #[] resultDeps : Array Nat := #[] structure InfoCacheKey where transparency : TransparencyMode expr : Expr nargs? : Option Nat deriving Inhabited, BEq namespace InfoCacheKey instance : Hashable InfoCacheKey := ⟨fun ⟨transparency, expr, nargs⟩ => mixHash (hash transparency) <| mixHash (hash expr) (hash nargs)⟩ end InfoCacheKey open Std (PersistentArray PersistentHashMap) abbrev SynthInstanceCache := PersistentHashMap Expr (Option Expr) abbrev InferTypeCache := PersistentExprStructMap Expr abbrev FunInfoCache := PersistentHashMap InfoCacheKey FunInfo abbrev WhnfCache := PersistentExprStructMap Expr /- A set of pairs. TODO: consider more efficient representations (e.g., a proper set) and caching policies (e.g., imperfect cache). We should also investigate the impact on memory consumption. -/ abbrev DefEqCache := PersistentHashMap (Expr × Expr) Unit structure Cache where inferType : InferTypeCache := {} funInfo : FunInfoCache := {} synthInstance : SynthInstanceCache := {} whnfDefault : WhnfCache := {} -- cache for closed terms and `TransparencyMode.default` whnfAll : WhnfCache := {} -- cache for closed terms and `TransparencyMode.all` defEqDefault : DefEqCache := {} defEqAll : DefEqCache := {} deriving Inhabited /-- "Context" for a postponed universe constraint. `lhs` and `rhs` are the surrounding `isDefEq` call when the postponed constraint was created. -/ structure DefEqContext where lhs : Expr rhs : Expr lctx : LocalContext localInstances : LocalInstances /-- Auxiliary structure for representing postponed universe constraints. Remark: the fields `ref` and `rootDefEq?` are used for error message generation only. Remark: we may consider improving the error message generation in the future. -/ structure PostponedEntry where ref : Syntax -- We save the `ref` at entry creation time lhs : Level rhs : Level ctx? : Option DefEqContext -- Context for the surrounding `isDefEq` call when entry was created deriving Inhabited structure State where mctx : MetavarContext := {} cache : Cache := {} /- When `trackZeta == true`, then any let-decl free variable that is zeta expansion performed by `MetaM` is stored in `zetaFVarIds`. -/ zetaFVarIds : FVarIdSet := {} postponed : PersistentArray PostponedEntry := {} deriving Inhabited structure SavedState where core : Core.State meta : State deriving Inhabited structure Context where config : Config := {} lctx : LocalContext := {} localInstances : LocalInstances := #[] /-- Not `none` when inside of an `isDefEq` test. See `PostponedEntry`. -/ defEqCtx? : Option DefEqContext := none /-- Track the number of nested `synthPending` invocations. Nested invocations can happen when the type class resolution invokes `synthPending`. Remark: in the current implementation, `synthPending` fails if `synthPendingDepth > 0`. We will add a configuration option if necessary. -/ synthPendingDepth : Nat := 0 /-- A predicate to control whether a constant can be unfolded or not at `whnf`. Note that we do not cache results at `whnf` when `canUnfold?` is not `none`. -/ canUnfold? : Option (Config → ConstantInfo → CoreM Bool) := none abbrev MetaM := ReaderT Context $ StateRefT State CoreM -- Make the compiler generate specialized `pure`/`bind` so we do not have to optimize through the -- whole monad stack at every use site. May eventually be covered by `deriving`. instance : Monad MetaM := let i := inferInstanceAs (Monad MetaM); { pure := i.pure, bind := i.bind } instance : Inhabited (MetaM α) where default := fun _ _ => arbitrary instance : MonadLCtx MetaM where getLCtx := return (← read).lctx instance : MonadMCtx MetaM where getMCtx := return (← get).mctx modifyMCtx f := modify fun s => { s with mctx := f s.mctx } instance : AddMessageContext MetaM where addMessageContext := addMessageContextFull protected def saveState : MetaM SavedState := return { core := (← getThe Core.State), meta := (← get) } /-- Restore backtrackable parts of the state. -/ def SavedState.restore (b : SavedState) : MetaM Unit := do Core.restore b.core modify fun s => { s with mctx := b.meta.mctx, zetaFVarIds := b.meta.zetaFVarIds, postponed := b.meta.postponed } instance : MonadBacktrack SavedState MetaM where saveState := Meta.saveState restoreState s := s.restore @[inline] def MetaM.run (x : MetaM α) (ctx : Context := {}) (s : State := {}) : CoreM (α × State) := x ctx |>.run s @[inline] def MetaM.run' (x : MetaM α) (ctx : Context := {}) (s : State := {}) : CoreM α := Prod.fst <$> x.run ctx s @[inline] def MetaM.toIO (x : MetaM α) (ctxCore : Core.Context) (sCore : Core.State) (ctx : Context := {}) (s : State := {}) : IO (α × Core.State × State) := do let ((a, s), sCore) ← (x.run ctx s).toIO ctxCore sCore pure (a, sCore, s) instance [MetaEval α] : MetaEval (MetaM α) := ⟨fun env opts x _ => MetaEval.eval env opts x.run' true⟩ protected def throwIsDefEqStuck : MetaM α := throw <| Exception.internal isDefEqStuckExceptionId builtin_initialize registerTraceClass `Meta registerTraceClass `Meta.debug @[inline] def liftMetaM [MonadLiftT MetaM m] (x : MetaM α) : m α := liftM x @[inline] def mapMetaM [MonadControlT MetaM m] [Monad m] (f : forall {α}, MetaM α → MetaM α) {α} (x : m α) : m α := controlAt MetaM fun runInBase => f <| runInBase x @[inline] def map1MetaM [MonadControlT MetaM m] [Monad m] (f : forall {α}, (β → MetaM α) → MetaM α) {α} (k : β → m α) : m α := controlAt MetaM fun runInBase => f fun b => runInBase <| k b @[inline] def map2MetaM [MonadControlT MetaM m] [Monad m] (f : forall {α}, (β → γ → MetaM α) → MetaM α) {α} (k : β → γ → m α) : m α := controlAt MetaM fun runInBase => f fun b c => runInBase <| k b c section Methods variable [MonadControlT MetaM n] [Monad n] @[inline] def modifyCache (f : Cache → Cache) : MetaM Unit := modify fun ⟨mctx, cache, zetaFVarIds, postponed⟩ => ⟨mctx, f cache, zetaFVarIds, postponed⟩ @[inline] def modifyInferTypeCache (f : InferTypeCache → InferTypeCache) : MetaM Unit := modifyCache fun ⟨ic, c1, c2, c3, c4, c5, c6⟩ => ⟨f ic, c1, c2, c3, c4, c5, c6⟩ def getLocalInstances : MetaM LocalInstances := return (← read).localInstances def getConfig : MetaM Config := return (← read).config def setMCtx (mctx : MetavarContext) : MetaM Unit := modify fun s => { s with mctx := mctx } def resetZetaFVarIds : MetaM Unit := modify fun s => { s with zetaFVarIds := {} } def getZetaFVarIds : MetaM FVarIdSet := return (← get).zetaFVarIds def getPostponed : MetaM (PersistentArray PostponedEntry) := return (← get).postponed def setPostponed (postponed : PersistentArray PostponedEntry) : MetaM Unit := modify fun s => { s with postponed := postponed } @[inline] def modifyPostponed (f : PersistentArray PostponedEntry → PersistentArray PostponedEntry) : MetaM Unit := modify fun s => { s with postponed := f s.postponed } /- WARNING: The following 4 constants are a hack for simulating forward declarations. They are defined later using the `export` attribute. This is hackish because we have to hard-code the true arity of these definitions here, and make sure the C names match. We have used another hack based on `IO.Ref`s in the past, it was safer but less efficient. -/ @[extern 6 "lean_whnf"] constant whnf : Expr → MetaM Expr @[extern 6 "lean_infer_type"] constant inferType : Expr → MetaM Expr @[extern 7 "lean_is_expr_def_eq"] constant isExprDefEqAux : Expr → Expr → MetaM Bool @[extern 7 "lean_is_level_def_eq"] constant isLevelDefEqAux : Level → Level → MetaM Bool @[extern 6 "lean_synth_pending"] protected constant synthPending : MVarId → MetaM Bool def whnfForall (e : Expr) : MetaM Expr := do let e' ← whnf e if e'.isForall then pure e' else pure e -- withIncRecDepth for a monad `n` such that `[MonadControlT MetaM n]` protected def withIncRecDepth (x : n α) : n α := mapMetaM (withIncRecDepth (m := MetaM)) x private def mkFreshExprMVarAtCore (mvarId : MVarId) (lctx : LocalContext) (localInsts : LocalInstances) (type : Expr) (kind : MetavarKind) (userName : Name) (numScopeArgs : Nat) : MetaM Expr := do modifyMCtx fun mctx => mctx.addExprMVarDecl mvarId userName lctx localInsts type kind numScopeArgs; return mkMVar mvarId def mkFreshExprMVarAt (lctx : LocalContext) (localInsts : LocalInstances) (type : Expr) (kind : MetavarKind := MetavarKind.natural) (userName : Name := Name.anonymous) (numScopeArgs : Nat := 0) : MetaM Expr := do mkFreshExprMVarAtCore (← mkFreshMVarId) lctx localInsts type kind userName numScopeArgs def mkFreshLevelMVar : MetaM Level := do let mvarId ← mkFreshMVarId modifyMCtx fun mctx => mctx.addLevelMVarDecl mvarId; return mkLevelMVar mvarId private def mkFreshExprMVarCore (type : Expr) (kind : MetavarKind) (userName : Name) : MetaM Expr := do mkFreshExprMVarAt (← getLCtx) (← getLocalInstances) type kind userName private def mkFreshExprMVarImpl (type? : Option Expr) (kind : MetavarKind) (userName : Name) : MetaM Expr := match type? with | some type => mkFreshExprMVarCore type kind userName | none => do let u ← mkFreshLevelMVar let type ← mkFreshExprMVarCore (mkSort u) MetavarKind.natural Name.anonymous mkFreshExprMVarCore type kind userName def mkFreshExprMVar (type? : Option Expr) (kind := MetavarKind.natural) (userName := Name.anonymous) : MetaM Expr := mkFreshExprMVarImpl type? kind userName def mkFreshTypeMVar (kind := MetavarKind.natural) (userName := Name.anonymous) : MetaM Expr := do let u ← mkFreshLevelMVar mkFreshExprMVar (mkSort u) kind userName /- Low-level version of `MkFreshExprMVar` which allows users to create/reserve a `mvarId` using `mkFreshId`, and then later create the metavar using this method. -/ private def mkFreshExprMVarWithIdCore (mvarId : MVarId) (type : Expr) (kind : MetavarKind := MetavarKind.natural) (userName : Name := Name.anonymous) (numScopeArgs : Nat := 0) : MetaM Expr := do mkFreshExprMVarAtCore mvarId (← getLCtx) (← getLocalInstances) type kind userName numScopeArgs def mkFreshExprMVarWithId (mvarId : MVarId) (type? : Option Expr := none) (kind : MetavarKind := MetavarKind.natural) (userName := Name.anonymous) : MetaM Expr := match type? with | some type => mkFreshExprMVarWithIdCore mvarId type kind userName | none => do let u ← mkFreshLevelMVar let type ← mkFreshExprMVar (mkSort u) mkFreshExprMVarWithIdCore mvarId type kind userName def mkFreshLevelMVars (num : Nat) : MetaM (List Level) := num.foldM (init := []) fun _ us => return (← mkFreshLevelMVar)::us def mkFreshLevelMVarsFor (info : ConstantInfo) : MetaM (List Level) := mkFreshLevelMVars info.numLevelParams def mkConstWithFreshMVarLevels (declName : Name) : MetaM Expr := do let info ← getConstInfo declName return mkConst declName (← mkFreshLevelMVarsFor info) def getTransparency : MetaM TransparencyMode := return (← getConfig).transparency def shouldReduceAll : MetaM Bool := return (← getTransparency) == TransparencyMode.all def shouldReduceReducibleOnly : MetaM Bool := return (← getTransparency) == TransparencyMode.reducible def getMVarDecl (mvarId : MVarId) : MetaM MetavarDecl := do match (← getMCtx).findDecl? mvarId with | some d => pure d | none => throwError "unknown metavariable '?{mvarId.name}'" def setMVarKind (mvarId : MVarId) (kind : MetavarKind) : MetaM Unit := modifyMCtx fun mctx => mctx.setMVarKind mvarId kind /- Update the type of the given metavariable. This function assumes the new type is definitionally equal to the current one -/ def setMVarType (mvarId : MVarId) (type : Expr) : MetaM Unit := do modifyMCtx fun mctx => mctx.setMVarType mvarId type def isReadOnlyExprMVar (mvarId : MVarId) : MetaM Bool := do return (← getMVarDecl mvarId).depth != (← getMCtx).depth def isReadOnlyOrSyntheticOpaqueExprMVar (mvarId : MVarId) : MetaM Bool := do let mvarDecl ← getMVarDecl mvarId match mvarDecl.kind with | MetavarKind.syntheticOpaque => return !(← getConfig).assignSyntheticOpaque | _ => return mvarDecl.depth != (← getMCtx).depth def getLevelMVarDepth (mvarId : MVarId) : MetaM Nat := do match (← getMCtx).findLevelDepth? mvarId with | some depth => return depth | _ => throwError "unknown universe metavariable '?{mvarId.name}'" def isReadOnlyLevelMVar (mvarId : MVarId) : MetaM Bool := do if (← getConfig).ignoreLevelMVarDepth then return false else return (← getLevelMVarDepth mvarId) != (← getMCtx).depth def renameMVar (mvarId : MVarId) (newUserName : Name) : MetaM Unit := modifyMCtx fun mctx => mctx.renameMVar mvarId newUserName def isExprMVarAssigned (mvarId : MVarId) : MetaM Bool := return (← getMCtx).isExprAssigned mvarId def getExprMVarAssignment? (mvarId : MVarId) : MetaM (Option Expr) := return (← getMCtx).getExprAssignment? mvarId /-- Return true if `e` contains `mvarId` directly or indirectly -/ def occursCheck (mvarId : MVarId) (e : Expr) : MetaM Bool := return (← getMCtx).occursCheck mvarId e def assignExprMVar (mvarId : MVarId) (val : Expr) : MetaM Unit := modifyMCtx fun mctx => mctx.assignExpr mvarId val def isDelayedAssigned (mvarId : MVarId) : MetaM Bool := return (← getMCtx).isDelayedAssigned mvarId def getDelayedAssignment? (mvarId : MVarId) : MetaM (Option DelayedMetavarAssignment) := return (← getMCtx).getDelayedAssignment? mvarId def hasAssignableMVar (e : Expr) : MetaM Bool := return (← getMCtx).hasAssignableMVar e def throwUnknownFVar (fvarId : FVarId) : MetaM α := throwError "unknown free variable '{mkFVar fvarId}'" def findLocalDecl? (fvarId : FVarId) : MetaM (Option LocalDecl) := return (← getLCtx).find? fvarId def getLocalDecl (fvarId : FVarId) : MetaM LocalDecl := do match (← getLCtx).find? fvarId with | some d => pure d | none => throwUnknownFVar fvarId def getFVarLocalDecl (fvar : Expr) : MetaM LocalDecl := getLocalDecl fvar.fvarId! def getLocalDeclFromUserName (userName : Name) : MetaM LocalDecl := do match (← getLCtx).findFromUserName? userName with | some d => pure d | none => throwError "unknown local declaration '{userName}'" def instantiateLevelMVars (u : Level) : MetaM Level := MetavarContext.instantiateLevelMVars u def instantiateMVars (e : Expr) : MetaM Expr := (MetavarContext.instantiateExprMVars e).run def instantiateLocalDeclMVars (localDecl : LocalDecl) : MetaM LocalDecl := match localDecl with | LocalDecl.cdecl idx id n type bi => return LocalDecl.cdecl idx id n (← instantiateMVars type) bi | LocalDecl.ldecl idx id n type val nonDep => return LocalDecl.ldecl idx id n (← instantiateMVars type) (← instantiateMVars val) nonDep @[inline] def liftMkBindingM (x : MetavarContext.MkBindingM α) : MetaM α := do match x (← getLCtx) { mctx := (← getMCtx), ngen := (← getNGen) } with | EStateM.Result.ok e newS => do setNGen newS.ngen; setMCtx newS.mctx; pure e | EStateM.Result.error (MetavarContext.MkBinding.Exception.revertFailure mctx lctx toRevert decl) newS => do setMCtx newS.mctx; setNGen newS.ngen; throwError "failed to create binder due to failure when reverting variable dependencies" def abstractRange (e : Expr) (n : Nat) (xs : Array Expr) : MetaM Expr := liftMkBindingM <| MetavarContext.abstractRange e n xs def abstract (e : Expr) (xs : Array Expr) : MetaM Expr := abstractRange e xs.size xs def mkForallFVars (xs : Array Expr) (e : Expr) (usedOnly : Bool := false) (usedLetOnly : Bool := true) : MetaM Expr := if xs.isEmpty then pure e else liftMkBindingM <| MetavarContext.mkForall xs e usedOnly usedLetOnly def mkLambdaFVars (xs : Array Expr) (e : Expr) (usedOnly : Bool := false) (usedLetOnly : Bool := true) : MetaM Expr := if xs.isEmpty then pure e else liftMkBindingM <| MetavarContext.mkLambda xs e usedOnly usedLetOnly def mkLetFVars (xs : Array Expr) (e : Expr) (usedLetOnly := true) : MetaM Expr := mkLambdaFVars xs e (usedLetOnly := usedLetOnly) def mkArrow (d b : Expr) : MetaM Expr := return Lean.mkForall (← mkFreshUserName `x) BinderInfo.default d b /-- `fun _ : Unit => a` -/ def mkFunUnit (a : Expr) : MetaM Expr := return Lean.mkLambda (← mkFreshUserName `x) BinderInfo.default (mkConst ``Unit) a def elimMVarDeps (xs : Array Expr) (e : Expr) (preserveOrder : Bool := false) : MetaM Expr := if xs.isEmpty then pure e else liftMkBindingM <| MetavarContext.elimMVarDeps xs e preserveOrder @[inline] def withConfig (f : Config → Config) : n α → n α := mapMetaM <| withReader (fun ctx => { ctx with config := f ctx.config }) @[inline] def withTrackingZeta (x : n α) : n α := withConfig (fun cfg => { cfg with trackZeta := true }) x @[inline] def withoutProofIrrelevance (x : n α) : n α := withConfig (fun cfg => { cfg with proofIrrelevance := false }) x @[inline] def withTransparency (mode : TransparencyMode) : n α → n α := mapMetaM <| withConfig (fun config => { config with transparency := mode }) @[inline] def withDefault (x : n α) : n α := withTransparency TransparencyMode.default x @[inline] def withReducible (x : n α) : n α := withTransparency TransparencyMode.reducible x @[inline] def withReducibleAndInstances (x : n α) : n α := withTransparency TransparencyMode.instances x @[inline] def withAtLeastTransparency (mode : TransparencyMode) (x : n α) : n α := withConfig (fun config => let oldMode := config.transparency let mode := if oldMode.lt mode then mode else oldMode { config with transparency := mode }) x /-- Execute `x` allowing `isDefEq` to assign synthetic opaque metavariables. -/ @[inline] def withAssignableSyntheticOpaque (x : n α) : n α := withConfig (fun config => { config with assignSyntheticOpaque := true }) x /-- Save cache, execute `x`, restore cache -/ @[inline] private def savingCacheImpl (x : MetaM α) : MetaM α := do let savedCache := (← get).cache try x finally modify fun s => { s with cache := savedCache } @[inline] def savingCache : n α → n α := mapMetaM savingCacheImpl def getTheoremInfo (info : ConstantInfo) : MetaM (Option ConstantInfo) := do if (← shouldReduceAll) then return some info else return none private def getDefInfoTemp (info : ConstantInfo) : MetaM (Option ConstantInfo) := do match (← getTransparency) with | TransparencyMode.all => return some info | TransparencyMode.default => return some info | _ => if (← isReducible info.name) then return some info else return none /- Remark: we later define `getConst?` at `GetConst.lean` after we define `Instances.lean`. This method is only used to implement `isClassQuickConst?`. It is very similar to `getConst?`, but it returns none when `TransparencyMode.instances` and `constName` is an instance. This difference should be irrelevant for `isClassQuickConst?`. -/ private def getConstTemp? (constName : Name) : MetaM (Option ConstantInfo) := do match (← getEnv).find? constName with | some (info@(ConstantInfo.thmInfo _)) => getTheoremInfo info | some (info@(ConstantInfo.defnInfo _)) => getDefInfoTemp info | some info => pure (some info) | none => throwUnknownConstant constName private def isClassQuickConst? (constName : Name) : MetaM (LOption Name) := do if isClass (← getEnv) constName then pure (LOption.some constName) else match (← getConstTemp? constName) with | some _ => pure LOption.undef | none => pure LOption.none private partial def isClassQuick? : Expr → MetaM (LOption Name) | Expr.bvar .. => pure LOption.none | Expr.lit .. => pure LOption.none | Expr.fvar .. => pure LOption.none | Expr.sort .. => pure LOption.none | Expr.lam .. => pure LOption.none | Expr.letE .. => pure LOption.undef | Expr.proj .. => pure LOption.undef | Expr.forallE _ _ b _ => isClassQuick? b | Expr.mdata _ e _ => isClassQuick? e | Expr.const n _ _ => isClassQuickConst? n | Expr.mvar mvarId _ => do match (← getExprMVarAssignment? mvarId) with | some val => isClassQuick? val | none => pure LOption.none | Expr.app f _ _ => match f.getAppFn with | Expr.const n .. => isClassQuickConst? n | Expr.lam .. => pure LOption.undef | _ => pure LOption.none def saveAndResetSynthInstanceCache : MetaM SynthInstanceCache := do let savedSythInstance := (← get).cache.synthInstance modifyCache fun c => { c with synthInstance := {} } pure savedSythInstance def restoreSynthInstanceCache (cache : SynthInstanceCache) : MetaM Unit := modifyCache fun c => { c with synthInstance := cache } @[inline] private def resettingSynthInstanceCacheImpl (x : MetaM α) : MetaM α := do let savedSythInstance ← saveAndResetSynthInstanceCache try x finally restoreSynthInstanceCache savedSythInstance /-- Reset `synthInstance` cache, execute `x`, and restore cache -/ @[inline] def resettingSynthInstanceCache : n α → n α := mapMetaM resettingSynthInstanceCacheImpl @[inline] def resettingSynthInstanceCacheWhen (b : Bool) (x : n α) : n α := if b then resettingSynthInstanceCache x else x private def withNewLocalInstanceImp (className : Name) (fvar : Expr) (k : MetaM α) : MetaM α := do let localDecl ← getFVarLocalDecl fvar /- Recall that we use `auxDecl` binderInfo when compiling recursive declarations. -/ match localDecl.binderInfo with | BinderInfo.auxDecl => k | _ => resettingSynthInstanceCache <| withReader (fun ctx => { ctx with localInstances := ctx.localInstances.push { className := className, fvar := fvar } }) k /-- Add entry `{ className := className, fvar := fvar }` to localInstances, and then execute continuation `k`. It resets the type class cache using `resettingSynthInstanceCache`. -/ def withNewLocalInstance (className : Name) (fvar : Expr) : n α → n α := mapMetaM <| withNewLocalInstanceImp className fvar private def fvarsSizeLtMaxFVars (fvars : Array Expr) (maxFVars? : Option Nat) : Bool := match maxFVars? with | some maxFVars => fvars.size < maxFVars | none => true mutual /-- `withNewLocalInstances isClassExpensive fvars j k` updates the vector or local instances using free variables `fvars[j] ... fvars.back`, and execute `k`. - `isClassExpensive` is defined later. - The type class chache is reset whenever a new local instance is found. - `isClassExpensive` uses `whnf` which depends (indirectly) on the set of local instances. Thus, each new local instance requires a new `resettingSynthInstanceCache`. -/ private partial def withNewLocalInstancesImp (fvars : Array Expr) (i : Nat) (k : MetaM α) : MetaM α := do if h : i < fvars.size then let fvar := fvars.get ⟨i, h⟩ let decl ← getFVarLocalDecl fvar match (← isClassQuick? decl.type) with | LOption.none => withNewLocalInstancesImp fvars (i+1) k | LOption.undef => match (← isClassExpensive? decl.type) with | none => withNewLocalInstancesImp fvars (i+1) k | some c => withNewLocalInstance c fvar <| withNewLocalInstancesImp fvars (i+1) k | LOption.some c => withNewLocalInstance c fvar <| withNewLocalInstancesImp fvars (i+1) k else k /-- `forallTelescopeAuxAux lctx fvars j type` Remarks: - `lctx` is the `MetaM` local context extended with declarations for `fvars`. - `type` is the type we are computing the telescope for. It contains only dangling bound variables in the range `[j, fvars.size)` - if `reducing? == true` and `type` is not `forallE`, we use `whnf`. - when `type` is not a `forallE` nor it can't be reduced to one, we excute the continuation `k`. Here is an example that demonstrates the `reducing?`. Suppose we have ``` abbrev StateM s a := s -> Prod a s ``` Now, assume we are trying to build the telescope for ``` forall (x : Nat), StateM Int Bool ``` if `reducing == true`, the function executes `k #[(x : Nat) (s : Int)] Bool`. if `reducing == false`, the function executes `k #[(x : Nat)] (StateM Int Bool)` if `maxFVars?` is `some max`, then we interrupt the telescope construction when `fvars.size == max` -/ private partial def forallTelescopeReducingAuxAux (reducing : Bool) (maxFVars? : Option Nat) (type : Expr) (k : Array Expr → Expr → MetaM α) : MetaM α := do let rec process (lctx : LocalContext) (fvars : Array Expr) (j : Nat) (type : Expr) : MetaM α := do match type with | Expr.forallE n d b c => if fvarsSizeLtMaxFVars fvars maxFVars? then let d := d.instantiateRevRange j fvars.size fvars let fvarId ← mkFreshFVarId let lctx := lctx.mkLocalDecl fvarId n d c.binderInfo let fvar := mkFVar fvarId let fvars := fvars.push fvar process lctx fvars j b else let type := type.instantiateRevRange j fvars.size fvars; withReader (fun ctx => { ctx with lctx := lctx }) do withNewLocalInstancesImp fvars j do k fvars type | _ => let type := type.instantiateRevRange j fvars.size fvars; withReader (fun ctx => { ctx with lctx := lctx }) do withNewLocalInstancesImp fvars j do if reducing && fvarsSizeLtMaxFVars fvars maxFVars? then let newType ← whnf type if newType.isForall then process lctx fvars fvars.size newType else k fvars type else k fvars type process (← getLCtx) #[] 0 type private partial def forallTelescopeReducingAux (type : Expr) (maxFVars? : Option Nat) (k : Array Expr → Expr → MetaM α) : MetaM α := do match maxFVars? with | some 0 => k #[] type | _ => do let newType ← whnf type if newType.isForall then forallTelescopeReducingAuxAux true maxFVars? newType k else k #[] type private partial def isClassExpensive? : Expr → MetaM (Option Name) | type => withReducible <| -- when testing whether a type is a type class, we only unfold reducible constants. forallTelescopeReducingAux type none fun xs type => do let env ← getEnv match type.getAppFn with | Expr.const c _ _ => do if isClass env c then return some c else -- make sure abbreviations are unfolded match (← whnf type).getAppFn with | Expr.const c _ _ => return if isClass env c then some c else none | _ => return none | _ => return none private partial def isClassImp? (type : Expr) : MetaM (Option Name) := do match (← isClassQuick? type) with | LOption.none => pure none | LOption.some c => pure (some c) | LOption.undef => isClassExpensive? type end def isClass? (type : Expr) : MetaM (Option Name) := try isClassImp? type catch _ => pure none private def withNewLocalInstancesImpAux (fvars : Array Expr) (j : Nat) : n α → n α := mapMetaM <| withNewLocalInstancesImp fvars j partial def withNewLocalInstances (fvars : Array Expr) (j : Nat) : n α → n α := mapMetaM <| withNewLocalInstancesImpAux fvars j @[inline] private def forallTelescopeImp (type : Expr) (k : Array Expr → Expr → MetaM α) : MetaM α := do forallTelescopeReducingAuxAux (reducing := false) (maxFVars? := none) type k /-- Given `type` of the form `forall xs, A`, execute `k xs A`. This combinator will declare local declarations, create free variables for them, execute `k` with updated local context, and make sure the cache is restored after executing `k`. -/ def forallTelescope (type : Expr) (k : Array Expr → Expr → n α) : n α := map2MetaM (fun k => forallTelescopeImp type k) k private def forallTelescopeReducingImp (type : Expr) (k : Array Expr → Expr → MetaM α) : MetaM α := forallTelescopeReducingAux type (maxFVars? := none) k /-- Similar to `forallTelescope`, but given `type` of the form `forall xs, A`, it reduces `A` and continues bulding the telescope if it is a `forall`. -/ def forallTelescopeReducing (type : Expr) (k : Array Expr → Expr → n α) : n α := map2MetaM (fun k => forallTelescopeReducingImp type k) k private def forallBoundedTelescopeImp (type : Expr) (maxFVars? : Option Nat) (k : Array Expr → Expr → MetaM α) : MetaM α := forallTelescopeReducingAux type maxFVars? k /-- Similar to `forallTelescopeReducing`, stops constructing the telescope when it reaches size `maxFVars`. -/ def forallBoundedTelescope (type : Expr) (maxFVars? : Option Nat) (k : Array Expr → Expr → n α) : n α := map2MetaM (fun k => forallBoundedTelescopeImp type maxFVars? k) k private partial def lambdaTelescopeImp (e : Expr) (consumeLet : Bool) (k : Array Expr → Expr → MetaM α) : MetaM α := do process consumeLet (← getLCtx) #[] 0 e where process (consumeLet : Bool) (lctx : LocalContext) (fvars : Array Expr) (j : Nat) (e : Expr) : MetaM α := do match consumeLet, e with | _, Expr.lam n d b c => let d := d.instantiateRevRange j fvars.size fvars let fvarId ← mkFreshFVarId let lctx := lctx.mkLocalDecl fvarId n d c.binderInfo let fvar := mkFVar fvarId process consumeLet lctx (fvars.push fvar) j b | true, Expr.letE n t v b _ => do let t := t.instantiateRevRange j fvars.size fvars let v := v.instantiateRevRange j fvars.size fvars let fvarId ← mkFreshFVarId let lctx := lctx.mkLetDecl fvarId n t v let fvar := mkFVar fvarId process true lctx (fvars.push fvar) j b | _, e => let e := e.instantiateRevRange j fvars.size fvars withReader (fun ctx => { ctx with lctx := lctx }) do withNewLocalInstancesImp fvars j do k fvars e /-- Similar to `forallTelescope` but for lambda and let expressions. -/ def lambdaLetTelescope (type : Expr) (k : Array Expr → Expr → n α) : n α := map2MetaM (fun k => lambdaTelescopeImp type true k) k /-- Similar to `forallTelescope` but for lambda expressions. -/ def lambdaTelescope (type : Expr) (k : Array Expr → Expr → n α) : n α := map2MetaM (fun k => lambdaTelescopeImp type false k) k /-- Return the parameter names for the givel global declaration. -/ def getParamNames (declName : Name) : MetaM (Array Name) := do forallTelescopeReducing (← getConstInfo declName).type fun xs _ => do xs.mapM fun x => do let localDecl ← getLocalDecl x.fvarId! pure localDecl.userName -- `kind` specifies the metavariable kind for metavariables not corresponding to instance implicit `[ ... ]` arguments. private partial def forallMetaTelescopeReducingAux (e : Expr) (reducing : Bool) (maxMVars? : Option Nat) (kind : MetavarKind) : MetaM (Array Expr × Array BinderInfo × Expr) := process #[] #[] 0 e where process (mvars : Array Expr) (bis : Array BinderInfo) (j : Nat) (type : Expr) : MetaM (Array Expr × Array BinderInfo × Expr) := do if maxMVars?.isEqSome mvars.size then let type := type.instantiateRevRange j mvars.size mvars; return (mvars, bis, type) else match type with | Expr.forallE n d b c => let d := d.instantiateRevRange j mvars.size mvars let k := if c.binderInfo.isInstImplicit then MetavarKind.synthetic else kind let mvar ← mkFreshExprMVar d k n let mvars := mvars.push mvar let bis := bis.push c.binderInfo process mvars bis j b | _ => let type := type.instantiateRevRange j mvars.size mvars; if reducing then do let newType ← whnf type; if newType.isForall then process mvars bis mvars.size newType else return (mvars, bis, type) else return (mvars, bis, type) /-- Similar to `forallTelescope`, but creates metavariables instead of free variables. -/ def forallMetaTelescope (e : Expr) (kind := MetavarKind.natural) : MetaM (Array Expr × Array BinderInfo × Expr) := forallMetaTelescopeReducingAux e (reducing := false) (maxMVars? := none) kind /-- Similar to `forallTelescopeReducing`, but creates metavariables instead of free variables. -/ def forallMetaTelescopeReducing (e : Expr) (maxMVars? : Option Nat := none) (kind := MetavarKind.natural) : MetaM (Array Expr × Array BinderInfo × Expr) := forallMetaTelescopeReducingAux e (reducing := true) maxMVars? kind /-- Similar to `forallMetaTelescopeReducing`, stops constructing the telescope when it reaches size `maxMVars`. -/ def forallMetaBoundedTelescope (e : Expr) (maxMVars : Nat) (kind : MetavarKind := MetavarKind.natural) : MetaM (Array Expr × Array BinderInfo × Expr) := forallMetaTelescopeReducingAux e (reducing := true) (maxMVars? := some maxMVars) (kind := kind) /-- Similar to `forallMetaTelescopeReducingAux` but for lambda expressions. -/ partial def lambdaMetaTelescope (e : Expr) (maxMVars? : Option Nat := none) : MetaM (Array Expr × Array BinderInfo × Expr) := process #[] #[] 0 e where process (mvars : Array Expr) (bis : Array BinderInfo) (j : Nat) (type : Expr) : MetaM (Array Expr × Array BinderInfo × Expr) := do let finalize : Unit → MetaM (Array Expr × Array BinderInfo × Expr) := fun _ => do let type := type.instantiateRevRange j mvars.size mvars pure (mvars, bis, type) if maxMVars?.isEqSome mvars.size then finalize () else match type with | Expr.lam n d b c => let d := d.instantiateRevRange j mvars.size mvars let mvar ← mkFreshExprMVar d let mvars := mvars.push mvar let bis := bis.push c.binderInfo process mvars bis j b | _ => finalize () private def withNewFVar (fvar fvarType : Expr) (k : Expr → MetaM α) : MetaM α := do match (← isClass? fvarType) with | none => k fvar | some c => withNewLocalInstance c fvar <| k fvar private def withLocalDeclImp (n : Name) (bi : BinderInfo) (type : Expr) (k : Expr → MetaM α) : MetaM α := do let fvarId ← mkFreshFVarId let ctx ← read let lctx := ctx.lctx.mkLocalDecl fvarId n type bi let fvar := mkFVar fvarId withReader (fun ctx => { ctx with lctx := lctx }) do withNewFVar fvar type k def withLocalDecl (name : Name) (bi : BinderInfo) (type : Expr) (k : Expr → n α) : n α := map1MetaM (fun k => withLocalDeclImp name bi type k) k def withLocalDeclD (name : Name) (type : Expr) (k : Expr → n α) : n α := withLocalDecl name BinderInfo.default type k partial def withLocalDecls [Inhabited α] (declInfos : Array (Name × BinderInfo × (Array Expr → n Expr))) (k : (xs : Array Expr) → n α) : n α := loop #[] where loop [Inhabited α] (acc : Array Expr) : n α := do if acc.size < declInfos.size then let (name, bi, typeCtor) := declInfos[acc.size] withLocalDecl name bi (←typeCtor acc) fun x => loop (acc.push x) else k acc def withLocalDeclsD [Inhabited α] (declInfos : Array (Name × (Array Expr → n Expr))) (k : (xs : Array Expr) → n α) : n α := withLocalDecls (declInfos.map (fun (name, typeCtor) => (name, BinderInfo.default, typeCtor))) k private def withNewBinderInfosImp (bs : Array (FVarId × BinderInfo)) (k : MetaM α) : MetaM α := do let lctx := bs.foldl (init := (← getLCtx)) fun lctx (fvarId, bi) => lctx.setBinderInfo fvarId bi withReader (fun ctx => { ctx with lctx := lctx }) k def withNewBinderInfos (bs : Array (FVarId × BinderInfo)) (k : n α) : n α := mapMetaM (fun k => withNewBinderInfosImp bs k) k private def withLetDeclImp (n : Name) (type : Expr) (val : Expr) (k : Expr → MetaM α) : MetaM α := do let fvarId ← mkFreshFVarId let ctx ← read let lctx := ctx.lctx.mkLetDecl fvarId n type val let fvar := mkFVar fvarId withReader (fun ctx => { ctx with lctx := lctx }) do withNewFVar fvar type k def withLetDecl (name : Name) (type : Expr) (val : Expr) (k : Expr → n α) : n α := map1MetaM (fun k => withLetDeclImp name type val k) k private def withExistingLocalDeclsImp (decls : List LocalDecl) (k : MetaM α) : MetaM α := do let ctx ← read let numLocalInstances := ctx.localInstances.size let lctx := decls.foldl (fun (lctx : LocalContext) decl => lctx.addDecl decl) ctx.lctx withReader (fun ctx => { ctx with lctx := lctx }) do let newLocalInsts ← decls.foldlM (fun (newlocalInsts : Array LocalInstance) (decl : LocalDecl) => (do { match (← isClass? decl.type) with | none => pure newlocalInsts | some c => pure <| newlocalInsts.push { className := c, fvar := decl.toExpr } } : MetaM _)) ctx.localInstances; if newLocalInsts.size == numLocalInstances then k else resettingSynthInstanceCache <| withReader (fun ctx => { ctx with localInstances := newLocalInsts }) k def withExistingLocalDecls (decls : List LocalDecl) : n α → n α := mapMetaM <| withExistingLocalDeclsImp decls private def withNewMCtxDepthImp (x : MetaM α) : MetaM α := do let saved ← get modify fun s => { s with mctx := s.mctx.incDepth, postponed := {} } try x finally modify fun s => { s with mctx := saved.mctx, postponed := saved.postponed } /-- Save cache and `MetavarContext`, bump the `MetavarContext` depth, execute `x`, and restore saved data. -/ def withNewMCtxDepth : n α → n α := mapMetaM withNewMCtxDepthImp private def withLocalContextImp (lctx : LocalContext) (localInsts : LocalInstances) (x : MetaM α) : MetaM α := do let localInstsCurr ← getLocalInstances withReader (fun ctx => { ctx with lctx := lctx, localInstances := localInsts }) do if localInsts == localInstsCurr then x else resettingSynthInstanceCache x def withLCtx (lctx : LocalContext) (localInsts : LocalInstances) : n α → n α := mapMetaM <| withLocalContextImp lctx localInsts private def withMVarContextImp (mvarId : MVarId) (x : MetaM α) : MetaM α := do let mvarDecl ← getMVarDecl mvarId withLocalContextImp mvarDecl.lctx mvarDecl.localInstances x /-- Execute `x` using the given metavariable `LocalContext` and `LocalInstances`. The type class resolution cache is flushed when executing `x` if its `LocalInstances` are different from the current ones. -/ def withMVarContext (mvarId : MVarId) : n α → n α := mapMetaM <| withMVarContextImp mvarId private def withMCtxImp (mctx : MetavarContext) (x : MetaM α) : MetaM α := do let mctx' ← getMCtx setMCtx mctx try x finally setMCtx mctx' def withMCtx (mctx : MetavarContext) : n α → n α := mapMetaM <| withMCtxImp mctx @[inline] private def approxDefEqImp (x : MetaM α) : MetaM α := withConfig (fun config => { config with foApprox := true, ctxApprox := true, quasiPatternApprox := true}) x /-- Execute `x` using approximate unification: `foApprox`, `ctxApprox` and `quasiPatternApprox`. -/ @[inline] def approxDefEq : n α → n α := mapMetaM approxDefEqImp @[inline] private def fullApproxDefEqImp (x : MetaM α) : MetaM α := withConfig (fun config => { config with foApprox := true, ctxApprox := true, quasiPatternApprox := true, constApprox := true }) x /-- Similar to `approxDefEq`, but uses all available approximations. We don't use `constApprox` by default at `approxDefEq` because it often produces undesirable solution for monadic code. For example, suppose we have `pure (x > 0)` which has type `?m Prop`. We also have the goal `[Pure ?m]`. Now, assume the expected type is `IO Bool`. Then, the unification constraint `?m Prop =?= IO Bool` could be solved as `?m := fun _ => IO Bool` using `constApprox`, but this spurious solution would generate a failure when we try to solve `[Pure (fun _ => IO Bool)]` -/ @[inline] def fullApproxDefEq : n α → n α := mapMetaM fullApproxDefEqImp def normalizeLevel (u : Level) : MetaM Level := do let u ← instantiateLevelMVars u pure u.normalize def assignLevelMVar (mvarId : MVarId) (u : Level) : MetaM Unit := do modifyMCtx fun mctx => mctx.assignLevel mvarId u def whnfR (e : Expr) : MetaM Expr := withTransparency TransparencyMode.reducible <| whnf e def whnfD (e : Expr) : MetaM Expr := withTransparency TransparencyMode.default <| whnf e def whnfI (e : Expr) : MetaM Expr := withTransparency TransparencyMode.instances <| whnf e def setInlineAttribute (declName : Name) (kind := Compiler.InlineAttributeKind.inline): MetaM Unit := do let env ← getEnv match Compiler.setInlineAttribute env declName kind with | Except.ok env => setEnv env | Except.error msg => throwError msg private partial def instantiateForallAux (ps : Array Expr) (i : Nat) (e : Expr) : MetaM Expr := do if h : i < ps.size then let p := ps.get ⟨i, h⟩ match (← whnf e) with | Expr.forallE _ _ b _ => instantiateForallAux ps (i+1) (b.instantiate1 p) | _ => throwError "invalid instantiateForall, too many parameters" else pure e /- Given `e` of the form `forall (a_1 : A_1) ... (a_n : A_n), B[a_1, ..., a_n]` and `p_1 : A_1, ... p_n : A_n`, return `B[p_1, ..., p_n]`. -/ def instantiateForall (e : Expr) (ps : Array Expr) : MetaM Expr := instantiateForallAux ps 0 e private partial def instantiateLambdaAux (ps : Array Expr) (i : Nat) (e : Expr) : MetaM Expr := do if h : i < ps.size then let p := ps.get ⟨i, h⟩ match (← whnf e) with | Expr.lam _ _ b _ => instantiateLambdaAux ps (i+1) (b.instantiate1 p) | _ => throwError "invalid instantiateLambda, too many parameters" else pure e /- Given `e` of the form `fun (a_1 : A_1) ... (a_n : A_n) => t[a_1, ..., a_n]` and `p_1 : A_1, ... p_n : A_n`, return `t[p_1, ..., p_n]`. It uses `whnf` to reduce `e` if it is not a lambda -/ def instantiateLambda (e : Expr) (ps : Array Expr) : MetaM Expr := instantiateLambdaAux ps 0 e /-- Return true iff `e` depends on the free variable `fvarId` -/ def dependsOn (e : Expr) (fvarId : FVarId) : MetaM Bool := return (← getMCtx).exprDependsOn e fvarId /-- Return true iff `e` depends on a free variable `x` s.t. `p x` -/ def dependsOnPred (e : Expr) (p : FVarId → Bool) : MetaM Bool := return (← getMCtx).findExprDependsOn e p /-- Return true iff the local declaration `localDecl` depends on a free variable `x` s.t. `p x` -/ def localDeclDependsOnPred (localDecl : LocalDecl) (p : FVarId → Bool) : MetaM Bool := do return (← getMCtx).findLocalDeclDependsOn localDecl p def ppExpr (e : Expr) : MetaM Format := do let ctxCore ← readThe Core.Context Lean.ppExpr { env := (← getEnv), mctx := (← getMCtx), lctx := (← getLCtx), opts := (← getOptions), currNamespace := ctxCore.currNamespace, openDecls := ctxCore.openDecls } e @[inline] protected def orElse (x : MetaM α) (y : Unit → MetaM α) : MetaM α := do let s ← saveState try x catch _ => s.restore; y () instance : OrElse (MetaM α) := ⟨Meta.orElse⟩ instance : Alternative MetaM where failure := fun {α} => throwError "failed" orElse := Meta.orElse @[inline] private def orelseMergeErrorsImp (x y : MetaM α) (mergeRef : Syntax → Syntax → Syntax := fun r₁ r₂ => r₁) (mergeMsg : MessageData → MessageData → MessageData := fun m₁ m₂ => m₁ ++ Format.line ++ m₂) : MetaM α := do let env ← getEnv let mctx ← getMCtx try x catch ex => setEnv env setMCtx mctx match ex with | Exception.error ref₁ m₁ => try y catch | Exception.error ref₂ m₂ => throw <| Exception.error (mergeRef ref₁ ref₂) (mergeMsg m₁ m₂) | ex => throw ex | ex => throw ex /-- Similar to `orelse`, but merge errors. Note that internal errors are not caught. The default `mergeRef` uses the `ref` (position information) for the first message. The default `mergeMsg` combines error messages using `Format.line ++ Format.line` as a separator. -/ @[inline] def orelseMergeErrors [MonadControlT MetaM m] [Monad m] (x y : m α) (mergeRef : Syntax → Syntax → Syntax := fun r₁ r₂ => r₁) (mergeMsg : MessageData → MessageData → MessageData := fun m₁ m₂ => m₁ ++ Format.line ++ Format.line ++ m₂) : m α := do controlAt MetaM fun runInBase => orelseMergeErrorsImp (runInBase x) (runInBase y) mergeRef mergeMsg /-- Execute `x`, and apply `f` to the produced error message -/ def mapErrorImp (x : MetaM α) (f : MessageData → MessageData) : MetaM α := do try x catch | Exception.error ref msg => throw <| Exception.error ref <| f msg | ex => throw ex @[inline] def mapError [MonadControlT MetaM m] [Monad m] (x : m α) (f : MessageData → MessageData) : m α := controlAt MetaM fun runInBase => mapErrorImp (runInBase x) f /-- Sort free variables using an order `x < y` iff `x` was defined before `y`. If a free variable is not in the local context, we use their id. -/ def sortFVarIds (fvarIds : Array FVarId) : MetaM (Array FVarId) := do let lctx ← getLCtx return fvarIds.qsort fun fvarId₁ fvarId₂ => match lctx.find? fvarId₁, lctx.find? fvarId₂ with | some d₁, some d₂ => d₁.index < d₂.index | some _, none => false | none, some _ => true | none, none => Name.quickLt fvarId₁.name fvarId₂.name end Methods def isInductivePredicate (declName : Name) : MetaM Bool := do match (← getEnv).find? declName with | some (ConstantInfo.inductInfo { type := type, ..}) => forallTelescopeReducing type fun _ type => do match (← whnfD type) with | Expr.sort u .. => return u == levelZero | _ => return false | _ => return false /- -/ def isListLevelDefEqAux : List Level → List Level → MetaM Bool | [], [] => return true | u::us, v::vs => isLevelDefEqAux u v <&&> isListLevelDefEqAux us vs | _, _ => return false private def getNumPostponed : MetaM Nat := do return (← getPostponed).size def getResetPostponed : MetaM (PersistentArray PostponedEntry) := do let ps ← getPostponed setPostponed {} return ps /-- Annotate any constant and sort in `e` that satisfies `p` with `pp.universes true` -/ private def exposeRelevantUniverses (e : Expr) (p : Level → Bool) : Expr := e.replace fun | Expr.const _ us _ => if us.any p then some (e.setPPUniverses true) else none | Expr.sort u _ => if p u then some (e.setPPUniverses true) else none | _ => none private def mkLeveErrorMessageCore (header : String) (entry : PostponedEntry) : MetaM MessageData := do match entry.ctx? with | none => return m!"{header}{indentD m!"{entry.lhs} =?= {entry.rhs}"}" | some ctx => withLCtx ctx.lctx ctx.localInstances do let s := entry.lhs.collectMVars entry.rhs.collectMVars /- `p u` is true if it contains a universe metavariable in `s` -/ let p (u : Level) := u.any fun | Level.mvar m _ => s.contains m | _ => false let lhs := exposeRelevantUniverses (← instantiateMVars ctx.lhs) p let rhs := exposeRelevantUniverses (← instantiateMVars ctx.rhs) p try addMessageContext m!"{header}{indentD m!"{entry.lhs} =?= {entry.rhs}"}\nwhile trying to unify{indentD m!"{lhs} : {← inferType lhs}"}\nwith{indentD m!"{rhs} : {← inferType rhs}"}" catch _ => addMessageContext m!"{header}{indentD m!"{entry.lhs} =?= {entry.rhs}"}\nwhile trying to unify{indentD lhs}\nwith{indentD rhs}" def mkLevelStuckErrorMessage (entry : PostponedEntry) : MetaM MessageData := do mkLeveErrorMessageCore "stuck at solving universe constraint" entry def mkLevelErrorMessage (entry : PostponedEntry) : MetaM MessageData := do mkLeveErrorMessageCore "failed to solve universe constraint" entry private def processPostponedStep (exceptionOnFailure : Bool) : MetaM Bool := traceCtx `Meta.isLevelDefEq.postponed.step do let ps ← getResetPostponed for p in ps do unless (← withReader (fun ctx => { ctx with defEqCtx? := p.ctx? }) <| isLevelDefEqAux p.lhs p.rhs) do if exceptionOnFailure then throwError (← mkLevelErrorMessage p) else return false return true partial def processPostponed (mayPostpone : Bool := true) (exceptionOnFailure := false) : MetaM Bool := do if (← getNumPostponed) == 0 then return true else traceCtx `Meta.isLevelDefEq.postponed do let rec loop : MetaM Bool := do let numPostponed ← getNumPostponed if numPostponed == 0 then return true else trace[Meta.isLevelDefEq.postponed] "processing #{numPostponed} postponed is-def-eq level constraints" if !(← processPostponedStep exceptionOnFailure) then return false else let numPostponed' ← getNumPostponed if numPostponed' == 0 then return true else if numPostponed' < numPostponed then loop else trace[Meta.isLevelDefEq.postponed] "no progress solving pending is-def-eq level constraints" return mayPostpone loop /-- `checkpointDefEq x` executes `x` and process all postponed universe level constraints produced by `x`. We keep the modifications only if `processPostponed` return true and `x` returned `true`. If `mayPostpone == false`, all new postponed universe level constraints must be solved before returning. We currently try to postpone universe constraints as much as possible, even when by postponing them we are not sure whether `x` really succeeded or not. -/ @[specialize] def checkpointDefEq (x : MetaM Bool) (mayPostpone : Bool := true) : MetaM Bool := do let s ← saveState let postponed ← getResetPostponed try if (← x) then if (← processPostponed mayPostpone) then let newPostponed ← getPostponed setPostponed (postponed ++ newPostponed) return true else s.restore return false else s.restore return false catch ex => s.restore throw ex def isLevelDefEq (u v : Level) : MetaM Bool := traceCtx `Meta.isLevelDefEq do let b ← checkpointDefEq (mayPostpone := true) <| Meta.isLevelDefEqAux u v trace[Meta.isLevelDefEq] "{u} =?= {v} ... {if b then "success" else "failure"}" return b def isExprDefEq (t s : Expr) : MetaM Bool := traceCtx `Meta.isDefEq <| withReader (fun ctx => { ctx with defEqCtx? := some { lhs := t, rhs := s, lctx := ctx.lctx, localInstances := ctx.localInstances } }) do let b ← checkpointDefEq (mayPostpone := true) <| Meta.isExprDefEqAux t s trace[Meta.isDefEq] "{t} =?= {s} ... {if b then "success" else "failure"}" return b abbrev isDefEq (t s : Expr) : MetaM Bool := isExprDefEq t s def isExprDefEqGuarded (a b : Expr) : MetaM Bool := do try isExprDefEq a b catch _ => return false abbrev isDefEqGuarded (t s : Expr) : MetaM Bool := isExprDefEqGuarded t s def isDefEqNoConstantApprox (t s : Expr) : MetaM Bool := approxDefEq <| isDefEq t s end Meta builtin_initialize registerTraceClass `Meta.isLevelDefEq.postponed export Meta (MetaM) end Lean
6e83a94575eace8c2375dc1b95bbcc5f04385e70
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebra/free_algebra.lean
0dd0cb1a592c4f4917f2353c90bbdf302b4b4acc
[ "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
16,409
lean
/- Copyright (c) 2020 Adam Topaz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Adam Topaz -/ import algebra.algebra.subalgebra.basic import algebra.monoid_algebra.basic /-! # Free Algebras Given a commutative semiring `R`, and a type `X`, we construct the free unital, associative `R`-algebra on `X`. ## Notation 1. `free_algebra R X` is the free algebra itself. It is endowed with an `R`-algebra structure. 2. `free_algebra.ι R` is the function `X → free_algebra R X`. 3. Given a function `f : X → A` to an R-algebra `A`, `lift R f` is the lift of `f` to an `R`-algebra morphism `free_algebra R X → A`. ## Theorems 1. `ι_comp_lift` states that the composition `(lift R f) ∘ (ι R)` is identical to `f`. 2. `lift_unique` states that whenever an R-algebra morphism `g : free_algebra R X → A` is given whose composition with `ι R` is `f`, then one has `g = lift R f`. 3. `hom_ext` is a variant of `lift_unique` in the form of an extensionality theorem. 4. `lift_comp_ι` is a combination of `ι_comp_lift` and `lift_unique`. It states that the lift of the composition of an algebra morphism with `ι` is the algebra morphism itself. 5. `equiv_monoid_algebra_free_monoid : free_algebra R X ≃ₐ[R] monoid_algebra R (free_monoid X)` 6. An inductive principle `induction`. ## Implementation details We construct the free algebra on `X` as a quotient of an inductive type `free_algebra.pre` by an inductively defined relation `free_algebra.rel`. Explicitly, the construction involves three steps: 1. We construct an inductive type `free_algebra.pre R X`, the terms of which should be thought of as representatives for the elements of `free_algebra R X`. It is the free type with maps from `R` and `X`, and with two binary operations `add` and `mul`. 2. We construct an inductive relation `free_algebra.rel R X` on `free_algebra.pre R X`. This is the smallest relation for which the quotient is an `R`-algebra where addition resp. multiplication are induced by `add` resp. `mul` from 1., and for which the map from `R` is the structure map for the algebra. 3. The free algebra `free_algebra R X` is the quotient of `free_algebra.pre R X` by the relation `free_algebra.rel R X`. -/ variables (R : Type*) [comm_semiring R] variables (X : Type*) namespace free_algebra /-- This inductive type is used to express representatives of the free algebra. -/ inductive pre | of : X → pre | of_scalar : R → pre | add : pre → pre → pre | mul : pre → pre → pre namespace pre instance : inhabited (pre R X) := ⟨of_scalar 0⟩ -- Note: These instances are only used to simplify the notation. /-- Coercion from `X` to `pre R X`. Note: Used for notation only. -/ def has_coe_generator : has_coe X (pre R X) := ⟨of⟩ /-- Coercion from `R` to `pre R X`. Note: Used for notation only. -/ def has_coe_semiring : has_coe R (pre R X) := ⟨of_scalar⟩ /-- Multiplication in `pre R X` defined as `pre.mul`. Note: Used for notation only. -/ def has_mul : has_mul (pre R X) := ⟨mul⟩ /-- Addition in `pre R X` defined as `pre.add`. Note: Used for notation only. -/ def has_add : has_add (pre R X) := ⟨add⟩ /-- Zero in `pre R X` defined as the image of `0` from `R`. Note: Used for notation only. -/ def has_zero : has_zero (pre R X) := ⟨of_scalar 0⟩ /-- One in `pre R X` defined as the image of `1` from `R`. Note: Used for notation only. -/ def has_one : has_one (pre R X) := ⟨of_scalar 1⟩ /-- Scalar multiplication defined as multiplication by the image of elements from `R`. Note: Used for notation only. -/ def has_smul : has_smul R (pre R X) := ⟨λ r m, mul (of_scalar r) m⟩ end pre local attribute [instance] pre.has_coe_generator pre.has_coe_semiring pre.has_mul pre.has_add pre.has_zero pre.has_one pre.has_smul /-- Given a function from `X` to an `R`-algebra `A`, `lift_fun` provides a lift of `f` to a function from `pre R X` to `A`. This is mainly used in the construction of `free_algebra.lift`. -/ def lift_fun {A : Type*} [semiring A] [algebra R A] (f : X → A) : pre R X → A := λ t, pre.rec_on t f (algebra_map _ _) (λ _ _, (+)) (λ _ _, (*)) /-- An inductively defined relation on `pre R X` used to force the initial algebra structure on the associated quotient. -/ inductive rel : (pre R X) → (pre R X) → Prop -- force `of_scalar` to be a central semiring morphism | add_scalar {r s : R} : rel ↑(r + s) (↑r + ↑s) | mul_scalar {r s : R} : rel ↑(r * s) (↑r * ↑s) | central_scalar {r : R} {a : pre R X} : rel (r * a) (a * r) -- commutative additive semigroup | add_assoc {a b c : pre R X} : rel (a + b + c) (a + (b + c)) | add_comm {a b : pre R X} : rel (a + b) (b + a) | zero_add {a : pre R X} : rel (0 + a) a -- multiplicative monoid | mul_assoc {a b c : pre R X} : rel (a * b * c) (a * (b * c)) | one_mul {a : pre R X} : rel (1 * a) a | mul_one {a : pre R X} : rel (a * 1) a -- distributivity | left_distrib {a b c : pre R X} : rel (a * (b + c)) (a * b + a * c) | right_distrib {a b c : pre R X} : rel ((a + b) * c) (a * c + b * c) -- other relations needed for semiring | zero_mul {a : pre R X} : rel (0 * a) 0 | mul_zero {a : pre R X} : rel (a * 0) 0 -- compatibility | add_compat_left {a b c : pre R X} : rel a b → rel (a + c) (b + c) | add_compat_right {a b c : pre R X} : rel a b → rel (c + a) (c + b) | mul_compat_left {a b c : pre R X} : rel a b → rel (a * c) (b * c) | mul_compat_right {a b c : pre R X} : rel a b → rel (c * a) (c * b) end free_algebra /-- The free algebra for the type `X` over the commutative semiring `R`. -/ def free_algebra := quot (free_algebra.rel R X) namespace free_algebra local attribute [instance] pre.has_coe_generator pre.has_coe_semiring pre.has_mul pre.has_add pre.has_zero pre.has_one pre.has_smul instance : semiring (free_algebra R X) := { add := quot.map₂ (+) (λ _ _ _, rel.add_compat_right) (λ _ _ _, rel.add_compat_left), add_assoc := by { rintros ⟨⟩ ⟨⟩ ⟨⟩, exact quot.sound rel.add_assoc }, zero := quot.mk _ 0, zero_add := by { rintro ⟨⟩, exact quot.sound rel.zero_add }, add_zero := begin rintros ⟨⟩, change quot.mk _ _ = _, rw [quot.sound rel.add_comm, quot.sound rel.zero_add], end, add_comm := by { rintros ⟨⟩ ⟨⟩, exact quot.sound rel.add_comm }, mul := quot.map₂ (*) (λ _ _ _, rel.mul_compat_right) (λ _ _ _, rel.mul_compat_left), mul_assoc := by { rintros ⟨⟩ ⟨⟩ ⟨⟩, exact quot.sound rel.mul_assoc }, one := quot.mk _ 1, one_mul := by { rintros ⟨⟩, exact quot.sound rel.one_mul }, mul_one := by { rintros ⟨⟩, exact quot.sound rel.mul_one }, left_distrib := by { rintros ⟨⟩ ⟨⟩ ⟨⟩, exact quot.sound rel.left_distrib }, right_distrib := by { rintros ⟨⟩ ⟨⟩ ⟨⟩, exact quot.sound rel.right_distrib }, zero_mul := by { rintros ⟨⟩, exact quot.sound rel.zero_mul }, mul_zero := by { rintros ⟨⟩, exact quot.sound rel.mul_zero } } instance : inhabited (free_algebra R X) := ⟨0⟩ instance : has_smul R (free_algebra R X) := { smul := λ r, quot.map ((*) ↑r) (λ a b, rel.mul_compat_right) } instance : algebra R (free_algebra R X) := { to_fun := λ r, quot.mk _ r, map_one' := rfl, map_mul' := λ _ _, quot.sound rel.mul_scalar, map_zero' := rfl, map_add' := λ _ _, quot.sound rel.add_scalar, commutes' := λ _, by { rintros ⟨⟩, exact quot.sound rel.central_scalar }, smul_def' := λ _ _, rfl } instance {S : Type*} [comm_ring S] : ring (free_algebra S X) := algebra.semiring_to_ring S variables {X} /-- The canonical function `X → free_algebra R X`. -/ def ι : X → free_algebra R X := λ m, quot.mk _ m @[simp] lemma quot_mk_eq_ι (m : X) : quot.mk (free_algebra.rel R X) m = ι R m := rfl variables {A : Type*} [semiring A] [algebra R A] /-- Internal definition used to define `lift` -/ private def lift_aux (f : X → A) : (free_algebra R X →ₐ[R] A) := { to_fun := λ a, quot.lift_on a (lift_fun _ _ f) $ λ a b h, begin induction h, { exact (algebra_map R A).map_add h_r h_s, }, { exact (algebra_map R A).map_mul h_r h_s }, { apply algebra.commutes }, { change _ + _ + _ = _ + (_ + _), rw add_assoc }, { change _ + _ = _ + _, rw add_comm, }, { change (algebra_map _ _ _) + lift_fun R X f _ = lift_fun R X f _, simp, }, { change _ * _ * _ = _ * (_ * _), rw mul_assoc }, { change (algebra_map _ _ _) * lift_fun R X f _ = lift_fun R X f _, simp, }, { change lift_fun R X f _ * (algebra_map _ _ _) = lift_fun R X f _, simp, }, { change _ * (_ + _) = _ * _ + _ * _, rw left_distrib, }, { change (_ + _) * _ = _ * _ + _ * _, rw right_distrib, }, { change (algebra_map _ _ _) * _ = algebra_map _ _ _, simp }, { change _ * (algebra_map _ _ _) = algebra_map _ _ _, simp }, repeat { change lift_fun R X f _ + lift_fun R X f _ = _, rw h_ih, refl, }, repeat { change lift_fun R X f _ * lift_fun R X f _ = _, rw h_ih, refl, }, end, map_one' := by { change algebra_map _ _ _ = _, simp }, map_mul' := by { rintros ⟨⟩ ⟨⟩, refl }, map_zero' := by { change algebra_map _ _ _ = _, simp }, map_add' := by { rintros ⟨⟩ ⟨⟩, refl }, commutes' := by tauto } /-- Given a function `f : X → A` where `A` is an `R`-algebra, `lift R f` is the unique lift of `f` to a morphism of `R`-algebras `free_algebra R X → A`. -/ def lift : (X → A) ≃ (free_algebra R X →ₐ[R] A) := { to_fun := lift_aux R, inv_fun := λ F, F ∘ (ι R), left_inv := λ f, by {ext, refl}, right_inv := λ F, by { ext x, rcases x, induction x, case pre.of : { change ((F : free_algebra R X → A) ∘ (ι R)) _ = _, refl }, case pre.of_scalar : { change algebra_map _ _ x = F (algebra_map _ _ x), rw alg_hom.commutes F x, }, case pre.add : a b ha hb { change lift_aux R (F ∘ ι R) (quot.mk _ _ + quot.mk _ _) = F (quot.mk _ _ + quot.mk _ _), rw [alg_hom.map_add, alg_hom.map_add, ha, hb], }, case pre.mul : a b ha hb { change lift_aux R (F ∘ ι R) (quot.mk _ _ * quot.mk _ _) = F (quot.mk _ _ * quot.mk _ _), rw [alg_hom.map_mul, alg_hom.map_mul, ha, hb], }, }, } @[simp] lemma lift_aux_eq (f : X → A) : lift_aux R f = lift R f := rfl @[simp] lemma lift_symm_apply (F : free_algebra R X →ₐ[R] A) : (lift R).symm F = F ∘ (ι R) := rfl variables {R X} @[simp] theorem ι_comp_lift (f : X → A) : (lift R f : free_algebra R X → A) ∘ (ι R) = f := by {ext, refl} @[simp] theorem lift_ι_apply (f : X → A) (x) : lift R f (ι R x) = f x := rfl @[simp] theorem lift_unique (f : X → A) (g : free_algebra R X →ₐ[R] A) : (g : free_algebra R X → A) ∘ (ι R) = f ↔ g = lift R f := (lift R).symm_apply_eq /-! At this stage we set the basic definitions as `@[irreducible]`, so from this point onwards one should only use the universal properties of the free algebra, and consider the actual implementation as a quotient of an inductive type as completely hidden. Of course, one still has the option to locally make these definitions `semireducible` if so desired, and Lean is still willing in some circumstances to do unification based on the underlying definition. -/ attribute [irreducible] ι lift -- Marking `free_algebra` irreducible makes `ring` instances inaccessible on quotients. -- https://leanprover.zulipchat.com/#narrow/stream/113488-general/topic/algebra.2Esemiring_to_ring.20breaks.20semimodule.20typeclass.20lookup/near/212580241 -- For now, we avoid this by not marking it irreducible. @[simp] theorem lift_comp_ι (g : free_algebra R X →ₐ[R] A) : lift R ((g : free_algebra R X → A) ∘ (ι R)) = g := by { rw ←lift_symm_apply, exact (lift R).apply_symm_apply g } /-- See note [partially-applied ext lemmas]. -/ @[ext] theorem hom_ext {f g : free_algebra R X →ₐ[R] A} (w : ((f : free_algebra R X → A) ∘ (ι R)) = ((g : free_algebra R X → A) ∘ (ι R))) : f = g := begin rw [←lift_symm_apply, ←lift_symm_apply] at w, exact (lift R).symm.injective w, end /-- The free algebra on `X` is "just" the monoid algebra on the free monoid on `X`. This would be useful when constructing linear maps out of a free algebra, for example. -/ noncomputable def equiv_monoid_algebra_free_monoid : free_algebra R X ≃ₐ[R] monoid_algebra R (free_monoid X) := alg_equiv.of_alg_hom (lift R (λ x, (monoid_algebra.of R (free_monoid X)) (free_monoid.of x))) ((monoid_algebra.lift R (free_monoid X) (free_algebra R X)) (free_monoid.lift (ι R))) begin apply monoid_algebra.alg_hom_ext, intro x, apply free_monoid.rec_on x, { simp, refl, }, { intros x y ih, simp at ih, simp [ih], } end (by { ext, simp, }) instance [nontrivial R] : nontrivial (free_algebra R X) := equiv_monoid_algebra_free_monoid.surjective.nontrivial section /-- The left-inverse of `algebra_map`. -/ def algebra_map_inv : free_algebra R X →ₐ[R] R := lift R (0 : X → R) lemma algebra_map_left_inverse : function.left_inverse algebra_map_inv (algebra_map R $ free_algebra R X) := λ x, by simp [algebra_map_inv] @[simp] lemma algebra_map_inj (x y : R) : algebra_map R (free_algebra R X) x = algebra_map R (free_algebra R X) y ↔ x = y := algebra_map_left_inverse.injective.eq_iff @[simp] lemma algebra_map_eq_zero_iff (x : R) : algebra_map R (free_algebra R X) x = 0 ↔ x = 0 := map_eq_zero_iff (algebra_map _ _) algebra_map_left_inverse.injective @[simp] lemma algebra_map_eq_one_iff (x : R) : algebra_map R (free_algebra R X) x = 1 ↔ x = 1 := map_eq_one_iff (algebra_map _ _) algebra_map_left_inverse.injective -- this proof is copied from the approach in `free_abelian_group.of_injective` lemma ι_injective [nontrivial R] : function.injective (ι R : X → free_algebra R X) := λ x y hoxy, classical.by_contradiction $ assume hxy : x ≠ y, let f : free_algebra R X →ₐ[R] R := lift R (λ z, by classical; exact if x = z then (1 : R) else 0) in have hfx1 : f (ι R x) = 1, from (lift_ι_apply _ _).trans $ if_pos rfl, have hfy1 : f (ι R y) = 1, from hoxy ▸ hfx1, have hfy0 : f (ι R y) = 0, from (lift_ι_apply _ _).trans $ if_neg hxy, one_ne_zero $ hfy1.symm.trans hfy0 @[simp] lemma ι_inj [nontrivial R] (x y : X) : ι R x = ι R y ↔ x = y := ι_injective.eq_iff @[simp] lemma ι_ne_algebra_map [nontrivial R] (x : X) (r : R) : ι R x ≠ algebra_map R _ r := λ h, let f0 : free_algebra R X →ₐ[R] R := lift R 0 in let f1 : free_algebra R X →ₐ[R] R := lift R 1 in have hf0 : f0 (ι R x) = 0, from lift_ι_apply _ _, have hf1 : f1 (ι R x) = 1, from lift_ι_apply _ _, begin rw [h, f0.commutes, algebra.id.map_eq_self] at hf0, rw [h, f1.commutes, algebra.id.map_eq_self] at hf1, exact zero_ne_one (hf0.symm.trans hf1), end @[simp] lemma ι_ne_zero [nontrivial R] (x : X) : ι R x ≠ 0 := ι_ne_algebra_map x 0 @[simp] lemma ι_ne_one [nontrivial R] (x : X) : ι R x ≠ 1 := ι_ne_algebra_map x 1 end end free_algebra /- There is something weird in the above namespace that breaks the typeclass resolution of `has_coe_to_sort` below. Closing it and reopening it fixes it... -/ namespace free_algebra /-- An induction principle for the free algebra. If `C` holds for the `algebra_map` of `r : R` into `free_algebra R X`, the `ι` of `x : X`, and is preserved under addition and muliplication, then it holds for all of `free_algebra R X`. -/ @[elab_as_eliminator] lemma induction {C : free_algebra R X → Prop} (h_grade0 : ∀ r, C (algebra_map R (free_algebra R X) r)) (h_grade1 : ∀ x, C (ι R x)) (h_mul : ∀ a b, C a → C b → C (a * b)) (h_add : ∀ a b, C a → C b → C (a + b)) (a : free_algebra R X) : C a := begin -- the arguments are enough to construct a subalgebra, and a mapping into it from X let s : subalgebra R (free_algebra R X) := { carrier := C, mul_mem' := h_mul, add_mem' := h_add, algebra_map_mem' := h_grade0, }, let of : X → s := subtype.coind (ι R) h_grade1, -- the mapping through the subalgebra is the identity have of_id : alg_hom.id R (free_algebra R X) = s.val.comp (lift R of), { ext, simp [of, subtype.coind], }, -- finding a proof is finding an element of the subalgebra convert subtype.prop (lift R of a), simp [alg_hom.ext_iff] at of_id, exact of_id a, end end free_algebra
a62ffbb1593b9a7a5e025faaca351f6f59e5232e
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/init/data/array/default_auto.lean
61630a986ed9176c14ef4aed3f43ca8551731aaf
[]
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
306
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.data.array.basic import Mathlib.Lean3Lib.init.data.array.slice namespace Mathlib end Mathlib
814a6748c6167a1e4fd955ff0ffd3e3df01a9723
69bc7d0780be17e452d542a93f9599488f1c0c8e
/prop_logic_test.lean
be6d05a7be4517713aa7e6abb9d680ea0c113684
[]
no_license
joek13/cs2102-notes
b7352285b1d1184fae25594f89f5926d74e6d7b4
25bb18788641b20af9cf3c429afe1da9b2f5eafb
refs/heads/master
1,673,461,162,867
1,575,561,090,000
1,575,561,090,000
207,573,549
0
0
null
null
null
null
UTF-8
Lean
false
false
2,018
lean
import .prop_logic open prop_logic open prop_logic.var open prop_logic.unOp open prop_logic.binOp open prop_logic.pExp def varX := mkVar 0 def varY := mkVar 1 def varZ := mkVar 2 def varW := mkVar 3 def X := varExp varX def Y := varExp varY def Z := varExp varZ def W := varExp varW -- Notes on operator precedence def mystery := ¬ (X ∧ Y) ∨ (¬ X ∧ ¬ Y) #check mystery -- Does the above expression represent ¬((X ∧ Y) ∨ (¬ X ∧ ¬ Y)) -- ... or does it represent (¬ (X ∧ Y)) ∨ (¬ X ∧ ¬ Y) #reduce mystery -- Since not has a higher precedence (or "binding power") than or def pxor := (X ∧ ¬Y) ∨ (¬X ∧ Y) def pXor : pExp → pExp → pExp | a b := (a ∧ ¬b) ∨ (¬a ∧ b) #reduce pXor X Y notation a ⊕ b := pXor a b -- our variable interpretation function simply takes us from variable to boolean value def allFalse : var → bool | _ := ff def allTrue : var → bool | _ := tt def interp : (var → bool) | (mkVar 0) := tt -- X | (mkVar 1) := ff -- Y | (mkVar 2) := tt -- z | (mkVar 3) := ff -- W | _ := ff #eval allFalse varX #eval allTrue varX #eval interp varX #eval interp varY #eval pEval pTrue allFalse -- still true, as pTrue is a literal—not a variable #eval pEval (X ⊕ Y) interp def max' (a b : nat) : nat := if a > b then a else b def var_list : pExp → list nat | (pExp.litExp _) := list.nil | (pExp.varExp (mkVar n)) := [n] | (pExp.unOpExp o e) := var_list e | (pExp.binOpExp o e1 e2) := list.append (var_list e1) (var_list e2) def pred_any {α : Type} : (α → bool) → list α → bool | f list.nil := ff | f (list.cons a t) := bor (f a) (pred_any f t) def unique_list : list nat → list nat | list.nil := list.nil | (list.cons a t) := if (pred_any (λ e, e=a) t) then unique_list t else list.cons a (unique_list t) def len {α : Type} : list α → nat | list.nil := 0 | (list.cons a t) := 1 + len t def count_variables : pExp → nat := λ exp, len (unique_list (var_list exp)) #eval count_variables (pAnd (pXor X Y) (pNot Z))
d4d4b4a7444a9bb575f6fa71431496baa9b02e6e
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/tactic/ring_exp.lean
5b502badf58ac671db535fb0b2d9a5bdf7e5543a
[ "Apache-2.0" ]
permissive
gebner/mathlib
eab0150cc4f79ec45d2016a8c21750244a2e7ff0
cc6a6edc397c55118df62831e23bfbd6e6c6b4ab
refs/heads/master
1,625,574,853,976
1,586,712,827,000
1,586,712,827,000
99,101,412
1
0
Apache-2.0
1,586,716,389,000
1,501,667,958,000
Lean
UTF-8
Lean
false
false
55,552
lean
/- Copyright (c) 2019 Tim Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Tim Baanen. Solve equations in commutative (semi)rings with exponents. -/ import tactic.norm_num /-! # `ring_exp` tactic A tactic for solving equations in commutative (semi)rings, where the exponents can also contain variables. More precisely, expressions of the following form are supported: - constants (non-negative integers) - variables - coefficients (any rational number, embedded into the (semi)ring) - addition of expressions - multiplication of expressions - exponentiation of expressions (the exponent must have type `ℕ`) - subtraction and negation of expressions (if the base is a full ring) The motivating example is proving `2 * 2^n * b = b * 2^(n+1)`, something that the `ring` tactic cannot do, but `ring_exp` can. ## Implementation notes The basic approach to prove equalities is to normalise both sides and check for equality. The normalisation is guided by building a value in the type `ex` at the meta level, together with a proof (at the base level) that the original value is equal to the normalised version. The normalised version and normalisation proofs are also stored in the `ex` type. The outline of the file: - Define an inductive family of types `ex`, parametrised over `ex_type`, which can represent expressions with `+`, `*`, `^` and rational numerals. The parametrisation over `ex_type` ensures that associativity and distributivity are applied, by restricting which kinds of subexpressions appear as arguments to the various operators. - Represent addition, multiplication and exponentiation in the `ex` type, thus allowing us to map expressions to `ex` (the `eval` function drives this). We apply associativity and distributivity of the operators here (helped by `ex_type`) and commutativity as well (by sorting the subterms; unfortunately not helped by anything). Any expression not of the above formats is treated as an atom (the same as a variable). There are some details we glossed over which make the plan more complicated: - The order on atoms is not initially obvious. We construct a list containing them in order of initial appearance in the expression, then use the index into the list as a key to order on. - In the tactic, a normalized expression `ps : ex` lives in the meta-world, but the normalization proofs live in the real world. Thus, we cannot directly say `ps.orig = ps.pretty` anywhere, but we have to carefully construct the proof when we compute `ps`. This was a major source of bugs in development! - For `pow`, the exponent must be a natural number, while the base can be any semiring `α`. We swap out operations for the base ring `α` with those for the exponent ring `ℕ` as soon as we deal with exponents. This is accomplished by the `in_exponent` function and is relatively painless since we work in a `reader` monad. - The normalized form of an expression is the one that is useful for the tactic, but not as nice to read. To remedy this, the user-facing normalization calls `ex.simp`. ## Caveats and future work Subtraction cancels out identical terms, but division does not. That is: `a - a = 0 := by ring_exp` solves the goal, but `a / a := 1 by ring_exp` doesn't. Note that `0 / 0` is generally defined to be `0`, so division cancelling out is not true in general. Multiplication of powers can be simplified a little bit further: `2 ^ n * 2 ^ n = 4 ^ n := by ring_exp` could be implemented in a similar way that `2 * a + 2 * a = 4 * a := by ring_exp` already works. This feature wasn't needed yet, so it's not implemented yet. ## Tags ring, semiring, exponent, power -/ -- The base ring `α` will have a universe level `u`. -- We do not introduce `α` as a variable yet, -- in order to make it explicit or implicit as required. universes u namespace tactic.ring_exp open nat /-- The `atom` structure is used to represent atomic expressions: those which `ring_exp` cannot parse any further. For instance, `a + (a % b)` has `a` and `(a % b)` as atoms. The `ring_exp_eq` tactic does not normalize the subexpressions in atoms, but `ring_exp` does if `ring_exp_eq` was not sufficient. Atoms in fact represent equivalence classes of expressions, modulo definitional equality. The field `index : ℕ` should be a unique number for each class, while `value : expr` contains a representative of this class. The function `resolve_atom` determines the appropriate atom for a given expression. -/ meta structure atom : Type := (value : expr) (index : ℕ) namespace atom /-- The `eq` operation on `atom`s works modulo definitional equality, ignoring their `value`s. The invariants on `atom` ensure indices are unique per value. Thus, `eq` indicates equality as long as the `atom`s come from the same context. -/ meta def eq (a b : atom) : bool := a.index = b.index /-- We order `atom`s on the order of appearance in the main expression. -/ meta def lt (a b : atom) : bool := a.index < b.index meta instance : has_repr atom := ⟨λ x, "(atom " ++ repr x.2 ++ ")"⟩ end atom section expression /-! ### `expression` section In this section, we define the `ex` type and its basic operations. First, we introduce the supporting types `coeff`, `ex_type` and `ex_info`. For understanding the code, it's easier to check out `ex` itself first, then refer back to the supporting types. The arithmetic operations on `ex` need additional definitions, so they are defined in a later section. -/ /-- Coefficients in the expression are stored in a wrapper structure, allowing for easier modification of the data structures. The modifications might be caching of the result of `expr.of_rat`, or using a different meta representation of numerals. -/ @[derive decidable_eq, derive inhabited] structure coeff : Type := (value : ℚ) /-- The values in `ex_type` are used as parameters to `ex` to control the expression's structure. -/ @[derive decidable_eq, derive inhabited] inductive ex_type : Type | base : ex_type | sum : ex_type | prod : ex_type | exp : ex_type open ex_type /-- Each `ex` stores information for its normalization proof. The `orig` expression is the expression that was passed to `eval`. The `pretty` expression is the normalised form that the `ex` represents. (I didn't call this something like `norm`, because there are already too many things called `norm` in mathematics!) The field `proof` contains an optional proof term of type `%%orig = %%pretty`. The value `none` for the proof indicates that everything reduces to reflexivity. (Which saves space in quite a lot of cases.) -/ meta structure ex_info : Type := (orig : expr) (pretty : expr) (proof : option expr) /-- The `ex` type is an abstract representation of an expression with `+`, `*` and `^`. Those operators are mapped to the `sum`, `prod` and `exp` constructors respectively. The `zero` constructor is the base case for `ex sum`, e.g. `1 + 2` is represented by (something along the lines of) `sum 1 (sum 2 zero)`. The `coeff` constructor is the base case for `ex prod`, and is used for numerals. The code maintains the invariant that the coefficient is never `0`. The `var` constructor is the base case for `ex exp`, and is used for atoms. The `sum_b` constructor allows for addition in the base of an exponentiation; it serves a similar purpose as the parentheses in `(a + b)^c`. The code maintains the invariant that the argument to `sum_b` is not `zero` or `sum _ zero`. All of the constructors contain an `ex_info` field, used to carry around (arguments to) proof terms. While the `ex_type` parameter enforces some simplification invariants, the following ones must be manually maintained at the risk of insufficient power: - the argument to `coeff` must be nonzero (to ensure `0 = 0 * 1`) - the argument to `sum_b` must be of the form `sum a (sum b bs)` (to ensure `(a + 0)^n = a^n`) - normalisation proofs of subexpressions must be `refl ps.pretty` - if we replace `sum` with `cons` and `zero` with `nil`, the resulting list is sorted according to the `lt` relation defined further down; similarly for `prod` and `coeff` (to ensure `a + b = b + a`). The first two invariants could be encoded in a subtype of `ex`, but aren't (yet) to spare some implementation burden. The other invariants cannot be encoded because we need the `tactic` monad to check them. (For example, the correct equality check of `expr` is `is_def_eq : expr → expr → tactic unit`.) -/ meta inductive ex : ex_type → Type | zero (info : ex_info) : ex sum | sum (info : ex_info) : ex prod → ex sum → ex sum | coeff (info : ex_info) : coeff → ex prod | prod (info : ex_info) : ex exp → ex prod → ex prod | var (info : ex_info) : atom → ex base | sum_b (info : ex_info) : ex sum → ex base | exp (info : ex_info) : ex base → ex prod → ex exp /-- Return the proof information associated to the `ex`. -/ meta def ex.info : Π {et : ex_type} (ps : ex et), ex_info | sum (ex.zero i) := i | sum (ex.sum i _ _) := i | prod (ex.coeff i _) := i | prod (ex.prod i _ _) := i | base (ex.var i _) := i | base (ex.sum_b i _) := i | exp (ex.exp i _ _) := i /-- Return the original, non-normalized version of this `ex`. Note that arguments to another `ex` are always "pre-normalized": their `orig` and `pretty` are equal, and their `proof` is reflexivity. -/ meta def ex.orig {et : ex_type} (ps : ex et) : expr := ps.info.orig /-- Return the normalized version of this `ex`. -/ meta def ex.pretty {et : ex_type} (ps : ex et) : expr := ps.info.pretty /-- Return the normalisation proof of the given expression. If the proof is `refl`, we give `none` instead, which helps to control the size of proof terms. To get an actual term, use `ex.proof_term`, or use `mk_proof` with the correct set of arguments. -/ meta def ex.proof {et : ex_type} (ps : ex et) : option expr := ps.info.proof /-- Update the `orig` and `proof` fields of the `ex_info`. Intended for use in `ex.set_info`. -/ meta def ex_info.set (i : ex_info) (o : option expr) (pf : option expr) : ex_info := {orig := o.get_or_else i.pretty, proof := pf, .. i} /-- Update the `ex_info` of the given expression. We use this to combine intermediate normalisation proofs. Since `pretty` only depends on the subexpressions, which do not change, we do not set `pretty`. -/ meta def ex.set_info : Π {et : ex_type} (ps : ex et), option expr → option expr → ex et | sum (ex.zero i) o pf := ex.zero (i.set o pf) | sum (ex.sum i p ps) o pf := ex.sum (i.set o pf) p ps | prod (ex.coeff i x) o pf := ex.coeff (i.set o pf) x | prod (ex.prod i p ps) o pf := ex.prod (i.set o pf) p ps | base (ex.var i x) o pf := ex.var (i.set o pf) x | base (ex.sum_b i ps) o pf := ex.sum_b (i.set o pf) ps | exp (ex.exp i p ps) o pf := ex.exp (i.set o pf) p ps instance coeff_has_repr : has_repr coeff := ⟨λ x, repr x.1⟩ /-- Convert an `ex` to a `string`. -/ meta def ex.repr : Π {et : ex_type}, ex et → string | sum (ex.zero _) := "0" | sum (ex.sum _ p ps) := ex.repr p ++ " + " ++ ex.repr ps | prod (ex.coeff _ x) := repr x | prod (ex.prod _ p ps) := ex.repr p ++ " * " ++ ex.repr ps | base (ex.var _ x) := repr x | base (ex.sum_b _ ps) := "(" ++ ex.repr ps ++ ")" | exp (ex.exp _ p ps) := ex.repr p ++ " ^ " ++ ex.repr ps meta instance {et : ex_type} : has_repr (ex et) := ⟨ex.repr⟩ /-- Equality test for expressions. Since equivalence of `atom`s is not the same as equality, we cannot make a true `(=)` operator for `ex` either. -/ meta def ex.eq : Π {et : ex_type}, ex et → ex et → bool | sum (ex.zero _) (ex.zero _) := tt | sum (ex.zero _) (ex.sum _ _ _) := ff | sum (ex.sum _ _ _) (ex.zero _) := ff | sum (ex.sum _ p ps) (ex.sum _ q qs) := p.eq q && ps.eq qs | prod (ex.coeff _ x) (ex.coeff _ y) := x = y | prod (ex.coeff _ _) (ex.prod _ _ _) := ff | prod (ex.prod _ _ _) (ex.coeff _ _) := ff | prod (ex.prod _ p ps) (ex.prod _ q qs) := p.eq q && ps.eq qs | base (ex.var _ x) (ex.var _ y) := x.eq y | base (ex.var _ _) (ex.sum_b _ _) := ff | base (ex.sum_b _ _) (ex.var _ _) := ff | base (ex.sum_b _ ps) (ex.sum_b _ qs) := ps.eq qs | exp (ex.exp _ p ps) (ex.exp _ q qs) := p.eq q && ps.eq qs /-- The ordering on expressions. As for `ex.eq`, this is a linear order only in one context. -/ meta def ex.lt : Π {et : ex_type}, ex et → ex et → bool | sum _ (ex.zero _) := ff | sum (ex.zero _) _ := tt | sum (ex.sum _ p ps) (ex.sum _ q qs) := p.lt q || (p.eq q && ps.lt qs) | prod (ex.coeff _ x) (ex.coeff _ y) := x.1 < y.1 | prod (ex.coeff _ _) _ := tt | prod _ (ex.coeff _ _) := ff | prod (ex.prod _ p ps) (ex.prod _ q qs) := p.lt q || (p.eq q && ps.lt qs) | base (ex.var _ x) (ex.var _ y) := x.lt y | base (ex.var _ _) (ex.sum_b _ _) := tt | base (ex.sum_b _ _) (ex.var _ _) := ff | base (ex.sum_b _ ps) (ex.sum_b _ qs) := ps.lt qs | exp (ex.exp _ p ps) (ex.exp _ q qs) := p.lt q || (p.eq q && ps.lt qs) end expression section operations /-! ### `operations` section This section defines the operations (on `ex`) that use tactics. They live in the `ring_exp_m` monad, which adds a cache and a list of encountered atoms to the `tactic` monad. Throughout this section, we will be constructing proof terms. The lemmas used in the construction are all defined over a commutative semiring α. -/ variables {α : Type u} [comm_semiring α] open tactic open ex_type /-- Stores the information needed in the `eval` function and its dependencies, so they can (re)construct expressions. The `eval_info` structure stores this information for one type, and the `context` combines the two types, one for bases and one for exponents. -/ meta structure eval_info := (α : expr) (univ : level) -- Cache the instances for optimization and consistency (csr_instance : expr) (ha_instance : expr) (hm_instance : expr) (hp_instance : expr) -- Optional instances (only required for (-) and (/) respectively) (ring_instance : option expr) (dr_instance : option expr) -- Cache common constants. (zero : expr) (one : expr) /-- The `context` contains the full set of information needed for the `eval` function. This structure has two copies of `eval_info`: one is for the base (typically some semiring `α`) and another for the exponent (always `ℕ`). When evaluating an exponent, we put `info_e` in `info_b`. -/ meta structure context := (info_b : eval_info) (info_e : eval_info) (transp : transparency) /-- The `ring_exp_m` monad is used instead of `tactic` to store the context. -/ meta def ring_exp_m (α : Type) : Type := reader_t context (state_t (list atom) tactic) α -- Basic operations on `ring_exp_m`: meta instance : monad ring_exp_m := by { dunfold ring_exp_m, apply_instance } meta instance : alternative ring_exp_m := by { dunfold ring_exp_m, apply_instance } /-- Access the instance cache. -/ meta def get_context : ring_exp_m context := reader_t.read /-- Lift an operation in the `tactic` monad to the `ring_exp_m` monad. This operation will not access the cache. -/ meta def lift {α} (m : tactic α) : ring_exp_m α := reader_t.lift (state_t.lift m) /-- Change the context of the given computation, so that expressions are evaluated in the exponent ring, instead of the base ring. -/ meta def in_exponent {α} (mx : ring_exp_m α) : ring_exp_m α := do ctx ← get_context, reader_t.lift $ mx.run ⟨ctx.info_e, ctx.info_e, ctx.transp⟩ /-- Specialized version of `mk_app` where the first two arguments are `{α}` `[some_class α]`. Should be faster because it can use the cached instances. -/ meta def mk_app_class (f : name) (inst : expr) (args : list expr) : ring_exp_m expr := do ctx ← get_context, pure $ (@expr.const tt f [ctx.info_b.univ] ctx.info_b.α inst).mk_app args /-- Specialized version of `mk_app` where the first two arguments are `{α}` `[comm_semiring α]`. Should be faster because it can use the cached instances. -/ meta def mk_app_csr (f : name) (args : list expr) : ring_exp_m expr := do ctx ← get_context, mk_app_class f (ctx.info_b.csr_instance) args /-- Specialized version of `mk_app ``has_add.add`. Should be faster because it can use the cached instances. -/ meta def mk_add (args : list expr) : ring_exp_m expr := do ctx ← get_context, mk_app_class ``has_add.add ctx.info_b.ha_instance args /-- Specialized version of `mk_app ``has_mul.mul`. Should be faster because it can use the cached instances. -/ meta def mk_mul (args : list expr) : ring_exp_m expr := do ctx ← get_context, mk_app_class ``has_mul.mul ctx.info_b.hm_instance args /-- Specialized version of `mk_app ``has_pow.pow`. Should be faster because it can use the cached instances. -/ meta def mk_pow (args : list expr) : ring_exp_m expr := do ctx ← get_context, pure $ (@expr.const tt ``has_pow.pow [ctx.info_b.univ, ctx.info_e.univ] ctx.info_b.α ctx.info_e.α ctx.info_b.hp_instance).mk_app args /-- Construct a normalization proof term or return the cached one. -/ meta def ex_info.proof_term (ps : ex_info) : ring_exp_m expr := match ps.proof with | none := lift $ tactic.mk_eq_refl ps.pretty | (some p) := pure p end /-- Construct a normalization proof term or return the cached one. -/ meta def ex.proof_term {et : ex_type} (ps : ex et) : ring_exp_m expr := ps.info.proof_term /-- If all `ex_info` have trivial proofs, return a trivial proof. Otherwise, construct all proof terms. Useful in applications where trivial proofs combine to another trivial proof, most importantly to pass to `mk_proof_or_refl`. -/ meta def none_or_proof_term : list ex_info → ring_exp_m (option (list expr)) | [] := pure none | (x :: xs) := do xs_pfs ← none_or_proof_term xs, match (x.proof, xs_pfs) with | (none, none) := pure none | (some x_pf, none) := do xs_pfs ← traverse ex_info.proof_term xs, pure (some (x_pf :: xs_pfs)) | (_, some xs_pfs) := do x_pf ← x.proof_term, pure (some (x_pf :: xs_pfs)) end /-- Use the proof terms as arguments to the given lemma. If the lemma could reduce to reflexivity, consider using `mk_proof_or_refl.` -/ meta def mk_proof (lem : name) (args : list expr) (hs : list ex_info) : ring_exp_m expr := do hs' ← traverse ex_info.proof_term hs, mk_app_csr lem (args ++ hs') /-- Use the proof terms as arguments to the given lemma. Often, we construct a proof term using congruence where reflexivity suffices. To solve this, the following function tries to get away with reflexivity. -/ meta def mk_proof_or_refl (term : expr) (lem : name) (args : list expr) (hs : list ex_info) : ring_exp_m expr := do hs_full ← none_or_proof_term hs, match hs_full with | none := lift $ mk_eq_refl term | (some hs') := mk_app_csr lem (args ++ hs') end /-- A shortcut for adding the original terms of two expressions. -/ meta def add_orig {et et'} (ps : ex et) (qs : ex et') : ring_exp_m expr := mk_add [ps.orig, qs.orig] /-- A shortcut for multiplying the original terms of two expressions. -/ meta def mul_orig {et et'} (ps : ex et) (qs : ex et') : ring_exp_m expr := mk_mul [ps.orig, qs.orig] /-- A shortcut for exponentiating the original terms of two expressions. -/ meta def pow_orig {et et'} (ps : ex et) (qs : ex et') : ring_exp_m expr := mk_pow [ps.orig, qs.orig] /-- Congruence lemma for constructing `ex.sum`. -/ lemma sum_congr {p p' ps ps' : α} : p = p' → ps = ps' → p + ps = p' + ps' := by cc /-- Congruence lemma for constructing `ex.prod`. -/ lemma prod_congr {p p' ps ps' : α} : p = p' → ps = ps' → p * ps = p' * ps' := by cc /-- Congruence lemma for constructing `ex.exp`. -/ lemma exp_congr {p p' : α} {ps ps' : ℕ} : p = p' → ps = ps' → p ^ ps = p' ^ ps' := by cc /-- Constructs `ex.zero` with the correct arguments. -/ meta def ex_zero : ring_exp_m (ex sum) := do ctx ← get_context, pure $ ex.zero ⟨ctx.info_b.zero, ctx.info_b.zero, none⟩ /-- Constructs `ex.sum` with the correct arguments. -/ meta def ex_sum (p : ex prod) (ps : ex sum) : ring_exp_m (ex sum) := do pps_o ← add_orig p ps, pps_p ← mk_add [p.pretty, ps.pretty], pps_pf ← mk_proof_or_refl pps_p ``sum_congr [p.orig, p.pretty, ps.orig, ps.pretty] [p.info, ps.info], pure (ex.sum ⟨pps_o, pps_p, pps_pf⟩ (p.set_info none none) (ps.set_info none none)) /-- Constructs `ex.coeff` with the correct arguments. There are more efficient constructors for specific numerals: if `x = 0`, you should use `ex_zero`; if `x = 1`, use `ex_one`. -/ meta def ex_coeff (x : rat) : ring_exp_m (ex prod) := do ctx ← get_context, x_p ← lift $ expr.of_rat ctx.info_b.α x, pure (ex.coeff ⟨x_p, x_p, none⟩ ⟨x⟩) /-- Constructs `ex.coeff 1` with the correct arguments. This is a special case for optimization purposes. -/ meta def ex_one : ring_exp_m (ex prod) := do ctx ← get_context, pure $ ex.coeff ⟨ctx.info_b.one, ctx.info_b.one, none⟩ ⟨1⟩ /-- Constructs `ex.prod` with the correct arguments. -/ meta def ex_prod (p : ex exp) (ps : ex prod) : ring_exp_m (ex prod) := do pps_o ← mul_orig p ps, pps_p ← mk_mul [p.pretty, ps.pretty], pps_pf ← mk_proof_or_refl pps_p ``prod_congr [p.orig, p.pretty, ps.orig, ps.pretty] [p.info, ps.info], pure (ex.prod ⟨pps_o, pps_p, pps_pf⟩ (p.set_info none none) (ps.set_info none none)) /-- Constructs `ex.var` with the correct arguments. -/ meta def ex_var (p : atom) : ring_exp_m (ex base) := pure (ex.var ⟨p.1, p.1, none⟩ p) /-- Constructs `ex.sum_b` with the correct arguments. -/ meta def ex_sum_b (ps : ex sum) : ring_exp_m (ex base) := pure (ex.sum_b ps.info (ps.set_info none none)) /-- Constructs `ex.exp` with the correct arguments. -/ meta def ex_exp (p : ex base) (ps : ex prod) : ring_exp_m (ex exp) := do ctx ← get_context, pps_o ← pow_orig p ps, pps_p ← mk_pow [p.pretty, ps.pretty], pps_pf ← mk_proof_or_refl pps_p ``exp_congr [p.orig, p.pretty, ps.orig, ps.pretty] [p.info, ps.info], pure (ex.exp ⟨pps_o, pps_p, pps_pf⟩ (p.set_info none none) (ps.set_info none none)) lemma base_to_exp_pf {p p' : α} : p = p' → p = p' ^ 1 := by simp /-- Conversion from `ex base` to `ex exp`. -/ meta def base_to_exp (p : ex base) : ring_exp_m (ex exp) := do o ← in_exponent $ ex_one, ps ← ex_exp p o, pf ← mk_proof ``base_to_exp_pf [p.orig, p.pretty] [p.info], pure $ ps.set_info p.orig pf lemma exp_to_prod_pf {p p' : α} : p = p' → p = p' * 1 := by simp /-- Conversion from `ex exp` to `ex prod`. -/ meta def exp_to_prod (p : ex exp) : ring_exp_m (ex prod) := do o ← ex_one, ps ← ex_prod p o, pf ← mk_proof ``exp_to_prod_pf [p.orig, p.pretty] [p.info], pure $ ps.set_info p.orig pf lemma prod_to_sum_pf {p p' : α} : p = p' → p = p' + 0 := by simp /-- Conversion from `ex prod` to `ex sum`. -/ meta def prod_to_sum (p : ex prod) : ring_exp_m (ex sum) := do z ← ex_zero, ps ← ex_sum p z, pf ← mk_proof ``prod_to_sum_pf [p.orig, p.pretty] [p.info], pure $ ps.set_info p.orig pf lemma atom_to_sum_pf (p : α) : p = p ^ 1 * 1 + 0 := by simp /-- A more efficient conversion from `atom` to `ex sum`. The result should be the same as `ex_var p >>= base_to_exp >>= exp_to_prod >>= prod_to_sum`, except we need to calculate less intermediate steps. -/ meta def atom_to_sum (p : atom) : ring_exp_m (ex sum) := do p' ← ex_var p, o ← in_exponent $ ex_one, p' ← ex_exp p' o, o ← ex_one, p' ← ex_prod p' o, z ← ex_zero, p' ← ex_sum p' z, pf ← mk_proof ``atom_to_sum_pf [p.1] [], pure $ p'.set_info p.1 pf /-- Compute the sum of two coefficients. Note that the result might not be a valid expression: if `p = -q`, then the result should be `ex.zero : ex sum` instead. The caller must detect when this happens! The returned value is of the form `ex.coeff _ (p + q)`, with the proof of `expr.of_rat p + expr.of_rat q = expr.of_rat (p + q)`. -/ meta def add_coeff (p_p q_p : expr) (p q : coeff) : ring_exp_m (ex prod) := do ctx ← get_context, pq_o ← mk_add [p_p, q_p], (pq_p, pq_pf) ← lift $ norm_num pq_o, pure $ ex.coeff ⟨pq_o, pq_p, pq_pf⟩ ⟨p.1 + q.1⟩ lemma mul_coeff_pf_one_mul (q : α) : 1 * q = q := one_mul q lemma mul_coeff_pf_mul_one (p : α) : p * 1 = p := mul_one p /-- Compute the product of two coefficients. The returned value is of the form `ex.coeff _ (p * q)`, with the proof of `expr.of_rat p * expr.of_rat q = expr.of_rat (p * q)`. -/ meta def mul_coeff (p_p q_p : expr) (p q : coeff) : ring_exp_m (ex prod) := match p.1, q.1 with -- Special case to speed up multiplication with 1. | ⟨1, 1, _, _⟩, _ := do ctx ← get_context, pq_o ← mk_mul [p_p, q_p], pf ← mk_app_csr ``mul_coeff_pf_one_mul [q_p], pure $ ex.coeff ⟨pq_o, q_p, pf⟩ ⟨q.1⟩ | _, ⟨1, 1, _, _⟩ := do ctx ← get_context, pq_o ← mk_mul [p_p, q_p], pf ← mk_app_csr ``mul_coeff_pf_mul_one [p_p], pure $ ex.coeff ⟨pq_o, p_p, pf⟩ ⟨p.1⟩ | _, _ := do ctx ← get_context, pq' ← mk_mul [p_p, q_p], (pq_p, pq_pf) ← lift $ norm_num pq', pure $ ex.coeff ⟨pq_p, pq_p, pq_pf⟩ ⟨p.1 * q.1⟩ end /-- Represents the way in which two products are equal except coefficient. This type is used in the function `add_overlap`. In order to deal with equations of the form `a * 2 + a = 3 * a`, the `add` function will add up overlapping products, turning `a * 2 + a` into `a * 3`. We need to distinguish `a * 2 + a` from `a * 2 + b` in order to do this, and the `overlap` type carries the information on how it overlaps. The case `none` corresponds to non-overlapping products, e.g. `a * 2 + b`; the case `nonzero` to overlapping products adding to non-zero, e.g. `a * 2 + a` (the `ex prod` field will then look like `a * 3` with a proof that `a * 2 + a = a * 3`); the case `zero` to overlapping products adding to zero, e.g. `a * 2 + a * -2`. We distinguish those two cases because in the second, the whole product reduces to `0`. A potential extension to the tactic would also do this for the base of exponents, e.g. to show `2^n * 2^n = 4^n`. -/ meta inductive overlap : Type | none : overlap | nonzero : ex prod → overlap | zero : ex sum → overlap lemma add_overlap_pf {ps qs pq} (p : α) : ps + qs = pq → p * ps + p * qs = p * pq := λ pq_pf, calc p * ps + p * qs = p * (ps + qs) : symm (mul_add _ _ _) ... = p * pq : by rw pq_pf lemma add_overlap_pf_zero {ps qs} (p : α) : ps + qs = 0 → p * ps + p * qs = 0 := λ pq_pf, calc p * ps + p * qs = p * (ps + qs) : symm (mul_add _ _ _) ... = p * 0 : by rw pq_pf ... = 0 : mul_zero _ /-- Given arguments `ps`, `qs` of the form `ps' * x` and `ps' * y` respectively return `ps + qs = ps' * (x + y)` (with `x` and `y` arbitrary coefficients). For other arguments, return `overlap.none`. -/ meta def add_overlap : ex prod → ex prod → ring_exp_m overlap | (ex.coeff x_i x) (ex.coeff y_i y) := do xy@(ex.coeff _ xy_c) ← add_coeff x_i.pretty y_i.pretty x y | lift $ fail "internal error: add_coeff should return ex.coeff", if xy_c.1 = 0 then do z ← ex_zero, pure $ overlap.zero (z.set_info xy.orig xy.proof) else pure $ overlap.nonzero xy | (ex.prod _ _ _) (ex.coeff _ _) := pure overlap.none | (ex.coeff _ _) (ex.prod _ _ _) := pure overlap.none | pps@(ex.prod _ p ps) qqs@(ex.prod _ q qs) := if p.eq q then do pq_ol ← add_overlap ps qs, pqs_o ← add_orig pps qqs, match pq_ol with | overlap.none := pure overlap.none | (overlap.nonzero pq) := do pqs ← ex_prod p pq, pf ← mk_proof ``add_overlap_pf [ps.pretty, qs.pretty, pq.pretty, p.pretty] [pq.info], pure $ overlap.nonzero (pqs.set_info pqs_o pf) | (overlap.zero pq) := do z ← ex_zero, pf ← mk_proof ``add_overlap_pf_zero [ps.pretty, qs.pretty, p.pretty] [pq.info], pure $ overlap.zero (z.set_info pqs_o pf) end else pure overlap.none section addition lemma add_pf_z_sum {ps qs qs' : α} : ps = 0 → qs = qs' → ps + qs = qs' := λ ps_pf qs_pf, calc ps + qs = 0 + qs' : by rw [ps_pf, qs_pf] ... = qs' : zero_add _ lemma add_pf_sum_z {ps ps' qs : α} : ps = ps' → qs = 0 → ps + qs = ps' := λ ps_pf qs_pf, calc ps + qs = ps' + 0 : by rw [ps_pf, qs_pf] ... = ps' : add_zero _ lemma add_pf_sum_overlap {pps p ps qqs q qs pq pqs : α} : pps = p + ps → qqs = q + qs → p + q = pq → ps + qs = pqs → pps + qqs = pq + pqs := by cc lemma add_pf_sum_overlap_zero {pps p ps qqs q qs pqs : α} : pps = p + ps → qqs = q + qs → p + q = 0 → ps + qs = pqs → pps + qqs = pqs := λ pps_pf qqs_pf pq_pf pqs_pf, calc pps + qqs = (p + ps) + (q + qs) : by rw [pps_pf, qqs_pf] ... = (p + q) + (ps + qs) : by cc ... = 0 + pqs : by rw [pq_pf, pqs_pf] ... = pqs : zero_add _ lemma add_pf_sum_lt {pps p ps qqs pqs : α} : pps = p + ps → ps + qqs = pqs → pps + qqs = p + pqs := by cc lemma add_pf_sum_gt {pps qqs q qs pqs : α} : qqs = q + qs → pps + qs = pqs → pps + qqs = q + pqs := by cc /-- Add two expressions. * `0 + qs = 0` * `ps + 0 = 0` * `ps * x + ps * y = ps * (x + y)` (for `x`, `y` coefficients; uses `add_overlap`) * `(p + ps) + (q + qs) = p + (ps + (q + qs))` (if `p.lt q`) * `(p + ps) + (q + qs) = q + ((p + ps) + qs)` (if not `p.lt q`) -/ meta def add : ex sum → ex sum → ring_exp_m (ex sum) | ps@(ex.zero ps_i) qs := do pf ← mk_proof ``add_pf_z_sum [ps.orig, qs.orig, qs.pretty] [ps.info, qs.info], pqs_o ← add_orig ps qs, pure $ qs.set_info pqs_o pf | ps qs@(ex.zero qs_i) := do pf ← mk_proof ``add_pf_sum_z [ps.orig, ps.pretty, qs.orig] [ps.info, qs.info], pqs_o ← add_orig ps qs, pure $ ps.set_info pqs_o pf | pps@(ex.sum pps_i p ps) qqs@(ex.sum qqs_i q qs) := do ol ← add_overlap p q, ppqqs_o ← add_orig pps qqs, match ol with | (overlap.nonzero pq) := do pqs ← add ps qs, pqqs ← ex_sum pq pqs, qqs_pf ← qqs.proof_term, pf ← mk_proof ``add_pf_sum_overlap [pps.orig, p.pretty, ps.pretty, qqs.orig, q.pretty, qs.pretty, pq.pretty, pqs.pretty] [pps.info, qqs.info, pq.info, pqs.info], pure $ pqqs.set_info ppqqs_o pf | (overlap.zero pq) := do pqs ← add ps qs, pf ← mk_proof ``add_pf_sum_overlap_zero [pps.orig, p.pretty, ps.pretty, qqs.orig, q.pretty, qs.pretty, pqs.pretty] [pps.info, qqs.info, pq.info, pqs.info], pure $ pqs.set_info ppqqs_o pf | overlap.none := if p.lt q then do pqs ← add ps qqs, ppqs ← ex_sum p pqs, pf ← mk_proof ``add_pf_sum_lt [pps.orig, p.pretty, ps.pretty, qqs.orig, pqs.pretty] [pps.info, pqs.info], pure $ ppqs.set_info ppqqs_o pf else do pqs ← add pps qs, pqqs ← ex_sum q pqs, pf ← mk_proof ``add_pf_sum_gt [pps.orig, qqs.orig, q.pretty, qs.pretty, pqs.pretty] [qqs.info, pqs.info], pure $ pqqs.set_info ppqqs_o pf end end addition section multiplication lemma mul_pf_c_c {ps ps' qs qs' pq : α} : ps = ps' → qs = qs' → ps' * qs' = pq → ps * qs = pq := by cc lemma mul_pf_c_prod {ps qqs q qs pqs : α} : qqs = q * qs → ps * qs = pqs → ps * qqs = q * pqs := by cc lemma mul_pf_prod_c {pps p ps qs pqs : α} : pps = p * ps → ps * qs = pqs → pps * qs = p * pqs := by cc lemma mul_pp_pf_overlap {pps p_b ps qqs qs psqs : α} {p_e q_e : ℕ} : pps = p_b ^ p_e * ps → qqs = p_b ^ q_e * qs → p_b ^ (p_e + q_e) * (ps * qs) = psqs → pps * qqs = psqs := λ ps_pf qs_pf psqs_pf, by simp [symm psqs_pf, _root_.pow_add, ps_pf, qs_pf]; ac_refl lemma mul_pp_pf_prod_lt {pps p ps qqs pqs : α} : pps = p * ps → ps * qqs = pqs → pps * qqs = p * pqs := by cc lemma mul_pp_pf_prod_gt {pps qqs q qs pqs : α} : qqs = q * qs → pps * qs = pqs → pps * qqs = q * pqs := by cc /-- Multiply two expressions. * `x * y = (x * y)` (for `x`, `y` coefficients) * `x * (q * qs) = q * (qs * x)` (for `x` coefficient) * `(p * ps) * y = p * (ps * y)` (for `y` coefficient) * `(p_b^p_e * ps) * (p_b^q_e * qs) = p_b^(p_e + q_e) * (ps * qs)` (if `p_e` and `q_e` are identical except coefficient) * `(p * ps) * (q * qs) = p * (ps * (q * qs))` (if `p.lt q`) * `(p * ps) * (q * qs) = q * ((p * ps) * qs)` (if not `p.lt q`) -/ meta def mul_pp : ex prod → ex prod → ring_exp_m (ex prod) | ps@(ex.coeff _ x) qs@(ex.coeff _ y) := do pq ← mul_coeff ps.pretty qs.pretty x y, pq_o ← mul_orig ps qs, pf ← mk_proof_or_refl pq.pretty ``mul_pf_c_c [ps.orig, ps.pretty, qs.orig, qs.pretty, pq.pretty] [ps.info, qs.info, pq.info], pure $ pq.set_info pq_o pf | ps@(ex.coeff _ x) qqs@(ex.prod _ q qs) := do pqs ← mul_pp ps qs, pqqs ← ex_prod q pqs, pqqs_o ← mul_orig ps qqs, pf ← mk_proof ``mul_pf_c_prod [ps.orig, qqs.orig, q.pretty, qs.pretty, pqs.pretty] [qqs.info, pqs.info], pure $ pqqs.set_info pqqs_o pf | pps@(ex.prod _ p ps) qs@(ex.coeff _ y) := do pqs ← mul_pp ps qs, ppqs ← ex_prod p pqs, ppqs_o ← mul_orig pps qs, pf ← mk_proof ``mul_pf_prod_c [pps.orig, p.pretty, ps.pretty, qs.orig, pqs.pretty] [pps.info, pqs.info], pure $ ppqs.set_info ppqs_o pf | pps@(ex.prod _ p@(ex.exp _ p_b p_e) ps) qqs@(ex.prod _ q@(ex.exp _ q_b q_e) qs) := do ppqqs_o ← mul_orig pps qqs, pq_ol ← in_exponent $ add_overlap p_e q_e, match pq_ol, p_b.eq q_b with | (overlap.nonzero pq_e), tt := do psqs ← mul_pp ps qs, pq ← ex_exp p_b pq_e, ppsqqs ← ex_prod pq psqs, pf ← mk_proof ``mul_pp_pf_overlap [pps.orig, p_b.pretty, ps.pretty, qqs.orig, qs.pretty, ppsqqs.pretty, p_e.pretty, q_e.pretty] [pps.info, qqs.info, ppsqqs.info], pure $ ppsqqs.set_info ppqqs_o pf | _, _ := if p.lt q then do pqs ← mul_pp ps qqs, ppqs ← ex_prod p pqs, pf ← mk_proof ``mul_pp_pf_prod_lt [pps.orig, p.pretty, ps.pretty, qqs.orig, pqs.pretty] [pps.info, pqs.info], pure $ ppqs.set_info ppqqs_o pf else do pqs ← mul_pp pps qs, pqqs ← ex_prod q pqs, pf ← mk_proof ``mul_pp_pf_prod_gt [pps.orig, qqs.orig, q.pretty, qs.pretty, pqs.pretty] [qqs.info, pqs.info], pure $ pqqs.set_info ppqqs_o pf end lemma mul_p_pf_zero {ps qs : α} : ps = 0 → ps * qs = 0 := λ ps_pf, by rw [ps_pf, zero_mul] lemma mul_p_pf_sum {pps p ps qs ppsqs : α} : pps = p + ps → p * qs + ps * qs = ppsqs → pps * qs = ppsqs := λ pps_pf ppsqs_pf, calc pps * qs = (p + ps) * qs : by rw [pps_pf] ... = p * qs + ps * qs : add_mul _ _ _ ... = ppsqs : ppsqs_pf /-- Multiply two expressions. * `0 * qs = 0` * `(p + ps) * qs = (p * qs) + (ps * qs)` -/ meta def mul_p : ex sum → ex prod → ring_exp_m (ex sum) | ps@(ex.zero ps_i) qs := do z ← ex_zero, z_o ← mul_orig ps qs, pf ← mk_proof ``mul_p_pf_zero [ps.orig, qs.orig] [ps.info], pure $ z.set_info z_o pf | pps@(ex.sum pps_i p ps) qs := do pqs ← mul_pp p qs >>= prod_to_sum, psqs ← mul_p ps qs, ppsqs ← add pqs psqs, pps_pf ← pps.proof_term, ppsqs_o ← mul_orig pps qs, ppsqs_pf ← ppsqs.proof_term, pf ← mk_proof ``mul_p_pf_sum [pps.orig, p.pretty, ps.pretty, qs.orig, ppsqs.pretty] [pps.info, ppsqs.info], pure $ ppsqs.set_info ppsqs_o pf lemma mul_pf_zero {ps qs : α} : qs = 0 → ps * qs = 0 := λ qs_pf, by rw [qs_pf, mul_zero] lemma mul_pf_sum {ps qqs q qs psqqs : α} : qqs = q + qs → ps * q + ps * qs = psqqs → ps * qqs = psqqs := λ qs_pf psqqs_pf, calc ps * qqs = ps * (q + qs) : by rw [qs_pf] ... = ps * q + ps * qs : mul_add _ _ _ ... = psqqs : psqqs_pf /-- Multiply two expressions. * `ps * 0 = 0` * `ps * (q + qs) = (ps * q) + (ps * qs)` -/ meta def mul : ex sum → ex sum → ring_exp_m (ex sum) | ps qs@(ex.zero qs_i) := do z ← ex_zero, z_o ← mul_orig ps qs, pf ← mk_proof ``mul_pf_zero [ps.orig, qs.orig] [qs.info], pure $ z.set_info z_o pf | ps qqs@(ex.sum qqs_i q qs) := do psq ← mul_p ps q, psqs ← mul ps qs, psqqs ← add psq psqs, psqqs_o ← mul_orig ps qqs, pf ← mk_proof ``mul_pf_sum [ps.orig, qqs.orig, q.orig, qs.orig, psqqs.pretty] [qqs.info, psqqs.info], pure $ psqqs.set_info psqqs_o pf end multiplication section exponentiation lemma pow_e_pf_exp {pps p : α} {ps qs psqs : ℕ} : pps = p ^ ps → ps * qs = psqs → pps ^ qs = p ^ psqs := λ pps_pf psqs_pf, calc pps ^ qs = (p ^ ps) ^ qs : by rw [pps_pf] ... = p ^ (ps * qs) : symm (pow_mul _ _ _) ... = p ^ psqs : by rw [psqs_pf] /-- Exponentiate two expressions. * `(p ^ ps) ^ qs = p ^ (ps * qs)` -/ meta def pow_e : ex exp → ex prod → ring_exp_m (ex exp) | pps@(ex.exp pps_i p ps) qs := do psqs ← in_exponent $ mul_pp ps qs, ppsqs ← ex_exp p psqs, ppsqs_o ← pow_orig pps qs, pf ← mk_proof ``pow_e_pf_exp [pps.orig, p.pretty, ps.pretty, qs.orig, psqs.pretty] [pps.info, psqs.info], pure $ ppsqs.set_info ppsqs_o pf lemma pow_pp_pf_one {ps : α} {qs : ℕ} : ps = 1 → ps ^ qs = 1 := λ ps_pf, by rw [ps_pf, _root_.one_pow] lemma pow_pp_pf_c {ps ps' pqs : α} {qs qs' : ℕ} : ps = ps' → qs = qs' → ps' ^ qs' = pqs → ps ^ qs = pqs * 1 := by simp; cc lemma pow_pp_pf_prod {pps p ps pqs psqs : α} {qs : ℕ} : pps = p * ps → p ^ qs = pqs → ps ^ qs = psqs → pps ^ qs = pqs * psqs := λ pps_pf pqs_pf psqs_pf, calc pps ^ qs = (p * ps) ^ qs : by rw [pps_pf] ... = p ^ qs * ps ^ qs : mul_pow _ _ _ ... = pqs * psqs : by rw [pqs_pf, psqs_pf] /-- Exponentiate two expressions. * `1 ^ qs = 1` * `x ^ qs = x ^ qs` (for `x` coefficient) * `(p * ps) ^ qs = p ^ qs + ps ^ qs` -/ meta def pow_pp : ex prod → ex prod → ring_exp_m (ex prod) | ps@(ex.coeff ps_i ⟨⟨1, 1, _, _⟩⟩) qs := do o ← ex_one, o_o ← pow_orig ps qs, pf ← mk_proof ``pow_pp_pf_one [ps.orig, qs.orig] [ps.info], pure $ o.set_info o_o pf | ps@(ex.coeff ps_i x) qs := do ps'' ← pure ps >>= prod_to_sum >>= ex_sum_b, pqs ← ex_exp ps'' qs, pqs_o ← pow_orig ps qs, pf ← mk_proof_or_refl pqs.pretty ``pow_pp_pf_c [ps.orig, ps.pretty, pqs.pretty, qs.orig, qs.pretty] [ps.info, qs.info, pqs.info], pqs' ← exp_to_prod pqs, pure $ pqs'.set_info pqs_o pf | pps@(ex.prod pps_i p ps) qs := do pqs ← pow_e p qs, psqs ← pow_pp ps qs, ppsqs ← ex_prod pqs psqs, ppsqs_o ← pow_orig pps qs, pf ← mk_proof ``pow_pp_pf_prod [pps.orig, p.pretty, ps.pretty, pqs.pretty, psqs.pretty, qs.orig] [pps.info, pqs.info, psqs.info], pure $ ppsqs.set_info ppsqs_o pf lemma pow_p_pf_one {ps ps' : α} {qs : ℕ} : ps = ps' → qs = succ zero → ps ^ qs = ps' := λ ps_pf qs_pf, calc ps ^ qs = ps' ^ 1 : by rw [ps_pf, qs_pf] ... = ps' : pow_one _ lemma pow_p_pf_zero {ps : α} {qs qs' : ℕ} : ps = 0 → qs = succ qs' → ps ^ qs = 0 := λ ps_pf qs_pf, calc ps ^ qs = 0 ^ (succ qs') : by rw [ps_pf, qs_pf] ... = 0 : zero_pow (succ_pos qs') lemma pow_p_pf_succ {ps pqqs : α} {qs qs' : ℕ} : qs = succ qs' → ps * ps ^ qs' = pqqs → ps ^ qs = pqqs := λ qs_pf pqqs_pf, calc ps ^ qs = ps ^ succ qs' : by rw [qs_pf] ... = ps * ps ^ qs' : pow_succ _ _ ... = pqqs : by rw [pqqs_pf] lemma pow_p_pf_singleton {pps p pqs : α} {qs : ℕ} : pps = p + 0 → p ^ qs = pqs → pps ^ qs = pqs := λ pps_pf pqs_pf, by rw [pps_pf, add_zero, pqs_pf] lemma pow_p_pf_cons {ps ps' : α} {qs qs' : ℕ} : ps = ps' → qs = qs' → ps ^ qs = ps' ^ qs' := by cc /-- Exponentiate two expressions. * `ps ^ 1 = ps` * `0 ^ qs = 0` (note that this is handled *after* `ps ^ 0 = 1`) * `(p + 0) ^ qs = p ^ qs` * `ps ^ (qs + 1) = ps * ps ^ qs` (note that this is handled *after* `p + 0 ^ qs = p ^ qs`) * `ps ^ qs = ps ^ qs` (otherwise) -/ meta def pow_p : ex sum → ex prod → ring_exp_m (ex sum) | ps qs@(ex.coeff qs_i ⟨⟨1, 1, _, _⟩⟩) := do ps_o ← pow_orig ps qs, pf ← mk_proof ``pow_p_pf_one [ps.orig, ps.pretty, qs.orig] [ps.info, qs.info], pure $ ps.set_info ps_o pf | ps@(ex.zero ps_i) qs@(ex.coeff qs_i ⟨⟨succ y, 1, _, _⟩⟩) := do ctx ← get_context, z ← ex_zero, qs_pred ← lift $ expr.of_nat ctx.info_e.α y, pf ← mk_proof ``pow_p_pf_zero [ps.orig, qs.orig, qs_pred] [ps.info, qs.info], z_o ← pow_orig ps qs, pure $ z.set_info z_o pf | pps@(ex.sum pps_i p (ex.zero _)) qqs := do pqs ← pow_pp p qqs, pqs_o ← pow_orig pps qqs, pf ← mk_proof ``pow_p_pf_singleton [pps.orig, p.pretty, pqs.pretty, qqs.orig] [pps.info, pqs.info], prod_to_sum $ pqs.set_info pqs_o pf | ps qs@(ex.coeff qs_i ⟨⟨int.of_nat (succ n), 1, den_pos, _⟩⟩) := do qs' ← in_exponent $ ex_coeff ⟨int.of_nat n, 1, den_pos, coprime_one_right _⟩, pqs ← pow_p ps qs', pqqs ← mul ps pqs, pqqs_o ← pow_orig ps qs, pf ← mk_proof ``pow_p_pf_succ [ps.orig, pqqs.pretty, qs.orig, qs'.pretty] [qs.info, pqqs.info], pure $ pqqs.set_info pqqs_o pf | pps qqs := do -- fallback: treat them as atoms pps' ← ex_sum_b pps, psqs ← ex_exp pps' qqs, psqs_o ← pow_orig pps qqs, pf ← mk_proof_or_refl psqs.pretty ``pow_p_pf_cons [pps.orig, pps.pretty, qqs.orig, qqs.pretty] [pps.info, qqs.info], exp_to_prod (psqs.set_info psqs_o pf) >>= prod_to_sum lemma pow_pf_zero {ps : α} {qs : ℕ} : qs = 0 → ps ^ qs = 1 := λ qs_pf, calc ps ^ qs = ps ^ 0 : by rw [qs_pf] ... = 1 : pow_zero _ lemma pow_pf_sum {ps psqqs : α} {qqs q qs : ℕ} : qqs = q + qs → ps ^ q * ps ^ qs = psqqs → ps ^ qqs = psqqs := λ qqs_pf psqqs_pf, calc ps ^ qqs = ps ^ (q + qs) : by rw [qqs_pf] ... = ps ^ q * ps ^ qs : pow_add _ _ _ ... = psqqs : psqqs_pf /-- Exponentiate two expressions. * `ps ^ 0 = 1` * `ps ^ (q + qs) = ps ^ q * ps ^ qs` -/ meta def pow : ex sum → ex sum → ring_exp_m (ex sum) | ps qs@(ex.zero qs_i) := do o ← ex_one, o_o ← pow_orig ps qs, pf ← mk_proof ``pow_pf_zero [ps.orig, qs.orig] [qs.info], prod_to_sum $ o.set_info o_o pf | ps qqs@(ex.sum qqs_i q qs) := do psq ← pow_p ps q, psqs ← pow ps qs, psqqs ← mul psq psqs, psqqs_o ← pow_orig ps qqs, pf ← mk_proof ``pow_pf_sum [ps.orig, psqqs.pretty, qqs.orig, q.pretty, qs.pretty] [qqs.info, psqqs.info], pure $ psqqs.set_info psqqs_o pf end exponentiation lemma simple_pf_sum_zero {p p' : α} : p = p' → p + 0 = p' := by simp lemma simple_pf_prod_one {p p' : α} : p = p' → p * 1 = p' := by simp lemma simple_pf_prod_neg_one {α} [ring α] {p p' : α} : p = p' → p * -1 = - p' := by simp lemma simple_pf_var_one (p : α) : p ^ 1 = p := by simp lemma simple_pf_exp_one {p p' : α} : p = p' → p ^ 1 = p' := by simp /-- Give a simpler, more human-readable representation of the normalized expression. Normalized expressions might have the form `a^1 * 1 + 0`, since the dummy operations reduce special cases in pattern-matching. Humans prefer to read `a` instead. This tactic gets rid of the dummy additions, multiplications and exponentiations. -/ meta def ex.simple : Π {et : ex_type}, ex et → ring_exp_m (expr × expr) | sum pps@(ex.sum pps_i p (ex.zero _)) := do (p_p, p_pf) ← p.simple, prod.mk p_p <$> mk_app_csr ``simple_pf_sum_zero [p.pretty, p_p, p_pf] | sum (ex.sum pps_i p ps) := do (p_p, p_pf) ← p.simple, (ps_p, ps_pf) ← ps.simple, prod.mk <$> mk_add [p_p, ps_p] <*> mk_app_csr ``sum_congr [p.pretty, p_p, ps.pretty, ps_p, p_pf, ps_pf] | prod (ex.prod pps_i p (ex.coeff _ ⟨⟨1, 1, _, _⟩⟩)) := do (p_p, p_pf) ← p.simple, prod.mk p_p <$> mk_app_csr ``simple_pf_prod_one [p.pretty, p_p, p_pf] | prod pps@(ex.prod pps_i p (ex.coeff _ ⟨⟨-1, 1, _, _⟩⟩)) := do ctx ← get_context, match ctx.info_b.ring_instance with | none := prod.mk pps.pretty <$> pps.proof_term | (some ringi) := do (p_p, p_pf) ← p.simple, prod.mk <$> lift (mk_app ``has_neg.neg [p_p]) <*> mk_app_class ``simple_pf_prod_neg_one ringi [p.pretty, p_p, p_pf] end | prod (ex.prod pps_i p ps) := do (p_p, p_pf) ← p.simple, (ps_p, ps_pf) ← ps.simple, prod.mk <$> mk_mul [p_p, ps_p] <*> mk_app_csr ``prod_congr [p.pretty, p_p, ps.pretty, ps_p, p_pf, ps_pf] | base (ex.sum_b pps_i ps) := ps.simple | exp (ex.exp pps_i p (ex.coeff _ ⟨⟨1, 1, _, _⟩⟩)) := do (p_p, p_pf) ← p.simple, prod.mk p_p <$> mk_app_csr ``simple_pf_exp_one [p.pretty, p_p, p_pf] | exp (ex.exp pps_i p ps) := do (p_p, p_pf) ← p.simple, (ps_p, ps_pf) ← in_exponent $ ps.simple, prod.mk <$> mk_pow [p_p, ps_p] <*> mk_app_csr ``exp_congr [p.pretty, p_p, ps.pretty, ps_p, p_pf, ps_pf] | et ps := prod.mk ps.pretty <$> ps.proof_term /-- Performs a lookup of the atom `a` in the list of known atoms, or allocates a new one. If `a` is not definitionally equal to any of the list's entries, a new atom is appended to the list and returned. The index of this atom is kept track of in the second inductive argument. This function is mostly useful in `resolve_atom`, which updates the state with the new list of atoms. -/ meta def resolve_atom_aux (a : expr) : list atom → ℕ → ring_exp_m (atom × list atom) | [] n := let atm : atom := ⟨a, n⟩ in pure (atm, [atm]) | bas@(b :: as) n := do ctx ← get_context, (lift $ is_def_eq a b.value ctx.transp >> pure (b , bas)) <|> do (atm, as') ← resolve_atom_aux as (succ n), pure (atm, b :: as') /-- Convert the expression to an atom: either look up a definitionally equal atom, or allocate it as a new atom. You probably want to use `eval_base` if `eval` doesn't work instead of directly calling `resolve_atom`, since `eval_base` can also handle numerals. -/ meta def resolve_atom (a : expr) : ring_exp_m atom := do atoms ← reader_t.lift $ state_t.get, (atm, atoms') ← resolve_atom_aux a atoms 0, reader_t.lift $ state_t.put atoms', pure atm /-- Treat the expression atomically: as a coefficient or atom. Handles cases where `eval` cannot treat the expression as a known operation because it is just a number or single variable. -/ meta def eval_base (ps : expr) : ring_exp_m (ex sum) := match ps.to_rat with | some ⟨0, 1, _, _⟩ := ex_zero | some x := ex_coeff x >>= prod_to_sum | none := do a ← resolve_atom ps, atom_to_sum a end lemma negate_pf {α} [ring α] {ps ps' : α} : (-1) * ps = ps' → -ps = ps' := by simp /-- Negate an expression by multiplying with `-1`. Only works if there is a `ring` instance; otherwise it will `fail`. -/ meta def negate (ps : ex sum) : ring_exp_m (ex sum) := do ctx ← get_context, match ctx.info_b.ring_instance with | none := lift $ fail "internal error: negate called in semiring" | (some ring_instance) := do minus_one ← ex_coeff (-1) >>= prod_to_sum, ps' ← mul minus_one ps, ps_pf ← ps'.proof_term, pf ← mk_app_class ``negate_pf ring_instance [ps.orig, ps'.pretty, ps_pf], ps'_o ← lift $ mk_app ``has_neg.neg [ps.orig], pure $ ps'.set_info ps'_o pf end lemma inverse_pf {α} [division_ring α] {ps ps_u ps_p e' e'' : α} : ps = ps_u → ps_u = ps_p → ps_p ⁻¹ = e' → e' = e'' → ps ⁻¹ = e'' := by cc /-- Invert an expression by simplifying, applying `has_inv.inv` and treating the result as an atom. Only works if there is a `division_ring` instance; otherwise it will `fail`. -/ meta def inverse (ps : ex sum) : ring_exp_m (ex sum) := do ctx ← get_context, dri ← match ctx.info_b.dr_instance with | none := lift $ fail "division is only supported in a division ring" | (some dri) := pure dri end, (ps_simple, ps_simple_pf) ← ps.simple, e ← lift $ mk_app ``has_inv.inv [ps_simple], (e', e_pf) ← lift (norm_num.derive e) <|> ((λ e_pf, (e, e_pf)) <$> lift (mk_eq_refl e)), e'' ← eval_base e', ps_pf ← ps.proof_term, e''_pf ← e''.proof_term, pf ← mk_app_class ``inverse_pf dri [ ps.orig, ps.pretty, ps_simple, e', e''.pretty, ps_pf, ps_simple_pf, e_pf, e''_pf], e''_o ← lift $ mk_app ``has_inv.inv [ps.orig], pure $ e''.set_info e''_o pf lemma sub_pf {α} [ring α] {ps qs psqs : α} : ps + -qs = psqs → ps - qs = psqs := id lemma div_pf {α} [division_ring α] {ps qs psqs : α} : ps * qs⁻¹ = psqs → ps / qs = psqs := id end operations section wiring /-! ### `wiring` section This section deals with going from `expr` to `ex` and back. The main attraction is `eval`, which uses `add`, `mul`, etc. to calculate an `ex` from a given `expr`. Other functions use `ex`es to produce `expr`s together with a proof, or produce the context to run `ring_exp_m` from an `expr`. -/ open tactic open ex_type /-- Compute a normalized form (of type `ex`) from an expression (of type `expr`). This is the main driver of the `ring_exp` tactic, calling out to `add`, `mul`, `pow`, etc. to parse the `expr`. -/ meta def eval : expr → ring_exp_m (ex sum) | e@`(%%ps + %%qs) := do ps' ← eval ps, qs' ← eval qs, add ps' qs' | e@`(%%ps - %%qs) := (do ctx ← get_context, ri ← match ctx.info_b.ring_instance with | none := lift $ fail "subtraction is not directly supported in a semiring" | (some ri) := pure ri end, ps' ← eval ps, qs' ← eval qs >>= negate, psqs ← add ps' qs', psqs_pf ← psqs.proof_term, pf ← mk_app_class ``sub_pf ri [ps, qs, psqs.pretty, psqs_pf], pure (psqs.set_info e pf)) <|> eval_base e | e@`(- %%ps) := do ps' ← eval ps, negate ps' <|> eval_base e | e@`(%%ps * %%qs) := do ps' ← eval ps, qs' ← eval qs, mul ps' qs' | e@`(has_inv.inv %%ps) := do ps' ← eval ps, inverse ps' <|> eval_base e | e@`(%%ps / %%qs) := do ctx ← get_context, dri ← match ctx.info_b.dr_instance with | none := lift $ fail "division is only directly supported in a division ring" | (some dri) := pure dri end, ps' ← eval ps, qs' ← eval qs, (do qs'' ← inverse qs', psqs ← mul ps' qs'', psqs_pf ← psqs.proof_term, pf ← mk_app_class ``div_pf dri [ps, qs, psqs.pretty, psqs_pf], pure (psqs.set_info e pf)) <|> eval_base e | e@`(@has_pow.pow _ _ %%hp_instance %%ps %%qs) := do ps' ← eval ps, qs' ← in_exponent $ eval qs, psqs ← pow ps' qs', psqs_pf ← psqs.proof_term, (do has_pow_pf ← match hp_instance with | `(monoid.has_pow) := lift $ mk_eq_refl e | `(nat.has_pow) := lift $ mk_app ``nat.pow_eq_pow [ps, qs] >>= mk_eq_symm | _ := lift $ fail "has_pow instance must be nat.has_pow or monoid.has_pow" end, pf ← lift $ mk_eq_trans has_pow_pf psqs_pf, pure $ psqs.set_info e pf) <|> eval_base e | ps := eval_base ps /-- Run `eval` on the expression and return the result together with normalization proof. See also `eval_simple` if you want something that behaves like `norm_num`. -/ meta def eval_with_proof (e : expr) : ring_exp_m (ex sum × expr) := do e' ← eval e, prod.mk e' <$> e'.proof_term /-- Run `eval` on the expression and simplify the result. Returns a simplified normalized expression, together with an equality proof. See also `eval_with_proof` if you just want to check the equality of two expressions. -/ meta def eval_simple (e : expr) : ring_exp_m (expr × expr) := do (complicated, complicated_pf) ← eval_with_proof e, (simple, simple_pf) ← complicated.simple, prod.mk simple <$> lift (mk_eq_trans complicated_pf simple_pf) /-- Compute the `eval_info` for a given type `α`. -/ meta def make_eval_info (α : expr) : tactic eval_info := do u ← mk_meta_univ, infer_type α >>= unify (expr.sort (level.succ u)), u ← get_univ_assignment u, csr_instance ← mk_app ``comm_semiring [α] >>= mk_instance, ring_instance ← (some <$> (mk_app ``ring [α] >>= mk_instance) <|> pure none), dr_instance ← (some <$> (mk_app ``division_ring [α] >>= mk_instance) <|> pure none), ha_instance ← mk_app ``has_add [α] >>= mk_instance, hm_instance ← mk_app ``has_mul [α] >>= mk_instance, hp_instance ← mk_mapp ``monoid.has_pow [some α, none], z ← mk_mapp ``has_zero.zero [α, none], o ← mk_mapp ``has_one.one [α, none], pure ⟨α, u, csr_instance, ha_instance, hm_instance, hp_instance, ring_instance, dr_instance, z, o⟩ /-- Use `e` to build the context for running `mx`. -/ meta def run_ring_exp {α} (transp : transparency) (e : expr) (mx : ring_exp_m α) : tactic α := do info_b ← infer_type e >>= make_eval_info, info_e ← mk_const ``nat >>= make_eval_info, (λ x : (_ × _), x.1) <$> (state_t.run (reader_t.run mx ⟨info_b, info_e, transp⟩) []) /-- Repeatedly apply `eval_simple` on (sub)expressions. -/ meta def normalize (transp : transparency) (e : expr) : tactic (expr × expr) := do (_, e', pf') ← ext_simplify_core () {} simp_lemmas.mk (λ _, failed) (λ _ _ _ _ e, do (e'', pf) ← run_ring_exp transp e $ eval_simple e, guard (¬ e'' =ₐ e), return ((), e'', some pf, ff)) (λ _ _ _ _ _, failed) `eq e, pure (e', pf') end wiring end tactic.ring_exp namespace tactic.interactive open interactive interactive.types lean.parser tactic tactic.ring_exp local postfix `?`:9001 := optional /-- Tactic for solving equations of *commutative* (semi)rings, allowing variables in the exponent. This version of `ring_exp` fails if the target is not an equality. The variant `ring_exp_eq!` will use a more aggressive reducibility setting to determine equality of atoms. -/ meta def ring_exp_eq (red : parse (tk "!")?) : tactic unit := do `(eq %%ps %%qs) ← target >>= whnf, let transp := if red.is_some then semireducible else reducible, ((ps', ps_pf), (qs', qs_pf)) ← run_ring_exp transp ps $ prod.mk <$> eval_with_proof ps <*> eval_with_proof qs, if ps'.eq qs' then do qs_pf_inv ← mk_eq_symm qs_pf, pf ← mk_eq_trans ps_pf qs_pf_inv, tactic.interactive.exact ``(%%pf) else fail "ring_exp failed to prove equality" /-- Tactic for evaluating expressions in *commutative* (semi)rings, allowing for variables in the exponent. This tactic extends `ring`: it should solve every goal that `ring` can solve. Additionally, it knows how to evaluate expressions with complicated exponents (where `ring` only understands constant exponents). The variants `ring_exp!` and `ring_exp_eq!` use a more aggessive reducibility setting to determine equality of atoms. For example: ```lean example (n : ℕ) (m : ℤ) : 2^(n+1) * m = 2 * 2^n * m := by ring_exp example (a b : ℤ) (n : ℕ) : (a + b)^(n + 2) = (a^2 + b^2 + a * b + b * a) * (a + b)^n := by ring_exp example (x y : ℕ) : x + id y = y + id x := by ring_exp! ``` -/ meta def ring_exp (red : parse (tk "!")?) (loc : parse location) : tactic unit := match loc with | interactive.loc.ns [none] := ring_exp_eq red | _ := failed end <|> do ns ← loc.get_locals, let transp := if red.is_some then semireducible else reducible, tt ← tactic.replace_at (normalize transp) ns loc.include_goal | fail "ring_exp failed to simplify", when loc.include_goal $ try tactic.reflexivity add_tactic_doc { name := "ring_exp", category := doc_category.tactic, decl_names := [`tactic.interactive.ring_exp], tags := ["arithmetic", "simplification", "decision procedure"] } end tactic.interactive namespace conv.interactive open conv interactive open tactic tactic.interactive (ring_exp_eq) open tactic.ring_exp (normalize) local postfix `?`:9001 := optional /-- Normalises expressions in commutative (semi-)rings inside of a `conv` block using the tactic `ring_exp`. -/ meta def ring_exp (red : parse (lean.parser.tk "!")?) : conv unit := let transp := if red.is_some then semireducible else reducible in discharge_eq_lhs (ring_exp_eq red) <|> replace_lhs (normalize transp) <|> fail "ring_exp failed to simplify" end conv.interactive
aa7a922c0384bf1c0958d6e2fba1a8d82650159f
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/03_Propositions_and_Proofs.org.36.lean
454eaef2702e7fae6fc02349272e499194435ff9
[]
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
250
lean
/- page 44 -/ import standard open classical variables p q : Prop -- BEGIN example (H : ¬ (p ∧ q)) : ¬ p ∨ ¬ q := or.elim (em p) (assume Hp : p, or.inr (show ¬q, from assume Hq : q, H (and.intro Hp Hq))) (assume Hp : ¬p, or.inl Hp) -- END
652dc949e37e4d5fefab390bf2f7aa2e68eb2910
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/linear_algebra/tensor_product.lean
c7ceca676048e63467db59af31e0c0936b73d624
[ "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
40,645
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Mario Carneiro -/ import group_theory.congruence import linear_algebra.basic /-! # Tensor product of modules over commutative semirings. This file constructs the tensor product of modules over commutative semirings. Given a semiring `R` and modules over it `M` and `N`, the standard construction of the tensor product is `tensor_product R M N`. It is also a module over `R`. It comes with a canonical bilinear map `M → N → tensor_product R M N`. Given any bilinear map `M → N → P`, there is a unique linear map `tensor_product R M N → P` whose composition with the canonical bilinear map `M → N → tensor_product R M N` is the given bilinear map `M → N → P`. We start by proving basic lemmas about bilinear maps. ## Notations This file uses the localized notation `M ⊗ N` and `M ⊗[R] N` for `tensor_product R M N`, as well as `m ⊗ₜ n` and `m ⊗ₜ[R] n` for `tensor_product.tmul R m n`. ## Tags bilinear, tensor, tensor product -/ namespace linear_map section semiring variables {R : Type*} [semiring R] {S : Type*} [semiring S] variables {M : Type*} {N : Type*} {P : Type*} variables {M' : Type*} {N' : Type*} {P' : Type*} variables [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] variables [add_comm_group M'] [add_comm_group N'] [add_comm_group P'] variables [module R M] [module S N] [module R P] [module S P] variables [module R M'] [module S N'] [module R P'] [module S P'] variables [smul_comm_class S R P] [smul_comm_class S R P'] include R variables (R S) /-- Create a bilinear map from a function that is linear in each component. See `mk₂` for the special case where both arguments come from modules over the same ring. -/ def mk₂' (f : M → N → P) (H1 : ∀ m₁ m₂ n, f (m₁ + m₂) n = f m₁ n + f m₂ n) (H2 : ∀ (c:R) m n, f (c • m) n = c • f m n) (H3 : ∀ m n₁ n₂, f m (n₁ + n₂) = f m n₁ + f m n₂) (H4 : ∀ (c:S) m n, f m (c • n) = c • f m n) : M →ₗ[R] N →ₗ[S] P := ⟨λ m, ⟨f m, H3 m, λ c, H4 c m⟩, λ m₁ m₂, linear_map.ext $ H1 m₁ m₂, λ c m, linear_map.ext $ H2 c m⟩ variables {R S} @[simp] theorem mk₂'_apply (f : M → N → P) {H1 H2 H3 H4} (m : M) (n : N) : (mk₂' R S f H1 H2 H3 H4 : M →ₗ[R] N →ₗ[S] P) m n = f m n := rfl theorem ext₂ {f g : M →ₗ[R] N →ₗ[S] P} (H : ∀ m n, f m n = g m n) : f = g := linear_map.ext (λ m, linear_map.ext $ λ n, H m n) section local attribute [instance] smul_comm_class.symm /-- Given a linear map from `M` to linear maps from `N` to `P`, i.e., a bilinear map from `M × N` to `P`, change the order of variables and get a linear map from `N` to linear maps from `M` to `P`. -/ def flip (f : M →ₗ[R] N →ₗ[S] P) : N →ₗ[S] M →ₗ[R] P := mk₂' S R (λ n m, f m n) (λ n₁ n₂ m, (f m).map_add _ _) (λ c n m, (f m).map_smul _ _) (λ n m₁ m₂, by rw f.map_add; refl) (λ c n m, by rw f.map_smul; refl) end @[simp] theorem flip_apply (f : M →ₗ[R] N →ₗ[S] P) (m : M) (n : N) : flip f n m = f m n := rfl open_locale big_operators variables {R} theorem flip_inj {f g : M →ₗ[R] N →ₗ[S] P} (H : flip f = flip g) : f = g := ext₂ $ λ m n, show flip f n m = flip g n m, by rw H theorem map_zero₂ (f : M →ₗ[R] N →ₗ[S] P) (y) : f 0 y = 0 := (flip f y).map_zero theorem map_neg₂ (f : M' →ₗ[R] N →ₗ[S] P') (x y) : f (-x) y = -f x y := (flip f y).map_neg _ theorem map_sub₂ (f : M' →ₗ[R] N →ₗ[S] P') (x y z) : f (x - y) z = f x z - f y z := (flip f z).map_sub _ _ theorem map_add₂ (f : M →ₗ[R] N →ₗ[S] P) (x₁ x₂ y) : f (x₁ + x₂) y = f x₁ y + f x₂ y := (flip f y).map_add _ _ theorem map_smul₂ (f : M →ₗ[R] N →ₗ[S] P) (r : R) (x y) : f (r • x) y = r • f x y := (flip f y).map_smul _ _ theorem map_sum₂ {ι : Type*} (f : M →ₗ[R] N →ₗ[S] P) (t : finset ι) (x : ι → M) (y) : f (∑ i in t, x i) y = ∑ i in t, f (x i) y := (flip f y).map_sum end semiring section comm_semiring variables {R : Type*} [comm_semiring R] variables {M : Type*} {N : Type*} {P : Type*} {Q : Type*} variables [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [add_comm_monoid Q] variables [module R M] [module R N] [module R P] [module R Q] variables (R) /-- Create a bilinear map from a function that is linear in each component. This is a shorthand for `mk₂'` for the common case when `R = S`. -/ def mk₂ (f : M → N → P) (H1 : ∀ m₁ m₂ n, f (m₁ + m₂) n = f m₁ n + f m₂ n) (H2 : ∀ (c:R) m n, f (c • m) n = c • f m n) (H3 : ∀ m n₁ n₂, f m (n₁ + n₂) = f m n₁ + f m n₂) (H4 : ∀ (c:R) m n, f m (c • n) = c • f m n) : M →ₗ[R] N →ₗ[R] P := mk₂' R R f H1 H2 H3 H4 @[simp] theorem mk₂_apply (f : M → N → P) {H1 H2 H3 H4} (m : M) (n : N) : (mk₂ R f H1 H2 H3 H4 : M →ₗ[R] N →ₗ[R] P) m n = f m n := rfl variables (R M N P) /-- Given a linear map from `M` to linear maps from `N` to `P`, i.e., a bilinear map `M → N → P`, change the order of variables and get a linear map from `N` to linear maps from `M` to `P`. -/ def lflip : (M →ₗ[R] N →ₗ[R] P) →ₗ[R] N →ₗ[R] M →ₗ[R] P := ⟨flip, λ _ _, rfl, λ _ _, rfl⟩ variables {R M N P} variables (f : M →ₗ[R] N →ₗ[R] P) @[simp] theorem lflip_apply (m : M) (n : N) : lflip R M N P f n m = f m n := rfl variables (R P) /-- Composing a linear map `M → N` and a linear map `N → P` to form a linear map `M → P`. -/ def lcomp (f : M →ₗ[R] N) : (N →ₗ[R] P) →ₗ[R] M →ₗ[R] P := flip $ linear_map.comp (flip id) f variables {R P} @[simp] theorem lcomp_apply (f : M →ₗ[R] N) (g : N →ₗ P) (x : M) : lcomp R P f g x = g (f x) := rfl variables (R M N P) /-- Composing a linear map `M → N` and a linear map `N → P` to form a linear map `M → P`. -/ def llcomp : (N →ₗ[R] P) →ₗ[R] (M →ₗ[R] N) →ₗ M →ₗ P := flip ⟨lcomp R P, λ f f', ext₂ $ λ g x, g.map_add _ _, λ (c : R) f, ext₂ $ λ g x, g.map_smul _ _⟩ variables {R M N P} section @[simp] theorem llcomp_apply (f : N →ₗ[R] P) (g : M →ₗ[R] N) (x : M) : llcomp R M N P f g x = f (g x) := rfl end /-- Composing a linear map `Q → N` and a bilinear map `M → N → P` to form a bilinear map `M → Q → P`. -/ def compl₂ (g : Q →ₗ N) : M →ₗ Q →ₗ P := (lcomp R _ g).comp f @[simp] theorem compl₂_apply (g : Q →ₗ[R] N) (m : M) (q : Q) : f.compl₂ g m q = f m (g q) := rfl /-- Composing a linear map `P → Q` and a bilinear map `M × N → P` to form a bilinear map `M → N → Q`. -/ def compr₂ (g : P →ₗ Q) : M →ₗ N →ₗ Q := linear_map.comp (llcomp R N P Q g) f @[simp] theorem compr₂_apply (g : P →ₗ[R] Q) (m : M) (n : N) : f.compr₂ g m n = g (f m n) := rfl variables (R M) /-- Scalar multiplication as a bilinear map `R → M → M`. -/ def lsmul : R →ₗ M →ₗ M := mk₂ R (•) add_smul (λ _ _ _, mul_smul _ _ _) smul_add (λ r s m, by simp only [smul_smul, smul_eq_mul, mul_comm]) variables {R M} @[simp] theorem lsmul_apply (r : R) (m : M) : lsmul R M r m = r • m := rfl end comm_semiring section comm_ring variables {R M : Type*} [comm_ring R] [add_comm_group M] [module R M] lemma lsmul_injective [no_zero_smul_divisors R M] {x : R} (hx : x ≠ 0) : function.injective (lsmul R M x) := smul_left_injective _ hx lemma ker_lsmul [no_zero_smul_divisors R M] {a : R} (ha : a ≠ 0) : (linear_map.lsmul R M a).ker = ⊥ := linear_map.ker_eq_bot_of_injective (linear_map.lsmul_injective ha) end comm_ring end linear_map section semiring variables {R : Type*} [comm_semiring R] variables {R' : Type*} [monoid R'] variables {R'' : Type*} [semiring R''] variables {M : Type*} {N : Type*} {P : Type*} {Q : Type*} {S : Type*} variables [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [add_comm_monoid Q] [add_comm_monoid S] variables [module R M] [module R N] [module R P] [module R Q] [module R S] variables [distrib_mul_action R' M] [distrib_mul_action R' N] variables [module R'' M] [module R'' N] include R variables (M N) namespace tensor_product section -- open free_add_monoid variables (R) /-- The relation on `free_add_monoid (M × N)` that generates a congruence whose quotient is the tensor product. -/ inductive eqv : free_add_monoid (M × N) → free_add_monoid (M × N) → Prop | of_zero_left : ∀ n : N, eqv (free_add_monoid.of (0, n)) 0 | of_zero_right : ∀ m : M, eqv (free_add_monoid.of (m, 0)) 0 | of_add_left : ∀ (m₁ m₂ : M) (n : N), eqv (free_add_monoid.of (m₁, n) + free_add_monoid.of (m₂, n)) (free_add_monoid.of (m₁ + m₂, n)) | of_add_right : ∀ (m : M) (n₁ n₂ : N), eqv (free_add_monoid.of (m, n₁) + free_add_monoid.of (m, n₂)) (free_add_monoid.of (m, n₁ + n₂)) | of_smul : ∀ (r : R) (m : M) (n : N), eqv (free_add_monoid.of (r • m, n)) (free_add_monoid.of (m, r • n)) | add_comm : ∀ x y, eqv (x + y) (y + x) end end tensor_product variables (R) /-- The tensor product of two modules `M` and `N` over the same commutative semiring `R`. The localized notations are `M ⊗ N` and `M ⊗[R] N`, accessed by `open_locale tensor_product`. -/ def tensor_product : Type* := (add_con_gen (tensor_product.eqv R M N)).quotient variables {R} localized "infix ` ⊗ `:100 := tensor_product _" in tensor_product localized "notation M ` ⊗[`:100 R `] `:0 N:100 := tensor_product R M N" in tensor_product namespace tensor_product section module instance : add_zero_class (M ⊗[R] N) := { .. (add_con_gen (tensor_product.eqv R M N)).add_monoid } instance : add_comm_semigroup (M ⊗[R] N) := { add_comm := λ x y, add_con.induction_on₂ x y $ λ x y, quotient.sound' $ add_con_gen.rel.of _ _ $ eqv.add_comm _ _, .. (add_con_gen (tensor_product.eqv R M N)).add_monoid } instance : inhabited (M ⊗[R] N) := ⟨0⟩ variables (R) {M N} /-- The canonical function `M → N → M ⊗ N`. The localized notations are `m ⊗ₜ n` and `m ⊗ₜ[R] n`, accessed by `open_locale tensor_product`. -/ def tmul (m : M) (n : N) : M ⊗[R] N := add_con.mk' _ $ free_add_monoid.of (m, n) variables {R} infix ` ⊗ₜ `:100 := tmul _ notation x ` ⊗ₜ[`:100 R `] `:0 y:100 := tmul R x y @[elab_as_eliminator] protected theorem induction_on {C : (M ⊗[R] N) → Prop} (z : M ⊗[R] N) (C0 : C 0) (C1 : ∀ {x y}, C $ x ⊗ₜ[R] y) (Cp : ∀ {x y}, C x → C y → C (x + y)) : C z := add_con.induction_on z $ λ x, free_add_monoid.rec_on x C0 $ λ ⟨m, n⟩ y ih, by { rw add_con.coe_add, exact Cp C1 ih } variables (M) @[simp] lemma zero_tmul (n : N) : (0 : M) ⊗ₜ[R] n = 0 := quotient.sound' $ add_con_gen.rel.of _ _ $ eqv.of_zero_left _ variables {M} lemma add_tmul (m₁ m₂ : M) (n : N) : (m₁ + m₂) ⊗ₜ n = m₁ ⊗ₜ n + m₂ ⊗ₜ[R] n := eq.symm $ quotient.sound' $ add_con_gen.rel.of _ _ $ eqv.of_add_left _ _ _ variables (N) @[simp] lemma tmul_zero (m : M) : m ⊗ₜ[R] (0 : N) = 0 := quotient.sound' $ add_con_gen.rel.of _ _ $ eqv.of_zero_right _ variables {N} lemma tmul_add (m : M) (n₁ n₂ : N) : m ⊗ₜ (n₁ + n₂) = m ⊗ₜ n₁ + m ⊗ₜ[R] n₂ := eq.symm $ quotient.sound' $ add_con_gen.rel.of _ _ $ eqv.of_add_right _ _ _ section variables (R R' M N) /-- A typeclass for `has_scalar` structures which can be moved across a tensor product. This typeclass is generated automatically from a `is_scalar_tower` instance, but exists so that we can also add an instance for `add_comm_group.int_module`, allowing `z •` to be moved even if `R` does not support negation. Note that `module R' (M ⊗[R] N)` is available even without this typeclass on `R'`; it's only needed if `tensor_product.smul_tmul`, `tensor_product.smul_tmul'`, or `tensor_product.tmul_smul` is used. -/ class compatible_smul := (smul_tmul : ∀ (r : R') (m : M) (n : N), (r • m) ⊗ₜ n = m ⊗ₜ[R] (r • n)) end /-- Note that this provides the default `compatible_smul R R M N` instance through `mul_action.is_scalar_tower.left`. -/ @[priority 100] instance compatible_smul.is_scalar_tower [has_scalar R' R] [is_scalar_tower R' R M] [is_scalar_tower R' R N] : compatible_smul R R' M N := ⟨λ r m n, begin conv_lhs {rw ← one_smul R m}, conv_rhs {rw ← one_smul R n}, rw [←smul_assoc, ←smul_assoc], exact (quotient.sound' $ add_con_gen.rel.of _ _ $ eqv.of_smul _ _ _), end⟩ /-- `smul` can be moved from one side of the product to the other .-/ lemma smul_tmul [compatible_smul R R' M N] (r : R') (m : M) (n : N) : (r • m) ⊗ₜ n = m ⊗ₜ[R] (r • n) := compatible_smul.smul_tmul _ _ _ /-- Auxiliary function to defining scalar multiplication on tensor product. -/ def smul.aux {R' : Type*} [has_scalar R' M] (r : R') : free_add_monoid (M × N) →+ M ⊗[R] N := free_add_monoid.lift $ λ p : M × N, (r • p.1) ⊗ₜ p.2 theorem smul.aux_of {R' : Type*} [has_scalar R' M] (r : R') (m : M) (n : N) : smul.aux r (free_add_monoid.of (m, n)) = (r • m) ⊗ₜ[R] n := rfl variables [smul_comm_class R R' M] [smul_comm_class R R' N] variables [smul_comm_class R R'' M] [smul_comm_class R R'' N] -- Most of the time we want the instance below this one, which is easier for typeclass resolution -- to find. The `unused_arguments` is from one of the two comm_classes - while we only make use -- of one, it makes sense to make the API symmetric. @[nolint unused_arguments] instance has_scalar' : has_scalar R' (M ⊗[R] N) := ⟨λ r, (add_con_gen (tensor_product.eqv R M N)).lift (smul.aux r : _ →+ M ⊗[R] N) $ add_con.add_con_gen_le $ λ x y hxy, match x, y, hxy with | _, _, (eqv.of_zero_left n) := (add_con.ker_rel _).2 $ by simp_rw [add_monoid_hom.map_zero, smul.aux_of, smul_zero, zero_tmul] | _, _, (eqv.of_zero_right m) := (add_con.ker_rel _).2 $ by simp_rw [add_monoid_hom.map_zero, smul.aux_of, tmul_zero] | _, _, (eqv.of_add_left m₁ m₂ n) := (add_con.ker_rel _).2 $ by simp_rw [add_monoid_hom.map_add, smul.aux_of, smul_add, add_tmul] | _, _, (eqv.of_add_right m n₁ n₂) := (add_con.ker_rel _).2 $ by simp_rw [add_monoid_hom.map_add, smul.aux_of, tmul_add] | _, _, (eqv.of_smul s m n) := (add_con.ker_rel _).2 $ by rw [smul.aux_of, smul.aux_of, ←smul_comm, smul_tmul] | _, _, (eqv.add_comm x y) := (add_con.ker_rel _).2 $ by simp_rw [add_monoid_hom.map_add, add_comm] end⟩ instance : has_scalar R (M ⊗[R] N) := tensor_product.has_scalar' protected theorem smul_zero (r : R') : (r • 0 : M ⊗[R] N) = 0 := add_monoid_hom.map_zero _ protected theorem smul_add (r : R') (x y : M ⊗[R] N) : r • (x + y) = r • x + r • y := add_monoid_hom.map_add _ _ _ protected theorem zero_smul (x : M ⊗[R] N) : (0 : R'') • x = 0 := have ∀ (r : R'') (m : M) (n : N), r • (m ⊗ₜ[R] n) = (r • m) ⊗ₜ n := λ _ _ _, rfl, tensor_product.induction_on x (by rw tensor_product.smul_zero) (λ m n, by rw [this, zero_smul, zero_tmul]) (λ x y ihx ihy, by rw [tensor_product.smul_add, ihx, ihy, add_zero]) protected theorem one_smul (x : M ⊗[R] N) : (1 : R') • x = x := have ∀ (r : R') (m : M) (n : N), r • (m ⊗ₜ[R] n) = (r • m) ⊗ₜ n := λ _ _ _, rfl, tensor_product.induction_on x (by rw tensor_product.smul_zero) (λ m n, by rw [this, one_smul]) (λ x y ihx ihy, by rw [tensor_product.smul_add, ihx, ihy]) protected theorem add_smul (r s : R'') (x : M ⊗[R] N) : (r + s) • x = r • x + s • x := have ∀ (r : R'') (m : M) (n : N), r • (m ⊗ₜ[R] n) = (r • m) ⊗ₜ n := λ _ _ _, rfl, tensor_product.induction_on x (by simp_rw [tensor_product.smul_zero, add_zero]) (λ m n, by simp_rw [this, add_smul, add_tmul]) (λ x y ihx ihy, by { simp_rw tensor_product.smul_add, rw [ihx, ihy, add_add_add_comm] }) instance : add_comm_monoid (M ⊗[R] N) := { nsmul := λ n v, n • v, nsmul_zero' := by simp [tensor_product.zero_smul], nsmul_succ' := by simp [nat.succ_eq_one_add, tensor_product.one_smul, tensor_product.add_smul], .. tensor_product.add_comm_semigroup _ _, .. tensor_product.add_zero_class _ _} -- Most of the time we want the instance below this one, which is easier for typeclass resolution -- to find. instance distrib_mul_action' : distrib_mul_action R' (M ⊗[R] N) := have ∀ (r : R') (m : M) (n : N), r • (m ⊗ₜ[R] n) = (r • m) ⊗ₜ n := λ _ _ _, rfl, { smul := (•), smul_add := λ r x y, tensor_product.smul_add r x y, mul_smul := λ r s x, tensor_product.induction_on x (by simp_rw tensor_product.smul_zero) (λ m n, by simp_rw [this, mul_smul]) (λ x y ihx ihy, by { simp_rw tensor_product.smul_add, rw [ihx, ihy] }), one_smul := tensor_product.one_smul, smul_zero := tensor_product.smul_zero } instance : distrib_mul_action R (M ⊗[R] N) := tensor_product.distrib_mul_action' -- note that we don't actually need `compatible_smul` here, but we include it for symmetry -- with `tmul_smul` to avoid exposing our asymmetric definition. @[nolint unused_arguments] theorem smul_tmul' [compatible_smul R R' M N] (r : R') (m : M) (n : N) : r • (m ⊗ₜ[R] n) = (r • m) ⊗ₜ n := rfl @[simp] lemma tmul_smul [compatible_smul R R' M N] (r : R') (x : M) (y : N) : x ⊗ₜ (r • y) = r • (x ⊗ₜ[R] y) := (smul_tmul _ _ _).symm -- Most of the time we want the instance below this one, which is easier for typeclass resolution -- to find. instance module' : module R'' (M ⊗[R] N) := { smul := (•), add_smul := tensor_product.add_smul, zero_smul := tensor_product.zero_smul, ..tensor_product.distrib_mul_action' } instance : module R (M ⊗[R] N) := tensor_product.module' variables (R M N) /-- The canonical bilinear map `M → N → M ⊗[R] N`. -/ def mk : M →ₗ N →ₗ M ⊗[R] N := linear_map.mk₂ R (⊗ₜ) add_tmul (λ c m n, by rw [smul_tmul, tmul_smul]) tmul_add tmul_smul variables {R M N} @[simp] lemma mk_apply (m : M) (n : N) : mk R M N m n = m ⊗ₜ n := rfl lemma ite_tmul (x₁ : M) (x₂ : N) (P : Prop) [decidable P] : (if P then x₁ else 0) ⊗ₜ[R] x₂ = if P then x₁ ⊗ₜ x₂ else 0 := by { split_ifs; simp } lemma tmul_ite (x₁ : M) (x₂ : N) (P : Prop) [decidable P] : x₁ ⊗ₜ[R] (if P then x₂ else 0) = if P then x₁ ⊗ₜ x₂ else 0 := by { split_ifs; simp } section open_locale big_operators lemma sum_tmul {α : Type*} (s : finset α) (m : α → M) (n : N) : (∑ a in s, m a) ⊗ₜ[R] n = ∑ a in s, m a ⊗ₜ[R] n := begin classical, induction s using finset.induction with a s has ih h, { simp, }, { simp [finset.sum_insert has, add_tmul, ih], }, end lemma tmul_sum (m : M) {α : Type*} (s : finset α) (n : α → N) : m ⊗ₜ[R] (∑ a in s, n a) = ∑ a in s, m ⊗ₜ[R] n a := begin classical, induction s using finset.induction with a s has ih h, { simp, }, { simp [finset.sum_insert has, tmul_add, ih], }, end end variables (R M N) /-- The simple (aka pure) elements span the tensor product. -/ lemma span_tmul_eq_top : submodule.span R { t : M ⊗[R] N | ∃ m n, m ⊗ₜ n = t } = ⊤ := begin ext t, simp only [submodule.mem_top, iff_true], apply t.induction_on, { exact submodule.zero_mem _, }, { intros m n, apply submodule.subset_span, use [m, n], }, { intros t₁ t₂ ht₁ ht₂, exact submodule.add_mem _ ht₁ ht₂, }, end end module section UMP variables {M N P Q} variables (f : M →ₗ[R] N →ₗ[R] P) /-- Auxiliary function to constructing a linear map `M ⊗ N → P` given a bilinear map `M → N → P` with the property that its composition with the canonical bilinear map `M → N → M ⊗ N` is the given bilinear map `M → N → P`. -/ def lift_aux : (M ⊗[R] N) →+ P := (add_con_gen (tensor_product.eqv R M N)).lift (free_add_monoid.lift $ λ p : M × N, f p.1 p.2) $ add_con.add_con_gen_le $ λ x y hxy, match x, y, hxy with | _, _, (eqv.of_zero_left n) := (add_con.ker_rel _).2 $ by simp_rw [add_monoid_hom.map_zero, free_add_monoid.lift_eval_of, f.map_zero₂] | _, _, (eqv.of_zero_right m) := (add_con.ker_rel _).2 $ by simp_rw [add_monoid_hom.map_zero, free_add_monoid.lift_eval_of, (f m).map_zero] | _, _, (eqv.of_add_left m₁ m₂ n) := (add_con.ker_rel _).2 $ by simp_rw [add_monoid_hom.map_add, free_add_monoid.lift_eval_of, f.map_add₂] | _, _, (eqv.of_add_right m n₁ n₂) := (add_con.ker_rel _).2 $ by simp_rw [add_monoid_hom.map_add, free_add_monoid.lift_eval_of, (f m).map_add] | _, _, (eqv.of_smul r m n) := (add_con.ker_rel _).2 $ by simp_rw [free_add_monoid.lift_eval_of, f.map_smul₂, (f m).map_smul] | _, _, (eqv.add_comm x y) := (add_con.ker_rel _).2 $ by simp_rw [add_monoid_hom.map_add, add_comm] end lemma lift_aux_tmul (m n) : lift_aux f (m ⊗ₜ n) = f m n := zero_add _ variable {f} @[simp] lemma lift_aux.smul (r : R) (x) : lift_aux f (r • x) = r • lift_aux f x := tensor_product.induction_on x (smul_zero _).symm (λ p q, by rw [← tmul_smul, lift_aux_tmul, lift_aux_tmul, (f p).map_smul]) (λ p q ih1 ih2, by rw [smul_add, (lift_aux f).map_add, ih1, ih2, (lift_aux f).map_add, smul_add]) variable (f) /-- Constructing a linear map `M ⊗ N → P` given a bilinear map `M → N → P` with the property that its composition with the canonical bilinear map `M → N → M ⊗ N` is the given bilinear map `M → N → P`. -/ def lift : M ⊗ N →ₗ P := { map_smul' := lift_aux.smul, .. lift_aux f } variable {f} @[simp] lemma lift.tmul (x y) : lift f (x ⊗ₜ y) = f x y := zero_add _ @[simp] lemma lift.tmul' (x y) : (lift f).1 (x ⊗ₜ y) = f x y := lift.tmul _ _ theorem ext {g h : (M ⊗[R] N) →ₗ[R] P} (H : ∀ x y, g (x ⊗ₜ y) = h (x ⊗ₜ y)) : g = h := linear_map.ext $ λ z, tensor_product.induction_on z (by simp_rw linear_map.map_zero) H $ λ x y ihx ihy, by rw [g.map_add, h.map_add, ihx, ihy] theorem lift.unique {g : (M ⊗[R] N) →ₗ[R] P} (H : ∀ x y, g (x ⊗ₜ y) = f x y) : g = lift f := ext $ λ m n, by rw [H, lift.tmul] theorem lift_mk : lift (mk R M N) = linear_map.id := eq.symm $ lift.unique $ λ x y, rfl theorem lift_compr₂ (g : P →ₗ Q) : lift (f.compr₂ g) = g.comp (lift f) := eq.symm $ lift.unique $ λ x y, by simp theorem lift_mk_compr₂ (f : M ⊗ N →ₗ P) : lift ((mk R M N).compr₂ f) = f := by rw [lift_compr₂ f, lift_mk, linear_map.comp_id] /-- Using this as the `@[ext]` lemma instead of `tensor_product.ext` allows `ext` to apply lemmas specific to `M →ₗ _` and `N →ₗ _`. See note [partially-applied ext lemmas]. -/ @[ext] theorem mk_compr₂_inj {g h : M ⊗ N →ₗ P} (H : (mk R M N).compr₂ g = (mk R M N).compr₂ h) : g = h := by rw [← lift_mk_compr₂ g, H, lift_mk_compr₂] example : M → N → (M → N → P) → P := λ m, flip $ λ f, f m variables (R M N P) /-- Linearly constructing a linear map `M ⊗ N → P` given a bilinear map `M → N → P` with the property that its composition with the canonical bilinear map `M → N → M ⊗ N` is the given bilinear map `M → N → P`. -/ def uncurry : (M →ₗ[R] N →ₗ[R] P) →ₗ[R] M ⊗[R] N →ₗ[R] P := linear_map.flip $ lift $ (linear_map.lflip _ _ _ _).comp (linear_map.flip linear_map.id) variables {R M N P} @[simp] theorem uncurry_apply (f : M →ₗ[R] N →ₗ[R] P) (m : M) (n : N) : uncurry R M N P f (m ⊗ₜ n) = f m n := by rw [uncurry, linear_map.flip_apply, lift.tmul]; refl variables (R M N P) /-- A linear equivalence constructing a linear map `M ⊗ N → P` given a bilinear map `M → N → P` with the property that its composition with the canonical bilinear map `M → N → M ⊗ N` is the given bilinear map `M → N → P`. -/ def lift.equiv : (M →ₗ N →ₗ P) ≃ₗ (M ⊗ N →ₗ P) := { inv_fun := λ f, (mk R M N).compr₂ f, left_inv := λ f, linear_map.ext₂ $ λ m n, lift.tmul _ _, right_inv := λ f, ext $ λ m n, lift.tmul _ _, .. uncurry R M N P } @[simp] lemma lift.equiv_apply (f : M →ₗ[R] N →ₗ[R] P) (m : M) (n : N) : lift.equiv R M N P f (m ⊗ₜ n) = f m n := uncurry_apply f m n @[simp] lemma lift.equiv_symm_apply (f : M ⊗[R] N →ₗ[R] P) (m : M) (n : N) : (lift.equiv R M N P).symm f m n = f (m ⊗ₜ n) := rfl /-- Given a linear map `M ⊗ N → P`, compose it with the canonical bilinear map `M → N → M ⊗ N` to form a bilinear map `M → N → P`. -/ def lcurry : (M ⊗[R] N →ₗ[R] P) →ₗ[R] M →ₗ[R] N →ₗ[R] P := (lift.equiv R M N P).symm variables {R M N P} @[simp] theorem lcurry_apply (f : M ⊗[R] N →ₗ[R] P) (m : M) (n : N) : lcurry R M N P f m n = f (m ⊗ₜ n) := rfl /-- Given a linear map `M ⊗ N → P`, compose it with the canonical bilinear map `M → N → M ⊗ N` to form a bilinear map `M → N → P`. -/ def curry (f : M ⊗ N →ₗ P) : M →ₗ N →ₗ P := lcurry R M N P f @[simp] theorem curry_apply (f : M ⊗ N →ₗ[R] P) (m : M) (n : N) : curry f m n = f (m ⊗ₜ n) := rfl theorem ext_threefold {g h : (M ⊗[R] N) ⊗[R] P →ₗ[R] Q} (H : ∀ x y z, g ((x ⊗ₜ y) ⊗ₜ z) = h ((x ⊗ₜ y) ⊗ₜ z)) : g = h := begin ext x y z, exact H x y z end -- We'll need this one for checking the pentagon identity! theorem ext_fourfold {g h : ((M ⊗[R] N) ⊗[R] P) ⊗[R] Q →ₗ[R] S} (H : ∀ w x y z, g (((w ⊗ₜ x) ⊗ₜ y) ⊗ₜ z) = h (((w ⊗ₜ x) ⊗ₜ y) ⊗ₜ z)) : g = h := begin ext w x y z, exact H w x y z, end end UMP variables {M N} section variables (R M) /-- The base ring is a left identity for the tensor product of modules, up to linear equivalence. -/ protected def lid : R ⊗ M ≃ₗ M := linear_equiv.of_linear (lift $ linear_map.lsmul R M) (mk R R M 1) (linear_map.ext $ λ _, by simp) (ext $ λ r m, by simp; rw [← tmul_smul, ← smul_tmul, smul_eq_mul, mul_one]) end @[simp] theorem lid_tmul (m : M) (r : R) : ((tensor_product.lid R M) : (R ⊗ M → M)) (r ⊗ₜ m) = r • m := begin dsimp [tensor_product.lid], simp, end @[simp] lemma lid_symm_apply (m : M) : (tensor_product.lid R M).symm m = 1 ⊗ₜ m := rfl section variables (R M N) /-- The tensor product of modules is commutative, up to linear equivalence. -/ protected def comm : M ⊗ N ≃ₗ N ⊗ M := linear_equiv.of_linear (lift (mk R N M).flip) (lift (mk R M N).flip) (ext $ λ m n, rfl) (ext $ λ m n, rfl) @[simp] theorem comm_tmul (m : M) (n : N) : (tensor_product.comm R M N) (m ⊗ₜ n) = n ⊗ₜ m := rfl @[simp] theorem comm_symm_tmul (m : M) (n : N) : (tensor_product.comm R M N).symm (n ⊗ₜ m) = m ⊗ₜ n := rfl end section variables (R M) /-- The base ring is a right identity for the tensor product of modules, up to linear equivalence. -/ protected def rid : M ⊗[R] R ≃ₗ M := linear_equiv.trans (tensor_product.comm R M R) (tensor_product.lid R M) end @[simp] theorem rid_tmul (m : M) (r : R) : (tensor_product.rid R M) (m ⊗ₜ r) = r • m := begin dsimp [tensor_product.rid, tensor_product.comm, tensor_product.lid], simp, end @[simp] lemma rid_symm_apply (m : M) : (tensor_product.rid R M).symm m = m ⊗ₜ 1 := rfl open linear_map section variables (R M N P) /-- The associator for tensor product of R-modules, as a linear equivalence. -/ protected def assoc : (M ⊗[R] N) ⊗[R] P ≃ₗ[R] M ⊗[R] (N ⊗[R] P) := begin refine linear_equiv.of_linear (lift $ lift $ comp (lcurry R _ _ _) $ mk _ _ _) (lift $ comp (uncurry R _ _ _) $ curry $ mk _ _ _) (mk_compr₂_inj $ linear_map.ext $ λ m, ext $ λ n p, _) (mk_compr₂_inj $ flip_inj $ linear_map.ext $ λ p, ext $ λ m n, _); repeat { rw lift.tmul <|> rw compr₂_apply <|> rw comp_apply <|> rw mk_apply <|> rw flip_apply <|> rw lcurry_apply <|> rw uncurry_apply <|> rw curry_apply <|> rw id_apply } end end @[simp] theorem assoc_tmul (m : M) (n : N) (p : P) : (tensor_product.assoc R M N P) ((m ⊗ₜ n) ⊗ₜ p) = m ⊗ₜ (n ⊗ₜ p) := rfl @[simp] theorem assoc_symm_tmul (m : M) (n : N) (p : P) : (tensor_product.assoc R M N P).symm (m ⊗ₜ (n ⊗ₜ p)) = (m ⊗ₜ n) ⊗ₜ p := rfl /-- The tensor product of a pair of linear maps between modules. -/ def map (f : M →ₗ[R] P) (g : N →ₗ Q) : M ⊗ N →ₗ[R] P ⊗ Q := lift $ comp (compl₂ (mk _ _ _) g) f @[simp] theorem map_tmul (f : M →ₗ[R] P) (g : N →ₗ[R] Q) (m : M) (n : N) : map f g (m ⊗ₜ n) = f m ⊗ₜ g n := rfl lemma map_range_eq_span_tmul (f : M →ₗ[R] P) (g : N →ₗ[R] Q) : (map f g).range = submodule.span R { t | ∃ m n, (f m) ⊗ₜ (g n) = t } := begin simp only [← submodule.map_top, ← span_tmul_eq_top, submodule.map_span, set.mem_image, set.mem_set_of_eq], congr, ext t, split, { rintros ⟨_, ⟨⟨m, n, rfl⟩, rfl⟩⟩, use [m, n], simp only [map_tmul], }, { rintros ⟨m, n, rfl⟩, use [m ⊗ₜ n, m, n], simp only [map_tmul], }, end /-- Given submodules `p ⊆ P` and `q ⊆ Q`, this is the natural map: `p ⊗ q → P ⊗ Q`. -/ @[simp] def map_incl (p : submodule R P) (q : submodule R Q) : p ⊗[R] q →ₗ[R] P ⊗[R] Q := map p.subtype q.subtype section variables {P' Q' : Type*} variables [add_comm_monoid P'] [module R P'] variables [add_comm_monoid Q'] [module R Q'] lemma map_comp (f₂ : P →ₗ[R] P') (f₁ : M →ₗ[R] P) (g₂ : Q →ₗ[R] Q') (g₁ : N →ₗ[R] Q) : map (f₂.comp f₁) (g₂.comp g₁) = (map f₂ g₂).comp (map f₁ g₁) := ext $ λ _ _, by simp only [linear_map.comp_apply, map_tmul] lemma lift_comp_map (i : P →ₗ[R] Q →ₗ[R] Q') (f : M →ₗ[R] P) (g : N →ₗ[R] Q) : (lift i).comp (map f g) = lift ((i.comp f).compl₂ g) := ext $ λ _ _, by simp only [lift.tmul, map_tmul, linear_map.compl₂_apply, linear_map.comp_apply] @[simp] lemma map_id : map (id : M →ₗ[R] M) (id : N →ₗ[R] N) = id := by { ext, simp only [mk_apply, id_coe, compr₂_apply, id.def, map_tmul], } @[simp] lemma map_one : map (1 : M →ₗ[R] M) (1 : N →ₗ[R] N) = 1 := map_id lemma map_mul (f₁ f₂ : M →ₗ[R] M) (g₁ g₂ : N →ₗ[R] N) : map (f₁ * f₂) (g₁ * g₂) = (map f₁ g₁) * (map f₂ g₂) := map_comp f₁ f₂ g₁ g₂ @[simp] lemma map_pow (f : M →ₗ[R] M) (g : N →ₗ[R] N) (n : ℕ) : (map f g)^n = map (f^n) (g^n) := begin induction n with n ih, { simp only [pow_zero, map_one], }, { simp only [pow_succ', ih, map_mul], }, end end /-- If `M` and `P` are linearly equivalent and `N` and `Q` are linearly equivalent then `M ⊗ N` and `P ⊗ Q` are linearly equivalent. -/ def congr (f : M ≃ₗ[R] P) (g : N ≃ₗ[R] Q) : M ⊗ N ≃ₗ[R] P ⊗ Q := linear_equiv.of_linear (map f g) (map f.symm g.symm) (ext $ λ m n, by simp; simp only [linear_equiv.apply_symm_apply]) (ext $ λ m n, by simp; simp only [linear_equiv.symm_apply_apply]) @[simp] theorem congr_tmul (f : M ≃ₗ[R] P) (g : N ≃ₗ[R] Q) (m : M) (n : N) : congr f g (m ⊗ₜ n) = f m ⊗ₜ g n := rfl @[simp] theorem congr_symm_tmul (f : M ≃ₗ[R] P) (g : N ≃ₗ[R] Q) (p : P) (q : Q) : (congr f g).symm (p ⊗ₜ q) = f.symm p ⊗ₜ g.symm q := rfl end tensor_product namespace linear_map variables {R} (M) {N P Q} /-- `ltensor M f : M ⊗ N →ₗ M ⊗ P` is the natural linear map induced by `f : N →ₗ P`. -/ def ltensor (f : N →ₗ[R] P) : M ⊗ N →ₗ[R] M ⊗ P := tensor_product.map id f /-- `rtensor f M : N₁ ⊗ M →ₗ N₂ ⊗ M` is the natural linear map induced by `f : N₁ →ₗ N₂`. -/ def rtensor (f : N →ₗ[R] P) : N ⊗ M →ₗ[R] P ⊗ M := tensor_product.map f id variables (g : P →ₗ[R] Q) (f : N →ₗ[R] P) @[simp] lemma ltensor_tmul (m : M) (n : N) : f.ltensor M (m ⊗ₜ n) = m ⊗ₜ (f n) := rfl @[simp] lemma rtensor_tmul (m : M) (n : N) : f.rtensor M (n ⊗ₜ m) = (f n) ⊗ₜ m := rfl open tensor_product /-- `ltensor_hom M` is the natural linear map that sends a linear map `f : N →ₗ P` to `M ⊗ f`. -/ def ltensor_hom : (N →ₗ[R] P) →ₗ[R] (M ⊗[R] N →ₗ[R] M ⊗[R] P) := { to_fun := ltensor M, map_add' := λ f g, by { ext x y, simp only [compr₂_apply, mk_apply, add_apply, ltensor_tmul, tmul_add] }, map_smul' := λ r f, by { ext x y, simp only [compr₂_apply, mk_apply, tmul_smul, smul_apply, ltensor_tmul] } } /-- `rtensor_hom M` is the natural linear map that sends a linear map `f : N →ₗ P` to `M ⊗ f`. -/ def rtensor_hom : (N →ₗ[R] P) →ₗ[R] (N ⊗[R] M →ₗ[R] P ⊗[R] M) := { to_fun := λ f, f.rtensor M, map_add' := λ f g, by { ext x y, simp only [compr₂_apply, mk_apply, add_apply, rtensor_tmul, add_tmul] }, map_smul' := λ r f, by { ext x y, simp only [compr₂_apply, mk_apply, smul_tmul, tmul_smul, smul_apply, rtensor_tmul] } } @[simp] lemma coe_ltensor_hom : (ltensor_hom M : (N →ₗ[R] P) → (M ⊗[R] N →ₗ[R] M ⊗[R] P)) = ltensor M := rfl @[simp] lemma coe_rtensor_hom : (rtensor_hom M : (N →ₗ[R] P) → (N ⊗[R] M →ₗ[R] P ⊗[R] M)) = rtensor M := rfl @[simp] lemma ltensor_add (f g : N →ₗ[R] P) : (f + g).ltensor M = f.ltensor M + g.ltensor M := (ltensor_hom M).map_add f g @[simp] lemma rtensor_add (f g : N →ₗ[R] P) : (f + g).rtensor M = f.rtensor M + g.rtensor M := (rtensor_hom M).map_add f g @[simp] lemma ltensor_zero : ltensor M (0 : N →ₗ[R] P) = 0 := (ltensor_hom M).map_zero @[simp] lemma rtensor_zero : rtensor M (0 : N →ₗ[R] P) = 0 := (rtensor_hom M).map_zero @[simp] lemma ltensor_smul (r : R) (f : N →ₗ[R] P) : (r • f).ltensor M = r • (f.ltensor M) := (ltensor_hom M).map_smul r f @[simp] lemma rtensor_smul (r : R) (f : N →ₗ[R] P) : (r • f).rtensor M = r • (f.rtensor M) := (rtensor_hom M).map_smul r f lemma ltensor_comp : (g.comp f).ltensor M = (g.ltensor M).comp (f.ltensor M) := by { ext m n, simp only [compr₂_apply, mk_apply, comp_apply, ltensor_tmul] } lemma rtensor_comp : (g.comp f).rtensor M = (g.rtensor M).comp (f.rtensor M) := by { ext m n, simp only [compr₂_apply, mk_apply, comp_apply, rtensor_tmul] } variables (N) @[simp] lemma ltensor_id : (id : N →ₗ[R] N).ltensor M = id := map_id @[simp] lemma rtensor_id : (id : N →ₗ[R] N).rtensor M = id := map_id variables {N} @[simp] lemma ltensor_comp_rtensor (f : M →ₗ[R] P) (g : N →ₗ[R] Q) : (g.ltensor P).comp (f.rtensor N) = map f g := by simp only [ltensor, rtensor, ← map_comp, id_comp, comp_id] @[simp] lemma rtensor_comp_ltensor (f : M →ₗ[R] P) (g : N →ₗ[R] Q) : (f.rtensor Q).comp (g.ltensor M) = map f g := by simp only [ltensor, rtensor, ← map_comp, id_comp, comp_id] @[simp] lemma map_comp_rtensor (f : M →ₗ[R] P) (g : N →ₗ[R] Q) (f' : S →ₗ[R] M) : (map f g).comp (f'.rtensor _) = map (f.comp f') g := by simp only [ltensor, rtensor, ← map_comp, id_comp, comp_id] @[simp] lemma map_comp_ltensor (f : M →ₗ[R] P) (g : N →ₗ[R] Q) (g' : S →ₗ[R] N) : (map f g).comp (g'.ltensor _) = map f (g.comp g') := by simp only [ltensor, rtensor, ← map_comp, id_comp, comp_id] @[simp] lemma rtensor_comp_map (f' : P →ₗ[R] S) (f : M →ₗ[R] P) (g : N →ₗ[R] Q) : (f'.rtensor _).comp (map f g) = map (f'.comp f) g := by simp only [ltensor, rtensor, ← map_comp, id_comp, comp_id] @[simp] lemma ltensor_comp_map (g' : Q →ₗ[R] S) (f : M →ₗ[R] P) (g : N →ₗ[R] Q) : (g'.ltensor _).comp (map f g) = map f (g'.comp g) := by simp only [ltensor, rtensor, ← map_comp, id_comp, comp_id] variables {M} @[simp] lemma rtensor_pow (f : M →ₗ[R] M) (n : ℕ) : (f.rtensor N)^n = (f^n).rtensor N := by { have h := map_pow f (id : N →ₗ[R] N) n, rwa id_pow at h, } @[simp] lemma ltensor_pow (f : N →ₗ[R] N) (n : ℕ) : (f.ltensor M)^n = (f^n).ltensor M := by { have h := map_pow (id : M →ₗ[R] M) f n, rwa id_pow at h, } end linear_map end semiring section ring variables {R : Type*} [comm_semiring R] variables {M : Type*} {N : Type*} {P : Type*} {Q : Type*} {S : Type*} variables [add_comm_group M] [add_comm_group N] [add_comm_group P] [add_comm_group Q] [add_comm_group S] variables [module R M] [module R N] [module R P] [module R Q] [module R S] namespace tensor_product open_locale tensor_product open linear_map variables (R) /-- Auxiliary function to defining negation multiplication on tensor product. -/ def neg.aux : free_add_monoid (M × N) →+ M ⊗[R] N := free_add_monoid.lift $ λ p : M × N, (-p.1) ⊗ₜ p.2 variables {R} theorem neg.aux_of (m : M) (n : N) : neg.aux R (free_add_monoid.of (m, n)) = (-m) ⊗ₜ[R] n := rfl instance : has_neg (M ⊗[R] N) := { neg := (add_con_gen (tensor_product.eqv R M N)).lift (neg.aux R) $ add_con.add_con_gen_le $ λ x y hxy, match x, y, hxy with | _, _, (eqv.of_zero_left n) := (add_con.ker_rel _).2 $ by simp_rw [add_monoid_hom.map_zero, neg.aux_of, neg_zero, zero_tmul] | _, _, (eqv.of_zero_right m) := (add_con.ker_rel _).2 $ by simp_rw [add_monoid_hom.map_zero, neg.aux_of, tmul_zero] | _, _, (eqv.of_add_left m₁ m₂ n) := (add_con.ker_rel _).2 $ by simp_rw [add_monoid_hom.map_add, neg.aux_of, neg_add, add_tmul] | _, _, (eqv.of_add_right m n₁ n₂) := (add_con.ker_rel _).2 $ by simp_rw [add_monoid_hom.map_add, neg.aux_of, tmul_add] | _, _, (eqv.of_smul s m n) := (add_con.ker_rel _).2 $ by simp_rw [neg.aux_of, tmul_smul s, smul_tmul', smul_neg] | _, _, (eqv.add_comm x y) := (add_con.ker_rel _).2 $ by simp_rw [add_monoid_hom.map_add, add_comm] end } protected theorem add_left_neg (x : M ⊗[R] N) : -x + x = 0 := tensor_product.induction_on x (by { rw [add_zero], apply (neg.aux R).map_zero, }) (λ x y, by { convert (add_tmul (-x) x y).symm, rw [add_left_neg, zero_tmul], }) (λ x y hx hy, by { unfold has_neg.neg sub_neg_monoid.neg, rw add_monoid_hom.map_add, ac_change (-x + x) + (-y + y) = 0, rw [hx, hy, add_zero], }) instance : add_comm_group (M ⊗[R] N) := { neg := has_neg.neg, sub := _, sub_eq_add_neg := λ _ _, rfl, add_left_neg := λ x, by exact tensor_product.add_left_neg x, gsmul := λ n v, n • v, gsmul_zero' := by simp [tensor_product.zero_smul], gsmul_succ' := by simp [nat.succ_eq_one_add, tensor_product.one_smul, tensor_product.add_smul], gsmul_neg' := λ n x, begin change (- n.succ : ℤ) • x = - (((n : ℤ) + 1) • x), rw [← zero_add (-↑(n.succ) • x), ← tensor_product.add_left_neg (↑(n.succ) • x), add_assoc, ← add_smul, ← sub_eq_add_neg, sub_self, zero_smul, add_zero], refl, end, .. tensor_product.add_comm_monoid } lemma neg_tmul (m : M) (n : N) : (-m) ⊗ₜ n = -(m ⊗ₜ[R] n) := rfl lemma tmul_neg (m : M) (n : N) : m ⊗ₜ (-n) = -(m ⊗ₜ[R] n) := (mk R M N _).map_neg _ lemma tmul_sub (m : M) (n₁ n₂ : N) : m ⊗ₜ (n₁ - n₂) = (m ⊗ₜ[R] n₁) - (m ⊗ₜ[R] n₂) := (mk R M N _).map_sub _ _ lemma sub_tmul (m₁ m₂ : M) (n : N) : (m₁ - m₂) ⊗ₜ n = (m₁ ⊗ₜ[R] n) - (m₂ ⊗ₜ[R] n) := (mk R M N).map_sub₂ _ _ _ /-- While the tensor product will automatically inherit a ℤ-module structure from `add_comm_group.int_module`, that structure won't be compatible with lemmas like `tmul_smul` unless we use a `ℤ-module` instance provided by `tensor_product.module'`. When `R` is a `ring` we get the required `tensor_product.compatible_smul` instance through `is_scalar_tower`, but when it is only a `semiring` we need to build it from scratch. The instance diamond in `compatible_smul` doesn't matter because it's in `Prop`. -/ instance compatible_smul.int [module ℤ M] [module ℤ N] : compatible_smul R ℤ M N := ⟨λ r m n, int.induction_on r (by simp) (λ r ih, by simpa [add_smul, tmul_add, add_tmul] using ih) (λ r ih, by simpa [sub_smul, tmul_sub, sub_tmul] using ih)⟩ instance compatible_smul.unit {S} [monoid S] [distrib_mul_action S M] [distrib_mul_action S N] [compatible_smul R S M N] : compatible_smul R (units S) M N := ⟨λ s m n, (compatible_smul.smul_tmul (s : S) m n : _)⟩ end tensor_product namespace linear_map @[simp] lemma ltensor_sub (f g : N →ₗ[R] P) : (f - g).ltensor M = f.ltensor M - g.ltensor M := by simp only [← coe_ltensor_hom, map_sub] @[simp] lemma rtensor_sub (f g : N →ₗ[R] P) : (f - g).rtensor M = f.rtensor M - g.rtensor M := by simp only [← coe_rtensor_hom, map_sub] @[simp] lemma ltensor_neg (f : N →ₗ[R] P) : (-f).ltensor M = -(f.ltensor M) := by simp only [← coe_ltensor_hom, map_neg] @[simp] lemma rtensor_neg (f : N →ₗ[R] P) : (-f).rtensor M = -(f.rtensor M) := by simp only [← coe_rtensor_hom, map_neg] end linear_map end ring
6f2bba0d2e9670496020e9b2c00974e555fda5e1
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/category_theory/limits/comma.lean
6de3508a4374b71ca6ee87e52c147b8e5139e8c2
[ "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
10,254
lean
/- Copyright (c) 2021 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import category_theory.arrow import category_theory.limits.constructions.epi_mono import category_theory.limits.creates import category_theory.limits.unit import category_theory.structured_arrow /-! # Limits and colimits in comma categories We build limits in the comma category `comma L R` provided that the two source categories have limits and `R` preserves them. This is used to construct limits in the arrow category, structured arrow category and under category, and show that the appropriate forgetful functors create limits. The duals of all the above are also given. -/ namespace category_theory open category limits universes w' w v u₁ u₂ u₃ variables {J : Type w} [category.{w'} J] variables {A : Type u₁} [category.{v} A] variables {B : Type u₂} [category.{v} B] variables {T : Type u₃} [category.{v} T] namespace comma variables {L : A ⥤ T} {R : B ⥤ T} variables (F : J ⥤ comma L R) /-- (Implementation). An auxiliary cone which is useful in order to construct limits in the comma category. -/ @[simps] def limit_auxiliary_cone (c₁ : cone (F ⋙ fst L R)) : cone ((F ⋙ snd L R) ⋙ R) := (cones.postcompose (whisker_left F (comma.nat_trans L R) : _)).obj (L.map_cone c₁) /-- If `R` preserves the appropriate limit, then given a cone for `F ⋙ fst L R : J ⥤ L` and a limit cone for `F ⋙ snd L R : J ⥤ R` we can build a cone for `F` which will turn out to be a limit cone. -/ @[simps] def cone_of_preserves [preserves_limit (F ⋙ snd L R) R] (c₁ : cone (F ⋙ fst L R)) {c₂ : cone (F ⋙ snd L R)} (t₂ : is_limit c₂) : cone F := { X := { left := c₁.X, right := c₂.X, hom := (is_limit_of_preserves R t₂).lift (limit_auxiliary_cone _ c₁) }, π := { app := λ j, { left := c₁.π.app j, right := c₂.π.app j, w' := ((is_limit_of_preserves R t₂).fac (limit_auxiliary_cone F c₁) j).symm }, naturality' := λ j₁ j₂ t, by ext; dsimp; simp [←c₁.w t, ←c₂.w t] } } /-- Provided that `R` preserves the appropriate limit, then the cone in `cone_of_preserves` is a limit. -/ def cone_of_preserves_is_limit [preserves_limit (F ⋙ snd L R) R] {c₁ : cone (F ⋙ fst L R)} (t₁ : is_limit c₁) {c₂ : cone (F ⋙ snd L R)} (t₂ : is_limit c₂) : is_limit (cone_of_preserves F c₁ t₂) := { lift := λ s, { left := t₁.lift ((fst L R).map_cone s), right := t₂.lift ((snd L R).map_cone s), w' := (is_limit_of_preserves R t₂).hom_ext $ λ j, begin rw [cone_of_preserves_X_hom, assoc, assoc, (is_limit_of_preserves R t₂).fac, limit_auxiliary_cone_π_app, ←L.map_comp_assoc, t₁.fac, R.map_cone_π_app, ←R.map_comp, t₂.fac], exact (s.π.app j).w, end }, uniq' := λ s m w, comma_morphism.ext _ _ (t₁.uniq ((fst L R).map_cone s) _ (λ j, by simp [←w])) (t₂.uniq ((snd L R).map_cone s) _ (λ j, by simp [←w])) } /-- (Implementation). An auxiliary cocone which is useful in order to construct colimits in the comma category. -/ @[simps] def colimit_auxiliary_cocone (c₂ : cocone (F ⋙ snd L R)) : cocone ((F ⋙ fst L R) ⋙ L) := (cocones.precompose (whisker_left F (comma.nat_trans L R) : _)).obj (R.map_cocone c₂) /-- If `L` preserves the appropriate colimit, then given a colimit cocone for `F ⋙ fst L R : J ⥤ L` and a cocone for `F ⋙ snd L R : J ⥤ R` we can build a cocone for `F` which will turn out to be a colimit cocone. -/ @[simps] def cocone_of_preserves [preserves_colimit (F ⋙ fst L R) L] {c₁ : cocone (F ⋙ fst L R)} (t₁ : is_colimit c₁) (c₂ : cocone (F ⋙ snd L R)) : cocone F := { X := { left := c₁.X, right := c₂.X, hom := (is_colimit_of_preserves L t₁).desc (colimit_auxiliary_cocone _ c₂) }, ι := { app := λ j, { left := c₁.ι.app j, right := c₂.ι.app j, w' := ((is_colimit_of_preserves L t₁).fac (colimit_auxiliary_cocone _ c₂) j) }, naturality' := λ j₁ j₂ t, by ext; dsimp; simp [←c₁.w t, ←c₂.w t] } } /-- Provided that `L` preserves the appropriate colimit, then the cocone in `cocone_of_preserves` is a colimit. -/ def cocone_of_preserves_is_colimit [preserves_colimit (F ⋙ fst L R) L] {c₁ : cocone (F ⋙ fst L R)} (t₁ : is_colimit c₁) {c₂ : cocone (F ⋙ snd L R)} (t₂ : is_colimit c₂) : is_colimit (cocone_of_preserves F t₁ c₂) := { desc := λ s, { left := t₁.desc ((fst L R).map_cocone s), right := t₂.desc ((snd L R).map_cocone s), w' := (is_colimit_of_preserves L t₁).hom_ext $ λ j, begin rw [cocone_of_preserves_X_hom, (is_colimit_of_preserves L t₁).fac_assoc, colimit_auxiliary_cocone_ι_app, assoc, ←R.map_comp, t₂.fac, L.map_cocone_ι_app, ←L.map_comp_assoc, t₁.fac], exact (s.ι.app j).w, end }, uniq' := λ s m w, comma_morphism.ext _ _ (t₁.uniq ((fst L R).map_cocone s) _ (by simp [←w])) (t₂.uniq ((snd L R).map_cocone s) _ (by simp [←w])) } instance has_limit (F : J ⥤ comma L R) [has_limit (F ⋙ fst L R)] [has_limit (F ⋙ snd L R)] [preserves_limit (F ⋙ snd L R) R] : has_limit F := has_limit.mk ⟨_, cone_of_preserves_is_limit _ (limit.is_limit _) (limit.is_limit _)⟩ instance has_limits_of_shape [has_limits_of_shape J A] [has_limits_of_shape J B] [preserves_limits_of_shape J R] : has_limits_of_shape J (comma L R) := {} instance has_limits [has_limits A] [has_limits B] [preserves_limits R] : has_limits (comma L R) := ⟨infer_instance⟩ instance has_colimit (F : J ⥤ comma L R) [has_colimit (F ⋙ fst L R)] [has_colimit (F ⋙ snd L R)] [preserves_colimit (F ⋙ fst L R) L] : has_colimit F := has_colimit.mk ⟨_, cocone_of_preserves_is_colimit _ (colimit.is_colimit _) (colimit.is_colimit _)⟩ instance has_colimits_of_shape [has_colimits_of_shape J A] [has_colimits_of_shape J B] [preserves_colimits_of_shape J L] : has_colimits_of_shape J (comma L R) := {} instance has_colimits [has_colimits A] [has_colimits B] [preserves_colimits L] : has_colimits (comma L R) := ⟨infer_instance⟩ end comma namespace arrow instance has_limit (F : J ⥤ arrow T) [i₁ : has_limit (F ⋙ left_func)] [i₂ : has_limit (F ⋙ right_func)] : has_limit F := @@comma.has_limit _ _ _ _ _ i₁ i₂ _ instance has_limits_of_shape [has_limits_of_shape J T] : has_limits_of_shape J (arrow T) := {} instance has_limits [has_limits T] : has_limits (arrow T) := ⟨infer_instance⟩ instance has_colimit (F : J ⥤ arrow T) [i₁ : has_colimit (F ⋙ left_func)] [i₂ : has_colimit (F ⋙ right_func)] : has_colimit F := @@comma.has_colimit _ _ _ _ _ i₁ i₂ _ instance has_colimits_of_shape [has_colimits_of_shape J T] : has_colimits_of_shape J (arrow T) := {} instance has_colimits [has_colimits T] : has_colimits (arrow T) := ⟨infer_instance⟩ end arrow namespace structured_arrow variables {X : T} {G : A ⥤ T} (F : J ⥤ structured_arrow X G) instance has_limit [i₁ : has_limit (F ⋙ proj X G)] [i₂ : preserves_limit (F ⋙ proj X G) G] : has_limit F := @@comma.has_limit _ _ _ _ _ _ i₁ i₂ instance has_limits_of_shape [has_limits_of_shape J A] [preserves_limits_of_shape J G] : has_limits_of_shape J (structured_arrow X G) := {} instance has_limits [has_limits A] [preserves_limits G] : has_limits (structured_arrow X G) := ⟨infer_instance⟩ noncomputable instance creates_limit [i : preserves_limit (F ⋙ proj X G) G] : creates_limit F (proj X G) := creates_limit_of_reflects_iso $ λ c t, { lifted_cone := @@comma.cone_of_preserves _ _ _ _ _ i punit_cone t, makes_limit := comma.cone_of_preserves_is_limit _ punit_cone_is_limit _, valid_lift := cones.ext (iso.refl _) $ λ j, (id_comp _).symm } noncomputable instance creates_limits_of_shape [preserves_limits_of_shape J G] : creates_limits_of_shape J (proj X G) := {} noncomputable instance creates_limits [preserves_limits G] : creates_limits (proj X G : _) := ⟨⟩ instance mono_right_of_mono [has_pullbacks A] [preserves_limits_of_shape walking_cospan G] {Y Z : structured_arrow X G} (f : Y ⟶ Z) [mono f] : mono f.right := show mono ((proj X G).map f), from infer_instance lemma mono_iff_mono_right [has_pullbacks A] [preserves_limits_of_shape walking_cospan G] {Y Z : structured_arrow X G} (f : Y ⟶ Z) : mono f ↔ mono f.right := ⟨λ h, by exactI infer_instance, λ h, by exactI mono_of_mono_right f⟩ end structured_arrow namespace costructured_arrow variables {G : A ⥤ T} {X : T} (F : J ⥤ costructured_arrow G X) instance has_colimit [i₁ : has_colimit (F ⋙ proj G X)] [i₂ : preserves_colimit (F ⋙ proj G X) G] : has_colimit F := @@comma.has_colimit _ _ _ _ _ i₁ _ i₂ instance has_colimits_of_shape [has_colimits_of_shape J A] [preserves_colimits_of_shape J G] : has_colimits_of_shape J (costructured_arrow G X) := {} instance has_colimits [has_colimits A] [preserves_colimits G] : has_colimits (costructured_arrow G X) := ⟨infer_instance⟩ noncomputable instance creates_colimit [i : preserves_colimit (F ⋙ proj G X) G] : creates_colimit F (proj G X) := creates_colimit_of_reflects_iso $ λ c t, { lifted_cocone := @@comma.cocone_of_preserves _ _ _ _ _ i t punit_cocone, makes_colimit := comma.cocone_of_preserves_is_colimit _ _ punit_cocone_is_colimit, valid_lift := cocones.ext (iso.refl _) $ λ j, comp_id _ } noncomputable instance creates_colimits_of_shape [preserves_colimits_of_shape J G] : creates_colimits_of_shape J (proj G X) := {} noncomputable instance creates_colimits [preserves_colimits G] : creates_colimits (proj G X : _) := ⟨⟩ instance epi_left_of_epi [has_pushouts A] [preserves_colimits_of_shape walking_span G] {Y Z : costructured_arrow G X} (f : Y ⟶ Z) [epi f] : epi f.left := show epi ((proj G X).map f), from infer_instance lemma epi_iff_epi_left [has_pushouts A] [preserves_colimits_of_shape walking_span G] {Y Z : costructured_arrow G X} (f : Y ⟶ Z) : epi f ↔ epi f.left := ⟨λ h, by exactI infer_instance, λ h, by exactI epi_of_epi_left f⟩ end costructured_arrow end category_theory
03b3f3188af2c7dd9ff5f567bef1b0309785ee4c
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/1888.lean
9e2644a753f02b3909c5b78d3f172e4416f4d87a
[ "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
600
lean
universes u variables {α : Sort u} {r p q : α → Prop} {P Q : ∀ x, p x → Prop} {a b c d : Prop} @[simp] theorem exists_prop {p q : Prop} : (∃ h : p, q) ↔ p ∧ q := sorry @[simp] theorem exists_and_distrib_right {q : Prop} {p : α → Prop} : (∃x, p x ∧ q) ↔ (∃x, p x) ∧ q := sorry @[simp] theorem and_imp : (a ∧ b → c) ↔ (a → b → c) := sorry @[simp] theorem exists_imp_distrib : ((∃ x, p x) → b) ↔ ∀ x, p x → b := sorry set_option trace.simplify.rewrite true @[simp] theorem bex_imp_distrib : ((∃ x h, P x h) → b) ↔ (∀ x h, P x h → b) := by simp
85eeafcb7baa3fd0bb47c7b95c5f0f7c2d79aa44
82e44445c70db0f03e30d7be725775f122d72f3e
/src/linear_algebra/multilinear.lean
6cf4ec9be8bef2a4f68f82481041671022ceb09b
[ "Apache-2.0" ]
permissive
stjordanis/mathlib
51e286d19140e3788ef2c470bc7b953e4991f0c9
2568d41bca08f5d6bf39d915434c8447e21f42ee
refs/heads/master
1,631,748,053,501
1,627,938,886,000
1,627,938,886,000
228,728,358
0
0
Apache-2.0
1,576,630,588,000
1,576,630,587,000
null
UTF-8
Lean
false
false
54,255
lean
/- Copyright (c) 2020 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import linear_algebra.basic import algebra.algebra.basic import algebra.big_operators.order import algebra.big_operators.ring import data.fintype.card import data.fintype.sort /-! # Multilinear maps We define multilinear maps as maps from `Π(i : ι), M₁ i` to `M₂` which are linear in each coordinate. Here, `M₁ i` and `M₂` are modules over a ring `R`, and `ι` is an arbitrary type (although some statements will require it to be a fintype). This space, denoted by `multilinear_map R M₁ M₂`, inherits a module structure by pointwise addition and multiplication. ## Main definitions * `multilinear_map R M₁ M₂` is the space of multilinear maps from `Π(i : ι), M₁ i` to `M₂`. * `f.map_smul` is the multiplicativity of the multilinear map `f` along each coordinate. * `f.map_add` is the additivity of the multilinear map `f` along each coordinate. * `f.map_smul_univ` expresses the multiplicativity of `f` over all coordinates at the same time, writing `f (λi, c i • m i)` as `(∏ i, c i) • f m`. * `f.map_add_univ` expresses the additivity of `f` over all coordinates at the same time, writing `f (m + m')` as the sum over all subsets `s` of `ι` of `f (s.piecewise m m')`. * `f.map_sum` expresses `f (Σ_{j₁} g₁ j₁, ..., Σ_{jₙ} gₙ jₙ)` as the sum of `f (g₁ (r 1), ..., gₙ (r n))` where `r` ranges over all possible functions. We also register isomorphisms corresponding to currying or uncurrying variables, transforming a multilinear function `f` on `n+1` variables into a linear function taking values in multilinear functions in `n` variables, and into a multilinear function in `n` variables taking values in linear functions. These operations are called `f.curry_left` and `f.curry_right` respectively (with inverses `f.uncurry_left` and `f.uncurry_right`). These operations induce linear equivalences between spaces of multilinear functions in `n+1` variables and spaces of linear functions into multilinear functions in `n` variables (resp. multilinear functions in `n` variables taking values in linear functions), called respectively `multilinear_curry_left_equiv` and `multilinear_curry_right_equiv`. ## Implementation notes Expressing that a map is linear along the `i`-th coordinate when all other coordinates are fixed can be done in two (equivalent) different ways: * fixing a vector `m : Π(j : ι - i), M₁ j.val`, and then choosing separately the `i`-th coordinate * fixing a vector `m : Πj, M₁ j`, and then modifying its `i`-th coordinate The second way is more artificial as the value of `m` at `i` is not relevant, but it has the advantage of avoiding subtype inclusion issues. This is the definition we use, based on `function.update` that allows to change the value of `m` at `i`. -/ open function fin set open_locale big_operators universes u v v' v₁ v₂ v₃ w u' variables {R : Type u} {ι : Type u'} {n : ℕ} {M : fin n.succ → Type v} {M₁ : ι → Type v₁} {M₂ : Type v₂} {M₃ : Type v₃} {M' : Type v'} [decidable_eq ι] /-- Multilinear maps over the ring `R`, from `Πi, M₁ i` to `M₂` where `M₁ i` and `M₂` are modules over `R`. -/ structure multilinear_map (R : Type u) {ι : Type u'} (M₁ : ι → Type v) (M₂ : Type w) [decidable_eq ι] [semiring R] [∀i, add_comm_monoid (M₁ i)] [add_comm_monoid M₂] [∀i, module R (M₁ i)] [module R M₂] := (to_fun : (Πi, M₁ i) → M₂) (map_add' : ∀(m : Πi, M₁ i) (i : ι) (x y : M₁ i), to_fun (update m i (x + y)) = to_fun (update m i x) + to_fun (update m i y)) (map_smul' : ∀(m : Πi, M₁ i) (i : ι) (c : R) (x : M₁ i), to_fun (update m i (c • x)) = c • to_fun (update m i x)) namespace multilinear_map section semiring variables [semiring R] [∀i, add_comm_monoid (M i)] [∀i, add_comm_monoid (M₁ i)] [add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_monoid M'] [∀i, module R (M i)] [∀i, module R (M₁ i)] [module R M₂] [module R M₃] [module R M'] (f f' : multilinear_map R M₁ M₂) instance : has_coe_to_fun (multilinear_map R M₁ M₂) := ⟨_, to_fun⟩ initialize_simps_projections multilinear_map (to_fun → apply) @[simp] lemma to_fun_eq_coe : f.to_fun = f := rfl @[simp] lemma coe_mk (f : (Π i, M₁ i) → M₂) (h₁ h₂ ) : ⇑(⟨f, h₁, h₂⟩ : multilinear_map R M₁ M₂) = f := rfl theorem congr_fun {f g : multilinear_map R M₁ M₂} (h : f = g) (x : Π i, M₁ i) : f x = g x := congr_arg (λ h : multilinear_map R M₁ M₂, h x) h theorem congr_arg (f : multilinear_map R M₁ M₂) {x y : Π i, M₁ i} (h : x = y) : f x = f y := congr_arg (λ x : Π i, M₁ i, f x) h theorem coe_inj ⦃f g : multilinear_map R M₁ M₂⦄ (h : ⇑f = g) : f = g := by cases f; cases g; cases h; refl @[ext] theorem ext {f f' : multilinear_map R M₁ M₂} (H : ∀ x, f x = f' x) : f = f' := coe_inj (funext H) theorem ext_iff {f g : multilinear_map R M₁ M₂} : f = g ↔ ∀ x, f x = g x := ⟨λ h x, h ▸ rfl, λ h, ext h⟩ @[simp] lemma map_add (m : Πi, M₁ i) (i : ι) (x y : M₁ i) : f (update m i (x + y)) = f (update m i x) + f (update m i y) := f.map_add' m i x y @[simp] lemma map_smul (m : Πi, M₁ i) (i : ι) (c : R) (x : M₁ i) : f (update m i (c • x)) = c • f (update m i x) := f.map_smul' m i c x lemma map_coord_zero {m : Πi, M₁ i} (i : ι) (h : m i = 0) : f m = 0 := begin have : (0 : R) • (0 : M₁ i) = 0, by simp, rw [← update_eq_self i m, h, ← this, f.map_smul, zero_smul] end @[simp] lemma map_update_zero (m : Πi, M₁ i) (i : ι) : f (update m i 0) = 0 := f.map_coord_zero i (update_same i 0 m) @[simp] lemma map_zero [nonempty ι] : f 0 = 0 := begin obtain ⟨i, _⟩ : ∃i:ι, i ∈ set.univ := set.exists_mem_of_nonempty ι, exact map_coord_zero f i rfl end instance : has_add (multilinear_map R M₁ M₂) := ⟨λf f', ⟨λx, f x + f' x, λm i x y, by simp [add_left_comm, add_assoc], λm i c x, by simp [smul_add]⟩⟩ @[simp] lemma add_apply (m : Πi, M₁ i) : (f + f') m = f m + f' m := rfl instance : has_zero (multilinear_map R M₁ M₂) := ⟨⟨λ _, 0, λm i x y, by simp, λm i c x, by simp⟩⟩ instance : inhabited (multilinear_map R M₁ M₂) := ⟨0⟩ @[simp] lemma zero_apply (m : Πi, M₁ i) : (0 : multilinear_map R M₁ M₂) m = 0 := rfl instance : add_comm_monoid (multilinear_map R M₁ M₂) := { zero := (0 : multilinear_map R M₁ M₂), add := (+), add_assoc := by intros; ext; simp [add_comm, add_left_comm], zero_add := by intros; ext; simp [add_comm, add_left_comm], add_zero := by intros; ext; simp [add_comm, add_left_comm], add_comm := by intros; ext; simp [add_comm, add_left_comm], nsmul := λ n f, ⟨λ m, n • f m, λm i x y, by simp [smul_add], λl i x d, by simp [←smul_comm x n] ⟩, nsmul_zero' := λ f, by { ext, simp }, nsmul_succ' := λ n f, by { ext, simp [add_smul, nat.succ_eq_one_add] } } @[simp] lemma sum_apply {α : Type*} (f : α → multilinear_map R M₁ M₂) (m : Πi, M₁ i) : ∀ {s : finset α}, (∑ a in s, f a) m = ∑ a in s, f a m := begin classical, apply finset.induction, { rw finset.sum_empty, simp }, { assume a s has H, rw finset.sum_insert has, simp [H, has] } end /-- If `f` is a multilinear map, then `f.to_linear_map m i` is the linear map obtained by fixing all coordinates but `i` equal to those of `m`, and varying the `i`-th coordinate. -/ def to_linear_map (m : Πi, M₁ i) (i : ι) : M₁ i →ₗ[R] M₂ := { to_fun := λx, f (update m i x), map_add' := λx y, by simp, map_smul' := λc x, by simp } /-- The cartesian product of two multilinear maps, as a multilinear map. -/ def prod (f : multilinear_map R M₁ M₂) (g : multilinear_map R M₁ M₃) : multilinear_map R M₁ (M₂ × M₃) := { to_fun := λ m, (f m, g m), map_add' := λ m i x y, by simp, map_smul' := λ m i c x, by simp } /-- Combine a family of multilinear maps with the same domain and codomains `M' i` into a multilinear map taking values in the space of functions `Π i, M' i`. -/ @[simps] def pi {ι' : Type*} {M' : ι' → Type*} [Π i, add_comm_monoid (M' i)] [Π i, module R (M' i)] (f : Π i, multilinear_map R M₁ (M' i)) : multilinear_map R M₁ (Π i, M' i) := { to_fun := λ m i, f i m, map_add' := λ m i x y, funext $ λ j, (f j).map_add _ _ _ _, map_smul' := λ m i c x, funext $ λ j, (f j).map_smul _ _ _ _ } /-- Given a multilinear map `f` on `n` variables (parameterized by `fin n`) and a subset `s` of `k` of these variables, one gets a new multilinear map on `fin k` by varying these variables, and fixing the other ones equal to a given value `z`. It is denoted by `f.restr s hk z`, where `hk` is a proof that the cardinality of `s` is `k`. The implicit identification between `fin k` and `s` that we use is the canonical (increasing) bijection. -/ def restr {k n : ℕ} (f : multilinear_map R (λ i : fin n, M') M₂) (s : finset (fin n)) (hk : s.card = k) (z : M') : multilinear_map R (λ i : fin k, M') M₂ := { to_fun := λ v, f (λ j, if h : j ∈ s then v ((s.order_iso_of_fin hk).symm ⟨j, h⟩) else z), map_add' := λ v i x y, by { erw [dite_comp_equiv_update, dite_comp_equiv_update, dite_comp_equiv_update], simp }, map_smul' := λ v i c x, by { erw [dite_comp_equiv_update, dite_comp_equiv_update], simp } } variable {R} /-- In the specific case of multilinear maps on spaces indexed by `fin (n+1)`, where one can build an element of `Π(i : fin (n+1)), M i` using `cons`, one can express directly the additivity of a multilinear map along the first variable. -/ lemma cons_add (f : multilinear_map R M M₂) (m : Π(i : fin n), M i.succ) (x y : M 0) : f (cons (x+y) m) = f (cons x m) + f (cons y m) := by rw [← update_cons_zero x m (x+y), f.map_add, update_cons_zero, update_cons_zero] /-- In the specific case of multilinear maps on spaces indexed by `fin (n+1)`, where one can build an element of `Π(i : fin (n+1)), M i` using `cons`, one can express directly the multiplicativity of a multilinear map along the first variable. -/ lemma cons_smul (f : multilinear_map R M M₂) (m : Π(i : fin n), M i.succ) (c : R) (x : M 0) : f (cons (c • x) m) = c • f (cons x m) := by rw [← update_cons_zero x m (c • x), f.map_smul, update_cons_zero] /-- In the specific case of multilinear maps on spaces indexed by `fin (n+1)`, where one can build an element of `Π(i : fin (n+1)), M i` using `snoc`, one can express directly the additivity of a multilinear map along the first variable. -/ lemma snoc_add (f : multilinear_map R M M₂) (m : Π(i : fin n), M i.cast_succ) (x y : M (last n)) : f (snoc m (x+y)) = f (snoc m x) + f (snoc m y) := by rw [← update_snoc_last x m (x+y), f.map_add, update_snoc_last, update_snoc_last] /-- In the specific case of multilinear maps on spaces indexed by `fin (n+1)`, where one can build an element of `Π(i : fin (n+1)), M i` using `cons`, one can express directly the multiplicativity of a multilinear map along the first variable. -/ lemma snoc_smul (f : multilinear_map R M M₂) (m : Π(i : fin n), M i.cast_succ) (c : R) (x : M (last n)) : f (snoc m (c • x)) = c • f (snoc m x) := by rw [← update_snoc_last x m (c • x), f.map_smul, update_snoc_last] section variables {M₁' : ι → Type*} [Π i, add_comm_monoid (M₁' i)] [Π i, module R (M₁' i)] /-- If `g` is a multilinear map and `f` is a collection of linear maps, then `g (f₁ m₁, ..., fₙ mₙ)` is again a multilinear map, that we call `g.comp_linear_map f`. -/ def comp_linear_map (g : multilinear_map R M₁' M₂) (f : Π i, M₁ i →ₗ[R] M₁' i) : multilinear_map R M₁ M₂ := { to_fun := λ m, g $ λ i, f i (m i), map_add' := λ m i x y, have ∀ j z, f j (update m i z j) = update (λ k, f k (m k)) i (f i z) j := λ j z, function.apply_update (λ k, f k) _ _ _ _, by simp [this], map_smul' := λ m i c x, have ∀ j z, f j (update m i z j) = update (λ k, f k (m k)) i (f i z) j := λ j z, function.apply_update (λ k, f k) _ _ _ _, by simp [this] } @[simp] lemma comp_linear_map_apply (g : multilinear_map R M₁' M₂) (f : Π i, M₁ i →ₗ[R] M₁' i) (m : Π i, M₁ i) : g.comp_linear_map f m = g (λ i, f i (m i)) := rfl end /-- If one adds to a vector `m'` another vector `m`, but only for coordinates in a finset `t`, then the image under a multilinear map `f` is the sum of `f (s.piecewise m m')` along all subsets `s` of `t`. This is mainly an auxiliary statement to prove the result when `t = univ`, given in `map_add_univ`, although it can be useful in its own right as it does not require the index set `ι` to be finite.-/ lemma map_piecewise_add (m m' : Πi, M₁ i) (t : finset ι) : f (t.piecewise (m + m') m') = ∑ s in t.powerset, f (s.piecewise m m') := begin revert m', refine finset.induction_on t (by simp) _, assume i t hit Hrec m', have A : (insert i t).piecewise (m + m') m' = update (t.piecewise (m + m') m') i (m i + m' i) := t.piecewise_insert _ _ _, have B : update (t.piecewise (m + m') m') i (m' i) = t.piecewise (m + m') m', { ext j, by_cases h : j = i, { rw h, simp [hit] }, { simp [h] } }, let m'' := update m' i (m i), have C : update (t.piecewise (m + m') m') i (m i) = t.piecewise (m + m'') m'', { ext j, by_cases h : j = i, { rw h, simp [m'', hit] }, { by_cases h' : j ∈ t; simp [h, hit, m'', h'] } }, rw [A, f.map_add, B, C, finset.sum_powerset_insert hit, Hrec, Hrec, add_comm], congr' 1, apply finset.sum_congr rfl (λs hs, _), have : (insert i s).piecewise m m' = s.piecewise m m'', { ext j, by_cases h : j = i, { rw h, simp [m'', finset.not_mem_of_mem_powerset_of_not_mem hs hit] }, { by_cases h' : j ∈ s; simp [h, m'', h'] } }, rw this end /-- Additivity of a multilinear map along all coordinates at the same time, writing `f (m + m')` as the sum of `f (s.piecewise m m')` over all sets `s`. -/ lemma map_add_univ [fintype ι] (m m' : Πi, M₁ i) : f (m + m') = ∑ s : finset ι, f (s.piecewise m m') := by simpa using f.map_piecewise_add m m' finset.univ section apply_sum variables {α : ι → Type*} (g : Π i, α i → M₁ i) (A : Π i, finset (α i)) open_locale classical open fintype finset /-- If `f` is multilinear, then `f (Σ_{j₁ ∈ A₁} g₁ j₁, ..., Σ_{jₙ ∈ Aₙ} gₙ jₙ)` is the sum of `f (g₁ (r 1), ..., gₙ (r n))` where `r` ranges over all functions with `r 1 ∈ A₁`, ..., `r n ∈ Aₙ`. This follows from multilinearity by expanding successively with respect to each coordinate. Here, we give an auxiliary statement tailored for an inductive proof. Use instead `map_sum_finset`. -/ lemma map_sum_finset_aux [fintype ι] {n : ℕ} (h : ∑ i, (A i).card = n) : f (λ i, ∑ j in A i, g i j) = ∑ r in pi_finset A, f (λ i, g i (r i)) := begin induction n using nat.strong_induction_on with n IH generalizing A, -- If one of the sets is empty, then all the sums are zero by_cases Ai_empty : ∃ i, A i = ∅, { rcases Ai_empty with ⟨i, hi⟩, have : ∑ j in A i, g i j = 0, by convert sum_empty, rw f.map_coord_zero i this, have : pi_finset A = ∅, { apply finset.eq_empty_of_forall_not_mem (λ r hr, _), have : r i ∈ A i := mem_pi_finset.mp hr i, rwa hi at this }, convert sum_empty.symm }, push_neg at Ai_empty, -- Otherwise, if all sets are at most singletons, then they are exactly singletons and the result -- is again straightforward by_cases Ai_singleton : ∀ i, (A i).card ≤ 1, { have Ai_card : ∀ i, (A i).card = 1, { assume i, have pos : finset.card (A i) ≠ 0, by simp [finset.card_eq_zero, Ai_empty i], have : finset.card (A i) ≤ 1 := Ai_singleton i, exact le_antisymm this (nat.succ_le_of_lt (_root_.pos_iff_ne_zero.mpr pos)) }, have : ∀ (r : Π i, α i), r ∈ pi_finset A → f (λ i, g i (r i)) = f (λ i, ∑ j in A i, g i j), { assume r hr, unfold_coes, congr' with i, have : ∀ j ∈ A i, g i j = g i (r i), { assume j hj, congr, apply finset.card_le_one_iff.1 (Ai_singleton i) hj, exact mem_pi_finset.mp hr i }, simp only [finset.sum_congr rfl this, finset.mem_univ, finset.sum_const, Ai_card i, one_nsmul] }, simp only [sum_congr rfl this, Ai_card, card_pi_finset, prod_const_one, one_nsmul, finset.sum_const] }, -- Remains the interesting case where one of the `A i`, say `A i₀`, has cardinality at least 2. -- We will split into two parts `B i₀` and `C i₀` of smaller cardinality, let `B i = C i = A i` -- for `i ≠ i₀`, apply the inductive assumption to `B` and `C`, and add up the corresponding -- parts to get the sum for `A`. push_neg at Ai_singleton, obtain ⟨i₀, hi₀⟩ : ∃ i, 1 < (A i).card := Ai_singleton, obtain ⟨j₁, j₂, hj₁, hj₂, j₁_ne_j₂⟩ : ∃ j₁ j₂, (j₁ ∈ A i₀) ∧ (j₂ ∈ A i₀) ∧ j₁ ≠ j₂ := finset.one_lt_card_iff.1 hi₀, let B := function.update A i₀ (A i₀ \ {j₂}), let C := function.update A i₀ {j₂}, have B_subset_A : ∀ i, B i ⊆ A i, { assume i, by_cases hi : i = i₀, { rw hi, simp only [B, sdiff_subset, update_same]}, { simp only [hi, B, update_noteq, ne.def, not_false_iff, finset.subset.refl] } }, have C_subset_A : ∀ i, C i ⊆ A i, { assume i, by_cases hi : i = i₀, { rw hi, simp only [C, hj₂, finset.singleton_subset_iff, update_same] }, { simp only [hi, C, update_noteq, ne.def, not_false_iff, finset.subset.refl] } }, -- split the sum at `i₀` as the sum over `B i₀` plus the sum over `C i₀`, to use additivity. have A_eq_BC : (λ i, ∑ j in A i, g i j) = function.update (λ i, ∑ j in A i, g i j) i₀ (∑ j in B i₀, g i₀ j + ∑ j in C i₀, g i₀ j), { ext i, by_cases hi : i = i₀, { rw [hi], simp only [function.update_same], have : A i₀ = B i₀ ∪ C i₀, { simp only [B, C, function.update_same, finset.sdiff_union_self_eq_union], symmetry, simp only [hj₂, finset.singleton_subset_iff, union_eq_left_iff_subset] }, rw this, apply finset.sum_union, apply finset.disjoint_right.2 (λ j hj, _), have : j = j₂, by { dsimp [C] at hj, simpa using hj }, rw this, dsimp [B], simp only [mem_sdiff, eq_self_iff_true, not_true, not_false_iff, finset.mem_singleton, update_same, and_false] }, { simp [hi] } }, have Beq : function.update (λ i, ∑ j in A i, g i j) i₀ (∑ j in B i₀, g i₀ j) = (λ i, ∑ j in B i, g i j), { ext i, by_cases hi : i = i₀, { rw hi, simp only [update_same] }, { simp only [hi, B, update_noteq, ne.def, not_false_iff] } }, have Ceq : function.update (λ i, ∑ j in A i, g i j) i₀ (∑ j in C i₀, g i₀ j) = (λ i, ∑ j in C i, g i j), { ext i, by_cases hi : i = i₀, { rw hi, simp only [update_same] }, { simp only [hi, C, update_noteq, ne.def, not_false_iff] } }, -- Express the inductive assumption for `B` have Brec : f (λ i, ∑ j in B i, g i j) = ∑ r in pi_finset B, f (λ i, g i (r i)), { have : ∑ i, finset.card (B i) < ∑ i, finset.card (A i), { refine finset.sum_lt_sum (λ i hi, finset.card_le_of_subset (B_subset_A i)) ⟨i₀, finset.mem_univ _, _⟩, have : {j₂} ⊆ A i₀, by simp [hj₂], simp only [B, finset.card_sdiff this, function.update_same, finset.card_singleton], exact nat.pred_lt (ne_of_gt (lt_trans nat.zero_lt_one hi₀)) }, rw h at this, exact IH _ this B rfl }, -- Express the inductive assumption for `C` have Crec : f (λ i, ∑ j in C i, g i j) = ∑ r in pi_finset C, f (λ i, g i (r i)), { have : ∑ i, finset.card (C i) < ∑ i, finset.card (A i) := finset.sum_lt_sum (λ i hi, finset.card_le_of_subset (C_subset_A i)) ⟨i₀, finset.mem_univ _, by simp [C, hi₀]⟩, rw h at this, exact IH _ this C rfl }, have D : disjoint (pi_finset B) (pi_finset C), { have : disjoint (B i₀) (C i₀), by simp [B, C], exact pi_finset_disjoint_of_disjoint B C this }, have pi_BC : pi_finset A = pi_finset B ∪ pi_finset C, { apply finset.subset.antisymm, { assume r hr, by_cases hri₀ : r i₀ = j₂, { apply finset.mem_union_right, apply mem_pi_finset.2 (λ i, _), by_cases hi : i = i₀, { have : r i₀ ∈ C i₀, by simp [C, hri₀], convert this }, { simp [C, hi, mem_pi_finset.1 hr i] } }, { apply finset.mem_union_left, apply mem_pi_finset.2 (λ i, _), by_cases hi : i = i₀, { have : r i₀ ∈ B i₀, by simp [B, hri₀, mem_pi_finset.1 hr i₀], convert this }, { simp [B, hi, mem_pi_finset.1 hr i] } } }, { exact finset.union_subset (pi_finset_subset _ _ (λ i, B_subset_A i)) (pi_finset_subset _ _ (λ i, C_subset_A i)) } }, rw A_eq_BC, simp only [multilinear_map.map_add, Beq, Ceq, Brec, Crec, pi_BC], rw ← finset.sum_union D, end /-- If `f` is multilinear, then `f (Σ_{j₁ ∈ A₁} g₁ j₁, ..., Σ_{jₙ ∈ Aₙ} gₙ jₙ)` is the sum of `f (g₁ (r 1), ..., gₙ (r n))` where `r` ranges over all functions with `r 1 ∈ A₁`, ..., `r n ∈ Aₙ`. This follows from multilinearity by expanding successively with respect to each coordinate. -/ lemma map_sum_finset [fintype ι] : f (λ i, ∑ j in A i, g i j) = ∑ r in pi_finset A, f (λ i, g i (r i)) := f.map_sum_finset_aux _ _ rfl /-- If `f` is multilinear, then `f (Σ_{j₁} g₁ j₁, ..., Σ_{jₙ} gₙ jₙ)` is the sum of `f (g₁ (r 1), ..., gₙ (r n))` where `r` ranges over all functions `r`. This follows from multilinearity by expanding successively with respect to each coordinate. -/ lemma map_sum [fintype ι] [∀ i, fintype (α i)] : f (λ i, ∑ j, g i j) = ∑ r : Π i, α i, f (λ i, g i (r i)) := f.map_sum_finset g (λ i, finset.univ) lemma map_update_sum {α : Type*} (t : finset α) (i : ι) (g : α → M₁ i) (m : Π i, M₁ i): f (update m i (∑ a in t, g a)) = ∑ a in t, f (update m i (g a)) := begin induction t using finset.induction with a t has ih h, { simp }, { simp [finset.sum_insert has, ih] } end end apply_sum section restrict_scalar variables (R) {A : Type*} [semiring A] [has_scalar R A] [Π (i : ι), module A (M₁ i)] [module A M₂] [∀ i, is_scalar_tower R A (M₁ i)] [is_scalar_tower R A M₂] /-- Reinterpret an `A`-multilinear map as an `R`-multilinear map, if `A` is an algebra over `R` and their actions on all involved modules agree with the action of `R` on `A`. -/ def restrict_scalars (f : multilinear_map A M₁ M₂) : multilinear_map R M₁ M₂ := { to_fun := f, map_add' := f.map_add, map_smul' := λ m i, (f.to_linear_map m i).map_smul_of_tower } @[simp] lemma coe_restrict_scalars (f : multilinear_map A M₁ M₂) : ⇑(f.restrict_scalars R) = f := rfl end restrict_scalar section variables {ι₁ ι₂ ι₃ : Type*} [decidable_eq ι₁] [decidable_eq ι₂] [decidable_eq ι₃] /-- Transfer the arguments to a map along an equivalence between argument indices. The naming is derived from `finsupp.dom_congr`, noting that here the permutation applies to the domain of the domain. -/ @[simps apply] def dom_dom_congr (σ : ι₁ ≃ ι₂) (m : multilinear_map R (λ i : ι₁, M₂) M₃) : multilinear_map R (λ i : ι₂, M₂) M₃ := { to_fun := λ v, m (λ i, v (σ i)), map_add' := λ v i a b, by { simp_rw function.update_apply_equiv_apply v, rw m.map_add, }, map_smul' := λ v i a b, by { simp_rw function.update_apply_equiv_apply v, rw m.map_smul, }, } lemma dom_dom_congr_trans (σ₁ : ι₁ ≃ ι₂) (σ₂ : ι₂ ≃ ι₃) (m : multilinear_map R (λ i : ι₁, M₂) M₃) : m.dom_dom_congr (σ₁.trans σ₂) = (m.dom_dom_congr σ₁).dom_dom_congr σ₂ := rfl lemma dom_dom_congr_mul (σ₁ : equiv.perm ι₁) (σ₂ : equiv.perm ι₁) (m : multilinear_map R (λ i : ι₁, M₂) M₃) : m.dom_dom_congr (σ₂ * σ₁) = (m.dom_dom_congr σ₁).dom_dom_congr σ₂ := rfl /-- `multilinear_map.dom_dom_congr` as an equivalence. This is declared separately because it does not work with dot notation. -/ @[simps apply symm_apply] def dom_dom_congr_equiv (σ : ι₁ ≃ ι₂) : multilinear_map R (λ i : ι₁, M₂) M₃ ≃+ multilinear_map R (λ i : ι₂, M₂) M₃ := { to_fun := dom_dom_congr σ, inv_fun := dom_dom_congr σ.symm, left_inv := λ m, by {ext, simp}, right_inv := λ m, by {ext, simp}, map_add' := λ a b, by {ext, simp} } end end semiring end multilinear_map namespace linear_map variables [semiring R] [Πi, add_comm_monoid (M₁ i)] [add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_monoid M'] [∀i, module R (M₁ i)] [module R M₂] [module R M₃] [module R M'] /-- Composing a multilinear map with a linear map gives again a multilinear map. -/ def comp_multilinear_map (g : M₂ →ₗ[R] M₃) (f : multilinear_map R M₁ M₂) : multilinear_map R M₁ M₃ := { to_fun := g ∘ f, map_add' := λ m i x y, by simp, map_smul' := λ m i c x, by simp } @[simp] lemma coe_comp_multilinear_map (g : M₂ →ₗ[R] M₃) (f : multilinear_map R M₁ M₂) : ⇑(g.comp_multilinear_map f) = g ∘ f := rfl lemma comp_multilinear_map_apply (g : M₂ →ₗ[R] M₃) (f : multilinear_map R M₁ M₂) (m : Π i, M₁ i) : g.comp_multilinear_map f m = g (f m) := rfl variables {ι₁ ι₂ : Type*} [decidable_eq ι₁] [decidable_eq ι₂] @[simp] lemma comp_multilinear_map_dom_dom_congr (σ : ι₁ ≃ ι₂) (g : M₂ →ₗ[R] M₃) (f : multilinear_map R (λ i : ι₁, M') M₂) : (g.comp_multilinear_map f).dom_dom_congr σ = g.comp_multilinear_map (f.dom_dom_congr σ) := by { ext, simp } end linear_map namespace multilinear_map section comm_semiring variables [comm_semiring R] [∀i, add_comm_monoid (M₁ i)] [∀i, add_comm_monoid (M i)] [add_comm_monoid M₂] [∀i, module R (M i)] [∀i, module R (M₁ i)] [module R M₂] (f f' : multilinear_map R M₁ M₂) /-- If one multiplies by `c i` the coordinates in a finset `s`, then the image under a multilinear map is multiplied by `∏ i in s, c i`. This is mainly an auxiliary statement to prove the result when `s = univ`, given in `map_smul_univ`, although it can be useful in its own right as it does not require the index set `ι` to be finite. -/ lemma map_piecewise_smul (c : ι → R) (m : Πi, M₁ i) (s : finset ι) : f (s.piecewise (λi, c i • m i) m) = (∏ i in s, c i) • f m := begin refine s.induction_on (by simp) _, assume j s j_not_mem_s Hrec, have A : function.update (s.piecewise (λi, c i • m i) m) j (m j) = s.piecewise (λi, c i • m i) m, { ext i, by_cases h : i = j, { rw h, simp [j_not_mem_s] }, { simp [h] } }, rw [s.piecewise_insert, f.map_smul, A, Hrec], simp [j_not_mem_s, mul_smul] end /-- Multiplicativity of a multilinear map along all coordinates at the same time, writing `f (λi, c i • m i)` as `(∏ i, c i) • f m`. -/ lemma map_smul_univ [fintype ι] (c : ι → R) (m : Πi, M₁ i) : f (λi, c i • m i) = (∏ i, c i) • f m := by simpa using map_piecewise_smul f c m finset.univ section distrib_mul_action variables {R' A : Type*} [monoid R'] [semiring A] [Π i, module A (M₁ i)] [distrib_mul_action R' M₂] [module A M₂] [smul_comm_class A R' M₂] instance : has_scalar R' (multilinear_map A M₁ M₂) := ⟨λ c f, ⟨λ m, c • f m, λm i x y, by simp [smul_add], λl i x d, by simp [←smul_comm x c] ⟩⟩ @[simp] lemma smul_apply (f : multilinear_map A M₁ M₂) (c : R') (m : Πi, M₁ i) : (c • f) m = c • f m := rfl instance : distrib_mul_action R' (multilinear_map A M₁ M₂) := { one_smul := λ f, ext $ λ x, one_smul _ _, mul_smul := λ c₁ c₂ f, ext $ λ x, mul_smul _ _ _, smul_zero := λ r, ext $ λ x, smul_zero _, smul_add := λ r f₁ f₂, ext $ λ x, smul_add _ _ _ } end distrib_mul_action section module variables {R' A : Type*} [semiring R'] [semiring A] [Π i, module A (M₁ i)] [module A M₂] [add_comm_monoid M₃] [module R' M₃] [module A M₃] [smul_comm_class A R' M₃] /-- The space of multilinear maps over an algebra over `R` is a module over `R`, for the pointwise addition and scalar multiplication. -/ instance [module R' M₂] [smul_comm_class A R' M₂] : module R' (multilinear_map A M₁ M₂) := { add_smul := λ r₁ r₂ f, ext $ λ x, add_smul _ _ _, zero_smul := λ f, ext $ λ x, zero_smul _ _ } variables (M₂ M₃ R' A) /-- `multilinear_map.dom_dom_congr` as a `linear_equiv`. -/ @[simps apply symm_apply] def dom_dom_congr_linear_equiv {ι₁ ι₂} [decidable_eq ι₁] [decidable_eq ι₂] (σ : ι₁ ≃ ι₂) : multilinear_map A (λ i : ι₁, M₂) M₃ ≃ₗ[R'] multilinear_map A (λ i : ι₂, M₂) M₃ := { map_smul' := λ c f, by { ext, simp }, .. (dom_dom_congr_equiv σ : multilinear_map A (λ i : ι₁, M₂) M₃ ≃+ multilinear_map A (λ i : ι₂, M₂) M₃) } end module section dom_coprod open_locale tensor_product variables {ι₁ ι₂ ι₃ ι₄ : Type*} variables [decidable_eq ι₁] [decidable_eq ι₂][decidable_eq ι₃] [decidable_eq ι₄] variables {N₁ : Type*} [add_comm_monoid N₁] [module R N₁] variables {N₂ : Type*} [add_comm_monoid N₂] [module R N₂] variables {N : Type*} [add_comm_monoid N] [module R N] /-- Given two multilinear maps `(ι₁ → N) → N₁` and `(ι₂ → N) → N₂`, this produces the map `(ι₁ ⊕ ι₂ → N) → N₁ ⊗ N₂` by taking the coproduct of the domain and the tensor product of the codomain. This can be thought of as combining `equiv.sum_arrow_equiv_prod_arrow.symm` with `tensor_product.map`, noting that the two operations can't be separated as the intermediate result is not a `multilinear_map`. While this can be generalized to work for dependent `Π i : ι₁, N'₁ i` instead of `ι₁ → N`, doing so introduces `sum.elim N'₁ N'₂` types in the result which are difficult to work with and not defeq to the simple case defined here. See [this zulip thread]( https://leanprover.zulipchat.com/#narrow/stream/217875-Is-there.20code.20for.20X.3F/topic/Instances.20on.20.60sum.2Eelim.20A.20B.20i.60/near/218484619). -/ @[simps apply] def dom_coprod (a : multilinear_map R (λ _ : ι₁, N) N₁) (b : multilinear_map R (λ _ : ι₂, N) N₂) : multilinear_map R (λ _ : ι₁ ⊕ ι₂, N) (N₁ ⊗[R] N₂) := { to_fun := λ v, a (λ i, v (sum.inl i)) ⊗ₜ b (λ i, v (sum.inr i)), map_add' := λ v i p q, by cases i; simp [tensor_product.add_tmul, tensor_product.tmul_add], map_smul' := λ v i c p, by cases i; simp [tensor_product.smul_tmul', tensor_product.tmul_smul] } /-- A more bundled version of `multilinear_map.dom_coprod` that maps `((ι₁ → N) → N₁) ⊗ ((ι₂ → N) → N₂)` to `(ι₁ ⊕ ι₂ → N) → N₁ ⊗ N₂`. -/ def dom_coprod' : multilinear_map R (λ _ : ι₁, N) N₁ ⊗[R] multilinear_map R (λ _ : ι₂, N) N₂ →ₗ[R] multilinear_map R (λ _ : ι₁ ⊕ ι₂, N) (N₁ ⊗[R] N₂) := tensor_product.lift $ linear_map.mk₂ R (dom_coprod) (λ m₁ m₂ n, by { ext, simp only [dom_coprod_apply, tensor_product.add_tmul, add_apply] }) (λ c m n, by { ext, simp only [dom_coprod_apply, tensor_product.smul_tmul', smul_apply] }) (λ m n₁ n₂, by { ext, simp only [dom_coprod_apply, tensor_product.tmul_add, add_apply] }) (λ c m n, by { ext, simp only [dom_coprod_apply, tensor_product.tmul_smul, smul_apply] }) @[simp] lemma dom_coprod'_apply (a : multilinear_map R (λ _ : ι₁, N) N₁) (b : multilinear_map R (λ _ : ι₂, N) N₂) : dom_coprod' (a ⊗ₜ[R] b) = dom_coprod a b := rfl /-- When passed an `equiv.sum_congr`, `multilinear_map.dom_dom_congr` distributes over `multilinear_map.dom_coprod`. -/ lemma dom_coprod_dom_dom_congr_sum_congr (a : multilinear_map R (λ _ : ι₁, N) N₁) (b : multilinear_map R (λ _ : ι₂, N) N₂) (σa : ι₁ ≃ ι₃) (σb : ι₂ ≃ ι₄) : (a.dom_coprod b).dom_dom_congr (σa.sum_congr σb) = (a.dom_dom_congr σa).dom_coprod (b.dom_dom_congr σb) := rfl end dom_coprod section variables (R ι) (A : Type*) [comm_semiring A] [algebra R A] [fintype ι] /-- Given an `R`-algebra `A`, `mk_pi_algebra` is the multilinear map on `A^ι` associating to `m` the product of all the `m i`. See also `multilinear_map.mk_pi_algebra_fin` for a version that works with a non-commutative algebra `A` but requires `ι = fin n`. -/ protected def mk_pi_algebra : multilinear_map R (λ i : ι, A) A := { to_fun := λ m, ∏ i, m i, map_add' := λ m i x y, by simp [finset.prod_update_of_mem, add_mul], map_smul' := λ m i c x, by simp [finset.prod_update_of_mem] } variables {R A ι} @[simp] lemma mk_pi_algebra_apply (m : ι → A) : multilinear_map.mk_pi_algebra R ι A m = ∏ i, m i := rfl end section variables (R n) (A : Type*) [semiring A] [algebra R A] /-- Given an `R`-algebra `A`, `mk_pi_algebra_fin` is the multilinear map on `A^n` associating to `m` the product of all the `m i`. See also `multilinear_map.mk_pi_algebra` for a version that assumes `[comm_semiring A]` but works for `A^ι` with any finite type `ι`. -/ protected def mk_pi_algebra_fin : multilinear_map R (λ i : fin n, A) A := { to_fun := λ m, (list.of_fn m).prod, map_add' := begin intros m i x y, have : (list.fin_range n).index_of i < n, by simpa using list.index_of_lt_length.2 (list.mem_fin_range i), simp [list.of_fn_eq_map, (list.nodup_fin_range n).map_update, list.prod_update_nth, add_mul, this, mul_add, add_mul] end, map_smul' := begin intros m i c x, have : (list.fin_range n).index_of i < n, by simpa using list.index_of_lt_length.2 (list.mem_fin_range i), simp [list.of_fn_eq_map, (list.nodup_fin_range n).map_update, list.prod_update_nth, this] end } variables {R A n} @[simp] lemma mk_pi_algebra_fin_apply (m : fin n → A) : multilinear_map.mk_pi_algebra_fin R n A m = (list.of_fn m).prod := rfl lemma mk_pi_algebra_fin_apply_const (a : A) : multilinear_map.mk_pi_algebra_fin R n A (λ _, a) = a ^ n := by simp end /-- Given an `R`-multilinear map `f` taking values in `R`, `f.smul_right z` is the map sending `m` to `f m • z`. -/ def smul_right (f : multilinear_map R M₁ R) (z : M₂) : multilinear_map R M₁ M₂ := (linear_map.smul_right linear_map.id z).comp_multilinear_map f @[simp] lemma smul_right_apply (f : multilinear_map R M₁ R) (z : M₂) (m : Π i, M₁ i) : f.smul_right z m = f m • z := rfl variables (R ι) /-- The canonical multilinear map on `R^ι` when `ι` is finite, associating to `m` the product of all the `m i` (multiplied by a fixed reference element `z` in the target module). See also `mk_pi_algebra` for a more general version. -/ protected def mk_pi_ring [fintype ι] (z : M₂) : multilinear_map R (λ(i : ι), R) M₂ := (multilinear_map.mk_pi_algebra R ι R).smul_right z variables {R ι} @[simp] lemma mk_pi_ring_apply [fintype ι] (z : M₂) (m : ι → R) : (multilinear_map.mk_pi_ring R ι z : (ι → R) → M₂) m = (∏ i, m i) • z := rfl lemma mk_pi_ring_apply_one_eq_self [fintype ι] (f : multilinear_map R (λ(i : ι), R) M₂) : multilinear_map.mk_pi_ring R ι (f (λi, 1)) = f := begin ext m, have : m = (λi, m i • 1), by { ext j, simp }, conv_rhs { rw [this, f.map_smul_univ] }, refl end end comm_semiring section range_add_comm_group variables [semiring R] [∀i, add_comm_monoid (M₁ i)] [add_comm_group M₂] [∀i, module R (M₁ i)] [module R M₂] (f g : multilinear_map R M₁ M₂) instance : has_neg (multilinear_map R M₁ M₂) := ⟨λ f, ⟨λ m, - f m, λm i x y, by simp [add_comm], λm i c x, by simp⟩⟩ @[simp] lemma neg_apply (m : Πi, M₁ i) : (-f) m = - (f m) := rfl instance : has_sub (multilinear_map R M₁ M₂) := ⟨λ f g, ⟨λ m, f m - g m, λ m i x y, by { simp only [map_add, sub_eq_add_neg, neg_add], cc }, λ m i c x, by { simp only [map_smul, smul_sub] }⟩⟩ @[simp] lemma sub_apply (m : Πi, M₁ i) : (f - g) m = f m - g m := rfl instance : add_comm_group (multilinear_map R M₁ M₂) := by refine { zero := (0 : multilinear_map R M₁ M₂), add := (+), neg := has_neg.neg, sub := has_sub.sub, sub_eq_add_neg := _, nsmul := λ n f, ⟨λ m, n • f m, λm i x y, by simp [smul_add], λl i x d, by simp [←smul_comm x n] ⟩, gsmul := λ n f, ⟨λ m, n • f m, λm i x y, by simp [smul_add], λl i x d, by simp [←smul_comm x n] ⟩, gsmul_zero' := _, gsmul_succ' := _, gsmul_neg' := _, .. multilinear_map.add_comm_monoid, .. }; intros; ext; simp [add_comm, add_left_comm, sub_eq_add_neg, add_smul, nat.succ_eq_add_one] end range_add_comm_group section add_comm_group variables [semiring R] [∀i, add_comm_group (M₁ i)] [add_comm_group M₂] [∀i, module R (M₁ i)] [module R M₂] (f : multilinear_map R M₁ M₂) @[simp] lemma map_neg (m : Πi, M₁ i) (i : ι) (x : M₁ i) : f (update m i (-x)) = -f (update m i x) := eq_neg_of_add_eq_zero $ by rw [←map_add, add_left_neg, f.map_coord_zero i (update_same i 0 m)] @[simp] lemma map_sub (m : Πi, M₁ i) (i : ι) (x y : M₁ i) : f (update m i (x - y)) = f (update m i x) - f (update m i y) := by rw [sub_eq_add_neg, sub_eq_add_neg, map_add, map_neg] end add_comm_group section comm_semiring variables [comm_semiring R] [∀i, add_comm_monoid (M₁ i)] [add_comm_monoid M₂] [∀i, module R (M₁ i)] [module R M₂] /-- When `ι` is finite, multilinear maps on `R^ι` with values in `M₂` are in bijection with `M₂`, as such a multilinear map is completely determined by its value on the constant vector made of ones. We register this bijection as a linear equivalence in `multilinear_map.pi_ring_equiv`. -/ protected def pi_ring_equiv [fintype ι] : M₂ ≃ₗ[R] (multilinear_map R (λ(i : ι), R) M₂) := { to_fun := λ z, multilinear_map.mk_pi_ring R ι z, inv_fun := λ f, f (λi, 1), map_add' := λ z z', by { ext m, simp [smul_add] }, map_smul' := λ c z, by { ext m, simp [smul_smul, mul_comm] }, left_inv := λ z, by simp, right_inv := λ f, f.mk_pi_ring_apply_one_eq_self } end comm_semiring end multilinear_map section currying /-! ### Currying We associate to a multilinear map in `n+1` variables (i.e., based on `fin n.succ`) two curried functions, named `f.curry_left` (which is a linear map on `E 0` taking values in multilinear maps in `n` variables) and `f.curry_right` (wich is a multilinear map in `n` variables taking values in linear maps on `E 0`). In both constructions, the variable that is singled out is `0`, to take advantage of the operations `cons` and `tail` on `fin n`. The inverse operations are called `uncurry_left` and `uncurry_right`. We also register linear equiv versions of these correspondences, in `multilinear_curry_left_equiv` and `multilinear_curry_right_equiv`. -/ open multilinear_map variables {R M M₂} [comm_semiring R] [∀i, add_comm_monoid (M i)] [add_comm_monoid M'] [add_comm_monoid M₂] [∀i, module R (M i)] [module R M'] [module R M₂] /-! #### Left currying -/ /-- Given a linear map `f` from `M 0` to multilinear maps on `n` variables, construct the corresponding multilinear map on `n+1` variables obtained by concatenating the variables, given by `m ↦ f (m 0) (tail m)`-/ def linear_map.uncurry_left (f : M 0 →ₗ[R] (multilinear_map R (λ(i : fin n), M i.succ) M₂)) : multilinear_map R M M₂ := { to_fun := λm, f (m 0) (tail m), map_add' := λm i x y, begin by_cases h : i = 0, { subst i, rw [update_same, update_same, update_same, f.map_add, add_apply, tail_update_zero, tail_update_zero, tail_update_zero] }, { rw [update_noteq (ne.symm h), update_noteq (ne.symm h), update_noteq (ne.symm h)], revert x y, rw ← succ_pred i h, assume x y, rw [tail_update_succ, map_add, tail_update_succ, tail_update_succ] } end, map_smul' := λm i c x, begin by_cases h : i = 0, { subst i, rw [update_same, update_same, tail_update_zero, tail_update_zero, ← smul_apply, f.map_smul] }, { rw [update_noteq (ne.symm h), update_noteq (ne.symm h)], revert x, rw ← succ_pred i h, assume x, rw [tail_update_succ, tail_update_succ, map_smul] } end } @[simp] lemma linear_map.uncurry_left_apply (f : M 0 →ₗ[R] (multilinear_map R (λ(i : fin n), M i.succ) M₂)) (m : Πi, M i) : f.uncurry_left m = f (m 0) (tail m) := rfl /-- Given a multilinear map `f` in `n+1` variables, split the first variable to obtain a linear map into multilinear maps in `n` variables, given by `x ↦ (m ↦ f (cons x m))`. -/ def multilinear_map.curry_left (f : multilinear_map R M M₂) : M 0 →ₗ[R] (multilinear_map R (λ(i : fin n), M i.succ) M₂) := { to_fun := λx, { to_fun := λm, f (cons x m), map_add' := λm i y y', by simp, map_smul' := λm i y c, by simp }, map_add' := λx y, by { ext m, exact cons_add f m x y }, map_smul' := λc x, by { ext m, exact cons_smul f m c x } } @[simp] lemma multilinear_map.curry_left_apply (f : multilinear_map R M M₂) (x : M 0) (m : Π(i : fin n), M i.succ) : f.curry_left x m = f (cons x m) := rfl @[simp] lemma linear_map.curry_uncurry_left (f : M 0 →ₗ[R] (multilinear_map R (λ(i : fin n), M i.succ) M₂)) : f.uncurry_left.curry_left = f := begin ext m x, simp only [tail_cons, linear_map.uncurry_left_apply, multilinear_map.curry_left_apply], rw cons_zero end @[simp] lemma multilinear_map.uncurry_curry_left (f : multilinear_map R M M₂) : f.curry_left.uncurry_left = f := by { ext m, simp, } variables (R M M₂) /-- The space of multilinear maps on `Π(i : fin (n+1)), M i` is canonically isomorphic to the space of linear maps from `M 0` to the space of multilinear maps on `Π(i : fin n), M i.succ `, by separating the first variable. We register this isomorphism as a linear isomorphism in `multilinear_curry_left_equiv R M M₂`. The direct and inverse maps are given by `f.uncurry_left` and `f.curry_left`. Use these unless you need the full framework of linear equivs. -/ def multilinear_curry_left_equiv : (M 0 →ₗ[R] (multilinear_map R (λ(i : fin n), M i.succ) M₂)) ≃ₗ[R] (multilinear_map R M M₂) := { to_fun := linear_map.uncurry_left, map_add' := λf₁ f₂, by { ext m, refl }, map_smul' := λc f, by { ext m, refl }, inv_fun := multilinear_map.curry_left, left_inv := linear_map.curry_uncurry_left, right_inv := multilinear_map.uncurry_curry_left } variables {R M M₂} /-! #### Right currying -/ /-- Given a multilinear map `f` in `n` variables to the space of linear maps from `M (last n)` to `M₂`, construct the corresponding multilinear map on `n+1` variables obtained by concatenating the variables, given by `m ↦ f (init m) (m (last n))`-/ def multilinear_map.uncurry_right (f : (multilinear_map R (λ(i : fin n), M i.cast_succ) (M (last n) →ₗ[R] M₂))) : multilinear_map R M M₂ := { to_fun := λm, f (init m) (m (last n)), map_add' := λm i x y, begin by_cases h : i.val < n, { have : last n ≠ i := ne.symm (ne_of_lt h), rw [update_noteq this, update_noteq this, update_noteq this], revert x y, rw [(cast_succ_cast_lt i h).symm], assume x y, rw [init_update_cast_succ, map_add, init_update_cast_succ, init_update_cast_succ, linear_map.add_apply] }, { revert x y, rw eq_last_of_not_lt h, assume x y, rw [init_update_last, init_update_last, init_update_last, update_same, update_same, update_same, linear_map.map_add] } end, map_smul' := λm i c x, begin by_cases h : i.val < n, { have : last n ≠ i := ne.symm (ne_of_lt h), rw [update_noteq this, update_noteq this], revert x, rw [(cast_succ_cast_lt i h).symm], assume x, rw [init_update_cast_succ, init_update_cast_succ, map_smul, linear_map.smul_apply] }, { revert x, rw eq_last_of_not_lt h, assume x, rw [update_same, update_same, init_update_last, init_update_last, linear_map.map_smul] } end } @[simp] lemma multilinear_map.uncurry_right_apply (f : (multilinear_map R (λ(i : fin n), M i.cast_succ) ((M (last n)) →ₗ[R] M₂))) (m : Πi, M i) : f.uncurry_right m = f (init m) (m (last n)) := rfl /-- Given a multilinear map `f` in `n+1` variables, split the last variable to obtain a multilinear map in `n` variables taking values in linear maps from `M (last n)` to `M₂`, given by `m ↦ (x ↦ f (snoc m x))`. -/ def multilinear_map.curry_right (f : multilinear_map R M M₂) : multilinear_map R (λ(i : fin n), M (fin.cast_succ i)) ((M (last n)) →ₗ[R] M₂) := { to_fun := λm, { to_fun := λx, f (snoc m x), map_add' := λx y, by rw f.snoc_add, map_smul' := λc x, by rw f.snoc_smul }, map_add' := λm i x y, begin ext z, change f (snoc (update m i (x + y)) z) = f (snoc (update m i x) z) + f (snoc (update m i y) z), rw [snoc_update, snoc_update, snoc_update, f.map_add] end, map_smul' := λm i c x, begin ext z, change f (snoc (update m i (c • x)) z) = c • f (snoc (update m i x) z), rw [snoc_update, snoc_update, f.map_smul] end } @[simp] lemma multilinear_map.curry_right_apply (f : multilinear_map R M M₂) (m : Π(i : fin n), M i.cast_succ) (x : M (last n)) : f.curry_right m x = f (snoc m x) := rfl @[simp] lemma multilinear_map.curry_uncurry_right (f : (multilinear_map R (λ(i : fin n), M i.cast_succ) ((M (last n)) →ₗ[R] M₂))) : f.uncurry_right.curry_right = f := begin ext m x, simp only [snoc_last, multilinear_map.curry_right_apply, multilinear_map.uncurry_right_apply], rw init_snoc end @[simp] lemma multilinear_map.uncurry_curry_right (f : multilinear_map R M M₂) : f.curry_right.uncurry_right = f := by { ext m, simp } variables (R M M₂) /-- The space of multilinear maps on `Π(i : fin (n+1)), M i` is canonically isomorphic to the space of linear maps from the space of multilinear maps on `Π(i : fin n), M i.cast_succ` to the space of linear maps on `M (last n)`, by separating the last variable. We register this isomorphism as a linear isomorphism in `multilinear_curry_right_equiv R M M₂`. The direct and inverse maps are given by `f.uncurry_right` and `f.curry_right`. Use these unless you need the full framework of linear equivs. -/ def multilinear_curry_right_equiv : (multilinear_map R (λ(i : fin n), M i.cast_succ) ((M (last n)) →ₗ[R] M₂)) ≃ₗ[R] (multilinear_map R M M₂) := { to_fun := multilinear_map.uncurry_right, map_add' := λf₁ f₂, by { ext m, refl }, map_smul' := λc f, by { ext m, rw [smul_apply], refl }, inv_fun := multilinear_map.curry_right, left_inv := multilinear_map.curry_uncurry_right, right_inv := multilinear_map.uncurry_curry_right } namespace multilinear_map variables {ι' : Type*} [decidable_eq ι'] [decidable_eq (ι ⊕ ι')] {R M₂} /-- A multilinear map on `Π i : ι ⊕ ι', M'` defines a multilinear map on `Π i : ι, M'` taking values in the space of multilinear maps on `Π i : ι', M'`. -/ def curry_sum (f : multilinear_map R (λ x : ι ⊕ ι', M') M₂) : multilinear_map R (λ x : ι, M') (multilinear_map R (λ x : ι', M') M₂) := { to_fun := λ u, { to_fun := λ v, f (sum.elim u v), map_add' := λ v i x y, by simp only [← sum.update_elim_inr, f.map_add], map_smul' := λ v i c x, by simp only [← sum.update_elim_inr, f.map_smul] }, map_add' := λ u i x y, ext $ λ v, by simp only [multilinear_map.coe_mk, add_apply, ← sum.update_elim_inl, f.map_add], map_smul' := λ u i c x, ext $ λ v, by simp only [multilinear_map.coe_mk, smul_apply, ← sum.update_elim_inl, f.map_smul] } @[simp] lemma curry_sum_apply (f : multilinear_map R (λ x : ι ⊕ ι', M') M₂) (u : ι → M') (v : ι' → M') : f.curry_sum u v = f (sum.elim u v) := rfl /-- A multilinear map on `Π i : ι, M'` taking values in the space of multilinear maps on `Π i : ι', M'` defines a multilinear map on `Π i : ι ⊕ ι', M'`. -/ def uncurry_sum (f : multilinear_map R (λ x : ι, M') (multilinear_map R (λ x : ι', M') M₂)) : multilinear_map R (λ x : ι ⊕ ι', M') M₂ := { to_fun := λ u, f (u ∘ sum.inl) (u ∘ sum.inr), map_add' := λ u i x y, by cases i; simp only [map_add, add_apply, sum.update_inl_comp_inl, sum.update_inl_comp_inr, sum.update_inr_comp_inl, sum.update_inr_comp_inr], map_smul' := λ u i c x, by cases i; simp only [map_smul, smul_apply, sum.update_inl_comp_inl, sum.update_inl_comp_inr, sum.update_inr_comp_inl, sum.update_inr_comp_inr] } @[simp] lemma uncurry_sum_aux_apply (f : multilinear_map R (λ x : ι, M') (multilinear_map R (λ x : ι', M') M₂)) (u : ι ⊕ ι' → M') : f.uncurry_sum u = f (u ∘ sum.inl) (u ∘ sum.inr) := rfl variables (ι ι' R M₂ M') /-- Linear equivalence between the space of multilinear maps on `Π i : ι ⊕ ι', M'` and the space of multilinear maps on `Π i : ι, M'` taking values in the space of multilinear maps on `Π i : ι', M'`. -/ def curry_sum_equiv : multilinear_map R (λ x : ι ⊕ ι', M') M₂ ≃ₗ[R] multilinear_map R (λ x : ι, M') (multilinear_map R (λ x : ι', M') M₂) := { to_fun := curry_sum, inv_fun := uncurry_sum, left_inv := λ f, ext $ λ u, by simp, right_inv := λ f, by { ext, simp }, map_add' := λ f g, by { ext, refl }, map_smul' := λ c f, by { ext, refl } } variables {ι ι' R M₂ M'} @[simp] lemma coe_curry_sum_equiv : ⇑(curry_sum_equiv R ι M₂ M' ι') = curry_sum := rfl @[simp] lemma coe_curr_sum_equiv_symm : ⇑(curry_sum_equiv R ι M₂ M' ι').symm = uncurry_sum := rfl variables (R M₂ M') /-- If `s : finset (fin n)` is a finite set of cardinality `k` and its complement has cardinality `l`, then the space of multilinear maps on `λ i : fin n, M'` is isomorphic to the space of multilinear maps on `λ i : fin k, M'` taking values in the space of multilinear maps on `λ i : fin l, M'`. -/ def curry_fin_finset {k l n : ℕ} {s : finset (fin n)} (hk : s.card = k) (hl : sᶜ.card = l) : multilinear_map R (λ x : fin n, M') M₂ ≃ₗ[R] multilinear_map R (λ x : fin k, M') (multilinear_map R (λ x : fin l, M') M₂) := (dom_dom_congr_linear_equiv M' M₂ R R (fin_sum_equiv_of_finset hk hl).symm).trans (curry_sum_equiv R (fin k) M₂ M' (fin l)) variables {R M₂ M'} @[simp] lemma curry_fin_finset_apply {k l n : ℕ} {s : finset (fin n)} (hk : s.card = k) (hl : sᶜ.card = l) (f : multilinear_map R (λ x : fin n, M') M₂) (mk : fin k → M') (ml : fin l → M') : curry_fin_finset R M₂ M' hk hl f mk ml = f (λ i, sum.elim mk ml ((fin_sum_equiv_of_finset hk hl).symm i)) := rfl @[simp] lemma curry_fin_finset_symm_apply {k l n : ℕ} {s : finset (fin n)} (hk : s.card = k) (hl : sᶜ.card = l) (f : multilinear_map R (λ x : fin k, M') (multilinear_map R (λ x : fin l, M') M₂)) (m : fin n → M') : (curry_fin_finset R M₂ M' hk hl).symm f m = f (λ i, m $ fin_sum_equiv_of_finset hk hl (sum.inl i)) (λ i, m $ fin_sum_equiv_of_finset hk hl (sum.inr i)) := rfl @[simp] lemma curry_fin_finset_symm_apply_piecewise_const {k l n : ℕ} {s : finset (fin n)} (hk : s.card = k) (hl : sᶜ.card = l) (f : multilinear_map R (λ x : fin k, M') (multilinear_map R (λ x : fin l, M') M₂)) (x y : M') : (curry_fin_finset R M₂ M' hk hl).symm f (s.piecewise (λ _, x) (λ _, y)) = f (λ _, x) (λ _, y) := begin rw curry_fin_finset_symm_apply, congr, { ext i, rw [fin_sum_equiv_of_finset_inl, finset.piecewise_eq_of_mem], apply finset.order_emb_of_fin_mem }, { ext i, rw [fin_sum_equiv_of_finset_inr, finset.piecewise_eq_of_not_mem], exact finset.mem_compl.1 (finset.order_emb_of_fin_mem _ _ _) } end @[simp] lemma curry_fin_finset_symm_apply_const {k l n : ℕ} {s : finset (fin n)} (hk : s.card = k) (hl : sᶜ.card = l) (f : multilinear_map R (λ x : fin k, M') (multilinear_map R (λ x : fin l, M') M₂)) (x : M') : (curry_fin_finset R M₂ M' hk hl).symm f (λ _, x) = f (λ _, x) (λ _, x) := rfl @[simp] lemma curry_fin_finset_apply_const {k l n : ℕ} {s : finset (fin n)} (hk : s.card = k) (hl : sᶜ.card = l) (f : multilinear_map R (λ x : fin n, M') M₂) (x y : M') : curry_fin_finset R M₂ M' hk hl f (λ _, x) (λ _, y) = f (s.piecewise (λ _, x) (λ _, y)) := begin refine (curry_fin_finset_symm_apply_piecewise_const hk hl _ _ _).symm.trans _, -- `rw` fails rw linear_equiv.symm_apply_apply end end multilinear_map end currying section submodule variables {R M M₂} [ring R] [∀i, add_comm_monoid (M₁ i)] [add_comm_monoid M'] [add_comm_monoid M₂] [∀i, module R (M₁ i)] [module R M'] [module R M₂] namespace multilinear_map /-- The pushforward of an indexed collection of submodule `p i ⊆ M₁ i` by `f : M₁ → M₂`. Note that this is not a submodule - it is not closed under addition. -/ def map [nonempty ι] (f : multilinear_map R M₁ M₂) (p : Π i, submodule R (M₁ i)) : sub_mul_action R M₂ := { carrier := f '' { v | ∀ i, v i ∈ p i}, smul_mem' := λ c _ ⟨x, hx, hf⟩, let ⟨i⟩ := ‹nonempty ι› in by { refine ⟨update x i (c • x i), λ j, if hij : j = i then _ else _, hf ▸ _⟩, { rw [hij, update_same], exact (p i).smul_mem _ (hx i) }, { rw [update_noteq hij], exact hx j }, { rw [f.map_smul, update_eq_self] } } } /-- The map is always nonempty. This lemma is needed to apply `sub_mul_action.zero_mem`. -/ lemma map_nonempty [nonempty ι] (f : multilinear_map R M₁ M₂) (p : Π i, submodule R (M₁ i)) : (map f p : set M₂).nonempty := ⟨f 0, 0, λ i, (p i).zero_mem, rfl⟩ /-- The range of a multilinear map, closed under scalar multiplication. -/ def range [nonempty ι] (f : multilinear_map R M₁ M₂) : sub_mul_action R M₂ := f.map (λ i, ⊤) end multilinear_map end submodule
2778f1fcac3b426df3ac155691b6e5467a47569c
367134ba5a65885e863bdc4507601606690974c1
/src/analysis/quaternion.lean
31621e0082334ae01e475787ba4ec31c5bac3ff5
[ "Apache-2.0" ]
permissive
kodyvajjha/mathlib
9bead00e90f68269a313f45f5561766cfd8d5cad
b98af5dd79e13a38d84438b850a2e8858ec21284
refs/heads/master
1,624,350,366,310
1,615,563,062,000
1,615,563,062,000
162,666,963
0
0
Apache-2.0
1,545,367,651,000
1,545,367,651,000
null
UTF-8
Lean
false
false
3,367
lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import data.quaternion import analysis.normed_space.inner_product /-! # Quaternions as a normed algebra In this file we define the following structures on the space `ℍ := ℍ[ℝ]` of quaternions: * inner product space; * normed ring; * normed space over `ℝ`. ## Notation The following notation is available with `open_locale quaternion`: * `ℍ` : quaternions ## Tags quaternion, normed ring, normed space, normed algebra -/ localized "notation `ℍ` := quaternion ℝ" in quaternion open_locale real_inner_product_space noncomputable theory namespace quaternion instance : has_inner ℝ ℍ := ⟨λ a b, (a * b.conj).re⟩ lemma inner_self (a : ℍ) : ⟪a, a⟫ = norm_sq a := rfl lemma inner_def (a b : ℍ) : ⟪a, b⟫ = (a * b.conj).re := rfl instance : inner_product_space ℝ ℍ := inner_product_space.of_core { inner := has_inner.inner, conj_sym := λ x y, by simp [inner_def, mul_comm], nonneg_re := λ x, norm_sq_nonneg, definite := λ x, norm_sq_eq_zero.1, add_left := λ x y z, by simp only [inner_def, add_mul, add_re], smul_left := λ x y r, by simp [inner_def] } lemma norm_sq_eq_norm_square (a : ℍ) : norm_sq a = ∥a∥ * ∥a∥ := by rw [← inner_self, real_inner_self_eq_norm_square] instance : norm_one_class ℍ := ⟨by rw [norm_eq_sqrt_real_inner, inner_self, norm_sq.map_one, real.sqrt_one]⟩ @[simp] lemma norm_mul (a b : ℍ) : ∥a * b∥ = ∥a∥ * ∥b∥ := begin simp only [norm_eq_sqrt_real_inner, inner_self, norm_sq.map_mul], exact real.sqrt_mul norm_sq_nonneg _ end @[simp, norm_cast] lemma norm_coe (a : ℝ) : ∥(a : ℍ)∥ = ∥a∥ := by rw [norm_eq_sqrt_real_inner, inner_self, norm_sq_coe, real.sqrt_sqr_eq_abs, real.norm_eq_abs] noncomputable instance : normed_ring ℍ := { dist_eq := λ _ _, rfl, norm_mul := λ a b, (norm_mul a b).le } noncomputable instance : normed_algebra ℝ ℍ := { norm_algebra_map_eq := norm_coe, to_algebra := quaternion.algebra } instance : has_coe ℂ ℍ := ⟨λ z, ⟨z.re, z.im, 0, 0⟩⟩ @[simp, norm_cast] lemma coe_complex_re (z : ℂ) : (z : ℍ).re = z.re := rfl @[simp, norm_cast] lemma coe_complex_im_i (z : ℂ) : (z : ℍ).im_i = z.im := rfl @[simp, norm_cast] lemma coe_complex_im_j (z : ℂ) : (z : ℍ).im_j = 0 := rfl @[simp, norm_cast] lemma coe_complex_im_k (z : ℂ) : (z : ℍ).im_k = 0 := rfl @[simp, norm_cast] lemma coe_complex_add (z w : ℂ) : ↑(z + w) = (z + w : ℍ) := by ext; simp @[simp, norm_cast] lemma coe_complex_mul (z w : ℂ) : ↑(z * w) = (z * w : ℍ) := by ext; simp @[simp, norm_cast] lemma coe_complex_zero : ((0 : ℂ) : ℍ) = 0 := rfl @[simp, norm_cast] lemma coe_complex_one : ((1 : ℂ) : ℍ) = 1 := rfl @[simp, norm_cast] lemma coe_real_complex_mul (r : ℝ) (z : ℂ) : (r • z : ℍ) = ↑r * ↑z := by ext; simp @[simp, norm_cast] lemma coe_complex_coe (r : ℝ) : ((r : ℂ) : ℍ) = r := rfl /-- Coercion `ℂ →ₐ[ℝ] ℍ` as an algebra homomorphism. -/ def of_complex : ℂ →ₐ[ℝ] ℍ := { to_fun := coe, map_one' := rfl, map_zero' := rfl, map_add' := coe_complex_add, map_mul' := coe_complex_mul, commutes' := λ x, rfl } @[simp] lemma coe_of_complex : ⇑of_complex = coe := rfl end quaternion
0afa40650d1d9d045df4326131b4f2a75e23a28e
92bfaf170880e47d55bf51d5a782fffd76db2f5f
/melting_point/naive.lean
1575f00836b35e060bc7efd0c037302ae14bd246
[]
no_license
forked-from-1kasper/melting_point
d33403e1985d876a2c7c06859962cc0c37570189
e5ea4a0917de086b7e5b122e8d5aa90d2761d147
refs/heads/master
1,624,785,375,577
1,618,305,367,000
1,618,305,367,000
222,729,018
2
0
null
null
null
null
UTF-8
Lean
false
false
6,642
lean
-- Naive set theory noncomputable theory open classical axiom ens : Type namespace ens axiom contains : ens → ens → Prop instance : has_mem ens ens := ⟨contains⟩ axiom comp : (ens → Prop) → ens @[simp] axiom compβrule : Π (φ : ens → Prop) (x : ens), (x ∈ comp φ) = φ x axiom setext.intro : ∀ {α β : ens}, (∀ x, x ∈ α ↔ x ∈ β) → α = β def setext.elim {α β : ens} : α = β → (∀ x, x ∈ α ↔ x ∈ β) := begin intro p, induction p, intro x, apply iff.refl end def setext {α β : ens} : (∀ x, x ∈ α ↔ x ∈ β) ↔ (α = β) := ⟨setext.intro, setext.elim⟩ def spec (f : ens → ens) := comp (λ y, ∃ x, f x = y) def map (α β : ens) (f : ens → ens) := comp (λ y, ∃ x, x ∈ α ∧ y ∈ β ∧ f x = y) def bimap (α β : ens) (f : ens → ens → ens) := comp (λ x, ∃ u v, u ∈ α ∧ v ∈ β ∧ x = f u v) def empty := comp (λ _, false) theorem {u} empty.elim {α : Sort u} {β : ens} : β ∈ empty → α := begin intro p, simp [empty] at p, induction p end def univ : ens := comp (λ _, true) def insert (x : ens) (α : ens) := comp (λ y, x = y ∨ y ∈ α) instance : has_insert ens ens := ⟨insert⟩ def sep (p : ens → Prop) (s : ens) := comp (λ x, x ∈ s ∧ p x) instance : has_sep ens ens := ⟨sep⟩ @[simp] def insertβrule (x y : ens) (α : ens) : (x ∈ insert y α) = (y = x ∨ x ∈ α) := by simp [insert] def union (α β : ens) := comp (λ x, x ∈ α ∨ x ∈ β) def diff (α β : ens) := {x ∈ α | x ∉ β} def inter (α β : ens) : ens := {x ∈ α | x ∈ β} def subset (α β : ens) := ∀ x, x ∈ α → x ∈ β def compl (α : ens) := comp (λ x, x ∉ α) instance : has_emptyc ens := ⟨empty⟩ instance : has_union ens := ⟨union⟩ instance : has_inter ens := ⟨inter⟩ instance : has_subset ens := ⟨subset⟩ instance : has_neg ens := ⟨compl⟩ instance : has_sdiff ens := ⟨diff⟩ instance : has_singleton ens ens := ⟨λ x, insert x ∅⟩ def singleton.id {α : ens} : α ∈ (singleton α : ens) := by simp [singleton, has_insert.insert] def sUnion (α : ens) : ens := comp (λ t, ∃ x ∈ α, t ∈ x) prefix ⋃₀ := sUnion def powerset (α : ens) := comp (⊆ α) prefix `𝒫` := powerset def unord (α β : ens) : ens := {α, β} def pair (α β : ens) : ens := {{α}, {α, β}} def prod (α β : ens) : ens := bimap α β pair local infix × := prod def prod.intro {α β x y : ens} : x ∈ α → y ∈ β → pair x y ∈ (α × β) := begin intros h g, simp [pair, prod, bimap], existsi x, existsi y, split, exact h, split, exact g, trivial end lemma unord.left {α β : ens} : α ∈ unord α β := begin simp [unord, has_insert.insert, singleton] end lemma unord.right {α β : ens} : β ∈ unord α β := begin simp [unord, has_insert.insert], right, simp [has_singleton.singleton, insertβrule] end def singleton.eq {α β : ens} : @eq ens {α} {β} → α = β := begin intro p, have q := (setext.elim p α).mp singleton.id, simp [singleton, has_insert.insert] at q, induction q, { symmetry, assumption }, { apply empty.elim q } end def unord.eq {α β α' β' : ens} : unord α β = unord α' β' → (α = α' ∧ β = β') ∨ (α = β' ∧ β = α') := begin intro x, have p := (setext.elim x α).mp unord.left, have q := (setext.elim x β).mp unord.right, have r := (setext.elim x α').mpr unord.left, have s := (setext.elim x β').mpr unord.right, simp [unord, has_insert.insert, singleton] at p q r s, repeat { induction p <|> induction q <|> induction r <|> induction s }, repeat { { left, split; refl } <|> { right, split; refl } <|> { apply empty.elim, assumption } } end def pair.eq {α β α' β' : ens} : pair α β = pair α' β' → α = α' ∧ β = β' := begin intro p, simp [pair] at p, cases unord.eq p with q, { induction q with u v, have q := singleton.eq u, split, { assumption }, { cases unord.eq v with x y, { cases x, assumption }, { cases y with r s, transitivity, exact s, transitivity, symmetry, exact q, exact r } } }, { induction h with r s, split, { have q := (setext.elim r α').mpr unord.left, simp [singleton, has_insert.insert] at q, induction q, assumption, apply empty.elim q }, { have a := (setext.elim r β').mpr unord.right, have b := (setext.elim s β).mp unord.right, have c := (setext.elim r α').mpr unord.left, simp [singleton, has_insert.insert, has_emptyc.emptyc, empty] at a b c, transitivity, { symmetry, exact b }, transitivity, { symmetry, exact c }, exact a } } end structure function (α β : ens) := (map : ens) (sub : map ⊆ (α × β)) (uniq : ∀ (u ∈ α), ∃! (v ∈ β), pair u v ∈ map) infix ` ⟶ `:30 := function def function.intro {α β : ens} (f : ens → ens) (cod : ∀ x, f x ∈ β) : α ⟶ β := ⟨map α (α × β) (λ x, pair x (f x)), begin intros y p, simp [map] at p, induction p with x p, induction p with u p, induction p with v p, exact v end, begin intros u p, existsi f u, split, { simp [map], existsi cod u, split, existsi u, split, exact p, split, apply prod.intro, exact p, exact cod u, trivial, { intros G H, trivial } }, { intros x q, induction q with x q, induction q with q r, simp [map] at q, induction q with y q, induction q with a q, induction q with b q, have s := pair.eq q, induction s with s₁ s₂, symmetry, induction s₁, assumption } end⟩ def une : ens := {∅} notation `𝟙` := une def bool : ens := {∅, 𝟙} def not : bool ⟶ bool := function.intro (λ x, match prop_decidable (x = ∅) with | is_true _ := 𝟙 | is_false _ := ∅ end) (begin intro x, simp [bool, has_insert.insert], induction prop_decidable (x = ∅), { left, trivial }, { right, apply singleton.id } end) lemma univ_in_univ : univ ∈ univ := by simp [univ] def R : ens := comp (λ x, x ∉ x) def Russell : R ∈ R ↔ R ∉ R := begin unfold R, split; intro H, { rw [compβrule] at H, assumption }, { rw [compβrule], assumption } end -- la fin def falso : false := match prop_decidable (R ∈ R) with | is_true h := absurd h (Russell.mp h) | is_false h := absurd (Russell.mpr h) h end end ens
cc8e7a2c1cfbc492f3a45b4873e190bd8e09656c
05f637fa14ac28031cb1ea92086a0f4eb23ff2b1
/tests/lean/env_errors.lean
bb38e0d41fbeb385929af7b686703b4a2098a0cd
[ "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
374
lean
variable x : Nat set_opaque x true. print "before import" (* local env = get_environment() env:import("tstblafoo.lean") *) print "before load1" (* local env = get_environment() env:load("tstblafoo.lean") *) print "before load2" (* local env = get_environment() env:load("fake1.olean") *) print "before load3" (* local env = get_environment() env:load("fake2.olean") *)
29879f7aa76f22a5136f0cb312fe26560cac90ed
9dc8cecdf3c4634764a18254e94d43da07142918
/src/field_theory/primitive_element.lean
0b0f3776da526374d89ec825d52864794d66f58e
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
8,802
lean
/- Copyright (c) 2020 Thomas Browning, Patrick Lutz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Thomas Browning, Patrick Lutz -/ import field_theory.adjoin import field_theory.fixed import field_theory.is_alg_closed.basic import field_theory.separable import ring_theory.integral_domain /-! # Primitive Element Theorem In this file we prove the primitive element theorem. ## Main results - `exists_primitive_element`: a finite separable extension `E / F` has a primitive element, i.e. there is an `α : E` such that `F⟮α⟯ = (⊤ : subalgebra F E)`. ## Implementation notes In declaration names, `primitive_element` abbreviates `adjoin_simple_eq_top`: it stands for the statement `F⟮α⟯ = (⊤ : subalgebra F E)`. We did not add an extra declaration `is_primitive_element F α := F⟮α⟯ = (⊤ : subalgebra F E)` because this requires more unfolding without much obvious benefit. ## Tags primitive element, separable field extension, separable extension, intermediate field, adjoin, exists_adjoin_simple_eq_top -/ noncomputable theory open_locale classical polynomial open finite_dimensional polynomial intermediate_field namespace field section primitive_element_finite variables (F : Type*) [field F] (E : Type*) [field E] [algebra F E] /-! ### Primitive element theorem for finite fields -/ /-- **Primitive element theorem** assuming E is finite. -/ lemma exists_primitive_element_of_finite_top [finite E] : ∃ α : E, F⟮α⟯ = ⊤ := begin obtain ⟨α, hα⟩ := is_cyclic.exists_generator (units E), use α, apply eq_top_iff.mpr, rintros x -, by_cases hx : x = 0, { rw hx, exact F⟮α.val⟯.zero_mem }, { obtain ⟨n, hn⟩ := set.mem_range.mp (hα (units.mk0 x hx)), rw (show x = α^n, by { norm_cast, rw [hn, units.coe_mk0] }), exact zpow_mem (mem_adjoin_simple_self F ↑α) n, }, end /-- Primitive element theorem for finite dimensional extension of a finite field. -/ theorem exists_primitive_element_of_finite_bot [finite F] [finite_dimensional F E] : ∃ α : E, F⟮α⟯ = ⊤ := begin haveI : finite E := finite_of_finite F E, exact exists_primitive_element_of_finite_top F E end end primitive_element_finite /-! ### Primitive element theorem for infinite fields -/ section primitive_element_inf variables {F : Type*} [field F] [infinite F] {E : Type*} [field E] (ϕ : F →+* E) (α β : E) lemma primitive_element_inf_aux_exists_c (f g : F[X]) : ∃ c : F, ∀ (α' ∈ (f.map ϕ).roots) (β' ∈ (g.map ϕ).roots), -(α' - α)/(β' - β) ≠ ϕ c := begin let sf := (f.map ϕ).roots, let sg := (g.map ϕ).roots, let s := (sf.bind (λ α', sg.map (λ β', -(α' - α) / (β' - β)))).to_finset, let s' := s.preimage ϕ (λ x hx y hy h, ϕ.injective h), obtain ⟨c, hc⟩ := infinite.exists_not_mem_finset s', simp_rw [finset.mem_preimage, multiset.mem_to_finset, multiset.mem_bind, multiset.mem_map] at hc, push_neg at hc, exact ⟨c, hc⟩, end variables (F) [algebra F E] -- This is the heart of the proof of the primitive element theorem. It shows that if `F` is -- infinite and `α` and `β` are separable over `F` then `F⟮α, β⟯` is generated by a single element. lemma primitive_element_inf_aux [is_separable F E] : ∃ γ : E, F⟮α, β⟯ = F⟮γ⟯ := begin have hα := is_separable.is_integral F α, have hβ := is_separable.is_integral F β, let f := minpoly F α, let g := minpoly F β, let ιFE := algebra_map F E, let ιEE' := algebra_map E (splitting_field (g.map ιFE)), obtain ⟨c, hc⟩ := primitive_element_inf_aux_exists_c (ιEE'.comp ιFE) (ιEE' α) (ιEE' β) f g, let γ := α + c • β, suffices β_in_Fγ : β ∈ F⟮γ⟯, { use γ, apply le_antisymm, { rw adjoin_le_iff, have α_in_Fγ : α ∈ F⟮γ⟯, { rw ← add_sub_cancel α (c • β), exact F⟮γ⟯.sub_mem (mem_adjoin_simple_self F γ) (F⟮γ⟯.to_subalgebra.smul_mem β_in_Fγ c) }, exact λ x hx, by cases hx; cases hx; cases hx; assumption }, { rw [adjoin_simple_le_iff], have α_in_Fαβ : α ∈ F⟮α, β⟯ := subset_adjoin F {α, β} (set.mem_insert α {β}), have β_in_Fαβ : β ∈ F⟮α, β⟯ := subset_adjoin F {α, β} (set.mem_insert_of_mem α rfl), exact F⟮α,β⟯.add_mem α_in_Fαβ (F⟮α, β⟯.smul_mem β_in_Fαβ) } }, let p := euclidean_domain.gcd ((f.map (algebra_map F F⟮γ⟯)).comp (C (adjoin_simple.gen F γ) - (C ↑c * X))) (g.map (algebra_map F F⟮γ⟯)), let h := euclidean_domain.gcd ((f.map ιFE).comp (C γ - (C (ιFE c) * X))) (g.map ιFE), have map_g_ne_zero : g.map ιFE ≠ 0 := map_ne_zero (minpoly.ne_zero hβ), have h_ne_zero : h ≠ 0 := mt euclidean_domain.gcd_eq_zero_iff.mp (not_and.mpr (λ _, map_g_ne_zero)), suffices p_linear : p.map (algebra_map F⟮γ⟯ E) = (C h.leading_coeff) * (X - C β), { have finale : β = algebra_map F⟮γ⟯ E (-p.coeff 0 / p.coeff 1), { rw [map_div₀, ring_hom.map_neg, ←coeff_map, ←coeff_map, p_linear], simp [mul_sub, coeff_C, mul_div_cancel_left β (mt leading_coeff_eq_zero.mp h_ne_zero)] }, rw finale, exact subtype.mem (-p.coeff 0 / p.coeff 1) }, have h_sep : h.separable := separable_gcd_right _ (is_separable.separable F β).map, have h_root : h.eval β = 0, { apply eval_gcd_eq_zero, { rw [eval_comp, eval_sub, eval_mul, eval_C, eval_C, eval_X, eval_map, ←aeval_def, ←algebra.smul_def, add_sub_cancel, minpoly.aeval] }, { rw [eval_map, ←aeval_def, minpoly.aeval] } }, have h_splits : splits ιEE' h := splits_of_splits_gcd_right ιEE' map_g_ne_zero (splitting_field.splits _), have h_roots : ∀ x ∈ (h.map ιEE').roots, x = ιEE' β, { intros x hx, rw mem_roots_map h_ne_zero at hx, specialize hc ((ιEE' γ) - (ιEE' (ιFE c)) * x) (begin have f_root := root_left_of_root_gcd hx, rw [eval₂_comp, eval₂_sub, eval₂_mul,eval₂_C, eval₂_C, eval₂_X, eval₂_map] at f_root, exact (mem_roots_map (minpoly.ne_zero hα)).mpr f_root, end), specialize hc x (begin rw [mem_roots_map (minpoly.ne_zero hβ), ←eval₂_map], exact root_right_of_root_gcd hx, end), by_contradiction a, apply hc, apply (div_eq_iff (sub_ne_zero.mpr a)).mpr, simp only [algebra.smul_def, ring_hom.map_add, ring_hom.map_mul, ring_hom.comp_apply], ring }, rw ← eq_X_sub_C_of_separable_of_root_eq h_sep h_root h_splits h_roots, transitivity euclidean_domain.gcd (_ : E[X]) (_ : E[X]), { dsimp only [p], convert (gcd_map (algebra_map F⟮γ⟯ E)).symm }, { simpa [map_comp, polynomial.map_map, ←is_scalar_tower.algebra_map_eq, h] }, end end primitive_element_inf variables (F E : Type*) [field F] [field E] variables [algebra F E] [finite_dimensional F E] section separable_assumption variable [is_separable F E] /-- Primitive element theorem: a finite separable field extension `E` of `F` has a primitive element, i.e. there is an `α ∈ E` such that `F⟮α⟯ = (⊤ : subalgebra F E)`.-/ theorem exists_primitive_element : ∃ α : E, F⟮α⟯ = ⊤ := begin rcases is_empty_or_nonempty (fintype F) with F_inf|⟨⟨F_finite⟩⟩, { let P : intermediate_field F E → Prop := λ K, ∃ α : E, F⟮α⟯ = K, have base : P ⊥ := ⟨0, adjoin_zero⟩, have ih : ∀ (K : intermediate_field F E) (x : E), P K → P (K⟮x⟯.restrict_scalars F), { intros K β hK, cases hK with α hK, rw [←hK, adjoin_simple_adjoin_simple], haveI : infinite F := is_empty_fintype.mp F_inf, cases primitive_element_inf_aux F α β with γ hγ, exact ⟨γ, hγ.symm⟩ }, exact induction_on_adjoin P base ih ⊤ }, { exactI exists_primitive_element_of_finite_bot F E } end /-- Alternative phrasing of primitive element theorem: a finite separable field extension has a basis `1, α, α^2, ..., α^n`. See also `exists_primitive_element`. -/ noncomputable def power_basis_of_finite_of_separable : power_basis F E := let α := (exists_primitive_element F E).some, pb := (adjoin.power_basis (is_separable.is_integral F α)) in have e : F⟮α⟯ = ⊤ := (exists_primitive_element F E).some_spec, pb.map ((intermediate_field.equiv_of_eq e).trans intermediate_field.top_equiv) end separable_assumption end field @[simp] lemma alg_hom.card (F E K : Type*) [field F] [field E] [field K] [is_alg_closed K] [algebra F E] [finite_dimensional F E] [is_separable F E] [algebra F K] : fintype.card (E →ₐ[F] K) = finrank F E := begin convert (alg_hom.card_of_power_basis (field.power_basis_of_finite_of_separable F E) (is_separable.separable _ _) (is_alg_closed.splits_codomain _)).trans (power_basis.finrank _).symm, apply_instance, end
62a835497070935d5f134d7be38addc91cb0bd52
32025d5c2d6e33ad3b6dd8a3c91e1e838066a7f7
/src/Lean/PrettyPrinter/Meta.lean
62b8769f84f7bdc2699a85e2babc30f864a11dfe
[ "Apache-2.0" ]
permissive
walterhu1015/lean4
b2c71b688975177402758924eaa513475ed6ce72
2214d81e84646a905d0b20b032c89caf89c737ad
refs/heads/master
1,671,342,096,906
1,599,695,985,000
1,599,695,985,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,963
lean
/- Copyright (c) 2020 Sebastian Ullrich. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich -/ /-! Set up pretty printer compilers for the next stage. -/ import Lean.PrettyPrinter.Parenthesizer import Lean.PrettyPrinter.Formatter import Lean.ParserCompiler namespace Lean namespace PrettyPrinter open Lean.ParserCompiler namespace Parenthesizer def ctx (interp) : ParserCompiler.Context Parenthesizer := ⟨`parenthesizer, parenthesizerAttribute, combinatorParenthesizerAttribute, interp⟩ unsafe def interpretParserDescr : ParserDescr → CoreM Parenthesizer | ParserDescr.andthen d₁ d₂ => andthen.parenthesizer <$> interpretParserDescr d₁ <*> interpretParserDescr d₂ | ParserDescr.orelse d₁ d₂ => orelse.parenthesizer <$> interpretParserDescr d₁ <*> interpretParserDescr d₂ | ParserDescr.optional d => optional.parenthesizer <$> interpretParserDescr d | ParserDescr.lookahead d => lookahead.parenthesizer <$> interpretParserDescr d | ParserDescr.try d => try.parenthesizer <$> interpretParserDescr d | ParserDescr.many d => many.parenthesizer <$> interpretParserDescr d | ParserDescr.many1 d => many1.parenthesizer <$> interpretParserDescr d | ParserDescr.sepBy d₁ d₂ => sepBy.parenthesizer <$> interpretParserDescr d₁ <*> interpretParserDescr d₂ | ParserDescr.sepBy1 d₁ d₂ => sepBy1.parenthesizer <$> interpretParserDescr d₁ <*> interpretParserDescr d₂ | ParserDescr.node k prec d => leadingNode.parenthesizer k prec <$> interpretParserDescr d | ParserDescr.trailingNode k prec d => trailingNode.parenthesizer k prec <$> interpretParserDescr d | ParserDescr.symbol tk => pure $ symbol.parenthesizer | ParserDescr.numLit => pure $ withAntiquot.parenthesizer (mkAntiquot.parenthesizer' "numLit" `numLit) numLitNoAntiquot.parenthesizer | ParserDescr.strLit => pure $ withAntiquot.parenthesizer (mkAntiquot.parenthesizer' "strLit" `strLit) strLitNoAntiquot.parenthesizer | ParserDescr.charLit => pure $ withAntiquot.parenthesizer (mkAntiquot.parenthesizer' "charLit" `charLit) charLitNoAntiquot.parenthesizer | ParserDescr.nameLit => pure $ withAntiquot.parenthesizer (mkAntiquot.parenthesizer' "nameLit" `nameLit) nameLitNoAntiquot.parenthesizer | ParserDescr.ident => pure $ withAntiquot.parenthesizer (mkAntiquot.parenthesizer' "ident" `ident) identNoAntiquot.parenthesizer | ParserDescr.nonReservedSymbol tk includeIdent => pure $ nonReservedSymbol.parenthesizer | ParserDescr.parser constName => interpretParser (ctx interpretParserDescr) constName | ParserDescr.cat catName prec => pure $ categoryParser.parenthesizer catName prec @[init] unsafe def regHook : IO Unit := ParserCompiler.registerParserCompiler (ctx interpretParserDescr) end Parenthesizer namespace Formatter def ctx (interp) : ParserCompiler.Context Formatter := ⟨`formatter, formatterAttribute, combinatorFormatterAttribute, interp⟩ unsafe def interpretParserDescr : ParserDescr → CoreM Formatter | ParserDescr.andthen d₁ d₂ => andthen.formatter <$> interpretParserDescr d₁ <*> interpretParserDescr d₂ | ParserDescr.orelse d₁ d₂ => orelse.formatter <$> interpretParserDescr d₁ <*> interpretParserDescr d₂ | ParserDescr.optional d => optional.formatter <$> interpretParserDescr d | ParserDescr.lookahead d => lookahead.formatter <$> interpretParserDescr d | ParserDescr.try d => try.formatter <$> interpretParserDescr d | ParserDescr.many d => many.formatter <$> interpretParserDescr d | ParserDescr.many1 d => many1.formatter <$> interpretParserDescr d | ParserDescr.sepBy d₁ d₂ => sepBy.formatter <$> interpretParserDescr d₁ <*> interpretParserDescr d₂ | ParserDescr.sepBy1 d₁ d₂ => sepBy1.formatter <$> interpretParserDescr d₁ <*> interpretParserDescr d₂ | ParserDescr.node k prec d => node.formatter k <$> interpretParserDescr d | ParserDescr.trailingNode k prec d => trailingNode.formatter k prec <$> interpretParserDescr d | ParserDescr.symbol tk => pure $ symbol.formatter tk | ParserDescr.numLit => pure $ withAntiquot.formatter (mkAntiquot.formatter' "numLit" `numLit) numLitNoAntiquot.formatter | ParserDescr.strLit => pure $ withAntiquot.formatter (mkAntiquot.formatter' "strLit" `strLit) strLitNoAntiquot.formatter | ParserDescr.charLit => pure $ withAntiquot.formatter (mkAntiquot.formatter' "charLit" `charLit) charLitNoAntiquot.formatter | ParserDescr.nameLit => pure $ withAntiquot.formatter (mkAntiquot.formatter' "nameLit" `nameLit) nameLitNoAntiquot.formatter | ParserDescr.ident => pure $ withAntiquot.formatter (mkAntiquot.formatter' "ident" `ident) identNoAntiquot.formatter | ParserDescr.nonReservedSymbol tk includeIdent => pure $ nonReservedSymbol.formatter tk | ParserDescr.parser constName => interpretParser (ctx interpretParserDescr) constName | ParserDescr.cat catName prec => pure $ categoryParser.formatter catName @[init] unsafe def regHook : IO Unit := ParserCompiler.registerParserCompiler (ctx interpretParserDescr) end Formatter end PrettyPrinter end Lean
85068075fa26e4a5b5be5573697e72f7dc3b757a
969dbdfed67fda40a6f5a2b4f8c4a3c7dc01e0fb
/src/group_theory/dihedral.lean
9ba253c6489b44a46e7d5102a71d73acffe49552
[ "Apache-2.0" ]
permissive
SAAluthwela/mathlib
62044349d72dd63983a8500214736aa7779634d3
83a4b8b990907291421de54a78988c024dc8a552
refs/heads/master
1,679,433,873,417
1,615,998,031,000
1,615,998,031,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,354
lean
/- Copyright (c) 2020 Shing Tak Lam. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Shing Tak Lam -/ import data.zmod.basic import group_theory.order_of_element /-! # Dihedral Groups We define the dihedral groups `dihedral n`, with elements `r i` and `sr i` for `i : zmod n`. For `n ≠ 0`, `dihedral n` represents the symmetry group of the regular `n`-gon. `r i` represents the rotations of the `n`-gon by `2πi/n`, and `sr i` represents the reflections of the `n`-gon. `dihedral 0` corresponds to the infinite dihedral group. -/ /-- For `n ≠ 0`, `dihedral n` represents the symmetry group of the regular `n`-gon. `r i` represents the rotations of the `n`-gon by `2πi/n`, and `sr i` represents the reflections of the `n`-gon. `dihedral 0` corresponds to the infinite dihedral group. -/ @[derive decidable_eq] inductive dihedral (n : ℕ) : Type | r : zmod n → dihedral | sr : zmod n → dihedral namespace dihedral variables {n : ℕ} /-- Multiplication of the dihedral group. -/ private def mul : dihedral n → dihedral n → dihedral n | (r i) (r j) := r (i + j) | (r i) (sr j) := sr (j - i) | (sr i) (r j) := sr (i + j) | (sr i) (sr j) := r (j - i) /-- The identity `1` is the rotation by `0`. -/ private def one : dihedral n := r 0 instance : inhabited (dihedral n) := ⟨one⟩ /-- The inverse of a an element of the dihedral group. -/ private def inv : dihedral n → dihedral n | (r i) := r (-i) | (sr i) := sr i /-- The group structure on `dihedral n`. -/ instance : group (dihedral n) := { mul := mul, mul_assoc := begin rintros (a | a) (b | b) (c | c); simp only [mul]; ring, end, one := one, one_mul := begin rintros (a | a), exact congr_arg r (zero_add a), exact congr_arg sr (sub_zero a), end, mul_one := begin rintros (a | a), exact congr_arg r (add_zero a), exact congr_arg sr (add_zero a), end, inv := inv, mul_left_inv := begin rintros (a | a), exact congr_arg r (neg_add_self a), exact congr_arg r (sub_self a), end } @[simp] lemma r_mul_r (i j : zmod n) : r i * r j = r (i + j) := rfl @[simp] lemma r_mul_sr (i j : zmod n) : r i * sr j = sr (j - i) := rfl @[simp] lemma sr_mul_r (i j : zmod n) : sr i * r j = sr (i + j) := rfl @[simp] lemma sr_mul_sr (i j : zmod n) : sr i * sr j = r (j - i) := rfl lemma one_def : (1 : dihedral n) = r 0 := rfl private def fintype_helper : (zmod n ⊕ zmod n) ≃ dihedral n := { inv_fun := λ i, match i with | (r j) := sum.inl j | (sr j) := sum.inr j end, to_fun := λ i, match i with | (sum.inl j) := r j | (sum.inr j) := sr j end, left_inv := by rintro (x | x); refl, right_inv := by rintro (x | x); refl } /-- If `0 < n`, then `dihedral n` is a finite group. -/ instance [fact (0 < n)] : fintype (dihedral n) := fintype.of_equiv _ fintype_helper instance : nontrivial (dihedral n) := ⟨⟨r 0, sr 0, dec_trivial⟩⟩ /-- If `0 < n`, then `dihedral n` has `2n` elements. -/ lemma card [fact (0 < n)] : fintype.card (dihedral n) = 2 * n := begin rw ←fintype.card_eq.mpr ⟨fintype_helper⟩, change fintype.card (zmod n ⊕ zmod n) = 2 * n, rw [fintype.card_sum, zmod.card, two_mul] end @[simp] lemma r_one_pow (k : ℕ) : (r 1 : dihedral n) ^ k = r k := begin induction k with k IH, { refl }, { rw [pow_succ, IH, r_mul_r], congr' 1, norm_cast, rw nat.one_add } end @[simp] lemma r_one_pow_n : (r (1 : zmod n))^n = 1 := begin cases n, { rw pow_zero }, { rw [r_one_pow, one_def], congr' 1, exact zmod.nat_cast_self _, } end @[simp] lemma sr_mul_self (i : zmod n) : sr i * sr i = 1 := by rw [sr_mul_sr, sub_self, one_def] /-- If `0 < n`, then `sr i` has order 2. -/ @[simp] lemma order_of_sr (i : zmod n) : order_of (sr i) = 2 := begin rw order_of_eq_prime _ _, { exact nat.prime_two }, rw [pow_two, sr_mul_self], dec_trivial, end /-- If `0 < n`, then `r 1` has order `n`. -/ @[simp] lemma order_of_r_one : order_of (r 1 : dihedral n) = n := begin by_cases hnpos : 0 < n, { haveI : fact (0 < n) := hnpos, cases lt_or_eq_of_le (nat.le_of_dvd hnpos (order_of_dvd_of_pow_eq_one (@r_one_pow_n n))) with h h, { have h1 : (r 1 : dihedral n)^(order_of (r 1)) = 1, { exact pow_order_of_eq_one _ }, rw r_one_pow at h1, injection h1 with h2, rw [← zmod.val_eq_zero, zmod.val_nat_cast, nat.mod_eq_of_lt h] at h2, apply absurd h2.symm, apply ne_of_lt, exact absurd h2.symm (ne_of_lt (order_of_pos _)) }, { exact h } }, { simp only [not_lt, nonpos_iff_eq_zero] at hnpos, rw hnpos, apply order_of_eq_zero, intros m hm, rw [r_one_pow, one_def], by_contradiction, rw not_not at h, have h' : (m : zmod 0) = 0, { exact r.inj h, }, have h'' : m = 0, { simp only [int.coe_nat_eq_zero, int.nat_cast_eq_coe_nat] at h', exact h', }, rw h'' at hm, apply nat.lt_irrefl, exact hm }, end /-- If `0 < n`, then `i : zmod n` has order `n / gcd n i`. -/ lemma order_of_r [fact (0 < n)] (i : zmod n) : order_of (r i) = n / nat.gcd n i.val := begin conv_lhs { rw ←zmod.nat_cast_zmod_val i }, rw [←r_one_pow, order_of_pow, order_of_r_one] end end dihedral