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
0b4a7eed4ab3a5fa131f31d7d6946dbc8a43d2de
4727251e0cd73359b15b664c3170e5d754078599
/src/category_theory/limits/shapes/terminal.lean
c15698b68ceac0ad98436e065f501cd611d324ae
[ "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
26,144
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Bhavik Mehta -/ import category_theory.pempty import category_theory.limits.has_limits import category_theory.epi_mono import category_theory.category.preorder /-! # Initial and terminal objects in a category. ## References * [Stacks: Initial and final objects](https://stacks.math.columbia.edu/tag/002B) -/ noncomputable theory universes w w' v v₁ v₂ u u₁ u₂ open category_theory namespace category_theory.limits variables {C : Type u₁} [category.{v₁} C] /-- Construct a cone for the empty diagram given an object. -/ @[simps] def as_empty_cone (X : C) : cone (functor.empty.{w} C) := { X := X, π := by tidy } /-- Construct a cocone for the empty diagram given an object. -/ @[simps] def as_empty_cocone (X : C) : cocone (functor.empty.{w} C) := { X := X, ι := by tidy } /-- `X` is terminal if the cone it induces on the empty diagram is limiting. -/ abbreviation is_terminal (X : C) := is_limit (as_empty_cone.{v₁} X) /-- `X` is initial if the cocone it induces on the empty diagram is colimiting. -/ abbreviation is_initial (X : C) := is_colimit (as_empty_cocone.{v₁} X) /-- An object `Y` is terminal iff for every `X` there is a unique morphism `X ⟶ Y`. -/ def is_terminal_equiv_unique (F : discrete.{v₁} pempty ⥤ C) (Y : C) : is_limit (⟨Y, by tidy⟩ : cone F) ≃ ∀ X : C, unique (X ⟶ Y) := { to_fun := λ t X, { default := t.lift ⟨X, by tidy⟩, uniq := λ f, t.uniq ⟨X, by tidy⟩ f (by tidy) }, inv_fun := λ u, { lift := λ s, (u s.X).default, uniq' := λ s _ _, (u s.X).2 _ }, left_inv := by tidy, right_inv := by tidy } /-- An object `Y` is terminal if for every `X` there is a unique morphism `X ⟶ Y` (as an instance). -/ def is_terminal.of_unique (Y : C) [h : Π X : C, unique (X ⟶ Y)] : is_terminal Y := { lift := λ s, (h s.X).default } /-- If `α` is a preorder with top, then `⊤` is a terminal object. -/ def is_terminal_top {α : Type*} [preorder α] [order_top α] : is_terminal (⊤ : α) := is_terminal.of_unique _ /-- Transport a term of type `is_terminal` across an isomorphism. -/ def is_terminal.of_iso {Y Z : C} (hY : is_terminal Y) (i : Y ≅ Z) : is_terminal Z := is_limit.of_iso_limit hY { hom := { hom := i.hom }, inv := { hom := i.inv } } /-- An object `X` is initial iff for every `Y` there is a unique morphism `X ⟶ Y`. -/ def is_initial_equiv_unique (F : discrete.{v₁} pempty ⥤ C) (X : C) : is_colimit (⟨X, by tidy⟩ : cocone F) ≃ ∀ Y : C, unique (X ⟶ Y) := { to_fun := λ t X, { default := t.desc ⟨X, by tidy⟩, uniq := λ f, t.uniq ⟨X, by tidy⟩ f (by tidy) }, inv_fun := λ u, { desc := λ s, (u s.X).default, uniq' := λ s _ _, (u s.X).2 _ }, left_inv := by tidy, right_inv := by tidy } /-- An object `X` is initial if for every `Y` there is a unique morphism `X ⟶ Y` (as an instance). -/ def is_initial.of_unique (X : C) [h : Π Y : C, unique (X ⟶ Y)] : is_initial X := { desc := λ s, (h s.X).default } /-- If `α` is a preorder with bot, then `⊥` is an initial object. -/ def is_initial_bot {α : Type*} [preorder α] [order_bot α] : is_initial (⊥ : α) := is_initial.of_unique _ /-- Transport a term of type `is_initial` across an isomorphism. -/ def is_initial.of_iso {X Y : C} (hX : is_initial X) (i : X ≅ Y) : is_initial Y := is_colimit.of_iso_colimit hX { hom := { hom := i.hom }, inv := { hom := i.inv } } /-- Give the morphism to a terminal object from any other. -/ def is_terminal.from {X : C} (t : is_terminal X) (Y : C) : Y ⟶ X := t.lift (as_empty_cone Y) /-- Any two morphisms to a terminal object are equal. -/ lemma is_terminal.hom_ext {X Y : C} (t : is_terminal X) (f g : Y ⟶ X) : f = g := t.hom_ext (by tidy) @[simp] lemma is_terminal.comp_from {Z : C} (t : is_terminal Z) {X Y : C} (f : X ⟶ Y) : f ≫ t.from Y = t.from X := t.hom_ext _ _ @[simp] lemma is_terminal.from_self {X : C} (t : is_terminal X) : t.from X = 𝟙 X := t.hom_ext _ _ /-- Give the morphism from an initial object to any other. -/ def is_initial.to {X : C} (t : is_initial X) (Y : C) : X ⟶ Y := t.desc (as_empty_cocone Y) /-- Any two morphisms from an initial object are equal. -/ lemma is_initial.hom_ext {X Y : C} (t : is_initial X) (f g : X ⟶ Y) : f = g := t.hom_ext (by tidy) @[simp] lemma is_initial.to_comp {X : C} (t : is_initial X) {Y Z : C} (f : Y ⟶ Z) : t.to Y ≫ f = t.to Z := t.hom_ext _ _ @[simp] lemma is_initial.to_self {X : C} (t : is_initial X) : t.to X = 𝟙 X := t.hom_ext _ _ /-- Any morphism from a terminal object is split mono. -/ def is_terminal.split_mono_from {X Y : C} (t : is_terminal X) (f : X ⟶ Y) : split_mono f := ⟨t.from _, t.hom_ext _ _⟩ /-- Any morphism to an initial object is split epi. -/ def is_initial.split_epi_to {X Y : C} (t : is_initial X) (f : Y ⟶ X) : split_epi f := ⟨t.to _, t.hom_ext _ _⟩ /-- Any morphism from a terminal object is mono. -/ lemma is_terminal.mono_from {X Y : C} (t : is_terminal X) (f : X ⟶ Y) : mono f := by haveI := t.split_mono_from f; apply_instance /-- Any morphism to an initial object is epi. -/ lemma is_initial.epi_to {X Y : C} (t : is_initial X) (f : Y ⟶ X) : epi f := by haveI := t.split_epi_to f; apply_instance /-- If `T` and `T'` are terminal, they are isomorphic. -/ @[simps] def is_terminal.unique_up_to_iso {T T' : C} (hT : is_terminal T) (hT' : is_terminal T') : T ≅ T' := { hom := hT'.from _, inv := hT.from _ } /-- If `I` and `I'` are initial, they are isomorphic. -/ @[simps] def is_initial.unique_up_to_iso {I I' : C} (hI : is_initial I) (hI' : is_initial I') : I ≅ I' := { hom := hI.to _, inv := hI'.to _ } variable (C) /-- A category has a terminal object if it has a limit over the empty diagram. Use `has_terminal_of_unique` to construct instances. -/ abbreviation has_terminal := has_limits_of_shape (discrete.{v₁} pempty) C /-- A category has an initial object if it has a colimit over the empty diagram. Use `has_initial_of_unique` to construct instances. -/ abbreviation has_initial := has_colimits_of_shape (discrete.{v₁} pempty) C section univ variables (X : C) {F₁ : discrete.{w} pempty ⥤ C} {F₂ : discrete.{w'} pempty ⥤ C} /-- Being terminal is independent of the empty diagram, its universe, and the cone over it, as long as the cone points are isomorphic. -/ def is_limit_change_empty_cone {c₁ : cone F₁} (hl : is_limit c₁) (c₂ : cone F₂) (hi : c₁.X ≅ c₂.X) : is_limit c₂ := { lift := λ c, hl.lift ⟨c.X, by tidy⟩ ≫ hi.hom, fac' := λ _ j, j.elim, uniq' := λ c f _, by { erw ← hl.uniq ⟨c.X, by tidy⟩ (f ≫ hi.inv) (λ j, j.elim), simp } } /-- Replacing an empty cone in `is_limit` by another with the same cone point is an equivalence. -/ def is_limit_empty_cone_equiv (c₁ : cone F₁) (c₂ : cone F₂) (h : c₁.X ≅ c₂.X) : is_limit c₁ ≃ is_limit c₂ := { to_fun := λ hl, is_limit_change_empty_cone C hl c₂ h, inv_fun := λ hl, is_limit_change_empty_cone C hl c₁ h.symm, left_inv := by tidy, right_inv := by tidy } lemma has_terminal_change_diagram (h : has_limit F₁) : has_limit F₂ := ⟨⟨⟨⟨limit F₁, by tidy⟩, is_limit_change_empty_cone C (limit.is_limit F₁) _ (eq_to_iso rfl)⟩⟩⟩ lemma has_terminal_change_universe [h : has_limits_of_shape (discrete.{w} pempty) C] : has_limits_of_shape (discrete.{w'} pempty) C := { has_limit := λ J, has_terminal_change_diagram C (let f := h.1 in f (functor.empty C)) } /-- Being initial is independent of the empty diagram, its universe, and the cocone over it, as long as the cocone points are isomorphic. -/ def is_colimit_change_empty_cocone {c₁ : cocone F₁} (hl : is_colimit c₁) (c₂ : cocone F₂) (hi : c₁.X ≅ c₂.X) : is_colimit c₂ := { desc := λ c, hi.inv ≫ hl.desc ⟨c.X, by tidy⟩, fac' := λ _ j, j.elim, uniq' := λ c f _, by { erw ← hl.uniq ⟨c.X, by tidy⟩ (hi.hom ≫ f) (λ j, j.elim), simp } } /-- Replacing an empty cocone in `is_colimit` by another with the same cocone point is an equivalence. -/ def is_colimit_empty_cocone_equiv (c₁ : cocone F₁) (c₂ : cocone F₂) (h : c₁.X ≅ c₂.X) : is_colimit c₁ ≃ is_colimit c₂ := { to_fun := λ hl, is_colimit_change_empty_cocone C hl c₂ h, inv_fun := λ hl, is_colimit_change_empty_cocone C hl c₁ h.symm, left_inv := by tidy, right_inv := by tidy } lemma has_initial_change_diagram (h : has_colimit F₁) : has_colimit F₂ := ⟨⟨⟨⟨colimit F₁, by tidy⟩, is_colimit_change_empty_cocone C (colimit.is_colimit F₁) _ (eq_to_iso rfl)⟩⟩⟩ lemma has_initial_change_universe [h : has_colimits_of_shape (discrete.{w} pempty) C] : has_colimits_of_shape (discrete.{w'} pempty) C := { has_colimit := λ J, has_initial_change_diagram C (let f := h.1 in f (functor.empty C)) } end univ /-- An arbitrary choice of terminal object, if one exists. You can use the notation `⊤_ C`. This object is characterized by having a unique morphism from any object. -/ abbreviation terminal [has_terminal C] : C := limit (functor.empty.{v₁} C) /-- An arbitrary choice of initial object, if one exists. You can use the notation `⊥_ C`. This object is characterized by having a unique morphism to any object. -/ abbreviation initial [has_initial C] : C := colimit (functor.empty.{v₁} C) notation `⊤_ ` C:20 := terminal C notation `⊥_ ` C:20 := initial C section variables {C} /-- We can more explicitly show that a category has a terminal object by specifying the object, and showing there is a unique morphism to it from any other object. -/ lemma has_terminal_of_unique (X : C) [h : Π Y : C, unique (Y ⟶ X)] : has_terminal C := { has_limit := λ F, has_limit.mk ⟨_, (is_terminal_equiv_unique F X).inv_fun h⟩ } /-- We can more explicitly show that a category has an initial object by specifying the object, and showing there is a unique morphism from it to any other object. -/ lemma has_initial_of_unique (X : C) [h : Π Y : C, unique (X ⟶ Y)] : has_initial C := { has_colimit := λ F, has_colimit.mk ⟨_, (is_initial_equiv_unique F X).inv_fun h⟩ } /-- The map from an object to the terminal object. -/ abbreviation terminal.from [has_terminal C] (P : C) : P ⟶ ⊤_ C := limit.lift (functor.empty C) (as_empty_cone P) /-- The map to an object from the initial object. -/ abbreviation initial.to [has_initial C] (P : C) : ⊥_ C ⟶ P := colimit.desc (functor.empty C) (as_empty_cocone P) /-- A terminal object is terminal. -/ def terminal_is_terminal [has_terminal C] : is_terminal (⊤_ C) := { lift := λ s, terminal.from _ } /-- An initial object is initial. -/ def initial_is_initial [has_initial C] : is_initial (⊥_ C) := { desc := λ s, initial.to _ } instance unique_to_terminal [has_terminal C] (P : C) : unique (P ⟶ ⊤_ C) := is_terminal_equiv_unique _ (⊤_ C) terminal_is_terminal P instance unique_from_initial [has_initial C] (P : C) : unique (⊥_ C ⟶ P) := is_initial_equiv_unique _ (⊥_ C) initial_is_initial P @[simp] lemma terminal.comp_from [has_terminal C] {P Q : C} (f : P ⟶ Q) : f ≫ terminal.from Q = terminal.from P := by tidy @[simp] lemma initial.to_comp [has_initial C] {P Q : C} (f : P ⟶ Q) : initial.to P ≫ f = initial.to Q := by tidy /-- The (unique) isomorphism between the chosen initial object and any other initial object. -/ @[simp] def initial_iso_is_initial [has_initial C] {P : C} (t : is_initial P) : ⊥_ C ≅ P := initial_is_initial.unique_up_to_iso t /-- The (unique) isomorphism between the chosen terminal object and any other terminal object. -/ @[simp] def terminal_iso_is_terminal [has_terminal C] {P : C} (t : is_terminal P) : ⊤_ C ≅ P := terminal_is_terminal.unique_up_to_iso t /-- Any morphism from a terminal object is split mono. -/ instance terminal.split_mono_from {Y : C} [has_terminal C] (f : ⊤_ C ⟶ Y) : split_mono f := is_terminal.split_mono_from terminal_is_terminal _ /-- Any morphism to an initial object is split epi. -/ instance initial.split_epi_to {Y : C} [has_initial C] (f : Y ⟶ ⊥_ C) : split_epi f := is_initial.split_epi_to initial_is_initial _ /-- An initial object is terminal in the opposite category. -/ def terminal_op_of_initial {X : C} (t : is_initial X) : is_terminal (opposite.op X) := { lift := λ s, (t.to s.X.unop).op, uniq' := λ s m w, quiver.hom.unop_inj (t.hom_ext _ _) } /-- An initial object in the opposite category is terminal in the original category. -/ def terminal_unop_of_initial {X : Cᵒᵖ} (t : is_initial X) : is_terminal X.unop := { lift := λ s, (t.to (opposite.op s.X)).unop, uniq' := λ s m w, quiver.hom.op_inj (t.hom_ext _ _) } /-- A terminal object is initial in the opposite category. -/ def initial_op_of_terminal {X : C} (t : is_terminal X) : is_initial (opposite.op X) := { desc := λ s, (t.from s.X.unop).op, uniq' := λ s m w, quiver.hom.unop_inj (t.hom_ext _ _) } /-- A terminal object in the opposite category is initial in the original category. -/ def initial_unop_of_terminal {X : Cᵒᵖ} (t : is_terminal X) : is_initial X.unop := { desc := λ s, (t.from (opposite.op s.X)).unop, uniq' := λ s m w, quiver.hom.op_inj (t.hom_ext _ _) } instance {J : Type*} [category J] {C : Type*} [category C] [has_terminal C] : has_limit ((category_theory.functor.const J).obj (⊤_ C)) := has_limit.mk { cone := { X := ⊤_ C, π := { app := λ _, terminal.from _, }, }, is_limit := { lift := λ s, terminal.from _, }, } /-- The limit of the constant `⊤_ C` functor is `⊤_ C`. -/ @[simps hom] def limit_const_terminal {J : Type*} [category J] {C : Type*} [category C] [has_terminal C] : limit ((category_theory.functor.const J).obj (⊤_ C)) ≅ ⊤_ C := { hom := terminal.from _, inv := limit.lift ((category_theory.functor.const J).obj (⊤_ C)) { X := ⊤_ C, π := { app := λ j, terminal.from _, }}, } @[simp, reassoc] lemma limit_const_terminal_inv_π {J : Type*} [category J] {C : Type*} [category C] [has_terminal C] {j : J} : limit_const_terminal.inv ≫ limit.π ((category_theory.functor.const J).obj (⊤_ C)) j = terminal.from _ := by ext ⟨⟩ instance {J : Type*} [category J] {C : Type*} [category C] [has_initial C] : has_colimit ((category_theory.functor.const J).obj (⊥_ C)) := has_colimit.mk { cocone := { X := ⊥_ C, ι := { app := λ _, initial.to _, }, }, is_colimit := { desc := λ s, initial.to _, }, } /-- The colimit of the constant `⊥_ C` functor is `⊥_ C`. -/ @[simps inv] def colimit_const_initial {J : Type*} [category J] {C : Type*} [category C] [has_initial C] : colimit ((category_theory.functor.const J).obj (⊥_ C)) ≅ ⊥_ C := { hom := colimit.desc ((category_theory.functor.const J).obj (⊥_ C)) { X := ⊥_ C, ι := { app := λ j, initial.to _, }, }, inv := initial.to _, } @[simp, reassoc] lemma ι_colimit_const_initial_hom {J : Type*} [category J] {C : Type*} [category C] [has_initial C] {j : J} : colimit.ι ((category_theory.functor.const J).obj (⊥_ C)) j ≫ colimit_const_initial.hom = initial.to _ := by ext ⟨⟩ /-- A category is a `initial_mono_class` if the canonical morphism of an initial object is a monomorphism. In practice, this is most useful when given an arbitrary morphism out of the chosen initial object, see `initial.mono_from`. Given a terminal object, this is equivalent to the assumption that the unique morphism from initial to terminal is a monomorphism, which is the second of Freyd's axioms for an AT category. TODO: This is a condition satisfied by categories with zero objects and morphisms. -/ class initial_mono_class (C : Type u₁) [category.{v₁} C] : Prop := (is_initial_mono_from : ∀ {I} (X : C) (hI : is_initial I), mono (hI.to X)) lemma is_initial.mono_from [initial_mono_class C] {I} {X : C} (hI : is_initial I) (f : I ⟶ X) : mono f := begin rw hI.hom_ext f (hI.to X), apply initial_mono_class.is_initial_mono_from, end @[priority 100] instance initial.mono_from [has_initial C] [initial_mono_class C] (X : C) (f : ⊥_ C ⟶ X) : mono f := initial_is_initial.mono_from f /-- To show a category is a `initial_mono_class` it suffices to give an initial object such that every morphism out of it is a monomorphism. -/ lemma initial_mono_class.of_is_initial {I : C} (hI : is_initial I) (h : ∀ X, mono (hI.to X)) : initial_mono_class C := { is_initial_mono_from := λ I' X hI', begin rw hI'.hom_ext (hI'.to X) ((hI'.unique_up_to_iso hI).hom ≫ hI.to X), apply mono_comp, end } /-- To show a category is a `initial_mono_class` it suffices to show every morphism out of the initial object is a monomorphism. -/ lemma initial_mono_class.of_initial [has_initial C] (h : ∀ X : C, mono (initial.to X)) : initial_mono_class C := initial_mono_class.of_is_initial initial_is_initial h /-- To show a category is a `initial_mono_class` it suffices to show the unique morphism from an initial object to a terminal object is a monomorphism. -/ lemma initial_mono_class.of_is_terminal {I T : C} (hI : is_initial I) (hT : is_terminal T) (f : mono (hI.to T)) : initial_mono_class C := initial_mono_class.of_is_initial hI (λ X, mono_of_mono_fac (hI.hom_ext (_ ≫ hT.from X) (hI.to T))) /-- To show a category is a `initial_mono_class` it suffices to show the unique morphism from the initial object to a terminal object is a monomorphism. -/ lemma initial_mono_class.of_terminal [has_initial C] [has_terminal C] (h : mono (initial.to (⊤_ C))) : initial_mono_class C := initial_mono_class.of_is_terminal initial_is_initial terminal_is_terminal h section comparison variables {D : Type u₂} [category.{v₂} D] (G : C ⥤ D) /-- The comparison morphism from the image of a terminal object to the terminal object in the target category. This is an isomorphism iff `G` preserves terminal objects, see `category_theory.limits.preserves_terminal.of_iso_comparison`. -/ def terminal_comparison [has_terminal C] [has_terminal D] : G.obj (⊤_ C) ⟶ ⊤_ D := terminal.from _ /-- The comparison morphism from the initial object in the target category to the image of the initial object. -/ -- TODO: Show this is an isomorphism if and only if `G` preserves initial objects. def initial_comparison [has_initial C] [has_initial D] : ⊥_ D ⟶ G.obj (⊥_ C) := initial.to _ end comparison variables {J : Type u} [category.{v} J] /-- From a functor `F : J ⥤ C`, given an initial object of `J`, construct a cone for `J`. In `limit_of_diagram_initial` we show it is a limit cone. -/ @[simps] def cone_of_diagram_initial {X : J} (tX : is_initial X) (F : J ⥤ C) : cone F := { X := F.obj X, π := { app := λ j, F.map (tX.to j), naturality' := λ j j' k, begin dsimp, rw [← F.map_comp, category.id_comp, tX.hom_ext (tX.to j ≫ k) (tX.to j')], end } } /-- From a functor `F : J ⥤ C`, given an initial object of `J`, show the cone `cone_of_diagram_initial` is a limit. -/ def limit_of_diagram_initial {X : J} (tX : is_initial X) (F : J ⥤ C) : is_limit (cone_of_diagram_initial tX F) := { lift := λ s, s.π.app X, uniq' := λ s m w, begin rw [← w X, cone_of_diagram_initial_π_app, tX.hom_ext (tX.to X) (𝟙 _)], dsimp, simp -- See note [dsimp, simp] end} -- This is reducible to allow usage of lemmas about `cone_point_unique_up_to_iso`. /-- For a functor `F : J ⥤ C`, if `J` has an initial object then the image of it is isomorphic to the limit of `F`. -/ @[reducible] def limit_of_initial (F : J ⥤ C) [has_initial J] [has_limit F] : limit F ≅ F.obj (⊥_ J) := is_limit.cone_point_unique_up_to_iso (limit.is_limit _) (limit_of_diagram_initial initial_is_initial F) /-- From a functor `F : J ⥤ C`, given a terminal object of `J`, construct a cone for `J`, provided that the morphisms in the diagram are isomorphisms. In `limit_of_diagram_terminal` we show it is a limit cone. -/ @[simps] def cone_of_diagram_terminal {X : J} (hX : is_terminal X) (F : J ⥤ C) [∀ (i j : J) (f : i ⟶ j), is_iso (F.map f)] : cone F := { X := F.obj X, π := { app := λ i, inv (F.map (hX.from _)), naturality' := begin intros i j f, dsimp, simp only [is_iso.eq_inv_comp, is_iso.comp_inv_eq, category.id_comp, ← F.map_comp, hX.hom_ext (hX.from i) (f ≫ hX.from j)], end } } /-- From a functor `F : J ⥤ C`, given a terminal object of `J` and that the morphisms in the diagram are isomorphisms, show the cone `cone_of_diagram_terminal` is a limit. -/ def limit_of_diagram_terminal {X : J} (hX : is_terminal X) (F : J ⥤ C) [∀ (i j : J) (f : i ⟶ j), is_iso (F.map f)] : is_limit (cone_of_diagram_terminal hX F) := { lift := λ S, S.π.app _ } -- This is reducible to allow usage of lemmas about `cone_point_unique_up_to_iso`. /-- For a functor `F : J ⥤ C`, if `J` has a terminal object and all the morphisms in the diagram are isomorphisms, then the image of the terminal object is isomorphic to the limit of `F`. -/ @[reducible] def limit_of_terminal (F : J ⥤ C) [has_terminal J] [has_limit F] [∀ (i j : J) (f : i ⟶ j), is_iso (F.map f)] : limit F ≅ F.obj (⊤_ J) := is_limit.cone_point_unique_up_to_iso (limit.is_limit _) (limit_of_diagram_terminal terminal_is_terminal F) /-- From a functor `F : J ⥤ C`, given a terminal object of `J`, construct a cocone for `J`. In `colimit_of_diagram_terminal` we show it is a colimit cocone. -/ @[simps] def cocone_of_diagram_terminal {X : J} (tX : is_terminal X) (F : J ⥤ C) : cocone F := { X := F.obj X, ι := { app := λ j, F.map (tX.from j), naturality' := λ j j' k, begin dsimp, rw [← F.map_comp, category.comp_id, tX.hom_ext (k ≫ tX.from j') (tX.from j)], end } } /-- From a functor `F : J ⥤ C`, given a terminal object of `J`, show the cocone `cocone_of_diagram_terminal` is a colimit. -/ def colimit_of_diagram_terminal {X : J} (tX : is_terminal X) (F : J ⥤ C) : is_colimit (cocone_of_diagram_terminal tX F) := { desc := λ s, s.ι.app X, uniq' := λ s m w, by { rw [← w X, cocone_of_diagram_terminal_ι_app, tX.hom_ext (tX.from X) (𝟙 _)], simp } } -- This is reducible to allow usage of lemmas about `cocone_point_unique_up_to_iso`. /-- For a functor `F : J ⥤ C`, if `J` has a terminal object then the image of it is isomorphic to the colimit of `F`. -/ @[reducible] def colimit_of_terminal (F : J ⥤ C) [has_terminal J] [has_colimit F] : colimit F ≅ F.obj (⊤_ J) := is_colimit.cocone_point_unique_up_to_iso (colimit.is_colimit _) (colimit_of_diagram_terminal terminal_is_terminal F) /-- From a functor `F : J ⥤ C`, given an initial object of `J`, construct a cocone for `J`, provided that the morphisms in the diagram are isomorphisms. In `colimit_of_diagram_initial` we show it is a colimit cocone. -/ @[simps] def cocone_of_diagram_initial {X : J} (hX : is_initial X) (F : J ⥤ C) [∀ (i j : J) (f : i ⟶ j), is_iso (F.map f)] : cocone F := { X := F.obj X, ι := { app := λ i, inv (F.map (hX.to _)), naturality' := begin intros i j f, dsimp, simp only [is_iso.eq_inv_comp, is_iso.comp_inv_eq, category.comp_id, ← F.map_comp, hX.hom_ext (hX.to i ≫ f) (hX.to j)], end } } /-- From a functor `F : J ⥤ C`, given an initial object of `J` and that the morphisms in the diagram are isomorphisms, show the cone `cocone_of_diagram_initial` is a colimit. -/ def colimit_of_diagram_initial {X : J} (hX : is_initial X) (F : J ⥤ C) [∀ (i j : J) (f : i ⟶ j), is_iso (F.map f)] : is_colimit (cocone_of_diagram_initial hX F) := { desc := λ S, S.ι.app _ } -- This is reducible to allow usage of lemmas about `cocone_point_unique_up_to_iso`. /-- For a functor `F : J ⥤ C`, if `J` has an initial object and all the morphisms in the diagram are isomorphisms, then the image of the initial object is isomorphic to the colimit of `F`. -/ @[reducible] def colimit_of_initial (F : J ⥤ C) [has_initial J] [has_colimit F] [∀ (i j : J) (f : i ⟶ j), is_iso (F.map f)] : colimit F ≅ F.obj (⊥_ J) := is_colimit.cocone_point_unique_up_to_iso (colimit.is_colimit _) (colimit_of_diagram_initial initial_is_initial _) /-- If `j` is initial in the index category, then the map `limit.π F j` is an isomorphism. -/ lemma is_iso_π_of_is_initial {j : J} (I : is_initial j) (F : J ⥤ C) [has_limit F] : is_iso (limit.π F j) := ⟨⟨limit.lift _ (cone_of_diagram_initial I F), ⟨by { ext, simp }, by simp⟩⟩⟩ instance is_iso_π_initial [has_initial J] (F : J ⥤ C) [has_limit F] : is_iso (limit.π F (⊥_ J)) := is_iso_π_of_is_initial (initial_is_initial) F lemma is_iso_π_of_is_terminal {j : J} (I : is_terminal j) (F : J ⥤ C) [has_limit F] [∀ (i j : J) (f : i ⟶ j), is_iso (F.map f)] : is_iso (limit.π F j) := ⟨⟨limit.lift _ (cone_of_diagram_terminal I F), by { ext, simp }, by simp ⟩⟩ instance is_iso_π_terminal [has_terminal J] (F : J ⥤ C) [has_limit F] [∀ (i j : J) (f : i ⟶ j), is_iso (F.map f)] : is_iso (limit.π F (⊤_ J)) := is_iso_π_of_is_terminal terminal_is_terminal F /-- If `j` is terminal in the index category, then the map `colimit.ι F j` is an isomorphism. -/ lemma is_iso_ι_of_is_terminal {j : J} (I : is_terminal j) (F : J ⥤ C) [has_colimit F] : is_iso (colimit.ι F j) := ⟨⟨colimit.desc _ (cocone_of_diagram_terminal I F), ⟨by simp, by { ext, simp }⟩⟩⟩ instance is_iso_ι_terminal [has_terminal J] (F : J ⥤ C) [has_colimit F] : is_iso (colimit.ι F (⊤_ J)) := is_iso_ι_of_is_terminal (terminal_is_terminal) F lemma is_iso_ι_of_is_initial {j : J} (I : is_initial j) (F : J ⥤ C) [has_colimit F] [∀ (i j : J) (f : i ⟶ j), is_iso (F.map f)] : is_iso (colimit.ι F j) := ⟨⟨colimit.desc _ (cocone_of_diagram_initial I F), ⟨by tidy, by { ext, simp }⟩⟩⟩ instance is_iso_ι_initial [has_initial J] (F : J ⥤ C) [has_colimit F] [∀ (i j : J) (f : i ⟶ j), is_iso (F.map f)] : is_iso (colimit.ι F (⊥_ J)) := is_iso_ι_of_is_initial initial_is_initial F end end category_theory.limits
6a134eefb4aa0de29fec6f4257cd1a902e5104d8
626e312b5c1cb2d88fca108f5933076012633192
/src/group_theory/group_action/basic.lean
8f074210876b129623f265183aab35b27d0d7a5f
[ "Apache-2.0" ]
permissive
Bioye97/mathlib
9db2f9ee54418d29dd06996279ba9dc874fd6beb
782a20a27ee83b523f801ff34efb1a9557085019
refs/heads/master
1,690,305,956,488
1,631,067,774,000
1,631,067,774,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
21,998
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import group_theory.group_action.defs import group_theory.group_action.group import group_theory.quotient_group import data.setoid.basic import data.fintype.card /-! # Basic properties of group actions -/ universes u v w variables {α : Type u} {β : Type v} {γ : Type w} open_locale big_operators open function namespace mul_action variables (α) [monoid α] [mul_action α β] /-- The orbit of an element under an action. -/ @[to_additive "The orbit of an element under an action."] def orbit (b : β) := set.range (λ x : α, x • b) variable {α} @[to_additive] lemma mem_orbit_iff {b₁ b₂ : β} : b₂ ∈ orbit α b₁ ↔ ∃ x : α, x • b₁ = b₂ := iff.rfl @[simp, to_additive] lemma mem_orbit (b : β) (x : α) : x • b ∈ orbit α b := ⟨x, rfl⟩ @[simp, to_additive] lemma mem_orbit_self (b : β) : b ∈ orbit α b := ⟨1, by simp [mul_action.one_smul]⟩ variables (α) (β) /-- The set of elements fixed under the whole action. -/ @[to_additive "The set of elements fixed under the whole action."] def fixed_points : set β := {b : β | ∀ x : α, x • b = b} /-- `fixed_by g` is the subfield of elements fixed by `g`. -/ @[to_additive "`fixed_by g` is the subfield of elements fixed by `g`."] def fixed_by (g : α) : set β := { x | g • x = x } @[to_additive] theorem fixed_eq_Inter_fixed_by : fixed_points α β = ⋂ g : α, fixed_by α β g := set.ext $ λ x, ⟨λ hx, set.mem_Inter.2 $ λ g, hx g, λ hx g, by exact (set.mem_Inter.1 hx g : _)⟩ variables {α} (β) @[simp, to_additive] lemma mem_fixed_points {b : β} : b ∈ fixed_points α β ↔ ∀ x : α, x • b = b := iff.rfl @[simp, to_additive] lemma mem_fixed_by {g : α} {b : β} : b ∈ fixed_by α β g ↔ g • b = b := iff.rfl @[to_additive] lemma mem_fixed_points' {b : β} : b ∈ fixed_points α β ↔ (∀ b', b' ∈ orbit α b → b' = b) := ⟨λ h b h₁, let ⟨x, hx⟩ := mem_orbit_iff.1 h₁ in hx ▸ h x, λ h b, h _ (mem_orbit _ _)⟩ variables (α) {β} /-- The stabilizer of a point `b` as a submonoid of `α`. -/ @[to_additive "The stabilizer of a point `b` as an additive submonoid of `α`."] def stabilizer.submonoid (b : β) : submonoid α := { carrier := { a | a • b = b }, one_mem' := one_smul _ b, mul_mem' := λ a a' (ha : a • b = b) (hb : a' • b = b), show (a * a') • b = b, by rw [←smul_smul, hb, ha] } @[simp, to_additive] lemma mem_stabilizer_submonoid_iff {b : β} {a : α} : a ∈ stabilizer.submonoid α b ↔ a • b = b := iff.rfl variables (α β) /-- `α` acts pretransitively on `β` if for any `x y` there is `g` such that `g • x = y`. A transitive action should furthermore have `β` nonempty. -/ class is_pretransitive : Prop := (exists_smul_eq : ∀ x y : β, ∃ g : α, g • x = y) variables {β} lemma exists_smul_eq [is_pretransitive α β] (x y : β) : ∃ m : α, m • x = y := is_pretransitive.exists_smul_eq x y end mul_action namespace add_action variables (α β) [add_monoid α] [add_action α β] /-- `α` acts pretransitively on `β` if for any `x y` there is `g` such that `g +ᵥ x = y`. A transitive action should furthermore have `β` nonempty. -/ class is_pretransitive : Prop := (exists_vadd_eq : ∀ x y : β, ∃ g : α, g +ᵥ x = y) variables {β} lemma exists_vadd_eq [is_pretransitive α β] (x y : β) : ∃ m : α, m +ᵥ x = y := is_pretransitive.exists_vadd_eq x y end add_action namespace mul_action variable (α) variables [group α] [mul_action α β] /-- The stabilizer of an element under an action, i.e. what sends the element to itself. A subgroup. -/ @[to_additive "The stabilizer of an element under an action, i.e. what sends the element to itself. An additive subgroup."] def stabilizer (b : β) : subgroup α := { inv_mem' := λ a (ha : a • b = b), show a⁻¹ • b = b, by rw [inv_smul_eq_iff, ha] ..stabilizer.submonoid α b } variables {α} {β} @[simp, to_additive] lemma mem_stabilizer_iff {b : β} {a : α} : a ∈ stabilizer α b ↔ a • b = b := iff.rfl @[to_additive] lemma orbit_eq_iff {a b : β} : orbit α a = orbit α b ↔ a ∈ orbit α b:= ⟨λ h, h ▸ mem_orbit_self _, λ ⟨x, (hx : x • b = a)⟩, set.ext (λ c, ⟨λ ⟨y, (hy : y • a = c)⟩, ⟨y * x, show (y * x) • b = c, by rwa [mul_action.mul_smul, hx]⟩, λ ⟨y, (hy : y • b = c)⟩, ⟨y * x⁻¹, show (y * x⁻¹) • a = c, by conv {to_rhs, rw [← hy, ← mul_one y, ← inv_mul_self x, ← mul_assoc, mul_action.mul_smul, hx]}⟩⟩)⟩ @[to_additive] lemma mem_fixed_points_iff_card_orbit_eq_one {a : β} [fintype (orbit α a)] : a ∈ fixed_points α β ↔ fintype.card (orbit α a) = 1 := begin rw [fintype.card_eq_one_iff, mem_fixed_points], split, { exact λ h, ⟨⟨a, mem_orbit_self _⟩, λ ⟨b, ⟨x, hx⟩⟩, subtype.eq $ by simp [h x, hx.symm]⟩ }, { assume h x, rcases h with ⟨⟨z, hz⟩, hz₁⟩, exact calc x • a = z : subtype.mk.inj (hz₁ ⟨x • a, mem_orbit _ _⟩) ... = a : (subtype.mk.inj (hz₁ ⟨a, mem_orbit_self _⟩)).symm } end variables (α) {β} @[simp, to_additive] lemma mem_orbit_smul (g : α) (a : β) : a ∈ orbit α (g • a) := ⟨g⁻¹, by simp⟩ @[simp, to_additive] lemma smul_mem_orbit_smul (g h : α) (a : β) : g • a ∈ orbit α (h • a) := ⟨g * h⁻¹, by simp [mul_smul]⟩ variables (α) (β) /-- The relation 'in the same orbit'. -/ @[to_additive "The relation 'in the same orbit'."] def orbit_rel : setoid β := { r := λ a b, a ∈ orbit α b, iseqv := ⟨mem_orbit_self, λ a b, by simp [orbit_eq_iff.symm, eq_comm], λ a b, by simp [orbit_eq_iff.symm, eq_comm] {contextual := tt}⟩ } local notation `Ω` := (quotient $ orbit_rel α β) /-- Decomposition of a type `X` as a disjoint union of its orbits under a group action. This version works with any right inverse to `quotient.mk'` in order to stay computable. In most cases you'll want to use `quotient.out'`, so we provide `mul_action.self_equiv_sigma_orbits` as a special case. -/ @[to_additive "Decomposition of a type `X` as a disjoint union of its orbits under an additive group action. This version works with any right inverse to `quotient.mk'` in order to stay computable. In most cases you'll want to use `quotient.out'`, so we provide `add_action.self_equiv_sigma_orbits` as a special case."] def self_equiv_sigma_orbits' {φ : Ω → β} (hφ : right_inverse φ quotient.mk') : β ≃ Σ (ω : Ω), orbit α (φ ω) := calc β ≃ Σ (ω : Ω), {b // quotient.mk' b = ω} : (equiv.sigma_preimage_equiv quotient.mk').symm ... ≃ Σ (ω : Ω), orbit α (φ ω) : equiv.sigma_congr_right (λ ω, equiv.subtype_equiv_right $ λ x, by {rw [← hφ ω, quotient.eq', hφ ω], refl }) /-- Decomposition of a type `X` as a disjoint union of its orbits under a group action. -/ @[to_additive "Decomposition of a type `X` as a disjoint union of its orbits under an additive group action."] noncomputable def self_equiv_sigma_orbits : β ≃ Σ (ω : Ω), orbit α ω.out' := self_equiv_sigma_orbits' α β quotient.out_eq' variables {α β} /-- If the stabilizer of `x` is `S`, then the stabilizer of `g • x` is `gSg⁻¹`. -/ lemma stabilizer_smul_eq_stabilizer_map_conj (g : α) (x : β) : (stabilizer α (g • x) = (stabilizer α x).map (mul_aut.conj g).to_monoid_hom) := begin ext h, rw [mem_stabilizer_iff, ← smul_left_cancel_iff g⁻¹, smul_smul, smul_smul, smul_smul, mul_left_inv, one_smul, ← mem_stabilizer_iff, subgroup.mem_map_equiv, mul_aut.conj_symm_apply] end /-- A bijection between the stabilizers of two elements in the same orbit. -/ noncomputable def stabilizer_equiv_stabilizer_of_orbit_rel {x y : β} (h : (orbit_rel α β).rel x y) : stabilizer α x ≃* stabilizer α y := let g : α := classical.some h in have hg : g • y = x := classical.some_spec h, have this : stabilizer α x = (stabilizer α y).map (mul_aut.conj g).to_monoid_hom, by rw [← hg, stabilizer_smul_eq_stabilizer_map_conj], (mul_equiv.subgroup_congr this).trans ((mul_aut.conj g).subgroup_equiv_map $ stabilizer α y).symm end mul_action namespace add_action variables [add_group α] [add_action α β] /-- If the stabilizer of `x` is `S`, then the stabilizer of `g +ᵥ x` is `g + S + (-g)`. -/ lemma stabilizer_vadd_eq_stabilizer_map_conj (g : α) (x : β) : (stabilizer α (g +ᵥ x) = (stabilizer α x).map (add_aut.conj g).to_add_monoid_hom) := begin ext h, rw [mem_stabilizer_iff, ← vadd_left_cancel_iff (-g) , vadd_vadd, vadd_vadd, vadd_vadd, add_left_neg, zero_vadd, ← mem_stabilizer_iff, add_subgroup.mem_map_equiv, add_aut.conj_symm_apply] end /-- A bijection between the stabilizers of two elements in the same orbit. -/ noncomputable def stabilizer_equiv_stabilizer_of_orbit_rel {x y : β} (h : (orbit_rel α β).rel x y) : stabilizer α x ≃+ stabilizer α y := let g : α := classical.some h in have hg : g +ᵥ y = x := classical.some_spec h, have this : stabilizer α x = (stabilizer α y).map (add_aut.conj g).to_add_monoid_hom, by rw [← hg, stabilizer_vadd_eq_stabilizer_map_conj], (add_equiv.add_subgroup_congr this).trans ((add_aut.conj g).add_subgroup_equiv_map $ stabilizer α y).symm end add_action namespace mul_action variables [group α] [mul_action α β] open quotient_group /-- Action on left cosets. -/ @[to_additive "Action on left cosets."] def mul_left_cosets (H : subgroup α) (x : α) (y : quotient H) : quotient H := quotient.lift_on' y (λ y, quotient_group.mk ((x : α) * y)) (λ a b (hab : _ ∈ H), quotient_group.eq.2 (by rwa [mul_inv_rev, ← mul_assoc, mul_assoc (a⁻¹), inv_mul_self, mul_one])) @[to_additive] instance quotient (H : subgroup α) : mul_action α (quotient H) := { smul := mul_left_cosets H, one_smul := λ a, quotient.induction_on' a (λ a, quotient_group.eq.2 (by simp [subgroup.one_mem])), mul_smul := λ x y a, quotient.induction_on' a (λ a, quotient_group.eq.2 (by simp [mul_inv_rev, subgroup.one_mem, mul_assoc])) } @[simp, to_additive] lemma quotient.smul_mk (H : subgroup α) (a x : α) : (a • quotient_group.mk x : quotient_group.quotient H) = quotient_group.mk (a * x) := rfl @[simp, to_additive] lemma quotient.smul_coe (H : subgroup α) (a x : α) : (a • x : quotient_group.quotient H) = ↑(a * x) := rfl @[to_additive] instance mul_left_cosets_comp_subtype_val (H I : subgroup α) : mul_action I (quotient H) := mul_action.comp_hom (quotient H) (subgroup.subtype I) variables (α) {β} (x : β) /-- The canonical map from the quotient of the stabilizer to the set. -/ @[to_additive "The canonical map from the quotient of the stabilizer to the set. "] def of_quotient_stabilizer (g : quotient (mul_action.stabilizer α x)) : β := quotient.lift_on' g (•x) $ λ g1 g2 H, calc g1 • x = g1 • (g1⁻¹ * g2) • x : congr_arg _ H.symm ... = g2 • x : by rw [smul_smul, mul_inv_cancel_left] @[simp, to_additive] theorem of_quotient_stabilizer_mk (g : α) : of_quotient_stabilizer α x (quotient_group.mk g) = g • x := rfl @[to_additive] theorem of_quotient_stabilizer_mem_orbit (g) : of_quotient_stabilizer α x g ∈ orbit α x := quotient.induction_on' g $ λ g, ⟨g, rfl⟩ @[to_additive] theorem of_quotient_stabilizer_smul (g : α) (g' : quotient (mul_action.stabilizer α x)) : of_quotient_stabilizer α x (g • g') = g • of_quotient_stabilizer α x g' := quotient.induction_on' g' $ λ _, mul_smul _ _ _ @[to_additive] theorem injective_of_quotient_stabilizer : function.injective (of_quotient_stabilizer α x) := λ y₁ y₂, quotient.induction_on₂' y₁ y₂ $ λ g₁ g₂ (H : g₁ • x = g₂ • x), quotient.sound' $ show (g₁⁻¹ * g₂) • x = x, by rw [mul_smul, ← H, inv_smul_smul] /-- Orbit-stabilizer theorem. -/ @[to_additive "Orbit-stabilizer theorem."] noncomputable def orbit_equiv_quotient_stabilizer (b : β) : orbit α b ≃ quotient (stabilizer α b) := equiv.symm $ equiv.of_bijective (λ g, ⟨of_quotient_stabilizer α b g, of_quotient_stabilizer_mem_orbit α b g⟩) ⟨λ x y hxy, injective_of_quotient_stabilizer α b (by convert congr_arg subtype.val hxy), λ ⟨b, ⟨g, hgb⟩⟩, ⟨g, subtype.eq hgb⟩⟩ /-- Orbit-stabilizer theorem. -/ @[to_additive "Orbit-stabilizer theorem."] noncomputable def orbit_prod_stabilizer_equiv_group (b : β) : orbit α b × stabilizer α b ≃ α := (equiv.prod_congr (orbit_equiv_quotient_stabilizer α _) (equiv.refl _)).trans subgroup.group_equiv_quotient_times_subgroup.symm /-- Orbit-stabilizer theorem. -/ @[to_additive "Orbit-stabilizer theorem."] lemma card_orbit_mul_card_stabilizer_eq_card_group (b : β) [fintype α] [fintype $ orbit α b] [fintype $ stabilizer α b] : fintype.card (orbit α b) * fintype.card (stabilizer α b) = fintype.card α := by rw [← fintype.card_prod, fintype.card_congr (orbit_prod_stabilizer_equiv_group α b)] @[simp, to_additive] theorem orbit_equiv_quotient_stabilizer_symm_apply (b : β) (a : α) : ((orbit_equiv_quotient_stabilizer α b).symm a : β) = a • b := rfl @[simp, to_additive] lemma stabilizer_quotient {G} [group G] (H : subgroup G) : mul_action.stabilizer G ((1 : G) : quotient H) = H := by { ext, simp [quotient_group.eq] } variable (β) local notation `Ω` := (quotient $ orbit_rel α β) /-- **Class formula** : given `G` a group acting on `X` and `φ` a function mapping each orbit of `X` under this action (that is, each element of the quotient of `X` by the relation `orbit_rel G X`) to an element in this orbit, this gives a (noncomputable) bijection between `X` and the disjoint union of `G/Stab(φ(ω))` over all orbits `ω`. In most cases you'll want `φ` to be `quotient.out'`, so we provide `mul_action.self_equiv_sigma_orbits_quotient_stabilizer` as a special case. -/ @[to_additive "**Class formula** : given `G` an additive group acting on `X` and `φ` a function mapping each orbit of `X` under this action (that is, each element of the quotient of `X` by the relation `orbit_rel G X`) to an element in this orbit, this gives a (noncomputable) bijection between `X` and the disjoint union of `G/Stab(φ(ω))` over all orbits `ω`. In most cases you'll want `φ` to be `quotient.out'`, so we provide `add_action.self_equiv_sigma_orbits_quotient_stabilizer` as a special case. "] noncomputable def self_equiv_sigma_orbits_quotient_stabilizer' {φ : Ω → β} (hφ : left_inverse quotient.mk' φ) : β ≃ Σ (ω : Ω), quotient (stabilizer α (φ ω)) := calc β ≃ Σ (ω : Ω), orbit α (φ ω) : self_equiv_sigma_orbits' α β hφ ... ≃ Σ (ω : Ω), quotient (stabilizer α (φ ω)) : equiv.sigma_congr_right (λ ω, orbit_equiv_quotient_stabilizer α (φ ω)) /-- **Class formula** for a finite group acting on a finite type. See `mul_action.card_eq_sum_card_group_div_card_stabilizer` for a specialized version using `quotient.out'`. -/ @[to_additive "**Class formula** for a finite group acting on a finite type. See `add_action.card_eq_sum_card_add_group_div_card_stabilizer` for a specialized version using `quotient.out'`."] lemma card_eq_sum_card_group_div_card_stabilizer' [fintype α] [fintype β] [fintype Ω] [Π (b : β), fintype $ stabilizer α b] {φ : Ω → β} (hφ : left_inverse quotient.mk' φ) : fintype.card β = ∑ (ω : Ω), fintype.card α / fintype.card (stabilizer α (φ ω)) := begin classical, have : ∀ ω : Ω, fintype.card α / fintype.card ↥(stabilizer α (φ ω)) = fintype.card (quotient $ stabilizer α (φ ω)), { intro ω, rw [fintype.card_congr (@subgroup.group_equiv_quotient_times_subgroup α _ (stabilizer α $ φ ω)), fintype.card_prod, nat.mul_div_cancel], exact fintype.card_pos_iff.mpr (by apply_instance) }, simp_rw [this, ← fintype.card_sigma, fintype.card_congr (self_equiv_sigma_orbits_quotient_stabilizer' α β hφ)], end /-- **Class formula**. This is a special case of `mul_action.self_equiv_sigma_orbits_quotient_stabilizer'` with `φ = quotient.out'`. -/ @[to_additive "**Class formula**. This is a special case of `add_action.self_equiv_sigma_orbits_quotient_stabilizer'` with `φ = quotient.out'`. "] noncomputable def self_equiv_sigma_orbits_quotient_stabilizer : β ≃ Σ (ω : Ω), quotient (stabilizer α ω.out') := self_equiv_sigma_orbits_quotient_stabilizer' α β quotient.out_eq' /-- **Class formula** for a finite group acting on a finite type. -/ @[to_additive "**Class formula** for a finite group acting on a finite type."] lemma card_eq_sum_card_group_div_card_stabilizer [fintype α] [fintype β] [fintype Ω] [Π (b : β), fintype $ stabilizer α b] : fintype.card β = ∑ (ω : Ω), fintype.card α / fintype.card (stabilizer α ω.out') := card_eq_sum_card_group_div_card_stabilizer' α β quotient.out_eq' /-- **Burnside's lemma** : a (noncomputable) bijection between the disjoint union of all `{x ∈ X | g • x = x}` for `g ∈ G` and the product `G × X/G`, where `G` is a group acting on `X` and `X/G`denotes the quotient of `X` by the relation `orbit_rel G X`. -/ @[to_additive "**Burnside's lemma** : a (noncomputable) bijection between the disjoint union of all `{x ∈ X | g • x = x}` for `g ∈ G` and the product `G × X/G`, where `G` is an additive group acting on `X` and `X/G`denotes the quotient of `X` by the relation `orbit_rel G X`. "] noncomputable def sigma_fixed_by_equiv_orbits_prod_group : (Σ (a : α), (fixed_by α β a)) ≃ Ω × α := calc (Σ (a : α), fixed_by α β a) ≃ {ab : α × β // ab.1 • ab.2 = ab.2} : (equiv.subtype_prod_equiv_sigma_subtype _).symm ... ≃ {ba : β × α // ba.2 • ba.1 = ba.1} : (equiv.prod_comm α β).subtype_equiv (λ ab, iff.rfl) ... ≃ Σ (b : β), stabilizer α b : equiv.subtype_prod_equiv_sigma_subtype (λ (b : β) a, a ∈ stabilizer α b) ... ≃ Σ (ωb : (Σ (ω : Ω), orbit α ω.out')), stabilizer α (ωb.2 : β) : (self_equiv_sigma_orbits α β).sigma_congr_left' ... ≃ Σ (ω : Ω), (Σ (b : orbit α ω.out'), stabilizer α (b : β)) : equiv.sigma_assoc (λ (ω : Ω) (b : orbit α ω.out'), stabilizer α (b : β)) ... ≃ Σ (ω : Ω), (Σ (b : orbit α ω.out'), stabilizer α ω.out') : equiv.sigma_congr_right (λ ω, equiv.sigma_congr_right $ λ ⟨b, hb⟩, (stabilizer_equiv_stabilizer_of_orbit_rel hb).to_equiv) ... ≃ Σ (ω : Ω), orbit α ω.out' × stabilizer α ω.out' : equiv.sigma_congr_right (λ ω, equiv.sigma_equiv_prod _ _) ... ≃ Σ (ω : Ω), α : equiv.sigma_congr_right (λ ω, orbit_prod_stabilizer_equiv_group α ω.out') ... ≃ Ω × α : equiv.sigma_equiv_prod Ω α /-- **Burnside's lemma** : given a finite group `G` acting on a set `X`, the average number of elements fixed by each `g ∈ G` is the number of orbits. -/ @[to_additive "**Burnside's lemma** : given a finite additive group `G` acting on a set `X`, the average number of elements fixed by each `g ∈ G` is the number of orbits. "] lemma sum_card_fixed_by_eq_card_orbits_mul_card_group [fintype α] [Π a, fintype $ fixed_by α β a] [fintype Ω] : ∑ (a : α), fintype.card (fixed_by α β a) = fintype.card Ω * fintype.card α := by rw [← fintype.card_prod, ← fintype.card_sigma, fintype.card_congr (sigma_fixed_by_equiv_orbits_prod_group α β)] @[to_additive] instance is_pretransitive_quotient (G) [group G] (H : subgroup G) : is_pretransitive G (quotient_group.quotient H) := { exists_smul_eq := begin rintros ⟨x⟩ ⟨y⟩, refine ⟨y * x⁻¹, quotient_group.eq.mpr _⟩, simp only [H.one_mem, mul_left_inv, inv_mul_cancel_right], end } end mul_action section variables [monoid α] [add_monoid β] [distrib_mul_action α β] lemma list.smul_sum {r : α} {l : list β} : r • l.sum = (l.map ((•) r)).sum := (distrib_mul_action.to_add_monoid_hom β r).map_list_sum l /-- `smul` by a `k : M` over a ring is injective, if `k` is not a zero divisor. The general theory of such `k` is elaborated by `is_smul_regular`. The typeclass that restricts all terms of `M` to have this property is `no_zero_smul_divisors`. -/ lemma smul_cancel_of_non_zero_divisor {M R : Type*} [monoid M] [ring R] [distrib_mul_action M R] (k : M) (h : ∀ (x : R), k • x = 0 → x = 0) {a b : R} (h' : k • a = k • b) : a = b := begin rw ←sub_eq_zero, refine h _ _, rw [smul_sub, h', sub_self] end end section variables [monoid α] [add_comm_monoid β] [distrib_mul_action α β] lemma multiset.smul_sum {r : α} {s : multiset β} : r • s.sum = (s.map ((•) r)).sum := (distrib_mul_action.to_add_monoid_hom β r).map_multiset_sum s lemma finset.smul_sum {r : α} {f : γ → β} {s : finset γ} : r • ∑ x in s, f x = ∑ x in s, r • f x := (distrib_mul_action.to_add_monoid_hom β r).map_sum f s end namespace subgroup variables {G : Type*} [group G] (H : subgroup G) lemma normal_core_eq_ker : H.normal_core = (mul_action.to_perm_hom G (quotient_group.quotient H)).ker := begin refine le_antisymm (λ g hg, equiv.perm.ext (λ q, quotient_group.induction_on q (λ g', (mul_action.quotient.smul_mk H g g').trans (quotient_group.eq.mpr _)))) (subgroup.normal_le_normal_core.mpr (λ g hg, _)), { rw [mul_inv_rev, ←inv_inv g', inv_inv], exact H.normal_core.inv_mem hg g'⁻¹ }, { rw [←H.inv_mem_iff, ←mul_one g⁻¹, ←quotient_group.eq, ←mul_one g], exact (mul_action.quotient.smul_mk H g 1).symm.trans (equiv.perm.ext_iff.mp hg (1 : G)) }, end noncomputable instance fintype_quotient_normal_core [fintype (quotient_group.quotient H)] : fintype (quotient_group.quotient H.normal_core) := begin rw H.normal_core_eq_ker, classical, exact fintype.of_equiv _ (quotient_group.quotient_ker_equiv_range _).symm.to_equiv, end end subgroup
8ab53f94f2672680e0d16d5837368a5d65e3f5ff
82b86ba2ae0d5aed0f01f49c46db5afec0eb2bd7
/src/Lean/LocalContext.lean
ab025e63d8a229be349be02a902912d57a196b28
[ "Apache-2.0" ]
permissive
banksonian/lean4
3a2e6b0f1eb63aa56ff95b8d07b2f851072d54dc
78da6b3aa2840693eea354a41e89fc5b212a5011
refs/heads/master
1,673,703,624,165
1,605,123,551,000
1,605,123,551,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
14,968
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Std.Data.PersistentArray import Lean.Expr import Lean.Hygiene namespace Lean inductive LocalDecl | cdecl (index : Nat) (fvarId : FVarId) (userName : Name) (type : Expr) (bi : BinderInfo) | ldecl (index : Nat) (fvarId : FVarId) (userName : Name) (type : Expr) (value : Expr) (nonDep : Bool) @[export lean_mk_local_decl] def mkLocalDeclEx (index : Nat) (fvarId : FVarId) (userName : Name) (type : Expr) (bi : BinderInfo) : LocalDecl := LocalDecl.cdecl index fvarId userName type bi @[export lean_mk_let_decl] def mkLetDeclEx (index : Nat) (fvarId : FVarId) (userName : Name) (type : Expr) (val : Expr) : LocalDecl := LocalDecl.ldecl index fvarId userName type val false @[export lean_local_decl_binder_info] def LocalDecl.binderInfoEx : LocalDecl → BinderInfo | LocalDecl.cdecl _ _ _ _ bi => bi | _ => BinderInfo.default namespace LocalDecl instance : Inhabited LocalDecl := ⟨ldecl (arbitrary _) (arbitrary _) (arbitrary _) (arbitrary _) (arbitrary _) false⟩ def isLet : LocalDecl → Bool | cdecl .. => false | ldecl .. => true def index : LocalDecl → Nat | cdecl (index := i) .. => i | ldecl (index := i) .. => i def setIndex : LocalDecl → Nat → LocalDecl | cdecl _ id n t bi, idx => cdecl idx id n t bi | ldecl _ id n t v nd, idx => ldecl idx id n t v nd def fvarId : LocalDecl → FVarId | cdecl (fvarId := id) .. => id | ldecl (fvarId := id) .. => id def userName : LocalDecl → Name | cdecl (userName := n) .. => n | ldecl (userName := n) .. => n def type : LocalDecl → Expr | cdecl (type := t) .. => t | ldecl (type := t) .. => t def setType : LocalDecl → Expr → LocalDecl | cdecl idx id n _ bi, t => cdecl idx id n t bi | ldecl idx id n _ v nd, t => ldecl idx id n t v nd def binderInfo : LocalDecl → BinderInfo | cdecl (bi := bi) .. => bi | ldecl .. => BinderInfo.default def isAuxDecl (d : LocalDecl) : Bool := d.binderInfo.isAuxDecl def value? : LocalDecl → Option Expr | cdecl .. => none | ldecl (value := v) .. => some v def value : LocalDecl → Expr | cdecl .. => panic! "let declaration expected" | ldecl (value := v) .. => v def setValue : LocalDecl → Expr → LocalDecl | ldecl idx id n t _ nd, v => ldecl idx id n t v nd | d, _ => d def updateUserName : LocalDecl → Name → LocalDecl | cdecl index id _ type bi, userName => cdecl index id userName type bi | ldecl index id _ type val nd, userName => ldecl index id userName type val nd def updateBinderInfo : LocalDecl → BinderInfo → LocalDecl | cdecl index id n type _, bi => cdecl index id n type bi | ldecl .., _ => panic! "unexpected let declaration" def toExpr (decl : LocalDecl) : Expr := mkFVar decl.fvarId def hasExprMVar : LocalDecl → Bool | cdecl (type := t) .. => t.hasExprMVar | ldecl (type := t) (value := v) .. => t.hasExprMVar || v.hasExprMVar end LocalDecl open Std (PersistentHashMap PersistentArray PArray) structure LocalContext := (fvarIdToDecl : PersistentHashMap FVarId LocalDecl := {}) (decls : PersistentArray (Option LocalDecl) := {}) namespace LocalContext instance : Inhabited LocalContext := ⟨{}⟩ @[export lean_mk_empty_local_ctx] def mkEmpty : Unit → LocalContext := fun _ => {} def empty : LocalContext := {} @[export lean_local_ctx_is_empty] def isEmpty (lctx : LocalContext) : Bool := lctx.fvarIdToDecl.isEmpty /- Low level API for creating local declarations. It is used to implement actions in the monads `Elab` and `Tactic`. It should not be used directly since the argument `(name : Name)` is assumed to be "unique". -/ @[export lean_local_ctx_mk_local_decl] def mkLocalDecl (lctx : LocalContext) (fvarId : FVarId) (userName : Name) (type : Expr) (bi : BinderInfo := BinderInfo.default) : LocalContext := match lctx with | { fvarIdToDecl := map, decls := decls } => let idx := decls.size let decl := LocalDecl.cdecl idx fvarId userName type bi { fvarIdToDecl := map.insert fvarId decl, decls := decls.push decl } @[export lean_local_ctx_mk_let_decl] def mkLetDecl (lctx : LocalContext) (fvarId : FVarId) (userName : Name) (type : Expr) (value : Expr) (nonDep := false) : LocalContext := match lctx with | { fvarIdToDecl := map, decls := decls } => let idx := decls.size let decl := LocalDecl.ldecl idx fvarId userName type value nonDep { fvarIdToDecl := map.insert fvarId decl, decls := decls.push decl } /- Low level API -/ def addDecl (lctx : LocalContext) (newDecl : LocalDecl) : LocalContext := match lctx with | { fvarIdToDecl := map, decls := decls } => let idx := decls.size let newDecl := newDecl.setIndex idx { fvarIdToDecl := map.insert newDecl.fvarId newDecl, decls := decls.push newDecl } @[export lean_local_ctx_find] def find? (lctx : LocalContext) (fvarId : FVarId) : Option LocalDecl := lctx.fvarIdToDecl.find? fvarId def findFVar? (lctx : LocalContext) (e : Expr) : Option LocalDecl := lctx.find? e.fvarId! def get! (lctx : LocalContext) (fvarId : FVarId) : LocalDecl := match lctx.find? fvarId with | some d => d | none => panic! "unknown free variable" def getFVar! (lctx : LocalContext) (e : Expr) : LocalDecl := lctx.get! e.fvarId! def contains (lctx : LocalContext) (fvarId : FVarId) : Bool := lctx.fvarIdToDecl.contains fvarId def containsFVar (lctx : LocalContext) (e : Expr) : Bool := lctx.contains e.fvarId! def getFVarIds (lctx : LocalContext) : Array FVarId := lctx.decls.foldl (init := #[]) fun r decl? => match decl? with | some decl => r.push decl.fvarId | none => r def getFVars (lctx : LocalContext) : Array Expr := lctx.getFVarIds.map mkFVar private partial def popTailNoneAux (a : PArray (Option LocalDecl)) : PArray (Option LocalDecl) := if a.size == 0 then a else match a.get! (a.size - 1) with | none => popTailNoneAux a.pop | some _ => a @[export lean_local_ctx_erase] def erase (lctx : LocalContext) (fvarId : FVarId) : LocalContext := match lctx with | { fvarIdToDecl := map, decls := decls } => match map.find? fvarId with | none => lctx | some decl => { fvarIdToDecl := map.erase fvarId, decls := popTailNoneAux (decls.set decl.index none) } @[export lean_local_ctx_pop] def pop (lctx : LocalContext): LocalContext := match lctx with | { fvarIdToDecl := map, decls := decls } => if decls.size == 0 then lctx else match decls.get! (decls.size - 1) with | none => lctx -- unreachable | some decl => { fvarIdToDecl := map.erase decl.fvarId, decls := popTailNoneAux decls.pop } @[export lean_local_ctx_find_from_user_name] def findFromUserName? (lctx : LocalContext) (userName : Name) : Option LocalDecl := lctx.decls.findSomeRev? fun decl => match decl with | none => none | some decl => if decl.userName == userName then some decl else none @[export lean_local_ctx_uses_user_name] def usesUserName (lctx : LocalContext) (userName : Name) : Bool := (lctx.findFromUserName? userName).isSome private partial def getUnusedNameAux (lctx : LocalContext) (suggestion : Name) (i : Nat) : Name × Nat := let curr := suggestion.appendIndexAfter i if lctx.usesUserName curr then getUnusedNameAux lctx suggestion (i + 1) else (curr, i + 1) @[export lean_local_ctx_get_unused_name] def getUnusedName (lctx : LocalContext) (suggestion : Name) : Name := let suggestion := suggestion.eraseMacroScopes if lctx.usesUserName suggestion then (getUnusedNameAux lctx suggestion 1).1 else suggestion @[export lean_local_ctx_last_decl] def lastDecl (lctx : LocalContext) : Option LocalDecl := lctx.decls.get! (lctx.decls.size - 1) def setUserName (lctx : LocalContext) (fvarId : FVarId) (userName : Name) : LocalContext := let decl := lctx.get! fvarId let decl := decl.updateUserName userName { fvarIdToDecl := lctx.fvarIdToDecl.insert decl.fvarId decl, decls := lctx.decls.set decl.index decl } @[export lean_local_ctx_rename_user_name] def renameUserName (lctx : LocalContext) (fromName : Name) (toName : Name) : LocalContext := match lctx with | { fvarIdToDecl := map, decls := decls } => match lctx.findFromUserName? fromName with | none => lctx | some decl => let decl := decl.updateUserName toName; { fvarIdToDecl := map.insert decl.fvarId decl, decls := decls.set decl.index decl } /-- Low-level function for updating the local context. Assumptions about `f`, the resulting nested expressions must be definitionally equal to their original values, the `index` nor `fvarId` are modified. -/ @[inline] def modifyLocalDecl (lctx : LocalContext) (fvarId : FVarId) (f : LocalDecl → LocalDecl) : LocalContext := match lctx with | { fvarIdToDecl := map, decls := decls } => match lctx.find? fvarId with | none => lctx | some decl => let decl := f decl; { fvarIdToDecl := map.insert decl.fvarId decl, decls := decls.set decl.index decl } def updateBinderInfo (lctx : LocalContext) (fvarId : FVarId) (bi : BinderInfo) : LocalContext := modifyLocalDecl lctx fvarId fun decl => decl.updateBinderInfo bi @[export lean_local_ctx_num_indices] def numIndices (lctx : LocalContext) : Nat := lctx.decls.size @[export lean_local_ctx_get] def getAt! (lctx : LocalContext) (i : Nat) : Option LocalDecl := lctx.decls.get! i section universes u v variables {m : Type u → Type v} [Monad m] variable {β : Type u} @[specialize] def foldlM (lctx : LocalContext) (f : β → LocalDecl → m β) (init : β) (start : Nat := 0) : m β := lctx.decls.foldlM (init := init) (start := start) fun b decl => match decl with | none => pure b | some decl => f b decl @[specialize] def forM (lctx : LocalContext) (f : LocalDecl → m PUnit) : m PUnit := lctx.decls.forM fun decl => match decl with | none => pure PUnit.unit | some decl => f decl @[specialize] def findDeclM? (lctx : LocalContext) (f : LocalDecl → m (Option β)) : m (Option β) := lctx.decls.findSomeM? fun decl => match decl with | none => pure none | some decl => f decl @[specialize] def findDeclRevM? (lctx : LocalContext) (f : LocalDecl → m (Option β)) : m (Option β) := lctx.decls.findSomeRevM? fun decl => match decl with | none => pure none | some decl => f decl end @[inline] def foldl {β} (lctx : LocalContext) (f : β → LocalDecl → β) (init : β) (start : Nat := 0) : β := Id.run $ lctx.foldlM f init start @[inline] def findDecl? {β} (lctx : LocalContext) (f : LocalDecl → Option β) : Option β := Id.run $ lctx.findDeclM? f @[inline] def findDeclRev? {β} (lctx : LocalContext) (f : LocalDecl → Option β) : Option β := Id.run $ lctx.findDeclRevM? f partial def isSubPrefixOfAux (a₁ a₂ : PArray (Option LocalDecl)) (exceptFVars : Array Expr) (i j : Nat) : Bool := if i < a₁.size then match a₁[i] with | none => isSubPrefixOfAux a₁ a₂ exceptFVars (i+1) j | some decl₁ => if exceptFVars.any fun fvar => fvar.fvarId! == decl₁.fvarId then isSubPrefixOfAux a₁ a₂ exceptFVars (i+1) j else if j < a₂.size then match a₂[j] with | none => isSubPrefixOfAux a₁ a₂ exceptFVars i (j+1) | some decl₂ => if decl₁.fvarId == decl₂.fvarId then isSubPrefixOfAux a₁ a₂ exceptFVars (i+1) (j+1) else isSubPrefixOfAux a₁ a₂ exceptFVars i (j+1) else false else true /- Given `lctx₁ - exceptFVars` of the form `(x_1 : A_1) ... (x_n : A_n)`, then return true iff there is a local context `B_1* (x_1 : A_1) ... B_n* (x_n : A_n)` which is a prefix of `lctx₂` where `B_i`'s are (possibly empty) sequences of local declarations. -/ def isSubPrefixOf (lctx₁ lctx₂ : LocalContext) (exceptFVars : Array Expr := #[]) : Bool := isSubPrefixOfAux lctx₁.decls lctx₂.decls exceptFVars 0 0 @[inline] def mkBinding (isLambda : Bool) (lctx : LocalContext) (xs : Array Expr) (b : Expr) : Expr := let b := b.abstract xs xs.size.foldRev (init := b) fun i b => let x := xs[i] match lctx.findFVar? x with | some (LocalDecl.cdecl _ _ n ty bi) => let ty := ty.abstractRange i xs; if isLambda then Lean.mkLambda n bi ty b else Lean.mkForall n bi ty b | some (LocalDecl.ldecl _ _ n ty val nonDep) => if b.hasLooseBVar 0 then let ty := ty.abstractRange i xs let val := val.abstractRange i xs mkLet n ty val b nonDep else b.lowerLooseBVars 1 1 | none => panic! "unknown free variable" def mkLambda (lctx : LocalContext) (xs : Array Expr) (b : Expr) : Expr := mkBinding true lctx xs b def mkForall (lctx : LocalContext) (xs : Array Expr) (b : Expr) : Expr := mkBinding false lctx xs b section universes u variables {m : Type → Type u} [Monad m] @[inline] def anyM (lctx : LocalContext) (p : LocalDecl → m Bool) : m Bool := lctx.decls.anyM fun d => match d with | some decl => p decl | none => pure false @[inline] def allM (lctx : LocalContext) (p : LocalDecl → m Bool) : m Bool := lctx.decls.allM fun d => match d with | some decl => p decl | none => pure true end @[inline] def any (lctx : LocalContext) (p : LocalDecl → Bool) : Bool := Id.run $ lctx.anyM p @[inline] def all (lctx : LocalContext) (p : LocalDecl → Bool) : Bool := Id.run $ lctx.allM p def sanitizeNames (lctx : LocalContext) : StateM NameSanitizerState LocalContext := do let st ← get if !getSanitizeNames st.options then pure lctx else flip StateT.run' ({} : NameSet) $ lctx.decls.size.foldRevM (fun i lctx => match lctx.decls.get! i with | none => pure lctx | some decl => do let usedNames ← get set $ usedNames.insert decl.userName if decl.userName.hasMacroScopes || usedNames.contains decl.userName then do let userNameNew ← sanitizeName decl.userName pure $ lctx.setUserName decl.fvarId userNameNew else pure lctx) lctx end LocalContext class MonadLCtx (m : Type → Type) := (getLCtx : m LocalContext) export MonadLCtx (getLCtx) instance (m n) [MonadLCtx m] [MonadLift m n] : MonadLCtx n := { getLCtx := liftM (getLCtx : m _) } def replaceFVarIdAtLocalDecl (fvarId : FVarId) (e : Expr) (d : LocalDecl) : LocalDecl := if d.fvarId == fvarId then d else match d with | LocalDecl.cdecl idx id n type bi => LocalDecl.cdecl idx id n (type.replaceFVarId fvarId e) bi | LocalDecl.ldecl idx id n type val nonDep => LocalDecl.ldecl idx id n (type.replaceFVarId fvarId e) (val.replaceFVarId fvarId e) nonDep end Lean
3ec3314a159e1a56a769357ecc630dea440f9a2e
e00ea76a720126cf9f6d732ad6216b5b824d20a7
/src/data/complex/basic.lean
5eac203e62cf76dc4fc9313b51d41385a256e040
[ "Apache-2.0" ]
permissive
vaibhavkarve/mathlib
a574aaf68c0a431a47fa82ce0637f0f769826bfe
17f8340912468f49bdc30acdb9a9fa02eeb0473a
refs/heads/master
1,621,263,802,637
1,585,399,588,000
1,585,399,588,000
250,833,447
0
0
Apache-2.0
1,585,410,341,000
1,585,410,341,000
null
UTF-8
Lean
false
false
19,403
lean
/- Copyright (c) 2017 Kevin Buzzard. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Buzzard, Mario Carneiro The complex numbers, modelled as R^2 in the obvious way. -/ import data.real.basic tactic.ring algebra.field_power import tactic.norm_cast structure complex : Type := (re : ℝ) (im : ℝ) notation `ℂ` := complex namespace complex @[simp] theorem eta : ∀ z : ℂ, complex.mk z.re z.im = z | ⟨a, b⟩ := rfl @[ext] theorem ext : ∀ {z w : ℂ}, z.re = w.re → z.im = w.im → z = w | ⟨zr, zi⟩ ⟨_, _⟩ rfl rfl := rfl theorem ext_iff {z w : ℂ} : z = w ↔ z.re = w.re ∧ z.im = w.im := ⟨λ H, by simp [H], and.rec ext⟩ def of_real (r : ℝ) : ℂ := ⟨r, 0⟩ instance : has_coe ℝ ℂ := ⟨of_real⟩ @[simp] lemma of_real_eq_coe (r : ℝ) : of_real r = r := rfl @[simp, elim_cast] lemma of_real_re (r : ℝ) : (r : ℂ).re = r := rfl @[simp, elim_cast] lemma of_real_im (r : ℝ) : (r : ℂ).im = 0 := rfl @[simp, elim_cast] theorem of_real_inj {z w : ℝ} : (z : ℂ) = w ↔ z = w := ⟨congr_arg re, congr_arg _⟩ instance : has_zero ℂ := ⟨(0 : ℝ)⟩ instance : inhabited ℂ := ⟨0⟩ @[simp] lemma zero_re : (0 : ℂ).re = 0 := rfl @[simp] lemma zero_im : (0 : ℂ).im = 0 := rfl @[simp, squash_cast] lemma of_real_zero : ((0 : ℝ) : ℂ) = 0 := rfl @[simp] theorem of_real_eq_zero {z : ℝ} : (z : ℂ) = 0 ↔ z = 0 := of_real_inj theorem of_real_ne_zero {z : ℝ} : (z : ℂ) ≠ 0 ↔ z ≠ 0 := not_congr of_real_eq_zero instance : has_one ℂ := ⟨(1 : ℝ)⟩ @[simp] lemma one_re : (1 : ℂ).re = 1 := rfl @[simp] lemma one_im : (1 : ℂ).im = 0 := rfl @[simp, squash_cast] lemma of_real_one : ((1 : ℝ) : ℂ) = 1 := rfl def I : ℂ := ⟨0, 1⟩ @[simp] lemma I_re : I.re = 0 := rfl @[simp] lemma I_im : I.im = 1 := rfl instance : has_add ℂ := ⟨λ z w, ⟨z.re + w.re, z.im + w.im⟩⟩ @[simp] lemma add_re (z w : ℂ) : (z + w).re = z.re + w.re := rfl @[simp] lemma add_im (z w : ℂ) : (z + w).im = z.im + w.im := rfl @[simp, move_cast] lemma of_real_add (r s : ℝ) : ((r + s : ℝ) : ℂ) = r + s := ext_iff.2 $ by simp @[simp, squash_cast, move_cast] lemma of_real_bit0 (r : ℝ) : ((bit0 r : ℝ) : ℂ) = bit0 r := ext_iff.2 $ by simp [bit0] @[simp, squash_cast, move_cast] lemma of_real_bit1 (r : ℝ) : ((bit1 r : ℝ) : ℂ) = bit1 r := ext_iff.2 $ by simp [bit1] instance : has_neg ℂ := ⟨λ z, ⟨-z.re, -z.im⟩⟩ @[simp] lemma neg_re (z : ℂ) : (-z).re = -z.re := rfl @[simp] lemma neg_im (z : ℂ) : (-z).im = -z.im := rfl @[simp, move_cast] lemma of_real_neg (r : ℝ) : ((-r : ℝ) : ℂ) = -r := ext_iff.2 $ by simp instance : has_mul ℂ := ⟨λ z w, ⟨z.re * w.re - z.im * w.im, z.re * w.im + z.im * w.re⟩⟩ @[simp] lemma mul_re (z w : ℂ) : (z * w).re = z.re * w.re - z.im * w.im := rfl @[simp] lemma mul_im (z w : ℂ) : (z * w).im = z.re * w.im + z.im * w.re := rfl @[simp, move_cast] lemma of_real_mul (r s : ℝ) : ((r * s : ℝ) : ℂ) = r * s := ext_iff.2 $ by simp lemma smul_re (r : ℝ) (z : ℂ) : (↑r * z).re = r * z.re := by simp lemma smul_im (r : ℝ) (z : ℂ) : (↑r * z).im = r * z.im := by simp @[simp] lemma I_mul_I : I * I = -1 := ext_iff.2 $ by simp lemma I_ne_zero : (I : ℂ) ≠ 0 := mt (congr_arg im) zero_ne_one.symm lemma mk_eq_add_mul_I (a b : ℝ) : complex.mk a b = a + b * I := ext_iff.2 $ by simp @[simp] lemma re_add_im (z : ℂ) : (z.re : ℂ) + z.im * I = z := ext_iff.2 $ by simp def real_prod_equiv : ℂ ≃ (ℝ × ℝ) := { to_fun := λ z, ⟨z.re, z.im⟩, inv_fun := λ p, ⟨p.1, p.2⟩, left_inv := λ ⟨x, y⟩, rfl, right_inv := λ ⟨x, y⟩, rfl } @[simp] theorem real_prod_equiv_apply (z : ℂ) : real_prod_equiv z = (z.re, z.im) := rfl theorem real_prod_equiv_symm_re (x y : ℝ) : (real_prod_equiv.symm (x, y)).re = x := rfl theorem real_prod_equiv_symm_im (x y : ℝ) : (real_prod_equiv.symm (x, y)).im = y := rfl def conj (z : ℂ) : ℂ := ⟨z.re, -z.im⟩ @[simp] lemma conj_re (z : ℂ) : (conj z).re = z.re := rfl @[simp] lemma conj_im (z : ℂ) : (conj z).im = -z.im := rfl @[simp] lemma conj_of_real (r : ℝ) : conj r = r := ext_iff.2 $ by simp [conj] @[simp] lemma conj_zero : conj 0 = 0 := ext_iff.2 $ by simp [conj] @[simp] lemma conj_one : conj 1 = 1 := ext_iff.2 $ by simp @[simp] lemma conj_I : conj I = -I := ext_iff.2 $ by simp @[simp] lemma conj_add (z w : ℂ) : conj (z + w) = conj z + conj w := ext_iff.2 $ by simp [add_comm] @[simp] lemma conj_neg (z : ℂ) : conj (-z) = -conj z := rfl @[simp] lemma conj_neg_I : conj (-I) = I := ext_iff.2 $ by simp @[simp] lemma conj_mul (z w : ℂ) : conj (z * w) = conj z * conj w := ext_iff.2 $ by simp [add_comm] @[simp] lemma conj_conj (z : ℂ) : conj (conj z) = z := ext_iff.2 $ by simp lemma conj_involutive : function.involutive conj := conj_conj lemma conj_bijective : function.bijective conj := conj_involutive.bijective lemma conj_inj {z w : ℂ} : conj z = conj w ↔ z = w := conj_bijective.1.eq_iff @[simp] lemma conj_eq_zero {z : ℂ} : conj z = 0 ↔ z = 0 := by simpa using @conj_inj z 0 lemma eq_conj_iff_real {z : ℂ} : conj z = z ↔ ∃ r : ℝ, z = r := ⟨λ h, ⟨z.re, ext rfl $ eq_zero_of_neg_eq (congr_arg im h)⟩, λ ⟨h, e⟩, e.symm ▸ rfl⟩ lemma eq_conj_iff_re {z : ℂ} : conj z = z ↔ (z.re : ℂ) = z := eq_conj_iff_real.trans ⟨by rintro ⟨r, rfl⟩; simp, λ h, ⟨_, h.symm⟩⟩ def norm_sq (z : ℂ) : ℝ := z.re * z.re + z.im * z.im @[simp] lemma norm_sq_of_real (r : ℝ) : norm_sq r = r * r := by simp [norm_sq] @[simp] lemma norm_sq_zero : norm_sq 0 = 0 := by simp [norm_sq] @[simp] lemma norm_sq_one : norm_sq 1 = 1 := by simp [norm_sq] @[simp] lemma norm_sq_I : norm_sq I = 1 := by simp [norm_sq] lemma norm_sq_nonneg (z : ℂ) : 0 ≤ norm_sq z := add_nonneg (mul_self_nonneg _) (mul_self_nonneg _) @[simp] lemma norm_sq_eq_zero {z : ℂ} : norm_sq z = 0 ↔ z = 0 := ⟨λ h, ext (eq_zero_of_mul_self_add_mul_self_eq_zero h) (eq_zero_of_mul_self_add_mul_self_eq_zero $ (add_comm _ _).trans h), λ h, h.symm ▸ norm_sq_zero⟩ @[simp] lemma norm_sq_pos {z : ℂ} : 0 < norm_sq z ↔ z ≠ 0 := by rw [lt_iff_le_and_ne, ne, eq_comm]; simp [norm_sq_nonneg] @[simp] lemma norm_sq_neg (z : ℂ) : norm_sq (-z) = norm_sq z := by simp [norm_sq] @[simp] lemma norm_sq_conj (z : ℂ) : norm_sq (conj z) = norm_sq z := by simp [norm_sq] @[simp] lemma norm_sq_mul (z w : ℂ) : norm_sq (z * w) = norm_sq z * norm_sq w := by dsimp [norm_sq]; ring lemma norm_sq_add (z w : ℂ) : norm_sq (z + w) = norm_sq z + norm_sq w + 2 * (z * conj w).re := by dsimp [norm_sq]; ring lemma re_sq_le_norm_sq (z : ℂ) : z.re * z.re ≤ norm_sq z := le_add_of_nonneg_right (mul_self_nonneg _) lemma im_sq_le_norm_sq (z : ℂ) : z.im * z.im ≤ norm_sq z := le_add_of_nonneg_left (mul_self_nonneg _) theorem mul_conj (z : ℂ) : z * conj z = norm_sq z := ext_iff.2 $ by simp [norm_sq, mul_comm, sub_eq_neg_add, add_comm] theorem add_conj (z : ℂ) : z + conj z = (2 * z.re : ℝ) := ext_iff.2 $ by simp [two_mul] instance : comm_ring ℂ := by refine { zero := 0, add := (+), neg := has_neg.neg, one := 1, mul := (*), ..}; { intros, apply ext_iff.2; split; simp; ring } @[simp] lemma I_sq : I ^ 2 = -1 := by rw [pow_two, I_mul_I] @[simp] lemma bit0_re (z : ℂ) : (bit0 z).re = bit0 z.re := rfl @[simp] lemma bit1_re (z : ℂ) : (bit1 z).re = bit1 z.re := rfl @[simp] lemma bit0_im (z : ℂ) : (bit0 z).im = bit0 z.im := eq.refl _ @[simp] lemma bit1_im (z : ℂ) : (bit1 z).im = bit0 z.im := add_zero _ @[simp] lemma sub_re (z w : ℂ) : (z - w).re = z.re - w.re := rfl @[simp] lemma sub_im (z w : ℂ) : (z - w).im = z.im - w.im := rfl @[simp, move_cast] lemma of_real_sub (r s : ℝ) : ((r - s : ℝ) : ℂ) = r - s := ext_iff.2 $ by simp @[simp, move_cast] lemma of_real_pow (r : ℝ) (n : ℕ) : ((r ^ n : ℝ) : ℂ) = r ^ n := by induction n; simp [*, of_real_mul, pow_succ] theorem sub_conj (z : ℂ) : z - conj z = (2 * z.im : ℝ) * I := ext_iff.2 $ by simp [two_mul, sub_eq_add_neg] lemma conj_pow (z : ℂ) (n : ℕ) : conj (z ^ n) = conj z ^ n := by induction n; simp [*, conj_mul, pow_succ] @[simp] lemma conj_two : conj (2 : ℂ) = 2 := by apply complex.ext; simp lemma norm_sq_sub (z w : ℂ) : norm_sq (z - w) = norm_sq z + norm_sq w - 2 * (z * conj w).re := by rw [sub_eq_add_neg, norm_sq_add]; simp [-mul_re, add_comm, add_left_comm, sub_eq_add_neg] noncomputable instance : has_inv ℂ := ⟨λ z, conj z * ((norm_sq z)⁻¹:ℝ)⟩ theorem inv_def (z : ℂ) : z⁻¹ = conj z * ((norm_sq z)⁻¹:ℝ) := rfl @[simp] lemma inv_re (z : ℂ) : (z⁻¹).re = z.re / norm_sq z := by simp [inv_def, division_def] @[simp] lemma inv_im (z : ℂ) : (z⁻¹).im = -z.im / norm_sq z := by simp [inv_def, division_def] @[simp, move_cast] lemma of_real_inv (r : ℝ) : ((r⁻¹ : ℝ) : ℂ) = r⁻¹ := ext_iff.2 $ begin simp, by_cases r = 0, {simp [h]}, rw [← div_div_eq_div_mul, div_self h, one_div_eq_inv] end protected lemma inv_zero : (0⁻¹ : ℂ) = 0 := by rw [← of_real_zero, ← of_real_inv, inv_zero] protected theorem mul_inv_cancel {z : ℂ} (h : z ≠ 0) : z * z⁻¹ = 1 := by rw [inv_def, ← mul_assoc, mul_conj, ← of_real_mul, mul_inv_cancel (mt norm_sq_eq_zero.1 h), of_real_one] noncomputable instance : field ℂ := { inv := has_inv.inv, zero_ne_one := mt (congr_arg re) zero_ne_one, mul_inv_cancel := @complex.mul_inv_cancel, inv_zero := complex.inv_zero, ..complex.comm_ring } instance re.is_add_group_hom : is_add_group_hom complex.re := { map_add := complex.add_re } instance im.is_add_group_hom : is_add_group_hom complex.im := { map_add := complex.add_im } instance : is_ring_hom conj := by refine_struct {..}; simp instance of_real.is_ring_hom : is_ring_hom (coe : ℝ → ℂ) := by refine_struct {..}; simp lemma div_re (z w : ℂ) : (z / w).re = z.re * w.re / norm_sq w + z.im * w.im / norm_sq w := by simp [div_eq_mul_inv, mul_assoc, sub_eq_add_neg, add_comm, add_left_comm] lemma div_im (z w : ℂ) : (z / w).im = z.im * w.re / norm_sq w - z.re * w.im / norm_sq w := by simp [div_eq_mul_inv, mul_assoc, sub_eq_add_neg, add_comm, add_left_comm] @[simp, move_cast] lemma of_real_div (r s : ℝ) : ((r / s : ℝ) : ℂ) = r / s := is_ring_hom.map_div coe @[simp, move_cast] lemma of_real_fpow (r : ℝ) (n : ℤ) : ((r ^ n : ℝ) : ℂ) = (r : ℂ) ^ n := is_ring_hom.map_fpow of_real r n @[simp, squash_cast] theorem of_real_int_cast : ∀ n : ℤ, ((n : ℝ) : ℂ) = n := int.eq_cast (λ n, ((n : ℝ) : ℂ)) (by rw [int.cast_one, of_real_one]) (λ _ _, by rw [int.cast_add, of_real_add]) @[simp, squash_cast] theorem of_real_nat_cast (n : ℕ) : ((n : ℝ) : ℂ) = n := by rw [← int.cast_coe_nat, of_real_int_cast]; refl @[simp] lemma conj_sub (z w : ℂ) : conj (z - w) = conj z - conj w := by simp [sub_eq_add_neg] @[simp] lemma conj_inv (z : ℂ) : conj z⁻¹ = (conj z)⁻¹ := by ext; simp [neg_div] @[simp] lemma conj_div (z w : ℂ) : conj (z / w) = conj z / conj w := by rw [division_def, conj_mul, conj_inv]; refl @[simp] lemma norm_sq_inv (z : ℂ) : norm_sq z⁻¹ = (norm_sq z)⁻¹ := by classical; exact if h : z = 0 then by simp [h] else (domain.mul_left_inj (mt norm_sq_eq_zero.1 h)).1 $ by rw [← norm_sq_mul]; simp [h, -norm_sq_mul] @[simp] lemma norm_sq_div (z w : ℂ) : norm_sq (z / w) = norm_sq z / norm_sq w := by rw [division_def, norm_sq_mul, norm_sq_inv]; refl instance char_zero_complex : char_zero ℂ := add_group.char_zero_of_inj_zero $ λ n h, by rwa [← of_real_nat_cast, of_real_eq_zero, nat.cast_eq_zero] at h @[simp, squash_cast] theorem of_real_rat_cast : ∀ n : ℚ, ((n : ℝ) : ℂ) = n := by apply rat.eq_cast (λ n, ((n : ℝ) : ℂ)); simp theorem re_eq_add_conj (z : ℂ) : (z.re : ℂ) = (z + conj z) / 2 := by rw [add_conj]; simp; rw [mul_div_cancel_left (z.re:ℂ) two_ne_zero'] @[simp, elim_cast] lemma nat_cast_re (n : ℕ) : (n : ℂ).re = n := by rw [← of_real_nat_cast, of_real_re] @[simp, elim_cast] lemma nat_cast_im (n : ℕ) : (n : ℂ).im = 0 := by rw [← of_real_nat_cast, of_real_im] @[simp, elim_cast] lemma int_cast_re (n : ℤ) : (n : ℂ).re = n := by rw [← of_real_int_cast, of_real_re] @[simp, elim_cast] lemma int_cast_im (n : ℤ) : (n : ℂ).im = 0 := by rw [← of_real_int_cast, of_real_im] @[simp, elim_cast] lemma rat_cast_re (q : ℚ) : (q : ℂ).re = q := by rw [← of_real_rat_cast, of_real_re] @[simp, elim_cast] lemma rat_cast_im (q : ℚ) : (q : ℂ).im = 0 := by rw [← of_real_rat_cast, of_real_im] noncomputable def abs (z : ℂ) : ℝ := (norm_sq z).sqrt local notation `abs'` := _root_.abs @[simp] lemma abs_of_real (r : ℝ) : abs r = abs' r := by simp [abs, norm_sq_of_real, real.sqrt_mul_self_eq_abs] lemma abs_of_nonneg {r : ℝ} (h : 0 ≤ r) : abs r = r := (abs_of_real _).trans (abs_of_nonneg h) lemma abs_of_nat (n : ℕ) : complex.abs n = n := calc complex.abs n = complex.abs (n:ℝ) : by rw [of_real_nat_cast] ... = _ : abs_of_nonneg (nat.cast_nonneg n) lemma mul_self_abs (z : ℂ) : abs z * abs z = norm_sq z := real.mul_self_sqrt (norm_sq_nonneg _) @[simp] lemma abs_zero : abs 0 = 0 := by simp [abs] @[simp] lemma abs_one : abs 1 = 1 := by simp [abs] @[simp] lemma abs_I : abs I = 1 := by simp [abs] @[simp] lemma abs_two : abs 2 = 2 := calc abs 2 = abs (2 : ℝ) : by rw [of_real_bit0, of_real_one] ... = (2 : ℝ) : abs_of_nonneg (by norm_num) lemma abs_nonneg (z : ℂ) : 0 ≤ abs z := real.sqrt_nonneg _ @[simp] lemma abs_eq_zero {z : ℂ} : abs z = 0 ↔ z = 0 := (real.sqrt_eq_zero $ norm_sq_nonneg _).trans norm_sq_eq_zero @[simp] lemma abs_conj (z : ℂ) : abs (conj z) = abs z := by simp [abs] @[simp] lemma abs_mul (z w : ℂ) : abs (z * w) = abs z * abs w := by rw [abs, norm_sq_mul, real.sqrt_mul (norm_sq_nonneg _)]; refl lemma abs_re_le_abs (z : ℂ) : abs' z.re ≤ abs z := by rw [mul_self_le_mul_self_iff (_root_.abs_nonneg z.re) (abs_nonneg _), abs_mul_abs_self, mul_self_abs]; apply re_sq_le_norm_sq lemma abs_im_le_abs (z : ℂ) : abs' z.im ≤ abs z := by rw [mul_self_le_mul_self_iff (_root_.abs_nonneg z.im) (abs_nonneg _), abs_mul_abs_self, mul_self_abs]; apply im_sq_le_norm_sq lemma re_le_abs (z : ℂ) : z.re ≤ abs z := (abs_le.1 (abs_re_le_abs _)).2 lemma im_le_abs (z : ℂ) : z.im ≤ abs z := (abs_le.1 (abs_im_le_abs _)).2 lemma abs_add (z w : ℂ) : abs (z + w) ≤ abs z + abs w := (mul_self_le_mul_self_iff (abs_nonneg _) (add_nonneg (abs_nonneg _) (abs_nonneg _))).2 $ begin rw [mul_self_abs, add_mul_self_eq, mul_self_abs, mul_self_abs, add_right_comm, norm_sq_add, add_le_add_iff_left, mul_assoc, mul_le_mul_left (@two_pos ℝ _)], simpa [-mul_re] using re_le_abs (z * conj w) end instance : is_absolute_value abs := { abv_nonneg := abs_nonneg, abv_eq_zero := λ _, abs_eq_zero, abv_add := abs_add, abv_mul := abs_mul } open is_absolute_value @[simp] lemma abs_abs (z : ℂ) : abs' (abs z) = abs z := _root_.abs_of_nonneg (abs_nonneg _) @[simp] lemma abs_pos {z : ℂ} : 0 < abs z ↔ z ≠ 0 := abv_pos abs @[simp] lemma abs_neg : ∀ z, abs (-z) = abs z := abv_neg abs lemma abs_sub : ∀ z w, abs (z - w) = abs (w - z) := abv_sub abs lemma abs_sub_le : ∀ a b c, abs (a - c) ≤ abs (a - b) + abs (b - c) := abv_sub_le abs @[simp] theorem abs_inv : ∀ z, abs z⁻¹ = (abs z)⁻¹ := abv_inv abs @[simp] theorem abs_div : ∀ z w, abs (z / w) = abs z / abs w := abv_div abs lemma abs_abs_sub_le_abs_sub : ∀ z w, abs' (abs z - abs w) ≤ abs (z - w) := abs_abv_sub_le_abv_sub abs lemma abs_le_abs_re_add_abs_im (z : ℂ) : abs z ≤ abs' z.re + abs' z.im := by simpa [re_add_im] using abs_add z.re (z.im * I) lemma abs_re_div_abs_le_one (z : ℂ) : abs' (z.re / z.abs) ≤ 1 := by classical; exact if hz : z = 0 then by simp [hz, zero_le_one] else by rw [_root_.abs_div, abs_abs]; exact div_le_of_le_mul (abs_pos.2 hz) (by rw mul_one; exact abs_re_le_abs _) lemma abs_im_div_abs_le_one (z : ℂ) : abs' (z.im / z.abs) ≤ 1 := by classical; exact if hz : z = 0 then by simp [hz, zero_le_one] else by rw [_root_.abs_div, abs_abs]; exact div_le_of_le_mul (abs_pos.2 hz) (by rw mul_one; exact abs_im_le_abs _) @[simp, elim_cast] lemma abs_cast_nat (n : ℕ) : abs (n : ℂ) = n := by rw [← of_real_nat_cast, abs_of_nonneg (nat.cast_nonneg n)] lemma norm_sq_eq_abs (x : ℂ) : norm_sq x = abs x ^ 2 := by rw [abs, pow_two, real.mul_self_sqrt (norm_sq_nonneg _)] theorem is_cau_seq_re (f : cau_seq ℂ abs) : is_cau_seq abs' (λ n, (f n).re) := λ ε ε0, (f.cauchy ε0).imp $ λ i H j ij, lt_of_le_of_lt (by simpa using abs_re_le_abs (f j - f i)) (H _ ij) theorem is_cau_seq_im (f : cau_seq ℂ abs) : is_cau_seq abs' (λ n, (f n).im) := λ ε ε0, (f.cauchy ε0).imp $ λ i H j ij, lt_of_le_of_lt (by simpa using abs_im_le_abs (f j - f i)) (H _ ij) noncomputable def cau_seq_re (f : cau_seq ℂ abs) : cau_seq ℝ abs' := ⟨_, is_cau_seq_re f⟩ noncomputable def cau_seq_im (f : cau_seq ℂ abs) : cau_seq ℝ abs' := ⟨_, is_cau_seq_im f⟩ lemma is_cau_seq_abs {f : ℕ → ℂ} (hf : is_cau_seq abs f) : is_cau_seq abs' (abs ∘ f) := λ ε ε0, let ⟨i, hi⟩ := hf ε ε0 in ⟨i, λ j hj, lt_of_le_of_lt (abs_abs_sub_le_abs_sub _ _) (hi j hj)⟩ noncomputable def lim_aux (f : cau_seq ℂ abs) : ℂ := ⟨cau_seq.lim (cau_seq_re f), cau_seq.lim (cau_seq_im f)⟩ theorem equiv_lim_aux (f : cau_seq ℂ abs) : f ≈ cau_seq.const abs (lim_aux f) := λ ε ε0, (exists_forall_ge_and (cau_seq.equiv_lim ⟨_, is_cau_seq_re f⟩ _ (half_pos ε0)) (cau_seq.equiv_lim ⟨_, is_cau_seq_im f⟩ _ (half_pos ε0))).imp $ λ i H j ij, begin cases H _ ij with H₁ H₂, apply lt_of_le_of_lt (abs_le_abs_re_add_abs_im _), dsimp [lim_aux] at *, have := add_lt_add H₁ H₂, rwa add_halves at this, end noncomputable instance : cau_seq.is_complete ℂ abs := ⟨λ f, ⟨lim_aux f, equiv_lim_aux f⟩⟩ open cau_seq lemma lim_eq_lim_im_add_lim_re (f : cau_seq ℂ abs) : lim f = ↑(lim (cau_seq_re f)) + ↑(lim (cau_seq_im f)) * I := lim_eq_of_equiv_const $ calc f ≈ _ : equiv_lim_aux f ... = cau_seq.const abs (↑(lim (cau_seq_re f)) + ↑(lim (cau_seq_im f)) * I) : cau_seq.ext (λ _, complex.ext (by simp [lim_aux, cau_seq_re]) (by simp [lim_aux, cau_seq_im])) lemma lim_re (f : cau_seq ℂ abs) : lim (cau_seq_re f) = (lim f).re := by rw [lim_eq_lim_im_add_lim_re]; simp lemma lim_im (f : cau_seq ℂ abs) : lim (cau_seq_im f) = (lim f).im := by rw [lim_eq_lim_im_add_lim_re]; simp lemma is_cau_seq_conj (f : cau_seq ℂ abs) : is_cau_seq abs (λ n, conj (f n)) := λ ε ε0, let ⟨i, hi⟩ := f.2 ε ε0 in ⟨i, λ j hj, by rw [← conj_sub, abs_conj]; exact hi j hj⟩ noncomputable def cau_seq_conj (f : cau_seq ℂ abs) : cau_seq ℂ abs := ⟨_, is_cau_seq_conj f⟩ lemma lim_conj (f : cau_seq ℂ abs) : lim (cau_seq_conj f) = conj (lim f) := complex.ext (by simp [cau_seq_conj, (lim_re _).symm, cau_seq_re]) (by simp [cau_seq_conj, (lim_im _).symm, cau_seq_im, (lim_neg _).symm]; refl) noncomputable def cau_seq_abs (f : cau_seq ℂ abs) : cau_seq ℝ abs' := ⟨_, is_cau_seq_abs f.2⟩ lemma lim_abs (f : cau_seq ℂ abs) : lim (cau_seq_abs f) = abs (lim f) := lim_eq_of_equiv_const (λ ε ε0, let ⟨i, hi⟩ := equiv_lim f ε ε0 in ⟨i, λ j hj, lt_of_le_of_lt (abs_abs_sub_le_abs_sub _ _) (hi j hj)⟩) end complex
2df53829f7642cf5123290cd19b5ca1089a2c329
9dc8cecdf3c4634764a18254e94d43da07142918
/src/number_theory/padics/padic_integers.lean
3a151d38e601a2ccb15222657a1fb680ac19f924
[ "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
19,371
lean
/- Copyright (c) 2018 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis, Mario Carneiro, Johan Commelin -/ import data.int.modeq import number_theory.padics.padic_numbers import ring_theory.discrete_valuation_ring import topology.metric_space.cau_seq_filter /-! # p-adic integers This file defines the p-adic integers `ℤ_p` as the subtype of `ℚ_p` with norm `≤ 1`. We show that `ℤ_p` * is complete * is nonarchimedean * is a normed ring * is a local ring * is a discrete valuation ring The relation between `ℤ_[p]` and `zmod p` is established in another file. ## Important definitions * `padic_int` : the type of p-adic numbers ## Notation We introduce the notation `ℤ_[p]` for the p-adic integers. ## Implementation notes Much, but not all, of this file assumes that `p` is prime. This assumption is inferred automatically by taking `[fact (nat.prime p)] as a type class argument. Coercions into `ℤ_p` are set up to work with the `norm_cast` tactic. ## References * [F. Q. Gouvêa, *p-adic numbers*][gouvea1997] * [R. Y. Lewis, *A formal proof of Hensel's lemma over the p-adic integers*][lewis2019] * <https://en.wikipedia.org/wiki/P-adic_number> ## Tags p-adic, p adic, padic, p-adic integer -/ open padic metric local_ring noncomputable theory open_locale classical /-- The p-adic integers ℤ_p are the p-adic numbers with norm ≤ 1. -/ def padic_int (p : ℕ) [fact p.prime] := {x : ℚ_[p] // ∥x∥ ≤ 1} notation `ℤ_[`p`]` := padic_int p namespace padic_int /-! ### Ring structure and coercion to `ℚ_[p]` -/ variables {p : ℕ} [fact p.prime] instance : has_coe ℤ_[p] ℚ_[p] := ⟨subtype.val⟩ lemma ext {x y : ℤ_[p]} : (x : ℚ_[p]) = y → x = y := subtype.ext variables (p) /-- The padic integers as a subring of the padics -/ def subring : subring (ℚ_[p]) := { carrier := {x : ℚ_[p] | ∥x∥ ≤ 1}, zero_mem' := by norm_num, one_mem' := by norm_num, add_mem' := λ x y hx hy, (padic_norm_e.nonarchimedean _ _).trans $ max_le_iff.2 ⟨hx, hy⟩, mul_mem' := λ x y hx hy, (padic_norm_e.mul _ _).trans_le $ mul_le_one hx (norm_nonneg _) hy, neg_mem' := λ x hx, (norm_neg _).trans_le hx } @[simp] lemma mem_subring_iff {x : ℚ_[p]} : x ∈ subring p ↔ ∥x∥ ≤ 1 := iff.rfl variables {p} /-- Addition on ℤ_p is inherited from ℚ_p. -/ instance : has_add ℤ_[p] := (by apply_instance : has_add (subring p)) /-- Multiplication on ℤ_p is inherited from ℚ_p. -/ instance : has_mul ℤ_[p] := (by apply_instance : has_mul (subring p)) /-- Negation on ℤ_p is inherited from ℚ_p. -/ instance : has_neg ℤ_[p] := (by apply_instance : has_neg (subring p)) /-- Subtraction on ℤ_p is inherited from ℚ_p. -/ instance : has_sub ℤ_[p] := (by apply_instance : has_sub (subring p)) /-- Zero on ℤ_p is inherited from ℚ_p. -/ instance : has_zero ℤ_[p] := (by apply_instance : has_zero (subring p)) instance : inhabited ℤ_[p] := ⟨0⟩ /-- One on ℤ_p is inherited from ℚ_p. -/ instance : has_one ℤ_[p] := ⟨⟨1, by norm_num⟩⟩ @[simp] lemma mk_zero {h} : (⟨0, h⟩ : ℤ_[p]) = (0 : ℤ_[p]) := rfl @[simp] lemma val_eq_coe (z : ℤ_[p]) : z.val = z := rfl @[simp, norm_cast] lemma coe_add (z1 z2 : ℤ_[p]) : ((z1 + z2 : ℤ_[p]) : ℚ_[p]) = z1 + z2 := rfl @[simp, norm_cast] lemma coe_mul (z1 z2 : ℤ_[p]) : ((z1 * z2 : ℤ_[p]) : ℚ_[p]) = z1 * z2 := rfl @[simp, norm_cast] lemma coe_neg (z1 : ℤ_[p]) : ((-z1 : ℤ_[p]) : ℚ_[p]) = -z1 := rfl @[simp, norm_cast] lemma coe_sub (z1 z2 : ℤ_[p]) : ((z1 - z2 : ℤ_[p]) : ℚ_[p]) = z1 - z2 := rfl @[simp, norm_cast] lemma coe_one : ((1 : ℤ_[p]) : ℚ_[p]) = 1 := rfl @[simp, norm_cast] lemma coe_zero : ((0 : ℤ_[p]) : ℚ_[p]) = 0 := rfl instance : add_comm_group ℤ_[p] := (by apply_instance : add_comm_group (subring p)) instance : comm_ring ℤ_[p] := (by apply_instance : comm_ring (subring p)) @[simp, norm_cast] lemma coe_nat_cast (n : ℕ) : ((n : ℤ_[p]) : ℚ_[p]) = n := rfl @[simp, norm_cast] lemma coe_int_cast (z : ℤ) : ((z : ℤ_[p]) : ℚ_[p]) = z := rfl /-- The coercion from ℤ[p] to ℚ[p] as a ring homomorphism. -/ def coe.ring_hom : ℤ_[p] →+* ℚ_[p] := (subring p).subtype @[simp, norm_cast] lemma coe_pow (x : ℤ_[p]) (n : ℕ) : (↑(x^n) : ℚ_[p]) = (↑x : ℚ_[p])^n := rfl @[simp] lemma mk_coe (k : ℤ_[p]) : (⟨k, k.2⟩ : ℤ_[p]) = k := subtype.coe_eta _ _ /-- The inverse of a p-adic integer with norm equal to 1 is also a p-adic integer. Otherwise, the inverse is defined to be 0. -/ def inv : ℤ_[p] → ℤ_[p] | ⟨k, _⟩ := if h : ∥k∥ = 1 then ⟨1/k, by simp [h]⟩ else 0 instance : char_zero ℤ_[p] := { cast_injective := λ m n h, nat.cast_injective $ show (m:ℚ_[p]) = n, by { rw subtype.ext_iff at h, norm_cast at h, exact h } } @[simp, norm_cast] lemma coe_int_eq (z1 z2 : ℤ) : (z1 : ℤ_[p]) = z2 ↔ z1 = z2 := suffices (z1 : ℚ_[p]) = z2 ↔ z1 = z2, from iff.trans (by norm_cast) this, by norm_cast /-- A sequence of integers that is Cauchy with respect to the `p`-adic norm converges to a `p`-adic integer. -/ def of_int_seq (seq : ℕ → ℤ) (h : is_cau_seq (padic_norm p) (λ n, seq n)) : ℤ_[p] := ⟨⟦⟨_, h⟩⟧, show ↑(padic_seq.norm _) ≤ (1 : ℝ), begin rw padic_seq.norm, split_ifs with hne; norm_cast, { exact zero_le_one }, { apply padic_norm.of_int } end ⟩ end padic_int namespace padic_int /-! ### Instances We now show that `ℤ_[p]` is a * complete metric space * normed ring * integral domain -/ variables (p : ℕ) [fact p.prime] instance : metric_space ℤ_[p] := subtype.metric_space instance complete_space : complete_space ℤ_[p] := have is_closed {x : ℚ_[p] | ∥x∥ ≤ 1}, from is_closed_le continuous_norm continuous_const, this.complete_space_coe instance : has_norm ℤ_[p] := ⟨λ z, ∥(z : ℚ_[p])∥⟩ variables {p} lemma norm_def {z : ℤ_[p]} : ∥z∥ = ∥(z : ℚ_[p])∥ := rfl variables (p) instance : normed_comm_ring ℤ_[p] := { dist_eq := λ ⟨_, _⟩ ⟨_, _⟩, rfl, norm_mul := by simp [norm_def], norm := norm, .. padic_int.comm_ring, .. padic_int.metric_space p } instance : norm_one_class ℤ_[p] := ⟨norm_def.trans norm_one⟩ instance is_absolute_value : is_absolute_value (λ z : ℤ_[p], ∥z∥) := { abv_nonneg := norm_nonneg, abv_eq_zero := λ ⟨_, _⟩, by simp [norm_eq_zero], abv_add := λ ⟨_,_⟩ ⟨_, _⟩, norm_add_le _ _, abv_mul := λ _ _, by simp only [norm_def, padic_norm_e.mul, padic_int.coe_mul]} variables {p} instance : is_domain ℤ_[p] := function.injective.is_domain (subring p).subtype subtype.coe_injective end padic_int namespace padic_int /-! ### Norm -/ variables {p : ℕ} [fact p.prime] lemma norm_le_one (z : ℤ_[p]) : ∥z∥ ≤ 1 := z.2 @[simp] lemma norm_mul (z1 z2 : ℤ_[p]) : ∥z1 * z2∥ = ∥z1∥ * ∥z2∥ := by simp [norm_def] @[simp] lemma norm_pow (z : ℤ_[p]) : ∀ n : ℕ, ∥z^n∥ = ∥z∥^n | 0 := by simp | (k+1) := by { rw [pow_succ, pow_succ, norm_mul], congr, apply norm_pow } theorem nonarchimedean (q r : ℤ_[p]) : ∥q + r∥ ≤ max (∥q∥) (∥r∥) := padic_norm_e.nonarchimedean _ _ theorem norm_add_eq_max_of_ne {q r : ℤ_[p]} : ∥q∥ ≠ ∥r∥ → ∥q+r∥ = max (∥q∥) (∥r∥) := padic_norm_e.add_eq_max_of_ne lemma norm_eq_of_norm_add_lt_right {z1 z2 : ℤ_[p]} (h : ∥z1 + z2∥ < ∥z2∥) : ∥z1∥ = ∥z2∥ := by_contradiction $ λ hne, not_lt_of_ge (by rw norm_add_eq_max_of_ne hne; apply le_max_right) h lemma norm_eq_of_norm_add_lt_left {z1 z2 : ℤ_[p]} (h : ∥z1 + z2∥ < ∥z1∥) : ∥z1∥ = ∥z2∥ := by_contradiction $ λ hne, not_lt_of_ge (by rw norm_add_eq_max_of_ne hne; apply le_max_left) h @[simp] lemma padic_norm_e_of_padic_int (z : ℤ_[p]) : ∥(↑z : ℚ_[p])∥ = ∥z∥ := by simp [norm_def] lemma norm_int_cast_eq_padic_norm (z : ℤ) : ∥(z : ℤ_[p])∥ = ∥(z : ℚ_[p])∥ := by simp [norm_def] @[simp] lemma norm_eq_padic_norm {q : ℚ_[p]} (hq : ∥q∥ ≤ 1) : @norm ℤ_[p] _ ⟨q, hq⟩ = ∥q∥ := rfl @[simp] lemma norm_p : ∥(p : ℤ_[p])∥ = p⁻¹ := padic_norm_e.norm_p @[simp] lemma norm_p_pow (n : ℕ) : ∥(p : ℤ_[p])^n∥ = p^(-n:ℤ) := padic_norm_e.norm_p_pow n private def cau_seq_to_rat_cau_seq (f : cau_seq ℤ_[p] norm) : cau_seq ℚ_[p] (λ a, ∥a∥) := ⟨ λ n, f n, λ _ hε, by simpa [norm, norm_def] using f.cauchy hε ⟩ variables (p) instance complete : cau_seq.is_complete ℤ_[p] norm := ⟨ λ f, have hqn : ∥cau_seq.lim (cau_seq_to_rat_cau_seq f)∥ ≤ 1, from padic_norm_e_lim_le zero_lt_one (λ _, norm_le_one _), ⟨ ⟨_, hqn⟩, λ ε, by simpa [norm, norm_def] using cau_seq.equiv_lim (cau_seq_to_rat_cau_seq f) ε⟩⟩ end padic_int namespace padic_int variables (p : ℕ) [hp : fact p.prime] include hp lemma exists_pow_neg_lt {ε : ℝ} (hε : 0 < ε) : ∃ (k : ℕ), ↑p ^ -((k : ℕ) : ℤ) < ε := begin obtain ⟨k, hk⟩ := exists_nat_gt ε⁻¹, use k, rw ← inv_lt_inv hε (_root_.zpow_pos_of_pos _ _), { rw [zpow_neg, inv_inv, zpow_coe_nat], apply lt_of_lt_of_le hk, norm_cast, apply le_of_lt, convert nat.lt_pow_self _ _ using 1, exact hp.1.one_lt }, { exact_mod_cast hp.1.pos } end lemma exists_pow_neg_lt_rat {ε : ℚ} (hε : 0 < ε) : ∃ (k : ℕ), ↑p ^ -((k : ℕ) : ℤ) < ε := begin obtain ⟨k, hk⟩ := @exists_pow_neg_lt p _ ε (by exact_mod_cast hε), use k, rw (show (p : ℝ) = (p : ℚ), by simp) at hk, exact_mod_cast hk end variable {p} lemma norm_int_lt_one_iff_dvd (k : ℤ) : ∥(k : ℤ_[p])∥ < 1 ↔ (p : ℤ) ∣ k := suffices ∥(k : ℚ_[p])∥ < 1 ↔ ↑p ∣ k, by rwa norm_int_cast_eq_padic_norm, padic_norm_e.norm_int_lt_one_iff_dvd k lemma norm_int_le_pow_iff_dvd {k : ℤ} {n : ℕ} : ∥(k : ℤ_[p])∥ ≤ p ^ (-n : ℤ) ↔ (p^n : ℤ) ∣ k := suffices ∥(k : ℚ_[p])∥ ≤ ((↑p)^(-n : ℤ)) ↔ ↑(p^n) ∣ k, by simpa [norm_int_cast_eq_padic_norm], padic_norm_e.norm_int_le_pow_iff_dvd _ _ /-! ### Valuation on `ℤ_[p]` -/ /-- `padic_int.valuation` lifts the p-adic valuation on `ℚ` to `ℤ_[p]`. -/ def valuation (x : ℤ_[p]) := padic.valuation (x : ℚ_[p]) lemma norm_eq_pow_val {x : ℤ_[p]} (hx : x ≠ 0) : ∥x∥ = p^(-x.valuation) := begin convert padic.norm_eq_pow_val _, contrapose! hx, exact subtype.val_injective hx end @[simp] lemma valuation_zero : valuation (0 : ℤ_[p]) = 0 := padic.valuation_zero @[simp] lemma valuation_one : valuation (1 : ℤ_[p]) = 0 := padic.valuation_one @[simp] lemma valuation_p : valuation (p : ℤ_[p]) = 1 := by simp [valuation] lemma valuation_nonneg (x : ℤ_[p]) : 0 ≤ x.valuation := begin by_cases hx : x = 0, { simp [hx] }, have h : (1 : ℝ) < p := by exact_mod_cast hp.1.one_lt, rw [← neg_nonpos, ← (zpow_strict_mono h).le_iff_le], show (p : ℝ) ^ -valuation x ≤ p ^ 0, rw [← norm_eq_pow_val hx], simpa using x.property end @[simp] lemma valuation_p_pow_mul (n : ℕ) (c : ℤ_[p]) (hc : c ≠ 0) : (↑p ^ n * c).valuation = n + c.valuation := begin have : ∥(↑p ^ n * c)∥ = ∥(p ^ n : ℤ_[p])∥ * ∥c∥, { exact norm_mul _ _ }, have aux : (↑p ^ n * c) ≠ 0, { contrapose! hc, rw mul_eq_zero at hc, cases hc, { refine (hp.1.ne_zero _).elim, exact_mod_cast (pow_eq_zero hc) }, { exact hc } }, rwa [norm_eq_pow_val aux, norm_p_pow, norm_eq_pow_val hc, ← zpow_add₀, ← neg_add, zpow_inj, neg_inj] at this, { exact_mod_cast hp.1.pos }, { exact_mod_cast hp.1.ne_one }, { exact_mod_cast hp.1.ne_zero } end section units /-! ### Units of `ℤ_[p]` -/ local attribute [reducible] padic_int lemma mul_inv : ∀ {z : ℤ_[p]}, ∥z∥ = 1 → z * z.inv = 1 | ⟨k, _⟩ h := begin have hk : k ≠ 0, from λ h', @zero_ne_one ℚ_[p] _ _ (by simpa [h'] using h), unfold padic_int.inv, rw [norm_eq_padic_norm] at h, rw dif_pos h, apply subtype.ext_iff_val.2, simp [mul_inv_cancel hk] end lemma inv_mul {z : ℤ_[p]} (hz : ∥z∥ = 1) : z.inv * z = 1 := by rw [mul_comm, mul_inv hz] lemma is_unit_iff {z : ℤ_[p]} : is_unit z ↔ ∥z∥ = 1 := ⟨λ h, begin rcases is_unit_iff_dvd_one.1 h with ⟨w, eq⟩, refine le_antisymm (norm_le_one _) _, have := mul_le_mul_of_nonneg_left (norm_le_one w) (norm_nonneg z), rwa [mul_one, ← norm_mul, ← eq, norm_one] at this end, λ h, ⟨⟨z, z.inv, mul_inv h, inv_mul h⟩, rfl⟩⟩ lemma norm_lt_one_add {z1 z2 : ℤ_[p]} (hz1 : ∥z1∥ < 1) (hz2 : ∥z2∥ < 1) : ∥z1 + z2∥ < 1 := lt_of_le_of_lt (nonarchimedean _ _) (max_lt hz1 hz2) lemma norm_lt_one_mul {z1 z2 : ℤ_[p]} (hz2 : ∥z2∥ < 1) : ∥z1 * z2∥ < 1 := calc ∥z1 * z2∥ = ∥z1∥ * ∥z2∥ : by simp ... < 1 : mul_lt_one_of_nonneg_of_lt_one_right (norm_le_one _) (norm_nonneg _) hz2 @[simp] lemma mem_nonunits {z : ℤ_[p]} : z ∈ nonunits ℤ_[p] ↔ ∥z∥ < 1 := by rw lt_iff_le_and_ne; simp [norm_le_one z, nonunits, is_unit_iff] /-- A `p`-adic number `u` with `∥u∥ = 1` is a unit of `ℤ_[p]`. -/ def mk_units {u : ℚ_[p]} (h : ∥u∥ = 1) : ℤ_[p]ˣ := let z : ℤ_[p] := ⟨u, le_of_eq h⟩ in ⟨z, z.inv, mul_inv h, inv_mul h⟩ @[simp] lemma mk_units_eq {u : ℚ_[p]} (h : ∥u∥ = 1) : ((mk_units h : ℤ_[p]) : ℚ_[p]) = u := rfl @[simp] lemma norm_units (u : ℤ_[p]ˣ) : ∥(u : ℤ_[p])∥ = 1 := is_unit_iff.mp $ by simp /-- `unit_coeff hx` is the unit `u` in the unique representation `x = u * p ^ n`. See `unit_coeff_spec`. -/ def unit_coeff {x : ℤ_[p]} (hx : x ≠ 0) : ℤ_[p]ˣ := let u : ℚ_[p] := x*p^(-x.valuation) in have hu : ∥u∥ = 1, by simp [hx, nat.zpow_ne_zero_of_pos (by exact_mod_cast hp.1.pos) x.valuation, norm_eq_pow_val, zpow_neg, inv_mul_cancel], mk_units hu @[simp] lemma unit_coeff_coe {x : ℤ_[p]} (hx : x ≠ 0) : (unit_coeff hx : ℚ_[p]) = x * p ^ (-x.valuation) := rfl lemma unit_coeff_spec {x : ℤ_[p]} (hx : x ≠ 0) : x = (unit_coeff hx : ℤ_[p]) * p ^ int.nat_abs (valuation x) := begin apply subtype.coe_injective, push_cast, have repr : (x : ℚ_[p]) = (unit_coeff hx) * p ^ x.valuation, { rw [unit_coeff_coe, mul_assoc, ← zpow_add₀], { simp }, { exact_mod_cast hp.1.ne_zero } }, convert repr using 2, rw [← zpow_coe_nat, int.nat_abs_of_nonneg (valuation_nonneg x)] end end units section norm_le_iff /-! ### Various characterizations of open unit balls -/ lemma norm_le_pow_iff_le_valuation (x : ℤ_[p]) (hx : x ≠ 0) (n : ℕ) : ∥x∥ ≤ p ^ (-n : ℤ) ↔ ↑n ≤ x.valuation := begin rw norm_eq_pow_val hx, lift x.valuation to ℕ using x.valuation_nonneg with k hk, simp only [int.coe_nat_le, zpow_neg, zpow_coe_nat], have aux : ∀ n : ℕ, 0 < (p ^ n : ℝ), { apply pow_pos, exact_mod_cast hp.1.pos }, rw [inv_le_inv (aux _) (aux _)], have : p ^ n ≤ p ^ k ↔ n ≤ k := (strict_mono_pow hp.1.one_lt).le_iff_le, rw [← this], norm_cast end lemma mem_span_pow_iff_le_valuation (x : ℤ_[p]) (hx : x ≠ 0) (n : ℕ) : x ∈ (ideal.span {p ^ n} : ideal ℤ_[p]) ↔ ↑n ≤ x.valuation := begin rw [ideal.mem_span_singleton], split, { rintro ⟨c, rfl⟩, suffices : c ≠ 0, { rw [valuation_p_pow_mul _ _ this, le_add_iff_nonneg_right], apply valuation_nonneg }, contrapose! hx, rw [hx, mul_zero] }, { rw [unit_coeff_spec hx] { occs := occurrences.pos [2] }, lift x.valuation to ℕ using x.valuation_nonneg with k hk, simp only [int.nat_abs_of_nat, units.is_unit, is_unit.dvd_mul_left, int.coe_nat_le], intro H, obtain ⟨k, rfl⟩ := nat.exists_eq_add_of_le H, simp only [pow_add, dvd_mul_right] } end lemma norm_le_pow_iff_mem_span_pow (x : ℤ_[p]) (n : ℕ) : ∥x∥ ≤ p ^ (-n : ℤ) ↔ x ∈ (ideal.span {p ^ n} : ideal ℤ_[p]) := begin by_cases hx : x = 0, { subst hx, simp only [norm_zero, zpow_neg, zpow_coe_nat, inv_nonneg, iff_true, submodule.zero_mem], exact_mod_cast nat.zero_le _ }, rw [norm_le_pow_iff_le_valuation x hx, mem_span_pow_iff_le_valuation x hx] end lemma norm_le_pow_iff_norm_lt_pow_add_one (x : ℤ_[p]) (n : ℤ) : ∥x∥ ≤ p ^ n ↔ ∥x∥ < p ^ (n + 1) := begin rw norm_def, exact padic.norm_le_pow_iff_norm_lt_pow_add_one _ _, end lemma norm_lt_pow_iff_norm_le_pow_sub_one (x : ℤ_[p]) (n : ℤ) : ∥x∥ < p ^ n ↔ ∥x∥ ≤ p ^ (n - 1) := by rw [norm_le_pow_iff_norm_lt_pow_add_one, sub_add_cancel] lemma norm_lt_one_iff_dvd (x : ℤ_[p]) : ∥x∥ < 1 ↔ ↑p ∣ x := begin have := norm_le_pow_iff_mem_span_pow x 1, rw [ideal.mem_span_singleton, pow_one] at this, rw [← this, norm_le_pow_iff_norm_lt_pow_add_one], simp only [zpow_zero, int.coe_nat_zero, int.coe_nat_succ, add_left_neg, zero_add] end @[simp] lemma pow_p_dvd_int_iff (n : ℕ) (a : ℤ) : (p ^ n : ℤ_[p]) ∣ a ↔ ↑p ^ n ∣ a := by rw [← norm_int_le_pow_iff_dvd, norm_le_pow_iff_mem_span_pow, ideal.mem_span_singleton] end norm_le_iff section dvr /-! ### Discrete valuation ring -/ instance : local_ring ℤ_[p] := local_ring.of_nonunits_add $ by simp only [mem_nonunits]; exact λ x y, norm_lt_one_add lemma p_nonnunit : (p : ℤ_[p]) ∈ nonunits ℤ_[p] := have (p : ℝ)⁻¹ < 1, from inv_lt_one $ by exact_mod_cast hp.1.one_lt, by simp [this] lemma maximal_ideal_eq_span_p : maximal_ideal ℤ_[p] = ideal.span {p} := begin apply le_antisymm, { intros x hx, rw ideal.mem_span_singleton, simp only [local_ring.mem_maximal_ideal, mem_nonunits] at hx, rwa ← norm_lt_one_iff_dvd }, { rw [ideal.span_le, set.singleton_subset_iff], exact p_nonnunit } end lemma prime_p : prime (p : ℤ_[p]) := begin rw [← ideal.span_singleton_prime, ← maximal_ideal_eq_span_p], { apply_instance }, { exact_mod_cast hp.1.ne_zero } end lemma irreducible_p : irreducible (p : ℤ_[p]) := prime.irreducible prime_p instance : discrete_valuation_ring ℤ_[p] := discrete_valuation_ring.of_has_unit_mul_pow_irreducible_factorization ⟨p, irreducible_p, λ x hx, ⟨x.valuation.nat_abs, unit_coeff hx, by rw [mul_comm, ← unit_coeff_spec hx]⟩⟩ lemma ideal_eq_span_pow_p {s : ideal ℤ_[p]} (hs : s ≠ ⊥) : ∃ n : ℕ, s = ideal.span {p ^ n} := discrete_valuation_ring.ideal_eq_span_pow_irreducible hs irreducible_p open cau_seq instance : is_adic_complete (maximal_ideal ℤ_[p]) ℤ_[p] := { prec' := λ x hx, begin simp only [← ideal.one_eq_top, smul_eq_mul, mul_one, smodeq.sub_mem, maximal_ideal_eq_span_p, ideal.span_singleton_pow, ← norm_le_pow_iff_mem_span_pow] at hx ⊢, let x' : cau_seq ℤ_[p] norm := ⟨x, _⟩, swap, { intros ε hε, obtain ⟨m, hm⟩ := exists_pow_neg_lt p hε, refine ⟨m, λ n hn, lt_of_le_of_lt _ hm⟩, rw [← neg_sub, norm_neg], exact hx hn }, { refine ⟨x'.lim, λ n, _⟩, have : (0:ℝ) < p ^ (-n : ℤ), { apply zpow_pos_of_pos, exact_mod_cast hp.1.pos }, obtain ⟨i, hi⟩ := equiv_def₃ (equiv_lim x') this, by_cases hin : i ≤ n, { exact (hi i le_rfl n hin).le }, { push_neg at hin, specialize hi i le_rfl i le_rfl, specialize hx hin.le, have := nonarchimedean (x n - x i) (x i - x'.lim), rw [sub_add_sub_cancel] at this, refine this.trans (max_le_iff.mpr ⟨hx, hi.le⟩) } } end } end dvr end padic_int
23743fc54e1815f55fba80e49cc29fc1bb418538
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/topology/category/Top/epi_mono.lean
fd7100d1ebe59a604b7449d2f53faf94044e2911
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
1,124
lean
/- Copyright (c) 2019 Reid Barton. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Reid Barton -/ import topology.category.Top.adjunctions /-! # Epi- and monomorphisms in `Top` This file shows that a continuous function is an epimorphism in the category of topological spaces if and only if it is surjective, and that a continuous function is a monomorphism in the category of topological spaces if and only if it is injective. -/ universe u open category_theory open Top namespace Top lemma epi_iff_surjective {X Y : Top.{u}} (f : X ⟶ Y) : epi f ↔ function.surjective f := begin suffices : epi f ↔ epi ((forget Top).map f), { rw [this, category_theory.epi_iff_surjective], refl }, split, { introI, apply_instance }, { apply functor.epi_of_epi_map } end lemma mono_iff_injective {X Y : Top.{u}} (f : X ⟶ Y) : mono f ↔ function.injective f := begin suffices : mono f ↔ mono ((forget Top).map f), { rw [this, category_theory.mono_iff_injective], refl }, split, { introI, apply_instance }, { apply functor.mono_of_mono_map } end end Top
615f5e28316e98bc21966364abb79bfd9bbbe57f
4e3bf8e2b29061457a887ac8889e88fa5aa0e34c
/lean/love03_structured_proofs_and_proof_terms_exercise_solution.lean
80fdd8f6ee6e7e31ada82f37ae8dfa4f969d46dd
[]
no_license
mukeshtiwari/logical_verification_2019
9f964c067a71f65eb8884743273fbeef99e6503d
16f62717f55ed5b7b87e03ae0134791a9bef9b9a
refs/heads/master
1,619,158,844,208
1,585,139,500,000
1,585,139,500,000
249,906,380
0
0
null
1,585,118,728,000
1,585,118,727,000
null
UTF-8
Lean
false
false
2,561
lean
/- LoVe Exercise 3: Structured Proofs and Proof Terms -/ import .lovelib namespace LoVe /- Question 1: Chain of Equalities -/ /- 1.1. Write the following proof using `calc`. (a + b) * (a + b) = a * (a + b) + b * (a + b) = a * a + a * b + b * a + b * b = a * a + a * b + a * b + b * b = a * a + 2 * a * b + b * b Hint: You might need `rw`, `simp`, `ac_refl`, and the lemmas `mul_add`, `add_mul`, and `two_mul`. -/ lemma binomial_square (a b : ℕ) : (a + b) * (a + b) = a * a + 2 * a * b + b * b := calc (a + b) * (a + b) = a * (a + b) + b * (a + b) : by simp [add_mul] ... = a * a + a * b + b * a + b * b : by simp [mul_add] ... = a * a + a * b + a * b + b * b : by ac_refl ... = a * a + 2 * a * b + b * b : by simp [two_mul, add_mul]; ac_refl /- 1.2. Prove the same argument again, this time as a structured proof. Try to reuse as much of the above proof idea as possible. -/ lemma binomial_square₂ (a b : ℕ) : (a + b) * (a + b) = a * a + 2 * a * b + b * b := have h1 : (a + b) * (a + b) = a * (a + b) + b * (a + b) := by simp [add_mul], have h2 : a * (a + b) + b * (a + b) = a * a + a * b + b * a + b * b := by simp [mul_add], have h3 : a * a + a * b + b * a + b * b = a * a + a * b + a * b + b * b := by ac_refl, have h4 : a * a + a * b + a * b + b * b = a * a + 2 * a * b + b * b := by simp [two_mul, add_mul]; ac_refl, show _, by rw [h1, h2, h3, h4] /- 1.3 (**optional**). Prove the same lemma again, this time using tactics. -/ lemma binomial_square₃ (a b : ℕ) : (a + b) * (a + b) = a * a + 2 * a * b + b * b := begin simp [add_mul, mul_add, two_mul], ac_refl end /- Question 2: Connectives and Quantifiers -/ /- 2.1. Supply structured proofs of the following lemmas. -/ lemma I (a : Prop) : a → a := assume ha, show a, from ha lemma K (a b : Prop) : a → b → b := assume ha hb, show b, from hb lemma C (a b c : Prop) : (a → b → c) → b → a → c := assume hg hb ha, show c, from hg ha hb lemma proj_1st (a : Prop) : a → a → a := assume ha ha', show a, from ha -- please give a different answer than for `proj_1st` lemma proj_2nd (a : Prop) : a → a → a := assume ha ha', show a, from ha' lemma some_nonsense (a b c : Prop) : (a → b → c) → a → (a → c) → b → c := assume hg ha hf hb, have hc : c := hf ha, show c, from hc /- 2.2. Supply a structured proof of the contraposition rule. -/ lemma contrapositive (a b : Prop) : (a → b) → ¬ b → ¬ a := assume hab hnb ha, have hb : b := hab ha, show false, from hnb hb end LoVe
1da8ad9cdba5221998d86f1f6a689107204e6862
22e97a5d648fc451e25a06c668dc03ac7ed7bc25
/src/data/zsqrtd/basic.lean
82d5a9576e072f1a9fcadb78a6365dfb9e4fca79
[ "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
27,027
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import algebra.associated import tactic.ring /-- The ring of integers adjoined with a square root of `d`. These have the form `a + b √d` where `a b : ℤ`. The components are called `re` and `im` by analogy to the negative `d` case, but of course both parts are real here since `d` is nonnegative. -/ structure zsqrtd (d : ℤ) := (re : ℤ) (im : ℤ) prefix `ℤ√`:100 := zsqrtd namespace zsqrtd section parameters {d : ℤ} instance : decidable_eq ℤ√d := by tactic.mk_dec_eq_instance theorem ext : ∀ {z w : ℤ√d}, z = w ↔ z.re = w.re ∧ z.im = w.im | ⟨x, y⟩ ⟨x', y'⟩ := ⟨λ h, by injection h; split; assumption, λ ⟨h₁, h₂⟩, by congr; assumption⟩ /-- Convert an integer to a `ℤ√d` -/ def of_int (n : ℤ) : ℤ√d := ⟨n, 0⟩ theorem of_int_re (n : ℤ) : (of_int n).re = n := rfl theorem of_int_im (n : ℤ) : (of_int n).im = 0 := rfl /-- The zero of the ring -/ def zero : ℤ√d := of_int 0 instance : has_zero ℤ√d := ⟨zsqrtd.zero⟩ @[simp] theorem zero_re : (0 : ℤ√d).re = 0 := rfl @[simp] theorem zero_im : (0 : ℤ√d).im = 0 := rfl instance : inhabited ℤ√d := ⟨0⟩ /-- The one of the ring -/ def one : ℤ√d := of_int 1 instance : has_one ℤ√d := ⟨zsqrtd.one⟩ @[simp] theorem one_re : (1 : ℤ√d).re = 1 := rfl @[simp] theorem one_im : (1 : ℤ√d).im = 0 := rfl /-- The representative of `√d` in the ring -/ def sqrtd : ℤ√d := ⟨0, 1⟩ @[simp] theorem sqrtd_re : (sqrtd : ℤ√d).re = 0 := rfl @[simp] theorem sqrtd_im : (sqrtd : ℤ√d).im = 1 := rfl /-- Addition of elements of `ℤ√d` -/ def add : ℤ√d → ℤ√d → ℤ√d | ⟨x, y⟩ ⟨x', y'⟩ := ⟨x + x', y + y'⟩ instance : has_add ℤ√d := ⟨zsqrtd.add⟩ @[simp] theorem add_def (x y x' y' : ℤ) : (⟨x, y⟩ + ⟨x', y'⟩ : ℤ√d) = ⟨x + x', y + y'⟩ := rfl @[simp] theorem add_re : ∀ z w : ℤ√d, (z + w).re = z.re + w.re | ⟨x, y⟩ ⟨x', y'⟩ := rfl @[simp] theorem add_im : ∀ z w : ℤ√d, (z + w).im = z.im + w.im | ⟨x, y⟩ ⟨x', y'⟩ := rfl @[simp] theorem bit0_re (z) : (bit0 z : ℤ√d).re = bit0 z.re := add_re _ _ @[simp] theorem bit0_im (z) : (bit0 z : ℤ√d).im = bit0 z.im := add_im _ _ @[simp] theorem bit1_re (z) : (bit1 z : ℤ√d).re = bit1 z.re := by simp [bit1] @[simp] theorem bit1_im (z) : (bit1 z : ℤ√d).im = bit0 z.im := by simp [bit1] /-- Negation in `ℤ√d` -/ def neg : ℤ√d → ℤ√d | ⟨x, y⟩ := ⟨-x, -y⟩ instance : has_neg ℤ√d := ⟨zsqrtd.neg⟩ @[simp] theorem neg_re : ∀ z : ℤ√d, (-z).re = -z.re | ⟨x, y⟩ := rfl @[simp] theorem neg_im : ∀ z : ℤ√d, (-z).im = -z.im | ⟨x, y⟩ := rfl /-- Conjugation in `ℤ√d`. The conjugate of `a + b √d` is `a - b √d`. -/ def conj : ℤ√d → ℤ√d | ⟨x, y⟩ := ⟨x, -y⟩ @[simp] theorem conj_re : ∀ z : ℤ√d, (conj z).re = z.re | ⟨x, y⟩ := rfl @[simp] theorem conj_im : ∀ z : ℤ√d, (conj z).im = -z.im | ⟨x, y⟩ := rfl /-- Multiplication in `ℤ√d` -/ def mul : ℤ√d → ℤ√d → ℤ√d | ⟨x, y⟩ ⟨x', y'⟩ := ⟨x * x' + d * y * y', x * y' + y * x'⟩ instance : has_mul ℤ√d := ⟨zsqrtd.mul⟩ @[simp] theorem mul_re : ∀ z w : ℤ√d, (z * w).re = z.re * w.re + d * z.im * w.im | ⟨x, y⟩ ⟨x', y'⟩ := rfl @[simp] theorem mul_im : ∀ z w : ℤ√d, (z * w).im = z.re * w.im + z.im * w.re | ⟨x, y⟩ ⟨x', y'⟩ := rfl instance : comm_ring ℤ√d := by refine { add := (+), zero := 0, neg := has_neg.neg, mul := (*), one := 1, ..}; { intros, simp [ext, add_mul, mul_add, add_comm, add_left_comm, mul_comm, mul_left_comm] } instance : add_comm_monoid ℤ√d := by apply_instance instance : add_monoid ℤ√d := by apply_instance instance : monoid ℤ√d := by apply_instance instance : comm_monoid ℤ√d := by apply_instance instance : comm_semigroup ℤ√d := by apply_instance instance : semigroup ℤ√d := by apply_instance instance : add_comm_semigroup ℤ√d := by apply_instance instance : add_semigroup ℤ√d := by apply_instance instance : comm_semiring ℤ√d := by apply_instance instance : semiring ℤ√d := by apply_instance instance : ring ℤ√d := by apply_instance instance : distrib ℤ√d := by apply_instance instance : zero_ne_one_class ℤ√d := { zero := 0, one := 1, zero_ne_one := dec_trivial } instance : nonzero_comm_ring ℤ√d := { ..zsqrtd.comm_ring, ..zsqrtd.zero_ne_one_class } @[simp] theorem coe_nat_re (n : ℕ) : (n : ℤ√d).re = n := by induction n; simp * @[simp] theorem coe_nat_im (n : ℕ) : (n : ℤ√d).im = 0 := by induction n; simp * theorem coe_nat_val (n : ℕ) : (n : ℤ√d) = ⟨n, 0⟩ := by simp [ext] @[simp] theorem coe_int_re (n : ℤ) : (n : ℤ√d).re = n := by cases n; simp [*, int.of_nat_eq_coe, int.neg_succ_of_nat_eq] @[simp] theorem coe_int_im (n : ℤ) : (n : ℤ√d).im = 0 := by cases n; simp * theorem coe_int_val (n : ℤ) : (n : ℤ√d) = ⟨n, 0⟩ := by simp [ext] instance : char_zero ℤ√d := { cast_injective := λ m n, by simp [ext] } @[simp] theorem of_int_eq_coe (n : ℤ) : (of_int n : ℤ√d) = n := by simp [ext, of_int_re, of_int_im] @[simp] theorem smul_val (n x y : ℤ) : (n : ℤ√d) * ⟨x, y⟩ = ⟨n * x, n * y⟩ := by simp [ext] @[simp] theorem muld_val (x y : ℤ) : sqrtd * ⟨x, y⟩ = ⟨d * y, x⟩ := by simp [ext] @[simp] theorem smuld_val (n x y : ℤ) : sqrtd * (n : ℤ√d) * ⟨x, y⟩ = ⟨d * n * y, n * x⟩ := by simp [ext] theorem decompose {x y : ℤ} : (⟨x, y⟩ : ℤ√d) = x + sqrtd * y := by simp [ext] theorem mul_conj {x y : ℤ} : (⟨x, y⟩ * conj ⟨x, y⟩ : ℤ√d) = x * x - d * y * y := by simp [ext, sub_eq_add_neg, mul_comm] theorem conj_mul : Π {a b : ℤ√d}, conj (a * b) = conj a * conj b := by simp [ext, add_comm] protected lemma coe_int_add (m n : ℤ) : (↑(m + n) : ℤ√d) = ↑m + ↑n := by simp [ext] protected lemma coe_int_sub (m n : ℤ) : (↑(m - n) : ℤ√d) = ↑m - ↑n := by simp [ext, sub_eq_add_neg] protected lemma coe_int_mul (m n : ℤ) : (↑(m * n) : ℤ√d) = ↑m * ↑n := by simp [ext] protected lemma coe_int_inj {m n : ℤ} (h : (↑m : ℤ√d) = ↑n) : m = n := by simpa using congr_arg re h /-- Read `sq_le a c b d` as `a √c ≤ b √d` -/ def sq_le (a c b d : ℕ) : Prop := c*a*a ≤ d*b*b theorem sq_le_of_le {c d x y z w : ℕ} (xz : z ≤ x) (yw : y ≤ w) (xy : sq_le x c y d) : sq_le z c w d := le_trans (mul_le_mul (nat.mul_le_mul_left _ xz) xz (nat.zero_le _) (nat.zero_le _)) $ le_trans xy (mul_le_mul (nat.mul_le_mul_left _ yw) yw (nat.zero_le _) (nat.zero_le _)) theorem sq_le_add_mixed {c d x y z w : ℕ} (xy : sq_le x c y d) (zw : sq_le z c w d) : c * (x * z) ≤ d * (y * w) := nat.mul_self_le_mul_self_iff.2 $ by simpa [mul_comm, mul_left_comm] using mul_le_mul xy zw (nat.zero_le _) (nat.zero_le _) theorem sq_le_add {c d x y z w : ℕ} (xy : sq_le x c y d) (zw : sq_le z c w d) : sq_le (x + z) c (y + w) d := begin have xz := sq_le_add_mixed xy zw, simp [sq_le, mul_assoc] at xy zw, simp [sq_le, mul_add, mul_comm, mul_left_comm, add_le_add, *] end theorem sq_le_cancel {c d x y z w : ℕ} (zw : sq_le y d x c) (h : sq_le (x + z) c (y + w) d) : sq_le z c w d := begin apply le_of_not_gt, intro l, refine not_le_of_gt _ h, simp [sq_le, mul_add, mul_comm, mul_left_comm, add_assoc], have hm := sq_le_add_mixed zw (le_of_lt l), simp [sq_le, mul_assoc] at l zw, exact lt_of_le_of_lt (add_le_add_right zw _) (add_lt_add_left (add_lt_add_of_le_of_lt hm (add_lt_add_of_le_of_lt hm l)) _) end theorem sq_le_smul {c d x y : ℕ} (n : ℕ) (xy : sq_le x c y d) : sq_le (n * x) c (n * y) d := by simpa [sq_le, mul_left_comm, mul_assoc] using nat.mul_le_mul_left (n * n) xy theorem sq_le_mul {d x y z w : ℕ} : (sq_le x 1 y d → sq_le z 1 w d → sq_le (x * w + y * z) d (x * z + d * y * w) 1) ∧ (sq_le x 1 y d → sq_le w d z 1 → sq_le (x * z + d * y * w) 1 (x * w + y * z) d) ∧ (sq_le y d x 1 → sq_le z 1 w d → sq_le (x * z + d * y * w) 1 (x * w + y * z) d) ∧ (sq_le y d x 1 → sq_le w d z 1 → sq_le (x * w + y * z) d (x * z + d * y * w) 1) := by refine ⟨_, _, _, _⟩; { intros xy zw, have := int.mul_nonneg (sub_nonneg_of_le (int.coe_nat_le_coe_nat_of_le xy)) (sub_nonneg_of_le (int.coe_nat_le_coe_nat_of_le zw)), refine int.le_of_coe_nat_le_coe_nat (le_of_sub_nonneg _), convert this, simp only [one_mul, int.coe_nat_add, int.coe_nat_mul], ring } /-- "Generalized" `nonneg`. `nonnegg c d x y` means `a √c + b √d ≥ 0`; we are interested in the case `c = 1` but this is more symmetric -/ def nonnegg (c d : ℕ) : ℤ → ℤ → Prop | (a : ℕ) (b : ℕ) := true | (a : ℕ) -[1+ b] := sq_le (b+1) c a d | -[1+ a] (b : ℕ) := sq_le (a+1) d b c | -[1+ a] -[1+ b] := false theorem nonnegg_comm {c d : ℕ} {x y : ℤ} : nonnegg c d x y = nonnegg d c y x := by induction x; induction y; refl theorem nonnegg_neg_pos {c d} : Π {a b : ℕ}, nonnegg c d (-a) b ↔ sq_le a d b c | 0 b := ⟨by simp [sq_le, nat.zero_le], λa, trivial⟩ | (a+1) b := by rw ← int.neg_succ_of_nat_coe; refl theorem nonnegg_pos_neg {c d} {a b : ℕ} : nonnegg c d a (-b) ↔ sq_le b c a d := by rw nonnegg_comm; exact nonnegg_neg_pos theorem nonnegg_cases_right {c d} {a : ℕ} : Π {b : ℤ}, (Π x : ℕ, b = -x → sq_le x c a d) → nonnegg c d a b | (b:nat) h := trivial | -[1+ b] h := h (b+1) rfl theorem nonnegg_cases_left {c d} {b : ℕ} {a : ℤ} (h : Π x : ℕ, a = -x → sq_le x d b c) : nonnegg c d a b := cast nonnegg_comm (nonnegg_cases_right h) section norm def norm (n : ℤ√d) : ℤ := n.re * n.re - d * n.im * n.im @[simp] lemma norm_zero : norm 0 = 0 := by simp [norm] @[simp] lemma norm_one : norm 1 = 1 := by simp [norm] @[simp] lemma norm_int_cast (n : ℤ) : norm n = n * n := by simp [norm] @[simp] lemma norm_nat_cast (n : ℕ) : norm n = n * n := norm_int_cast n @[simp] lemma norm_mul (n m : ℤ√d) : norm (n * m) = norm n * norm m := by { simp only [norm, mul_im, mul_re], ring } lemma norm_eq_mul_conj (n : ℤ√d) : (norm n : ℤ√d) = n * n.conj := by cases n; simp [norm, conj, zsqrtd.ext, mul_comm, sub_eq_add_neg] instance : is_monoid_hom norm := { map_one := norm_one, map_mul := norm_mul } lemma norm_nonneg (hd : d ≤ 0) (n : ℤ√d) : 0 ≤ n.norm := add_nonneg (mul_self_nonneg _) (by rw [mul_assoc, neg_mul_eq_neg_mul]; exact (mul_nonneg (neg_nonneg.2 hd) (mul_self_nonneg _))) lemma norm_eq_one_iff {x : ℤ√d} : x.norm.nat_abs = 1 ↔ is_unit x := ⟨λ h, is_unit_iff_dvd_one.2 $ (le_total 0 (norm x)).cases_on (λ hx, show x ∣ 1, from ⟨x.conj, by rwa [← int.coe_nat_inj', int.nat_abs_of_nonneg hx, ← @int.cast_inj (ℤ√d) _ _, norm_eq_mul_conj, eq_comm] at h⟩) (λ hx, show x ∣ 1, from ⟨- x.conj, by rwa [← int.coe_nat_inj', int.of_nat_nat_abs_of_nonpos hx, ← @int.cast_inj (ℤ√d) _ _, int.cast_neg, norm_eq_mul_conj, neg_mul_eq_mul_neg, eq_comm] at h⟩), λ h, let ⟨y, hy⟩ := is_unit_iff_dvd_one.1 h in begin have := congr_arg (int.nat_abs ∘ norm) hy, rw [function.comp_app, function.comp_app, norm_mul, int.nat_abs_mul, norm_one, int.nat_abs_one, eq_comm, nat.mul_eq_one_iff] at this, exact this.1 end⟩ end norm end section parameter {d : ℕ} /-- Nonnegativity of an element of `ℤ√d`. -/ def nonneg : ℤ√d → Prop | ⟨a, b⟩ := nonnegg d 1 a b protected def le (a b : ℤ√d) : Prop := nonneg (b - a) instance : has_le ℤ√d := ⟨zsqrtd.le⟩ protected def lt (a b : ℤ√d) : Prop := ¬(b ≤ a) instance : has_lt ℤ√d := ⟨zsqrtd.lt⟩ instance decidable_nonnegg (c d a b) : decidable (nonnegg c d a b) := by cases a; cases b; repeat {rw int.of_nat_eq_coe}; unfold nonnegg sq_le; apply_instance instance decidable_nonneg : Π (a : ℤ√d), decidable (nonneg a) | ⟨a, b⟩ := zsqrtd.decidable_nonnegg _ _ _ _ instance decidable_le (a b : ℤ√d) : decidable (a ≤ b) := decidable_nonneg _ theorem nonneg_cases : Π {a : ℤ√d}, nonneg a → ∃ x y : ℕ, a = ⟨x, y⟩ ∨ a = ⟨x, -y⟩ ∨ a = ⟨-x, y⟩ | ⟨(x : ℕ), (y : ℕ)⟩ h := ⟨x, y, or.inl rfl⟩ | ⟨(x : ℕ), -[1+ y]⟩ h := ⟨x, y+1, or.inr $ or.inl rfl⟩ | ⟨-[1+ x], (y : ℕ)⟩ h := ⟨x+1, y, or.inr $ or.inr rfl⟩ | ⟨-[1+ x], -[1+ y]⟩ h := false.elim h lemma nonneg_add_lem {x y z w : ℕ} (xy : nonneg ⟨x, -y⟩) (zw : nonneg ⟨-z, w⟩) : nonneg (⟨x, -y⟩ + ⟨-z, w⟩) := have nonneg ⟨int.sub_nat_nat x z, int.sub_nat_nat w y⟩, from int.sub_nat_nat_elim x z (λm n i, sq_le y d m 1 → sq_le n 1 w d → nonneg ⟨i, int.sub_nat_nat w y⟩) (λj k, int.sub_nat_nat_elim w y (λm n i, sq_le n d (k + j) 1 → sq_le k 1 m d → nonneg ⟨int.of_nat j, i⟩) (λm n xy zw, trivial) (λm n xy zw, sq_le_cancel zw xy)) (λj k, int.sub_nat_nat_elim w y (λm n i, sq_le n d k 1 → sq_le (k + j + 1) 1 m d → nonneg ⟨-[1+ j], i⟩) (λm n xy zw, sq_le_cancel xy zw) (λm n xy zw, let t := nat.le_trans zw (sq_le_of_le (nat.le_add_right n (m+1)) (le_refl _) xy) in have k + j + 1 ≤ k, from nat.mul_self_le_mul_self_iff.2 (by repeat{rw one_mul at t}; exact t), absurd this (not_le_of_gt $ nat.succ_le_succ $ nat.le_add_right _ _))) (nonnegg_pos_neg.1 xy) (nonnegg_neg_pos.1 zw), show nonneg ⟨_, _⟩, by rw [neg_add_eq_sub]; rwa [int.sub_nat_nat_eq_coe,int.sub_nat_nat_eq_coe] at this theorem nonneg_add {a b : ℤ√d} (ha : nonneg a) (hb : nonneg b) : nonneg (a + b) := begin rcases nonneg_cases ha with ⟨x, y, rfl|rfl|rfl⟩; rcases nonneg_cases hb with ⟨z, w, rfl|rfl|rfl⟩; dsimp [add, nonneg] at ha hb ⊢, { trivial }, { refine nonnegg_cases_right (λi h, sq_le_of_le _ _ (nonnegg_pos_neg.1 hb)), { exact int.coe_nat_le.1 (le_of_neg_le_neg (@int.le.intro _ _ y (by simp [add_comm, *]))) }, { apply nat.le_add_left } }, { refine nonnegg_cases_left (λi h, sq_le_of_le _ _ (nonnegg_neg_pos.1 hb)), { exact int.coe_nat_le.1 (le_of_neg_le_neg (@int.le.intro _ _ x (by simp [add_comm, *]))) }, { apply nat.le_add_left } }, { refine nonnegg_cases_right (λi h, sq_le_of_le _ _ (nonnegg_pos_neg.1 ha)), { exact int.coe_nat_le.1 (le_of_neg_le_neg (@int.le.intro _ _ w (by simp *))) }, { apply nat.le_add_right } }, { simpa [add_comm] using nonnegg_pos_neg.2 (sq_le_add (nonnegg_pos_neg.1 ha) (nonnegg_pos_neg.1 hb)) }, { exact nonneg_add_lem ha hb }, { refine nonnegg_cases_left (λi h, sq_le_of_le _ _ (nonnegg_neg_pos.1 ha)), { exact int.coe_nat_le.1 (le_of_neg_le_neg (@int.le.intro _ _ z (by simp *))) }, { apply nat.le_add_right } }, { rw [add_comm, add_comm ↑y], exact nonneg_add_lem hb ha }, { simpa [add_comm] using nonnegg_neg_pos.2 (sq_le_add (nonnegg_neg_pos.1 ha) (nonnegg_neg_pos.1 hb)) }, end theorem le_refl (a : ℤ√d) : a ≤ a := show nonneg (a - a), by simp protected theorem le_trans {a b c : ℤ√d} (ab : a ≤ b) (bc : b ≤ c) : a ≤ c := have nonneg (b - a + (c - b)), from nonneg_add ab bc, by simpa [sub_add_sub_cancel'] theorem nonneg_iff_zero_le {a : ℤ√d} : nonneg a ↔ 0 ≤ a := show _ ↔ nonneg _, by simp theorem le_of_le_le {x y z w : ℤ} (xz : x ≤ z) (yw : y ≤ w) : (⟨x, y⟩ : ℤ√d) ≤ ⟨z, w⟩ := show nonneg ⟨z - x, w - y⟩, from match z - x, w - y, int.le.dest_sub xz, int.le.dest_sub yw with ._, ._, ⟨a, rfl⟩, ⟨b, rfl⟩ := trivial end theorem le_arch (a : ℤ√d) : ∃n : ℕ, a ≤ n := let ⟨x, y, (h : a ≤ ⟨x, y⟩)⟩ := show ∃x y : ℕ, nonneg (⟨x, y⟩ + -a), from match -a with | ⟨int.of_nat x, int.of_nat y⟩ := ⟨0, 0, trivial⟩ | ⟨int.of_nat x, -[1+ y]⟩ := ⟨0, y+1, by simp [int.neg_succ_of_nat_coe, add_assoc]⟩ | ⟨-[1+ x], int.of_nat y⟩ := ⟨x+1, 0, by simp [int.neg_succ_of_nat_coe, add_assoc]⟩ | ⟨-[1+ x], -[1+ y]⟩ := ⟨x+1, y+1, by simp [int.neg_succ_of_nat_coe, add_assoc]⟩ end in begin refine ⟨x + d*y, zsqrtd.le_trans h _⟩, rw [← int.cast_coe_nat, ← of_int_eq_coe], change nonneg ⟨(↑x + d*y) - ↑x, 0-↑y⟩, cases y with y, { simp }, have h : ∀y, sq_le y d (d * y) 1 := λ y, by simpa [sq_le, mul_comm, mul_left_comm] using nat.mul_le_mul_right (y * y) (nat.le_mul_self d), rw [show (x:ℤ) + d * nat.succ y - x = d * nat.succ y, by simp], exact h (y+1) end protected theorem nonneg_total : Π (a : ℤ√d), nonneg a ∨ nonneg (-a) | ⟨(x : ℕ), (y : ℕ)⟩ := or.inl trivial | ⟨-[1+ x], -[1+ y]⟩ := or.inr trivial | ⟨0, -[1+ y]⟩ := or.inr trivial | ⟨-[1+ x], 0⟩ := or.inr trivial | ⟨(x+1:ℕ), -[1+ y]⟩ := nat.le_total | ⟨-[1+ x], (y+1:ℕ)⟩ := nat.le_total protected theorem le_total (a b : ℤ√d) : a ≤ b ∨ b ≤ a := let t := nonneg_total (b - a) in by rw [show -(b-a) = a-b, from neg_sub b a] at t; exact t instance : preorder ℤ√d := { le := zsqrtd.le, le_refl := zsqrtd.le_refl, le_trans := @zsqrtd.le_trans, lt := zsqrtd.lt, lt_iff_le_not_le := λ a b, (and_iff_right_of_imp (zsqrtd.le_total _ _).resolve_left).symm } protected theorem add_le_add_left (a b : ℤ√d) (ab : a ≤ b) (c : ℤ√d) : c + a ≤ c + b := show nonneg _, by rw add_sub_add_left_eq_sub; exact ab protected theorem le_of_add_le_add_left (a b c : ℤ√d) (h : c + a ≤ c + b) : a ≤ b := by simpa using zsqrtd.add_le_add_left _ _ h (-c) protected theorem add_lt_add_left (a b : ℤ√d) (h : a < b) (c) : c + a < c + b := λ h', h (zsqrtd.le_of_add_le_add_left _ _ _ h') theorem nonneg_smul {a : ℤ√d} {n : ℕ} (ha : nonneg a) : nonneg (n * a) := by rw ← int.cast_coe_nat; exact match a, nonneg_cases ha, ha with | ._, ⟨x, y, or.inl rfl⟩, ha := by rw smul_val; trivial | ._, ⟨x, y, or.inr $ or.inl rfl⟩, ha := by rw smul_val; simpa using nonnegg_pos_neg.2 (sq_le_smul n $ nonnegg_pos_neg.1 ha) | ._, ⟨x, y, or.inr $ or.inr rfl⟩, ha := by rw smul_val; simpa using nonnegg_neg_pos.2 (sq_le_smul n $ nonnegg_neg_pos.1 ha) end theorem nonneg_muld {a : ℤ√d} (ha : nonneg a) : nonneg (sqrtd * a) := by refine match a, nonneg_cases ha, ha with | ._, ⟨x, y, or.inl rfl⟩, ha := trivial | ._, ⟨x, y, or.inr $ or.inl rfl⟩, ha := by simp; apply nonnegg_neg_pos.2; simpa [sq_le, mul_comm, mul_left_comm] using nat.mul_le_mul_left d (nonnegg_pos_neg.1 ha) | ._, ⟨x, y, or.inr $ or.inr rfl⟩, ha := by simp; apply nonnegg_pos_neg.2; simpa [sq_le, mul_comm, mul_left_comm] using nat.mul_le_mul_left d (nonnegg_neg_pos.1 ha) end theorem nonneg_mul_lem {x y : ℕ} {a : ℤ√d} (ha : nonneg a) : nonneg (⟨x, y⟩ * a) := have (⟨x, y⟩ * a : ℤ√d) = x * a + sqrtd * (y * a), by rw [decompose, right_distrib, mul_assoc]; refl, by rw this; exact nonneg_add (nonneg_smul ha) (nonneg_muld $ nonneg_smul ha) theorem nonneg_mul {a b : ℤ√d} (ha : nonneg a) (hb : nonneg b) : nonneg (a * b) := match a, b, nonneg_cases ha, nonneg_cases hb, ha, hb with | ._, ._, ⟨x, y, or.inl rfl⟩, ⟨z, w, or.inl rfl⟩, ha, hb := trivial | ._, ._, ⟨x, y, or.inl rfl⟩, ⟨z, w, or.inr $ or.inr rfl⟩, ha, hb := nonneg_mul_lem hb | ._, ._, ⟨x, y, or.inl rfl⟩, ⟨z, w, or.inr $ or.inl rfl⟩, ha, hb := nonneg_mul_lem hb | ._, ._, ⟨x, y, or.inr $ or.inr rfl⟩, ⟨z, w, or.inl rfl⟩, ha, hb := by rw mul_comm; exact nonneg_mul_lem ha | ._, ._, ⟨x, y, or.inr $ or.inl rfl⟩, ⟨z, w, or.inl rfl⟩, ha, hb := by rw mul_comm; exact nonneg_mul_lem ha | ._, ._, ⟨x, y, or.inr $ or.inr rfl⟩, ⟨z, w, or.inr $ or.inr rfl⟩, ha, hb := by rw [calc (⟨-x, y⟩ * ⟨-z, w⟩ : ℤ√d) = ⟨_, _⟩ : rfl ... = ⟨x * z + d * y * w, -(x * w + y * z)⟩ : by simp [add_comm]]; exact nonnegg_pos_neg.2 (sq_le_mul.left (nonnegg_neg_pos.1 ha) (nonnegg_neg_pos.1 hb)) | ._, ._, ⟨x, y, or.inr $ or.inr rfl⟩, ⟨z, w, or.inr $ or.inl rfl⟩, ha, hb := by rw [calc (⟨-x, y⟩ * ⟨z, -w⟩ : ℤ√d) = ⟨_, _⟩ : rfl ... = ⟨-(x * z + d * y * w), x * w + y * z⟩ : by simp [add_comm]]; exact nonnegg_neg_pos.2 (sq_le_mul.right.left (nonnegg_neg_pos.1 ha) (nonnegg_pos_neg.1 hb)) | ._, ._, ⟨x, y, or.inr $ or.inl rfl⟩, ⟨z, w, or.inr $ or.inr rfl⟩, ha, hb := by rw [calc (⟨x, -y⟩ * ⟨-z, w⟩ : ℤ√d) = ⟨_, _⟩ : rfl ... = ⟨-(x * z + d * y * w), x * w + y * z⟩ : by simp [add_comm]]; exact nonnegg_neg_pos.2 (sq_le_mul.right.right.left (nonnegg_pos_neg.1 ha) (nonnegg_neg_pos.1 hb)) | ._, ._, ⟨x, y, or.inr $ or.inl rfl⟩, ⟨z, w, or.inr $ or.inl rfl⟩, ha, hb := by rw [calc (⟨x, -y⟩ * ⟨z, -w⟩ : ℤ√d) = ⟨_, _⟩ : rfl ... = ⟨x * z + d * y * w, -(x * w + y * z)⟩ : by simp [add_comm]]; exact nonnegg_pos_neg.2 (sq_le_mul.right.right.right (nonnegg_pos_neg.1 ha) (nonnegg_pos_neg.1 hb)) end protected theorem mul_nonneg (a b : ℤ√d) : 0 ≤ a → 0 ≤ b → 0 ≤ a * b := by repeat {rw ← nonneg_iff_zero_le}; exact nonneg_mul theorem not_sq_le_succ (c d y) (h : 0 < c) : ¬sq_le (y + 1) c 0 d := not_le_of_gt $ mul_pos (mul_pos h $ nat.succ_pos _) $ nat.succ_pos _ /-- A nonsquare is a natural number that is not equal to the square of an integer. This is implemented as a typeclass because it's a necessary condition for much of the Pell equation theory. -/ class nonsquare (x : ℕ) : Prop := (ns [] : ∀n : ℕ, x ≠ n*n) parameter [dnsq : nonsquare d] include dnsq theorem d_pos : 0 < d := lt_of_le_of_ne (nat.zero_le _) $ ne.symm $ (nonsquare.ns d 0) theorem divides_sq_eq_zero {x y} (h : x * x = d * y * y) : x = 0 ∧ y = 0 := let g := x.gcd y in or.elim g.eq_zero_or_pos (λH, ⟨nat.eq_zero_of_gcd_eq_zero_left H, nat.eq_zero_of_gcd_eq_zero_right H⟩) (λgpos, false.elim $ let ⟨m, n, co, (hx : x = m * g), (hy : y = n * g)⟩ := nat.exists_coprime gpos in begin rw [hx, hy] at h, have : m * m = d * (n * n) := nat.eq_of_mul_eq_mul_left (mul_pos gpos gpos) (by simpa [mul_comm, mul_left_comm] using h), have co2 := let co1 := co.mul_right co in co1.mul co1, exact nonsquare.ns d m (nat.dvd_antisymm (by rw this; apply dvd_mul_right) $ co2.dvd_of_dvd_mul_right $ by simp [this]) end) theorem divides_sq_eq_zero_z {x y : ℤ} (h : x * x = d * y * y) : x = 0 ∧ y = 0 := by rw [mul_assoc, ← int.nat_abs_mul_self, ← int.nat_abs_mul_self, ← int.coe_nat_mul, ← mul_assoc] at h; exact let ⟨h1, h2⟩ := divides_sq_eq_zero (int.coe_nat_inj h) in ⟨int.eq_zero_of_nat_abs_eq_zero h1, int.eq_zero_of_nat_abs_eq_zero h2⟩ theorem not_divides_square (x y) : (x + 1) * (x + 1) ≠ d * (y + 1) * (y + 1) := λe, by have t := (divides_sq_eq_zero e).left; contradiction theorem nonneg_antisymm : Π {a : ℤ√d}, nonneg a → nonneg (-a) → a = 0 | ⟨0, 0⟩ xy yx := rfl | ⟨-[1+ x], -[1+ y]⟩ xy yx := false.elim xy | ⟨(x+1:nat), (y+1:nat)⟩ xy yx := false.elim yx | ⟨-[1+ x], 0⟩ xy yx := absurd xy (not_sq_le_succ _ _ _ dec_trivial) | ⟨(x+1:nat), 0⟩ xy yx := absurd yx (not_sq_le_succ _ _ _ dec_trivial) | ⟨0, -[1+ y]⟩ xy yx := absurd xy (not_sq_le_succ _ _ _ d_pos) | ⟨0, (y+1:nat)⟩ _ yx := absurd yx (not_sq_le_succ _ _ _ d_pos) | ⟨(x+1:nat), -[1+ y]⟩ (xy : sq_le _ _ _ _) (yx : sq_le _ _ _ _) := let t := le_antisymm yx xy in by rw[one_mul] at t; exact absurd t (not_divides_square _ _) | ⟨-[1+ x], (y+1:nat)⟩ (xy : sq_le _ _ _ _) (yx : sq_le _ _ _ _) := let t := le_antisymm xy yx in by rw[one_mul] at t; exact absurd t (not_divides_square _ _) theorem le_antisymm {a b : ℤ√d} (ab : a ≤ b) (ba : b ≤ a) : a = b := eq_of_sub_eq_zero $ nonneg_antisymm ba (by rw neg_sub; exact ab) instance : decidable_linear_order ℤ√d := { le_antisymm := @zsqrtd.le_antisymm, le_total := zsqrtd.le_total, decidable_le := zsqrtd.decidable_le, ..zsqrtd.preorder } protected theorem eq_zero_or_eq_zero_of_mul_eq_zero : Π {a b : ℤ√d}, a * b = 0 → a = 0 ∨ b = 0 | ⟨x, y⟩ ⟨z, w⟩ h := by injection h with h1 h2; exact have h1 : x*z = -(d*y*w), from eq_neg_of_add_eq_zero h1, have h2 : x*w = -(y*z), from eq_neg_of_add_eq_zero h2, have fin : x*x = d*y*y → (⟨x, y⟩:ℤ√d) = 0, from λe, match x, y, divides_sq_eq_zero_z e with ._, ._, ⟨rfl, rfl⟩ := rfl end, if z0 : z = 0 then if w0 : w = 0 then or.inr (match z, w, z0, w0 with ._, ._, rfl, rfl := rfl end) else or.inl $ fin $ eq_of_mul_eq_mul_right w0 $ calc x * x * w = -y * (x * z) : by simp [h2, mul_assoc, mul_left_comm] ... = d * y * y * w : by simp [h1, mul_assoc, mul_left_comm] else or.inl $ fin $ eq_of_mul_eq_mul_right z0 $ calc x * x * z = d * -y * (x * w) : by simp [h1, mul_assoc, mul_left_comm] ... = d * y * y * z : by simp [h2, mul_assoc, mul_left_comm] instance : integral_domain ℤ√d := { zero_ne_one := zero_ne_one, eq_zero_or_eq_zero_of_mul_eq_zero := @zsqrtd.eq_zero_or_eq_zero_of_mul_eq_zero, ..zsqrtd.comm_ring } protected theorem mul_pos (a b : ℤ√d) (a0 : 0 < a) (b0 : 0 < b) : 0 < a * b := λab, or.elim (eq_zero_or_eq_zero_of_mul_eq_zero (le_antisymm ab (mul_nonneg _ _ (le_of_lt a0) (le_of_lt b0)))) (λe, ne_of_gt a0 e) (λe, ne_of_gt b0 e) instance : decidable_linear_ordered_comm_ring ℤ√d := { add_le_add_left := @zsqrtd.add_le_add_left, zero_ne_one := zero_ne_one, mul_pos := @zsqrtd.mul_pos, zero_lt_one := dec_trivial, ..zsqrtd.comm_ring, ..zsqrtd.decidable_linear_order } instance : decidable_linear_ordered_semiring ℤ√d := by apply_instance instance : linear_ordered_semiring ℤ√d := by apply_instance instance : ordered_semiring ℤ√d := by apply_instance end end zsqrtd
812b72eda10e8bb2cc6fd8385df41a80618873f8
64874bd1010548c7f5a6e3e8902efa63baaff785
/hott/init/logic.hlean
12dbff7abb52b44577e3f2bfac40362bd8e24db6
[ "Apache-2.0" ]
permissive
tjiaqi/lean
4634d729795c164664d10d093f3545287c76628f
d0ce4cf62f4246b0600c07e074d86e51f2195e30
refs/heads/master
1,622,323,796,480
1,422,643,069,000
1,422,643,069,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
11,203
hlean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.datatypes init.reserved_notation definition not.{l} (a : Type.{l}) := a → empty.{l} prefix `¬` := not definition absurd {a : Type} {b : Type} (H₁ : a) (H₂ : ¬a) : b := empty.rec (λ e, b) (H₂ H₁) definition mt {a b : Type} (H₁ : a → b) (H₂ : ¬b) : ¬a := assume Ha : a, absurd (H₁ Ha) H₂ -- not -- --- protected definition not_empty : ¬ empty := assume H : empty, H definition not_not_intro {a : Type} (Ha : a) : ¬¬a := assume Hna : ¬a, absurd Ha Hna definition not.intro {a : Type} (H : a → empty) : ¬a := H definition not.elim {a : Type} (H₁ : ¬a) (H₂ : a) : empty := H₁ H₂ definition not_not_of_not_implies {a b : Type} (H : ¬(a → b)) : ¬¬a := assume Hna : ¬a, absurd (assume Ha : a, absurd Ha Hna) H definition not_of_not_implies {a b : Type} (H : ¬(a → b)) : ¬b := assume Hb : b, absurd (assume Ha : a, Hb) H -- eq -- -- notation a = b := eq a b definition rfl {A : Type} {a : A} := eq.refl a namespace eq variables {A : Type} variables {a b c a' : A} definition subst {P : A → Type} (H₁ : a = b) (H₂ : P a) : P b := rec H₂ H₁ definition trans (H₁ : a = b) (H₂ : b = c) : a = c := subst H₂ H₁ definition symm (H : a = b) : b = a := subst H (refl a) namespace ops notation H `⁻¹` := symm H --input with \sy or \-1 or \inv notation H1 ⬝ H2 := trans H1 H2 notation H1 ▸ H2 := subst H1 H2 end ops end eq calc_subst eq.subst calc_refl eq.refl calc_trans eq.trans calc_symm eq.symm namespace lift definition down_up.{l₁ l₂} {A : Type.{l₁}} (a : A) : down (up.{l₁ l₂} a) = a := rfl definition up_down.{l₁ l₂} {A : Type.{l₁}} (a : lift.{l₁ l₂} A) : up (down a) = a := lift.rec_on a (λ d, rfl) end lift -- ne -- -- definition ne {A : Type} (a b : A) := ¬(a = b) notation a ≠ b := ne a b namespace ne open eq.ops variable {A : Type} variables {a b : A} definition intro : (a = b → empty) → a ≠ b := assume H, H definition elim : a ≠ b → a = b → empty := assume H₁ H₂, H₁ H₂ definition irrefl : a ≠ a → empty := assume H, H rfl definition symm : a ≠ b → b ≠ a := assume (H : a ≠ b) (H₁ : b = a), H (H₁⁻¹) end ne section open eq.ops variables {A : Type} {a b c : A} definition false.of_ne : a ≠ a → empty := assume H, H rfl definition ne.of_eq_of_ne : a = b → b ≠ c → a ≠ c := assume H₁ H₂, H₁⁻¹ ▸ H₂ definition ne.of_ne_of_eq : a ≠ b → b = c → a ≠ c := assume H₁ H₂, H₂ ▸ H₁ end calc_trans ne.of_eq_of_ne calc_trans ne.of_ne_of_eq -- iff -- --- definition iff (a b : Type) := prod (a → b) (b → a) notation a <-> b := iff a b notation a ↔ b := iff a b namespace iff variables {a b c : Type} definition def : (a ↔ b) = (prod (a → b) (b → a)) := rfl definition intro (H₁ : a → b) (H₂ : b → a) : a ↔ b := prod.mk H₁ H₂ definition elim (H₁ : (a → b) → (b → a) → c) (H₂ : a ↔ b) : c := prod.rec H₁ H₂ definition elim_left (H : a ↔ b) : a → b := elim (assume H₁ H₂, H₁) H definition mp := @elim_left definition elim_right (H : a ↔ b) : b → a := elim (assume H₁ H₂, H₂) H definition flip_sign (H₁ : a ↔ b) : ¬a ↔ ¬b := intro (assume Hna, mt (elim_right H₁) Hna) (assume Hnb, mt (elim_left H₁) Hnb) definition refl (a : Type) : a ↔ a := intro (assume H, H) (assume H, H) definition rfl {a : Type} : a ↔ a := refl a definition trans (H₁ : a ↔ b) (H₂ : b ↔ c) : a ↔ c := intro (assume Ha, elim_left H₂ (elim_left H₁ Ha)) (assume Hc, elim_right H₁ (elim_right H₂ Hc)) definition symm (H : a ↔ b) : b ↔ a := intro (assume Hb, elim_right H Hb) (assume Ha, elim_left H Ha) definition true_elim (H : a ↔ unit) : a := mp (symm H) unit.star definition false_elim (H : a ↔ empty) : ¬a := assume Ha : a, mp H Ha open eq.ops definition of_eq {a b : Type} (H : a = b) : a ↔ b := iff.intro (λ Ha, H ▸ Ha) (λ Hb, H⁻¹ ▸ Hb) end iff calc_refl iff.refl calc_trans iff.trans -- inhabited -- --------- inductive inhabited [class] (A : Type) : Type := mk : A → inhabited A namespace inhabited protected definition destruct {A : Type} {B : Type} (H1 : inhabited A) (H2 : A → B) : B := inhabited.rec H2 H1 definition fun_inhabited [instance] (A : Type) {B : Type} (H : inhabited B) : inhabited (A → B) := destruct H (λb, mk (λa, b)) definition dfun_inhabited [instance] (A : Type) {B : A → Type} (H : Πx, inhabited (B x)) : inhabited (Πx, B x) := mk (λa, destruct (H a) (λb, b)) definition default (A : Type) [H : inhabited A] : A := destruct H (take a, a) end inhabited -- decidable -- --------- inductive decidable.{l} [class] (p : Type.{l}) : Type.{l} := inl : p → decidable p, inr : ¬p → decidable p namespace decidable variables {p q : Type} definition pos_witness [C : decidable p] (H : p) : p := rec_on C (λ Hp, Hp) (λ Hnp, absurd H Hnp) definition neg_witness [C : decidable p] (H : ¬ p) : ¬ p := rec_on C (λ Hp, absurd Hp H) (λ Hnp, Hnp) definition by_cases {q : Type} [C : decidable p] (Hpq : p → q) (Hnpq : ¬p → q) : q := rec_on C (assume Hp, Hpq Hp) (assume Hnp, Hnpq Hnp) definition em (p : Type) [H : decidable p] : sum p ¬p := by_cases (λ Hp, sum.inl Hp) (λ Hnp, sum.inr Hnp) definition by_contradiction [Hp : decidable p] (H : ¬p → empty) : p := by_cases (assume H₁ : p, H₁) (assume H₁ : ¬p, empty.rec (λ e, p) (H H₁)) definition decidable_iff_equiv (Hp : decidable p) (H : p ↔ q) : decidable q := rec_on Hp (assume Hp : p, inl (iff.elim_left H Hp)) (assume Hnp : ¬p, inr (iff.elim_left (iff.flip_sign H) Hnp)) definition decidable_eq_equiv.{l} {p q : Type.{l}} (Hp : decidable p) (H : p = q) : decidable q := decidable_iff_equiv Hp (iff.of_eq H) end decidable section variables {p q : Type} open decidable (rec_on inl inr) definition unit.decidable [instance] : decidable unit := inl unit.star definition empty.decidable [instance] : decidable empty := inr not_empty definition prod.decidable [instance] (Hp : decidable p) (Hq : decidable q) : decidable (prod p q) := rec_on Hp (assume Hp : p, rec_on Hq (assume Hq : q, inl (prod.mk Hp Hq)) (assume Hnq : ¬q, inr (λ H : prod p q, prod.rec_on H (λ Hp Hq, absurd Hq Hnq)))) (assume Hnp : ¬p, inr (λ H : prod p q, prod.rec_on H (λ Hp Hq, absurd Hp Hnp))) definition sum.decidable [instance] (Hp : decidable p) (Hq : decidable q) : decidable (sum p q) := rec_on Hp (assume Hp : p, inl (sum.inl Hp)) (assume Hnp : ¬p, rec_on Hq (assume Hq : q, inl (sum.inr Hq)) (assume Hnq : ¬q, inr (λ H : sum p q, sum.rec_on H (λ Hp, absurd Hp Hnp) (λ Hq, absurd Hq Hnq)))) definition not.decidable [instance] (Hp : decidable p) : decidable (¬p) := rec_on Hp (assume Hp, inr (not_not_intro Hp)) (assume Hnp, inl Hnp) definition implies.decidable [instance] (Hp : decidable p) (Hq : decidable q) : decidable (p → q) := rec_on Hp (assume Hp : p, rec_on Hq (assume Hq : q, inl (assume H, Hq)) (assume Hnq : ¬q, inr (assume H : p → q, absurd (H Hp) Hnq))) (assume Hnp : ¬p, inl (assume Hp, absurd Hp Hnp)) definition iff.decidable [instance] (Hp : decidable p) (Hq : decidable q) : decidable (p ↔ q) := _ end definition decidable_pred {A : Type} (R : A → Type) := Π (a : A), decidable (R a) definition decidable_rel {A : Type} (R : A → A → Type) := Π (a b : A), decidable (R a b) definition decidable_eq (A : Type) := decidable_rel (@eq A) definition ite (c : Type) [H : decidable c] {A : Type} (t e : A) : A := decidable.rec_on H (λ Hc, t) (λ Hnc, e) definition if_pos {c : Type} [H : decidable c] (Hc : c) {A : Type} {t e : A} : (if c then t else e) = t := decidable.rec (λ Hc : c, eq.refl (@ite c (decidable.inl Hc) A t e)) (λ Hnc : ¬c, absurd Hc Hnc) H definition if_neg {c : Type} [H : decidable c] (Hnc : ¬c) {A : Type} {t e : A} : (if c then t else e) = e := decidable.rec (λ Hc : c, absurd Hc Hnc) (λ Hnc : ¬c, eq.refl (@ite c (decidable.inr Hnc) A t e)) H definition if_t_t (c : Type) [H : decidable c] {A : Type} (t : A) : (if c then t else t) = t := decidable.rec (λ Hc : c, eq.refl (@ite c (decidable.inl Hc) A t t)) (λ Hnc : ¬c, eq.refl (@ite c (decidable.inr Hnc) A t t)) H definition if_unit {A : Type} (t e : A) : (if unit then t else e) = t := if_pos unit.star definition if_empty {A : Type} (t e : A) : (if empty then t else e) = e := if_neg not_empty definition if_cond_congr {c₁ c₂ : Type} [H₁ : decidable c₁] [H₂ : decidable c₂] (Heq : c₁ ↔ c₂) {A : Type} (t e : A) : (if c₁ then t else e) = (if c₂ then t else e) := decidable.rec_on H₁ (λ Hc₁ : c₁, decidable.rec_on H₂ (λ Hc₂ : c₂, if_pos Hc₁ ⬝ (if_pos Hc₂)⁻¹) (λ Hnc₂ : ¬c₂, absurd (iff.elim_left Heq Hc₁) Hnc₂)) (λ Hnc₁ : ¬c₁, decidable.rec_on H₂ (λ Hc₂ : c₂, absurd (iff.elim_right Heq Hc₂) Hnc₁) (λ Hnc₂ : ¬c₂, if_neg Hnc₁ ⬝ (if_neg Hnc₂)⁻¹)) definition if_congr_aux {c₁ c₂ : Type} [H₁ : decidable c₁] [H₂ : decidable c₂] {A : Type} {t₁ t₂ e₁ e₂ : A} (Hc : c₁ ↔ c₂) (Ht : t₁ = t₂) (He : e₁ = e₂) : (if c₁ then t₁ else e₁) = (if c₂ then t₂ else e₂) := Ht ▸ He ▸ (if_cond_congr Hc t₁ e₁) definition if_congr {c₁ c₂ : Type} [H₁ : decidable c₁] {A : Type} {t₁ t₂ e₁ e₂ : A} (Hc : c₁ ↔ c₂) (Ht : t₁ = t₂) (He : e₁ = e₂) : (if c₁ then t₁ else e₁) = (@ite c₂ (decidable.decidable_iff_equiv H₁ Hc) A t₂ e₂) := have H2 [visible] : decidable c₂, from (decidable.decidable_iff_equiv H₁ Hc), if_congr_aux Hc Ht He -- We use "dependent" if-then-else to be able to communicate the if-then-else condition -- to the branches definition dite (c : Type) [H : decidable c] {A : Type} (t : c → A) (e : ¬ c → A) : A := decidable.rec_on H (λ Hc, t Hc) (λ Hnc, e Hnc) definition dif_pos {c : Type} [H : decidable c] (Hc : c) {A : Type} {t : c → A} {e : ¬ c → A} : (if H : c then t H else e H) = t (decidable.pos_witness Hc) := decidable.rec (λ Hc : c, eq.refl (@dite c (decidable.inl Hc) A t e)) (λ Hnc : ¬c, absurd Hc Hnc) H definition dif_neg {c : Type} [H : decidable c] (Hnc : ¬c) {A : Type} {t : c → A} {e : ¬ c → A} : (if H : c then t H else e H) = e (decidable.neg_witness Hnc) := decidable.rec (λ Hc : c, absurd Hc Hnc) (λ Hnc : ¬c, eq.refl (@dite c (decidable.inr Hnc) A t e)) H -- Remark: dite and ite are "definitionally equal" when we ignore the proofs. definition dite_ite_eq (c : Type) [H : decidable c] {A : Type} (t : A) (e : A) : dite c (λh, t) (λh, e) = ite c t e := rfl
22aee10b756bd3f142dd238f891b70982eb487e9
9dc8cecdf3c4634764a18254e94d43da07142918
/src/algebra/homology/Module.lean
295bb7921d4250dd9817658c0102a7d4221a1f89
[ "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
3,837
lean
/- Copyright (c) 2021 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import algebra.homology.homotopy import algebra.category.Module.abelian import algebra.category.Module.subobject /-! # Complexes of modules We provide some additional API to work with homological complexes in `Module R`. -/ universes v u open_locale classical noncomputable theory open category_theory category_theory.limits homological_complex variables {R : Type v} [ring R] variables {ι : Type*} {c : complex_shape ι} {C D : homological_complex (Module.{u} R) c} namespace Module /-- To prove that two maps out of a homology group are equal, it suffices to check they are equal on the images of cycles. -/ lemma homology_ext {L M N K : Module R} {f : L ⟶ M} {g : M ⟶ N} (w : f ≫ g = 0) {h k : homology f g w ⟶ K} (w : ∀ (x : linear_map.ker g), h (cokernel.π (image_to_kernel _ _ w) (to_kernel_subobject x)) = k (cokernel.π (image_to_kernel _ _ w) (to_kernel_subobject x))) : h = k := begin refine cokernel_funext (λ n, _), -- Gosh it would be nice if `equiv_rw` could directly use an isomorphism, or an enriched `≃`. equiv_rw (kernel_subobject_iso g ≪≫ Module.kernel_iso_ker g).to_linear_equiv.to_equiv at n, convert w n; simp [to_kernel_subobject], end /-- Bundle an element `C.X i` such that `C.d_from i x = 0` as a term of `C.cycles i`. -/ abbreviation to_cycles {C : homological_complex (Module.{u} R) c} {i : ι} (x : linear_map.ker (C.d_from i)) : C.cycles i := to_kernel_subobject x @[ext] lemma cycles_ext {C : homological_complex (Module.{u} R) c} {i : ι} {x y : C.cycles i} (w : (C.cycles i).arrow x = (C.cycles i).arrow y) : x = y := begin apply_fun (C.cycles i).arrow using (Module.mono_iff_injective _).mp (cycles C i).arrow_mono, exact w, end local attribute [instance] concrete_category.has_coe_to_sort @[simp] lemma cycles_map_to_cycles (f : C ⟶ D) {i : ι} (x : linear_map.ker (C.d_from i)) : (cycles_map f i) (to_cycles x) = to_cycles ⟨f.f i x.1, by simp [x.2]⟩ := by { ext, simp, } /-- Build a term of `C.homology i` from an element `C.X i` such that `C.d_from i x = 0`. -/ abbreviation to_homology {C : homological_complex (Module.{u} R) c} {i : ι} (x : linear_map.ker (C.d_from i)) : C.homology i := homology.π (C.d_to i) (C.d_from i) _ (to_cycles x) @[ext] lemma homology_ext' {M : Module R} (i : ι) {h k : C.homology i ⟶ M} (w : ∀ (x : linear_map.ker (C.d_from i)), h (to_homology x) = k (to_homology x)) : h = k := homology_ext _ w /-- We give an alternative proof of `homology_map_eq_of_homotopy`, specialized to the setting of `V = Module R`, to demonstrate the use of extensionality lemmas for homology in `Module R`. -/ example (f g : C ⟶ D) (h : homotopy f g) (i : ι) : (homology_functor (Module.{u} R) c i).map f = (homology_functor (Module.{u} R) c i).map g := begin -- To check that two morphisms out of a homology group agree, it suffices to check on cycles: ext, simp only [homology_functor_map, homology.π_map_apply], -- To check that two elements are equal mod boundaries, it suffices to exhibit a boundary: ext1, swap, exact (to_prev i h.hom) x.1, -- Moreover, to check that two cycles are equal, it suffices to check their underlying elements: ext1, simp only [map_add, image_to_kernel_arrow_apply, homological_complex.hom.sq_from_left, Module.to_kernel_subobject_arrow, category_theory.limits.kernel_subobject_map_arrow_apply, d_next_eq_d_from_from_next, function.comp_app, zero_add, Module.coe_comp, linear_map.add_apply, map_zero, subtype.val_eq_coe, category_theory.limits.image_subobject_arrow_comp_apply, linear_map.map_coe_ker, prev_d_eq_to_prev_d_to, h.comm i, x.2], abel end end Module
8fd054e7603a67626a24b2b72031c304bc014700
ec5a7ae10c533e1b1f4b0bc7713e91ecf829a3eb
/ijcar16/examples/cc6.lean
dbfad25b11a0a0c6af9accdd7863e01023cbf90b
[ "MIT" ]
permissive
leanprover/leanprover.github.io
cf248934af7c7e9aeff17cf8df3c12c5e7e73f1a
071a20d2e059a2c3733e004c681d3949cac3c07a
refs/heads/master
1,692,621,047,417
1,691,396,994,000
1,691,396,994,000
19,366,263
18
27
MIT
1,693,989,071,000
1,399,006,345,000
Lean
UTF-8
Lean
false
false
930
lean
/- Example/test file for the congruence closure procedure described in the paper: "Congruence Closure for Intensional Type Theory" Daniel Selsam and Leonardo de Moura The tactic `by blast` has been configured in this file to use just the congruence closure procedure using the command set_option blast.strategy "cc" -/ import data.list set_option blast.strategy "cc" open perm list /- The implemented procedure supports arbitrary equivalence relations. In the following example, it is using the permutation relation ~ for lists -/ example (A : Type) (l₁ l₂ l₃ l₄ l₅ : list A) : (l₁ ~ l₂) → (l₃ ~ l₄) → (l₁ ++ l₃ ++ l₅ ++ l₄ ++ l₁) ~ (l₂ ++ l₄ ++ l₅ ++ l₃ ++ l₂) := by blast example (A : Type) (l₁ l₂ l₃ l₄ l₅ : list A) : (l₁ ~ l₂) → (l₃ = l₄) → (l₁ ++ l₃ ++ l₅ ++ l₄ ++ l₁) ~ (l₂ ++ l₄ ++ l₅ ++ l₃ ++ l₂) := by blast
6b58f3bf85034413267c8fcf6d43681b48dbc333
366210ee84e5cc86b5ae5d69decefe097bb44783
/src/support.lean
6e63d0846bb129a5856863cc3ec49c70ffd09520
[]
no_license
ChrisHughes24/lean-scratchpad
016e47c4a2cb51a48f99e3249fe4563f3477f463
6cbc455cb7c5403c601a06e3146cd18b6e32a883
refs/heads/master
1,583,998,813,691
1,524,342,716,000
1,524,342,716,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
6,528
lean
import analysis.topology.topological_space import data.set import data.fin import homeos import tactic.find import invariant_norms import tactic noncomputable theory local attribute [instance] classical.prop_decidable --set_option pp.coercions false open set function equiv def fix {X} (f : X → X) := { x : X | f x = x } lemma fix_stable {X} (f : X → X) : f '' fix f = fix f := begin apply subset.antisymm, { intros x H, rcases H with ⟨y, y_in_fix, f_y_x⟩, simp [fix] at y_in_fix, rw y_in_fix at f_y_x, finish }, { intros x H, existsi x, finish } end variables {X : Type} [topological_space X] (f : X → X) def supp := closure (-fix f) lemma compl_supp_eq_interior_fix : -supp f = interior (fix f) := calc -supp f = -closure (-fix f) : rfl ... = -(-interior (fix f)) : by rw closure_compl ... = interior (fix f) : by rw compl_compl lemma compl_supp_subset_fix : -supp f ⊆ fix f := calc -supp f = interior (fix f) : by rw compl_supp_eq_interior_fix ... ⊆ fix f : interior_subset lemma fix_of_not_in_supp {x : X} {f : homeo X X} (h : x ∉ supp f) : f x = x := compl_supp_subset_fix f h lemma mem_supp_or_fix (x) : x ∈ supp f ∨ f x = x := or_iff_not_imp_left.2 (λ h, compl_supp_subset_fix _ h) -- Recall: or_iff_not_imp_left : a ∨ b ↔ (¬ a → b) lemma stable_support (f : homeo X X) : f '' supp f = supp f := calc f '' supp f = f '' (closure (-fix f)) : rfl ... = closure (f '' (-fix f)) : by rw f.image_closure ... = closure (-(f '' (fix f))) : by rw f.image_compl ... = closure (-(fix f)) : by rw fix_stable lemma fundamental {f g : homeo X X} (H : supp f ∩ supp g = ∅) : f * g = g * f := begin apply homeo.ext, intro x, suffices special_case : ∀ f g : homeo X X, supp f ∩ supp g = ∅ → ∀ x ∈ supp f, f (g x) = g (f x), { cases mem_supp_or_fix f x with hf hf, { simp [special_case f g H x hf] }, { cases mem_supp_or_fix g x with hg hg, { rw inter_comm at H, simp [special_case g f H x hg] }, { simp [hf, hg] } } }, intros f g H x h, have hg : g x = x := compl_supp_subset_fix _ ((subset_compl_iff_disjoint.2 H) h), simp [hg], refine (compl_supp_subset_fix _ $ (subset_compl_iff_disjoint.2 H) _).symm, rw ← stable_support, finish end lemma fundamental' {f g : homeo X X} (H : supp f ∩ supp g = ∅) : f * g = g * f := begin ext x, by_cases H' : x ∈ supp f ∨ x ∈ supp g, { -- Here we assume H' : x ∈ supp f ∨ x ∈ supp g wlog h : x ∈ supp f using f g, have x_not_supp_g : x ∉ supp g := (subset_compl_iff_disjoint.2 H) h, have f_x_supp_f : f x ∈ supp f, { have : f x ∈ f '' supp f := mem_image_of_mem f h, finish [stable_support f] }, have : f x ∉ supp g := (subset_compl_iff_disjoint.2 H) f_x_supp_f, finish [fix_of_not_in_supp] }, { -- Now we assume H' : ¬(x ∈ supp f ∨ x ∈ supp g) rw not_or_distrib at H', finish [fix_of_not_in_supp] } end lemma fundamental'' {f g : homeo X X} (H : supp f ∩ supp g = ∅) : f * g = g * f := begin ext x, by_cases H' : x ∈ supp f ∨ x ∈ supp g, { -- Here we assume H' : x ∈ supp f ∨ x ∈ supp g wlog h : x ∈ supp f using f g, exact calc (f * g) x = f (g x) : by simp ... = f x : by { have x_not_supp_g : x ∉ supp g := (subset_compl_iff_disjoint.2 H) h, finish [fix_of_not_in_supp] } ... = g (f x) : by { have f_x_supp_f : f x ∈ supp f, { have : f x ∈ f '' supp f := mem_image_of_mem f h, finish [stable_support f] }, have : f x ∉ supp g := (subset_compl_iff_disjoint.2 H) f_x_supp_f, finish [fix_of_not_in_supp] } ... = (g * f) x : by simp }, { -- Now we assume H' : ¬(x ∈ supp f ∨ x ∈ supp g) rw not_or_distrib at H', finish [fix_of_not_in_supp] } end lemma supp_conj (f g : homeo X X) : supp (conj g f : homeo X X) = g '' supp f := begin unfold supp, rw homeo.image_closure, congr_n 1, apply set.ext, intro x, rw mem_image_iff_of_inverse g.left_inverse g.right_inverse, apply not_congr, dsimp [conj], exact calc (g * f * g⁻¹) x = x ↔ g⁻¹ (g (f (g⁻¹ x))) = g⁻¹ x : by simp [(g⁻¹).bijective.1.eq_iff] ... ↔ (f (g⁻¹ x)) = g⁻¹ x : by rw [← aut_mul_val, mul_left_inv]; simp end local notation `[[`a, b`]]` := comm a b lemma trading_of_displaced (g a b : homeo X X) (supp_hyp : supp a ∩ g '' supp b = ∅) : ∃ c d e f : homeo X X, [[a, b]] = (conj c g⁻¹)*(conj d g)*(conj e g⁻¹)*(conj f g) := begin apply commutator_trading, rw ← supp_conj at supp_hyp, rw commuting, exact fundamental supp_hyp, end local notation `Π_{i=` k `..` n `}` f := list.prod ((list.range' k (n-k+1)).map f) lemma commutators_crunching (U : set X) (φ f : homeo X X) (wandering_hyp : ∀ i j : ℕ, i ≠ j → ⇑(φ^i) '' U ∩ ⇑(φ^j) '' U = ∅) (n : ℕ) (a : ℕ → homeo X X) (b : ℕ → homeo X X) (supp_hyp : ∀ k : ℕ, supp (a k) ⊆ U ∧ supp (b k) ⊆ U) (comm_hyp : f = Π_{i=1..n} λ i, [[a i, b i]]) : ∃ A B C D : homeo X X, f = [[A, B]]* [[C, D]] := sorry /- lemma fix_conj (f g : perm X) : fix (conj g f : perm X) = g '' (fix f) := begin apply set.ext, intro x, rw mem_image_iff_of_inverse g.left_inverse g.right_inverse, dsimp[conj], exact calc (g * f * g⁻¹) x = x ↔ g⁻¹ (g (f (g⁻¹ x))) = g⁻¹ x : by { simp [(g⁻¹).bijective.1.eq_iff], } ... ↔ (f (g⁻¹ x)) = g⁻¹ x : by rw [← perm_mul_val, mul_left_inv] ; simp end instance : has_coe (homeo X X) (perm X) := ⟨λ f, f.to_equiv⟩ set_option pp.coercions true --set_option pp.all true lemma mul_perm_homeo (f g : homeo X X) : (f : perm X)*(g : perm X) = (f*g : homeo X X) := begin apply equiv.ext, intro x, simp, sorry -- rw equiv.trans_apply, end lemma inv_perm_homeo (f : homeo X X) : (f : perm X)⁻¹ = (f⁻¹ : homeo X X) := rfl lemma conj_perm_homeo (f g : homeo X X) : conj (g : perm X) (f : perm X) = (conj g f : homeo X X) := by simp [conj, mul_perm_homeo, inv_perm_homeo] lemma supp_conj (f g : homeo X X) : supp (conj g f : homeo X X) = g '' supp f := begin unfold supp, rw homeo.image_closure, congr_n 1, rw g.image_compl, congr, have := fix_conj (f : perm X) (g : perm X), rw conj_perm_homeo at this, exact this end -/
22da7b99e5e8d195c77a26c0177531359b894049
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/10_Structures_and_Records.org.16.lean
71eb5d03c57d44e3ee527ff70159a4e84184c6bb
[]
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
368
lean
import standard namespace hide -- BEGIN structure prod (A : Type) (B : Type) := pair :: (pr1 : A) (pr2 : B) -- Rename fields pr1 and pr2 to x and y respectively. structure point3 (A : Type) extends prod A A renaming pr1→x pr2→y := mk :: (z : A) check point3.x check point3.y check point3.z example : point3.mk 10 20 30 = prod.pair 10 20 := rfl -- END end hide
f28430ffb4e86414c6ecd46663c37d9fb724d8b9
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/analysis/normed_space/units.lean
c42e8fcb34961d7246d5a0fe2ebf2de8e611dd9c
[ "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,816
lean
/- Copyright (c) 2020 Heather Macbeth. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Heather Macbeth -/ import topology.algebra.ring.ideal import analysis.specific_limits.normed /-! # The group of units of a complete normed ring > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file contains the basic theory for the group of units (invertible elements) of a complete normed ring (Banach algebras being a notable special case). ## Main results The constructions `one_sub`, `add` and `unit_of_nearby` state, in varying forms, that perturbations of a unit are units. The latter two are not stated in their optimal form; more precise versions would use the spectral radius. The first main result is `is_open`: the group of units of a complete normed ring is an open subset of the ring. The function `inverse` (defined in `algebra.ring`), for a ring `R`, sends `a : R` to `a⁻¹` if `a` is a unit and 0 if not. The other major results of this file (notably `inverse_add`, `inverse_add_norm` and `inverse_add_norm_diff_nth_order`) cover the asymptotic properties of `inverse (x + t)` as `t → 0`. -/ noncomputable theory open_locale topology variables {R : Type*} [normed_ring R] [complete_space R] namespace units /-- In a complete normed ring, a perturbation of `1` by an element `t` of distance less than `1` from `1` is a unit. Here we construct its `units` structure. -/ @[simps coe] def one_sub (t : R) (h : ‖t‖ < 1) : Rˣ := { val := 1 - t, inv := ∑' n : ℕ, t ^ n, val_inv := mul_neg_geom_series t h, inv_val := geom_series_mul_neg t h } /-- In a complete normed ring, a perturbation of a unit `x` by an element `t` of distance less than `‖x⁻¹‖⁻¹` from `x` is a unit. Here we construct its `units` structure. -/ @[simps coe] def add (x : Rˣ) (t : R) (h : ‖t‖ < ‖(↑x⁻¹ : R)‖⁻¹) : Rˣ := units.copy -- to make `coe_add` true definitionally, for convenience (x * (units.one_sub (-(↑x⁻¹ * t)) begin nontriviality R using [zero_lt_one], have hpos : 0 < ‖(↑x⁻¹ : R)‖ := units.norm_pos x⁻¹, calc ‖-(↑x⁻¹ * t)‖ = ‖↑x⁻¹ * t‖ : by { rw norm_neg } ... ≤ ‖(↑x⁻¹ : R)‖ * ‖t‖ : norm_mul_le ↑x⁻¹ _ ... < ‖(↑x⁻¹ : R)‖ * ‖(↑x⁻¹ : R)‖⁻¹ : by nlinarith only [h, hpos] ... = 1 : mul_inv_cancel (ne_of_gt hpos) end)) (x + t) (by simp [mul_add]) _ rfl /-- In a complete normed ring, an element `y` of distance less than `‖x⁻¹‖⁻¹` from `x` is a unit. Here we construct its `units` structure. -/ @[simps coe] def unit_of_nearby (x : Rˣ) (y : R) (h : ‖y - x‖ < ‖(↑x⁻¹ : R)‖⁻¹) : Rˣ := units.copy (x.add (y - x : R) h) y (by simp) _ rfl /-- The group of units of a complete normed ring is an open subset of the ring. -/ protected lemma is_open : is_open {x : R | is_unit x} := begin nontriviality R, apply metric.is_open_iff.mpr, rintros x' ⟨x, rfl⟩, refine ⟨‖(↑x⁻¹ : R)‖⁻¹, _root_.inv_pos.mpr (units.norm_pos x⁻¹), _⟩, intros y hy, rw [metric.mem_ball, dist_eq_norm] at hy, exact (x.unit_of_nearby y hy).is_unit end protected lemma nhds (x : Rˣ) : {x : R | is_unit x} ∈ 𝓝 (x : R) := is_open.mem_nhds units.is_open x.is_unit end units namespace nonunits /-- The `nonunits` in a complete normed ring are contained in the complement of the ball of radius `1` centered at `1 : R`. -/ lemma subset_compl_ball : nonunits R ⊆ (metric.ball (1 : R) 1)ᶜ := set.subset_compl_comm.mp $ λ x hx, by simpa [sub_sub_self, units.coe_one_sub] using (units.one_sub (1 - x) (by rwa [metric.mem_ball, dist_eq_norm, norm_sub_rev] at hx)).is_unit /- The `nonunits` in a complete normed ring are a closed set -/ protected lemma is_closed : is_closed (nonunits R) := units.is_open.is_closed_compl end nonunits namespace normed_ring open_locale classical big_operators open asymptotics filter metric finset ring lemma inverse_one_sub (t : R) (h : ‖t‖ < 1) : inverse (1 - t) = ↑(units.one_sub t h)⁻¹ := by rw [← inverse_unit (units.one_sub t h), units.coe_one_sub] /-- The formula `inverse (x + t) = inverse (1 + x⁻¹ * t) * x⁻¹` holds for `t` sufficiently small. -/ lemma inverse_add (x : Rˣ) : ∀ᶠ t in (𝓝 0), inverse ((x : R) + t) = inverse (1 + ↑x⁻¹ * t) * ↑x⁻¹ := begin nontriviality R, rw [eventually_iff, metric.mem_nhds_iff], have hinv : 0 < ‖(↑x⁻¹ : R)‖⁻¹, by cancel_denoms, use [‖(↑x⁻¹ : R)‖⁻¹, hinv], intros t ht, simp only [mem_ball, dist_zero_right] at ht, have ht' : ‖-↑x⁻¹ * t‖ < 1, { refine lt_of_le_of_lt (norm_mul_le _ _) _, rw norm_neg, refine lt_of_lt_of_le (mul_lt_mul_of_pos_left ht x⁻¹.norm_pos) _, cancel_denoms }, have hright := inverse_one_sub (-↑x⁻¹ * t) ht', have hleft := inverse_unit (x.add t ht), simp only [neg_mul, sub_neg_eq_add] at hright, simp only [units.coe_add] at hleft, simp [hleft, hright, units.add] end lemma inverse_one_sub_nth_order (n : ℕ) : ∀ᶠ t in (𝓝 0), inverse ((1:R) - t) = (∑ i in range n, t ^ i) + (t ^ n) * inverse (1 - t) := begin simp only [eventually_iff, metric.mem_nhds_iff], use [1, by norm_num], intros t ht, simp only [mem_ball, dist_zero_right] at ht, simp only [inverse_one_sub t ht, set.mem_set_of_eq], have h : 1 = ((range n).sum (λ i, t ^ i)) * (units.one_sub t ht) + t ^ n, { simp only [units.coe_one_sub], rw [geom_sum_mul_neg], simp }, rw [← one_mul ↑(units.one_sub t ht)⁻¹, h, add_mul], congr, { rw [mul_assoc, (units.one_sub t ht).mul_inv], simp }, { simp only [units.coe_one_sub], rw [← add_mul, geom_sum_mul_neg], simp } end /-- The formula `inverse (x + t) = (∑ i in range n, (- x⁻¹ * t) ^ i) * x⁻¹ + (- x⁻¹ * t) ^ n * inverse (x + t)` holds for `t` sufficiently small. -/ lemma inverse_add_nth_order (x : Rˣ) (n : ℕ) : ∀ᶠ t in (𝓝 0), inverse ((x : R) + t) = (∑ i in range n, (- ↑x⁻¹ * t) ^ i) * ↑x⁻¹ + (- ↑x⁻¹ * t) ^ n * inverse (x + t) := begin refine (inverse_add x).mp _, have hzero : tendsto (λ (t : R), - ↑x⁻¹ * t) (𝓝 0) (𝓝 0), { convert ((mul_left_continuous (- (↑x⁻¹ : R))).tendsto 0).comp tendsto_id, simp }, refine (hzero.eventually (inverse_one_sub_nth_order n)).mp (eventually_of_forall _), simp only [neg_mul, sub_neg_eq_add], intros t h1 h2, have h := congr_arg (λ (a : R), a * ↑x⁻¹) h1, dsimp at h, convert h, rw [add_mul, mul_assoc], simp [h2.symm] end lemma inverse_one_sub_norm : (λ t : R, inverse (1 - t)) =O[𝓝 0] (λ t, 1 : R → ℝ) := begin simp only [is_O, is_O_with, eventually_iff, metric.mem_nhds_iff], refine ⟨‖(1:R)‖ + 1, (2:ℝ)⁻¹, by norm_num, _⟩, intros t ht, simp only [ball, dist_zero_right, set.mem_set_of_eq] at ht, have ht' : ‖t‖ < 1, { have : (2:ℝ)⁻¹ < 1 := by cancel_denoms, linarith }, simp only [inverse_one_sub t ht', norm_one, mul_one, set.mem_set_of_eq], change ‖∑' n : ℕ, t ^ n‖ ≤ _, have := normed_ring.tsum_geometric_of_norm_lt_1 t ht', have : (1 - ‖t‖)⁻¹ ≤ 2, { rw ← inv_inv (2:ℝ), refine inv_le_inv_of_le (by norm_num) _, have : (2:ℝ)⁻¹ + (2:ℝ)⁻¹ = 1 := by ring, linarith }, linarith end /-- The function `λ t, inverse (x + t)` is O(1) as `t → 0`. -/ lemma inverse_add_norm (x : Rˣ) : (λ t : R, inverse (↑x + t)) =O[𝓝 0] (λ t, (1:ℝ)) := begin simp only [is_O_iff, norm_one, mul_one], cases is_O_iff.mp (@inverse_one_sub_norm R _ _) with C hC, use C * ‖((x⁻¹:Rˣ):R)‖, have hzero : tendsto (λ t, - (↑x⁻¹ : R) * t) (𝓝 0) (𝓝 0), { convert ((mul_left_continuous (-↑x⁻¹ : R)).tendsto 0).comp tendsto_id, simp }, refine (inverse_add x).mp ((hzero.eventually hC).mp (eventually_of_forall _)), intros t bound iden, rw iden, simp at bound, have hmul := norm_mul_le (inverse (1 + ↑x⁻¹ * t)) ↑x⁻¹, nlinarith [norm_nonneg (↑x⁻¹ : R)] end /-- The function `λ t, inverse (x + t) - (∑ i in range n, (- x⁻¹ * t) ^ i) * x⁻¹` is `O(t ^ n)` as `t → 0`. -/ lemma inverse_add_norm_diff_nth_order (x : Rˣ) (n : ℕ) : (λ t : R, inverse (↑x + t) - (∑ i in range n, (- ↑x⁻¹ * t) ^ i) * ↑x⁻¹) =O[𝓝 (0:R)] (λ t, ‖t‖ ^ n) := begin by_cases h : n = 0, { simpa [h] using inverse_add_norm x }, have hn : 0 < n := nat.pos_of_ne_zero h, simp [is_O_iff], cases (is_O_iff.mp (inverse_add_norm x)) with C hC, use C * ‖(1:ℝ)‖ * ‖(↑x⁻¹ : R)‖ ^ n, have h : eventually_eq (𝓝 (0:R)) (λ t, inverse (↑x + t) - (∑ i in range n, (- ↑x⁻¹ * t) ^ i) * ↑x⁻¹) (λ t, ((- ↑x⁻¹ * t) ^ n) * inverse (x + t)), { refine (inverse_add_nth_order x n).mp (eventually_of_forall _), intros t ht, convert congr_arg (λ a, a - (range n).sum (pow (-↑x⁻¹ * t)) * ↑x⁻¹) ht, simp }, refine h.mp (hC.mp (eventually_of_forall _)), intros t _ hLHS, simp only [neg_mul] at hLHS, rw hLHS, refine le_trans (norm_mul_le _ _ ) _, have h' : ‖(-(↑x⁻¹ * t)) ^ n‖ ≤ ‖(↑x⁻¹ : R)‖ ^ n * ‖t‖ ^ n, { calc ‖(-(↑x⁻¹ * t)) ^ n‖ ≤ ‖(-(↑x⁻¹ * t))‖ ^ n : norm_pow_le' _ hn ... = ‖↑x⁻¹ * t‖ ^ n : by rw norm_neg ... ≤ (‖(↑x⁻¹ : R)‖ * ‖t‖) ^ n : _ ... = ‖(↑x⁻¹ : R)‖ ^ n * ‖t‖ ^ n : mul_pow _ _ n, exact pow_le_pow_of_le_left (norm_nonneg _) (norm_mul_le ↑x⁻¹ t) n }, have h'' : 0 ≤ ‖(↑x⁻¹ : R)‖ ^ n * ‖t‖ ^ n, { refine mul_nonneg _ _; exact pow_nonneg (norm_nonneg _) n }, nlinarith [norm_nonneg (inverse (↑x + t))], end /-- The function `λ t, inverse (x + t) - x⁻¹` is `O(t)` as `t → 0`. -/ lemma inverse_add_norm_diff_first_order (x : Rˣ) : (λ t : R, inverse (↑x + t) - ↑x⁻¹) =O[𝓝 0] (λ t, ‖t‖) := by simpa using inverse_add_norm_diff_nth_order x 1 /-- The function `λ t, inverse (x + t) - x⁻¹ + x⁻¹ * t * x⁻¹` is `O(t ^ 2)` as `t → 0`. -/ lemma inverse_add_norm_diff_second_order (x : Rˣ) : (λ t : R, inverse (↑x + t) - ↑x⁻¹ + ↑x⁻¹ * t * ↑x⁻¹) =O[𝓝 0] (λ t, ‖t‖ ^ 2) := begin convert inverse_add_norm_diff_nth_order x 2, ext t, simp only [range_succ, range_one, sum_insert, mem_singleton, sum_singleton, not_false_iff, one_ne_zero, pow_zero, add_mul, pow_one, one_mul, neg_mul, sub_add_eq_sub_sub_swap, sub_neg_eq_add], end /-- The function `inverse` is continuous at each unit of `R`. -/ lemma inverse_continuous_at (x : Rˣ) : continuous_at inverse (x : R) := begin have h_is_o : (λ t : R, inverse (↑x + t) - ↑x⁻¹) =o[𝓝 0] (λ _, 1 : R → ℝ) := (inverse_add_norm_diff_first_order x).trans_is_o (is_o.norm_left $ is_o_id_const one_ne_zero), have h_lim : tendsto (λ (y:R), y - x) (𝓝 x) (𝓝 0), { refine tendsto_zero_iff_norm_tendsto_zero.mpr _, exact tendsto_iff_norm_tendsto_zero.mp tendsto_id }, rw [continuous_at, tendsto_iff_norm_tendsto_zero, inverse_unit], simpa [(∘)] using h_is_o.norm_left.tendsto_div_nhds_zero.comp h_lim end end normed_ring namespace units open mul_opposite filter normed_ring /-- In a normed ring, the coercion from `Rˣ` (equipped with the induced topology from the embedding in `R × R`) to `R` is an open map. -/ lemma is_open_map_coe : is_open_map (coe : Rˣ → R) := begin rw is_open_map_iff_nhds_le, intros x s, rw [mem_map, mem_nhds_induced], rintros ⟨t, ht, hts⟩, obtain ⟨u, hu, v, hv, huvt⟩ : ∃ (u : set R), u ∈ 𝓝 ↑x ∧ ∃ (v : set Rᵐᵒᵖ), v ∈ 𝓝 (op ↑x⁻¹) ∧ u ×ˢ v ⊆ t, { simpa [embed_product, mem_nhds_prod_iff] using ht }, have : u ∩ (op ∘ ring.inverse) ⁻¹' v ∩ (set.range (coe : Rˣ → R)) ∈ 𝓝 ↑x, { refine inter_mem (inter_mem hu _) (units.nhds x), refine (continuous_op.continuous_at.comp (inverse_continuous_at x)).preimage_mem_nhds _, simpa using hv }, refine mem_of_superset this _, rintros _ ⟨⟨huy, hvy⟩, ⟨y, rfl⟩⟩, have : embed_product R y ∈ u ×ˢ v := ⟨huy, by simpa using hvy⟩, simpa using hts (huvt this) end /-- In a normed ring, the coercion from `Rˣ` (equipped with the induced topology from the embedding in `R × R`) to `R` is an open embedding. -/ lemma open_embedding_coe : open_embedding (coe : Rˣ → R) := open_embedding_of_continuous_injective_open continuous_coe ext is_open_map_coe end units namespace ideal /-- An ideal which contains an element within `1` of `1 : R` is the unit ideal. -/ lemma eq_top_of_norm_lt_one (I : ideal R) {x : R} (hxI : x ∈ I) (hx : ‖1 - x‖ < 1) : I = ⊤ := let u := units.one_sub (1 - x) hx in (I.eq_top_iff_one.mpr $ by simpa only [show u.inv * x = 1, by simp] using I.mul_mem_left u.inv hxI) /-- The `ideal.closure` of a proper ideal in a complete normed ring is proper. -/ lemma closure_ne_top (I : ideal R) (hI : I ≠ ⊤) : I.closure ≠ ⊤ := have h : _ := closure_minimal (coe_subset_nonunits hI) nonunits.is_closed, by simpa only [I.closure.eq_top_iff_one, ne.def] using mt (@h 1) one_not_mem_nonunits /-- The `ideal.closure` of a maximal ideal in a complete normed ring is the ideal itself. -/ lemma is_maximal.closure_eq {I : ideal R} (hI : I.is_maximal) : I.closure = I := (hI.eq_of_le (I.closure_ne_top hI.ne_top) subset_closure).symm /-- Maximal ideals in complete normed rings are closed. -/ instance is_maximal.is_closed {I : ideal R} [hI : I.is_maximal] : is_closed (I : set R) := is_closed_of_closure_subset $ eq.subset $ congr_arg (coe : ideal R → set R) hI.closure_eq end ideal
79915c64c6809838444799d5c6ff7c0bef512141
680b0d1592ce164979dab866b232f6fa743f2cc8
/library/theories/number_theory/irrational_roots.lean
f2f4d3b7c81b28dbe4d2f64f998253f11b225158
[ "Apache-2.0" ]
permissive
syohex/lean
657428ab520f8277fc18cf04bea2ad200dbae782
081ad1212b686780f3ff8a6d0e5f8a1d29a7d8bc
refs/heads/master
1,611,274,838,635
1,452,668,188,000
1,452,668,188,000
49,562,028
0
0
null
1,452,675,604,000
1,452,675,602,000
null
UTF-8
Lean
false
false
7,781
lean
/- Copyright (c) 2015 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad A proof that if n > 1 and a > 0, then the nth root of a is irrational, unless a is a perfect nth power. -/ import data.rat .prime_factorization open eq.ops /- First, a textbook proof that sqrt 2 is irrational. -/ section open nat theorem sqrt_two_irrational {a b : ℕ} (co : coprime a b) : a^2 ≠ 2 * b^2 := assume H : a^2 = 2 * b^2, have even (a^2), from even_of_exists (exists.intro _ H), have even a, from even_of_even_pow this, obtain (c : nat) (aeq : a = 2 * c), from exists_of_even this, have 2 * (2 * c^2) = 2 * b^2, by rewrite [-H, aeq, *pow_two, mul.assoc, mul.left_comm c], have 2 * c^2 = b^2, from eq_of_mul_eq_mul_left dec_trivial this, have even (b^2), from even_of_exists (exists.intro _ (eq.symm this)), have even b, from even_of_even_pow this, assert 2 ∣ gcd a b, from dvd_gcd (dvd_of_even `even a`) (dvd_of_even `even b`), have 2 ∣ 1, begin rewrite [gcd_eq_one_of_coprime co at this], exact this end, show false, from absurd `2 ∣ 1` dec_trivial end /- Replacing 2 by an arbitrary prime and the power 2 by any n ≥ 1 yields the stronger result that the nth root of an integer is irrational, unless the integer is already a perfect nth power. -/ section open nat decidable theorem root_irrational {a b c n : ℕ} (npos : n > 0) (apos : a > 0) (co : coprime a b) (H : a^n = c * b^n) : b = 1 := have bpos : b > 0, from pos_of_ne_zero (suppose b = 0, have a^n = 0, by rewrite [H, this, zero_pow npos], assert a = 0, from eq_zero_of_pow_eq_zero this, show false, from ne_of_lt `0 < a` this⁻¹), have H₁ : ∀ p, prime p → ¬ p ∣ b, from take p, suppose prime p, suppose p ∣ b, assert p ∣ b^n, from dvd_pow_of_dvd_of_pos `p ∣ b` `n > 0`, have p ∣ a^n, by rewrite H; apply dvd_mul_of_dvd_right this, have p ∣ a, from dvd_of_prime_of_dvd_pow `prime p` this, have ¬ coprime a b, from not_coprime_of_dvd_of_dvd (gt_one_of_prime `prime p`) `p ∣ a` `p ∣ b`, show false, from this `coprime a b`, have blt2 : b < 2, from by_contradiction (suppose ¬ b < 2, have b ≥ 2, from le_of_not_gt this, obtain p [primep pdvdb], from exists_prime_and_dvd this, show false, from H₁ p primep pdvdb), show b = 1, from (le.antisymm (le_of_lt_succ blt2) (succ_le_of_lt bpos)) end /- Here we state this in terms of the rationals, ℚ. The main difficulty is casting between ℕ, ℤ, and ℚ. -/ section open rat int nat decidable theorem denom_eq_one_of_pow_eq {q : ℚ} {n : ℕ} {c : ℤ} (npos : n > 0) (H : q^n = c) : denom q = 1 := let a := num q, b := denom q in have b ≠ 0, from ne_of_gt (denom_pos q), have bnz : b ≠ (0 : ℚ), from assume H, `b ≠ 0` (of_int.inj H), have bnnz : ((b : rat)^n ≠ 0), from assume bneqz, bnz (eq_zero_of_pow_eq_zero bneqz), have a^n /[rat] b^n = c, using bnz, begin rewrite [*of_int_pow, -div_pow, -eq_num_div_denom, -H] end, have (a^n : rat) = c *[rat] b^n, from eq.symm (!mul_eq_of_eq_div bnnz this⁻¹), have a^n = c * b^n, -- int version using this, by rewrite [-of_int_pow at this, -of_int_mul at this]; exact of_int.inj this, have (abs a)^n = abs c * (abs b)^n, using this, by rewrite [-abs_pow, this, abs_mul, abs_pow], have H₁ : (nat_abs a)^n = nat_abs c * (nat_abs b)^n, using this, begin apply int.of_nat.inj, rewrite [int.of_nat_mul, +int.of_nat_pow, +of_nat_nat_abs], exact this end, have H₂ : nat.coprime (nat_abs a) (nat_abs b), from of_nat.inj !coprime_num_denom, have nat_abs b = 1, from by_cases (suppose q = 0, by rewrite this) (suppose qne0 : q ≠ 0, using H₁ H₂, begin have ane0 : a ≠ 0, from suppose aeq0 : a = 0, have qeq0 : q = 0, by rewrite [eq_num_div_denom, aeq0, of_int_zero, zero_div], show false, from qne0 qeq0, have nat_abs a ≠ 0, from suppose nat_abs a = 0, have aeq0 : a = 0, from eq_zero_of_nat_abs_eq_zero this, show false, from ane0 aeq0, show nat_abs b = 1, from (root_irrational npos (pos_of_ne_zero this) H₂ H₁) end), show b = 1, using this, begin rewrite [-of_nat_nat_abs_of_nonneg (le_of_lt !denom_pos), this] end theorem eq_num_pow_of_pow_eq {q : ℚ} {n : ℕ} {c : ℤ} (npos : n > 0) (H : q^n = c) : c = (num q)^n := have denom q = 1, from denom_eq_one_of_pow_eq npos H, have of_int c = of_int ((num q)^n), using this, by rewrite [-H, eq_num_div_denom q at {1}, this, of_int_one, div_one, of_int_pow], show c = (num q)^n , from of_int.inj this end /- As a corollary, for n > 1, the nth root of a prime is irrational. -/ section open nat theorem not_eq_pow_of_prime {p n : ℕ} (a : ℕ) (ngt1 : n > 1) (primep : prime p) : p ≠ a^n := assume peq : p = a^n, have npos : n > 0, from lt.trans dec_trivial ngt1, have pnez : p ≠ 0, from (suppose p = 0, show false, by note H := (pos_of_prime primep); rewrite this at H; exfalso; exact !lt.irrefl H), assert agtz : a > 0, from pos_of_ne_zero (suppose a = 0, show false, using npos pnez, by revert peq; rewrite [this, zero_pow npos]; exact pnez), have n * mult p a = 1, from calc n * mult p a = mult p (a^n) : begin rewrite [mult_pow n agtz primep] end ... = mult p p : peq ... = 1 : mult_self (gt_one_of_prime primep), have n ∣ 1, from dvd_of_mul_right_eq this, have n = 1, from eq_one_of_dvd_one this, show false, using this, by rewrite this at ngt1; exact !lt.irrefl ngt1 open int rat theorem root_prime_irrational {p n : ℕ} {q : ℚ} (qnonneg : q ≥ 0) (ngt1 : n > 1) (primep : prime p) : q^n ≠ p := have numq : num q ≥ 0, from num_nonneg_of_nonneg qnonneg, have npos : n > 0, from lt.trans dec_trivial ngt1, suppose q^n = p, have p = (num q)^n, from eq_num_pow_of_pow_eq npos this, have p = (nat_abs (num q))^n, using this numq, by apply of_nat.inj; rewrite [this, of_nat_pow, of_nat_nat_abs_of_nonneg numq], show false, from not_eq_pow_of_prime _ ngt1 primep this end /- Thaetetus, who lives in the fourth century BC, is said to have proved the irrationality of square roots up to seventeen. In Chapter 4 of /Why Prove it Again/, John Dawson notes that Thaetetus may have used an approach similar to the one below. (See data/nat/gcd.lean for the key theorem, "div_gcd_eq_div_gcd".) -/ section open int example {a b c : ℤ} (co : coprime a b) (apos : a > 0) (bpos : b > 0) (H : a * a = c * (b * b)) : b = 1 := assert H₁ : gcd (c * b) a = gcd c a, from gcd_mul_right_cancel_of_coprime _ (coprime_swap co), have a * a = c * b * b, by rewrite -mul.assoc at H; apply H, have a / (gcd a b) = c * b / gcd (c * b) a, from div_gcd_eq_div_gcd this bpos apos, have a = c * b / gcd c a, using this, by revert this; rewrite [↑coprime at co, co, int.div_one, H₁]; intros; assumption, have a = b * (c / gcd c a), using this, by revert this; rewrite [mul.comm, !int.mul_div_assoc !gcd_dvd_left]; intros; assumption, have b ∣ a, from dvd_of_mul_right_eq this⁻¹, have b ∣ gcd a b, from dvd_gcd this !dvd.refl, have b ∣ 1, using this, by rewrite [↑coprime at co, co at this]; apply this, show b = 1, from eq_one_of_dvd_one (le_of_lt bpos) this end
8ea875c5e431b1a3162c0487870ef9b8b5d7bcf4
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/algebra/group_power/basic.lean
8206e9de62e873f2e20fa19f3665593006c876bc
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
13,990
lean
/- Copyright (c) 2015 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Robert Y. Lewis -/ import data.nat.basic import tactic.monotonicity.basic import group_theory.group_action.defs /-! # Power operations on monoids and groups The power operation on monoids and groups. We separate this from group, because it depends on `ℕ`, which in turn depends on other parts of algebra. This module contains lemmas about `a ^ n` and `n • a`, where `n : ℕ` or `n : ℤ`. Further lemmas can be found in `algebra.group_power.lemmas`. ## Notation - `a ^ n` is used as notation for `has_pow.pow a n`; in this file `n : ℕ` or `n : ℤ`. - `n • a` is used as notation for `has_scalar.smul n a`; in this file `n : ℕ` or `n : ℤ`. ## Implementation details We adopt the convention that `0^0 = 1`. -/ universes u v w x y z u₁ u₂ variables {M : Type u} {N : Type v} {G : Type w} {H : Type x} {A : Type y} {B : Type z} {R : Type u₁} {S : Type u₂} /-! ### Commutativity First we prove some facts about `semiconj_by` and `commute`. They do not require any theory about `pow` and/or `nsmul` and will be useful later in this file. -/ section monoid variables [monoid M] [monoid N] [add_monoid A] [add_monoid B] @[simp, to_additive one_nsmul] theorem pow_one (a : M) : a^1 = a := by rw [pow_succ, pow_zero, mul_one] /-- Note that most of the lemmas about powers of two refer to it as `sq`. -/ @[to_additive two_nsmul] theorem pow_two (a : M) : a^2 = a * a := by rw [pow_succ, pow_one] alias pow_two ← sq @[to_additive nsmul_add_comm'] theorem pow_mul_comm' (a : M) (n : ℕ) : a^n * a = a * a^n := commute.pow_self a n @[to_additive add_nsmul] theorem pow_add (a : M) (m n : ℕ) : a^(m + n) = a^m * a^n := by induction n with n ih; [rw [nat.add_zero, pow_zero, mul_one], rw [pow_succ', ← mul_assoc, ← ih, ← pow_succ', nat.add_assoc]] @[simp] lemma pow_ite (P : Prop) [decidable P] (a : M) (b c : ℕ) : a ^ (if P then b else c) = if P then a ^ b else a ^ c := by split_ifs; refl @[simp] lemma ite_pow (P : Prop) [decidable P] (a b : M) (c : ℕ) : (if P then a else b) ^ c = if P then a ^ c else b ^ c := by split_ifs; refl @[simp] lemma pow_boole (P : Prop) [decidable P] (a : M) : a ^ (if P then 1 else 0) = if P then a else 1 := by simp -- the attributes are intentionally out of order. `smul_zero` proves `nsmul_zero`. @[to_additive nsmul_zero, simp] theorem one_pow (n : ℕ) : (1 : M)^n = 1 := by induction n with n ih; [exact pow_zero _, rw [pow_succ, ih, one_mul]] @[to_additive mul_nsmul'] theorem pow_mul (a : M) (m n : ℕ) : a^(m * n) = (a^m)^n := begin induction n with n ih, { rw [nat.mul_zero, pow_zero, pow_zero] }, { rw [nat.mul_succ, pow_add, pow_succ', ih] } end @[to_additive nsmul_left_comm] lemma pow_right_comm (a : M) (m n : ℕ) : (a^m)^n = (a^n)^m := by rw [←pow_mul, nat.mul_comm, pow_mul] @[to_additive mul_nsmul] theorem pow_mul' (a : M) (m n : ℕ) : a^(m * n) = (a^n)^m := by rw [nat.mul_comm, pow_mul] @[to_additive nsmul_add_sub_nsmul] theorem pow_mul_pow_sub (a : M) {m n : ℕ} (h : m ≤ n) : a ^ m * a ^ (n - m) = a ^ n := by rw [←pow_add, nat.add_comm, tsub_add_cancel_of_le h] @[to_additive sub_nsmul_nsmul_add] theorem pow_sub_mul_pow (a : M) {m n : ℕ} (h : m ≤ n) : a ^ (n - m) * a ^ m = a ^ n := by rw [←pow_add, tsub_add_cancel_of_le h] @[to_additive bit0_nsmul] theorem pow_bit0 (a : M) (n : ℕ) : a ^ bit0 n = a^n * a^n := pow_add _ _ _ @[to_additive bit1_nsmul] theorem pow_bit1 (a : M) (n : ℕ) : a ^ bit1 n = a^n * a^n * a := by rw [bit1, pow_succ', pow_bit0] @[to_additive nsmul_add_comm] theorem pow_mul_comm (a : M) (m n : ℕ) : a^m * a^n = a^n * a^m := commute.pow_pow_self a m n @[to_additive] lemma commute.mul_pow {a b : M} (h : commute a b) (n : ℕ) : (a * b) ^ n = a ^ n * b ^ n := nat.rec_on n (by simp only [pow_zero, one_mul]) $ λ n ihn, by simp only [pow_succ, ihn, ← mul_assoc, (h.pow_left n).right_comm] theorem neg_pow [ring R] (a : R) (n : ℕ) : (- a) ^ n = (-1) ^ n * a ^ n := (neg_one_mul a) ▸ (commute.neg_one_left a).mul_pow n @[to_additive bit0_nsmul'] theorem pow_bit0' (a : M) (n : ℕ) : a ^ bit0 n = (a * a) ^ n := by rw [pow_bit0, (commute.refl a).mul_pow] @[to_additive bit1_nsmul'] theorem pow_bit1' (a : M) (n : ℕ) : a ^ bit1 n = (a * a) ^ n * a := by rw [bit1, pow_succ', pow_bit0'] @[simp] theorem neg_pow_bit0 [ring R] (a : R) (n : ℕ) : (- a) ^ (bit0 n) = a ^ (bit0 n) := by rw [pow_bit0', neg_mul_neg, pow_bit0'] @[simp] theorem neg_pow_bit1 [ring R] (a : R) (n : ℕ) : (- a) ^ (bit1 n) = - a ^ (bit1 n) := by simp only [bit1, pow_succ, neg_pow_bit0, neg_mul_eq_neg_mul] end monoid /-! ### Commutative (additive) monoid -/ section comm_monoid variables [comm_monoid M] [add_comm_monoid A] @[to_additive nsmul_add] theorem mul_pow (a b : M) (n : ℕ) : (a * b)^n = a^n * b^n := (commute.all a b).mul_pow n /-- The `n`th power map on a commutative monoid for a natural `n`, considered as a morphism of monoids. -/ @[to_additive nsmul_add_monoid_hom "Multiplication by a natural `n` on a commutative additive monoid, considered as a morphism of additive monoids.", simps] def pow_monoid_hom (n : ℕ) : M →* M := { to_fun := (^ n), map_one' := one_pow _, map_mul' := λ a b, mul_pow a b n } -- the below line causes the linter to complain :-/ -- attribute [simps] pow_monoid_hom nsmul_add_monoid_hom lemma dvd_pow {x y : M} (hxy : x ∣ y) : ∀ {n : ℕ} (hn : n ≠ 0), x ∣ y^n | 0 hn := (hn rfl).elim | (n + 1) hn := by { rw pow_succ, exact hxy.mul_right _ } alias dvd_pow ← has_dvd.dvd.pow lemma dvd_pow_self (a : M) {n : ℕ} (hn : n ≠ 0) : a ∣ a^n := dvd_rfl.pow hn end comm_monoid section div_inv_monoid variable [div_inv_monoid G] open int @[simp, to_additive one_zsmul] theorem zpow_one (a : G) : a ^ (1:ℤ) = a := by { convert pow_one a using 1, exact zpow_coe_nat a 1 } theorem zpow_two (a : G) : a ^ (2 : ℤ) = a * a := by { convert pow_two a using 1, exact zpow_coe_nat a 2 } end div_inv_monoid section group variables [group G] [group H] [add_group A] [add_group B] open int section nat @[simp, to_additive neg_nsmul] theorem inv_pow (a : G) (n : ℕ) : (a⁻¹)^n = (a^n)⁻¹ := begin induction n with n ih, { rw [pow_zero, pow_zero, one_inv] }, { rw [pow_succ', pow_succ, ih, mul_inv_rev] } end @[to_additive nsmul_sub] -- rename to sub_nsmul? theorem pow_sub (a : G) {m n : ℕ} (h : n ≤ m) : a^(m - n) = a^m * (a^n)⁻¹ := have h1 : m - n + n = m, from tsub_add_cancel_of_le h, have h2 : a^(m - n) * a^n = a^m, by rw [←pow_add, h1], eq_mul_inv_of_mul_eq h2 @[to_additive nsmul_neg_comm] theorem pow_inv_comm (a : G) (m n : ℕ) : (a⁻¹)^m * a^n = a^n * (a⁻¹)^m := (commute.refl a).inv_left.pow_pow m n @[to_additive sub_nsmul_neg] theorem inv_pow_sub (a : G) {m n : ℕ} (h : n ≤ m) : a⁻¹^(m - n) = (a^m)⁻¹ * a^n := by rw [pow_sub a⁻¹ h, inv_pow, inv_pow, inv_inv] end nat @[simp, to_additive zsmul_zero] theorem one_zpow : ∀ (n : ℤ), (1 : G) ^ n = 1 | (n : ℕ) := by rw [zpow_coe_nat, one_pow] | -[1+ n] := by rw [zpow_neg_succ_of_nat, one_pow, one_inv] @[simp, to_additive neg_zsmul] theorem zpow_neg (a : G) : ∀ (n : ℤ), a ^ -n = (a ^ n)⁻¹ | (n+1:ℕ) := div_inv_monoid.zpow_neg' _ _ | 0 := by { change a ^ (0 : ℤ) = (a ^ (0 : ℤ))⁻¹, simp } | -[1+ n] := by { rw [zpow_neg_succ_of_nat, inv_inv, ← zpow_coe_nat], refl } lemma mul_zpow_neg_one (a b : G) : (a*b)^(-(1:ℤ)) = b^(-(1:ℤ))*a^(-(1:ℤ)) := by simp only [mul_inv_rev, zpow_one, zpow_neg] @[to_additive neg_one_zsmul] theorem zpow_neg_one (x : G) : x ^ (-1:ℤ) = x⁻¹ := by { rw [← congr_arg has_inv.inv (pow_one x), zpow_neg, ← zpow_coe_nat], refl } @[to_additive zsmul_neg] theorem inv_zpow (a : G) : ∀n:ℤ, a⁻¹ ^ n = (a ^ n)⁻¹ | (n : ℕ) := by rw [zpow_coe_nat, zpow_coe_nat, inv_pow] | -[1+ n] := by rw [zpow_neg_succ_of_nat, zpow_neg_succ_of_nat, inv_pow] @[to_additive add_commute.zsmul_add] theorem commute.mul_zpow {a b : G} (h : commute a b) : ∀ n : ℤ, (a * b) ^ n = a ^ n * b ^ n | (n : ℕ) := by simp [zpow_coe_nat, h.mul_pow n] | -[1+n] := by simp [h.mul_pow, (h.pow_pow n.succ n.succ).inv_inv.symm.eq] end group section comm_group variables [comm_group G] [add_comm_group A] @[to_additive zsmul_add] theorem mul_zpow (a b : G) (n : ℤ) : (a * b)^n = a^n * b^n := (commute.all a b).mul_zpow n @[to_additive zsmul_sub] theorem div_zpow (a b : G) (n : ℤ) : (a / b) ^ n = a ^ n / b ^ n := by rw [div_eq_mul_inv, div_eq_mul_inv, mul_zpow, inv_zpow] /-- The `n`th power map (`n` an integer) on a commutative group, considered as a group homomorphism. -/ @[to_additive "Multiplication by an integer `n` on a commutative additive group, considered as an additive group homomorphism.", simps] def zpow_group_hom (n : ℤ) : G →* G := { to_fun := (^ n), map_one' := one_zpow n, map_mul' := λ a b, mul_zpow a b n } end comm_group lemma zero_pow [monoid_with_zero R] : ∀ {n : ℕ}, 0 < n → (0 : R) ^ n = 0 | (n+1) _ := by rw [pow_succ, zero_mul] lemma zero_pow_eq [monoid_with_zero R] (n : ℕ) : (0 : R)^n = if n = 0 then 1 else 0 := begin split_ifs with h, { rw [h, pow_zero], }, { rw [zero_pow (nat.pos_of_ne_zero h)] }, end lemma pow_eq_zero_of_le [monoid_with_zero M] {x : M} {n m : ℕ} (hn : n ≤ m) (hx : x^n = 0) : x^m = 0 := by rw [← tsub_add_cancel_of_le hn, pow_add, hx, mul_zero] namespace ring_hom variables [semiring R] [semiring S] @[simp] lemma map_pow (f : R →+* S) (a) : ∀ n : ℕ, f (a ^ n) = (f a) ^ n := f.to_monoid_hom.map_pow a end ring_hom section variables (R) theorem neg_one_pow_eq_or [ring R] : ∀ n : ℕ, (-1 : R)^n = 1 ∨ (-1 : R)^n = -1 | 0 := or.inl (pow_zero _) | (n+1) := (neg_one_pow_eq_or n).swap.imp (λ h, by rw [pow_succ, h, neg_one_mul, neg_neg]) (λ h, by rw [pow_succ, h, mul_one]) end @[simp] lemma neg_one_pow_mul_eq_zero_iff [ring R] {n : ℕ} {r : R} : (-1)^n * r = 0 ↔ r = 0 := by rcases neg_one_pow_eq_or R n; simp [h] @[simp] lemma mul_neg_one_pow_eq_zero_iff [ring R] {n : ℕ} {r : R} : r * (-1)^n = 0 ↔ r = 0 := by rcases neg_one_pow_eq_or R n; simp [h] lemma pow_dvd_pow [monoid R] (a : R) {m n : ℕ} (h : m ≤ n) : a ^ m ∣ a ^ n := ⟨a ^ (n - m), by rw [← pow_add, nat.add_comm, tsub_add_cancel_of_le h]⟩ theorem pow_dvd_pow_of_dvd [comm_monoid R] {a b : R} (h : a ∣ b) : ∀ n : ℕ, a ^ n ∣ b ^ n | 0 := by rw [pow_zero, pow_zero] | (n+1) := by { rw [pow_succ, pow_succ], exact mul_dvd_mul h (pow_dvd_pow_of_dvd n) } lemma sq_sub_sq {R : Type*} [comm_ring R] (a b : R) : a ^ 2 - b ^ 2 = (a + b) * (a - b) := by rw [sq, sq, mul_self_sub_mul_self] alias sq_sub_sq ← pow_two_sub_pow_two lemma eq_or_eq_neg_of_sq_eq_sq [comm_ring R] [is_domain R] (a b : R) (h : a ^ 2 = b ^ 2) : a = b ∨ a = -b := by rwa [← add_eq_zero_iff_eq_neg, ← sub_eq_zero, or_comm, ← mul_eq_zero, ← sq_sub_sq a b, sub_eq_zero] theorem pow_eq_zero [monoid_with_zero R] [no_zero_divisors R] {x : R} {n : ℕ} (H : x^n = 0) : x = 0 := begin induction n with n ih, { rw pow_zero at H, rw [← mul_one x, H, mul_zero] }, { rw pow_succ at H, exact or.cases_on (mul_eq_zero.1 H) id ih } end @[simp] lemma pow_eq_zero_iff [monoid_with_zero R] [no_zero_divisors R] {a : R} {n : ℕ} (hn : 0 < n) : a ^ n = 0 ↔ a = 0 := begin refine ⟨pow_eq_zero, _⟩, rintros rfl, exact zero_pow hn, end lemma pow_ne_zero_iff [monoid_with_zero R] [no_zero_divisors R] {a : R} {n : ℕ} (hn : 0 < n) : a ^ n ≠ 0 ↔ a ≠ 0 := by rwa [not_iff_not, pow_eq_zero_iff] @[field_simps] theorem pow_ne_zero [monoid_with_zero R] [no_zero_divisors R] {a : R} (n : ℕ) (h : a ≠ 0) : a ^ n ≠ 0 := mt pow_eq_zero h section semiring variables [semiring R] lemma min_pow_dvd_add {n m : ℕ} {a b c : R} (ha : c ^ n ∣ a) (hb : c ^ m ∣ b) : c ^ (min n m) ∣ a + b := begin replace ha := (pow_dvd_pow c (min_le_left n m)).trans ha, replace hb := (pow_dvd_pow c (min_le_right n m)).trans hb, exact dvd_add ha hb end end semiring section comm_semiring variables [comm_semiring R] lemma add_sq (a b : R) : (a + b) ^ 2 = a ^ 2 + 2 * a * b + b ^ 2 := by simp only [sq, add_mul_self_eq] alias add_sq ← add_pow_two end comm_semiring @[simp] lemma neg_sq {α} [ring α] (z : α) : (-z)^2 = z^2 := by simp [sq] alias neg_sq ← neg_pow_two lemma sub_sq {R} [comm_ring R] (a b : R) : (a - b) ^ 2 = a ^ 2 - 2 * a * b + b ^ 2 := by rw [sub_eq_add_neg, add_sq, neg_sq, mul_neg_eq_neg_mul_symm, ← sub_eq_add_neg] alias sub_sq ← sub_pow_two lemma of_add_nsmul [add_monoid A] (x : A) (n : ℕ) : multiplicative.of_add (n • x) = (multiplicative.of_add x)^n := rfl lemma of_add_zsmul [add_group A] (x : A) (n : ℤ) : multiplicative.of_add (n • x) = (multiplicative.of_add x)^n := rfl lemma of_mul_pow {A : Type*} [monoid A] (x : A) (n : ℕ) : additive.of_mul (x ^ n) = n • (additive.of_mul x) := rfl lemma of_mul_zpow [group G] (x : G) (n : ℤ) : additive.of_mul (x ^ n) = n • additive.of_mul x := rfl @[simp] lemma semiconj_by.zpow_right [group G] {a x y : G} (h : semiconj_by a x y) : ∀ m : ℤ, semiconj_by a (x^m) (y^m) | (n : ℕ) := by simp [zpow_coe_nat, h.pow_right n] | -[1+n] := by simp [(h.pow_right n.succ).inv_right] namespace commute variables [group G] {a b : G} @[simp] lemma zpow_right (h : commute a b) (m : ℤ) : commute a (b^m) := h.zpow_right m @[simp] lemma zpow_left (h : commute a b) (m : ℤ) : commute (a^m) b := (h.symm.zpow_right m).symm lemma zpow_zpow (h : commute a b) (m n : ℤ) : commute (a^m) (b^n) := (h.zpow_left m).zpow_right n variables (a) (m n : ℤ) @[simp] theorem self_zpow : commute a (a ^ n) := (commute.refl a).zpow_right n @[simp] theorem zpow_self : commute (a ^ n) a := (commute.refl a).zpow_left n @[simp] theorem zpow_zpow_self : commute (a ^ m) (a ^ n) := (commute.refl a).zpow_zpow m n end commute
c76eaf50e5d094ce8a585652f3e22fff16a2178b
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/data/option/basic.lean
77c8d3852518e5974900e84c89cb0324c0d12154
[ "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
7,295
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import logic.basic data.bool data.option.defs tactic.basic namespace option variables {α : Type*} {β : Type*} {γ : Type*} lemma some_ne_none (x : α) : some x ≠ none := λ h, option.no_confusion h @[simp] theorem get_mem : ∀ {o : option α} (h : is_some o), option.get h ∈ o | (some a) _ := rfl theorem get_of_mem {a : α} : ∀ {o : option α} (h : is_some o), a ∈ o → option.get h = a | _ _ rfl := rfl @[simp] lemma not_mem_none (a : α) : a ∉ (none : option α) := λ h, option.no_confusion h @[simp] lemma some_get : ∀ {x : option α} (h : is_some x), some (option.get h) = x | (some x) hx := rfl @[simp] lemma get_some (x : α) (h : is_some (some x)) : option.get h = x := rfl @[simp] lemma get_or_else_some (x y : α) : option.get_or_else (some x) y = x := rfl theorem mem_unique {o : option α} {a b : α} (ha : a ∈ o) (hb : b ∈ o) : a = b := option.some.inj $ ha.symm.trans hb theorem injective_some (α : Type*) : function.injective (@some α) := λ _ _, some_inj.mp /-- `option.map f` is injective if `f` is injective. -/ theorem injective_map {f : α → β} (Hf : function.injective f) : function.injective (option.map f) | none none H := rfl | (some a₁) (some a₂) H := by rw Hf (option.some.inj H) @[ext] theorem ext : ∀ {o₁ o₂ : option α}, (∀ a, a ∈ o₁ ↔ a ∈ o₂) → o₁ = o₂ | none none H := rfl | (some a) o H := ((H _).1 rfl).symm | o (some b) H := (H _).2 rfl theorem eq_none_iff_forall_not_mem {o : option α} : o = none ↔ (∀ a, a ∉ o) := ⟨λ e a h, by rw e at h; cases h, λ h, ext $ by simpa⟩ @[simp] theorem none_bind {α β} (f : α → option β) : none >>= f = none := rfl @[simp] theorem some_bind {α β} (a : α) (f : α → option β) : some a >>= f = f a := rfl @[simp] theorem none_bind' (f : α → option β) : none.bind f = none := rfl @[simp] theorem some_bind' (a : α) (f : α → option β) : (some a).bind f = f a := rfl @[simp] theorem bind_some : ∀ x : option α, x >>= some = x := @bind_pure α option _ _ @[simp] theorem bind_eq_some {α β} {x : option α} {f : α → option β} {b : β} : x >>= f = some b ↔ ∃ a, x = some a ∧ f a = some b := by cases x; simp @[simp] theorem bind_eq_some' {x : option α} {f : α → option β} {b : β} : x.bind f = some b ↔ ∃ a, x = some a ∧ f a = some b := by cases x; simp @[simp] theorem bind_eq_none' {o : option α} {f : α → option β} : o.bind f = none ↔ (∀ b a, a ∈ o → b ∉ f a) := by simp only [eq_none_iff_forall_not_mem, not_exists, not_and, mem_def, bind_eq_some'] @[simp] theorem bind_eq_none {α β} {o : option α} {f : α → option β} : o >>= f = none ↔ (∀ b a, a ∈ o → b ∉ f a) := bind_eq_none' lemma bind_comm {α β γ} {f : α → β → option γ} (a : option α) (b : option β) : a.bind (λx, b.bind (f x)) = b.bind (λy, a.bind (λx, f x y)) := by cases a; cases b; refl lemma bind_assoc (x : option α) (f : α → option β) (g : β → option γ) : (x.bind f).bind g = x.bind (λ y, (f y).bind g) := by cases x; refl @[simp] theorem map_none {α β} {f : α → β} : f <$> none = none := rfl @[simp] theorem map_some {α β} {a : α} {f : α → β} : f <$> some a = some (f a) := rfl @[simp] theorem map_none' {f : α → β} : option.map f none = none := rfl @[simp] theorem map_some' {a : α} {f : α → β} : option.map f (some a) = some (f a) := rfl @[simp] theorem map_eq_some {α β} {x : option α} {f : α → β} {b : β} : f <$> x = some b ↔ ∃ a, x = some a ∧ f a = b := by cases x; simp @[simp] theorem map_eq_some' {x : option α} {f : α → β} {b : β} : x.map f = some b ↔ ∃ a, x = some a ∧ f a = b := by cases x; simp @[simp] theorem map_id' : option.map (@id α) = id := map_id @[simp] theorem seq_some {α β} {a : α} {f : α → β} : some f <*> some a = some (f a) := rfl @[simp] theorem some_orelse' (a : α) (x : option α) : (some a).orelse x = some a := rfl @[simp] theorem some_orelse (a : α) (x : option α) : (some a <|> x) = some a := rfl @[simp] theorem none_orelse' (x : option α) : none.orelse x = x := by cases x; refl @[simp] theorem none_orelse (x : option α) : (none <|> x) = x := none_orelse' x @[simp] theorem orelse_none' (x : option α) : x.orelse none = x := by cases x; refl @[simp] theorem orelse_none (x : option α) : (x <|> none) = x := orelse_none' x @[simp] theorem is_some_none : @is_some α none = ff := rfl @[simp] theorem is_some_some {a : α} : is_some (some a) = tt := rfl theorem is_some_iff_exists {x : option α} : is_some x ↔ ∃ a, x = some a := by cases x; simp [is_some]; exact ⟨_, rfl⟩ @[simp] theorem is_none_none : @is_none α none = tt := rfl @[simp] theorem is_none_some {a : α} : is_none (some a) = ff := rfl @[simp] theorem not_is_some {a : option α} : is_some a = ff ↔ a.is_none = tt := by cases a; simp lemma eq_some_iff_get_eq {o : option α} {a : α} : o = some a ↔ ∃ h : o.is_some, option.get h = a := by cases o; simp lemma not_is_some_iff_eq_none {o : option α} : ¬o.is_some ↔ o = none := by cases o; simp lemma ne_none_iff_is_some {o : option α} : o ≠ none ↔ o.is_some := by cases o; simp lemma bex_ne_none {p : option α → Prop} : (∃ x ≠ none, p x) ↔ ∃ x, p (some x) := ⟨λ ⟨x, hx, hp⟩, ⟨get $ ne_none_iff_is_some.1 hx, by rwa [some_get]⟩, λ ⟨x, hx⟩, ⟨some x, some_ne_none x, hx⟩⟩ lemma ball_ne_none {p : option α → Prop} : (∀ x ≠ none, p x) ↔ ∀ x, p (some x) := ⟨λ h x, h (some x) (some_ne_none x), λ h x hx, by simpa only [some_get] using h (get $ ne_none_iff_is_some.1 hx)⟩ theorem iget_mem [inhabited α] : ∀ {o : option α}, is_some o → o.iget ∈ o | (some a) _ := rfl theorem iget_of_mem [inhabited α] {a : α} : ∀ {o : option α}, a ∈ o → o.iget = a | _ rfl := rfl @[simp] theorem guard_eq_some {p : α → Prop} [decidable_pred p] {a b : α} : guard p a = some b ↔ a = b ∧ p a := by by_cases p a; simp [option.guard, h]; intro; contradiction @[simp] theorem guard_eq_some' {p : Prop} [decidable p] : ∀ u, _root_.guard p = some u ↔ p | () := by by_cases p; simp [guard, h, pure]; intro; contradiction theorem lift_or_get_choice {f : α → α → α} (h : ∀ a b, f a b = a ∨ f a b = b) : ∀ o₁ o₂, lift_or_get f o₁ o₂ = o₁ ∨ lift_or_get f o₁ o₂ = o₂ | none none := or.inl rfl | (some a) none := or.inl rfl | none (some b) := or.inr rfl | (some a) (some b) := by simpa [lift_or_get] using h a b @[simp] lemma lift_or_get_none_left {f} {b : option α} : lift_or_get f none b = b := by cases b; refl @[simp] lemma lift_or_get_none_right {f} {a : option α} : lift_or_get f a none = a := by cases a; refl @[simp] lemma lift_or_get_some_some {f} {a b : α} : lift_or_get f (some a) (some b) = f a b := rfl /-- given an element of `a : option α`, a default element `b : β` and a function `α → β`, apply this function to `a` if it comes from `α`, and return `b` otherwise. -/ def cases_on' : option α → β → (α → β) → β | none n s := n | (some a) n s := s a end option
620c2bbb7cc9a2c3e8174086aea79bf69dabb238
6dc0c8ce7a76229dd81e73ed4474f15f88a9e294
/tests/lean/run/meta7.lean
287bbb60377291f8783a7610b539ab5469503d51
[ "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
4,593
lean
import Lean.Meta open Lean open Lean.Meta partial def fact : Nat → Nat | 0 => 1 | n+1 => (n+1)*fact n set_option trace.Meta.debug true set_option trace.Meta.check false def print (msg : MessageData) : MetaM Unit := trace! `Meta.debug msg def checkM (x : MetaM Bool) : MetaM Unit := unless (← x) do throwError "check failed" def ex (x_1 x_2 x_3 : Nat) : Nat × Nat := let x := fact (10 + x_1 + x_2 + x_3); let ty := Nat → Nat; let f : ty := fun x => x; let n := 20; let z := f 10; (let y : { v : Nat // v = n } := ⟨20, rfl⟩; y.1 + n + f x, z + 10) def tst1 : MetaM Unit := do print "----- tst1 -----"; let c ← getConstInfo `ex; lambdaTelescope c.value?.get! fun xs body => withTrackingZeta do check body; let ys ← getZetaFVarIds; let ys := ys.toList.map mkFVar; print ys; checkM $ pure $ ys.length == 2; let c ← mkAuxDefinitionFor `foo body; print c; check c; pure () #eval tst1 #print foo def tst2 : MetaM Unit := do print "----- tst2 -----"; let nat := mkConst `Nat; let t0 := mkApp (mkConst `IO) nat; let t := mkForall `_ BinderInfo.default nat t0; print t; check t; forallBoundedTelescope t (some 1) fun xs b => do print b; checkM $ pure $ xs.size == 1; checkM $ pure $ b == t0; pure () #eval tst2 def tst3 : MetaM Unit := do print "----- tst2 -----"; let nat := mkConst `Nat; let t0 := mkApp (mkConst `IO) nat; let t := t0; print t; check t; forallBoundedTelescope t (some 0) fun xs b => do print b; checkM $ pure $ xs.size == 0; checkM $ pure $ b == t0; pure () #eval tst3 def tst4 : MetaM Unit := do print "----- tst4 -----"; let nat := mkConst `Nat; withLocalDeclD `x nat fun x => withLocalDeclD `y nat fun y => do let m ← mkFreshExprMVar nat; print (← ppGoal m.mvarId!); let val ← mkAppM `Add.add #[mkNatLit 10, y]; let ⟨zId, nId, subst⟩ ← assertAfter m.mvarId! x.fvarId! `z nat val; print m; print (← ppGoal nId); withMVarContext nId do { print m!"{subst.apply x} {subst.apply y} {mkFVar zId}"; assignExprMVar nId (← mkAppM `Add.add #[subst.apply x, mkFVar zId]); print (mkMVar nId) }; print m; let expected ← mkAppM `Add.add #[x, val]; checkM (isDefEq m expected); pure () #eval tst4 def tst5 : MetaM Unit := do print "----- tst5 -----"; let prop := mkSort levelZero; withLocalDeclD `p prop fun p => withLocalDeclD `q prop fun q => do withLocalDeclD `h₁ p fun h₁ => do let eq ← mkEq p q; withLocalDeclD `h₂ eq fun h₂ => do let m ← mkFreshExprMVar q; let r ← replaceLocalDecl m.mvarId! h₁.fvarId! q h₂; print (← ppGoal r.mvarId); assignExprMVar r.mvarId (mkFVar r.fvarId); print m; check m; pure () #eval tst5 def tst6 : MetaM Unit := do print "----- tst6 -----"; let nat := mkConst `Nat; withLocalDeclD `x nat fun x => withLocalDeclD `y nat fun y => do let m ← mkFreshExprMVar nat; print (← ppGoal m.mvarId!); let val ← mkAppM `Add.add #[mkNatLit 10, y]; let ⟨zId, nId, subst⟩ ← assertAfter m.mvarId! y.fvarId! `z nat val; print m; print (← ppGoal nId); withMVarContext nId do { print m!"{subst.apply x} {subst.apply y} {mkFVar zId}"; assignExprMVar nId (← mkAppM `Add.add #[subst.apply x, mkFVar zId]); print (mkMVar nId) }; print m; let expected ← mkAppM `Add.add #[x, val]; checkM (isDefEq m expected); pure () #eval tst6 def tst7 : MetaM Unit := do print "----- tst7 -----"; let nat := mkConst `Nat; withLocalDeclD `x nat fun x => withLocalDeclD `y nat fun y => do let val ← mkAppM `Add.add #[x, y]; print val; let val := val.replaceFVars #[x, y] #[mkNatLit 0, mkNatLit 1]; print val; let expected ← mkAppM `Add.add #[mkNatLit 0, mkNatLit 1]; print expected; checkM (pure $ val == expected); pure () #eval tst7 def aux := [1, 2, 3].isEmpty def tst8 : MetaM Unit := do print "----- tst8 -----" let t := mkConst `aux let some t ← unfoldDefinition? t | throwError! "unexpected" let some t ← unfoldDefinition? t | throwError! "unexpected" print t let t ← whnfCore t print t pure () #eval tst8 def tst9 : MetaM Unit := do print "----- tst9 -----" let defInsts ← getDefaultInstances `OfNat print (toString defInsts) pure () #eval tst9 mutual inductive Foo (α : Type) where | mk : List (Bla α) → Foo α | leaf : α → Foo α inductive Bla (α : Type) where | nil : Bla α | cons : Foo α → Bla α → Bla α end def tst10 : MetaM Unit := do assert! !(← getConstInfoInduct `List).isNested assert! (← getConstInfoInduct `Bla).isNested assert! (← getConstInfoInduct `Foo).isNested assert! !(← getConstInfoInduct `Prod).isNested #eval tst10
dfe1b5a37f8ee5a9a036838573824278b6207d19
b70031c8e2c5337b91d7e70f1e0c5f528f7b0e77
/src/ring_theory/polynomial/cyclotomic.lean
100ddb458baa575a7724dc178a04a8a0ad375781
[ "Apache-2.0" ]
permissive
molodiuc/mathlib
cae2ba3ef1601c1f42ca0b625c79b061b63fef5b
98ebe5a6739fbe254f9ee9d401882d4388f91035
refs/heads/master
1,674,237,127,059
1,606,353,533,000
1,606,353,533,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
19,048
lean
/- Copyright (c) 2020 Riccardo Brasca. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Riccardo Brasca -/ import field_theory.splitting_field import ring_theory.roots_of_unity import algebra.polynomial.big_operators import number_theory.divisors import data.polynomial.lifts import analysis.complex.roots_of_unity /-! # Cyclotomic polynomials. For `n : ℕ` and an integral domain `R`, we define a modified version of the `n`-th cyclotomic polynomial with coefficients in `R`, denoted `cyclotomic' n R`, as `∏ (X - μ)`, where `μ` varies over the primitive `n`th roots of unity. If there is a primitive `n`th root of unity in `R` then this the standard definition. We then define the standard cyclotomic polynomial `cyclotomic n R` with coefficients in any ring `R`. ## Main definition * `cyclotomic n R` : the `n`-th cyclotomic polynomial with coefficients in `R`. ## Main results * `int_coeff_of_cycl` : If there is a primitive `n`-th root of unity in `K`, then `cyclotomic' n K` comes from a polynomial with integer coefficients. * `deg_of_cyclotomic` : The degree of `cyclotomic n` is `totient n`. * `X_pow_sub_one_eq_prod_cycl` : `X ^ n - 1 = ∏ (cyclotomic i)`, where `i` divides `n`. ## Implementation details Our definition of `cyclotomic' n R` makes sense in any integral domain `R`, but the interesting results hold if there is a primitive `n`th root of unity in `R`. In particular, our definition is not the standard one unless there is a primitive `n`th root of unity in `R`. For example, `cyclotomic' 3 ℤ = 1`, since there are no primitive cube roots of unity in `ℤ`. The main example is `R = ℂ`, we decided to work in general since the difficulties are essentially the same. To get the standard cyclotomic polynomials, we use `int_coeff_of_cycl`, with `R = ℂ`, to get a polynomial with integer coefficients and then we map it to `polynomial R`, for any ring `R`. -/ open_locale classical big_operators noncomputable theory universe u namespace polynomial section cyclotomic' section integral_domain variables {R : Type*} [integral_domain R] /-- The modified `n`-th cyclotomic polynomial with coefficients in `R`, it is the usual cyclotomic polynomial if there is a primitive `n`-th root of unity in `R`. -/ def cyclotomic' (n : ℕ) (R : Type*) [integral_domain R] : polynomial R := ∏ μ in primitive_roots n R, (X - C μ) /-- The zeroth modified cyclotomic polyomial is `1`. -/ @[simp] lemma cyclotomic'_zero (R : Type*) [integral_domain R] : cyclotomic' 0 R = 1 := by simp only [cyclotomic', finset.prod_empty, is_primitive_root.primitive_roots_zero] /-- The first modified cyclotomic polyomial is `X - 1`. -/ @[simp] lemma cyclotomic'_one (R : Type*) [integral_domain R] : cyclotomic' 1 R = X - 1 := begin simp only [cyclotomic', finset.prod_singleton, ring_hom.map_one, is_primitive_root.primitive_roots_one] end /-- The second modified cyclotomic polyomial is `X + 1` if the characteristic of `R` is not `2`. -/ @[simp] lemma cyclotomic'_two (R : Type*) [integral_domain R] (p : ℕ) [char_p R p] (hp : p ≠ 2) : cyclotomic' 2 R = X + 1 := begin rw [cyclotomic'], have prim_root_two : primitive_roots 2 R = {(-1 : R)}, { apply finset.eq_singleton_iff_unique_mem.2, split, { simp only [is_primitive_root.neg_one p hp, nat.succ_pos', mem_primitive_roots] }, { intros x hx, rw [mem_primitive_roots zero_lt_two] at hx, exact is_primitive_root.eq_neg_one_of_two_right hx } }, simp only [prim_root_two, finset.prod_singleton, ring_hom.map_neg, ring_hom.map_one, sub_neg_eq_add] end /-- `cyclotomic' n R` is monic. -/ lemma cyclotomic'.monic (n : ℕ) (R : Type*) [integral_domain R] : (cyclotomic' n R).monic := monic_prod_of_monic _ _ $ λ z hz, monic_X_sub_C _ /-- `cyclotomic' n R` is different from `0`. -/ lemma cyclotomic'_ne_zero (n : ℕ) (R : Type*) [integral_domain R] : cyclotomic' n R ≠ 0 := (cyclotomic'.monic n R).ne_zero /-- The natural degree of `cyclotomic' n R` is `totient n` if there is a primitive root of unity in `R`. -/ lemma nat_degree_cyclotomic' {ζ : R} {n : ℕ} (h : is_primitive_root ζ n) : (cyclotomic' n R).nat_degree = nat.totient n := begin cases nat.eq_zero_or_pos n with hzero hpos, { simp only [hzero, cyclotomic'_zero, nat.totient_zero, nat_degree_one] }, rw [cyclotomic'], rw nat_degree_prod (primitive_roots n R) (λ (z : R), (X - C z)), simp only [is_primitive_root.card_primitive_roots h hpos, mul_one, nat_degree_X_sub_C, nat.cast_id, finset.sum_const, nsmul_eq_mul], intros z hz, exact X_sub_C_ne_zero z end /-- The degree of `cyclotomic' n R` is `totient n` if there is a primitive root of unity in `R`. -/ lemma degree_cyclotomic' {ζ : R} {n : ℕ} (h : is_primitive_root ζ n) : (cyclotomic' n R).degree = nat.totient n := by simp only [degree_eq_nat_degree (cyclotomic'_ne_zero n R), nat_degree_cyclotomic' h] /-- The roots of `cyclotomic' n R` are the primitive `n`-th roots of unity. -/ lemma roots_of_cyclotomic (n : ℕ) (R : Type*) [integral_domain R] : (cyclotomic' n R).roots = (primitive_roots n R).val := by { rw cyclotomic', exact roots_prod_X_sub_C (primitive_roots n R) } end integral_domain section field variables {K : Type*} [field K] /-- If there is a primitive `n`th root of unity in `K`, then `X ^ n - 1 = ∏ (X - μ)`, where `μ` varies over the `n`-th roots of unity. -/ lemma X_pow_sub_one_eq_prod {ζ : K} {n : ℕ} (hpos : 0 < n) (h : is_primitive_root ζ n) : X ^ n - 1 = ∏ ζ in nth_roots_finset n K, (X - C ζ) := begin rw [nth_roots_finset, ← multiset.to_finset_eq (is_primitive_root.nth_roots_nodup h)], simp only [finset.prod_mk, ring_hom.map_one], rw [nth_roots], have hmonic : (X ^ n - C (1 : K)).monic := monic_X_pow_sub_C (1 : K) (ne_of_lt hpos).symm, symmetry, apply prod_multiset_X_sub_C_of_monic_of_roots_card_eq hmonic, rw [@nat_degree_X_pow_sub_C K _ _ n hpos 1, ← nth_roots], exact is_primitive_root.card_nth_roots h end /-- `cyclotomic' n K` splits. -/ lemma cyclotomic'_splits (n : ℕ) : splits (ring_hom.id K) (cyclotomic' n K) := begin apply splits_prod (ring_hom.id K), intros z hz, simp only [splits_X_sub_C (ring_hom.id K)] end /-- If there is a primitive `n`-th root of unity in `K`, then `X ^ n - 1`splits. -/ lemma X_pow_sub_one_splits {ζ : K} {n : ℕ} (h : is_primitive_root ζ n) : splits (ring_hom.id K) (X ^ n - C (1 : K)) := begin by_cases hzero : n = 0, { simp only [hzero, ring_hom.map_one, splits_zero, pow_zero, sub_self] }, rw [splits_iff_card_roots, ← nth_roots, is_primitive_root.card_nth_roots h, nat_degree_X_pow_sub_C], exact nat.pos_of_ne_zero hzero end /-- If there is a primitive `n`-th root of unity in `K`, then `∏ i in nat.divisors n, cyclotomic' i K = X ^ n - 1`. -/ lemma prod_cyclotomic'_eq_X_pow_sub_one {ζ : K} {n : ℕ} (hpos : 0 < n) (h : is_primitive_root ζ n) : ∏ i in nat.divisors n, cyclotomic' i K = X ^ n - 1 := begin rw [X_pow_sub_one_eq_prod hpos h], have rwcyc : ∀ i ∈ nat.divisors n, cyclotomic' i K = ∏ μ in primitive_roots i K, (X - C μ), { intros i hi, simp only [cyclotomic'] }, conv_lhs { apply_congr, skip, simp [rwcyc, H] }, rw ← finset.prod_bind, { simp only [is_primitive_root.nth_roots_one_eq_bind_primitive_roots hpos h] }, intros x hx y hy hdiff, simp only [nat.mem_divisors, and_true, ne.def, pnat.ne_zero, not_false_iff] at hx hy, refine is_primitive_root.disjoint _ _ hdiff, { exact @nat.pos_of_mem_divisors n x (nat.mem_divisors.2 hx) }, { exact @nat.pos_of_mem_divisors n y (nat.mem_divisors.2 hy) } end /-- If there is a primitive `n`-th root of unity in `K`, then `cyclotomic' n K = (X ^ k - 1) /ₘ (∏ i in nat.proper_divisors k, cyclotomic' i K)`. -/ lemma cyclotomic'_eq_X_pow_sub_one_div {ζ : K} {n : ℕ} (hpos: 0 < n) (h : is_primitive_root ζ n) : cyclotomic' n K = (X ^ n - 1) /ₘ (∏ i in nat.proper_divisors n, cyclotomic' i K) := begin rw [←prod_cyclotomic'_eq_X_pow_sub_one hpos h, nat.divisors_eq_proper_divisors_insert_self_of_pos hpos, finset.prod_insert nat.proper_divisors.not_self_mem], have prod_monic : (∏ i in nat.proper_divisors n, cyclotomic' i K).monic, { apply monic_prod_of_monic, intros i hi, exact cyclotomic'.monic i K }, rw (div_mod_by_monic_unique (cyclotomic' n K) 0 prod_monic _).1, simp only [degree_zero, zero_add], split, { rw mul_comm }, rw [bot_lt_iff_ne_bot], intro h, exact monic.ne_zero prod_monic (degree_eq_bot.1 h) end /-- If there is a primitive `n`-th root of unity in `K`, then `cyclotomic' n K` comes from a polynomial with integer coefficients. -/ lemma int_coeff_of_cyclotomic {ζ : K} {n : ℕ} (h : is_primitive_root ζ n) : (∃ (P : polynomial ℤ), map (int.cast_ring_hom K) P = cyclotomic' n K ∧ P.degree = (cyclotomic' n K).degree ∧ P.monic) := begin refine lifts_and_degree_eq_and_monic _ (cyclotomic'.monic n K), revert h ζ, apply nat.strong_induction_on n, intros k hk z hzeta, cases nat.eq_zero_or_pos k with hzero hpos, { use 1, simp only [hzero, cyclotomic'_zero, set.mem_univ, subsemiring.coe_top, eq_self_iff_true, map_one, ring_hom.coe_of, and_self], }, by_cases hone : k = 1, { use X - 1, simp only [hone, cyclotomic'_one K, set.mem_univ, pnat.one_coe, subsemiring.coe_top, eq_self_iff_true, map_X, map_one, ring_hom.coe_of, and_self, map_sub] }, let B : polynomial K := ∏ i in nat.proper_divisors k, cyclotomic' i K, have Bmo : B.monic, { apply monic_prod_of_monic, intros i hi, exact (cyclotomic'.monic i K) }, have Bint : B ∈ lifts (int.cast_ring_hom K), { refine subsemiring.prod_mem (lifts (int.cast_ring_hom K)) _, intros x hx, have xsmall := (nat.mem_proper_divisors.1 hx).2, obtain ⟨d, hd⟩ := (nat.mem_proper_divisors.1 hx).1, rw [mul_comm] at hd, exact hk x xsmall (is_primitive_root.pow hpos hzeta hd) }, replace Bint := lifts_and_degree_eq_and_monic Bint Bmo, obtain ⟨B₁, hB₁, hB₁deg, hB₁mo⟩ := Bint, let Q₁ : polynomial ℤ := (X ^ k - 1) /ₘ B₁, have huniq : 0 + B * cyclotomic' k K = X ^ k - 1 ∧ (0 : polynomial K).degree < B.degree, { split, { rw [zero_add, mul_comm, ←(prod_cyclotomic'_eq_X_pow_sub_one hpos hzeta), nat.divisors_eq_proper_divisors_insert_self_of_pos hpos], simp only [true_and, finset.prod_insert, not_lt, nat.mem_proper_divisors, dvd_refl] }, rw [degree_zero, bot_lt_iff_ne_bot], intro habs, exact (monic.ne_zero Bmo) (degree_eq_bot.1 habs) }, replace huniq := div_mod_by_monic_unique (cyclotomic' k K) (0 : polynomial K) Bmo huniq, simp only [lifts, ring_hom.coe_of, ring_hom.mem_srange], use Q₁, rw [(map_div_by_monic (int.cast_ring_hom K) hB₁mo), hB₁, ← huniq.1], simp end /-- If `K` is of characteristic `0` and there is a primitive `n`-th root of unity in `K`, then `cyclotomic n K` comes from a unique polynomial with integer coefficients. -/ lemma unique_int_coeff_of_cycl [char_zero K] {ζ : K} {n : ℕ+} (h : is_primitive_root ζ n) : (∃! (P : polynomial ℤ), map (int.cast_ring_hom K) P = cyclotomic' n K) := begin obtain ⟨P, hP⟩ := int_coeff_of_cyclotomic h, rw exists_unique, use [P, hP.1], intros Q hQ, have mapinj : function.injective (map (int.cast_ring_hom K)), { apply map_injective, simp only [int.cast_injective, int.coe_cast_ring_hom] }, rw [function.injective] at mapinj, apply mapinj, rw [hP.1, hQ] end end field end cyclotomic' section cyclotomic /-- The `n`-th cyclotomic polynomial with coefficients in `R`. -/ def cyclotomic (n : ℕ) (R : Type*) [ring R] : polynomial R := if h : n = 0 then 1 else map (int.cast_ring_hom R) (classical.some (int_coeff_of_cyclotomic (complex.is_primitive_root_exp n h))) lemma int_cyclotomic_rw {n : ℕ} (h : n ≠ 0) : cyclotomic n ℤ = (classical.some (int_coeff_of_cyclotomic (complex.is_primitive_root_exp n h))) := begin simp only [cyclotomic, h, dif_neg, not_false_iff], ext i, simp only [coeff_map, int.cast_id, ring_hom.eq_int_cast] end /-- `cyclotomic n R` comes from `cyclotomic n ℤ`. -/ lemma map_cyclotomic_int (n : ℕ) (R : Type*) [ring R] : map (int.cast_ring_hom R) (cyclotomic n ℤ) = cyclotomic n R := begin by_cases hzero : n = 0, { simp only [hzero, cyclotomic, dif_pos, map_one] }, simp only [cyclotomic, int_cyclotomic_rw, hzero, ne.def, dif_neg, not_false_iff] end lemma int_cyclotomic_spec (n : ℕ) : map (int.cast_ring_hom ℂ) (cyclotomic n ℤ) = cyclotomic' n ℂ ∧ (cyclotomic n ℤ).degree = (cyclotomic' n ℂ).degree ∧ (cyclotomic n ℤ).monic := begin by_cases hzero : n = 0, { simp only [hzero, cyclotomic, degree_one, monic_one, cyclotomic'_zero, dif_pos, eq_self_iff_true, map_one, and_self] }, rw int_cyclotomic_rw hzero, exact classical.some_spec (int_coeff_of_cyclotomic (complex.is_primitive_root_exp n hzero)) end lemma int_cyclotomic_unique {n : ℕ} {P : polynomial ℤ} (h : map (int.cast_ring_hom ℂ) P = cyclotomic' n ℂ) : P = cyclotomic n ℤ := begin have mapinj : function.injective (map (int.cast_ring_hom ℂ)), { apply map_injective, simp only [int.cast_injective, int.coe_cast_ring_hom] }, apply mapinj, rw [h, (int_cyclotomic_spec n).1] end /-- The definition of `cyclotomic n R` commutes with any ring homomorphism. -/ @[simp] lemma map_cyclotomic (n : ℕ) {R S : Type*} [ring R] [ring S] (f : R →+* S) : map f (cyclotomic n R) = cyclotomic n S := begin rw [←map_cyclotomic_int n R, ←map_cyclotomic_int n S], ext i, simp only [coeff_map, ring_hom.eq_int_cast, ring_hom.map_int_cast] end /-- The zeroth cyclotomic polyomial is `1`. -/ @[simp] lemma cyclotomic_zero (R : Type*) [ring R] : cyclotomic 0 R = 1 := by simp only [cyclotomic, dif_pos] /-- The first cyclotomic polyomial is `X - 1`. -/ @[simp] lemma cyclotomic_one (R : Type*) [ring R] : cyclotomic 1 R = X - 1 := begin have hspec : map (int.cast_ring_hom ℂ) (X - 1) = cyclotomic' 1 ℂ, { simp only [cyclotomic'_one, pnat.one_coe, map_X, map_one, map_sub] }, symmetry, rw [←map_cyclotomic_int, ←(int_cyclotomic_unique hspec)], simp only [map_X, map_one, map_sub] end /-- The second cyclotomic polyomial is `X + 1`. -/ @[simp] lemma cyclotomic_two (R : Type*) [ring R] : cyclotomic 2 R = X + 1 := begin have hspec : map (int.cast_ring_hom ℂ) (X + 1) = cyclotomic' 2 ℂ, { simp only [cyclotomic'_two ℂ 0 two_ne_zero.symm, map_add, map_X, map_one] }, symmetry, rw [←map_cyclotomic_int, ←(int_cyclotomic_unique hspec)], simp only [map_add, map_X, map_one] end /-- `cyclotomic n` is monic. -/ lemma cyclotomic.monic (n : ℕ) (R : Type*) [ring R] : (cyclotomic n R).monic := begin rw ←map_cyclotomic_int, apply monic_map, exact (int_cyclotomic_spec n).2.2 end /-- `cyclotomic n R` is different from `0`. -/ lemma cyclotomic_ne_zero (n : ℕ) (R : Type*) [ring R] [nontrivial R] : cyclotomic n R ≠ 0 := monic.ne_zero (cyclotomic.monic n R) /-- The degree of `cyclotomic n` is `totient n`. -/ lemma degree_cyclotomic (n : ℕ) (R : Type*) [ring R] [nontrivial R] : (cyclotomic n R).degree = nat.totient n := begin rw ←map_cyclotomic_int, rw degree_map_eq_of_leading_coeff_ne_zero (int.cast_ring_hom R) _, { cases n with k, { simp only [cyclotomic, degree_one, dif_pos, nat.totient_zero, with_top.coe_zero]}, rw [←degree_cyclotomic' (complex.is_primitive_root_exp k.succ (nat.succ_ne_zero k))], exact (int_cyclotomic_spec k.succ).2.1 }, simp only [(int_cyclotomic_spec n).right.right, ring_hom.eq_int_cast, monic.leading_coeff, int.cast_one, ne.def, not_false_iff, one_ne_zero] end /-- The natural degree of `cyclotomic n` is `totient n`. -/ lemma nat_degree_cyclotomic (n : ℕ) (R : Type*) [ring R] [nontrivial R] : (cyclotomic n R).nat_degree = nat.totient n := begin have hdeg := degree_cyclotomic n R, rw degree_eq_nat_degree (cyclotomic_ne_zero n R) at hdeg, norm_cast at hdeg, exact hdeg end /-- `∏ i in nat.divisors n, cyclotomic i R = X ^ n - 1`. -/ lemma prod_cyclotomic_eq_X_pow_sub_one {n : ℕ} (hpos : 0 < n) (R : Type*) [comm_ring R] : ∏ i in nat.divisors n, cyclotomic i R = X ^ n - 1 := begin have integer : ∏ i in nat.divisors n, cyclotomic i ℤ = X ^ n - 1, { have mapinj : function.injective (map (int.cast_ring_hom ℂ)), { apply map_injective, simp only [int.cast_injective, int.coe_cast_ring_hom] }, apply mapinj, rw map_prod (int.cast_ring_hom ℂ) (λ i, cyclotomic i ℤ), simp only [int_cyclotomic_spec, map_pow, nat.cast_id, map_X, map_one, ring_hom.coe_of, map_sub], exact prod_cyclotomic'_eq_X_pow_sub_one hpos (complex.is_primitive_root_exp n (ne_of_lt hpos).symm) }, have coerc : X ^ n - 1 = map (int.cast_ring_hom R) (X ^ n - 1), { simp only [map_pow, map_X, map_one, map_sub] }, have h : ∀ i ∈ n.divisors, cyclotomic i R = map (int.cast_ring_hom R) (cyclotomic i ℤ), { intros i hi, exact (map_cyclotomic_int i R).symm }, rw [finset.prod_congr (refl n.divisors) h, coerc, ←map_prod (int.cast_ring_hom R) (λ i, cyclotomic i ℤ), integer] end /-- We have `cyclotomic n R = (X ^ k - 1) /ₘ (∏ i in nat.proper_divisors k, cyclotomic i K)`. -/ lemma cyclotomic_eq_X_pow_sub_one_div {R : Type*} [comm_ring R] [nontrivial R] {n : ℕ} (hpos: 0 < n) : cyclotomic n R = (X ^ n - 1) /ₘ (∏ i in nat.proper_divisors n, cyclotomic i R) := begin rw [←prod_cyclotomic_eq_X_pow_sub_one hpos, nat.divisors_eq_proper_divisors_insert_self_of_pos hpos, finset.prod_insert nat.proper_divisors.not_self_mem], have prod_monic : (∏ i in nat.proper_divisors n, cyclotomic i R).monic, { apply monic_prod_of_monic, intros i hi, exact cyclotomic.monic i R }, rw (div_mod_by_monic_unique (cyclotomic n R) 0 prod_monic _).1, simp only [degree_zero, zero_add], split, { rw mul_comm }, rw [bot_lt_iff_ne_bot], intro h, exact monic.ne_zero prod_monic (degree_eq_bot.1 h) end /-- If there is a primitive `n`-th root of unity in `K`, then `cyclotomic n K = ∏ μ in primitive_roots n R, (X - C μ)`. In particular, `cyclotomic n K = cyclotomic' n K` -/ lemma cyclotomic_eq_prod_X_sub_primitive_roots {K : Type*} [field K] {ζ : K} {n : ℕ} (h : is_primitive_root ζ n) : cyclotomic n K = ∏ μ in primitive_roots n K, (X - C μ) := begin rw ←cyclotomic', revert h ζ, apply nat.strong_induction_on n, intros k hk z hz, cases nat.eq_zero_or_pos k with hzero hpos, { simp only [hzero, cyclotomic'_zero, cyclotomic_zero] }, have h : ∀ i ∈ k.proper_divisors, cyclotomic i K = cyclotomic' i K, { intros i hi, obtain ⟨d, hd⟩ := (nat.mem_proper_divisors.1 hi).1, rw mul_comm at hd, exact hk i (nat.mem_proper_divisors.1 hi).2 (is_primitive_root.pow hpos hz hd) }, rw [@cyclotomic_eq_X_pow_sub_one_div _ _ (field.to_nontrivial K) _ hpos, cyclotomic'_eq_X_pow_sub_one_div hpos hz, finset.prod_congr (refl k.proper_divisors) h] end end cyclotomic end polynomial
9bc9b8e0bc428a36b4979a4af920956dd15a827f
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/tactic/norm_num_auto.lean
7cb33f675165b5e13175907677709057f8b45342
[]
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
25,535
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 -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.rat.cast import Mathlib.data.rat.meta_defs import Mathlib.PostPort universes u_1 u namespace Mathlib /-! # `norm_num` Evaluating arithmetic expressions including `*`, `+`, `-`, `^`, `≤`. -/ namespace tactic /-- Reflexivity conversion: given `e` returns `(e, ⊢ e = e)` -/ /-- Transitivity conversion: given two conversions (which take an expression `e` and returns `(e', ⊢ e = e')`), produces another conversion that combines them with transitivity, treating failures as reflexivity conversions. -/ namespace instance_cache /-- Faster version of `mk_app ``bit0 [e]`. -/ /-- Faster version of `mk_app ``bit1 [e]`. -/ end instance_cache end tactic namespace norm_num theorem subst_into_add {α : Type u_1} [Add α] (l : α) (r : α) (tl : α) (tr : α) (t : α) (prl : l = tl) (prr : r = tr) (prt : tl + tr = t) : l + r = t := eq.mpr (id (Eq._oldrec (Eq.refl (l + r = t)) prl)) (eq.mpr (id (Eq._oldrec (Eq.refl (tl + r = t)) prr)) (eq.mpr (id (Eq._oldrec (Eq.refl (tl + tr = t)) prt)) (Eq.refl t))) theorem subst_into_mul {α : Type u_1} [Mul α] (l : α) (r : α) (tl : α) (tr : α) (t : α) (prl : l = tl) (prr : r = tr) (prt : tl * tr = t) : l * r = t := eq.mpr (id (Eq._oldrec (Eq.refl (l * r = t)) prl)) (eq.mpr (id (Eq._oldrec (Eq.refl (tl * r = t)) prr)) (eq.mpr (id (Eq._oldrec (Eq.refl (tl * tr = t)) prt)) (Eq.refl t))) theorem subst_into_neg {α : Type u_1} [Neg α] (a : α) (ta : α) (t : α) (pra : a = ta) (prt : -ta = t) : -a = t := sorry /-- The result type of `match_numeral`, either `0`, `1`, or a top level decomposition of `bit0 e` or `bit1 e`. The `other` case means it is not a numeral. -/ /-- Unfold the top level constructor of the numeral expression. -/ theorem zero_succ {α : Type u_1} [semiring α] : 0 + 1 = 1 := zero_add 1 theorem one_succ {α : Type u_1} [semiring α] : 1 + 1 = bit0 1 := rfl theorem bit0_succ {α : Type u_1} [semiring α] (a : α) : bit0 a + 1 = bit1 a := rfl theorem bit1_succ {α : Type u_1} [semiring α] (a : α) (b : α) (h : a + 1 = b) : bit1 a + 1 = bit0 b := sorry /-- Given `a`, `b` natural numerals, proves `⊢ a + 1 = b`, assuming that this is provable. (It may prove garbage instead of failing if `a + 1 = b` is false.) -/ theorem zero_adc {α : Type u_1} [semiring α] (a : α) (b : α) (h : a + 1 = b) : 0 + a + 1 = b := eq.mpr (id (Eq._oldrec (Eq.refl (0 + a + 1 = b)) (zero_add a))) h theorem adc_zero {α : Type u_1} [semiring α] (a : α) (b : α) (h : a + 1 = b) : a + 0 + 1 = b := eq.mpr (id (Eq._oldrec (Eq.refl (a + 0 + 1 = b)) (add_zero a))) h theorem one_add {α : Type u_1} [semiring α] (a : α) (b : α) (h : a + 1 = b) : 1 + a = b := eq.mpr (id (Eq._oldrec (Eq.refl (1 + a = b)) (add_comm 1 a))) h theorem add_bit0_bit0 {α : Type u_1} [semiring α] (a : α) (b : α) (c : α) (h : a + b = c) : bit0 a + bit0 b = bit0 c := sorry theorem add_bit0_bit1 {α : Type u_1} [semiring α] (a : α) (b : α) (c : α) (h : a + b = c) : bit0 a + bit1 b = bit1 c := sorry theorem add_bit1_bit0 {α : Type u_1} [semiring α] (a : α) (b : α) (c : α) (h : a + b = c) : bit1 a + bit0 b = bit1 c := sorry theorem add_bit1_bit1 {α : Type u_1} [semiring α] (a : α) (b : α) (c : α) (h : a + b + 1 = c) : bit1 a + bit1 b = bit0 c := sorry theorem adc_one_one {α : Type u_1} [semiring α] : 1 + 1 + 1 = bit1 1 := rfl theorem adc_bit0_one {α : Type u_1} [semiring α] (a : α) (b : α) (h : a + 1 = b) : bit0 a + 1 + 1 = bit0 b := sorry theorem adc_one_bit0 {α : Type u_1} [semiring α] (a : α) (b : α) (h : a + 1 = b) : 1 + bit0 a + 1 = bit0 b := sorry theorem adc_bit1_one {α : Type u_1} [semiring α] (a : α) (b : α) (h : a + 1 = b) : bit1 a + 1 + 1 = bit1 b := sorry theorem adc_one_bit1 {α : Type u_1} [semiring α] (a : α) (b : α) (h : a + 1 = b) : 1 + bit1 a + 1 = bit1 b := sorry theorem adc_bit0_bit0 {α : Type u_1} [semiring α] (a : α) (b : α) (c : α) (h : a + b = c) : bit0 a + bit0 b + 1 = bit1 c := sorry theorem adc_bit1_bit0 {α : Type u_1} [semiring α] (a : α) (b : α) (c : α) (h : a + b + 1 = c) : bit1 a + bit0 b + 1 = bit0 c := sorry theorem adc_bit0_bit1 {α : Type u_1} [semiring α] (a : α) (b : α) (c : α) (h : a + b + 1 = c) : bit0 a + bit1 b + 1 = bit0 c := sorry theorem adc_bit1_bit1 {α : Type u_1} [semiring α] (a : α) (b : α) (c : α) (h : a + b + 1 = c) : bit1 a + bit1 b + 1 = bit1 c := sorry /-- Given `a`,`b`,`r` natural numerals, proves `⊢ a + b = r`. -/ /-- Given `a`,`b`,`r` natural numerals, proves `⊢ a + b + 1 = r`. -/ /-- Given `a`,`b` natural numerals, returns `(r, ⊢ a + b = r)`. -/ theorem bit0_mul {α : Type u_1} [semiring α] (a : α) (b : α) (c : α) (h : a * b = c) : bit0 a * b = bit0 c := sorry theorem mul_bit0' {α : Type u_1} [semiring α] (a : α) (b : α) (c : α) (h : a * b = c) : a * bit0 b = bit0 c := sorry theorem mul_bit0_bit0 {α : Type u_1} [semiring α] (a : α) (b : α) (c : α) (h : a * b = c) : bit0 a * bit0 b = bit0 (bit0 c) := bit0_mul a (bit0 b) (bit0 c) (mul_bit0' a b c h) theorem mul_bit1_bit1 {α : Type u_1} [semiring α] (a : α) (b : α) (c : α) (d : α) (e : α) (hc : a * b = c) (hd : a + b = d) (he : bit0 c + d = e) : bit1 a * bit1 b = bit1 e := sorry /-- Given `a`,`b` natural numerals, returns `(r, ⊢ a * b = r)`. -/ /-- Given `a` a positive natural numeral, returns `⊢ 0 < a`. -/ /-- Given `a` a rational numeral, returns `⊢ 0 < a`. -/ /-- `match_neg (- e) = some e`, otherwise `none` -/ /-- `match_sign (- e) = inl e`, `match_sign 0 = inr ff`, otherwise `inr tt` -/ theorem ne_zero_of_pos {α : Type u_1} [ordered_add_comm_group α] (a : α) : 0 < a → a ≠ 0 := ne_of_gt theorem ne_zero_neg {α : Type u_1} [add_group α] (a : α) : a ≠ 0 → -a ≠ 0 := mt (iff.mp neg_eq_zero) /-- Given `a` a rational numeral, returns `⊢ a ≠ 0`. -/ theorem clear_denom_div {α : Type u_1} [division_ring α] (a : α) (b : α) (b' : α) (c : α) (d : α) (h₀ : b ≠ 0) (h₁ : b * b' = d) (h₂ : a * b' = c) : a / b * d = c := eq.mpr (id (Eq._oldrec (Eq.refl (a / b * d = c)) (Eq.symm h₁))) (eq.mpr (id (Eq._oldrec (Eq.refl (a / b * (b * b') = c)) (Eq.symm (mul_assoc (a / b) b b')))) (eq.mpr (id (Eq._oldrec (Eq.refl (a / b * b * b' = c)) (div_mul_cancel a h₀))) h₂)) /-- Given `a` nonnegative rational and `d` a natural number, returns `(b, ⊢ a * d = b)`. (`d` should be a multiple of the denominator of `a`, so that `b` is a natural number.) -/ theorem nonneg_pos {α : Type u_1} [ordered_cancel_add_comm_monoid α] (a : α) : 0 < a → 0 ≤ a := le_of_lt theorem lt_one_bit0 {α : Type u_1} [linear_ordered_semiring α] (a : α) (h : 1 ≤ a) : 1 < bit0 a := lt_of_lt_of_le one_lt_two (iff.mpr bit0_le_bit0 h) theorem lt_one_bit1 {α : Type u_1} [linear_ordered_semiring α] (a : α) (h : 0 < a) : 1 < bit1 a := iff.mpr one_lt_bit1 h theorem lt_bit0_bit0 {α : Type u_1} [linear_ordered_semiring α] (a : α) (b : α) : a < b → bit0 a < bit0 b := iff.mpr bit0_lt_bit0 theorem lt_bit0_bit1 {α : Type u_1} [linear_ordered_semiring α] (a : α) (b : α) (h : a ≤ b) : bit0 a < bit1 b := lt_of_le_of_lt (iff.mpr bit0_le_bit0 h) (lt_add_one (bit0 b)) theorem lt_bit1_bit0 {α : Type u_1} [linear_ordered_semiring α] (a : α) (b : α) (h : a + 1 ≤ b) : bit1 a < bit0 b := sorry theorem lt_bit1_bit1 {α : Type u_1} [linear_ordered_semiring α] (a : α) (b : α) : a < b → bit1 a < bit1 b := iff.mpr bit1_lt_bit1 theorem le_one_bit0 {α : Type u_1} [linear_ordered_semiring α] (a : α) (h : 1 ≤ a) : 1 ≤ bit0 a := le_of_lt (lt_one_bit0 a h) -- deliberately strong hypothesis because bit1 0 is not a numeral theorem le_one_bit1 {α : Type u_1} [linear_ordered_semiring α] (a : α) (h : 0 < a) : 1 ≤ bit1 a := le_of_lt (lt_one_bit1 a h) theorem le_bit0_bit0 {α : Type u_1} [linear_ordered_semiring α] (a : α) (b : α) : a ≤ b → bit0 a ≤ bit0 b := iff.mpr bit0_le_bit0 theorem le_bit0_bit1 {α : Type u_1} [linear_ordered_semiring α] (a : α) (b : α) (h : a ≤ b) : bit0 a ≤ bit1 b := le_of_lt (lt_bit0_bit1 a b h) theorem le_bit1_bit0 {α : Type u_1} [linear_ordered_semiring α] (a : α) (b : α) (h : a + 1 ≤ b) : bit1 a ≤ bit0 b := le_of_lt (lt_bit1_bit0 a b h) theorem le_bit1_bit1 {α : Type u_1} [linear_ordered_semiring α] (a : α) (b : α) : a ≤ b → bit1 a ≤ bit1 b := iff.mpr bit1_le_bit1 theorem sle_one_bit0 {α : Type u_1} [linear_ordered_semiring α] (a : α) : 1 ≤ a → 1 + 1 ≤ bit0 a := iff.mpr bit0_le_bit0 theorem sle_one_bit1 {α : Type u_1} [linear_ordered_semiring α] (a : α) : 1 ≤ a → 1 + 1 ≤ bit1 a := le_bit0_bit1 1 a theorem sle_bit0_bit0 {α : Type u_1} [linear_ordered_semiring α] (a : α) (b : α) : a + 1 ≤ b → bit0 a + 1 ≤ bit0 b := le_bit1_bit0 a b theorem sle_bit0_bit1 {α : Type u_1} [linear_ordered_semiring α] (a : α) (b : α) (h : a ≤ b) : bit0 a + 1 ≤ bit1 b := iff.mpr bit1_le_bit1 h theorem sle_bit1_bit0 {α : Type u_1} [linear_ordered_semiring α] (a : α) (b : α) (h : a + 1 ≤ b) : bit1 a + 1 ≤ bit0 b := Eq.symm (bit1_succ a (a + 1) rfl) ▸ iff.mpr bit0_le_bit0 h theorem sle_bit1_bit1 {α : Type u_1} [linear_ordered_semiring α] (a : α) (b : α) (h : a + 1 ≤ b) : bit1 a + 1 ≤ bit1 b := Eq.symm (bit1_succ a (a + 1) rfl) ▸ le_bit0_bit1 (a + 1) b h /-- Given `a` a rational numeral, returns `⊢ 0 ≤ a`. -/ /-- Given `a` a rational numeral, returns `⊢ 1 ≤ a`. -/ /-- Given `a`,`b` natural numerals, proves `⊢ a ≤ b`. -/ /-- Given `a`,`b` natural numerals, proves `⊢ a + 1 ≤ b`. -/ /-- Given `a`,`b` natural numerals, proves `⊢ a < b`. -/ theorem clear_denom_lt {α : Type u_1} [linear_ordered_semiring α] (a : α) (a' : α) (b : α) (b' : α) (d : α) (h₀ : 0 < d) (ha : a * d = a') (hb : b * d = b') (h : a' < b') : a < b := lt_of_mul_lt_mul_right (eq.mpr (id (Eq._oldrec (Eq.refl (a * d < b * d)) ha)) (eq.mpr (id (Eq._oldrec (Eq.refl (a' < b * d)) hb)) h)) (le_of_lt h₀) /-- Given `a`,`b` nonnegative rational numerals, proves `⊢ a < b`. -/ theorem lt_neg_pos {α : Type u_1} [ordered_add_comm_group α] (a : α) (b : α) (ha : 0 < a) (hb : 0 < b) : -a < b := lt_trans (neg_neg_of_pos ha) hb /-- Given `a`,`b` rational numerals, proves `⊢ a < b`. -/ theorem clear_denom_le {α : Type u_1} [linear_ordered_semiring α] (a : α) (a' : α) (b : α) (b' : α) (d : α) (h₀ : 0 < d) (ha : a * d = a') (hb : b * d = b') (h : a' ≤ b') : a ≤ b := le_of_mul_le_mul_right (eq.mpr (id (Eq._oldrec (Eq.refl (a * d ≤ b * d)) ha)) (eq.mpr (id (Eq._oldrec (Eq.refl (a' ≤ b * d)) hb)) h)) h₀ /-- Given `a`,`b` nonnegative rational numerals, proves `⊢ a ≤ b`. -/ theorem le_neg_pos {α : Type u_1} [ordered_add_comm_group α] (a : α) (b : α) (ha : 0 ≤ a) (hb : 0 ≤ b) : -a ≤ b := le_trans (neg_nonpos_of_nonneg ha) hb /-- Given `a`,`b` rational numerals, proves `⊢ a ≤ b`. -/ /-- Given `a`,`b` rational numerals, proves `⊢ a ≠ b`. This version tries to prove `⊢ a < b` or `⊢ b < a`, and so is not appropriate for types without an order relation. -/ theorem nat_cast_zero {α : Type u_1} [semiring α] : ↑0 = 0 := nat.cast_zero theorem nat_cast_one {α : Type u_1} [semiring α] : ↑1 = 1 := nat.cast_one theorem nat_cast_bit0 {α : Type u_1} [semiring α] (a : ℕ) (a' : α) (h : ↑a = a') : ↑(bit0 a) = bit0 a' := h ▸ nat.cast_bit0 a theorem nat_cast_bit1 {α : Type u_1} [semiring α] (a : ℕ) (a' : α) (h : ↑a = a') : ↑(bit1 a) = bit1 a' := h ▸ nat.cast_bit1 a theorem int_cast_zero {α : Type u_1} [ring α] : ↑0 = 0 := int.cast_zero theorem int_cast_one {α : Type u_1} [ring α] : ↑1 = 1 := int.cast_one theorem int_cast_bit0 {α : Type u_1} [ring α] (a : ℤ) (a' : α) (h : ↑a = a') : ↑(bit0 a) = bit0 a' := h ▸ int.cast_bit0 a theorem int_cast_bit1 {α : Type u_1} [ring α] (a : ℤ) (a' : α) (h : ↑a = a') : ↑(bit1 a) = bit1 a' := h ▸ int.cast_bit1 a theorem rat_cast_bit0 {α : Type u_1} [division_ring α] [char_zero α] (a : ℚ) (a' : α) (h : ↑a = a') : ↑(bit0 a) = bit0 a' := h ▸ rat.cast_bit0 a theorem rat_cast_bit1 {α : Type u_1} [division_ring α] [char_zero α] (a : ℚ) (a' : α) (h : ↑a = a') : ↑(bit1 a) = bit1 a' := h ▸ rat.cast_bit1 a /-- Given `a' : α` a natural numeral, returns `(a : ℕ, ⊢ ↑a = a')`. (Note that the returned value is on the left of the equality.) -/ /-- Given `a' : α` a natural numeral, returns `(a : ℤ, ⊢ ↑a = a')`. (Note that the returned value is on the left of the equality.) -/ /-- Given `a' : α` a natural numeral, returns `(a : ℚ, ⊢ ↑a = a')`. (Note that the returned value is on the left of the equality.) -/ theorem rat_cast_div {α : Type u_1} [division_ring α] [char_zero α] (a : ℚ) (b : ℚ) (a' : α) (b' : α) (ha : ↑a = a') (hb : ↑b = b') : ↑(a / b) = a' / b' := ha ▸ hb ▸ rat.cast_div a b /-- Given `a' : α` a nonnegative rational numeral, returns `(a : ℚ, ⊢ ↑a = a')`. (Note that the returned value is on the left of the equality.) -/ theorem int_cast_neg {α : Type u_1} [ring α] (a : ℤ) (a' : α) (h : ↑a = a') : ↑(-a) = -a' := h ▸ int.cast_neg a theorem rat_cast_neg {α : Type u_1} [division_ring α] (a : ℚ) (a' : α) (h : ↑a = a') : ↑(-a) = -a' := h ▸ rat.cast_neg a /-- Given `a' : α` an integer numeral, returns `(a : ℤ, ⊢ ↑a = a')`. (Note that the returned value is on the left of the equality.) -/ /-- Given `a' : α` a rational numeral, returns `(a : ℚ, ⊢ ↑a = a')`. (Note that the returned value is on the left of the equality.) -/ theorem nat_cast_ne {α : Type u_1} [semiring α] [char_zero α] (a : ℕ) (b : ℕ) (a' : α) (b' : α) (ha : ↑a = a') (hb : ↑b = b') (h : a ≠ b) : a' ≠ b' := ha ▸ hb ▸ mt (iff.mp nat.cast_inj) h theorem int_cast_ne {α : Type u_1} [ring α] [char_zero α] (a : ℤ) (b : ℤ) (a' : α) (b' : α) (ha : ↑a = a') (hb : ↑b = b') (h : a ≠ b) : a' ≠ b' := ha ▸ hb ▸ mt (iff.mp int.cast_inj) h theorem rat_cast_ne {α : Type u_1} [division_ring α] [char_zero α] (a : ℚ) (b : ℚ) (a' : α) (b' : α) (ha : ↑a = a') (hb : ↑b = b') (h : a ≠ b) : a' ≠ b' := ha ▸ hb ▸ mt (iff.mp rat.cast_inj) h /-- Given `a`,`b` rational numerals, proves `⊢ a ≠ b`. Currently it tries two methods: * Prove `⊢ a < b` or `⊢ b < a`, if the base type has an order * Embed `↑(a':ℚ) = a` and `↑(b':ℚ) = b`, and then prove `a' ≠ b'`. This requires that the base type be `char_zero`, and also that it be a `division_ring` so that the coercion from `ℚ` is well defined. We may also add coercions to `ℤ` and `ℕ` as well in order to support `char_zero` rings and semirings. -/ /-- Given `a` a rational numeral, returns `⊢ a ≠ 0`. -/ /-- Given `a` nonnegative rational and `d` a natural number, returns `(b, ⊢ a * d = b)`. (`d` should be a multiple of the denominator of `a`, so that `b` is a natural number.) -/ theorem clear_denom_add {α : Type u_1} [division_ring α] (a : α) (a' : α) (b : α) (b' : α) (c : α) (c' : α) (d : α) (h₀ : d ≠ 0) (ha : a * d = a') (hb : b * d = b') (hc : c * d = c') (h : a' + b' = c') : a + b = c := sorry /-- Given `a`,`b`,`c` nonnegative rational numerals, returns `⊢ a + b = c`. -/ theorem add_pos_neg_pos {α : Type u_1} [add_group α] (a : α) (b : α) (c : α) (h : c + b = a) : a + -b = c := sorry theorem add_pos_neg_neg {α : Type u_1} [add_group α] (a : α) (b : α) (c : α) (h : c + a = b) : a + -b = -c := sorry theorem add_neg_pos_pos {α : Type u_1} [add_group α] (a : α) (b : α) (c : α) (h : a + c = b) : -a + b = c := sorry theorem add_neg_pos_neg {α : Type u_1} [add_group α] (a : α) (b : α) (c : α) (h : b + c = a) : -a + b = -c := sorry theorem add_neg_neg {α : Type u_1} [add_group α] (a : α) (b : α) (c : α) (h : b + a = c) : -a + -b = -c := sorry /-- Given `a`,`b`,`c` rational numerals, returns `⊢ a + b = c`. -/ /-- Given `a`,`b` rational numerals, returns `(c, ⊢ a + b = c)`. -/ theorem clear_denom_simple_nat {α : Type u_1} [division_ring α] (a : α) : 1 ≠ 0 ∧ a * 1 = a := { left := one_ne_zero, right := mul_one a } theorem clear_denom_simple_div {α : Type u_1} [division_ring α] (a : α) (b : α) (h : b ≠ 0) : b ≠ 0 ∧ a / b * b = a := { left := h, right := div_mul_cancel a h } /-- Given `a` a nonnegative rational numeral, returns `(b, c, ⊢ a * b = c)` where `b` and `c` are natural numerals. (`b` will be the denominator of `a`.) -/ theorem clear_denom_mul {α : Type u_1} [field α] (a : α) (a' : α) (b : α) (b' : α) (c : α) (c' : α) (d₁ : α) (d₂ : α) (d : α) (ha : d₁ ≠ 0 ∧ a * d₁ = a') (hb : d₂ ≠ 0 ∧ b * d₂ = b') (hc : c * d = c') (hd : d₁ * d₂ = d) (h : a' * b' = c') : a * b = c := sorry /-- Given `a`,`b` nonnegative rational numerals, returns `(c, ⊢ a * b = c)`. -/ theorem mul_neg_pos {α : Type u_1} [ring α] (a : α) (b : α) (c : α) (h : a * b = c) : -a * b = -c := sorry theorem mul_pos_neg {α : Type u_1} [ring α] (a : α) (b : α) (c : α) (h : a * b = c) : a * -b = -c := sorry theorem mul_neg_neg {α : Type u_1} [ring α] (a : α) (b : α) (c : α) (h : a * b = c) : -a * -b = c := sorry /-- Given `a`,`b` rational numerals, returns `(c, ⊢ a * b = c)`. -/ theorem inv_neg {α : Type u_1} [division_ring α] (a : α) (b : α) (h : a⁻¹ = b) : -a⁻¹ = -b := sorry theorem inv_one {α : Type u_1} [division_ring α] : 1⁻¹ = 1 := inv_one theorem inv_one_div {α : Type u_1} [division_ring α] (a : α) : 1 / a⁻¹ = a := eq.mpr (id (Eq._oldrec (Eq.refl (1 / a⁻¹ = a)) (one_div a))) (eq.mpr (id (Eq._oldrec (Eq.refl (a⁻¹⁻¹ = a)) (inv_inv' a))) (Eq.refl a)) theorem inv_div_one {α : Type u_1} [division_ring α] (a : α) : a⁻¹ = 1 / a := inv_eq_one_div a theorem inv_div {α : Type u_1} [division_ring α] (a : α) (b : α) : a / b⁻¹ = b / a := sorry /-- Given `a` a rational numeral, returns `(b, ⊢ a⁻¹ = b)`. -/ theorem div_eq {α : Type u_1} [division_ring α] (a : α) (b : α) (b' : α) (c : α) (hb : b⁻¹ = b') (h : a * b' = c) : a / b = c := eq.mp (Eq._oldrec (Eq.refl (a * (b⁻¹) = c)) (Eq.symm (div_eq_mul_inv a b))) (eq.mp (Eq._oldrec (Eq.refl (a * b' = c)) (Eq.symm hb)) h) /-- Given `a`,`b` rational numerals, returns `(c, ⊢ a / b = c)`. -/ /-- Given `a` a rational numeral, returns `(b, ⊢ -a = b)`. -/ theorem sub_pos {α : Type u_1} [add_group α] (a : α) (b : α) (b' : α) (c : α) (hb : -b = b') (h : a + b' = c) : a - b = c := eq.mp (Eq._oldrec (Eq.refl (a + -b = c)) (Eq.symm (sub_eq_add_neg a b))) (eq.mp (Eq._oldrec (Eq.refl (a + b' = c)) (Eq.symm hb)) h) theorem sub_neg {α : Type u_1} [add_group α] (a : α) (b : α) (c : α) (h : a + b = c) : a - -b = c := eq.mpr (id (Eq._oldrec (Eq.refl (a - -b = c)) (sub_neg_eq_add a b))) h /-- Given `a`,`b` rational numerals, returns `(c, ⊢ a - b = c)`. -/ theorem sub_nat_pos (a : ℕ) (b : ℕ) (c : ℕ) (h : b + c = a) : a - b = c := h ▸ nat.add_sub_cancel_left b c theorem sub_nat_neg (a : ℕ) (b : ℕ) (c : ℕ) (h : a + c = b) : a - b = 0 := nat.sub_eq_zero_of_le (h ▸ nat.le_add_right a c) /-- Given `a : nat`,`b : nat` natural numerals, returns `(c, ⊢ a - b = c)`. -/ /-- Evaluates the basic field operations `+`,`neg`,`-`,`*`,`inv`,`/` on numerals. Also handles nat subtraction. Does not do recursive simplification; that is, `1 + 1 + 1` will not simplify but `2 + 1` will. This is handled by the top level `simp` call in `norm_num.derive`. -/ theorem pow_bit0 {α : Type u} [monoid α] (a : α) (c' : α) (c : α) (b : ℕ) (h : a ^ b = c') (h₂ : c' * c' = c) : a ^ bit0 b = c := sorry theorem pow_bit1 {α : Type u} [monoid α] (a : α) (c₁ : α) (c₂ : α) (c : α) (b : ℕ) (h : a ^ b = c₁) (h₂ : c₁ * c₁ = c₂) (h₃ : c₂ * a = c) : a ^ bit1 b = c := sorry /-- Given `a` a rational numeral and `b : nat`, returns `(c, ⊢ a ^ b = c)`. -/ /-- Evaluates expressions of the form `a ^ b`, `monoid.pow a b` or `nat.pow a b`. -/ /-- Given `⊢ p`, returns `(true, ⊢ p = true)`. -/ /-- Given `⊢ ¬ p`, returns `(false, ⊢ p = false)`. -/ theorem not_refl_false_intro {α : Sort u_1} (a : α) : a ≠ a = False := eq_false_intro (not_not_intro rfl) /-- Evaluates the inequality operations `=`,`<`,`>`,`≤`,`≥`,`≠` on numerals. -/ theorem nat_succ_eq (a : ℕ) (b : ℕ) (c : ℕ) (h₁ : a = b) (h₂ : b + 1 = c) : Nat.succ a = c := eq.mpr (id (Eq._oldrec (Eq.refl (Nat.succ a = c)) h₁)) h₂ /-- Evaluates the expression `nat.succ ... (nat.succ n)` where `n` is a natural numeral. (We could also just handle `nat.succ n` here and rely on `simp` to work bottom up, but we figure that towers of successors coming from e.g. `induction` are a common case.) -/ theorem nat_div (a : ℕ) (b : ℕ) (q : ℕ) (r : ℕ) (m : ℕ) (hm : q * b = m) (h : r + m = a) (h₂ : r < b) : a / b = q := sorry theorem int_div (a : ℤ) (b : ℤ) (q : ℤ) (r : ℤ) (m : ℤ) (hm : q * b = m) (h : r + m = a) (h₁ : 0 ≤ r) (h₂ : r < b) : a / b = q := sorry theorem nat_mod (a : ℕ) (b : ℕ) (q : ℕ) (r : ℕ) (m : ℕ) (hm : q * b = m) (h : r + m = a) (h₂ : r < b) : a % b = r := sorry theorem int_mod (a : ℤ) (b : ℤ) (q : ℤ) (r : ℤ) (m : ℤ) (hm : q * b = m) (h : r + m = a) (h₁ : 0 ≤ r) (h₂ : r < b) : a % b = r := sorry theorem int_div_neg (a : ℤ) (b : ℤ) (c' : ℤ) (c : ℤ) (h : a / b = c') (h₂ : -c' = c) : a / -b = c := h₂ ▸ h ▸ int.div_neg a b theorem int_mod_neg (a : ℤ) (b : ℤ) (c : ℤ) (h : a % b = c) : a % -b = c := Eq.trans (int.mod_neg a b) h /-- Given `a`,`b` numerals in `nat` or `int`, * `prove_div_mod ic a b ff` returns `(c, ⊢ a / b = c)` * `prove_div_mod ic a b tt` returns `(c, ⊢ a % b = c)` -/ theorem dvd_eq_nat (a : ℕ) (b : ℕ) (c : ℕ) (p : Prop) (h₁ : b % a = c) (h₂ : c = 0 = p) : a ∣ b = p := sorry theorem dvd_eq_int (a : ℤ) (b : ℤ) (c : ℤ) (p : Prop) (h₁ : b % a = c) (h₂ : c = 0 = p) : a ∣ b = p := sorry /-- Evaluates some extra numeric operations on `nat` and `int`, specifically `nat.succ`, `/` and `%`, and `∣` (divisibility). -/ /-- This version of `derive` does not fail when the input is already a numeral -/ /-- An attribute for adding additional extensions to `norm_num`. To use this attribute, put `@[norm_num]` on a tactic of type `expr → tactic (expr × expr)`; the tactic will be called on subterms by `norm_num`, and it is responsible for identifying that the expression is a numerical function applied to numerals, for example `nat.fib 17`, and should return the reduced numerical expression (which must be in `norm_num`-normal form: a natural or rational numeral, i.e. `37`, `12 / 7` or `-(2 / 3)`, although this can be an expression in any type), and the proof that the original expression is equal to the rewritten expression. Failure is used to indicate that this tactic does not apply to the term. For performance reasons, it is best to detect non-applicability as soon as possible so that the next tactic can have a go, so generally it will start with a pattern match and then checking that the arguments to the term are numerals or of the appropriate form, followed by proof construction, which should not fail. Propositions are treated like any other term. The normal form for propositions is `true` or `false`, so it should produce a proof of the form `p = true` or `p = false`. `eq_true_intro` can be used to help here. -/ /-- Look up the `norm_num` extensions in the cache and return a tactic extending `derive.step` with additional reduction procedures. -/ /-- Simplify an expression bottom-up using `step` to simplify the subexpressions. -/ /-- Simplify an expression bottom-up using the default `norm_num` set to simplify the subexpressions. -/ end norm_num /-- Basic version of `norm_num` that does not call `simp`. It uses the provided `step` tactic to simplify the expression; use `get_step` to get the default `norm_num` set and `derive.step` for the basic builtin set of simplifications. -/ /-- Normalize numerical expressions. It uses the provided `step` tactic to simplify the expression; use `get_step` to get the default `norm_num` set and `derive.step` for the basic builtin set of simplifications. -/ namespace tactic.interactive /-- Basic version of `norm_num` that does not call `simp`. -/ /-- Normalize numerical expressions. Supports the operations `+` `-` `*` `/` `^` and `%` over numerical types such as `ℕ`, `ℤ`, `ℚ`, `ℝ`, `ℂ` and some general algebraic types, and can prove goals of the form `A = B`, `A ≠ B`, `A < B` and `A ≤ B`, where `A` and `B` are numerical expressions. It also has a relatively simple primality prover. -/ /-- Normalizes a numerical expression and tries to close the goal with the result. -/ /-- Normalises numerical expressions. It supports the operations `+` `-` `*` `/` `^` and `%` over end Mathlib
732b419e54ef5dfb5bbc5cfa5d13364106785e31
6e8de6b43162bef473b4a0bd93b71db886df98ce
/src/tactics/default.lean
c957dfac41d7afd869f71e863f0b017e50994406
[ "Unlicense" ]
permissive
adamtopaz/comb_geom
38ec6fde8d2543f56227ec50cdfb86cac6ac33c1
e16b629d6de3fbdea54a528755e7305dfb51e902
refs/heads/master
1,668,613,552,530
1,593,199,940,000
1,593,199,940,000
269,824,442
6
0
Unlicense
1,593,119,545,000
1,591,404,975,000
Lean
UTF-8
Lean
false
false
14
lean
import .macros
0b617d13ee1a11ba590bb143e2e906716a022702
cf39355caa609c0f33405126beee2739aa3cb77e
/library/init/meta/decl_cmds.lean
56cb738e606fe1eac1d67e59073903ce9e81b279
[ "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,036
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.meta.tactic init.meta.rb_map open tactic open native private meta def apply_replacement (replacements : name_map name) (e : expr) : expr := e.replace (λ e d, match e with | expr.const n ls := match replacements.find n with | some new_n := some (expr.const new_n ls) | none := none end | _ := none end) /-- Given a set of constant renamings `replacements` and a declaration name `src_decl_name`, create a new declaration called `new_decl_name` s.t. its type is the type of `src_decl_name` after applying the given constant replacement. Remark: the new type must be definitionally equal to the type of `src_decl_name`. Example: Assume the environment contains def f : nat -> nat := ... def g : nat -> nat := f lemma f_lemma : forall a, f a > 0 := ... Moreover, assume we have a mapping M containing `f -> `g Then, the command run_command copy_decl_updating_type M `f_lemma `g_lemma creates the declaration lemma g_lemma : forall a, g a > 0 := ... -/ meta def copy_decl_updating_type (replacements : name_map name) (src_decl_name : name) (new_decl_name : name) : command := do env ← get_env, decl ← env.get src_decl_name, let decl := decl.update_name $ new_decl_name, let decl := decl.update_type $ apply_replacement replacements decl.type, let decl := decl.update_value $ expr.const src_decl_name (decl.univ_params.map level.param), add_decl decl meta def copy_decl_using (replacements : name_map name) (src_decl_name : name) (new_decl_name : name) : command := do env ← get_env, decl ← env.get src_decl_name, let decl := decl.update_name $ new_decl_name, let decl := decl.update_type $ apply_replacement replacements decl.type, let decl := decl.map_value $ apply_replacement replacements, add_decl decl
35303d6271b535aacc3cb9e3c8cd6d1520c83539
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/measure_theory/measure/regular.lean
24cc65a014c334ed1aacf8416be66226012209fc
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
34,370
lean
/- Copyright (c) 2021 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris Van Doorn, Yury Kudryashov -/ import measure_theory.constructions.borel_space /-! # Regular measures A measure is `outer_regular` if the measure of any measurable set `A` is the infimum of `μ U` over all open sets `U` containing `A`. A measure is `regular` if it satisfies the following properties: * it is finite on compact sets; * it is outer regular; * it is inner regular for open sets with respect to compacts sets: the measure of any open set `U` is the supremum of `μ K` over all compact sets `K` contained in `U`. A measure is `weakly_regular` if it satisfies the following properties: * it is outer regular; * it is inner regular for open sets with respect to closed sets: the measure of any open set `U` is the supremum of `μ F` over all compact sets `F` contained in `U`. In a Hausdorff topological space, regularity implies weak regularity. These three conditions are registered as typeclasses for a measure `μ`, and this implication is recorded as an instance. In order to avoid code duplication, we also define a measure `μ` to be `inner_regular` for sets satisfying a predicate `q` with respect to sets satisfying a predicate `p` if for any set `U ∈ {U | q U}` and a number `r < μ U` there exists `F ⊆ U` such that `p F` and `r < μ F`. We prove that inner regularity for open sets with respect to compact sets or closed sets implies inner regularity for all measurable sets of finite measure (with respect to compact sets or closed sets respectively), and register some corollaries for (weakly) regular measures. Note that a similar statement for measurable sets of infinite mass can fail. For a counterexample, consider the group `ℝ × ℝ` where the first factor has the discrete topology and the second one the usual topology. It is a locally compact Hausdorff topological group, with Haar measure equal to Lebesgue measure on each vertical fiber. The set `ℝ × {0}` has infinite measure (by outer regularity), but any compact set it contains has zero measure (as it is finite). Several authors require as a definition of regularity that all measurable sets are inner regular. We have opted for the slightly weaker definition above as it holds for all Haar measures, it is enough for essentially all applications, and it is equivalent to the other definition when the measure is finite. The interest of the notion of weak regularity is that it is enough for many applications, and it is automatically satisfied by any finite measure on a metric space. ## Main definitions * `measure_theory.measure.outer_regular μ`: a typeclass registering that a measure `μ` on a topological space is outer regular. * `measure_theory.measure.regular μ`: a typeclass registering that a measure `μ` on a topological space is regular. * `measure_theory.measure.weakly_regular μ`: a typeclass registering that a measure `μ` on a topological space is weakly regular. * `measure_theory.measure.inner_regular μ p q`: a non-typeclass predicate saying that a measure `μ` is inner regular for sets satisfying `q` with respect to sets satisfying `p`. ## Main results ### Outer regular measures * `set.measure_eq_infi_is_open` asserts that, when `μ` is outer regular, the measure of a set is the infimum of the measure of open sets containing it. * `set.exists_is_open_lt_of_lt'` asserts that, when `μ` is outer regular, for every set `s` and `r > μ s` there exists an open superset `U ⊇ s` of measure less than `r`. * push forward of an outer regular measure is outer regular, and scalar multiplication of a regular measure by a finite number is outer regular. * `measure_theory.measure.outer_regular.of_sigma_compact_space_of_is_locally_finite_measure`: a locally finite measure on a `σ`-compact metric (or even pseudo emetric) space is outer regular. ### Weakly regular measures * `is_open.measure_eq_supr_is_closed` asserts that the measure of an open set is the supremum of the measure of closed sets it contains. * `is_open.exists_lt_is_closed`: for an open set `U` and `r < μ U`, there exists a closed `F ⊆ U` of measure greater than `r`; * `measurable_set.measure_eq_supr_is_closed_of_ne_top` asserts that the measure of a measurable set of finite measure is the supremum of the measure of closed sets it contains. * `measurable_set.exists_lt_is_closed_of_ne_top` and `measurable_set.exists_is_closed_lt_add`: a measurable set of finite measure can be approximated by a closed subset (stated as `r < μ F` and `μ s < μ F + ε`, respectively). * `measure_theory.measure.weakly_regular.of_pseudo_emetric_space_of_is_finite_measure` is an instance registering that a finite measure on a metric space is weakly regular (in fact, a pseudo emetric space is enough); * `measure_theory.measure.weakly_regular.of_pseudo_emetric_sigma_compact_space_of_locally_finite` is an instance registering that a locally finite measure on a `σ`-compact metric space (or even a pseudo emetric space) is weakly regular. ### Regular measures * `is_open.measure_eq_supr_is_compact` asserts that the measure of an open set is the supremum of the measure of compact sets it contains. * `is_open.exists_lt_is_compact`: for an open set `U` and `r < μ U`, there exists a compact `K ⊆ U` of measure greater than `r`; * `measurable_set.measure_eq_supr_is_compact_of_ne_top` asserts that the measure of a measurable set of finite measure is the supremum of the measure of compact sets it contains. * `measurable_set.exists_lt_is_compact_of_ne_top` and `measurable_set.exists_is_compact_lt_add`: a measurable set of finite measure can be approximated by a compact subset (stated as `r < μ K` and `μ s < μ K + ε`, respectively). * `measure_theory.measure.regular.of_sigma_compact_space_of_is_locally_finite_measure` is an instance registering that a locally finite measure on a `σ`-compact metric space is regular (in fact, an emetric space is enough). ## Implementation notes The main nontrivial statement is `measure_theory.measure.inner_regular.weakly_regular_of_finite`, expressing that in a finite measure space, if every open set can be approximated from inside by closed sets, then the measure is in fact weakly regular. To prove that we show that any measurable set can be approximated from inside by closed sets and from outside by open sets. This statement is proved by measurable induction, starting from open sets and checking that it is stable by taking complements (this is the point of this condition, being symmetrical between inside and outside) and countable disjoint unions. Once this statement is proved, one deduces results for `σ`-finite measures from this statement, by restricting them to finite measure sets (and proving that this restriction is weakly regular, using again the same statement). ## References [Halmos, Measure Theory, §52][halmos1950measure]. Note that Halmos uses an unusual definition of Borel sets (for him, they are elements of the `σ`-algebra generated by compact sets!), so his proofs or statements do not apply directly. [Billingsley, Convergence of Probability Measures][billingsley1999] -/ open set filter open_locale ennreal topological_space nnreal big_operators namespace measure_theory namespace measure /-- We say that a measure `μ` is *inner regular* with respect to predicates `p q : set α → Prop`, if for every `U` such that `q U` and `r < μ U`, there exists a subset `K ⊆ U` satisfying `p K` of measure greater than `r`. This definition is used to prove some facts about regular and weakly regular measures without repeating the proofs. -/ def inner_regular {α} {m : measurable_space α} (μ : measure α) (p q : set α → Prop) := ∀ ⦃U⦄, q U → ∀ r < μ U, ∃ K ⊆ U, p K ∧ r < μ K namespace inner_regular variables {α : Type*} {m : measurable_space α} {μ : measure α} {p q : set α → Prop} {U : set α} {ε : ℝ≥0∞} lemma measure_eq_supr (H : inner_regular μ p q) (hU : q U) : μ U = ⨆ (K ⊆ U) (hK : p K), μ K := begin refine le_antisymm (le_of_forall_lt (λ r hr, _)) (bsupr_le $ λ K hK, supr_le $ λ _, μ.mono hK), simpa only [lt_supr_iff, exists_prop] using H hU r hr end lemma exists_subset_lt_add (H : inner_regular μ p q) (h0 : p ∅) (hU : q U) (hμU : μ U ≠ ∞) (hε : ε ≠ 0) : ∃ K ⊆ U, p K ∧ μ U < μ K + ε := begin cases eq_or_ne (μ U) 0 with h₀ h₀, { refine ⟨∅, empty_subset _, h0, _⟩, rwa [measure_empty, h₀, zero_add, pos_iff_ne_zero] }, { rcases H hU _ (ennreal.sub_lt_self hμU h₀ hε) with ⟨K, hKU, hKc, hrK⟩, exact ⟨K, hKU, hKc, ennreal.lt_add_of_sub_lt (or.inl hμU) hrK⟩ } end lemma map {α β} [measurable_space α] [measurable_space β] {μ : measure α} {pa qa : set α → Prop} (H : inner_regular μ pa qa) (f : α ≃ β) (hf : measurable f) {pb qb : set β → Prop} (hAB : ∀ U, qb U → qa (f ⁻¹' U)) (hAB' : ∀ K, pa K → pb (f '' K)) (hB₁ : ∀ K, pb K → measurable_set K) (hB₂ : ∀ U, qb U → measurable_set U) : inner_regular (map f μ) pb qb := begin intros U hU r hr, rw [map_apply hf (hB₂ _ hU)] at hr, rcases H (hAB U hU) r hr with ⟨K, hKU, hKc, hK⟩, refine ⟨f '' K, image_subset_iff.2 hKU, hAB' _ hKc, _⟩, rwa [map_apply hf (hB₁ _ $ hAB' _ hKc), f.preimage_image] end lemma smul (H : inner_regular μ p q) (c : ℝ≥0∞) : inner_regular (c • μ) p q := begin intros U hU r hr, rw [smul_apply, H.measure_eq_supr hU] at hr, simpa only [ennreal.mul_supr, lt_supr_iff, exists_prop] using hr end lemma trans {q' : set α → Prop} (H : inner_regular μ p q) (H' : inner_regular μ q q') : inner_regular μ p q' := begin intros U hU r hr, rcases H' hU r hr with ⟨F, hFU, hqF, hF⟩, rcases H hqF _ hF with ⟨K, hKF, hpK, hrK⟩, exact ⟨K, hKF.trans hFU, hpK, hrK⟩ end end inner_regular variables {α β : Type*} [measurable_space α] [topological_space α] {μ : measure α} /-- A measure `μ` is outer regular if `μ(A) = inf {μ(U) | A ⊆ U open}` for a measurable set `A`. This definition implies the same equality for any (not necessarily measurable) set, see `set.measure_eq_infi_is_open`. -/ @[protect_proj] class outer_regular (μ : measure α) : Prop := (outer_regular : ∀ ⦃A : set α⦄, measurable_set A → ∀ r > μ A, ∃ U ⊇ A, is_open U ∧ μ U < r) /-- A measure `μ` is regular if - it is finite on all compact sets; - it is outer regular: `μ(A) = inf {μ(U) | A ⊆ U open}` for `A` measurable; - it is inner regular for open sets, using compact sets: `μ(U) = sup {μ(K) | K ⊆ U compact}` for `U` open. -/ @[protect_proj] class regular (μ : measure α) extends outer_regular μ : Prop := (lt_top_of_is_compact : ∀ ⦃K : set α⦄, is_compact K → μ K < ∞) (inner_regular : inner_regular μ is_compact is_open) /-- A measure `μ` is weakly regular if - it is outer regular: `μ(A) = inf { μ(U) | A ⊆ U open }` for `A` measurable; - it is inner regular for open sets, using closed sets: `μ(U) = sup {μ(F) | F ⊆ U compact}` for `U` open. -/ @[protect_proj] class weakly_regular (μ : measure α) extends outer_regular μ : Prop := (inner_regular : inner_regular μ is_closed is_open) /-- A regular measure is weakly regular. -/ @[priority 100] -- see Note [lower instance priority] instance regular.weakly_regular [t2_space α] [regular μ] : weakly_regular μ := { inner_regular := λ U hU r hr, let ⟨K, hKU, hcK, hK⟩ := regular.inner_regular hU r hr in ⟨K, hKU, hcK.is_closed, hK⟩ } namespace outer_regular instance zero : outer_regular (0 : measure α) := ⟨λ A hA r hr, ⟨univ, subset_univ A, is_open_univ, hr⟩⟩ /-- Given `r` larger than the measure of a set `A`, there exists an open superset of `A` with measure less than `r`. -/ lemma _root_.set.exists_is_open_lt_of_lt [outer_regular μ] (A : set α) (r : ℝ≥0∞) (hr : μ A < r) : ∃ U ⊇ A, is_open U ∧ μ U < r := begin rcases outer_regular.outer_regular (measurable_set_to_measurable μ A) r (by rwa measure_to_measurable) with ⟨U, hAU, hUo, hU⟩, exact ⟨U, (subset_to_measurable _ _).trans hAU, hUo, hU⟩ end /-- For an outer regular measure, the measure of a set is the infimum of the measures of open sets containing it. -/ lemma _root_.set.measure_eq_infi_is_open (A : set α) (μ : measure α) [outer_regular μ] : μ A = (⨅ (U : set α) (h : A ⊆ U) (h2 : is_open U), μ U) := begin refine le_antisymm (le_binfi $ λ s hs, le_infi $ λ h2s, μ.mono hs) _, refine le_of_forall_lt' (λ r hr, _), simpa only [infi_lt_iff, exists_prop] using A.exists_is_open_lt_of_lt r hr end lemma _root_.set.exists_is_open_lt_add [outer_regular μ] (A : set α) (hA : μ A ≠ ∞) {ε : ℝ≥0∞} (hε : ε ≠ 0) : ∃ U ⊇ A, is_open U ∧ μ U < μ A + ε := A.exists_is_open_lt_of_lt _ (ennreal.lt_add_right hA hε) lemma _root_.set.exists_is_open_le_add (A : set α) (μ : measure α) [outer_regular μ] {ε : ℝ≥0∞} (hε : ε ≠ 0) : ∃ U ⊇ A, is_open U ∧ μ U ≤ μ A + ε := begin rcases le_or_lt ∞ (μ A) with H|H, { exact ⟨univ, subset_univ _, is_open_univ, by simp only [top_le_iff.mp H, ennreal.top_add, le_top]⟩ }, { rcases A.exists_is_open_lt_add H.ne hε with ⟨U, AU, U_open, hU⟩, exact ⟨U, AU, U_open, hU.le⟩ } end lemma _root_.measurable_set.exists_is_open_diff_lt [opens_measurable_space α] [outer_regular μ] {A : set α} (hA : measurable_set A) (hA' : μ A ≠ ∞) {ε : ℝ≥0∞} (hε : ε ≠ 0) : ∃ U ⊇ A, is_open U ∧ μ U < ∞ ∧ μ (U \ A) < ε := begin rcases A.exists_is_open_lt_add hA' hε with ⟨U, hAU, hUo, hU⟩, use [U, hAU, hUo, hU.trans_le le_top], exact measure_diff_lt_of_lt_add hA hUo.measurable_set hAU hA' hU, end protected lemma map [opens_measurable_space α] [measurable_space β] [topological_space β] [borel_space β] (f : α ≃ₜ β) (μ : measure α) [outer_regular μ] : (measure.map f μ).outer_regular := begin refine ⟨λ A hA r hr, _⟩, rw [map_apply f.measurable hA, ← f.image_symm] at hr, rcases set.exists_is_open_lt_of_lt _ r hr with ⟨U, hAU, hUo, hU⟩, have : is_open (f.symm ⁻¹' U), from hUo.preimage f.symm.continuous, refine ⟨f.symm ⁻¹' U, image_subset_iff.1 hAU, this, _⟩, rwa [map_apply f.measurable this.measurable_set, f.preimage_symm, f.preimage_image], end protected lemma smul (μ : measure α) [outer_regular μ] {x : ℝ≥0∞} (hx : x ≠ ∞) : (x • μ).outer_regular := begin rcases eq_or_ne x 0 with rfl|h0, { rw zero_smul, exact outer_regular.zero }, { refine ⟨λ A hA r hr, _⟩, rw [smul_apply, A.measure_eq_infi_is_open] at hr, simpa only [ennreal.mul_infi_of_ne h0 hx, gt_iff_lt, infi_lt_iff, exists_prop] using hr } end end outer_regular /-- If a measure `μ` admits finite spanning open sets such that the restriction of `μ` to each set is outer regular, then the original measure is outer regular as well. -/ protected lemma finite_spanning_sets_in.outer_regular [opens_measurable_space α] {μ : measure α} (s : μ.finite_spanning_sets_in {U | is_open U ∧ outer_regular (μ.restrict U)}) : outer_regular μ := begin refine ⟨λ A hA r hr, _⟩, have hm : ∀ n, measurable_set (s.set n), from λ n, (s.set_mem n).1.measurable_set, haveI : ∀ n, outer_regular (μ.restrict (s.set n)) := λ n, (s.set_mem n).2, -- Note that `A = ⋃ n, A ∩ disjointed s n`. We replace `A` with this sequence. obtain ⟨A, hAm, hAs, hAd, rfl⟩ : ∃ A' : ℕ → set α, (∀ n, measurable_set (A' n)) ∧ (∀ n, A' n ⊆ s.set n) ∧ pairwise (disjoint on A') ∧ A = ⋃ n, A' n, { refine ⟨λ n, A ∩ disjointed s.set n, λ n, hA.inter (measurable_set.disjointed hm _), λ n, (inter_subset_right _ _).trans (disjointed_subset _ _), (disjoint_disjointed s.set).mono (λ k l hkl, hkl.mono inf_le_right inf_le_right), _⟩, rw [← inter_Union, Union_disjointed, s.spanning, inter_univ] }, rcases ennreal.exists_pos_sum_of_encodable' (tsub_pos_iff_lt.2 hr).ne' ℕ with ⟨δ, δ0, hδε⟩, rw [lt_tsub_iff_right, add_comm] at hδε, have : ∀ n, ∃ U ⊇ A n, is_open U ∧ μ U < μ (A n) + δ n, { intro n, have H₁ : ∀ t, μ.restrict (s.set n) t = μ (t ∩ s.set n), from λ t, restrict_apply' (hm n), have Ht : μ.restrict (s.set n) (A n) ≠ ⊤, { rw H₁, exact ((measure_mono $ inter_subset_right _ _).trans_lt (s.finite n)).ne }, rcases (A n).exists_is_open_lt_add Ht (δ0 n).ne' with ⟨U, hAU, hUo, hU⟩, rw [H₁, H₁, inter_eq_self_of_subset_left (hAs _)] at hU, exact ⟨U ∩ s.set n, subset_inter hAU (hAs _), hUo.inter (s.set_mem n).1, hU⟩ }, choose U hAU hUo hU, refine ⟨⋃ n, U n, Union_subset_Union hAU, is_open_Union hUo, _⟩, calc μ (⋃ n, U n) ≤ ∑' n, μ (U n) : measure_Union_le _ ... ≤ ∑' n, (μ (A n) + δ n) : ennreal.tsum_le_tsum (λ n, (hU n).le) ... = ∑' n, μ (A n) + ∑' n, δ n : ennreal.tsum_add ... = μ (⋃ n, A n) + ∑' n, δ n : congr_arg2 (+) (measure_Union hAd hAm).symm rfl ... < r : hδε end namespace inner_regular variables {p q : set α → Prop} {U s : set α} {ε r : ℝ≥0∞} /-- If a measure is inner regular (using closed or compact sets), then every measurable set of finite measure can by approximated by a (closed or compact) subset. -/ lemma measurable_set_of_open [opens_measurable_space α] [outer_regular μ] (H : inner_regular μ p is_open) (h0 : p ∅) (hd : ∀ ⦃s U⦄, p s → is_open U → p (s \ U)) : inner_regular μ p (λ s, measurable_set s ∧ μ s ≠ ∞) := begin rintros s ⟨hs, hμs⟩ r hr, obtain ⟨ε, hε, hεs, rfl⟩ : ∃ ε ≠ 0, ε + ε ≤ μ s ∧ r = μ s - (ε + ε), { use (μ s - r) / 2, simp [*, hr.le, ennreal.add_halves, ennreal.sub_sub_cancel, le_add_right] }, rcases hs.exists_is_open_diff_lt hμs hε with ⟨U, hsU, hUo, hUt, hμU⟩, rcases (U \ s).exists_is_open_lt_of_lt _ hμU with ⟨U', hsU', hU'o, hμU'⟩, replace hsU' := diff_subset_comm.1 hsU', rcases H.exists_subset_lt_add h0 hUo hUt.ne hε with ⟨K, hKU, hKc, hKr⟩, refine ⟨K \ U', λ x hx, hsU' ⟨hKU hx.1, hx.2⟩, hd hKc hU'o, ennreal.sub_lt_of_lt_add hεs _⟩, calc μ s ≤ μ U : μ.mono hsU ... < μ K + ε : hKr ... ≤ μ (K \ U') + μ U' + ε : add_le_add_right (tsub_le_iff_right.1 le_measure_diff) _ ... ≤ μ (K \ U') + ε + ε : by { mono*, exacts [hμU'.le, le_rfl] } ... = μ (K \ U') + (ε + ε) : add_assoc _ _ _ end open finset /-- In a finite measure space, assume that any open set can be approximated from inside by closed sets. Then the measure is weakly regular. -/ lemma weakly_regular_of_finite [borel_space α] (μ : measure α) [is_finite_measure μ] (H : inner_regular μ is_closed is_open) : weakly_regular μ := begin have hfin : ∀ {s}, μ s ≠ ⊤ := measure_ne_top μ, suffices : ∀ s, measurable_set s → ∀ ε ≠ 0, ∃ (F ⊆ s) (U ⊇ s), is_closed F ∧ is_open U ∧ μ s ≤ μ F + ε ∧ μ U ≤ μ s + ε, { refine { outer_regular := λ s hs r hr, _, inner_regular := H }, rcases exists_between hr with ⟨r', hsr', hr'r⟩, rcases this s hs _ (tsub_pos_iff_lt.2 hsr').ne' with ⟨-, -, U, hsU, -, hUo, -, H⟩, refine ⟨U, hsU, hUo, _⟩, rw [add_tsub_cancel_of_le hsr'.le] at H, exact H.trans_lt hr'r }, refine measurable_set.induction_on_open _ _ _, /- The proof is by measurable induction: we should check that the property is true for the empty set, for open sets, and is stable by taking the complement and by taking countable disjoint unions. The point of the property we are proving is that it is stable by taking complements (exchanging the roles of closed and open sets and thanks to the finiteness of the measure). -/ -- check for open set { intros U hU ε hε, rcases H.exists_subset_lt_add is_closed_empty hU hfin hε with ⟨F, hsF, hFc, hF⟩, exact ⟨F, hsF, U, subset.rfl, hFc, hU, hF.le, le_self_add⟩ }, -- check for complements { rintros s hs H ε hε, rcases H ε hε with ⟨F, hFs, U, hsU, hFc, hUo, hF, hU⟩, refine ⟨Uᶜ, compl_subset_compl.2 hsU, Fᶜ, compl_subset_compl.2 hFs, hUo.is_closed_compl, hFc.is_open_compl, _⟩, simp only [measure_compl_le_add_iff, *, hUo.measurable_set, hFc.measurable_set, true_and] }, -- check for disjoint unions { intros s hsd hsm H ε ε0, have ε0' : ε / 2 ≠ 0, from (ennreal.half_pos ε0).ne', rcases ennreal.exists_pos_sum_of_encodable' ε0' ℕ with ⟨δ, δ0, hδε⟩, choose F hFs U hsU hFc hUo hF hU using λ n, H n (δ n) (δ0 n).ne', -- the approximating closed set is constructed by considering finitely many sets `s i`, which -- cover all the measure up to `ε/2`, approximating each of these by a closed set `F i`, and -- taking the union of these (finitely many) `F i`. have : tendsto (λ t, ∑ k in t, μ (s k) + ε / 2) at_top (𝓝 $ μ (⋃ n, s n) + ε / 2), { rw measure_Union hsd hsm, exact tendsto.add ennreal.summable.has_sum tendsto_const_nhds }, rcases (this.eventually $ lt_mem_nhds $ ennreal.lt_add_right hfin ε0').exists with ⟨t, ht⟩, -- the approximating open set is constructed by taking for each `s n` an approximating open set -- `U n` with measure at most `μ (s n) + δ n` for a summable `δ`, and taking the union of these. refine ⟨⋃ k ∈ t, F k, Union_subset_Union $ λ k, Union_subset $ λ _, hFs _, ⋃ n, U n, Union_subset_Union hsU, is_closed_bUnion t.finite_to_set $ λ k _, hFc k, is_open_Union hUo, ht.le.trans _, _⟩, { calc ∑ k in t, μ (s k) + ε / 2 ≤ ∑ k in t, μ (F k) + ∑ k in t, δ k + ε / 2 : by { rw ← sum_add_distrib, exact add_le_add_right (sum_le_sum $ λ k hk, hF k) _ } ... ≤ ∑ k in t, μ (F k) + ε / 2 + ε / 2 : add_le_add_right (add_le_add_left ((ennreal.sum_le_tsum _).trans hδε.le) _) _ ... = μ (⋃ k ∈ t, F k) + ε : _, rw [measure_bUnion_finset, add_assoc, ennreal.add_halves], exacts [λ k _ n _ hkn, (hsd k n hkn).mono (hFs k) (hFs n), λ k hk, (hFc k).measurable_set] }, { calc μ (⋃ n, U n) ≤ ∑' n, μ (U n) : measure_Union_le _ ... ≤ ∑' n, (μ (s n) + δ n) : ennreal.tsum_le_tsum hU ... = μ (⋃ n, s n) + ∑' n, δ n : by rw [measure_Union hsd hsm, ennreal.tsum_add] ... ≤ μ (⋃ n, s n) + ε : add_le_add_left (hδε.le.trans ennreal.half_le_self) _ } } end /-- In a metric space (or even a pseudo emetric space), an open set can be approximated from inside by closed sets. -/ lemma of_pseudo_emetric_space {X : Type*} [pseudo_emetric_space X] [measurable_space X] [opens_measurable_space X] (μ : measure X) : inner_regular μ is_closed is_open := begin intros U hU r hr, rcases hU.exists_Union_is_closed with ⟨F, F_closed, -, rfl, F_mono⟩, rw measure_Union_eq_supr (λ n, (F_closed n).measurable_set) F_mono.directed_le at hr, rcases lt_supr_iff.1 hr with ⟨n, hn⟩, exact ⟨F n, subset_Union _ _, F_closed n, hn⟩ end /-- In a `σ`-compact space, any closed set can be approximated by a compact subset. -/ lemma is_compact_is_closed {X : Type*} [topological_space X] [t2_space X] [sigma_compact_space X] [measurable_space X] [opens_measurable_space X] (μ : measure X) : inner_regular μ is_compact is_closed := begin intros F hF r hr, set B : ℕ → set X := compact_covering X, have hBc : ∀ n, is_compact (F ∩ B n), from λ n, (is_compact_compact_covering X n).inter_left hF, have hBU : (⋃ n, F ∩ B n) = F, by rw [← inter_Union, Union_compact_covering, set.inter_univ], have : μ F = ⨆ n, μ (F ∩ B n), { rw [← measure_Union_eq_supr, hBU], exacts [λ n, (hBc n).measurable_set, monotone.directed_le $ λ m n h, inter_subset_inter_right _ (compact_covering_subset _ h)] }, rw this at hr, rcases lt_supr_iff.1 hr with ⟨n, hn⟩, exact ⟨_, inter_subset_left _ _, hBc n, hn⟩ end end inner_regular namespace regular instance zero : regular (0 : measure α) := ⟨λ K hK, ennreal.coe_lt_top, λ U hU r hr, ⟨∅, empty_subset _, is_compact_empty, hr⟩⟩ /-- If `μ` is a regular measure, then any open set can be approximated by a compact subset. -/ lemma _root_.is_open.exists_lt_is_compact [regular μ] ⦃U : set α⦄ (hU : is_open U) {r : ℝ≥0∞} (hr : r < μ U) : ∃ K ⊆ U, is_compact K ∧ r < μ K := regular.inner_regular hU r hr /-- The measure of an open set is the supremum of the measures of compact sets it contains. -/ lemma _root_.is_open.measure_eq_supr_is_compact ⦃U : set α⦄ (hU : is_open U) (μ : measure α) [regular μ] : μ U = (⨆ (K : set α) (h : K ⊆ U) (h2 : is_compact K), μ K) := regular.inner_regular.measure_eq_supr hU lemma exists_compact_not_null [regular μ] : (∃ K, is_compact K ∧ μ K ≠ 0) ↔ μ ≠ 0 := by simp_rw [ne.def, ← measure_univ_eq_zero, is_open_univ.measure_eq_supr_is_compact, ennreal.supr_eq_zero, not_forall, exists_prop, subset_univ, true_and] /-- If `μ` is a regular measure, then any measurable set of finite measure can be approximated by a compact subset. See also `measurable_set.exists_is_compact_lt_add` and `measurable_set.exists_lt_is_compact_of_ne_top`. -/ lemma inner_regular_measurable [opens_measurable_space α] [regular μ] : inner_regular μ is_compact (λ s, measurable_set s ∧ μ s ≠ ∞) := regular.inner_regular.measurable_set_of_open is_compact_empty (λ _ _, is_compact.diff) /-- If `μ` is a regular measure, then any measurable set of finite measure can be approximated by a compact subset. See also `measurable_set.exists_lt_is_compact_of_ne_top`. -/ lemma _root_.measurable_set.exists_is_compact_lt_add [opens_measurable_space α] [regular μ] ⦃A : set α⦄ (hA : measurable_set A) (h'A : μ A ≠ ∞) {ε : ℝ≥0∞} (hε : ε ≠ 0) : ∃ K ⊆ A, is_compact K ∧ μ A < μ K + ε := regular.inner_regular_measurable.exists_subset_lt_add is_compact_empty ⟨hA, h'A⟩ h'A hε /-- If `μ` is a regular measure, then any measurable set of finite measure can be approximated by a compact subset. See also `measurable_set.exists_is_compact_lt_add` and `measurable_set.exists_lt_is_compact_of_ne_top`. -/ lemma _root_.measurable_set.exists_is_compact_diff_lt [opens_measurable_space α] [t2_space α] [regular μ] ⦃A : set α⦄ (hA : measurable_set A) (h'A : μ A ≠ ∞) {ε : ℝ≥0∞} (hε : ε ≠ 0) : ∃ K ⊆ A, is_compact K ∧ μ (A \ K) < ε := begin rcases hA.exists_is_compact_lt_add h'A hε with ⟨K, hKA, hKc, hK⟩, exact ⟨K, hKA, hKc, measure_diff_lt_of_lt_add hKc.measurable_set hA hKA (ne_top_of_le_ne_top h'A $ measure_mono hKA) hK⟩ end /-- If `μ` is a regular measure, then any measurable set of finite measure can be approximated by a compact subset. See also `measurable_set.exists_is_compact_lt_add`. -/ lemma _root_.measurable_set.exists_lt_is_compact_of_ne_top [regular μ] [opens_measurable_space α] ⦃A : set α⦄ (hA : measurable_set A) (h'A : μ A ≠ ∞) {r : ℝ≥0∞} (hr : r < μ A) : ∃ K ⊆ A, is_compact K ∧ r < μ K := regular.inner_regular_measurable ⟨hA, h'A⟩ _ hr /-- Given a regular measure, any measurable set of finite mass can be approximated from inside by compact sets. -/ lemma _root_.measurable_set.measure_eq_supr_is_compact_of_ne_top [opens_measurable_space α] [regular μ] ⦃A : set α⦄ (hA : measurable_set A) (h'A : μ A ≠ ∞) : μ A = (⨆ (K ⊆ A) (h : is_compact K), μ K) := regular.inner_regular_measurable.measure_eq_supr ⟨hA, h'A⟩ protected lemma map [opens_measurable_space α] [measurable_space β] [topological_space β] [t2_space β] [borel_space β] [regular μ] (f : α ≃ₜ β) : (measure.map f μ).regular := begin haveI := outer_regular.map f μ, split, { intros K hK, rw [map_apply f.measurable hK.measurable_set], apply regular.lt_top_of_is_compact, rwa f.compact_preimage }, { exact regular.inner_regular.map f.to_equiv f.measurable (λ U hU, hU.preimage f.continuous) (λ K hK, hK.image f.continuous) (λ K hK, hK.measurable_set) (λ U hU, hU.measurable_set) } end protected lemma smul [regular μ] {x : ℝ≥0∞} (hx : x ≠ ∞) : (x • μ).regular := begin haveI := outer_regular.smul μ hx, exact ⟨λ K hK, ennreal.mul_lt_top hx (regular.lt_top_of_is_compact hK).ne, regular.inner_regular.smul x⟩ end /-- A regular measure in a σ-compact space is σ-finite. -/ @[priority 100] -- see Note [lower instance priority] instance sigma_finite [sigma_compact_space α] [regular μ] : sigma_finite μ := ⟨⟨{ set := compact_covering α, set_mem := λ n, trivial, finite := λ n, regular.lt_top_of_is_compact $ is_compact_compact_covering α n, spanning := Union_compact_covering α }⟩⟩ end regular namespace weakly_regular /-- If `μ` is a weakly regular measure, then any open set can be approximated by a closed subset. -/ lemma _root_.is_open.exists_lt_is_closed [weakly_regular μ] ⦃U : set α⦄ (hU : is_open U) {r : ℝ≥0∞} (hr : r < μ U) : ∃ F ⊆ U, is_closed F ∧ r < μ F := weakly_regular.inner_regular hU r hr /-- If `μ` is a weakly regular measure, then any open set can be approximated by a closed subset. -/ lemma _root_.is_open.measure_eq_supr_is_closed ⦃U : set α⦄ (hU : is_open U) (μ : measure α) [weakly_regular μ] : μ U = (⨆ (F ⊆ U) (h : is_closed F), μ F) := weakly_regular.inner_regular.measure_eq_supr hU lemma inner_regular_measurable [opens_measurable_space α] [weakly_regular μ] : inner_regular μ is_closed (λ s, measurable_set s ∧ μ s ≠ ∞) := weakly_regular.inner_regular.measurable_set_of_open is_closed_empty (λ _ _ h₁ h₂, h₁.inter h₂.is_closed_compl) /-- If `s` is a measurable set, a weakly regular measure `μ` is finite on `s`, and `ε` is a positive number, then there exist a closed set `K ⊆ s` such that `μ s < μ K + ε`. -/ lemma _root_.measurable_set.exists_is_closed_lt_add [weakly_regular μ] [opens_measurable_space α] {s : set α} (hs : measurable_set s) (hμs : μ s ≠ ∞) {ε : ℝ≥0∞} (hε : ε ≠ 0) : ∃ K ⊆ s, is_closed K ∧ μ s < μ K + ε := inner_regular_measurable.exists_subset_lt_add is_closed_empty ⟨hs, hμs⟩ hμs hε lemma _root_.measurable_set.exists_is_closed_diff_lt [opens_measurable_space α] [weakly_regular μ] ⦃A : set α⦄ (hA : measurable_set A) (h'A : μ A ≠ ∞) {ε : ℝ≥0∞} (hε : ε ≠ 0) : ∃ F ⊆ A, is_closed F ∧ μ (A \ F) < ε := begin rcases hA.exists_is_closed_lt_add h'A hε with ⟨F, hFA, hFc, hF⟩, exact ⟨F, hFA, hFc, measure_diff_lt_of_lt_add hFc.measurable_set hA hFA (ne_top_of_le_ne_top h'A $ measure_mono hFA) hF⟩ end /-- Given a weakly regular measure, any measurable set of finite mass can be approximated from inside by closed sets. -/ lemma _root_.measurable_set.exists_lt_is_closed_of_ne_top [weakly_regular μ] [opens_measurable_space α] ⦃A : set α⦄ (hA : measurable_set A) (h'A : μ A ≠ ∞) {r : ℝ≥0∞} (hr : r < μ A) : ∃ K ⊆ A, is_closed K ∧ r < μ K := inner_regular_measurable ⟨hA, h'A⟩ _ hr /-- Given a weakly regular measure, any measurable set of finite mass can be approximated from inside by closed sets. -/ lemma _root_.measurable_set.measure_eq_supr_is_closed_of_ne_top [opens_measurable_space α] [weakly_regular μ] ⦃A : set α⦄ (hA : measurable_set A) (h'A : μ A ≠ ∞) : μ A = (⨆ (K ⊆ A) (h : is_closed K), μ K) := inner_regular_measurable.measure_eq_supr ⟨hA, h'A⟩ /-- The restriction of a weakly regular measure to a measurable set of finite measure is weakly regular. -/ lemma restrict_of_measurable_set [borel_space α] [weakly_regular μ] (A : set α) (hA : measurable_set A) (h'A : μ A ≠ ∞) : weakly_regular (μ.restrict A) := begin haveI : fact (μ A < ∞) := ⟨h'A.lt_top⟩, refine inner_regular.weakly_regular_of_finite _ (λ V V_open, _), simp only [restrict_apply' hA], intros r hr, have : μ (V ∩ A) ≠ ∞, from ne_top_of_le_ne_top h'A (measure_mono $ inter_subset_right _ _), rcases (V_open.measurable_set.inter hA).exists_lt_is_closed_of_ne_top this hr with ⟨F, hFVA, hFc, hF⟩, refine ⟨F, hFVA.trans (inter_subset_left _ _), hFc, _⟩, rwa inter_eq_self_of_subset_left (hFVA.trans $ inter_subset_right _ _) end /-- Any finite measure on a metric space (or even a pseudo emetric space) is weakly regular. -/ @[priority 100] -- see Note [lower instance priority] instance of_pseudo_emetric_space_of_is_finite_measure {X : Type*} [pseudo_emetric_space X] [measurable_space X] [borel_space X] (μ : measure X) [is_finite_measure μ] : weakly_regular μ := (inner_regular.of_pseudo_emetric_space μ).weakly_regular_of_finite μ /-- Any locally finite measure on a `σ`-compact metric space (or even a pseudo emetric space) is weakly regular. -/ @[priority 100] -- see Note [lower instance priority] instance of_pseudo_emetric_sigma_compact_space_of_locally_finite {X : Type*} [pseudo_emetric_space X] [sigma_compact_space X] [measurable_space X] [borel_space X] (μ : measure X) [is_locally_finite_measure μ] : weakly_regular μ := begin haveI : outer_regular μ, { refine (μ.finite_spanning_sets_in_open.mono' $ λ U hU, _).outer_regular, haveI : fact (μ U < ∞), from ⟨hU.2⟩, exact ⟨hU.1, infer_instance⟩ }, exact ⟨inner_regular.of_pseudo_emetric_space μ⟩ end end weakly_regular /-- Any locally finite measure on a `σ`-compact (e)metric space is regular. -/ @[priority 100] -- see Note [lower instance priority] instance regular.of_sigma_compact_space_of_is_locally_finite_measure {X : Type*} [emetric_space X] [sigma_compact_space X] [measurable_space X] [borel_space X] (μ : measure X) [is_locally_finite_measure μ] : regular μ := { lt_top_of_is_compact := λ K hK, hK.measure_lt_top, inner_regular := (inner_regular.is_compact_is_closed μ).trans (inner_regular.of_pseudo_emetric_space μ) } end measure end measure_theory
f8174289c198bb7a18968af141f07107dc5304eb
94e33a31faa76775069b071adea97e86e218a8ee
/src/linear_algebra/linear_pmap.lean
bee9db2f11e97bbd8ae2365022362e527b370b6a
[ "Apache-2.0" ]
permissive
urkud/mathlib
eab80095e1b9f1513bfb7f25b4fa82fa4fd02989
6379d39e6b5b279df9715f8011369a301b634e41
refs/heads/master
1,658,425,342,662
1,658,078,703,000
1,658,078,703,000
186,910,338
0
0
Apache-2.0
1,568,512,083,000
1,557,958,709,000
Lean
UTF-8
Lean
false
false
23,071
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 linear_algebra.basic import linear_algebra.prod /-! # Partially defined linear maps A `linear_pmap R E F` is a linear map from a submodule of `E` to `F`. We define a `semilattice_inf` with `order_bot` instance on this this, and define three operations: * `mk_span_singleton` defines a partial linear map defined on the span of a singleton. * `sup` takes two partial linear maps `f`, `g` that agree on the intersection of their domains, and returns the unique partial linear map on `f.domain ⊔ g.domain` that extends both `f` and `g`. * `Sup` takes a `directed_on (≤)` set of partial linear maps, and returns the unique partial linear map on the `Sup` of their domains that extends all these maps. Partially defined maps are currently used in `mathlib` to prove Hahn-Banach theorem and its variations. Namely, `linear_pmap.Sup` implies that every chain of `linear_pmap`s is bounded above. Another possible use (not yet in `mathlib`) would be the theory of unbounded linear operators. -/ open set universes u v w /-- A `linear_pmap R E F` is a linear map from a submodule of `E` to `F`. -/ structure linear_pmap (R : Type u) [ring R] (E : Type v) [add_comm_group E] [module R E] (F : Type w) [add_comm_group F] [module R F] := (domain : submodule R E) (to_fun : domain →ₗ[R] F) variables {R : Type*} [ring R] {E : Type*} [add_comm_group E] [module R E] {F : Type*} [add_comm_group F] [module R F] {G : Type*} [add_comm_group G] [module R G] namespace linear_pmap open submodule instance : has_coe_to_fun (linear_pmap R E F) (λ f : linear_pmap R E F, f.domain → F) := ⟨λ f, f.to_fun⟩ @[simp] lemma to_fun_eq_coe (f : linear_pmap R E F) (x : f.domain) : f.to_fun x = f x := rfl @[ext] lemma ext {f g : linear_pmap R E F} (h : f.domain = g.domain) (h' : ∀ ⦃x : f.domain⦄ ⦃y : g.domain⦄ (h : (x:E) = y), f x = g y) : f = g := begin rcases f with ⟨f_dom, f⟩, rcases g with ⟨g_dom, g⟩, obtain rfl : f_dom = g_dom := h, obtain rfl : f = g := linear_map.ext (λ x, h' rfl), refl, end @[simp] lemma map_zero (f : linear_pmap R E F) : f 0 = 0 := f.to_fun.map_zero lemma map_add (f : linear_pmap R E F) (x y : f.domain) : f (x + y) = f x + f y := f.to_fun.map_add x y lemma map_neg (f : linear_pmap R E F) (x : f.domain) : f (-x) = -f x := f.to_fun.map_neg x lemma map_sub (f : linear_pmap R E F) (x y : f.domain) : f (x - y) = f x - f y := f.to_fun.map_sub x y lemma map_smul (f : linear_pmap R E F) (c : R) (x : f.domain) : f (c • x) = c • f x := f.to_fun.map_smul c x @[simp] lemma mk_apply (p : submodule R E) (f : p →ₗ[R] F) (x : p) : mk p f x = f x := rfl /-- The unique `linear_pmap` on `R ∙ x` that sends `x` to `y`. This version works for modules over rings, and requires a proof of `∀ c, c • x = 0 → c • y = 0`. -/ noncomputable def mk_span_singleton' (x : E) (y : F) (H : ∀ c : R, c • x = 0 → c • y = 0) : linear_pmap R E F := { domain := R ∙ x, to_fun := have H : ∀ c₁ c₂ : R, c₁ • x = c₂ • x → c₁ • y = c₂ • y, { intros c₁ c₂ h, rw [← sub_eq_zero, ← sub_smul] at h ⊢, exact H _ h }, { to_fun := λ z, (classical.some (mem_span_singleton.1 z.prop) • y), map_add' := λ y z, begin rw [← add_smul], apply H, simp only [add_smul, sub_smul, classical.some_spec (mem_span_singleton.1 _)], apply coe_add end, map_smul' := λ c z, begin rw [smul_smul], apply H, simp only [mul_smul, classical.some_spec (mem_span_singleton.1 _)], apply coe_smul end } } @[simp] lemma domain_mk_span_singleton (x : E) (y : F) (H : ∀ c : R, c • x = 0 → c • y = 0) : (mk_span_singleton' x y H).domain = R ∙ x := rfl @[simp] lemma mk_span_singleton'_apply (x : E) (y : F) (H : ∀ c : R, c • x = 0 → c • y = 0) (c : R) (h) : mk_span_singleton' x y H ⟨c • x, h⟩ = c • y := begin dsimp [mk_span_singleton'], rw [← sub_eq_zero, ← sub_smul], apply H, simp only [sub_smul, one_smul, sub_eq_zero], apply classical.some_spec (mem_span_singleton.1 h), end @[simp] lemma mk_span_singleton'_apply_self (x : E) (y : F) (H : ∀ c : R, c • x = 0 → c • y = 0) (h) : mk_span_singleton' x y H ⟨x, h⟩ = y := by convert mk_span_singleton'_apply x y H 1 _; rwa one_smul /-- The unique `linear_pmap` on `span R {x}` that sends a non-zero vector `x` to `y`. This version works for modules over division rings. -/ @[reducible] noncomputable def mk_span_singleton {K E F : Type*} [division_ring K] [add_comm_group E] [module K E] [add_comm_group F] [module K F] (x : E) (y : F) (hx : x ≠ 0) : linear_pmap K E F := mk_span_singleton' x y $ λ c hc, (smul_eq_zero.1 hc).elim (λ hc, by rw [hc, zero_smul]) (λ hx', absurd hx' hx) lemma mk_span_singleton_apply (K : Type*) {E F : Type*} [division_ring K] [add_comm_group E] [module K E] [add_comm_group F] [module K F] {x : E} (hx : x ≠ 0) (y : F) : mk_span_singleton x y hx ⟨x, (submodule.mem_span_singleton_self x : x ∈ submodule.span K {x})⟩ = y := linear_pmap.mk_span_singleton'_apply_self _ _ _ _ /-- Projection to the first coordinate as a `linear_pmap` -/ protected def fst (p : submodule R E) (p' : submodule R F) : linear_pmap R (E × F) E := { domain := p.prod p', to_fun := (linear_map.fst R E F).comp (p.prod p').subtype } @[simp] lemma fst_apply (p : submodule R E) (p' : submodule R F) (x : p.prod p') : linear_pmap.fst p p' x = (x : E × F).1 := rfl /-- Projection to the second coordinate as a `linear_pmap` -/ protected def snd (p : submodule R E) (p' : submodule R F) : linear_pmap R (E × F) F := { domain := p.prod p', to_fun := (linear_map.snd R E F).comp (p.prod p').subtype } @[simp] lemma snd_apply (p : submodule R E) (p' : submodule R F) (x : p.prod p') : linear_pmap.snd p p' x = (x : E × F).2 := rfl instance : has_neg (linear_pmap R E F) := ⟨λ f, ⟨f.domain, -f.to_fun⟩⟩ @[simp] lemma neg_apply (f : linear_pmap R E F) (x) : (-f) x = -(f x) := rfl instance : has_le (linear_pmap R E F) := ⟨λ f g, f.domain ≤ g.domain ∧ ∀ ⦃x : f.domain⦄ ⦃y : g.domain⦄ (h : (x:E) = y), f x = g y⟩ lemma eq_of_le_of_domain_eq {f g : linear_pmap R E F} (hle : f ≤ g) (heq : f.domain = g.domain) : f = g := ext heq hle.2 /-- Given two partial linear maps `f`, `g`, the set of points `x` such that both `f` and `g` are defined at `x` and `f x = g x` form a submodule. -/ def eq_locus (f g : linear_pmap R E F) : submodule R E := { carrier := {x | ∃ (hf : x ∈ f.domain) (hg : x ∈ g.domain), f ⟨x, hf⟩ = g ⟨x, hg⟩}, zero_mem' := ⟨zero_mem _, zero_mem _, f.map_zero.trans g.map_zero.symm⟩, add_mem' := λ x y ⟨hfx, hgx, hx⟩ ⟨hfy, hgy, hy⟩, ⟨add_mem hfx hfy, add_mem hgx hgy, by erw [f.map_add ⟨x, hfx⟩ ⟨y, hfy⟩, g.map_add ⟨x, hgx⟩ ⟨y, hgy⟩, hx, hy]⟩, smul_mem' := λ c x ⟨hfx, hgx, hx⟩, ⟨smul_mem _ c hfx, smul_mem _ c hgx, by erw [f.map_smul c ⟨x, hfx⟩, g.map_smul c ⟨x, hgx⟩, hx]⟩ } instance : has_inf (linear_pmap R E F) := ⟨λ f g, ⟨f.eq_locus g, f.to_fun.comp $ of_le $ λ x hx, hx.fst⟩⟩ instance : has_bot (linear_pmap R E F) := ⟨⟨⊥, 0⟩⟩ instance : inhabited (linear_pmap R E F) := ⟨⊥⟩ instance : semilattice_inf (linear_pmap R E F) := { le := (≤), le_refl := λ f, ⟨le_refl f.domain, λ x y h, subtype.eq h ▸ rfl⟩, le_trans := λ f g h ⟨fg_le, fg_eq⟩ ⟨gh_le, gh_eq⟩, ⟨le_trans fg_le gh_le, λ x z hxz, have hxy : (x:E) = of_le fg_le x, from rfl, (fg_eq hxy).trans (gh_eq $ hxy.symm.trans hxz)⟩, le_antisymm := λ f g fg gf, eq_of_le_of_domain_eq fg (le_antisymm fg.1 gf.1), inf := (⊓), le_inf := λ f g h ⟨fg_le, fg_eq⟩ ⟨fh_le, fh_eq⟩, ⟨λ x hx, ⟨fg_le hx, fh_le hx, by refine (fg_eq _).symm.trans (fh_eq _); [exact ⟨x, hx⟩, refl, refl]⟩, λ x ⟨y, yg, hy⟩ h, by { apply fg_eq, exact h }⟩, inf_le_left := λ f g, ⟨λ x hx, hx.fst, λ x y h, congr_arg f $ subtype.eq $ by exact h⟩, inf_le_right := λ f g, ⟨λ x hx, hx.snd.fst, λ ⟨x, xf, xg, hx⟩ y h, hx.trans $ congr_arg g $ subtype.eq $ by exact h⟩ } instance : order_bot (linear_pmap R E F) := { bot := ⊥, bot_le := λ f, ⟨bot_le, λ x y h, have hx : x = 0, from subtype.eq ((mem_bot R).1 x.2), have hy : y = 0, from subtype.eq (h.symm.trans (congr_arg _ hx)), by rw [hx, hy, map_zero, map_zero]⟩ } lemma le_of_eq_locus_ge {f g : linear_pmap R E F} (H : f.domain ≤ f.eq_locus g) : f ≤ g := suffices f ≤ f ⊓ g, from le_trans this inf_le_right, ⟨H, λ x y hxy, ((inf_le_left : f ⊓ g ≤ f).2 hxy.symm).symm⟩ lemma domain_mono : strict_mono (@domain R _ E _ _ F _ _) := λ f g hlt, lt_of_le_of_ne hlt.1.1 $ λ heq, ne_of_lt hlt $ eq_of_le_of_domain_eq (le_of_lt hlt) heq private lemma sup_aux (f g : linear_pmap R E F) (h : ∀ (x : f.domain) (y : g.domain), (x:E) = y → f x = g y) : ∃ fg : ↥(f.domain ⊔ g.domain) →ₗ[R] F, ∀ (x : f.domain) (y : g.domain) (z), (x:E) + y = ↑z → fg z = f x + g y := begin choose x hx y hy hxy using λ z : f.domain ⊔ g.domain, mem_sup.1 z.prop, set fg := λ z, f ⟨x z, hx z⟩ + g ⟨y z, hy z⟩, have fg_eq : ∀ (x' : f.domain) (y' : g.domain) (z' : f.domain ⊔ g.domain) (H : (x':E) + y' = z'), fg z' = f x' + g y', { intros x' y' z' H, dsimp [fg], rw [add_comm, ← sub_eq_sub_iff_add_eq_add, eq_comm, ← map_sub, ← map_sub], apply h, simp only [← eq_sub_iff_add_eq] at hxy, simp only [add_subgroup_class.coe_sub, coe_mk, coe_mk, hxy, ← sub_add, ← sub_sub, sub_self, zero_sub, ← H], apply neg_add_eq_sub }, refine ⟨{ to_fun := fg, .. }, fg_eq⟩, { rintros ⟨z₁, hz₁⟩ ⟨z₂, hz₂⟩, rw [← add_assoc, add_right_comm (f _), ← map_add, add_assoc, ← map_add], apply fg_eq, simp only [coe_add, coe_mk, ← add_assoc], rw [add_right_comm (x _), hxy, add_assoc, hxy, coe_mk, coe_mk] }, { intros c z, rw [smul_add, ← map_smul, ← map_smul], apply fg_eq, simp only [coe_smul, coe_mk, ← smul_add, hxy, ring_hom.id_apply] }, end /-- Given two partial linear maps that agree on the intersection of their domains, `f.sup g h` is the unique partial linear map on `f.domain ⊔ g.domain` that agrees with `f` and `g`. -/ protected noncomputable def sup (f g : linear_pmap R E F) (h : ∀ (x : f.domain) (y : g.domain), (x:E) = y → f x = g y) : linear_pmap R E F := ⟨_, classical.some (sup_aux f g h)⟩ @[simp] lemma domain_sup (f g : linear_pmap R E F) (h : ∀ (x : f.domain) (y : g.domain), (x:E) = y → f x = g y) : (f.sup g h).domain = f.domain ⊔ g.domain := rfl lemma sup_apply {f g : linear_pmap R E F} (H : ∀ (x : f.domain) (y : g.domain), (x:E) = y → f x = g y) (x y z) (hz : (↑x:E) + ↑y = ↑z) : f.sup g H z = f x + g y := classical.some_spec (sup_aux f g H) x y z hz protected lemma left_le_sup (f g : linear_pmap R E F) (h : ∀ (x : f.domain) (y : g.domain), (x:E) = y → f x = g y) : f ≤ f.sup g h := begin refine ⟨le_sup_left, λ z₁ z₂ hz, _⟩, rw [← add_zero (f _), ← g.map_zero], refine (sup_apply h _ _ _ _).symm, simpa end protected lemma right_le_sup (f g : linear_pmap R E F) (h : ∀ (x : f.domain) (y : g.domain), (x:E) = y → f x = g y) : g ≤ f.sup g h := begin refine ⟨le_sup_right, λ z₁ z₂ hz, _⟩, rw [← zero_add (g _), ← f.map_zero], refine (sup_apply h _ _ _ _).symm, simpa end protected lemma sup_le {f g h : linear_pmap R E F} (H : ∀ (x : f.domain) (y : g.domain), (x:E) = y → f x = g y) (fh : f ≤ h) (gh : g ≤ h) : f.sup g H ≤ h := have Hf : f ≤ (f.sup g H) ⊓ h, from le_inf (f.left_le_sup g H) fh, have Hg : g ≤ (f.sup g H) ⊓ h, from le_inf (f.right_le_sup g H) gh, le_of_eq_locus_ge $ sup_le Hf.1 Hg.1 /-- Hypothesis for `linear_pmap.sup` holds, if `f.domain` is disjoint with `g.domain`. -/ lemma sup_h_of_disjoint (f g : linear_pmap R E F) (h : disjoint f.domain g.domain) (x : f.domain) (y : g.domain) (hxy : (x:E) = y) : f x = g y := begin rw [disjoint_def] at h, have hy : y = 0, from subtype.eq (h y (hxy ▸ x.2) y.2), have hx : x = 0, from subtype.eq (hxy.trans $ congr_arg _ hy), simp [*] end section smul variables {M N : Type*} [monoid M] [distrib_mul_action M F] [smul_comm_class R M F] variables [monoid N] [distrib_mul_action N F] [smul_comm_class R N F] instance : has_smul M (linear_pmap R E F) := ⟨λ a f, { domain := f.domain, to_fun := a • f.to_fun }⟩ lemma smul_apply (a : M) (f : linear_pmap R E F) (x : ((a • f).domain)) : (a • f) x = a • f x := rfl @[simp] lemma coe_smul (a : M) (f : linear_pmap R E F) : ⇑(a • f) = a • f := rfl instance [smul_comm_class M N F] : smul_comm_class M N (linear_pmap R E F) := ⟨λ a b f, ext rfl $ λ x y hxy, by simp_rw [smul_apply, subtype.eq hxy, smul_comm]⟩ instance [has_smul M N] [is_scalar_tower M N F] : is_scalar_tower M N (linear_pmap R E F) := ⟨λ a b f, ext rfl $ λ x y hxy, by simp_rw [smul_apply, subtype.eq hxy, smul_assoc]⟩ end smul section variables {K : Type*} [division_ring K] [module K E] [module K F] /-- Extend a `linear_pmap` to `f.domain ⊔ K ∙ x`. -/ noncomputable def sup_span_singleton (f : linear_pmap K E F) (x : E) (y : F) (hx : x ∉ f.domain) : linear_pmap K E F := f.sup (mk_span_singleton x y (λ h₀, hx $ h₀.symm ▸ f.domain.zero_mem)) $ sup_h_of_disjoint _ _ $ by simpa [disjoint_span_singleton] @[simp] lemma domain_sup_span_singleton (f : linear_pmap K E F) (x : E) (y : F) (hx : x ∉ f.domain) : (f.sup_span_singleton x y hx).domain = f.domain ⊔ K ∙ x := rfl @[simp] lemma sup_span_singleton_apply_mk (f : linear_pmap K E F) (x : E) (y : F) (hx : x ∉ f.domain) (x' : E) (hx' : x' ∈ f.domain) (c : K) : f.sup_span_singleton x y hx ⟨x' + c • x, mem_sup.2 ⟨x', hx', _, mem_span_singleton.2 ⟨c, rfl⟩, rfl⟩⟩ = f ⟨x', hx'⟩ + c • y := begin erw [sup_apply _ ⟨x', hx'⟩ ⟨c • x, _⟩, mk_span_singleton'_apply], refl, exact mem_span_singleton.2 ⟨c, rfl⟩ end end private lemma Sup_aux (c : set (linear_pmap R E F)) (hc : directed_on (≤) c) : ∃ f : ↥(Sup (domain '' c)) →ₗ[R] F, (⟨_, f⟩ : linear_pmap R E F) ∈ upper_bounds c := begin cases c.eq_empty_or_nonempty with ceq cne, { subst c, simp }, have hdir : directed_on (≤) (domain '' c), from directed_on_image.2 (hc.mono domain_mono.monotone), have P : Π x : Sup (domain '' c), {p : c // (x : E) ∈ p.val.domain }, { rintros x, apply classical.indefinite_description, have := (mem_Sup_of_directed (cne.image _) hdir).1 x.2, rwa [bex_image_iff, set_coe.exists'] at this }, set f : Sup (domain '' c) → F := λ x, (P x).val.val ⟨x, (P x).property⟩, have f_eq : ∀ (p : c) (x : Sup (domain '' c)) (y : p.1.1) (hxy : (x : E) = y), f x = p.1 y, { intros p x y hxy, rcases hc (P x).1.1 (P x).1.2 p.1 p.2 with ⟨q, hqc, hxq, hpq⟩, refine (hxq.2 _).trans (hpq.2 _).symm, exacts [of_le hpq.1 y, hxy, rfl] }, refine ⟨{ to_fun := f, .. }, _⟩, { intros x y, rcases hc (P x).1.1 (P x).1.2 (P y).1.1 (P y).1.2 with ⟨p, hpc, hpx, hpy⟩, set x' := of_le hpx.1 ⟨x, (P x).2⟩, set y' := of_le hpy.1 ⟨y, (P y).2⟩, rw [f_eq ⟨p, hpc⟩ x x' rfl, f_eq ⟨p, hpc⟩ y y' rfl, f_eq ⟨p, hpc⟩ (x + y) (x' + y') rfl, map_add] }, { intros c x, simp [f_eq (P x).1 (c • x) (c • ⟨x, (P x).2⟩) rfl, ← map_smul] }, { intros p hpc, refine ⟨le_Sup $ mem_image_of_mem domain hpc, λ x y hxy, eq.symm _⟩, exact f_eq ⟨p, hpc⟩ _ _ hxy.symm } end /-- Glue a collection of partially defined linear maps to a linear map defined on `Sup` of these submodules. -/ protected noncomputable def Sup (c : set (linear_pmap R E F)) (hc : directed_on (≤) c) : linear_pmap R E F := ⟨_, classical.some $ Sup_aux c hc⟩ protected lemma le_Sup {c : set (linear_pmap R E F)} (hc : directed_on (≤) c) {f : linear_pmap R E F} (hf : f ∈ c) : f ≤ linear_pmap.Sup c hc := classical.some_spec (Sup_aux c hc) hf protected lemma Sup_le {c : set (linear_pmap R E F)} (hc : directed_on (≤) c) {g : linear_pmap R E F} (hg : ∀ f ∈ c, f ≤ g) : linear_pmap.Sup c hc ≤ g := le_of_eq_locus_ge $ Sup_le $ λ _ ⟨f, hf, eq⟩, eq ▸ have f ≤ (linear_pmap.Sup c hc) ⊓ g, from le_inf (linear_pmap.le_Sup _ hf) (hg f hf), this.1 end linear_pmap namespace linear_map /-- Restrict a linear map to a submodule, reinterpreting the result as a `linear_pmap`. -/ def to_pmap (f : E →ₗ[R] F) (p : submodule R E) : linear_pmap R E F := ⟨p, f.comp p.subtype⟩ @[simp] lemma to_pmap_apply (f : E →ₗ[R] F) (p : submodule R E) (x : p) : f.to_pmap p x = f x := rfl /-- Compose a linear map with a `linear_pmap` -/ def comp_pmap (g : F →ₗ[R] G) (f : linear_pmap R E F) : linear_pmap R E G := { domain := f.domain, to_fun := g.comp f.to_fun } @[simp] lemma comp_pmap_apply (g : F →ₗ[R] G) (f : linear_pmap R E F) (x) : g.comp_pmap f x = g (f x) := rfl end linear_map namespace linear_pmap /-- Restrict codomain of a `linear_pmap` -/ def cod_restrict (f : linear_pmap R E F) (p : submodule R F) (H : ∀ x, f x ∈ p) : linear_pmap R E p := { domain := f.domain, to_fun := f.to_fun.cod_restrict p H } /-- Compose two `linear_pmap`s -/ def comp (g : linear_pmap R F G) (f : linear_pmap R E F) (H : ∀ x : f.domain, f x ∈ g.domain) : linear_pmap R E G := g.to_fun.comp_pmap $ f.cod_restrict _ H /-- `f.coprod g` is the partially defined linear map defined on `f.domain × g.domain`, and sending `p` to `f p.1 + g p.2`. -/ def coprod (f : linear_pmap R E G) (g : linear_pmap R F G) : linear_pmap R (E × F) G := { domain := f.domain.prod g.domain, to_fun := (f.comp (linear_pmap.fst f.domain g.domain) (λ x, x.2.1)).to_fun + (g.comp (linear_pmap.snd f.domain g.domain) (λ x, x.2.2)).to_fun } @[simp] lemma coprod_apply (f : linear_pmap R E G) (g : linear_pmap R F G) (x) : f.coprod g x = f ⟨(x : E × F).1, x.2.1⟩ + g ⟨(x : E × F).2, x.2.2⟩ := rfl /-! ### Graph -/ section graph /-- The graph of a `linear_pmap` viewed as a submodule on `E × F`. -/ def graph (f : linear_pmap R E F) : submodule R (E × F) := f.to_fun.graph.map (f.domain.subtype.prod_map linear_map.id) lemma mem_graph_iff' (f : linear_pmap R E F) {x : E × F} : x ∈ f.graph ↔ ∃ y : f.domain, (↑y, f y) = x := by simp [graph] @[simp] lemma mem_graph_iff (f : linear_pmap R E F) {x : E × F} : x ∈ f.graph ↔ ∃ y : f.domain, (↑y : E) = x.1 ∧ f y = x.2 := by { cases x, simp_rw [mem_graph_iff', prod.mk.inj_iff] } /-- The tuple `(x, f x)` is contained in the graph of `f`. -/ lemma mem_graph (f : linear_pmap R E F) (x : domain f) : ((x : E), f x) ∈ f.graph := by simp lemma mem_graph_snd_inj (f : linear_pmap R E F) {x y : E} {x' y' : F} (hx : (x,x') ∈ f.graph) (hy : (y,y') ∈ f.graph) (hxy : x = y) : x' = y' := begin rw [mem_graph_iff] at hx hy, rcases hx with ⟨x'', hx1, hx2⟩, rcases hy with ⟨y'', hy1, hy2⟩, simp only at hx1 hx2 hy1 hy2, rw [←hx1, ←hy1, set_like.coe_eq_coe] at hxy, rw [←hx2, ←hy2, hxy], end lemma mem_graph_snd_inj' (f : linear_pmap R E F) {x y : E × F} (hx : x ∈ f.graph) (hy : y ∈ f.graph) (hxy : x.1 = y.1) : x.2 = y.2 := by { cases x, cases y, exact f.mem_graph_snd_inj hx hy hxy } /-- The property that `f 0 = 0` in terms of the graph. -/ lemma graph_fst_eq_zero_snd (f : linear_pmap R E F) {x : E} {x' : F} (h : (x,x') ∈ f.graph) (hx : x = 0) : x' = 0 := f.mem_graph_snd_inj h f.graph.zero_mem hx end graph end linear_pmap namespace submodule section submodule_to_linear_pmap lemma exists_unique_from_graph {g : submodule R (E × F)} (hg : ∀ {x : E × F} (hx : x ∈ g) (hx' : x.fst = 0), x.snd = 0) {a : E} (ha : a ∈ g.map (linear_map.fst R E F)) : ∃! (b : F), (a,b) ∈ g := begin refine exists_unique_of_exists_of_unique _ _, { convert ha, simp }, intros y₁ y₂ hy₁ hy₂, have hy : ((0 : E), y₁ - y₂) ∈ g := begin convert g.sub_mem hy₁ hy₂, exact (sub_self _).symm, end, exact sub_eq_zero.mp (hg hy (by simp)), end /-- Auxiliary definition to unfold the existential quantifier. -/ noncomputable def val_from_graph {g : submodule R (E × F)} (hg : ∀ (x : E × F) (hx : x ∈ g) (hx' : x.fst = 0), x.snd = 0) {a : E} (ha : a ∈ g.map (linear_map.fst R E F)) : F := (exists_of_exists_unique (exists_unique_from_graph hg ha)).some lemma val_from_graph_mem {g : submodule R (E × F)} (hg : ∀ (x : E × F) (hx : x ∈ g) (hx' : x.fst = 0), x.snd = 0) {a : E} (ha : a ∈ g.map (linear_map.fst R E F)) : (a, val_from_graph hg ha) ∈ g := (exists_of_exists_unique (exists_unique_from_graph hg ha)).some_spec /-- Define a `linear_pmap` from its graph. -/ noncomputable def to_linear_pmap (g : submodule R (E × F)) (hg : ∀ (x : E × F) (hx : x ∈ g) (hx' : x.fst = 0), x.snd = 0) : linear_pmap R E F := { domain := g.map (linear_map.fst R E F), to_fun := { to_fun := λ x, val_from_graph hg x.2, map_add' := λ v w, begin have hadd := (g.map (linear_map.fst R E F)).add_mem v.2 w.2, have hvw := val_from_graph_mem hg hadd, have hvw' := g.add_mem (val_from_graph_mem hg v.2) (val_from_graph_mem hg w.2), rw [prod.mk_add_mk] at hvw', exact (exists_unique_from_graph hg hadd).unique hvw hvw', end, map_smul' := λ a v, begin have hsmul := (g.map (linear_map.fst R E F)).smul_mem a v.2, have hav := val_from_graph_mem hg hsmul, have hav' := g.smul_mem a (val_from_graph_mem hg v.2), rw [prod.smul_mk] at hav', exact (exists_unique_from_graph hg hsmul).unique hav hav', end } } lemma mem_graph_to_linear_pmap (g : submodule R (E × F)) (hg : ∀ (x : E × F) (hx : x ∈ g) (hx' : x.fst = 0), x.snd = 0) (x : g.map (linear_map.fst R E F)) : (x.val, g.to_linear_pmap hg x) ∈ g := val_from_graph_mem hg x.2 @[simp] lemma to_linear_pmap_graph_eq (g : submodule R (E × F)) (hg : ∀ (x : E × F) (hx : x ∈ g) (hx' : x.fst = 0), x.snd = 0) : (g.to_linear_pmap hg).graph = g := begin ext, split; intro hx, { rw [linear_pmap.mem_graph_iff] at hx, rcases hx with ⟨y,hx1,hx2⟩, convert g.mem_graph_to_linear_pmap hg y, rw [subtype.val_eq_coe], exact prod.ext hx1.symm hx2.symm }, rw linear_pmap.mem_graph_iff, cases x, have hx_fst : x_fst ∈ g.map (linear_map.fst R E F) := begin simp only [mem_map, linear_map.fst_apply, prod.exists, exists_and_distrib_right, exists_eq_right], exact ⟨x_snd, hx⟩, end, refine ⟨⟨x_fst, hx_fst⟩, subtype.coe_mk x_fst hx_fst, _⟩, exact (exists_unique_from_graph hg hx_fst).unique (val_from_graph_mem hg hx_fst) hx, end end submodule_to_linear_pmap end submodule
c81db98a2d466b6dd73c1ab6d34b1eaad6551867
e429a7c31201d4c56a2716f77a99c4831967b0de
/list_extra.lean
3333a68f714f6d61d30a1e860ead84bcefac2f07
[]
no_license
jthickstun/lean
cdb5ee8ec78294167d771a6167c0947419afa9eb
8254b987f06be1f98ef2e0cc33b7d4655d77dc85
refs/heads/master
1,620,156,057,836
1,557,865,724,000
1,557,865,724,000
106,618,304
8
1
null
null
null
null
UTF-8
Lean
false
false
8,269
lean
import .definitions import .nat_extra import .decidable_relations def plist : list ℕ → bool | [] := tt | (h :: t) := nt.irreducible h && plist t namespace list /- Basic lemmas concerning products and prime lists -/ lemma product_concat (l1 l2 : list ℕ) : product (l1 ++ l2) = (product l1) * (product l2) := begin induction l1, { by simp [product] }, { by simp [product, ih_1] } end lemma plist_concat (l1 l2 : list ℕ) : plist l1 = tt → plist l2 = tt → plist (l1 ++ l2) = tt := begin induction l1, { intros, by simp [a_1] }, { intros, simp [plist] at a_2, simp [plist], apply and.intro, { exact a_2.right }, { exact ih_1 a_2.left a_3 } } end lemma lmax_head {x y : ℕ} {t : list ℕ} (h : sorted (x :: y :: t) = tt) : y ≤ x := begin simp [sorted] at h, have : max x (lmax (y :: t)) = x, exact nat.eq_eq h.right.right, have hx : max y (lmax t) ≤ x, by rw [←this]; exact le_max_right x (lmax (y :: t)), have hy : y ≤ max y (lmax t), by simp [le_max_left], exact nat.le_trans hy hx end lemma plist_prod_nonzero {l : list ℕ} (h : plist l = tt) : product l ≠ 0 := begin induction l with p t ih, { simp [product] }, { simp [product], have ht : plist t = tt, by simp [plist] at h; exact h.left, by_cases p = 0 with hp, { simp [plist] at h, have : nt.irreducible p, from of_to_bool_true h.right, exact absurd hp this.left }, { have hpg0 : product t ≠ 0, from ih ht, --this was incredibly annoying; any ideas how we could make this easier? have hp : nat.succ (nat.pred p) = p, from nat.succ_pred_eq_of_pos (nat.pos_of_ne_zero hp), have ht : nat.succ (nat.pred (product t)) = product t, from nat.succ_pred_eq_of_pos (nat.pos_of_ne_zero hpg0), have : p*(product t) = 1 + (nat.pred p) + (nat.pred (product t)) + (nat.pred p)*(nat.pred (product t)), by rw [←hp,←ht]; apply nat.foil, have : p*(product t) = nat.succ((nat.pred p) + (nat.pred (product t)) + (nat.pred p)*(nat.pred (product t))), by rw [←nat.one_add]; simp [this], rw [this], exact nat.succ_ne_zero ((nat.pred p) + (nat.pred (product t)) + (nat.pred p)*(nat.pred (product t))) } } end lemma plist_prod_one {l : list ℕ} (h : plist l = tt) : product l = 1 → l = [] := begin cases l with p t, { simp }, { intro, simp [product] at a, have : p = 1, from (nat.unique_unit a).left, simp [plist, nt.computable_irreducible] at h, have : p ≠ 1, from (of_to_bool_true h.right).right.left, contradiction } end /- We'll need some machinery about permutations to talk about unique prime lists. This stuff is ripped from mathlib. -/ variable {α : Type} open perm @[refl] protected theorem perm.refl : ∀ (l : list α), l ~ l | [] := perm.nil | (x::xs) := skip x (perm.refl xs) @[symm] protected theorem perm.symm {l₁ l₂ : list α} (p : l₁ ~ l₂) : l₂ ~ l₁ := perm.rec_on p perm.nil (λ x l₁ l₂ p₁ r₁, skip x r₁) (λ x y l, swap y x l) (λ l₁ l₂ l₃ p₁ p₂ r₁ r₂, trans r₂ r₁) attribute [trans] perm.trans /- Interactions of permutations with our other list definitions -/ lemma perm_product {l₁ l₂ : list ℕ} (h : l₁ ~ l₂) : product l₁ = product l₂ := begin induction h, { simp }, { simp [product,ih_1] }, { simp [product] }, { simp [ih_1,ih_2] } end lemma perm_lmax {l₁ l₂ : list ℕ} (h : l₁ ~ l₂) : lmax l₁ = lmax l₂ := begin induction h, { simp }, { simp [lmax,ih_1] }, { simp [lmax,max_left_comm] }, { simp [ih_1,ih_2] } end lemma perm_plist {l₁ l₂ : list ℕ} (h : l₁ ~ l₂) (hp : plist l₁ = tt) : plist l₂ = tt := begin -- is there a way to clean up this induction re: term introduction? -- check out perm_induction_on in perm.lean in mathlib? induction h with x l₁ l₂ l₃ ih x y l l₁ l₂, { exact hp }, { have : plist l₁ = tt, by simp [plist] at hp; exact hp.left, have hp2 : plist l₂ = tt, by simp [this] at ih; exact ih, have : nt.irreducible x, by simp [plist] at hp; exact of_to_bool_true hp.right, simp [plist], exact and.intro hp2 (to_bool_true this) }, { have hpx : to_bool (nt.irreducible x) = tt, by simp [plist] at hp; exact hp.right.left, have hpy : to_bool (nt.irreducible y) = tt, by simp [plist,plist] at hp; exact hp.right.right, have hpl : plist l = tt, by simp [plist, plist] at hp; exact hp.left, have hpyl : plist (y :: l) = tt, by simp [plist]; exact and.intro hpl hpy, simp [plist], exact and.intro hpl (and.intro hpx hpy) }, { apply ih_2, apply ih_1, assumption } end /- We need to prove the existence of sorted lists. To do this, we introduce a sorting algorithm and show that it spits out a sorted permutation. -/ lemma perm_ordered_insert (x : ℕ) (l : list ℕ) : ordered_insert x l ~ x :: l := begin induction l with y l ih, { simp [ordered_insert] }, { by_cases y ≤ x with h, { simp [ordered_insert, h] }, { simp [ordered_insert, h], have hxy : y :: x :: l ~ x :: y :: l, by simp [perm.swap], suffices : y :: ordered_insert x l ~ y :: x :: l, { transitivity, apply this, apply hxy }, { apply perm.skip, simp [ih] } } } end lemma perm_insertion_sort (l : list ℕ) : insertion_sort l ~ l := begin induction l with y l ih, { simp [insertion_sort] }, { simp [insertion_sort], have h : ordered_insert y (insertion_sort l) ~ y :: insertion_sort l, by apply perm_ordered_insert, transitivity, assumption, apply perm.skip, apply ih } end lemma sorted_singleton (x : ℕ) : sorted [x] = tt := begin simp [sorted, lmax, max], by_cases x ≤ 0, { simp [nat.eq_zero_of_le_zero h, nat.eq] }, { simp [h, nat.eq] } end lemma sorted_head (x : ℕ) (l : list ℕ) : sorted (x :: l) = tt ↔ lmax l ≤ x ∧ sorted l = tt := begin split, { intro h, simp [sorted] at h, have hx : max x (lmax l) = x, from nat.eq_eq h.right, split, { rw [←hx], simp [le_max_right] }, { exact h.left } }, { intro h, simp [sorted], have : max x (lmax l) = x, by simp [max_eq_left h.left], apply and.intro, { exact h.right }, { exact nat.eq_of_eq this } } end lemma sorted_ordered_insert {x : ℕ} {l : list ℕ} : sorted l = tt → sorted (ordered_insert x l) = tt := begin intro h, induction l with y l ih, { simp [sorted_singleton] }, { by_cases y ≤ x with hxy, { simp [hxy], simp [sorted], apply and.intro, { simp [sorted] at h, exact h.left }, { simp [sorted] at h, apply and.intro, { exact h.right }, { have : lmax (y :: l) ≤ x, begin simp [lmax], have : max y (lmax l) = y, from nat.eq_eq h.right, rw [←this] at hxy, exact hxy end, have : max x (lmax (y :: l)) = x, from max_eq_left this, exact nat.eq_of_eq this } } }, { have : x ≤ y ∨ y ≤ x, from le_total x y, have hyx : x ≤ y, by simp [hxy] at this; assumption, have hyl : lmax l ≤ y, by simp [sorted_head] at h; exact h.right, have : ordered_insert x l ~ x :: l, by simp [perm_ordered_insert], have hyxl : lmax (ordered_insert x l) ≤ y, by simp [perm_lmax this, lmax]; simp [max_le hyx hyl], have : sorted l = tt, by simp [sorted] at h; exact h.left, have hxl : sorted (ordered_insert x l) = tt, from ih this, simp [hxy,sorted_head], apply and.intro, { exact hxl }, { exact hyxl } } } end lemma sorted_insertion_sort (l : list ℕ) : (sorted $ insertion_sort l) = tt := begin induction l with x l ih, { simp [insertion_sort, sorted] }, { simp [sorted_ordered_insert ih] } end /- Sorting a sorted list is idempotent: idem_insertion_sort. We conceptually might want the following lemma: lemma perm_sorted {l₁ l₂ : list ℕ} (h : l₁ ~ l₂) (hs1 : sorted l₁) (hs2 : sorted l₂) : l₁ = l₂ But this seems very hard to prove given our definition of perm_sorted. So instead we'll get the needed result from less general principles. -/ lemma idem_insertion_sort {l : list ℕ} (h : sorted l = tt) : insertion_sort l = l := --perm_sorted (perm_insertion_sort l) (sorted_insertion_sort l) h begin induction l with x t ih, { simp }, { have : sorted t = tt, by simp [sorted] at h; exact h.left, simp [insertion_sort], rw [ih this], induction t, { simp }, { simp [ordered_insert, list.lmax_head h] } } end end list
6b5d531bc25878fe82b9397f89eb2bab62f3bd95
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/analysis/complex/upper_half_plane/topology.lean
a47570b6e516b3614aeae4a98bd7a01a6a774b36
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
2,136
lean
/- Copyright (c) 2022 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov -/ import analysis.complex.upper_half_plane.basic import analysis.convex.contractible import analysis.convex.topology import analysis.convex.complex import analysis.complex.re_im_topology import topology.homotopy.contractible /-! # Topology on the upper half plane In this file we introduce a `topological_space` structure on the upper half plane and provide various instances. -/ noncomputable theory open set filter function topological_space complex open_locale filter topological_space upper_half_plane namespace upper_half_plane instance : topological_space ℍ := subtype.topological_space lemma open_embedding_coe : open_embedding (coe : ℍ → ℂ) := is_open.open_embedding_subtype_coe $ is_open_lt continuous_const complex.continuous_im lemma embedding_coe : embedding (coe : ℍ → ℂ) := embedding_subtype_coe lemma continuous_coe : continuous (coe : ℍ → ℂ) := embedding_coe.continuous lemma continuous_re : continuous re := complex.continuous_re.comp continuous_coe lemma continuous_im : continuous im := complex.continuous_im.comp continuous_coe instance : topological_space.second_countable_topology ℍ := topological_space.subtype.second_countable_topology _ _ instance : t3_space ℍ := subtype.t3_space instance : normal_space ℍ := normal_space_of_t3_second_countable ℍ instance : contractible_space ℍ := (convex_halfspace_im_gt 0).contractible_space ⟨I, one_pos.trans_eq I_im.symm⟩ instance : loc_path_connected_space ℍ := loc_path_connected_of_is_open $ is_open_lt continuous_const complex.continuous_im instance : noncompact_space ℍ := begin refine ⟨λ h, _⟩, have : is_compact (complex.im ⁻¹' Ioi 0), from is_compact_iff_is_compact_univ.2 h, replace := this.is_closed.closure_eq, rw [closure_preimage_im, closure_Ioi, set.ext_iff] at this, exact absurd ((this 0).1 left_mem_Ici) (lt_irrefl _) end instance : locally_compact_space ℍ := open_embedding_coe.locally_compact_space end upper_half_plane
b536823b338434ce3cea87eab293f320cadd67cc
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/reductionBug.lean
0e9fdcd6e7bba54a16a6045623fbff1fc25f7129
[ "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
415
lean
abbrev VName := String inductive Ty where | Bool | Int def Ctxt := VName → Option Ty variable (Γ : Ctxt) in inductive Expr : Ty → Type where | var (h : Γ x = some τ) : Expr τ def Expr.constFold : Expr Γ τ → Option Unit | var n => none theorem Expr.constFold_sound {e : Expr Γ τ} : constFold e = some v → True := by intro h induction e with | var => simp only [constFold] at h
3bc93eb18675d3a915b283818e4fd627e732dcc4
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/group_theory/perm/cycles.lean
e2f3591a885e7f7f91a65eb4e20bc8c87ad9427c
[ "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
58,404
lean
/- Copyright (c) 2019 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import data.nat.parity import data.equiv.fintype import group_theory.perm.sign import data.finset.noncomm_prod /-! # Cyclic permutations ## Main definitions In the following, `f : equiv.perm β`. * `equiv.perm.is_cycle`: `f.is_cycle` when two nonfixed points of `β` are related by repeated application of `f`. * `equiv.perm.same_cycle`: `f.same_cycle x y` when `x` and `y` are in the same cycle of `f`. The following two definitions require that `β` is a `fintype`: * `equiv.perm.cycle_of`: `f.cycle_of x` is the cycle of `f` that `x` belongs to. * `equiv.perm.cycle_factors`: `f.cycle_factors` is a list of disjoint cyclic permutations that multiply to `f`. ## Main results * This file contains several closure results: - `closure_is_cycle` : The symmetric group is generated by cycles - `closure_cycle_adjacent_swap` : The symmetric group is generated by a cycle and an adjacent transposition - `closure_cycle_coprime_swap` : The symmetric group is generated by a cycle and a coprime transposition - `closure_prime_cycle_swap` : The symmetric group is generated by a prime cycle and a transposition -/ namespace equiv.perm open equiv function finset variables {α : Type*} {β : Type*} [decidable_eq α] section sign_cycle /-! ### `is_cycle` -/ variables [fintype α] /-- A permutation is a cycle when any two nonfixed points of the permutation are related by repeated application of the permutation. -/ def is_cycle (f : perm β) : Prop := ∃ x, f x ≠ x ∧ ∀ y, f y ≠ y → ∃ i : ℤ, (f ^ i) x = y lemma is_cycle.ne_one {f : perm β} (h : is_cycle f) : f ≠ 1 := λ hf, by simpa [hf, is_cycle] using h @[simp] lemma not_is_cycle_one : ¬ (1 : perm β).is_cycle := λ H, H.ne_one rfl lemma is_cycle.two_le_card_support {f : perm α} (h : is_cycle f) : 2 ≤ f.support.card := two_le_card_support_of_ne_one h.ne_one lemma is_cycle_swap {α : Type*} [decidable_eq α] {x y : α} (hxy : x ≠ y) : is_cycle (swap x y) := ⟨y, by rwa swap_apply_right, λ a (ha : ite (a = x) y (ite (a = y) x a) ≠ a), if hya : y = a then ⟨0, hya⟩ else ⟨1, by { rw [gpow_one, swap_apply_def], split_ifs at *; cc }⟩⟩ lemma is_swap.is_cycle {α : Type*} [decidable_eq α] {f : perm α} (hf : is_swap f) : is_cycle f := begin obtain ⟨x, y, hxy, rfl⟩ := hf, exact is_cycle_swap hxy, end lemma is_cycle.inv {f : perm β} (hf : is_cycle f) : is_cycle (f⁻¹) := let ⟨x, hx⟩ := hf in ⟨x, by { simp only [inv_eq_iff_eq, *, forall_prop_of_true, ne.def] at *, cc }, λ y hy, let ⟨i, hi⟩ := hx.2 y (by { simp only [inv_eq_iff_eq, *, forall_prop_of_true, ne.def] at *, cc }) in ⟨-i, by rwa [gpow_neg, inv_gpow, inv_inv]⟩⟩ lemma is_cycle.is_cycle_conj {f g : perm β} (hf : is_cycle f) : is_cycle (g * f * g⁻¹) := begin obtain ⟨a, ha1, ha2⟩ := hf, refine ⟨g a, by simp [ha1], λ b hb, _⟩, obtain ⟨i, hi⟩ := ha2 (g⁻¹ b) _, { refine ⟨i, _⟩, rw conj_gpow, simp [hi] }, { contrapose! hb, rw [perm.mul_apply, perm.mul_apply, hb, apply_inv_self] } end lemma is_cycle.exists_gpow_eq {f : perm β} (hf : is_cycle f) {x y : β} (hx : f x ≠ x) (hy : f y ≠ y) : ∃ i : ℤ, (f ^ i) x = y := let ⟨g, hg⟩ := hf in let ⟨a, ha⟩ := hg.2 x hx in let ⟨b, hb⟩ := hg.2 y hy in ⟨b - a, by rw [← ha, ← mul_apply, ← gpow_add, sub_add_cancel, hb]⟩ lemma is_cycle.exists_pow_eq [fintype β] {f : perm β} (hf : is_cycle f) {x y : β} (hx : f x ≠ x) (hy : f y ≠ y) : ∃ i : ℕ, (f ^ i) x = y := let ⟨n, hn⟩ := hf.exists_gpow_eq hx hy in by classical; exact ⟨(n % order_of f).to_nat, by { have := n.mod_nonneg (int.coe_nat_ne_zero.mpr (ne_of_gt (order_of_pos f))), rwa [← gpow_coe_nat, int.to_nat_of_nonneg this, ← gpow_eq_mod_order_of] }⟩ lemma is_cycle.exists_pow_eq_one [fintype β] {f : perm β} (hf : is_cycle f) : ∃ (k : ℕ) (hk : 1 < k), f ^ k = 1 := begin classical, have : is_of_fin_order f := exists_pow_eq_one f, rw is_of_fin_order_iff_pow_eq_one at this, obtain ⟨x, hx, hx'⟩ := hf, obtain ⟨_ | _ | k, hk, hk'⟩ := this, { exact absurd hk (lt_asymm hk) }, { rw pow_one at hk', simpa [hk'] using hx }, { exact ⟨k + 2, by simp, hk'⟩ } end /-- The subgroup generated by a cycle is in bijection with its support -/ noncomputable def is_cycle.gpowers_equiv_support {σ : perm α} (hσ : is_cycle σ) : (↑(subgroup.gpowers σ) : set (perm α)) ≃ (↑(σ.support) : set α) := equiv.of_bijective (λ τ, ⟨τ (classical.some hσ), begin obtain ⟨τ, n, rfl⟩ := τ, rw [finset.mem_coe, coe_fn_coe_base, subtype.coe_mk, gpow_apply_mem_support, mem_support], exact (classical.some_spec hσ).1, end⟩) begin split, { rintros ⟨a, m, rfl⟩ ⟨b, n, rfl⟩ h, ext y, by_cases hy : σ y = y, { simp_rw [subtype.coe_mk, gpow_apply_eq_self_of_apply_eq_self hy] }, { obtain ⟨i, rfl⟩ := (classical.some_spec hσ).2 y hy, rw [subtype.coe_mk, subtype.coe_mk, gpow_apply_comm σ m i, gpow_apply_comm σ n i], exact congr_arg _ (subtype.ext_iff.mp h) } }, by { rintros ⟨y, hy⟩, rw [finset.mem_coe, mem_support] at hy, obtain ⟨n, rfl⟩ := (classical.some_spec hσ).2 y hy, exact ⟨⟨σ ^ n, n, rfl⟩, rfl⟩ }, end @[simp] lemma is_cycle.gpowers_equiv_support_apply {σ : perm α} (hσ : is_cycle σ) {n : ℕ} : hσ.gpowers_equiv_support ⟨σ ^ n, n, rfl⟩ = ⟨(σ ^ n) (classical.some hσ), pow_apply_mem_support.2 (mem_support.2 (classical.some_spec hσ).1)⟩ := rfl @[simp] lemma is_cycle.gpowers_equiv_support_symm_apply {σ : perm α} (hσ : is_cycle σ) (n : ℕ) : hσ.gpowers_equiv_support.symm ⟨(σ ^ n) (classical.some hσ), pow_apply_mem_support.2 (mem_support.2 (classical.some_spec hσ).1)⟩ = ⟨σ ^ n, n, rfl⟩ := (equiv.symm_apply_eq _).2 hσ.gpowers_equiv_support_apply lemma order_of_is_cycle {σ : perm α} (hσ : is_cycle σ) : order_of σ = σ.support.card := begin rw [order_eq_card_gpowers, ←fintype.card_coe], convert fintype.card_congr (is_cycle.gpowers_equiv_support hσ), end lemma is_cycle_swap_mul_aux₁ {α : Type*} [decidable_eq α] : ∀ (n : ℕ) {b x : α} {f : perm α} (hb : (swap x (f x) * f) b ≠ b) (h : (f ^ n) (f x) = b), ∃ i : ℤ, ((swap x (f x) * f) ^ i) (f x) = b | 0 := λ b x f hb h, ⟨0, h⟩ | (n+1 : ℕ) := λ b x f hb h, if hfbx : f x = b then ⟨0, hfbx⟩ else have f b ≠ b ∧ b ≠ x, from ne_and_ne_of_swap_mul_apply_ne_self hb, have hb' : (swap x (f x) * f) (f⁻¹ b) ≠ f⁻¹ b, by { rw [mul_apply, apply_inv_self, swap_apply_of_ne_of_ne this.2 (ne.symm hfbx), ne.def, ← f.injective.eq_iff, apply_inv_self], exact this.1 }, let ⟨i, hi⟩ := is_cycle_swap_mul_aux₁ n hb' (f.injective $ by { rw [apply_inv_self], rwa [pow_succ, mul_apply] at h }) in ⟨i + 1, by rw [add_comm, gpow_add, mul_apply, hi, gpow_one, mul_apply, apply_inv_self, swap_apply_of_ne_of_ne (ne_and_ne_of_swap_mul_apply_ne_self hb).2 (ne.symm hfbx)]⟩ lemma is_cycle_swap_mul_aux₂ {α : Type*} [decidable_eq α] : ∀ (n : ℤ) {b x : α} {f : perm α} (hb : (swap x (f x) * f) b ≠ b) (h : (f ^ n) (f x) = b), ∃ i : ℤ, ((swap x (f x) * f) ^ i) (f x) = b | (n : ℕ) := λ b x f, is_cycle_swap_mul_aux₁ n | -[1+ n] := λ b x f hb h, if hfbx : f⁻¹ x = b then ⟨-1, by rwa [gpow_neg, gpow_one, mul_inv_rev, mul_apply, swap_inv, swap_apply_right]⟩ else if hfbx' : f x = b then ⟨0, hfbx'⟩ else have f b ≠ b ∧ b ≠ x := ne_and_ne_of_swap_mul_apply_ne_self hb, have hb : (swap x (f⁻¹ x) * f⁻¹) (f⁻¹ b) ≠ f⁻¹ b, by { rw [mul_apply, swap_apply_def], split_ifs; simp only [inv_eq_iff_eq, perm.mul_apply, gpow_neg_succ_of_nat, ne.def, perm.apply_inv_self] at *; cc }, let ⟨i, hi⟩ := is_cycle_swap_mul_aux₁ n hb (show (f⁻¹ ^ n) (f⁻¹ x) = f⁻¹ b, by rw [← gpow_coe_nat, ← h, ← mul_apply, ← mul_apply, ← mul_apply, gpow_neg_succ_of_nat, ← inv_pow, pow_succ', mul_assoc, mul_assoc, inv_mul_self, mul_one, gpow_coe_nat, ← pow_succ', ← pow_succ]) in have h : (swap x (f⁻¹ x) * f⁻¹) (f x) = f⁻¹ x, by rw [mul_apply, inv_apply_self, swap_apply_left], ⟨-i, by rw [← add_sub_cancel i 1, neg_sub, sub_eq_add_neg, gpow_add, gpow_one, gpow_neg, ← inv_gpow, mul_inv_rev, swap_inv, mul_swap_eq_swap_mul, inv_apply_self, swap_comm _ x, gpow_add, gpow_one, mul_apply, mul_apply (_ ^ i), h, hi, mul_apply, apply_inv_self, swap_apply_of_ne_of_ne this.2 (ne.symm hfbx')]⟩ lemma is_cycle.eq_swap_of_apply_apply_eq_self {α : Type*} [decidable_eq α] {f : perm α} (hf : is_cycle f) {x : α} (hfx : f x ≠ x) (hffx : f (f x) = x) : f = swap x (f x) := equiv.ext $ λ y, let ⟨z, hz⟩ := hf in let ⟨i, hi⟩ := hz.2 x hfx in if hyx : y = x then by simp [hyx] else if hfyx : y = f x then by simp [hfyx, hffx] else begin rw [swap_apply_of_ne_of_ne hyx hfyx], refine by_contradiction (λ hy, _), cases hz.2 y hy with j hj, rw [← sub_add_cancel j i, gpow_add, mul_apply, hi] at hj, cases gpow_apply_eq_of_apply_apply_eq_self hffx (j - i) with hji hji, { rw [← hj, hji] at hyx, cc }, { rw [← hj, hji] at hfyx, cc } end lemma is_cycle.swap_mul {α : Type*} [decidable_eq α] {f : perm α} (hf : is_cycle f) {x : α} (hx : f x ≠ x) (hffx : f (f x) ≠ x) : is_cycle (swap x (f x) * f) := ⟨f x, by { simp only [swap_apply_def, mul_apply], split_ifs; simp [f.injective.eq_iff] at *; cc }, λ y hy, let ⟨i, hi⟩ := hf.exists_gpow_eq hx (ne_and_ne_of_swap_mul_apply_ne_self hy).1 in have hi : (f ^ (i - 1)) (f x) = y, from calc (f ^ (i - 1)) (f x) = (f ^ (i - 1) * f ^ (1 : ℤ)) x : by rw [gpow_one, mul_apply] ... = y : by rwa [← gpow_add, sub_add_cancel], is_cycle_swap_mul_aux₂ (i - 1) hy hi⟩ lemma is_cycle.sign : ∀ {f : perm α} (hf : is_cycle f), sign f = -(-1) ^ f.support.card | f := λ hf, let ⟨x, hx⟩ := hf in calc sign f = sign (swap x (f x) * (swap x (f x) * f)) : by rw [← mul_assoc, mul_def, mul_def, swap_swap, trans_refl] ... = -(-1) ^ f.support.card : if h1 : f (f x) = x then have h : swap x (f x) * f = 1, begin rw hf.eq_swap_of_apply_apply_eq_self hx.1 h1, simp only [perm.mul_def, perm.one_def, swap_apply_left, swap_swap] end, by { rw [sign_mul, sign_swap hx.1.symm, h, sign_one, hf.eq_swap_of_apply_apply_eq_self hx.1 h1, card_support_swap hx.1.symm], refl } else have h : card (support (swap x (f x) * f)) + 1 = card (support f), by rw [← insert_erase (mem_support.2 hx.1), support_swap_mul_eq _ _ h1, card_insert_of_not_mem (not_mem_erase _ _), sdiff_singleton_eq_erase], have wf : card (support (swap x (f x) * f)) < card (support f), from card_support_swap_mul hx.1, by { rw [sign_mul, sign_swap hx.1.symm, (hf.swap_mul hx.1 h1).sign, ← h], simp only [pow_add, mul_one, units.neg_neg, one_mul, units.mul_neg, eq_self_iff_true, pow_one, units.neg_mul_neg] } using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf (λ f, f.support.card)⟩]} lemma is_cycle_of_is_cycle_pow {σ : perm α} {n : ℕ} (h1 : is_cycle (σ ^ n)) (h2 : σ.support ≤ (σ ^ n).support) : is_cycle σ := begin have key : ∀ x : α, (σ ^ n) x ≠ x ↔ σ x ≠ x, { simp_rw [←mem_support], exact finset.ext_iff.mp (le_antisymm (support_pow_le σ n) h2) }, obtain ⟨x, hx1, hx2⟩ := h1, refine ⟨x, (key x).mp hx1, λ y hy, _⟩, cases (hx2 y ((key y).mpr hy)) with i _, exact ⟨n * i, by rwa gpow_mul⟩ end -- The lemma `support_gpow_le` is relevant. It means that `h2` is equivalent to -- `σ.support = (σ ^ n).support`, as well as to `σ.support.card ≤ (σ ^ n).support.card`. lemma is_cycle_of_is_cycle_gpow {σ : perm α} {n : ℤ} (h1 : is_cycle (σ ^ n)) (h2 : σ.support ≤ (σ ^ n).support) : is_cycle σ := begin cases n, { exact is_cycle_of_is_cycle_pow h1 h2 }, { simp only [le_eq_subset, gpow_neg_succ_of_nat, perm.support_inv] at h1 h2, simpa using is_cycle_of_is_cycle_pow h1.inv h2 } end lemma is_cycle.extend_domain {α : Type*} {p : β → Prop} [decidable_pred p] (f : α ≃ subtype p) {g : perm α} (h : is_cycle g) : is_cycle (g.extend_domain f) := begin obtain ⟨a, ha, ha'⟩ := h, refine ⟨f a, _, λ b hb, _⟩, { rw extend_domain_apply_image, exact λ con, ha (f.injective (subtype.coe_injective con)) }, by_cases pb : p b, { obtain ⟨i, hi⟩ := ha' (f.symm ⟨b, pb⟩) (λ con, hb _), { refine ⟨i, _⟩, have hnat : ∀ (k : ℕ) (a : α), (g.extend_domain f ^ k) ↑(f a) = f ((g ^ k) a), { intros k a, induction k with k ih, { refl }, rw [pow_succ, perm.mul_apply, ih, extend_domain_apply_image, pow_succ, perm.mul_apply] }, have hint : ∀ (k : ℤ) (a : α), (g.extend_domain f ^ k) ↑(f a) = f ((g ^ k) a), { intros k a, induction k with k k, { rw [gpow_of_nat, gpow_of_nat, hnat] }, rw [gpow_neg_succ_of_nat, gpow_neg_succ_of_nat, inv_eq_iff_eq, hnat, apply_inv_self] }, rw [hint, hi, apply_symm_apply, subtype.coe_mk] }, { rw [extend_domain_apply_subtype _ _ pb, con, apply_symm_apply, subtype.coe_mk] } }, { exact (hb (extend_domain_apply_not_subtype _ _ pb)).elim } end lemma nodup_of_pairwise_disjoint_cycles {l : list (perm β)} (h1 : ∀ f ∈ l, is_cycle f) (h2 : l.pairwise disjoint) : l.nodup := nodup_of_pairwise_disjoint (λ h, (h1 1 h).ne_one rfl) h2 end sign_cycle /-! ### `same_cycle` -/ /-- The equivalence relation indicating that two points are in the same cycle of a permutation. -/ def same_cycle (f : perm β) (x y : β) : Prop := ∃ i : ℤ, (f ^ i) x = y @[refl] lemma same_cycle.refl (f : perm β) (x : β) : same_cycle f x x := ⟨0, rfl⟩ @[symm] lemma same_cycle.symm {f : perm β} {x y : β} : same_cycle f x y → same_cycle f y x := λ ⟨i, hi⟩, ⟨-i, by rw [gpow_neg, ← hi, inv_apply_self]⟩ @[trans] lemma same_cycle.trans {f : perm β} {x y z : β} : same_cycle f x y → same_cycle f y z → same_cycle f x z := λ ⟨i, hi⟩ ⟨j, hj⟩, ⟨j + i, by rw [gpow_add, mul_apply, hi, hj]⟩ lemma same_cycle.apply_eq_self_iff {f : perm β} {x y : β} : same_cycle f x y → (f x = x ↔ f y = y) := λ ⟨i, hi⟩, by rw [← hi, ← mul_apply, ← gpow_one_add, add_comm, gpow_add_one, mul_apply, (f ^ i).injective.eq_iff] lemma is_cycle.same_cycle {f : perm β} (hf : is_cycle f) {x y : β} (hx : f x ≠ x) (hy : f y ≠ y) : same_cycle f x y := hf.exists_gpow_eq hx hy lemma same_cycle.nat' [fintype β] {f : perm β} {x y : β} (h : same_cycle f x y) : ∃ (i : ℕ) (h : i < order_of f), (f ^ i) x = y := begin classical, obtain ⟨k, rfl⟩ := id h, by_cases hk : (k % order_of f) = 0, { use 0, rw ←int.dvd_iff_mod_eq_zero at hk, obtain ⟨m, rfl⟩ := hk, simp [pow_order_of_eq_one, order_of_pos, gpow_mul] }, { use ((k % order_of f).nat_abs), rw [←gpow_coe_nat, int.nat_abs_of_nonneg, ←gpow_eq_mod_order_of], { refine ⟨_, rfl⟩, rw [←int.coe_nat_lt, int.nat_abs_of_nonneg], { refine (int.mod_lt_of_pos _ _), simpa using order_of_pos _ }, { refine int.mod_nonneg _ _, simpa using ne_of_gt (order_of_pos _) } }, { refine int.mod_nonneg _ _, simpa using (order_of_pos _).ne' } } end lemma same_cycle.nat'' [fintype β] {f : perm β} {x y : β} (h : same_cycle f x y) : ∃ (i : ℕ) (hpos : 0 < i) (h : i ≤ order_of f), (f ^ i) x = y := begin classical, obtain ⟨_|i, hi, rfl⟩ := h.nat', { refine ⟨order_of f, order_of_pos f, le_rfl, _⟩, rw [pow_order_of_eq_one, pow_zero] }, { exact ⟨i.succ, i.zero_lt_succ, hi.le, rfl⟩ } end instance [fintype α] (f : perm α) : decidable_rel (same_cycle f) := λ x y, decidable_of_iff (∃ n ∈ list.range (fintype.card (perm α)), (f ^ n) x = y) ⟨λ ⟨n, _, hn⟩, ⟨n, hn⟩, λ ⟨i, hi⟩, ⟨(i % order_of f).nat_abs, list.mem_range.2 (int.coe_nat_lt.1 $ by { rw int.nat_abs_of_nonneg (int.mod_nonneg _ (int.coe_nat_ne_zero_iff_pos.2 (order_of_pos _))), { apply lt_of_lt_of_le (int.mod_lt _ (int.coe_nat_ne_zero_iff_pos.2 (order_of_pos _))), { simp [order_of_le_card_univ] }, exact fintype_perm }, exact fintype_perm, }), by { rw [← gpow_coe_nat, int.nat_abs_of_nonneg (int.mod_nonneg _ (int.coe_nat_ne_zero_iff_pos.2 (order_of_pos _))), ← gpow_eq_mod_order_of, hi], exact fintype_perm }⟩⟩ lemma same_cycle_apply {f : perm β} {x y : β} : same_cycle f x (f y) ↔ same_cycle f x y := ⟨λ ⟨i, hi⟩, ⟨-1 + i, by rw [gpow_add, mul_apply, hi, gpow_neg_one, inv_apply_self]⟩, λ ⟨i, hi⟩, ⟨1 + i, by rw [gpow_add, mul_apply, hi, gpow_one]⟩⟩ lemma same_cycle_cycle {f : perm β} {x : β} (hx : f x ≠ x) : is_cycle f ↔ (∀ {y}, same_cycle f x y ↔ f y ≠ y) := ⟨λ hf y, ⟨λ ⟨i, hi⟩ hy, hx $ by { rw [← gpow_apply_eq_self_of_apply_eq_self hy i, (f ^ i).injective.eq_iff] at hi, rw [hi, hy] }, hf.exists_gpow_eq hx⟩, λ h, ⟨x, hx, λ y hy, h.2 hy⟩⟩ lemma same_cycle_inv (f : perm β) {x y : β} : same_cycle f⁻¹ x y ↔ same_cycle f x y := ⟨λ ⟨i, hi⟩, ⟨-i, by rw [gpow_neg, ← inv_gpow, hi]⟩, λ ⟨i, hi⟩, ⟨-i, by rw [gpow_neg, ← inv_gpow, inv_inv, hi]⟩ ⟩ lemma same_cycle_inv_apply {f : perm β} {x y : β} : same_cycle f x (f⁻¹ y) ↔ same_cycle f x y := by rw [← same_cycle_inv, same_cycle_apply, same_cycle_inv] @[simp] lemma same_cycle_pow_left_iff {f : perm β} {x y : β} {n : ℕ} : same_cycle f ((f ^ n) x) y ↔ same_cycle f x y := begin split, { rintro ⟨k, rfl⟩, use (k + n), simp [gpow_add] }, { rintro ⟨k, rfl⟩, use (k - n), rw [←gpow_coe_nat, ←mul_apply, ←gpow_add, int.sub_add_cancel] } end @[simp] lemma same_cycle_gpow_left_iff {f : perm β} {x y : β} {n : ℤ} : same_cycle f ((f ^ n) x) y ↔ same_cycle f x y := begin cases n, { exact same_cycle_pow_left_iff }, { rw [gpow_neg_succ_of_nat, ←inv_pow, ←same_cycle_inv, same_cycle_pow_left_iff, same_cycle_inv] } end /-- Unlike `support_congr`, which assumes that `∀ (x ∈ g.support), f x = g x)`, here we have the weaker assumption that `∀ (x ∈ f.support), f x = g x`. -/ lemma is_cycle.support_congr [fintype α] {f g : perm α} (hf : is_cycle f) (hg : is_cycle g) (h : f.support ⊆ g.support) (h' : ∀ (x ∈ f.support), f x = g x) : f = g := begin have : f.support = g.support, { refine le_antisymm h _, intros z hz, obtain ⟨x, hx, hf'⟩ := id hf, have hx' : g x ≠ x, { rwa [←h' x (mem_support.mpr hx)] }, obtain ⟨m, hm⟩ := hg.exists_pow_eq hx' (mem_support.mp hz), have h'' : ∀ (x ∈ f.support ∩ g.support), f x = g x, { intros x hx, exact h' x (mem_of_mem_inter_left hx) }, rwa [←hm, ←pow_eq_on_of_mem_support h'' _ x (mem_inter_of_mem (mem_support.mpr hx) (mem_support.mpr hx')), pow_apply_mem_support, mem_support] }, refine support_congr h _, simpa [←this] using h' end /-- If two cyclic permutations agree on all terms in their intersection, and that intersection is not empty, then the two cyclic permutations must be equal. -/ lemma is_cycle.eq_on_support_inter_nonempty_congr [fintype α] {f g : perm α} (hf : is_cycle f) (hg : is_cycle g) (h : ∀ (x ∈ f.support ∩ g.support), f x = g x) {x : α} (hx : f x = g x) (hx' : x ∈ f.support) : f = g := begin have hx'' : x ∈ g.support, { rwa [mem_support, ←hx, ←mem_support] }, have : f.support ⊆ g.support, { intros y hy, obtain ⟨k, rfl⟩ := hf.exists_pow_eq (mem_support.mp hx') (mem_support.mp hy), rwa [pow_eq_on_of_mem_support h _ _ (mem_inter_of_mem hx' hx''), pow_apply_mem_support] }, rw (inter_eq_left_iff_subset _ _).mpr this at h, exact hf.support_congr hg this h end lemma is_cycle.support_pow_eq_iff [fintype α] {f : perm α} (hf : is_cycle f) {n : ℕ} : support (f ^ n) = support f ↔ ¬ order_of f ∣ n := begin rw order_of_dvd_iff_pow_eq_one, split, { intros h H, refine hf.ne_one _, rw [←support_eq_empty_iff, ←h, H, support_one] }, { intro H, apply le_antisymm (support_pow_le _ n) _, intros x hx, contrapose! H, ext z, by_cases hz : f z = z, { rw [pow_apply_eq_self_of_apply_eq_self hz, one_apply] }, { obtain ⟨k, rfl⟩ := hf.exists_pow_eq hz (mem_support.mp hx), apply (f ^ k).injective, rw [←mul_apply, (commute.pow_pow_self _ _ _).eq, mul_apply], simpa using H } } end lemma is_cycle.pow_iff [fintype β] {f : perm β} (hf : is_cycle f) {n : ℕ} : is_cycle (f ^ n) ↔ n.coprime (order_of f) := begin classical, split, { intro h, have hr : support (f ^ n) = support f, { rw hf.support_pow_eq_iff, rintro ⟨k, rfl⟩, refine h.ne_one _, simp [pow_mul, pow_order_of_eq_one] }, have : order_of (f ^ n) = order_of f, { rw [order_of_is_cycle h, hr, order_of_is_cycle hf] }, rw [order_of_pow, nat.div_eq_self] at this, cases this, { exact absurd this (order_of_pos _).ne' }, { rwa [nat.coprime_iff_gcd_eq_one, nat.gcd_comm] } }, { intro h, obtain ⟨m, hm⟩ := exists_pow_eq_self_of_coprime h, have hf' : is_cycle ((f ^ n) ^ m) := by rwa hm, refine is_cycle_of_is_cycle_pow hf' _, intros x hx, rw [hm], exact support_pow_le _ n hx } end lemma is_cycle.pow_eq_one_iff [fintype α] {f : perm α} (hf : is_cycle f) {n : ℕ} : f ^ n = 1 ↔ ∃ (x ∈ f.support), (f ^ n) x = x := begin split, { intro h, obtain ⟨x, hx, -⟩ := id hf, exact ⟨x, mem_support.mpr hx, by simp [h]⟩ }, { rintro ⟨x, hx, hx'⟩, by_cases h : support (f ^ n) = support f, { rw [←h, mem_support] at hx, contradiction }, { rw [hf.support_pow_eq_iff, not_not] at h, obtain ⟨k, rfl⟩ := h, rw [pow_mul, pow_order_of_eq_one, one_pow] } } end lemma is_cycle.mem_support_pos_pow_iff_of_lt_order_of [fintype α] {f : perm α} (hf : is_cycle f) {n : ℕ} (npos : 0 < n) (hn : n < order_of f) {x : α} : x ∈ (f ^ n).support ↔ x ∈ f.support := begin have : ¬ order_of f ∣ n := nat.not_dvd_of_pos_of_lt npos hn, rw ←hf.support_pow_eq_iff at this, rw this end lemma is_cycle.is_cycle_pow_pos_of_lt_prime_order [fintype β] {f : perm β} (hf : is_cycle f) (hf' : (order_of f).prime) (n : ℕ) (hn : 0 < n) (hn' : n < order_of f) : is_cycle (f ^ n) := begin classical, have : n.coprime (order_of f), { refine nat.coprime.symm _, rw nat.prime.coprime_iff_not_dvd hf', exact nat.not_dvd_of_pos_of_lt hn hn' }, obtain ⟨m, hm⟩ := exists_pow_eq_self_of_coprime this, have hf'' := hf, rw ←hm at hf'', refine is_cycle_of_is_cycle_pow hf'' _, rw [hm], exact support_pow_le f n end /-! ### `cycle_of` -/ /-- `f.cycle_of x` is the cycle of the permutation `f` to which `x` belongs. -/ def cycle_of [fintype α] (f : perm α) (x : α) : perm α := of_subtype (@subtype_perm _ f (same_cycle f x) (λ _, same_cycle_apply.symm)) lemma cycle_of_apply [fintype α] (f : perm α) (x y : α) : cycle_of f x y = if same_cycle f x y then f y else y := rfl lemma cycle_of_inv [fintype α] (f : perm α) (x : α) : (cycle_of f x)⁻¹ = cycle_of f⁻¹ x := equiv.ext $ λ y, begin rw [inv_eq_iff_eq, cycle_of_apply, cycle_of_apply], split_ifs; simp [*, same_cycle_inv, same_cycle_inv_apply] at * end @[simp] lemma cycle_of_pow_apply_self [fintype α] (f : perm α) (x : α) : ∀ n : ℕ, (cycle_of f x ^ n) x = (f ^ n) x | 0 := rfl | (n+1) := by { rw [pow_succ, mul_apply, cycle_of_apply, cycle_of_pow_apply_self, if_pos, pow_succ, mul_apply], exact ⟨n, rfl⟩ } @[simp] lemma cycle_of_gpow_apply_self [fintype α] (f : perm α) (x : α) : ∀ n : ℤ, (cycle_of f x ^ n) x = (f ^ n) x | (n : ℕ) := cycle_of_pow_apply_self f x n | -[1+ n] := by rw [gpow_neg_succ_of_nat, ← inv_pow, cycle_of_inv, gpow_neg_succ_of_nat, ← inv_pow, cycle_of_pow_apply_self] lemma same_cycle.cycle_of_apply [fintype α] {f : perm α} {x y : α} (h : same_cycle f x y) : cycle_of f x y = f y := dif_pos h lemma cycle_of_apply_of_not_same_cycle [fintype α] {f : perm α} {x y : α} (h : ¬same_cycle f x y) : cycle_of f x y = y := dif_neg h lemma same_cycle.cycle_of_eq [fintype α] {f : perm α} {x y : α} (h : same_cycle f x y) : cycle_of f x = cycle_of f y := begin ext z, rw cycle_of_apply, split_ifs with hz hz, { exact (h.symm.trans hz).cycle_of_apply.symm }, { exact (cycle_of_apply_of_not_same_cycle (mt h.trans hz)).symm } end @[simp] lemma cycle_of_apply_apply_gpow_self [fintype α] (f : perm α) (x : α) (k : ℤ) : cycle_of f x ((f ^ k) x) = (f ^ (k + 1)) x := begin rw same_cycle.cycle_of_apply, { rw [add_comm, gpow_add, gpow_one, mul_apply] }, { exact ⟨k, rfl⟩ } end @[simp] lemma cycle_of_apply_apply_pow_self [fintype α] (f : perm α) (x : α) (k : ℕ) : cycle_of f x ((f ^ k) x) = (f ^ (k + 1)) x := by convert cycle_of_apply_apply_gpow_self f x k using 1 @[simp] lemma cycle_of_apply_apply_self [fintype α] (f : perm α) (x : α) : cycle_of f x (f x) = f (f x) := by convert cycle_of_apply_apply_pow_self f x 1 using 1 @[simp] lemma cycle_of_apply_self [fintype α] (f : perm α) (x : α) : cycle_of f x x = f x := (same_cycle.refl _ _).cycle_of_apply lemma is_cycle.cycle_of_eq [fintype α] {f : perm α} (hf : is_cycle f) {x : α} (hx : f x ≠ x) : cycle_of f x = f := equiv.ext $ λ y, if h : same_cycle f x y then by rw [h.cycle_of_apply] else by rw [cycle_of_apply_of_not_same_cycle h, not_not.1 (mt ((same_cycle_cycle hx).1 hf).2 h)] @[simp] lemma cycle_of_eq_one_iff [fintype α] (f : perm α) {x : α} : cycle_of f x = 1 ↔ f x = x := begin simp_rw [ext_iff, cycle_of_apply, one_apply], refine ⟨λ h, (if_pos (same_cycle.refl f x)).symm.trans (h x), λ h y, _⟩, by_cases hy : f y = y, { rw [hy, if_t_t] }, { exact if_neg (mt same_cycle.apply_eq_self_iff (by tauto)) }, end @[simp] lemma cycle_of_self_apply [fintype α] (f : perm α) (x : α) : cycle_of f (f x) = cycle_of f x := (same_cycle_apply.mpr (same_cycle.refl _ _)).symm.cycle_of_eq @[simp] lemma cycle_of_self_apply_pow [fintype α] (f : perm α) (n : ℕ) (x : α) : cycle_of f ((f ^ n) x) = cycle_of f x := (same_cycle_pow_left_iff.mpr (same_cycle.refl _ _)).cycle_of_eq @[simp] lemma cycle_of_self_apply_gpow [fintype α] (f : perm α) (n : ℤ) (x : α) : cycle_of f ((f ^ n) x) = cycle_of f x := (same_cycle_gpow_left_iff.mpr (same_cycle.refl _ _)).cycle_of_eq lemma is_cycle.cycle_of [fintype α] {f : perm α} (hf : is_cycle f) {x : α} : cycle_of f x = if f x = x then 1 else f := begin by_cases hx : f x = x, { rwa [if_pos hx, cycle_of_eq_one_iff] }, { rwa [if_neg hx, hf.cycle_of_eq] }, end lemma cycle_of_one [fintype α] (x : α) : cycle_of 1 x = 1 := (cycle_of_eq_one_iff 1).mpr rfl lemma is_cycle_cycle_of [fintype α] (f : perm α) {x : α} (hx : f x ≠ x) : is_cycle (cycle_of f x) := have cycle_of f x x ≠ x, by rwa [(same_cycle.refl _ _).cycle_of_apply], (same_cycle_cycle this).2 $ λ y, ⟨λ h, mt h.apply_eq_self_iff.2 this, λ h, if hxy : same_cycle f x y then let ⟨i, hi⟩ := hxy in ⟨i, by rw [cycle_of_gpow_apply_self, hi]⟩ else by { rw [cycle_of_apply_of_not_same_cycle hxy] at h, exact (h rfl).elim }⟩ @[simp] lemma two_le_card_support_cycle_of_iff [fintype α] {f : perm α} {x : α} : 2 ≤ card (cycle_of f x).support ↔ f x ≠ x := begin refine ⟨λ h, _, λ h, by simpa using (is_cycle_cycle_of _ h).two_le_card_support⟩, contrapose! h, rw ←cycle_of_eq_one_iff at h, simp [h] end @[simp] lemma card_support_cycle_of_pos_iff [fintype α] {f : perm α} {x : α} : 0 < card (cycle_of f x).support ↔ f x ≠ x := begin rw [←two_le_card_support_cycle_of_iff, ←nat.succ_le_iff], exact ⟨λ h, or.resolve_left h.eq_or_lt (card_support_ne_one _).symm, zero_lt_two.trans_le⟩ end lemma pow_apply_eq_pow_mod_order_of_cycle_of_apply [fintype α] (f : perm α) (n : ℕ) (x : α) : (f ^ n) x = (f ^ (n % order_of (cycle_of f x))) x := by rw [←cycle_of_pow_apply_self f, ←cycle_of_pow_apply_self f, pow_eq_mod_order_of] lemma cycle_of_mul_of_apply_right_eq_self [fintype α] {f g : perm α} (h : _root_.commute f g) (x : α) (hx : g x = x) : (f * g).cycle_of x = f.cycle_of x := begin ext y, by_cases hxy : (f * g).same_cycle x y, { obtain ⟨z, rfl⟩ := hxy, rw cycle_of_apply_apply_gpow_self, simp [h.mul_gpow, gpow_apply_eq_self_of_apply_eq_self hx] }, { rw [cycle_of_apply_of_not_same_cycle hxy, cycle_of_apply_of_not_same_cycle], contrapose! hxy, obtain ⟨z, rfl⟩ := hxy, refine ⟨z, _⟩, simp [h.mul_gpow, gpow_apply_eq_self_of_apply_eq_self hx] } end lemma disjoint.cycle_of_mul_distrib [fintype α] {f g : perm α} (h : f.disjoint g) (x : α) : (f * g).cycle_of x = (f.cycle_of x * g.cycle_of x) := begin cases (disjoint_iff_eq_or_eq.mp h) x with hfx hgx, { simp [h.commute.eq, cycle_of_mul_of_apply_right_eq_self h.symm.commute, hfx] }, { simp [cycle_of_mul_of_apply_right_eq_self h.commute, hgx] } end lemma support_cycle_of_eq_nil_iff [fintype α] {f : perm α} {x : α} : (f.cycle_of x).support = ∅ ↔ x ∉ f.support := by simp lemma support_cycle_of_le [fintype α] (f : perm α) (x : α) : support (f.cycle_of x) ≤ support f := begin intros y hy, rw [mem_support, cycle_of_apply] at hy, split_ifs at hy, { exact mem_support.mpr hy }, { exact absurd rfl hy } end lemma mem_support_cycle_of_iff [fintype α] {f : perm α} {x y : α} : y ∈ support (f.cycle_of x) ↔ same_cycle f x y ∧ x ∈ support f := begin by_cases hx : f x = x, { rw (cycle_of_eq_one_iff _).mpr hx, simp [hx] }, { rw [mem_support, cycle_of_apply], split_ifs with hy, { simp only [hx, hy, iff_true, ne.def, not_false_iff, and_self, mem_support], rcases hy with ⟨k, rfl⟩, rw ←not_mem_support, simpa using hx }, { simpa [hx] using hy } } end lemma same_cycle.mem_support_iff [fintype α] {f : perm α} {x y : α} (h : same_cycle f x y) : x ∈ support f ↔ y ∈ support f := ⟨λ hx, support_cycle_of_le f x (mem_support_cycle_of_iff.mpr ⟨h, hx⟩), λ hy, support_cycle_of_le f y (mem_support_cycle_of_iff.mpr ⟨h.symm, hy⟩)⟩ lemma pow_mod_card_support_cycle_of_self_apply [fintype α] (f : perm α) (n : ℕ) (x : α) : (f ^ (n % (f.cycle_of x).support.card)) x = (f ^ n) x := begin by_cases hx : f x = x, { rw [pow_apply_eq_self_of_apply_eq_self hx, pow_apply_eq_self_of_apply_eq_self hx] }, { rw [←cycle_of_pow_apply_self, ←cycle_of_pow_apply_self f, ←order_of_is_cycle (is_cycle_cycle_of f hx), ←pow_eq_mod_order_of] } end /-! ### `cycle_factors` -/ /-- Given a list `l : list α` and a permutation `f : perm α` whose nonfixed points are all in `l`, recursively factors `f` into cycles. -/ def cycle_factors_aux [fintype α] : Π (l : list α) (f : perm α), (∀ {x}, f x ≠ x → x ∈ l) → {l : list (perm α) // l.prod = f ∧ (∀ g ∈ l, is_cycle g) ∧ l.pairwise disjoint} | [] f h := ⟨[], by { simp only [imp_false, list.pairwise.nil, list.not_mem_nil, forall_const, and_true, forall_prop_of_false, not_not, not_false_iff, list.prod_nil] at *, ext, simp * }⟩ | (x::l) f h := if hx : f x = x then cycle_factors_aux l f (λ y hy, list.mem_of_ne_of_mem (λ h, hy (by rwa h)) (h hy)) else let ⟨m, hm₁, hm₂, hm₃⟩ := cycle_factors_aux l ((cycle_of f x)⁻¹ * f) (λ y hy, list.mem_of_ne_of_mem (λ h : y = x, by { rw [h, mul_apply, ne.def, inv_eq_iff_eq, cycle_of_apply_self] at hy, exact hy rfl }) (h (λ h : f y = y, by { rw [mul_apply, h, ne.def, inv_eq_iff_eq, cycle_of_apply] at hy, split_ifs at hy; cc }))) in ⟨(cycle_of f x) :: m, by { rw [list.prod_cons, hm₁], simp }, λ g hg, ((list.mem_cons_iff _ _ _).1 hg).elim (λ hg, hg.symm ▸ is_cycle_cycle_of _ hx) (hm₂ g), list.pairwise_cons.2 ⟨λ g hg y, or_iff_not_imp_left.2 (λ hfy, have hxy : same_cycle f x y := not_not.1 (mt cycle_of_apply_of_not_same_cycle hfy), have hgm : g :: m.erase g ~ m := list.cons_perm_iff_perm_erase.2 ⟨hg, list.perm.refl _⟩, have ∀ h ∈ m.erase g, disjoint g h, from (list.pairwise_cons.1 ((hgm.pairwise_iff (λ a b (h : disjoint a b), h.symm)).2 hm₃)).1, classical.by_cases id $ λ hgy : g y ≠ y, (disjoint_prod_right _ this y).resolve_right $ have hsc : same_cycle f⁻¹ x (f y), by rwa [same_cycle_inv, same_cycle_apply], by { rw [disjoint_prod_perm hm₃ hgm.symm, list.prod_cons, ← eq_inv_mul_iff_mul_eq] at hm₁, rwa [hm₁, mul_apply, mul_apply, cycle_of_inv, hsc.cycle_of_apply, inv_apply_self, inv_eq_iff_eq, eq_comm] }), hm₃⟩⟩ lemma mem_list_cycles_iff {α : Type*} [fintype α] {l : list (perm α)} (h1 : ∀ σ : perm α, σ ∈ l → σ.is_cycle) (h2 : l.pairwise disjoint) {σ : perm α} : σ ∈ l ↔ σ.is_cycle ∧ ∀ (a : α) (h4 : σ a ≠ a), σ a = l.prod a := begin suffices : σ.is_cycle → (σ ∈ l ↔ ∀ (a : α) (h4 : σ a ≠ a), σ a = l.prod a), { exact ⟨λ hσ, ⟨h1 σ hσ, (this (h1 σ hσ)).mp hσ⟩, λ hσ, (this hσ.1).mpr hσ.2⟩ }, intro h3, classical, split, { intros h a ha, exact eq_on_support_mem_disjoint h h2 _ (mem_support.mpr ha) }, { intros h, have hσl : σ.support ⊆ l.prod.support, { intros x hx, rw mem_support at hx, rwa [mem_support, ←h _ hx] }, obtain ⟨a, ha, -⟩ := id h3, rw ←mem_support at ha, obtain ⟨τ, hτ, hτa⟩ := exists_mem_support_of_mem_support_prod (hσl ha), have hτl : ∀ (x ∈ τ.support), τ x = l.prod x := eq_on_support_mem_disjoint hτ h2, have key : ∀ (x ∈ σ.support ∩ τ.support), σ x = τ x, { intros x hx, rw [h x (mem_support.mp (mem_of_mem_inter_left hx)), hτl x (mem_of_mem_inter_right hx)] }, convert hτ, refine h3.eq_on_support_inter_nonempty_congr (h1 _ hτ) key _ ha, exact key a (mem_inter_of_mem ha hτa) } end lemma list_cycles_perm_list_cycles {α : Type*} [fintype α] {l₁ l₂ : list (perm α)} (h₀ : l₁.prod = l₂.prod) (h₁l₁ : ∀ σ : perm α, σ ∈ l₁ → σ.is_cycle) (h₁l₂ : ∀ σ : perm α, σ ∈ l₂ → σ.is_cycle) (h₂l₁ : l₁.pairwise disjoint) (h₂l₂ : l₂.pairwise disjoint) : l₁ ~ l₂ := begin classical, refine (list.perm_ext (nodup_of_pairwise_disjoint_cycles h₁l₁ h₂l₁) (nodup_of_pairwise_disjoint_cycles h₁l₂ h₂l₂)).mpr (λ σ, _), by_cases hσ : σ.is_cycle, { obtain ⟨a, ha⟩ := not_forall.mp (mt ext hσ.ne_one), rw [mem_list_cycles_iff h₁l₁ h₂l₁, mem_list_cycles_iff h₁l₂ h₂l₂, h₀] }, { exact iff_of_false (mt (h₁l₁ σ) hσ) (mt (h₁l₂ σ) hσ) } end /-- Factors a permutation `f` into a list of disjoint cyclic permutations that multiply to `f`. -/ def cycle_factors [fintype α] [linear_order α] (f : perm α) : {l : list (perm α) // l.prod = f ∧ (∀ g ∈ l, is_cycle g) ∧ l.pairwise disjoint} := cycle_factors_aux (univ.sort (≤)) f (λ _ _, (mem_sort _).2 (mem_univ _)) /-- Factors a permutation `f` into a list of disjoint cyclic permutations that multiply to `f`, without a linear order. -/ def trunc_cycle_factors [fintype α] (f : perm α) : trunc {l : list (perm α) // l.prod = f ∧ (∀ g ∈ l, is_cycle g) ∧ l.pairwise disjoint} := quotient.rec_on_subsingleton (@univ α _).1 (λ l h, trunc.mk (cycle_factors_aux l f h)) (show ∀ x, f x ≠ x → x ∈ (@univ α _).1, from λ _ _, mem_univ _) section cycle_factors_finset variables [fintype α] (f : perm α) /-- Factors a permutation `f` into a `finset` of disjoint cyclic permutations that multiply to `f`. -/ def cycle_factors_finset : finset (perm α) := (trunc_cycle_factors f).lift (λ (l : {l : list (perm α) // l.prod = f ∧ (∀ g ∈ l, is_cycle g) ∧ l.pairwise disjoint}), l.val.to_finset) (λ ⟨l, hl⟩ ⟨l', hl'⟩, list.to_finset_eq_of_perm _ _ (list_cycles_perm_list_cycles (hl'.left.symm ▸ hl.left) hl.right.left (hl'.right.left) hl.right.right hl'.right.right)) lemma cycle_factors_finset_eq_list_to_finset {σ : perm α} {l : list (perm α)} (hn : l.nodup) : σ.cycle_factors_finset = l.to_finset ↔ (∀ f : perm α, f ∈ l → f.is_cycle) ∧ l.pairwise disjoint ∧ l.prod = σ := begin obtain ⟨⟨l', hp', hc', hd'⟩, hl⟩ := trunc.exists_rep σ.trunc_cycle_factors, have ht : cycle_factors_finset σ = l'.to_finset, { rw [cycle_factors_finset, ←hl, trunc.lift_mk] }, rw ht, split, { intro h, have hn' : l'.nodup := nodup_of_pairwise_disjoint_cycles hc' hd', have hperm : l ~ l' := list.perm_of_nodup_nodup_to_finset_eq hn hn' h.symm, refine ⟨_, _, _⟩, { exact λ _ h, hc' _ (hperm.subset h)}, { rwa list.perm.pairwise_iff disjoint.symmetric hperm }, { rw [←hp', hperm.symm.prod_eq'], refine hd'.imp _, exact λ _ _, disjoint.commute } }, { rintro ⟨hc, hd, hp⟩, refine list.to_finset_eq_of_perm _ _ _, refine list_cycles_perm_list_cycles _ hc' hc hd' hd, rw [hp, hp'] } end lemma cycle_factors_finset_eq_finset {σ : perm α} {s : finset (perm α)} : σ.cycle_factors_finset = s ↔ (∀ f : perm α, f ∈ s → f.is_cycle) ∧ (∃ h : (∀ (a ∈ s) (b ∈ s), a ≠ b → disjoint a b), s.noncomm_prod id (λ a ha b hb, (em (a = b)).by_cases (λ h, h ▸ commute.refl a) (set.pairwise_on.mono' (λ _ _, disjoint.commute) h a ha b hb)) = σ) := begin obtain ⟨l, hl, rfl⟩ := s.exists_list_nodup_eq, rw cycle_factors_finset_eq_list_to_finset hl, simp only [noncomm_prod_to_finset, hl, exists_prop, list.mem_to_finset, and.congr_left_iff, and.congr_right_iff, list.map_id, ne.def], intros, exact ⟨list.forall_of_pairwise disjoint.symmetric, hl.pairwise_of_forall_ne⟩ end lemma cycle_factors_finset_pairwise_disjoint (p : perm α) (hp : p ∈ cycle_factors_finset f) (q : perm α) (hq : q ∈ cycle_factors_finset f) (h : p ≠ q) : disjoint p q := begin have : f.cycle_factors_finset = f.cycle_factors_finset := rfl, obtain ⟨-, hd, -⟩ := cycle_factors_finset_eq_finset.mp this, exact hd p hp q hq h end lemma cycle_factors_finset_mem_commute (p : perm α) (hp : p ∈ cycle_factors_finset f) (q : perm α) (hq : q ∈ cycle_factors_finset f) : _root_.commute p q := begin by_cases h : p = q, { exact h ▸ commute.refl _ }, { exact (cycle_factors_finset_pairwise_disjoint _ _ hp _ hq h).commute } end /-- The product of cycle factors is equal to the original `f : perm α`. -/ lemma cycle_factors_finset_noncomm_prod (comm : ∀ (g ∈ f.cycle_factors_finset) (h ∈ f.cycle_factors_finset), commute (id g) (id h) := cycle_factors_finset_mem_commute f) : f.cycle_factors_finset.noncomm_prod id (comm) = f := begin have : f.cycle_factors_finset = f.cycle_factors_finset := rfl, obtain ⟨-, hd, hp⟩ := cycle_factors_finset_eq_finset.mp this, exact hp end lemma mem_cycle_factors_finset_iff {f p : perm α} : p ∈ cycle_factors_finset f ↔ p.is_cycle ∧ ∀ (a ∈ p.support), p a = f a := begin obtain ⟨l, hl, hl'⟩ := f.cycle_factors_finset.exists_list_nodup_eq, rw ←hl', rw [eq_comm, cycle_factors_finset_eq_list_to_finset hl] at hl', simpa [list.mem_to_finset, ne.def, ←hl'.right.right] using mem_list_cycles_iff hl'.left hl'.right.left end lemma cycle_of_mem_cycle_factors_finset_iff {f : perm α} {x : α} : cycle_of f x ∈ cycle_factors_finset f ↔ x ∈ f.support := begin rw mem_cycle_factors_finset_iff, split, { rintro ⟨hc, h⟩, contrapose! hc, rw [not_mem_support, ←cycle_of_eq_one_iff] at hc, simp [hc] }, { intros hx, refine ⟨is_cycle_cycle_of _ (mem_support.mp hx), _⟩, intros y hy, rw mem_support at hy, rw cycle_of_apply, split_ifs with H, { refl }, { rw cycle_of_apply_of_not_same_cycle H at hy, contradiction } } end lemma mem_cycle_factors_finset_support_le {p f : perm α} (h : p ∈ cycle_factors_finset f) : p.support ≤ f.support := begin rw mem_cycle_factors_finset_iff at h, intros x hx, rwa [mem_support, ←h.right x hx, ←mem_support] end lemma cycle_factors_finset_eq_empty_iff {f : perm α} : cycle_factors_finset f = ∅ ↔ f = 1 := by simpa [cycle_factors_finset_eq_finset] using eq_comm @[simp] lemma cycle_factors_finset_one : cycle_factors_finset (1 : perm α) = ∅ := by simp [cycle_factors_finset_eq_empty_iff] @[simp] lemma cycle_factors_finset_eq_singleton_self_iff {f : perm α} : f.cycle_factors_finset = {f} ↔ f.is_cycle := by simp [cycle_factors_finset_eq_finset] lemma is_cycle.cycle_factors_finset_eq_singleton {f : perm α} (hf : is_cycle f) : f.cycle_factors_finset = {f} := cycle_factors_finset_eq_singleton_self_iff.mpr hf lemma cycle_factors_finset_eq_singleton_iff {f g : perm α} : f.cycle_factors_finset = {g} ↔ f.is_cycle ∧ f = g := begin suffices : f = g → (g.is_cycle ↔ f.is_cycle), { simpa [cycle_factors_finset_eq_finset, eq_comm] }, rintro rfl, exact iff.rfl end /-- Two permutations `f g : perm α` have the same cycle factors iff they are the same. -/ lemma cycle_factors_finset_injective : function.injective (@cycle_factors_finset α _ _) := begin intros f g h, rw ←cycle_factors_finset_noncomm_prod f, simpa [h] using cycle_factors_finset_noncomm_prod g end lemma disjoint.disjoint_cycle_factors_finset {f g : perm α} (h : disjoint f g) : _root_.disjoint (cycle_factors_finset f) (cycle_factors_finset g) := begin rw disjoint_iff_disjoint_support at h, intros x hx, simp only [mem_cycle_factors_finset_iff, inf_eq_inter, mem_inter, mem_support] at hx, obtain ⟨⟨⟨a, ha, -⟩, hf⟩, -, hg⟩ := hx, refine h (_ : a ∈ f.support ∩ g.support), simp [ha, ←hf a ha, ←hg a ha] end lemma disjoint.cycle_factors_finset_mul_eq_union {f g : perm α} (h : disjoint f g) : cycle_factors_finset (f * g) = cycle_factors_finset f ∪ cycle_factors_finset g := begin rw cycle_factors_finset_eq_finset, split, { simp only [mem_cycle_factors_finset_iff, mem_union], rintro _ (⟨h, -⟩ | ⟨h, -⟩); exact h }, { refine ⟨_, _⟩, { simp_rw mem_union, rintros x (hx | hx) y (hy | hy) hxy, { exact cycle_factors_finset_pairwise_disjoint _ _ hx _ hy hxy }, { exact h.mono (mem_cycle_factors_finset_support_le hx) (mem_cycle_factors_finset_support_le hy) }, { exact h.symm.mono (mem_cycle_factors_finset_support_le hx) (mem_cycle_factors_finset_support_le hy) }, { exact cycle_factors_finset_pairwise_disjoint _ _ hx _ hy hxy } }, { rw noncomm_prod_union_of_disjoint h.disjoint_cycle_factors_finset, rw [cycle_factors_finset_noncomm_prod, cycle_factors_finset_noncomm_prod] } } end lemma disjoint_mul_inv_of_mem_cycle_factors_finset {f g : perm α} (h : f ∈ cycle_factors_finset g) : disjoint (g * f⁻¹) f := begin rw mem_cycle_factors_finset_iff at h, intro x, by_cases hx : f x = x, { exact or.inr hx }, { refine or.inl _, rw [mul_apply, ←h.right, apply_inv_self], rwa [←support_inv, apply_mem_support, support_inv, mem_support] } end end cycle_factors_finset @[elab_as_eliminator] lemma cycle_induction_on [fintype β] (P : perm β → Prop) (σ : perm β) (base_one : P 1) (base_cycles : ∀ σ : perm β, σ.is_cycle → P σ) (induction_disjoint : ∀ σ τ : perm β, disjoint σ τ → is_cycle σ → P σ → P τ → P (σ * τ)) : P σ := begin suffices : ∀ l : list (perm β), (∀ τ : perm β, τ ∈ l → τ.is_cycle) → l.pairwise disjoint → P l.prod, { classical, let x := σ.trunc_cycle_factors.out, exact (congr_arg P x.2.1).mp (this x.1 x.2.2.1 x.2.2.2) }, intro l, induction l with σ l ih, { exact λ _ _, base_one }, { intros h1 h2, rw list.prod_cons, exact induction_disjoint σ l.prod (disjoint_prod_right _ (list.pairwise_cons.mp h2).1) (h1 _ (list.mem_cons_self _ _)) (base_cycles σ (h1 σ (l.mem_cons_self σ))) (ih (λ τ hτ, h1 τ (list.mem_cons_of_mem σ hτ)) (list.pairwise_of_pairwise_cons h2)) }, end lemma cycle_factors_finset_mul_inv_mem_eq_sdiff [fintype α] {f g : perm α} (h : f ∈ cycle_factors_finset g) : cycle_factors_finset (g * f⁻¹) = (cycle_factors_finset g) \ {f} := begin revert f, apply cycle_induction_on _ g, { simp }, { intros σ hσ f hf, simp only [cycle_factors_finset_eq_singleton_self_iff.mpr hσ, mem_singleton] at hf ⊢, simp [hf] }, { intros σ τ hd hc hσ hτ f, simp_rw [hd.cycle_factors_finset_mul_eq_union, mem_union], -- if only `wlog` could work here... rintro (hf | hf), { rw [hd.commute.eq, union_comm, union_sdiff_distrib, sdiff_singleton_eq_erase, erase_eq_of_not_mem, mul_assoc, disjoint.cycle_factors_finset_mul_eq_union, hσ hf], { rw mem_cycle_factors_finset_iff at hf, intro x, cases hd.symm x with hx hx, { exact or.inl hx }, { refine or.inr _, by_cases hfx : f x = x, { rw ←hfx, simpa [hx] using hfx.symm }, { rw mul_apply, rw ←hf.right _ (mem_support.mpr hfx) at hx, contradiction } } }, { exact λ H, hd.disjoint_cycle_factors_finset (mem_inter_of_mem hf H) } }, { rw [union_sdiff_distrib, sdiff_singleton_eq_erase, erase_eq_of_not_mem, mul_assoc, disjoint.cycle_factors_finset_mul_eq_union, hτ hf], { rw mem_cycle_factors_finset_iff at hf, intro x, cases hd x with hx hx, { exact or.inl hx }, { refine or.inr _, by_cases hfx : f x = x, { rw ←hfx, simpa [hx] using hfx.symm }, { rw mul_apply, rw ←hf.right _ (mem_support.mpr hfx) at hx, contradiction } } }, { exact λ H, hd.disjoint_cycle_factors_finset (mem_inter_of_mem H hf) } } } end lemma same_cycle.nat_of_mem_support [fintype α] (f : perm α) {x y : α} (h : same_cycle f x y) (hx : x ∈ f.support) : ∃ (i : ℕ) (hi' : i < (f.cycle_of x).support.card), (f ^ i) x = y := begin revert f, intro f, apply cycle_induction_on _ f, { simp }, { intros g hg H hx, rw mem_support at hx, rw [hg.cycle_of_eq hx, ←order_of_is_cycle hg], exact H.nat' }, { rintros g h hd hg IH IH' ⟨m, rfl⟩ hx, cases (disjoint_iff_eq_or_eq.mp hd) x with hgx hhx, { have hpow : ∀ (k : ℤ), ((g * h) ^ k) x = (h ^ k) x, { intro k, suffices : (g ^ k) x = x, { simpa [hd.commute.eq, hd.commute.symm.mul_gpow] }, rw gpow_apply_eq_self_of_apply_eq_self, simpa using hgx }, obtain ⟨k, hk, hk'⟩ := IH' _ _, { refine ⟨k, _, _⟩, { rw [←cycle_of_eq_one_iff] at hgx, rwa [hd.cycle_of_mul_distrib, hgx, one_mul] }, { simpa [←gpow_coe_nat, hpow] using hk' } }, { use m, simp [hpow] }, { rw [mem_support, hd.commute.eq] at hx, simpa [hgx] using hx } }, { have hpow : ∀ (k : ℤ), ((g * h) ^ k) x = (g ^ k) x, { intro k, suffices : (h ^ k) x = x, { simpa [hd.commute.mul_gpow] }, rw gpow_apply_eq_self_of_apply_eq_self, simpa using hhx }, obtain ⟨k, hk, hk'⟩ := IH _ _, { refine ⟨k, _, _⟩, { rw [←cycle_of_eq_one_iff] at hhx, rwa [hd.cycle_of_mul_distrib, hhx, mul_one] }, { simpa [←gpow_coe_nat, hpow] using hk' } }, { use m, simp [hpow] }, { simpa [hhx] using hx } } } end lemma same_cycle.nat [fintype α] (f : perm α) {x y : α} (h : same_cycle f x y) : ∃ (i : ℕ) (hi : 0 < i) (hi' : i ≤ (f.cycle_of x).support.card + 1), (f ^ i) x = y := begin by_cases hx : x ∈ f.support, { obtain ⟨k, hk, hk'⟩ := same_cycle.nat_of_mem_support f h hx, cases k, { refine ⟨(f.cycle_of x).support.card, _, self_le_add_right _ _, _⟩, { refine zero_lt_one.trans (one_lt_card_support_of_ne_one _), simpa using hx }, { simp only [perm.coe_one, id.def, pow_zero] at hk', subst hk', rw [←order_of_is_cycle (is_cycle_cycle_of _ (mem_support.mp hx)), ←cycle_of_pow_apply_self, pow_order_of_eq_one, one_apply] } }, { exact ⟨k + 1, by simp, nat.le_succ_of_le hk.le, hk'⟩ } }, { refine ⟨1, zero_lt_one, by simp, _⟩, obtain ⟨k, rfl⟩ := h, rw [not_mem_support] at hx, rw [pow_apply_eq_self_of_apply_eq_self hx, gpow_apply_eq_self_of_apply_eq_self hx] } end section generation variables [fintype α] [fintype β] open subgroup lemma closure_is_cycle : closure {σ : perm β | is_cycle σ} = ⊤ := begin classical, exact top_le_iff.mp (le_trans (ge_of_eq closure_is_swap) (closure_mono (λ _, is_swap.is_cycle))), end lemma closure_cycle_adjacent_swap {σ : perm α} (h1 : is_cycle σ) (h2 : σ.support = ⊤) (x : α) : closure ({σ, swap x (σ x)} : set (perm α)) = ⊤ := begin let H := closure ({σ, swap x (σ x)} : set (perm α)), have h3 : σ ∈ H := subset_closure (set.mem_insert σ _), have h4 : swap x (σ x) ∈ H := subset_closure (set.mem_insert_of_mem _ (set.mem_singleton _)), have step1 : ∀ (n : ℕ), swap ((σ ^ n) x) ((σ^(n+1)) x) ∈ H, { intro n, induction n with n ih, { exact subset_closure (set.mem_insert_of_mem _ (set.mem_singleton _)) }, { convert H.mul_mem (H.mul_mem h3 ih) (H.inv_mem h3), rw [mul_swap_eq_swap_mul, mul_inv_cancel_right], refl } }, have step2 : ∀ (n : ℕ), swap x ((σ ^ n) x) ∈ H, { intro n, induction n with n ih, { convert H.one_mem, exact swap_self x }, { by_cases h5 : x = (σ ^ n) x, { rw [pow_succ, mul_apply, ←h5], exact h4 }, by_cases h6 : x = (σ^(n+1)) x, { rw [←h6, swap_self], exact H.one_mem }, rw [swap_comm, ←swap_mul_swap_mul_swap h5 h6], exact H.mul_mem (H.mul_mem (step1 n) ih) (step1 n) } }, have step3 : ∀ (y : α), swap x y ∈ H, { intro y, have hx : x ∈ (⊤ : finset α) := finset.mem_univ x, rw [←h2, mem_support] at hx, have hy : y ∈ (⊤ : finset α) := finset.mem_univ y, rw [←h2, mem_support] at hy, cases is_cycle.exists_pow_eq h1 hx hy with n hn, rw ← hn, exact step2 n }, have step4 : ∀ (y z : α), swap y z ∈ H, { intros y z, by_cases h5 : z = x, { rw [h5, swap_comm], exact step3 y }, by_cases h6 : z = y, { rw [h6, swap_self], exact H.one_mem }, rw [←swap_mul_swap_mul_swap h5 h6, swap_comm z x], exact H.mul_mem (H.mul_mem (step3 y) (step3 z)) (step3 y) }, rw [eq_top_iff, ←closure_is_swap, closure_le], rintros τ ⟨y, z, h5, h6⟩, rw h6, exact step4 y z, end lemma closure_cycle_coprime_swap {n : ℕ} {σ : perm α} (h0 : nat.coprime n (fintype.card α)) (h1 : is_cycle σ) (h2 : σ.support = finset.univ) (x : α) : closure ({σ, swap x ((σ ^ n) x)} : set (perm α)) = ⊤ := begin rw [←finset.card_univ, ←h2, ←order_of_is_cycle h1] at h0, cases exists_pow_eq_self_of_coprime h0 with m hm, have h2' : (σ ^ n).support = ⊤ := eq.trans (support_pow_coprime h0) h2, have h1' : is_cycle ((σ ^ n) ^ (m : ℤ)) := by rwa ← hm at h1, replace h1' : is_cycle (σ ^ n) := is_cycle_of_is_cycle_pow h1' (le_trans (support_pow_le σ n) (ge_of_eq (congr_arg support hm))), rw [eq_top_iff, ←closure_cycle_adjacent_swap h1' h2' x, closure_le, set.insert_subset], exact ⟨subgroup.pow_mem (closure _) (subset_closure (set.mem_insert σ _)) n, set.singleton_subset_iff.mpr (subset_closure (set.mem_insert_of_mem _ (set.mem_singleton _)))⟩, end lemma closure_prime_cycle_swap {σ τ : perm α} (h0 : (fintype.card α).prime) (h1 : is_cycle σ) (h2 : σ.support = finset.univ) (h3 : is_swap τ) : closure ({σ, τ} : set (perm α)) = ⊤ := begin obtain ⟨x, y, h4, h5⟩ := h3, obtain ⟨i, hi⟩ := h1.exists_pow_eq (mem_support.mp ((finset.ext_iff.mp h2 x).mpr (finset.mem_univ x))) (mem_support.mp ((finset.ext_iff.mp h2 y).mpr (finset.mem_univ y))), rw [h5, ←hi], refine closure_cycle_coprime_swap (nat.coprime.symm (h0.coprime_iff_not_dvd.mpr (λ h, h4 _))) h1 h2 x, cases h with m hm, rwa [hm, pow_mul, ←finset.card_univ, ←h2, ←order_of_is_cycle h1, pow_order_of_eq_one, one_pow, one_apply] at hi, end end generation section variables [fintype α] {σ τ : perm α} noncomputable theory lemma is_conj_of_support_equiv (f : {x // x ∈ (σ.support : set α)} ≃ {x // x ∈ (τ.support : set α)}) (hf : ∀ (x : α) (hx : x ∈ (σ.support : set α)), (f ⟨σ x, apply_mem_support.2 hx⟩ : α) = τ ↑(f ⟨x,hx⟩)) : is_conj σ τ := begin refine is_conj_iff.2 ⟨equiv.extend_subtype f, _⟩, rw mul_inv_eq_iff_eq_mul, ext, simp only [perm.mul_apply], by_cases hx : x ∈ σ.support, { rw [equiv.extend_subtype_apply_of_mem, equiv.extend_subtype_apply_of_mem], { exact hf x (finset.mem_coe.2 hx) } }, { rwa [not_not.1 ((not_congr mem_support).1 (equiv.extend_subtype_not_mem f _ _)), not_not.1 ((not_congr mem_support).mp hx)] } end theorem is_cycle.is_conj (hσ : is_cycle σ) (hτ : is_cycle τ) (h : σ.support.card = τ.support.card) : is_conj σ τ := begin refine is_conj_of_support_equiv (hσ.gpowers_equiv_support.symm.trans ((gpowers_equiv_gpowers begin rw [order_of_is_cycle hσ, h, order_of_is_cycle hτ], end).trans hτ.gpowers_equiv_support)) _, intros x hx, simp only [perm.mul_apply, equiv.trans_apply, equiv.sum_congr_apply], obtain ⟨n, rfl⟩ := hσ.exists_pow_eq (classical.some_spec hσ).1 (mem_support.1 hx), apply eq.trans _ (congr rfl (congr rfl (congr rfl (congr rfl (hσ.gpowers_equiv_support_symm_apply n).symm)))), apply (congr rfl (congr rfl (congr rfl (hσ.gpowers_equiv_support_symm_apply (n + 1))))).trans _, simp only [ne.def, is_cycle.gpowers_equiv_support_apply, subtype.coe_mk, gpowers_equiv_gpowers_apply], rw [pow_succ, perm.mul_apply], end theorem is_cycle.is_conj_iff (hσ : is_cycle σ) (hτ : is_cycle τ) : is_conj σ τ ↔ σ.support.card = τ.support.card := ⟨begin intro h, obtain ⟨π, rfl⟩ := is_conj_iff.1 h, apply finset.card_congr (λ a ha, π a) (λ _ ha, _) (λ _ _ _ _ ab, π.injective ab) (λ b hb, _), { simp [mem_support.1 ha] }, { refine ⟨π⁻¹ b, ⟨_, π.apply_inv_self b⟩⟩, contrapose! hb, rw [mem_support, not_not] at hb, rw [mem_support, not_not, perm.mul_apply, perm.mul_apply, hb, perm.apply_inv_self] } end, hσ.is_conj hτ⟩ @[simp] lemma support_conj : (σ * τ * σ⁻¹).support = τ.support.map σ.to_embedding := begin ext, simp only [mem_map_equiv, perm.coe_mul, comp_app, ne.def, perm.mem_support, equiv.eq_symm_apply], refl, end lemma card_support_conj : (σ * τ * σ⁻¹).support.card = τ.support.card := by simp end theorem disjoint.is_conj_mul {α : Type*} [fintype α] {σ τ π ρ : perm α} (hc1 : is_conj σ π) (hc2 : is_conj τ ρ) (hd1 : disjoint σ τ) (hd2 : disjoint π ρ) : is_conj (σ * τ) (π * ρ) := begin classical, obtain ⟨f, rfl⟩ := is_conj_iff.1 hc1, obtain ⟨g, rfl⟩ := is_conj_iff.1 hc2, have hd1' := coe_inj.2 hd1.support_mul, have hd2' := coe_inj.2 hd2.support_mul, rw [coe_union] at *, have hd1'' := disjoint_iff_disjoint_coe.1 (disjoint_iff_disjoint_support.1 hd1), have hd2'' := disjoint_iff_disjoint_coe.1 (disjoint_iff_disjoint_support.1 hd2), refine is_conj_of_support_equiv _ _, { refine ((equiv.set.of_eq hd1').trans (equiv.set.union hd1'')).trans ((equiv.sum_congr (subtype_equiv f (λ a, _)) (subtype_equiv g (λ a, _))).trans ((equiv.set.of_eq hd2').trans (equiv.set.union hd2'')).symm); { simp only [set.mem_image, to_embedding_apply, exists_eq_right, support_conj, coe_map, apply_eq_iff_eq] } }, { intros x hx, simp only [trans_apply, symm_trans_apply, set.of_eq_apply, set.of_eq_symm_apply, equiv.sum_congr_apply], rw [hd1', set.mem_union] at hx, cases hx with hxσ hxτ, { rw [mem_coe, mem_support] at hxσ, rw [set.union_apply_left hd1'' _, set.union_apply_left hd1'' _], simp only [subtype_equiv_apply, perm.coe_mul, sum.map_inl, comp_app, set.union_symm_apply_left, subtype.coe_mk, apply_eq_iff_eq], { have h := (hd2 (f x)).resolve_left _, { rw [mul_apply, mul_apply] at h, rw [h, inv_apply_self, (hd1 x).resolve_left hxσ] }, { rwa [mul_apply, mul_apply, inv_apply_self, apply_eq_iff_eq] } }, { rwa [subtype.coe_mk, subtype.coe_mk, mem_coe, mem_support] }, { rwa [subtype.coe_mk, subtype.coe_mk, perm.mul_apply, (hd1 x).resolve_left hxσ, mem_coe, apply_mem_support, mem_support] } }, { rw [mem_coe, ← apply_mem_support, mem_support] at hxτ, rw [set.union_apply_right hd1'' _, set.union_apply_right hd1'' _], simp only [subtype_equiv_apply, perm.coe_mul, sum.map_inr, comp_app, set.union_symm_apply_right, subtype.coe_mk, apply_eq_iff_eq], { have h := (hd2 (g (τ x))).resolve_right _, { rw [mul_apply, mul_apply] at h, rw [inv_apply_self, h, (hd1 (τ x)).resolve_right hxτ] }, { rwa [mul_apply, mul_apply, inv_apply_self, apply_eq_iff_eq] } }, { rwa [subtype.coe_mk, subtype.coe_mk, mem_coe, ← apply_mem_support, mem_support] }, { rwa [subtype.coe_mk, subtype.coe_mk, perm.mul_apply, (hd1 (τ x)).resolve_right hxτ, mem_coe, mem_support] } } } end section fixed_points /-! ### Fixed points -/ lemma fixed_point_card_lt_of_ne_one [fintype α] {σ : perm α} (h : σ ≠ 1) : (filter (λ x, σ x = x) univ).card < fintype.card α - 1 := begin rw [lt_sub_iff_left, ← lt_sub_iff_right, ← finset.card_compl, finset.compl_filter], exact one_lt_card_support_of_ne_one h end end fixed_points end equiv.perm
584a7b1a45507a1125ec1f3ab19d8378da152d1c
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/linear_algebra/matrix/block.lean
0ce6585c06e1f9733020268cc4b87ea76bf290c1
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
12,737
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, Patrick Massot, Casper Putz, Anne Baanen -/ import linear_algebra.matrix.determinant import linear_algebra.matrix.nonsingular_inverse import tactic.fin_cases /-! # Block matrices and their determinant This file defines a predicate `matrix.block_triangular` saying a matrix is block triangular, and proves the value of the determinant for various matrices built out of blocks. ## Main definitions * `matrix.block_triangular` expresses that a `o` by `o` matrix is block triangular, if the rows and columns are ordered according to some order `b : o → α` ## Main results * `matrix.det_of_block_triangular`: the determinant of a block triangular matrix is equal to the product of the determinants of all the blocks * `matrix.det_of_upper_triangular` and `matrix.det_of_lower_triangular`: the determinant of a triangular matrix is the product of the entries along the diagonal ## Tags matrix, diagonal, det, block triangular -/ open finset function order_dual open_locale big_operators matrix universes v variables {α β m n o : Type*} {m' n' : α → Type*} variables {R : Type v} [comm_ring R] {M N : matrix m m R} {b : m → α} namespace matrix section has_lt variables [has_lt α] /-- Let `b` map rows and columns of a square matrix `M` to blocks indexed by `α`s. Then `block_triangular M n b` says the matrix is block triangular. -/ def block_triangular (M : matrix m m R) (b : m → α) : Prop := ∀ ⦃i j⦄, b j < b i → M i j = 0 @[simp] protected lemma block_triangular.submatrix {f : n → m} (h : M.block_triangular b) : (M.submatrix f f).block_triangular (b ∘ f) := λ i j hij, h hij lemma block_triangular_reindex_iff {b : n → α} {e : m ≃ n} : (reindex e e M).block_triangular b ↔ M.block_triangular (b ∘ e) := begin refine ⟨λ h, _, λ h, _⟩, { convert h.submatrix, simp only [reindex_apply, submatrix_submatrix, submatrix_id_id, equiv.symm_comp_self] }, { convert h.submatrix, simp only [comp.assoc b e e.symm, equiv.self_comp_symm, comp.right_id] } end protected lemma block_triangular.transpose : M.block_triangular b → Mᵀ.block_triangular (to_dual ∘ b) := swap @[simp] protected lemma block_triangular_transpose_iff {b : m → αᵒᵈ} : Mᵀ.block_triangular b ↔ M.block_triangular (of_dual ∘ b) := forall_swap @[simp] lemma block_triangular_zero : block_triangular (0 : matrix m m R) b := λ i j h, rfl protected lemma block_triangular.neg (hM : block_triangular M b) : block_triangular (-M) b := λ i j h, neg_eq_zero.2 $ hM h lemma block_triangular.add (hM : block_triangular M b) (hN : block_triangular N b) : block_triangular (M + N) b := λ i j h, by simp_rw [pi.add_apply, hM h, hN h, zero_add] lemma block_triangular.sub (hM : block_triangular M b) (hN : block_triangular N b) : block_triangular (M - N) b := λ i j h, by simp_rw [pi.sub_apply, hM h, hN h, sub_zero] end has_lt section preorder variables [preorder α] lemma block_triangular_diagonal [decidable_eq m] (d : m → R) : block_triangular (diagonal d) b := λ i j h, diagonal_apply_ne' d (λ h', ne_of_lt h (congr_arg _ h')) lemma block_triangular_block_diagonal' [decidable_eq α] (d : Π (i : α), matrix (m' i) (m' i) R) : block_triangular (block_diagonal' d) sigma.fst := begin rintros ⟨i, i'⟩ ⟨j, j'⟩ h, apply block_diagonal'_apply_ne d i' j' (λ h', ne_of_lt h h'.symm), end lemma block_triangular_block_diagonal [decidable_eq α] (d : α → matrix m m R) : block_triangular (block_diagonal d) prod.snd := begin rintros ⟨i, i'⟩ ⟨j, j'⟩ h, rw [block_diagonal'_eq_block_diagonal, block_triangular_block_diagonal'], exact h end end preorder section linear_order variables [linear_order α] lemma block_triangular.mul [fintype m] {M N : matrix m m R} (hM : block_triangular M b) (hN : block_triangular N b): block_triangular (M * N) b := begin intros i j hij, apply finset.sum_eq_zero, intros k hk, by_cases hki : b k < b i, { simp_rw [hM hki, zero_mul] }, { simp_rw [hN (lt_of_lt_of_le hij (le_of_not_lt hki)), mul_zero] }, end end linear_order lemma upper_two_block_triangular [preorder α] (A : matrix m m R) (B : matrix m n R) (D : matrix n n R) {a b : α} (hab : a < b) : block_triangular (from_blocks A B 0 D) (sum.elim (λ i, a) (λ j, b)) := by rintro (c | c) (d | d) hcd; simpa [hab.not_lt] using hcd <|> simp /-! ### Determinant -/ variables [decidable_eq m] [fintype m] [decidable_eq n] [fintype n] lemma equiv_block_det (M : matrix m m R) {p q : m → Prop} [decidable_pred p] [decidable_pred q] (e : ∀ x, q x ↔ p x) : (to_square_block_prop M p).det = (to_square_block_prop M q).det := by convert matrix.det_reindex_self (equiv.subtype_equiv_right e) (to_square_block_prop M q) @[simp] lemma det_to_square_block_id (M : matrix m m R) (i : m) : (M.to_square_block id i).det = M i i := begin letI : unique {a // id a = i} := ⟨⟨⟨i, rfl⟩⟩, λ j, subtype.ext j.property⟩, exact (det_unique _).trans rfl, end lemma det_to_block (M : matrix m m R) (p : m → Prop) [decidable_pred p] : M.det = (from_blocks (to_block M p p) (to_block M p $ λ j, ¬p j) (to_block M (λ j, ¬p j) p) $ to_block M (λ j, ¬p j) $ λ j, ¬p j).det := begin rw ←matrix.det_reindex_self (equiv.sum_compl p).symm M, rw [det_apply', det_apply'], congr, ext σ, congr, ext, generalize hy : σ x = y, cases x; cases y; simp only [matrix.reindex_apply, to_block_apply, equiv.symm_symm, equiv.sum_compl_apply_inr, equiv.sum_compl_apply_inl, from_blocks_apply₁₁, from_blocks_apply₁₂, from_blocks_apply₂₁, from_blocks_apply₂₂, matrix.submatrix_apply], end lemma two_block_triangular_det (M : matrix m m R) (p : m → Prop) [decidable_pred p] (h : ∀ i, ¬ p i → ∀ j, p j → M i j = 0) : M.det = (to_square_block_prop M p).det * (to_square_block_prop M (λ i, ¬p i)).det := begin rw det_to_block M p, convert det_from_blocks_zero₂₁ (to_block M p p) (to_block M p (λ j, ¬p j)) (to_block M (λ j, ¬p j) (λ j, ¬p j)), ext, exact h ↑i i.2 ↑j j.2 end lemma two_block_triangular_det' (M : matrix m m R) (p : m → Prop) [decidable_pred p] (h : ∀ i, p i → ∀ j, ¬ p j → M i j = 0) : M.det = (to_square_block_prop M p).det * (to_square_block_prop M (λ i, ¬p i)).det := begin rw [M.two_block_triangular_det (λ i, ¬ p i), mul_comm], simp_rw not_not, congr' 1, exact equiv_block_det _ (λ _, not_not.symm), simpa only [not_not] using h, end protected lemma block_triangular.det [decidable_eq α] [linear_order α] (hM : block_triangular M b) : M.det = ∏ a in univ.image b, (M.to_square_block b a).det := begin unfreezingI { induction hs : univ.image b using finset.strong_induction with s ih generalizing m }, subst hs, casesI is_empty_or_nonempty m, { simp }, let k := (univ.image b).max' (univ_nonempty.image _), rw two_block_triangular_det' M (λ i, b i = k), { have : univ.image b = insert k ((univ.image b).erase k), { rw insert_erase, apply max'_mem }, rw [this, prod_insert (not_mem_erase _ _)], refine congr_arg _ _, let b' := λ i : {a // b a ≠ k}, b ↑i, have h' : block_triangular (M.to_square_block_prop (λ i, b i ≠ k)) b' := hM.submatrix, have hb' : image b' univ = (image b univ).erase k, { convert image_subtype_ne_univ_eq_image_erase k b }, rw ih _ (erase_ssubset $ max'_mem _ _) h' hb', refine finset.prod_congr rfl (λ l hl, _), let he : {a // b' a = l} ≃ {a // b a = l}, { have hc : ∀ i, b i = l → b i ≠ k := λ i hi, ne_of_eq_of_ne hi (ne_of_mem_erase hl), exact equiv.subtype_subtype_equiv_subtype hc }, simp only [to_square_block_def], rw ← matrix.det_reindex_self he.symm (λ (i j : {a // b a = l}), M ↑i ↑j), refl }, { intros i hi j hj, apply hM, rw hi, apply lt_of_le_of_ne _ hj, exact finset.le_max' (univ.image b) _ (mem_image_of_mem _ (mem_univ _)) } end lemma block_triangular.det_fintype [decidable_eq α] [fintype α] [linear_order α] (h : block_triangular M b) : M.det = ∏ k : α, (M.to_square_block b k).det := begin refine h.det.trans (prod_subset (subset_univ _) $ λ a _ ha, _), have : is_empty {i // b i = a} := ⟨λ i, ha $ mem_image.2 ⟨i, mem_univ _, i.2⟩⟩, exactI det_is_empty, end lemma det_of_upper_triangular [linear_order m] (h : M.block_triangular id) : M.det = ∏ i : m, M i i := begin haveI : decidable_eq R := classical.dec_eq _, simp_rw [h.det, image_id, det_to_square_block_id], end lemma det_of_lower_triangular [linear_order m] (M : matrix m m R) (h : M.block_triangular to_dual) : M.det = ∏ i : m, M i i := by { rw ←det_transpose, exact det_of_upper_triangular h.transpose } /-! ### Invertible -/ lemma block_triangular.to_block_inverse_mul_to_block_eq_one [linear_order α] [invertible M] (hM : block_triangular M b) (k : α) : M⁻¹.to_block (λ i, b i < k) (λ i, b i < k) ⬝ M.to_block (λ i, b i < k) (λ i, b i < k) = 1 := begin let p := (λ i, b i < k), have h_sum : M⁻¹.to_block p p ⬝ M.to_block p p + M⁻¹.to_block p (λ i, ¬ p i) ⬝ M.to_block (λ i, ¬ p i) p = 1, by rw [←to_block_mul_eq_add, inv_mul_of_invertible M, to_block_one_self], have h_zero : M.to_block (λ i, ¬ p i) p = 0, { ext i j, simpa using hM (lt_of_lt_of_le j.2 (le_of_not_lt i.2)) }, simpa [h_zero] using h_sum end /-- The inverse of an upper-left subblock of a block-triangular matrix `M` is the upper-left subblock of `M⁻¹`. -/ lemma block_triangular.inv_to_block [linear_order α] [invertible M] (hM : block_triangular M b) (k : α) : (M.to_block (λ i, b i < k) (λ i, b i < k))⁻¹ = M⁻¹.to_block (λ i, b i < k) (λ i, b i < k) := inv_eq_left_inv $ hM.to_block_inverse_mul_to_block_eq_one k /-- An upper-left subblock of an invertible block-triangular matrix is invertible. -/ def block_triangular.invertible_to_block [linear_order α] [invertible M] (hM : block_triangular M b) (k : α) : invertible (M.to_block (λ i, b i < k) (λ i, b i < k)) := invertible_of_left_inverse _ ((⅟M).to_block (λ i, b i < k) (λ i, b i < k)) $ by simpa only [inv_of_eq_nonsing_inv] using hM.to_block_inverse_mul_to_block_eq_one k /-- A lower-left subblock of the inverse of a block-triangular matrix is zero. This is a first step towards `block_triangular.inv_to_block` below. -/ lemma to_block_inverse_eq_zero [linear_order α] [invertible M] (hM : block_triangular M b) (k : α) : M⁻¹.to_block (λ i, k ≤ b i) (λ i, b i < k) = 0 := begin let p := λ i, b i < k, let q := λ i, ¬ b i < k, have h_sum : M⁻¹.to_block q p ⬝ M.to_block p p + M⁻¹.to_block q q ⬝ M.to_block q p = 0, { rw [←to_block_mul_eq_add, inv_mul_of_invertible M, to_block_one_disjoint], rw disjoint_iff_inf_le, exact λ i h, h.1 h.2 }, have h_zero : M.to_block q p = 0, { ext i j, simpa using hM (lt_of_lt_of_le j.2 $ le_of_not_lt i.2) }, have h_mul_eq_zero : M⁻¹.to_block q p ⬝ M.to_block p p = 0 := by simpa [h_zero] using h_sum, haveI : invertible (M.to_block p p) := hM.invertible_to_block k, have : (λ i, k ≤ b i) = q := by { ext, exact not_lt.symm }, rw [this, ← matrix.zero_mul (M.to_block p p)⁻¹, ← h_mul_eq_zero, mul_inv_cancel_right_of_invertible], end /-- The inverse of a block-triangular matrix is block-triangular. -/ lemma block_triangular_inv_of_block_triangular [linear_order α] [invertible M] (hM : block_triangular M b) : block_triangular M⁻¹ b := begin unfreezingI { induction hs : univ.image b using finset.strong_induction with s ih generalizing m }, subst hs, intros i j hij, haveI : inhabited m := ⟨i⟩, let k := (univ.image b).max' (univ_nonempty.image _), let b' := λ i : {a // b a < k}, b ↑i, let A := M.to_block (λ i, b i < k) (λ j, b j < k), obtain hbi | hi : b i = k ∨ _ := (le_max' _ (b i) $ mem_image_of_mem _ $ mem_univ _).eq_or_lt, { have : M⁻¹.to_block (λ i, k ≤ b i) (λ i, b i < k) ⟨i, hbi.ge⟩ ⟨j, hbi ▸ hij⟩ = 0, { simp only [to_block_inverse_eq_zero hM k, pi.zero_apply] }, simp [this.symm] }, haveI : invertible A := hM.invertible_to_block _, have hA : A.block_triangular b' := hM.submatrix, have hb' : image b' univ ⊂ image b univ, { convert image_subtype_univ_ssubset_image_univ k b _ (λ a, a < k) (lt_irrefl _), convert max'_mem _ _ }, have hij' : b' ⟨j, hij.trans hi⟩ < b' ⟨i, hi⟩, by simp_rw [b', subtype.coe_mk, hij], simp [hM.inv_to_block k, (ih (image b' univ) hb' hA rfl hij').symm], end end matrix
6139a5f6143ff183a38d7a9f49f53a3cee86bdb6
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/geometry/manifold/instances/units_of_normed_algebra.lean
77bfb586b575e861cd82e9636565a04678fe93d2
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
2,474
lean
/- Copyright © 2021 Nicolò Cavalleri. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Nicolò Cavalleri, Heather Macbeth -/ import geometry.manifold.smooth_manifold_with_corners import analysis.normed_space.units /-! # Units of a normed algebra This file is a stub, containing a construction of the charted space structure on the group of units of a complete normed ring `R`, and of the smooth manifold structure on the group of units of a complete normed `𝕜`-algebra `R`. This manifold is actually a Lie group, which eventually should be the main result of this file. An important special case of this construction is the general linear group. For a normed space `V` over a field `𝕜`, the `𝕜`-linear endomorphisms of `V` are a normed `𝕜`-algebra (see `continuous_linear_map.to_normed_algebra`), so this construction provides a Lie group structure on its group of units, the general linear group GL(`𝕜`, `V`). ## TODO The Lie group instance requires the following fields: ``` instance : lie_group 𝓘(𝕜, R) Rˣ := { smooth_mul := sorry, smooth_inv := sorry, ..units.smooth_manifold_with_corners } ``` The ingredients needed for the construction are * smoothness of multiplication and inversion in the charts, i.e. as functions on the normed `𝕜`-space `R`: see `cont_diff_at_ring_inverse` for the inversion result, and `cont_diff_mul` (needs to be generalized from field to algebra) for the multiplication result * for an open embedding `f`, whose domain is equipped with the induced manifold structure `f.singleton_smooth_manifold_with_corners`, characterization of smoothness of functions to/from this manifold in terms of smoothness in the target space. See the pair of lemmas `cont_mdiff_coe_sphere` and `cont_mdiff.cod_restrict_sphere` for a model. None of this should be particularly difficult. -/ noncomputable theory open_locale manifold namespace units variables {R : Type*} [normed_ring R] [complete_space R] instance : charted_space R Rˣ := open_embedding_coe.singleton_charted_space lemma chart_at_apply {a : Rˣ} {b : Rˣ} : chart_at R a b = b := rfl lemma chart_at_source {a : Rˣ} : (chart_at R a).source = set.univ := rfl variables {𝕜 : Type*} [nontrivially_normed_field 𝕜] [normed_algebra 𝕜 R] instance : smooth_manifold_with_corners 𝓘(𝕜, R) Rˣ := open_embedding_coe.singleton_smooth_manifold_with_corners 𝓘(𝕜, R) end units
0e672eeb2b3b4ab4e8521e8ebf9e4cd2bc1f7c58
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/algebra/continued_fractions/continuants_recurrence.lean
ede976eec04b5fe77c88aa9fa545e04edf937ba8
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
3,371
lean
/- Copyright (c) 2019 Kevin Kappelmann. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Kappelmann -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.algebra.continued_fractions.translations import Mathlib.PostPort universes u_1 namespace Mathlib /-! # Recurrence Lemmas for the `continuants` Function of Continued Fractions. ## Summary Given a generalized continued fraction `g`, for all `n ≥ 1`, we prove that the `continuants` function indeed satisfies the following recurrences: - `Aₙ = bₙ * Aₙ₋₁ + aₙ * Aₙ₋₂`, and - `Bₙ = bₙ * Bₙ₋₁ + aₙ * Bₙ₋₂`. -/ namespace generalized_continued_fraction theorem continuants_aux_recurrence {K : Type u_1} {g : generalized_continued_fraction K} {n : ℕ} [division_ring K] {gp : pair K} {ppred : pair K} {pred : pair K} (nth_s_eq : seq.nth (s g) n = some gp) (nth_conts_aux_eq : continuants_aux g n = ppred) (succ_nth_conts_aux_eq : continuants_aux g (n + 1) = pred) : continuants_aux g (n + bit0 1) = pair.mk (pair.b gp * pair.a pred + pair.a gp * pair.a ppred) (pair.b gp * pair.b pred + pair.a gp * pair.b ppred) := sorry theorem continuants_recurrence_aux {K : Type u_1} {g : generalized_continued_fraction K} {n : ℕ} [division_ring K] {gp : pair K} {ppred : pair K} {pred : pair K} (nth_s_eq : seq.nth (s g) n = some gp) (nth_conts_aux_eq : continuants_aux g n = ppred) (succ_nth_conts_aux_eq : continuants_aux g (n + 1) = pred) : continuants g (n + 1) = pair.mk (pair.b gp * pair.a pred + pair.a gp * pair.a ppred) (pair.b gp * pair.b pred + pair.a gp * pair.b ppred) := sorry /-- Shows that `Aₙ = bₙ * Aₙ₋₁ + aₙ * Aₙ₋₂` and `Bₙ = bₙ * Bₙ₋₁ + aₙ * Bₙ₋₂`. -/ theorem continuants_recurrence {K : Type u_1} {g : generalized_continued_fraction K} {n : ℕ} [division_ring K] {gp : pair K} {ppred : pair K} {pred : pair K} (succ_nth_s_eq : seq.nth (s g) (n + 1) = some gp) (nth_conts_eq : continuants g n = ppred) (succ_nth_conts_eq : continuants g (n + 1) = pred) : continuants g (n + bit0 1) = pair.mk (pair.b gp * pair.a pred + pair.a gp * pair.a ppred) (pair.b gp * pair.b pred + pair.a gp * pair.b ppred) := continuants_recurrence_aux succ_nth_s_eq (eq.mp (Eq._oldrec (Eq.refl (continuants g n = ppred)) nth_cont_eq_succ_nth_cont_aux) nth_conts_eq) (eq.mp (Eq._oldrec (Eq.refl (continuants g (n + 1) = pred)) nth_cont_eq_succ_nth_cont_aux) succ_nth_conts_eq) /-- Shows that `Aₙ = bₙ * Aₙ₋₁ + aₙ * Aₙ₋₂`. -/ theorem numerators_recurrence {K : Type u_1} {g : generalized_continued_fraction K} {n : ℕ} [division_ring K] {gp : pair K} {ppredA : K} {predA : K} (succ_nth_s_eq : seq.nth (s g) (n + 1) = some gp) (nth_num_eq : numerators g n = ppredA) (succ_nth_num_eq : numerators g (n + 1) = predA) : numerators g (n + bit0 1) = pair.b gp * predA + pair.a gp * ppredA := sorry /-- Shows that `Bₙ = bₙ * Bₙ₋₁ + aₙ * Bₙ₋₂`. -/ theorem denominators_recurrence {K : Type u_1} {g : generalized_continued_fraction K} {n : ℕ} [division_ring K] {gp : pair K} {ppredB : K} {predB : K} (succ_nth_s_eq : seq.nth (s g) (n + 1) = some gp) (nth_denom_eq : denominators g n = ppredB) (succ_nth_denom_eq : denominators g (n + 1) = predB) : denominators g (n + bit0 1) = pair.b gp * predB + pair.a gp * ppredB := sorry
b153c96dd3cc282d467cdac1a3a1b1213c78aa50
5ee26964f602030578ef0159d46145dd2e357ba5
/src/for_mathlib/nonarchimedean/is_subgroups_basis.lean
ce61325336c9a251f7ce4b84dd99c77b7243f42e
[ "Apache-2.0" ]
permissive
fpvandoorn/lean-perfectoid-spaces
569b4006fdfe491ca8b58dd817bb56138ada761f
06cec51438b168837fc6e9268945735037fd1db6
refs/heads/master
1,590,154,571,918
1,557,685,392,000
1,557,685,392,000
186,363,547
0
0
Apache-2.0
1,557,730,933,000
1,557,730,933,000
null
UTF-8
Lean
false
false
8,585
lean
import for_mathlib.nonarchimedean.basic import for_mathlib.topological_rings open set filter function lattice add_group_with_zero_nhd local attribute [instance] set.pointwise_mul_semiring class is_subgroups_basis {A : Type*} [ring A] {ι : Type*} [inhabited ι] (G : ι → set A) : Prop := [sub_groups : ∀ i, is_add_subgroup $ G i] (h_directed : ∀ i j, ∃ k, G k ⊆ G i ∩ G j) (h_left_mul : ∀ x i, ∃ j, (λ y : A, x*y) '' (G j) ⊆ G i) (h_right_mul : ∀ x i, ∃ j, (λ y : A, y*x) '' (G j) ⊆ G i) (h_mul : ∀ i, ∃ j, G j * G j ⊆ G i) namespace is_subgroups_basis section basics variables {A : Type*} [ring A] {ι : Type*} [inhabited ι] (G : ι → set A) [is_subgroups_basis G] include G instance (i : ι) : is_add_subgroup (G i) := is_subgroups_basis.sub_groups G i def to_ring_with_zero_nhd : ring_with_zero_nhd A := { Z := (⨅ i, principal (G i)), zero_Z := assume U H, mem_pure $ let ⟨i, hi⟩ := (mem_infi_range_of_base (h_directed G) U).1 H in hi (is_add_submonoid.zero_mem (G i)), sub_Z := begin rw tendsto_infi, intro i, rw tendsto_prod_self_iff, intros W W_in, use G i, have ineq : (⨅ (i : ι), principal (G i)) ≤ principal (G i), from infi_le _ _, use ineq (mem_principal_self $ G i), intros x y x_in y_in, exact W_in (is_add_subgroup.sub_mem _ x y x_in y_in) end, left_mul := begin intro x₀, rw tendsto_infi, intro i, rw tendsto_principal, rcases h_left_mul G x₀ i with ⟨j, hj⟩, change (λ (y : A), x₀ * y) '' G j ⊆ G i at hj, rw mem_infi_range_of_base (h_directed G), use j, rwa image_subset_iff at hj, end, right_mul := begin intro x₀, rw tendsto_infi, intro i, rw tendsto_principal, rcases h_right_mul G x₀ i with ⟨j, hj⟩, rw mem_infi_range_of_base (h_directed G), use j, rwa image_subset_iff at hj, end, mul_Z := begin rw tendsto_infi, intro i, rw tendsto_prod_self_iff, intros W W_in, rcases h_mul G i with ⟨j, hj⟩, use G j, have ineq : (⨅ (i : ι), principal (G i)) ≤ principal (G j), from infi_le _ _, use ineq (mem_principal_self $ G j), intros x y x_in y_in, apply W_in, apply hj, exact ⟨_, x_in, _, y_in, rfl⟩ end, to_ring := ‹ring A› } local attribute [instance, priority 0] to_ring_with_zero_nhd ring_with_zero_nhd.topological_space ring_with_zero_nhd.to_add_group_with_zero_nhd lemma nhds_zero (U : set A) : U ∈ nhds (0 : A) ↔ ∃ i, G i ⊆ U := begin rw nhds_zero_eq_Z, change U ∈ (⨅ i, principal (G i)) ↔ _, rw mem_infi_range_of_base (h_directed G), end lemma mem_nhds_zero (i : ι) : G i ∈ nhds (0 : A) := by { rw nhds_zero, use i} lemma le_nhds_zero (f : filter A) : f ≤ nhds (0 : A) ↔ ∀ i, G i ∈ f := begin split ; intro h, { intro i, exact h (mem_nhds_zero G i), }, { intros U U_in, rw nhds_zero at U_in, cases U_in with i hi, exact mem_sets_of_superset (h i) hi} end lemma is_op (i : ι) : is_open (G i) := begin rw is_open_iff_nhds, intros a ha, erw [nhds_eq, le_principal_iff, filter.mem_map, filter.mem_infi], { rw set.mem_Union, use i, rw show {x : A | x + a ∈ G i} = G i, { ext, rw ← (is_add_subgroup.add_mem_cancel_left (G i) ha), simp only [iff_self, set.mem_set_of_eq] }, exact mem_principal_self _ }, { intros i j, cases h_directed G i j with k hk, use k, split; show principal _ ≤ principal _; rw principal_mono; refine set.subset.trans hk _, { apply set.inter_subset_left }, { apply set.inter_subset_right } }, { apply_instance } end def is_topological_add_group : topological_add_group A := add_group_with_zero_nhd.topological_add_group local attribute [instance] is_topological_add_group lemma nonarchimedean : topological_add_group.nonarchimedean A := begin intros U hU, rw nhds_zero at hU, cases hU with i hi, exact ⟨⟨G i, is_op G i, by apply_instance⟩, hi⟩, end def to_uniform_space : uniform_space A := topological_add_group.to_uniform_space A local attribute [instance] to_uniform_space -- Patrick is not sure f ≠ ⊥ cannot be deduced from the other condition. Too tired lemma cauchy_iff (f : filter A) : cauchy f ↔ f ≠ ⊥ ∧ ∀ i, ∃ M ∈ f, ∀ x y ∈ M, y - x ∈ G i := begin suffices : filter.prod f f ≤ uniformity A ↔ ∀ (i : ι), ∃ (M : set A) (H : M ∈ f), ∀ x y ∈ M, y - x ∈ G i, by split; rintro ⟨nebot, H⟩; [ rw this at H, rw ← this at H] ; exact ⟨nebot, H⟩, rw uniformity_eq_comap_nhds_zero', rw ← map_le_iff_le_comap, rw le_nhds_zero, simp only [mem_map, mem_prod_same_iff], split ; intros h i ; rcases h i with ⟨M, M_in, hM⟩ ; use [M, M_in] ; [rw set.prod_subset_iff at hM, rw set.prod_subset_iff] ; exact λ x y xin yin, hM x xin y yin, end section continuity variables {G} {α : Type*} [add_group α] [topological_space α] [topological_add_group α] variables (f : α → A) [is_add_group_hom f] lemma continuous_into (h : ∀ i, is_open (f ⁻¹' (G i))) : continuous f := begin apply topological_add_group.continuous_of_continuous_at_zero f, intros U hU, rw [is_add_group_hom.map_zero f, nhds_zero] at hU, cases hU with i hi, rw mem_map_sets_iff, refine ⟨f ⁻¹' G i, mem_nhds_sets (h i) _, set.subset.trans _ hi⟩, { apply is_add_submonoid.zero_mem }, { apply image_preimage_subset } end variables (g : A → α) [is_add_group_hom g] -- Following two lines temporarily avoid hell on earth. But there seems to be a real -- issue with ring_with_nhds related instances... def tutut := add_monoid.to_has_zero α local attribute [instance, priority 100] tutut lemma continuous_from (h : ∀ U : set α, U ∈ (nhds (0 : α)) → ∃ i, G i ⊆ g ⁻¹' U) : continuous g := begin apply topological_add_group.continuous_of_continuous_at_zero g, intros U hU, rw [is_add_group_hom.map_zero g] at hU, cases h U hU with i hi, exact mem_sets_of_superset (mem_nhds_zero G i) hi end variables {B : Type*} [ring B] {J : Type*} [inhabited J] {H : J → set B} [is_subgroups_basis H] variables (φ : A → B) [is_add_group_hom φ] lemma continuous_both (h : ∀ j, ∃ i, G i ⊆ φ ⁻¹' (H j)) : continuous φ := begin refine continuous_from _ _, intros U U_nhds, cases (nhds_zero H U).1 U_nhds with j hj, cases h j with i hi, exact ⟨i, subset.trans hi $ preimage_mono hj⟩, end end continuity end basics section comm_ring variables {A : Type*} [comm_ring A] {ι : Type*} [inhabited ι] (G : ι → set A) [∀ i, is_add_subgroup $ G i] (h_directed : ∀ i j, ∃ k, G k ⊆ G i ∩ G j) (h_left_mul : ∀ (x : A) i, ∃ j, x • (G j) ⊆ G i) (h_mul : ∀ i, ∃ j, G j * G j ⊆ G i) include h_directed h_left_mul h_mul lemma of_comm : is_subgroups_basis G := { sub_groups := λ i, by apply_instance, h_directed := h_directed, h_left_mul := by simpa only [set.smul_set_eq_image] using h_left_mul, h_right_mul := by simpa only [set.smul_set_eq_image, mul_comm] using h_left_mul, h_mul := h_mul } end comm_ring section comm_algebra open algebra submodule variables {R : Type*} {A: Type*} [comm_ring R] [comm_ring A] [algebra R A] {ι : Type*} [inhabited ι] (M : ι → submodule R A) (h_directed : ∀ i j, ∃ k, M k ≤ M i ⊓ M j) (h_left_mul : ∀ (a : A) i, ∃ j, a • M j ≤ M i) (h_mul : ∀ i, ∃ j, M j * M j ≤ M i) include h_directed h_left_mul h_mul lemma of_submodules_comm : is_subgroups_basis (λ i, (M i).carrier) := begin letI : ∀ i, is_add_subgroup (M i).carrier := λ i, submodule.submodule_is_add_subgroup _, apply is_subgroups_basis.of_comm _ h_directed, { intros x i, cases h_left_mul x i with j hj, use j, erw smul_singleton at hj, rw set.smul_set_eq_image, exact hj }, { intro i, cases h_mul i with j hj, use j, rintros _ ⟨x, hx, y, hy, rfl⟩, exact hj (mul_mem_mul hx hy) }, end end comm_algebra end is_subgroups_basis
79f1e04e2940b95aae0788fc070d0b8f051b9270
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/archive/imo/imo1998_q2.lean
7ce14e5cf3214c1262b64fae2047fe98384dce8b
[ "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
9,669
lean
/- Copyright (c) 2020 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import data.fintype.prod import data.int.parity import algebra.big_operators.order import tactic.ring import tactic.noncomm_ring /-! # IMO 1998 Q2 > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In a competition, there are `a` contestants and `b` judges, where `b ≥ 3` is an odd integer. Each judge rates each contestant as either "pass" or "fail". Suppose `k` is a number such that, for any two judges, their ratings coincide for at most `k` contestants. Prove that `k / a ≥ (b - 1) / (2b)`. ## Solution The problem asks us to think about triples consisting of a contestant and two judges whose ratings agree for that contestant. We thus consider the subset `A ⊆ C × JJ` of all such incidences of agreement, where `C` and `J` are the sets of contestants and judges, and `JJ = J × J - {(j, j)}`. We have natural maps: `left : A → C` and `right: A → JJ`. We count the elements of `A` in two ways: as the sum of the cardinalities of the fibres of `left` and as the sum of the cardinalities of the fibres of `right`. We obtain an upper bound on the cardinality of `A` from the count for `right`, and a lower bound from the count for `left`. These two bounds combine to the required result. First consider the map `right : A → JJ`. Since the size of any fibre over a point in JJ is bounded by `k` and since `|JJ| = b^2 - b`, we obtain the upper bound: `|A| ≤ k(b^2-b)`. Now consider the map `left : A → C`. The fibre over a given contestant `c ∈ C` is the set of ordered pairs of (distinct) judges who agree about `c`. We seek to bound the cardinality of this fibre from below. Minimum agreement for a contestant occurs when the judges' ratings are split as evenly as possible. Since `b` is odd, this occurs when they are divided into groups of size `(b-1)/2` and `(b+1)/2`. This corresponds to a fibre of cardinality `(b-1)^2/2` and so we obtain the lower bound: `a(b-1)^2/2 ≤ |A|`. Rearranging gives the result. -/ open_locale classical variables {C J : Type*} (r : C → J → Prop) namespace imo1998_q2 noncomputable theory /-- An ordered pair of judges. -/ abbreviation judge_pair (J : Type*) := J × J /-- A triple consisting of contestant together with an ordered pair of judges. -/ abbreviation agreed_triple (C J : Type*) := C × (judge_pair J) /-- The first judge from an ordered pair of judges. -/ abbreviation judge_pair.judge₁ : judge_pair J → J := prod.fst /-- The second judge from an ordered pair of judges. -/ abbreviation judge_pair.judge₂ : judge_pair J → J := prod.snd /-- The proposition that the judges in an ordered pair are distinct. -/ abbreviation judge_pair.distinct (p : judge_pair J) := p.judge₁ ≠ p.judge₂ /-- The proposition that the judges in an ordered pair agree about a contestant's rating. -/ abbreviation judge_pair.agree (p : judge_pair J) (c : C) := r c p.judge₁ ↔ r c p.judge₂ /-- The contestant from the triple consisting of a contestant and an ordered pair of judges. -/ abbreviation agreed_triple.contestant : agreed_triple C J → C := prod.fst /-- The ordered pair of judges from the triple consisting of a contestant and an ordered pair of judges. -/ abbreviation agreed_triple.judge_pair : agreed_triple C J → judge_pair J := prod.snd @[simp] lemma judge_pair.agree_iff_same_rating (p : judge_pair J) (c : C) : p.agree r c ↔ (r c p.judge₁ ↔ r c p.judge₂) := iff.rfl /-- The set of contestants on which two judges agree. -/ def agreed_contestants [fintype C] (p : judge_pair J) : finset C := finset.univ.filter (λ c, p.agree r c) section variables [fintype J] [fintype C] /-- All incidences of agreement. -/ def A : finset (agreed_triple C J) := finset.univ.filter (λ (a : agreed_triple C J), a.judge_pair.agree r a.contestant ∧ a.judge_pair.distinct) lemma A_maps_to_off_diag_judge_pair (a : agreed_triple C J) : a ∈ A r → a.judge_pair ∈ finset.off_diag (@finset.univ J _) := by simp [A, finset.mem_off_diag] lemma A_fibre_over_contestant (c : C) : finset.univ.filter (λ (p : judge_pair J), p.agree r c ∧ p.distinct) = ((A r).filter (λ (a : agreed_triple C J), a.contestant = c)).image prod.snd := begin ext p, simp only [A, finset.mem_univ, finset.mem_filter, finset.mem_image, true_and, exists_prop], split, { rintros ⟨h₁, h₂⟩, refine ⟨(c, p), _⟩, finish, }, { intros h, finish, }, end lemma A_fibre_over_contestant_card (c : C) : (finset.univ.filter (λ (p : judge_pair J), p.agree r c ∧ p.distinct)).card = ((A r).filter (λ (a : agreed_triple C J), a.contestant = c)).card := by { rw A_fibre_over_contestant r, apply finset.card_image_of_inj_on, tidy, } lemma A_fibre_over_judge_pair {p : judge_pair J} (h : p.distinct) : agreed_contestants r p = ((A r).filter(λ (a : agreed_triple C J), a.judge_pair = p)).image agreed_triple.contestant := begin dunfold A agreed_contestants, ext c, split; intros h, { rw finset.mem_image, refine ⟨⟨c, p⟩, _⟩, finish, }, { finish, }, end lemma A_fibre_over_judge_pair_card {p : judge_pair J} (h : p.distinct) : (agreed_contestants r p).card = ((A r).filter(λ (a : agreed_triple C J), a.judge_pair = p)).card := by { rw A_fibre_over_judge_pair r h, apply finset.card_image_of_inj_on, tidy, } lemma A_card_upper_bound {k : ℕ} (hk : ∀ (p : judge_pair J), p.distinct → (agreed_contestants r p).card ≤ k) : (A r).card ≤ k * ((fintype.card J) * (fintype.card J) - (fintype.card J)) := begin change _ ≤ k * ((finset.card _ ) * (finset.card _ ) - (finset.card _ )), rw ← finset.off_diag_card, apply finset.card_le_mul_card_image_of_maps_to (A_maps_to_off_diag_judge_pair r), intros p hp, have hp' : p.distinct, { simp [finset.mem_off_diag] at hp, exact hp, }, rw ← A_fibre_over_judge_pair_card r hp', apply hk, exact hp', end end lemma add_sq_add_sq_sub {α : Type*} [ring α] (x y : α) : (x + y) * (x + y) + (x - y) * (x - y) = 2*x*x + 2*y*y := by noncomm_ring lemma norm_bound_of_odd_sum {x y z : ℤ} (h : x + y = 2*z + 1) : 2*z*z + 2*z + 1 ≤ x*x + y*y := begin suffices : 4*z*z + 4*z + 1 + 1 ≤ 2*x*x + 2*y*y, { rw ← mul_le_mul_left (zero_lt_two' ℤ), convert this; ring, }, have h' : (x + y) * (x + y) = 4*z*z + 4*z + 1, { rw h, ring, }, rw [← add_sq_add_sq_sub, h', add_le_add_iff_left], suffices : 0 < (x - y) * (x - y), { apply int.add_one_le_of_lt this, }, rw [mul_self_pos, sub_ne_zero], apply int.ne_of_odd_add ⟨z, h⟩, end section variables [fintype J] lemma judge_pairs_card_lower_bound {z : ℕ} (hJ : fintype.card J = 2*z + 1) (c : C) : 2*z*z + 2*z + 1 ≤ (finset.univ.filter (λ (p : judge_pair J), p.agree r c)).card := begin let x := (finset.univ.filter (λ j, r c j)).card, let y := (finset.univ.filter (λ j, ¬ r c j)).card, have h : (finset.univ.filter (λ (p : judge_pair J), p.agree r c)).card = x*x + y*y, { simp [← finset.filter_product_card], }, rw h, apply int.le_of_coe_nat_le_coe_nat, simp only [int.coe_nat_add, int.coe_nat_mul], apply norm_bound_of_odd_sum, suffices : x + y = 2*z + 1, { simp [← int.coe_nat_add, this], }, rw [finset.filter_card_add_filter_neg_card_eq_card, ← hJ], refl, end lemma distinct_judge_pairs_card_lower_bound {z : ℕ} (hJ : fintype.card J = 2*z + 1) (c : C) : 2*z*z ≤ (finset.univ.filter (λ (p : judge_pair J), p.agree r c ∧ p.distinct)).card := begin let s := finset.univ.filter (λ (p : judge_pair J), p.agree r c), let t := finset.univ.filter (λ (p : judge_pair J), p.distinct), have hs : 2*z*z + 2*z + 1 ≤ s.card, { exact judge_pairs_card_lower_bound r hJ c, }, have hst : s \ t = finset.univ.diag, { ext p, split; intros, { finish, }, { suffices : p.judge₁ = p.judge₂, { simp [this], }, finish, }, }, have hst' : (s \ t).card = 2*z + 1, { rw [hst, finset.diag_card, ← hJ], refl, }, rw [finset.filter_and, ← finset.sdiff_sdiff_self_left s t, finset.card_sdiff], { rw hst', rw add_assoc at hs, apply le_tsub_of_add_le_right hs, }, { apply finset.sdiff_subset, }, end lemma A_card_lower_bound [fintype C] {z : ℕ} (hJ : fintype.card J = 2*z + 1) : 2*z*z * (fintype.card C) ≤ (A r).card := begin have h : ∀ a, a ∈ A r → prod.fst a ∈ @finset.univ C _, { intros, apply finset.mem_univ, }, apply finset.mul_card_image_le_card_of_maps_to h, intros c hc, rw ← A_fibre_over_contestant_card, apply distinct_judge_pairs_card_lower_bound r hJ, end end lemma clear_denominators {a b k : ℕ} (ha : 0 < a) (hb : 0 < b) : (b - 1 : ℚ) / (2 * b) ≤ k / a ↔ (b - 1) * a ≤ k * (2 * b) := by rw div_le_div_iff; norm_cast; simp [ha, hb] end imo1998_q2 open imo1998_q2 theorem imo1998_q2 [fintype J] [fintype C] (a b k : ℕ) (hC : fintype.card C = a) (hJ : fintype.card J = b) (ha : 0 < a) (hb : odd b) (hk : ∀ (p : judge_pair J), p.distinct → (agreed_contestants r p).card ≤ k) : (b - 1 : ℚ) / (2 * b) ≤ k / a := begin rw clear_denominators ha hb.pos, obtain ⟨z, hz⟩ := hb, rw hz at hJ, rw hz, have h := le_trans (A_card_lower_bound r hJ) (A_card_upper_bound r hk), rw [hC, hJ] at h, -- We are now essentially done; we just need to bash `h` into exactly the right shape. have hl : k * ((2 * z + 1) * (2 * z + 1) - (2 * z + 1)) = (k * (2 * (2 * z + 1))) * z, { simp only [add_mul, two_mul, mul_comm, mul_assoc], finish, }, have hr : 2 * z * z * a = 2 * z * a * z, { ring, }, rw [hl, hr] at h, cases z, { simp, }, { exact le_of_mul_le_mul_right h z.succ_pos, }, end
4e271160ab0c20c113f3a55737b00f09db208939
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/category_theory/differential_object.lean
38865e33667c7a954d34be0658527b26125ec6db
[ "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
9,128
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 data.int.basic import category_theory.shift.basic import category_theory.concrete_category.basic /-! # Differential objects in a category. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. A differential object in a category with zero morphisms and a shift is an object `X` equipped with a morphism `d : X ⟶ X⟦1⟧`, such that `d^2 = 0`. We build the category of differential objects, and some basic constructions such as the forgetful functor, zero morphisms and zero objects, and the shift functor on differential objects. -/ open category_theory.limits universes v u namespace category_theory variables (C : Type u) [category.{v} C] -- TODO: generalize to `has_shift C A` for an arbitrary `[add_monoid A]` `[has_one A]`. variables [has_zero_morphisms C] [has_shift C ℤ] /-- A differential object in a category with zero morphisms and a shift is an object `X` equipped with a morphism `d : X ⟶ X⟦1⟧`, such that `d^2 = 0`. -/ @[nolint has_nonempty_instance] structure differential_object := (X : C) (d : X ⟶ X⟦1⟧) (d_squared' : d ≫ d⟦(1:ℤ)⟧' = 0 . obviously) restate_axiom differential_object.d_squared' attribute [simp] differential_object.d_squared variables {C} namespace differential_object /-- A morphism of differential objects is a morphism commuting with the differentials. -/ @[ext, nolint has_nonempty_instance] structure hom (X Y : differential_object C) := (f : X.X ⟶ Y.X) (comm' : X.d ≫ f⟦1⟧' = f ≫ Y.d . obviously) restate_axiom hom.comm' attribute [simp, reassoc] hom.comm namespace hom /-- The identity morphism of a differential object. -/ @[simps] def id (X : differential_object C) : hom X X := { f := 𝟙 X.X } /-- The composition of morphisms of differential objects. -/ @[simps] def comp {X Y Z : differential_object C} (f : hom X Y) (g : hom Y Z) : hom X Z := { f := f.f ≫ g.f, } end hom instance category_of_differential_objects : category (differential_object C) := { hom := hom, id := hom.id, comp := λ X Y Z f g, hom.comp f g, } @[simp] lemma id_f (X : differential_object C) : ((𝟙 X) : X ⟶ X).f = 𝟙 (X.X) := rfl @[simp] lemma comp_f {X Y Z : differential_object C} (f : X ⟶ Y) (g : Y ⟶ Z) : (f ≫ g).f = f.f ≫ g.f := rfl @[simp] lemma eq_to_hom_f {X Y : differential_object C} (h : X = Y) : hom.f (eq_to_hom h) = eq_to_hom (congr_arg _ h) := by { subst h, rw [eq_to_hom_refl, eq_to_hom_refl], refl } variables (C) /-- The forgetful functor taking a differential object to its underlying object. -/ def forget : (differential_object C) ⥤ C := { obj := λ X, X.X, map := λ X Y f, f.f, } instance forget_faithful : faithful (forget C) := { } instance has_zero_morphisms : has_zero_morphisms (differential_object C) := { has_zero := λ X Y, ⟨{ f := 0 }⟩} variables {C} @[simp] lemma zero_f (P Q : differential_object C) : (0 : P ⟶ Q).f = 0 := rfl /-- An isomorphism of differential objects gives an isomorphism of the underlying objects. -/ @[simps] def iso_app {X Y : differential_object C} (f : X ≅ Y) : X.X ≅ Y.X := ⟨f.hom.f, f.inv.f, by { dsimp, rw [← comp_f, iso.hom_inv_id, id_f] }, by { dsimp, rw [← comp_f, iso.inv_hom_id, id_f] }⟩ @[simp] lemma iso_app_refl (X : differential_object C) : iso_app (iso.refl X) = iso.refl X.X := rfl @[simp] lemma iso_app_symm {X Y : differential_object C} (f : X ≅ Y) : iso_app f.symm = (iso_app f).symm := rfl @[simp] lemma iso_app_trans {X Y Z : differential_object C} (f : X ≅ Y) (g : Y ≅ Z) : iso_app (f ≪≫ g) = iso_app f ≪≫ iso_app g := rfl /-- An isomorphism of differential objects can be constructed from an isomorphism of the underlying objects that commutes with the differentials. -/ @[simps] def mk_iso {X Y : differential_object C} (f : X.X ≅ Y.X) (hf : X.d ≫ f.hom⟦1⟧' = f.hom ≫ Y.d) : X ≅ Y := { hom := ⟨f.hom, hf⟩, inv := ⟨f.inv, by { dsimp, rw [← functor.map_iso_inv, iso.comp_inv_eq, category.assoc, iso.eq_inv_comp, functor.map_iso_hom, hf] }⟩, hom_inv_id' := by { ext1, dsimp, exact f.hom_inv_id }, inv_hom_id' := by { ext1, dsimp, exact f.inv_hom_id } } end differential_object namespace functor universes v' u' variables (D : Type u') [category.{v'} D] variables [has_zero_morphisms D] [has_shift D ℤ] /-- A functor `F : C ⥤ D` which commutes with shift functors on `C` and `D` and preserves zero morphisms can be lifted to a functor `differential_object C ⥤ differential_object D`. -/ @[simps] def map_differential_object (F : C ⥤ D) (η : (shift_functor C (1:ℤ)).comp F ⟶ F.comp (shift_functor D (1:ℤ))) (hF : ∀ c c', F.map (0 : c ⟶ c') = 0) : differential_object C ⥤ differential_object D := { obj := λ X, { X := F.obj X.X, d := F.map X.d ≫ η.app X.X, d_squared' := begin rw [functor.map_comp, ← functor.comp_map F (shift_functor D (1:ℤ))], slice_lhs 2 3 { rw [← η.naturality X.d] }, rw [functor.comp_map], slice_lhs 1 2 { rw [← F.map_comp, X.d_squared, hF] }, rw [zero_comp, zero_comp], end }, map := λ X Y f, { f := F.map f.f, comm' := begin dsimp, slice_lhs 2 3 { rw [← functor.comp_map F (shift_functor D (1:ℤ)), ← η.naturality f.f] }, slice_lhs 1 2 { rw [functor.comp_map, ← F.map_comp, f.comm, F.map_comp] }, rw [category.assoc] end }, map_id' := by { intros, ext, simp }, map_comp' := by { intros, ext, simp }, } end functor end category_theory namespace category_theory namespace differential_object variables (C : Type u) [category.{v} C] variables [has_zero_object C] [has_zero_morphisms C] [has_shift C ℤ] open_locale zero_object instance has_zero_object : has_zero_object (differential_object C) := by { refine ⟨⟨⟨0, 0⟩, λ X, ⟨⟨⟨⟨0⟩⟩, λ f, _⟩⟩, λ X, ⟨⟨⟨⟨0⟩⟩, λ f, _⟩⟩⟩⟩; ext, } end differential_object namespace differential_object variables (C : Type (u+1)) [large_category C] [concrete_category C] [has_zero_morphisms C] [has_shift C ℤ] instance concrete_category_of_differential_objects : concrete_category (differential_object C) := { forget := forget C ⋙ category_theory.forget C } instance : has_forget₂ (differential_object C) C := { forget₂ := forget C } end differential_object /-! The category of differential objects itself has a shift functor. -/ namespace differential_object variables (C : Type u) [category.{v} C] variables [has_zero_morphisms C] [has_shift C ℤ] noncomputable theory /-- The shift functor on `differential_object C`. -/ @[simps] def shift_functor (n : ℤ) : differential_object C ⥤ differential_object C := { obj := λ X, { X := X.X⟦n⟧, d := X.d⟦n⟧' ≫ (shift_comm _ _ _).hom, d_squared' := by rw [functor.map_comp, category.assoc, shift_comm_hom_comp_assoc, ←functor.map_comp_assoc, X.d_squared, functor.map_zero, zero_comp] }, map := λ X Y f, { f := f.f⟦n⟧', comm' := begin dsimp, erw [category.assoc, shift_comm_hom_comp, ← functor.map_comp_assoc, f.comm, functor.map_comp_assoc], refl, end, }, map_id' := by { intros X, ext1, dsimp, rw functor.map_id }, map_comp' := by { intros X Y Z f g, ext1, dsimp, rw functor.map_comp } } /-- The shift functor on `differential_object C` is additive. -/ @[simps] def shift_functor_add (m n : ℤ) : shift_functor C (m + n) ≅ shift_functor C m ⋙ shift_functor C n := begin refine nat_iso.of_components (λ X, mk_iso (shift_add X.X _ _) _) _, { dsimp, rw [← cancel_epi ((shift_functor_add C m n).inv.app X.X)], simp only [category.assoc, iso.inv_hom_id_app_assoc], erw [← nat_trans.naturality_assoc], dsimp, simp only [functor.map_comp, category.assoc, shift_functor_comm_hom_app_comp_shift_shift_functor_add_hom_app 1 m n X.X, iso.inv_hom_id_app_assoc], }, { intros X Y f, ext, dsimp, exact nat_trans.naturality _ _ } end section /-- The shift by zero is naturally isomorphic to the identity. -/ @[simps] def shift_zero : shift_functor C 0 ≅ 𝟭 (differential_object C) := begin refine nat_iso.of_components (λ X, mk_iso ((shift_functor_zero C ℤ).app X.X) _) _, { erw [← nat_trans.naturality], dsimp, simp only [shift_functor_zero_hom_app_shift, category.assoc], }, { tidy, }, end end instance : has_shift (differential_object C) ℤ := has_shift_mk _ _ { F := shift_functor C, zero := shift_zero C, add := shift_functor_add C, assoc_hom_app := λ m₁ m₂ m₃ X, begin ext1, convert shift_functor_add_assoc_hom_app m₁ m₂ m₃ X.X, dsimp [shift_functor_add'], simpa, end, zero_add_hom_app := λ n X, begin ext1, convert shift_functor_add_zero_add_hom_app n X.X, simpa, end, add_zero_hom_app := λ n X, begin ext1, convert shift_functor_add_add_zero_hom_app n X.X, simpa, end, } end differential_object end category_theory
63ce11089e34209bcd6e3d5146fe176e91b547f3
31f556cdeb9239ffc2fad8f905e33987ff4feab9
/stage0/src/Lean/Compiler/LCNF/ToDecl.lean
f1df3e4aa577afe59d52deb67bab965d088a051d
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
tobiasgrosser/lean4
ce0fd9cca0feba1100656679bf41f0bffdbabb71
ebdbdc10436a4d9d6b66acf78aae7a23f5bd073f
refs/heads/master
1,673,103,412,948
1,664,930,501,000
1,664,930,501,000
186,870,185
0
0
Apache-2.0
1,665,129,237,000
1,557,939,901,000
Lean
UTF-8
Lean
false
false
5,399
lean
/- Copyright (c) 2022 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.Transform import Lean.Meta.Match.MatcherInfo import Lean.Compiler.ImplementedByAttr import Lean.Compiler.LCNF.ToLCNF namespace Lean.Compiler.LCNF /-- Inline constants tagged with the `[macroInline]` attribute occurring in `e`. -/ def macroInline (e : Expr) : CoreM Expr := Core.transform e fun e => do let .const declName us := e.getAppFn | return .continue unless hasMacroInlineAttribute (← getEnv) declName do return .continue let val ← Core.instantiateValueLevelParams (← getConstInfo declName) us return .visit <| val.beta e.getAppArgs private def normalizeAlt (e : Expr) (numParams : Nat) : MetaM Expr := Meta.lambdaTelescope e fun xs body => do if xs.size == numParams then return e else if xs.size > numParams then let body ← Meta.mkLambdaFVars xs[numParams:] body let body ← Meta.withLetDecl (← mkFreshUserName `_k) (← Meta.inferType body) body fun x => Meta.mkLetFVars #[x] x Meta.mkLambdaFVars xs[:numParams] body else Meta.forallBoundedTelescope (← Meta.inferType e) (numParams - xs.size) fun ys _ => Meta.mkLambdaFVars (xs ++ ys) (mkAppN e ys) /-- Inline auxiliary `matcher` applications. -/ partial def inlineMatchers (e : Expr) : CoreM Expr := Meta.MetaM.run' <| Meta.transform e fun e => do let .const declName us := e.getAppFn | return .continue let some info ← Meta.getMatcherInfo? declName | return .continue let numArgs := e.getAppNumArgs if numArgs > info.arity then return .continue else if numArgs < info.arity then Meta.forallBoundedTelescope (← Meta.inferType e) (info.arity - numArgs) fun xs _ => return .visit (← Meta.mkLambdaFVars xs (mkAppN e xs)) else let mut args := e.getAppArgs let numAlts := info.numAlts let altNumParams := info.altNumParams let rec inlineMatcher (i : Nat) (args : Array Expr) (letFVars : Array Expr) : MetaM Expr := do if i < numAlts then let altIdx := i + info.getFirstAltPos let numParams := altNumParams[i]! let alt ← normalizeAlt args[altIdx]! numParams Meta.withLetDecl (← mkFreshUserName `_alt) (← Meta.inferType alt) alt fun altFVar => inlineMatcher (i+1) (args.set! altIdx altFVar) (letFVars.push altFVar) else let info ← getConstInfo declName let value := (← Core.instantiateValueLevelParams info us).beta args Meta.mkLetFVars letFVars value return .visit (← inlineMatcher 0 args #[]) /-- Replace nested occurrences of `unsafeRec` names with the safe ones. -/ private def replaceUnsafeRecNames (value : Expr) : CoreM Expr := Core.transform value fun e => match e with | .const declName us => if let some safeDeclName := isUnsafeRecName? declName then return .done (.const safeDeclName us) else return .done e | _ => return .continue /-- Return the declaration `ConstantInfo` for the code generator. Remark: the unsafe recursive version is tried first. -/ def getDeclInfo? (declName : Name) : CoreM (Option ConstantInfo) := do let env ← getEnv return env.find? (mkUnsafeRecName declName) <|> env.find? declName /-- Convert the given declaration from the Lean environment into `Decl`. The steps for this are roughly: - partially erasing type information of the declaration - eta-expanding the declaration value. - if the declaration has an unsafe-rec version, use it. - expand declarations tagged with the `[macroInline]` attribute - turn the resulting term into LCNF declaration -/ def toDecl (declName : Name) : CompilerM Decl := do let declName := if let some name := isUnsafeRecName? declName then name else declName let some info ← getDeclInfo? declName | throwError "declaration `{declName}` not found" let some value := info.value? | throwError "declaration `{declName}` does not have a value" let (type, value) ← Meta.MetaM.run' do let type ← toLCNFType info.type let value ← Meta.lambdaTelescope value fun xs body => do Meta.mkLambdaFVars xs (← Meta.etaExpand body) let value ← replaceUnsafeRecNames value let value ← macroInline value /- Recall that some declarations tagged with `macroInline` contain matchers. -/ let value ← inlineMatchers value /- Recall that `inlineMatchers` may have exposed `ite`s and `dite`s which are tagged as `[macroInline]`. -/ let value ← macroInline value /- Remark: we have disabled the following transformation, we will perform it at phase 2, after code specialization. It prevents many optimizations (e.g., "cases-of-ctor"). -/ -- let value ← applyCasesOnImplementedBy value return (type, value) let value ← toLCNF value let safe := !info.isPartial && !info.isUnsafe let decl ← if let .fun decl (.return _) := value then eraseFunDecl decl (recursive := false) pure { name := declName, params := decl.params, type, value := decl.value, levelParams := info.levelParams, safe : Decl } else pure { name := declName, params := #[], type, value, levelParams := info.levelParams, safe } /- `toLCNF` may eta-reduce simple declarations. -/ decl.etaExpand end Lean.Compiler.LCNF
38d4831610f55034a08804ec815b6072c196c000
4727251e0cd73359b15b664c3170e5d754078599
/src/topology/tietze_extension.lean
7fda729bf52a9aac592d0aad1d5356f7fc426bb1
[ "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
22,811
lean
/- Copyright (c) 2021 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov -/ import data.set.intervals.monotone import topology.algebra.order.monotone_continuity import topology.urysohns_bounded /-! # Tietze extension theorem In this file we prove a few version of the Tietze extension theorem. The theorem says that a continuous function `s → ℝ` defined on a closed set in a normal topological space `Y` can be extended to a continuous function on the whole space. Moreover, if all values of the original function belong to some (finite or infinite, open or closed) interval, then the extension can be chosen so that it takes values in the same interval. In particular, if the original function is a bounded function, then there exists a bounded extension of the same norm. The proof mostly follows <https://ncatlab.org/nlab/show/Tietze+extension+theorem>. We patch a small gap in the proof for unbounded functions, see `exists_extension_forall_exists_le_ge_of_closed_embedding`. ## Implementation notes We first prove the theorems for a closed embedding `e : X → Y` of a topological space into a normal topological space, then specialize them to the case `X = s : set Y`, `e = coe`. ## Tags Tietze extension theorem, Urysohn's lemma, normal topological space -/ variables {X Y : Type*} [topological_space X] [topological_space Y] [normal_space Y] open metric set filter open_locale bounded_continuous_function topological_space noncomputable theory namespace bounded_continuous_function /-- One step in the proof of the Tietze extension theorem. If `e : C(X, Y)` is a closed embedding of a topological space into a normal topological space and `f : X →ᵇ ℝ` is a bounded continuous function, then there exists a bounded continuous function `g : Y →ᵇ ℝ` of the norm `∥g∥ ≤ ∥f∥ / 3` such that the distance between `g ∘ e` and `f` is at most `(2 / 3) * ∥f∥`. -/ lemma tietze_extension_step (f : X →ᵇ ℝ) (e : C(X, Y)) (he : closed_embedding e) : ∃ g : Y →ᵇ ℝ, ∥g∥ ≤ ∥f∥ / 3 ∧ dist (g.comp_continuous e) f ≤ (2 / 3) * ∥f∥ := begin have h3 : (0 : ℝ) < 3 := by norm_num1, have h23 : 0 < (2 / 3 : ℝ) := by norm_num1, -- In the trivial case `f = 0`, we take `g = 0` rcases eq_or_ne f 0 with (rfl|hf), { use 0, simp }, replace hf : 0 < ∥f∥ := norm_pos_iff.2 hf, /- Otherwise, the closed sets `e '' (f ⁻¹' (Iic (-∥f∥ / 3)))` and `e '' (f ⁻¹' (Ici (∥f∥ / 3)))` are disjoint, hence by Urysohn's lemma there exists a function `g` that is equal to `-∥f∥ / 3` on the former set and is equal to `∥f∥ / 3` on the latter set. This function `g` satisfies the assertions of the lemma. -/ have hf3 : -∥f∥ / 3 < ∥f∥ / 3, from (div_lt_div_right h3).2 (left.neg_lt_self hf), have hc₁ : is_closed (e '' (f ⁻¹' (Iic (-∥f∥ / 3)))), from he.is_closed_map _ (is_closed_Iic.preimage f.continuous), have hc₂ : is_closed (e '' (f ⁻¹' (Ici (∥f∥ / 3)))), from he.is_closed_map _ (is_closed_Ici.preimage f.continuous), have hd : disjoint (e '' (f ⁻¹' (Iic (-∥f∥ / 3)))) (e '' (f ⁻¹' (Ici (∥f∥ / 3)))), { refine disjoint_image_of_injective he.inj (disjoint_preimage _ _), rwa [Iic_disjoint_Ici, not_le] }, rcases exists_bounded_mem_Icc_of_closed_of_le hc₁ hc₂ hd hf3.le with ⟨g, hg₁, hg₂, hgf⟩, refine ⟨g, _, _⟩, { refine (norm_le $ div_nonneg hf.le h3.le).mpr (λ y, _), simpa [real.norm_eq_abs, abs_le, neg_div] using hgf y }, { refine (dist_le $ mul_nonneg h23.le hf.le).mpr (λ x, _), have hfx : -∥f∥ ≤ f x ∧ f x ≤ ∥f∥, by simpa only [real.norm_eq_abs, abs_le] using f.norm_coe_le_norm x, cases le_total (f x) (-∥f∥ / 3) with hle₁ hle₁, { calc |g (e x) - f x| = -∥f∥ / 3 - f x: by rw [hg₁ (mem_image_of_mem _ hle₁), abs_of_nonneg (sub_nonneg.2 hle₁)] ... ≤ (2 / 3) * ∥f∥ : by linarith }, { cases le_total (f x) (∥f∥ / 3) with hle₂ hle₂, { simp only [neg_div] at *, calc dist (g (e x)) (f x) ≤ |g (e x)| + |f x| : dist_le_norm_add_norm _ _ ... ≤ ∥f∥ / 3 + ∥f∥ / 3 : add_le_add (abs_le.2 $ hgf _) (abs_le.2 ⟨hle₁, hle₂⟩) ... = (2 / 3) * ∥f∥ : by linarith }, { calc |g (e x) - f x| = f x - ∥f∥ / 3 : by rw [hg₂ (mem_image_of_mem _ hle₂), abs_sub_comm, abs_of_nonneg (sub_nonneg.2 hle₂)] ... ≤ (2 / 3) * ∥f∥ : by linarith } } } end /-- **Tietze extension theorem** for real-valued bounded continuous maps, a version with a closed embedding and bundled composition. If `e : C(X, Y)` is a closed embedding of a topological space into a normal topological space and `f : X →ᵇ ℝ` is a bounded continuous function, then there exists a bounded continuous function `g : Y →ᵇ ℝ` of the same norm such that `g ∘ e = f`. -/ lemma exists_extension_norm_eq_of_closed_embedding' (f : X →ᵇ ℝ) (e : C(X, Y)) (he : closed_embedding e) : ∃ g : Y →ᵇ ℝ, ∥g∥ = ∥f∥ ∧ g.comp_continuous e = f := begin /- For the proof, we iterate `tietze_extension_step`. Each time we apply it to the difference between the previous approximation and `f`. -/ choose F hF_norm hF_dist using λ f : X →ᵇ ℝ, tietze_extension_step f e he, set g : ℕ → Y →ᵇ ℝ := λ n, (λ g, g + F (f - g.comp_continuous e))^[n] 0, have g0 : g 0 = 0 := rfl, have g_succ : ∀ n, g (n + 1) = g n + F (f - (g n).comp_continuous e), from λ n, function.iterate_succ_apply' _ _ _, have hgf : ∀ n, dist ((g n).comp_continuous e) f ≤ (2 / 3) ^ n * ∥f∥, { intro n, induction n with n ihn, { simp [g0] }, { rw [g_succ n, add_comp_continuous, ← dist_sub_right, add_sub_cancel', pow_succ, mul_assoc], refine (hF_dist _).trans (mul_le_mul_of_nonneg_left _ (by norm_num1)), rwa ← dist_eq_norm' } }, have hg_dist : ∀ n, dist (g n) (g (n + 1)) ≤ 1 / 3 * ∥f∥ * (2 / 3) ^ n, { intro n, calc dist (g n) (g (n + 1)) = ∥F (f - (g n).comp_continuous e)∥ : by rw [g_succ, dist_eq_norm', add_sub_cancel'] ... ≤ ∥f - (g n).comp_continuous e∥ / 3 : hF_norm _ ... = (1 / 3) * dist ((g n).comp_continuous e) f : by rw [dist_eq_norm', one_div, div_eq_inv_mul] ... ≤ (1 / 3) * ((2 / 3) ^ n * ∥f∥) : mul_le_mul_of_nonneg_left (hgf n) (by norm_num1) ... = 1 / 3 * ∥f∥ * (2 / 3) ^ n : by ac_refl }, have hg_cau : cauchy_seq g, from cauchy_seq_of_le_geometric _ _ (by norm_num1) hg_dist, have : tendsto (λ n, (g n).comp_continuous e) at_top (𝓝 $ (lim at_top g).comp_continuous e), from ((continuous_comp_continuous e).tendsto _).comp hg_cau.tendsto_lim, have hge : (lim at_top g).comp_continuous e = f, { refine tendsto_nhds_unique this (tendsto_iff_dist_tendsto_zero.2 _), refine squeeze_zero (λ _, dist_nonneg) hgf _, rw ← zero_mul (∥f∥), refine (tendsto_pow_at_top_nhds_0_of_lt_1 _ _).mul tendsto_const_nhds; norm_num1 }, refine ⟨lim at_top g, le_antisymm _ _, hge⟩, { rw [← dist_zero_left, ← g0], refine (dist_le_of_le_geometric_of_tendsto₀ _ _ (by norm_num1) hg_dist hg_cau.tendsto_lim).trans_eq _, field_simp [show (3 - 2 : ℝ) = 1, by norm_num1] }, { rw ← hge, exact norm_comp_continuous_le _ _ } end /-- **Tietze extension theorem** for real-valued bounded continuous maps, a version with a closed embedding and unbundled composition. If `e : C(X, Y)` is a closed embedding of a topological space into a normal topological space and `f : X →ᵇ ℝ` is a bounded continuous function, then there exists a bounded continuous function `g : Y →ᵇ ℝ` of the same norm such that `g ∘ e = f`. -/ lemma exists_extension_norm_eq_of_closed_embedding (f : X →ᵇ ℝ) {e : X → Y} (he : closed_embedding e) : ∃ g : Y →ᵇ ℝ, ∥g∥ = ∥f∥ ∧ g ∘ e = f := begin rcases exists_extension_norm_eq_of_closed_embedding' f ⟨e, he.continuous⟩ he with ⟨g, hg, rfl⟩, exact ⟨g, hg, rfl⟩ end /-- **Tietze extension theorem** for real-valued bounded continuous maps, a version for a closed set. If `f` is a bounded continuous real-valued function defined on a closed set in a normal topological space, then it can be extended to a bounded continuous function of the same norm defined on the whole space. -/ lemma exists_norm_eq_restrict_eq_of_closed {s : set Y} (f : s →ᵇ ℝ) (hs : is_closed s) : ∃ g : Y →ᵇ ℝ, ∥g∥ = ∥f∥ ∧ g.restrict s = f := exists_extension_norm_eq_of_closed_embedding' f ((continuous_map.id _).restrict s) (closed_embedding_subtype_coe hs) /-- **Tietze extension theorem** for real-valued bounded continuous maps, a version for a closed embedding and a bounded continuous function that takes values in a non-trivial closed interval. See also `exists_extension_forall_mem_of_closed_embedding` for a more general statement that works for any interval (finite or infinite, open or closed). If `e : X → Y` is a closed embedding and `f : X →ᵇ ℝ` is a bounded continuous function such that `f x ∈ [a, b]` for all `x`, where `a ≤ b`, then there exists a bounded continuous function `g : Y →ᵇ ℝ` such that `g y ∈ [a, b]` for all `y` and `g ∘ e = f`. -/ lemma exists_extension_forall_mem_Icc_of_closed_embedding (f : X →ᵇ ℝ) {a b : ℝ} {e : X → Y} (hf : ∀ x, f x ∈ Icc a b) (hle : a ≤ b) (he : closed_embedding e) : ∃ g : Y →ᵇ ℝ, (∀ y, g y ∈ Icc a b) ∧ g ∘ e = f := begin rcases exists_extension_norm_eq_of_closed_embedding (f - const X ((a + b) / 2)) he with ⟨g, hgf, hge⟩, refine ⟨const Y ((a + b) / 2) + g, λ y, _, _⟩, { suffices : ∥f - const X ((a + b) / 2)∥ ≤ (b - a) / 2, by simpa [real.Icc_eq_closed_ball, add_mem_closed_ball_iff_norm] using (norm_coe_le_norm g y).trans (hgf.trans_le this), refine (norm_le $ div_nonneg (sub_nonneg.2 hle) zero_le_two).2 (λ x, _), simpa only [real.Icc_eq_closed_ball] using hf x }, { ext x, have : g (e x) = f x - (a + b) / 2 := congr_fun hge x, simp [this] } end /-- **Tietze extension theorem** for real-valued bounded continuous maps, a version for a closed embedding. Let `e` be a closed embedding of a nonempty topological space `X` into a normal topological space `Y`. Let `f` be a bounded continuous real-valued function on `X`. Then there exists a bounded continuous function `g : Y →ᵇ ℝ` such that `g ∘ e = f` and each value `g y` belongs to a closed interval `[f x₁, f x₂]` for some `x₁` and `x₂`. -/ lemma exists_extension_forall_exists_le_ge_of_closed_embedding [nonempty X] (f : X →ᵇ ℝ) {e : X → Y} (he : closed_embedding e) : ∃ g : Y →ᵇ ℝ, (∀ y, ∃ x₁ x₂, g y ∈ Icc (f x₁) (f x₂)) ∧ g ∘ e = f := begin inhabit X, -- Put `a = ⨅ x, f x` and `b = ⨆ x, f x` obtain ⟨a, ha⟩ : ∃ a, is_glb (range f) a, from ⟨_, is_glb_cinfi (real.bounded_iff_bdd_below_bdd_above.1 f.bounded_range).1⟩, obtain ⟨b, hb⟩ : ∃ b, is_lub (range f) b, from ⟨_, is_lub_csupr (real.bounded_iff_bdd_below_bdd_above.1 f.bounded_range).2⟩, -- Then `f x ∈ [a, b]` for all `x` have hmem : ∀ x, f x ∈ Icc a b, from λ x, ⟨ha.1 ⟨x, rfl⟩, hb.1 ⟨x, rfl⟩⟩, -- Rule out the trivial case `a = b` have hle : a ≤ b := (hmem default).1.trans (hmem default).2, rcases hle.eq_or_lt with (rfl|hlt), { have : ∀ x, f x = a, by simpa using hmem, use const Y a, simp [this, function.funext_iff] }, -- Put `c = (a + b) / 2`. Then `a < c < b` and `c - a = b - c`. set c := (a + b) / 2, have hac : a < c := left_lt_add_div_two.2 hlt, have hcb : c < b := add_div_two_lt_right.2 hlt, have hsub : c - a = b - c, by { simp only [c], field_simp, ring }, /- Due to `exists_extension_forall_mem_Icc_of_closed_embedding`, there exists an extension `g` such that `g y ∈ [a, b]` for all `y`. However, if `a` and/or `b` do not belong to the range of `f`, then we need to ensure that these points do not belong to the range of `g`. This is done in two almost identical steps. First we deal with the case `∀ x, f x ≠ a`. -/ obtain ⟨g, hg_mem, hgf⟩ : ∃ g : Y →ᵇ ℝ, (∀ y, ∃ x, g y ∈ Icc (f x) b) ∧ g ∘ e = f, { rcases exists_extension_forall_mem_Icc_of_closed_embedding f hmem hle he with ⟨g, hg_mem, hgf⟩, -- If `a ∈ range f`, then we are done. rcases em (∃ x, f x = a) with ⟨x, rfl⟩|ha', { exact ⟨g, λ y, ⟨x, hg_mem _⟩, hgf⟩ }, /- Otherwise, `g ⁻¹' {a}` is disjoint with `range e ∪ g ⁻¹' (Ici c)`, hence there exists a function `dg : Y → ℝ` such that `dg ∘ e = 0`, `dg y = 0` whenever `c ≤ g y`, `dg y = c - a` whenever `g y = a`, and `0 ≤ dg y ≤ c - a` for all `y`. -/ have hd : disjoint (range e ∪ g ⁻¹' (Ici c)) (g ⁻¹' {a}), { refine disjoint_union_left.2 ⟨_, disjoint_preimage _ _⟩, { rintro _ ⟨⟨x, rfl⟩, rfl : g (e x) = a⟩, exact ha' ⟨x, (congr_fun hgf x).symm⟩ }, { exact set.disjoint_singleton_right.2 hac.not_le } }, rcases exists_bounded_mem_Icc_of_closed_of_le (he.closed_range.union $ is_closed_Ici.preimage g.continuous) (is_closed_singleton.preimage g.continuous) hd (sub_nonneg.2 hac.le) with ⟨dg, dg0, dga, dgmem⟩, replace hgf : ∀ x, (g + dg) (e x) = f x, { intro x, simp [dg0 (or.inl $ mem_range_self _), ← hgf] }, refine ⟨g + dg, λ y, _, funext hgf⟩, { have hay : a < (g + dg) y, { rcases (hg_mem y).1.eq_or_lt with rfl|hlt, { refine (lt_add_iff_pos_right _).2 _, calc 0 < c - g y : sub_pos.2 hac ... = dg y : (dga rfl).symm }, { exact hlt.trans_le ((le_add_iff_nonneg_right _).2 $ (dgmem y).1) } }, rcases ha.exists_between hay with ⟨_, ⟨x, rfl⟩, hax, hxy⟩, refine ⟨x, hxy.le, _⟩, cases le_total c (g y) with hc hc, { simp [dg0 (or.inr hc), (hg_mem y).2] }, { calc g y + dg y ≤ c + (c - a) : add_le_add hc (dgmem _).2 ... = b : by rw [hsub, add_sub_cancel'_right] } } }, /- Now we deal with the case `∀ x, f x ≠ b`. The proof is the same as in the first case, with minor modifications that make it hard to deduplicate code. -/ choose xl hxl hgb using hg_mem, rcases em (∃ x, f x = b) with ⟨x, rfl⟩|hb', { exact ⟨g, λ y, ⟨xl y, x, hxl y, hgb y⟩, hgf⟩ }, have hd : disjoint (range e ∪ g ⁻¹' (Iic c)) (g ⁻¹' {b}), { refine disjoint_union_left.2 ⟨_, disjoint_preimage _ _⟩, { rintro _ ⟨⟨x, rfl⟩, rfl : g (e x) = b⟩, exact hb' ⟨x, (congr_fun hgf x).symm⟩ }, { exact set.disjoint_singleton_right.2 hcb.not_le } }, rcases exists_bounded_mem_Icc_of_closed_of_le (he.closed_range.union $ is_closed_Iic.preimage g.continuous) (is_closed_singleton.preimage g.continuous) hd (sub_nonneg.2 hcb.le) with ⟨dg, dg0, dgb, dgmem⟩, replace hgf : ∀ x, (g - dg) (e x) = f x, { intro x, simp [dg0 (or.inl $ mem_range_self _), ← hgf] }, refine ⟨g - dg, λ y, _, funext hgf⟩, { have hyb : (g - dg) y < b, { rcases (hgb y).eq_or_lt with rfl|hlt, { refine (sub_lt_self_iff _).2 _, calc 0 < g y - c : sub_pos.2 hcb ... = dg y : (dgb rfl).symm }, { exact ((sub_le_self_iff _).2 (dgmem _).1).trans_lt hlt } }, rcases hb.exists_between hyb with ⟨_, ⟨xu, rfl⟩, hyxu, hxub⟩, cases lt_or_le c (g y) with hc hc, { rcases em (a ∈ range f) with ⟨x, rfl⟩|ha', { refine ⟨x, xu, _, hyxu.le⟩, calc f x = c - (b - c) : by rw [← hsub, sub_sub_cancel] ... ≤ g y - dg y : sub_le_sub hc.le (dgmem _).2 }, { have hay : a < (g - dg) y, { calc a = c - (b - c) : by rw [← hsub, sub_sub_cancel] ... < g y - (b - c) : sub_lt_sub_right hc _ ... ≤ g y - dg y : sub_le_sub_left (dgmem _).2 _ }, rcases ha.exists_between hay with ⟨_, ⟨x, rfl⟩, ha, hxy⟩, exact ⟨x, xu, hxy.le, hyxu.le⟩ } }, { refine ⟨xl y, xu, _, hyxu.le⟩, simp [dg0 (or.inr hc), hxl] } }, end /-- **Tietze extension theorem** for real-valued bounded continuous maps, a version for a closed embedding. Let `e` be a closed embedding of a nonempty topological space `X` into a normal topological space `Y`. Let `f` be a bounded continuous real-valued function on `X`. Let `t` be a nonempty convex set of real numbers (we use `ord_connected` instead of `convex` to automatically deduce this argument by typeclass search) such that `f x ∈ t` for all `x`. Then there exists a bounded continuous real-valued function `g : Y →ᵇ ℝ` such that `g y ∈ t` for all `y` and `g ∘ e = f`. -/ lemma exists_extension_forall_mem_of_closed_embedding (f : X →ᵇ ℝ) {t : set ℝ} {e : X → Y} [hs : ord_connected t] (hf : ∀ x, f x ∈ t) (hne : t.nonempty) (he : closed_embedding e) : ∃ g : Y →ᵇ ℝ, (∀ y, g y ∈ t) ∧ g ∘ e = f := begin casesI is_empty_or_nonempty X, { rcases hne with ⟨c, hc⟩, refine ⟨const Y c, λ y, hc, funext $ λ x, is_empty_elim x⟩ }, rcases exists_extension_forall_exists_le_ge_of_closed_embedding f he with ⟨g, hg, hgf⟩, refine ⟨g, λ y, _, hgf⟩, rcases hg y with ⟨xl, xu, h⟩, exact hs.out (hf _) (hf _) h end /-- **Tietze extension theorem** for real-valued bounded continuous maps, a version for a closed set. Let `s` be a closed set in a normal topological space `Y`. Let `f` be a bounded continuous real-valued function on `s`. Let `t` be a nonempty convex set of real numbers (we use `ord_connected` instead of `convex` to automatically deduce this argument by typeclass search) such that `f x ∈ t` for all `x : s`. Then there exists a bounded continuous real-valued function `g : Y →ᵇ ℝ` such that `g y ∈ t` for all `y` and `g.restrict s = f`. -/ lemma exists_forall_mem_restrict_eq_of_closed {s : set Y} (f : s →ᵇ ℝ) (hs : is_closed s) {t : set ℝ} [ord_connected t] (hf : ∀ x, f x ∈ t) (hne : t.nonempty) : ∃ g : Y →ᵇ ℝ, (∀ y, g y ∈ t) ∧ g.restrict s = f := begin rcases exists_extension_forall_mem_of_closed_embedding f hf hne (closed_embedding_subtype_coe hs) with ⟨g, hg, hgf⟩, exact ⟨g, hg, fun_like.coe_injective hgf⟩ end end bounded_continuous_function namespace continuous_map /-- **Tietze extension theorem** for real-valued continuous maps, a version for a closed embedding. Let `e` be a closed embedding of a nonempty topological space `X` into a normal topological space `Y`. Let `f` be a continuous real-valued function on `X`. Let `t` be a nonempty convex set of real numbers (we use `ord_connected` instead of `convex` to automatically deduce this argument by typeclass search) such that `f x ∈ t` for all `x`. Then there exists a continuous real-valued function `g : C(Y, ℝ)` such that `g y ∈ t` for all `y` and `g ∘ e = f`. -/ lemma exists_extension_forall_mem_of_closed_embedding (f : C(X, ℝ)) {t : set ℝ} {e : X → Y} [hs : ord_connected t] (hf : ∀ x, f x ∈ t) (hne : t.nonempty) (he : closed_embedding e) : ∃ g : C(Y, ℝ), (∀ y, g y ∈ t) ∧ g ∘ e = f := begin have h : ℝ ≃o Ioo (-1 : ℝ) 1 := order_iso_Ioo_neg_one_one ℝ, set F : X →ᵇ ℝ := { to_fun := coe ∘ (h ∘ f), continuous_to_fun := continuous_subtype_coe.comp (h.continuous.comp f.continuous), map_bounded' := bounded_range_iff.1 ((bounded_Ioo (-1 : ℝ) 1).mono $ forall_range_iff.2 $ λ x, (h (f x)).2) }, set t' : set ℝ := (coe ∘ h) '' t, have ht_sub : t' ⊆ Ioo (-1 : ℝ) 1 := image_subset_iff.2 (λ x hx, (h x).2), haveI : ord_connected t', { constructor, rintros _ ⟨x, hx, rfl⟩ _ ⟨y, hy, rfl⟩ z hz, lift z to Ioo (-1 : ℝ) 1 using (Icc_subset_Ioo (h x).2.1 (h y).2.2 hz), change z ∈ Icc (h x) (h y) at hz, rw [← h.image_Icc] at hz, rcases hz with ⟨z, hz, rfl⟩, exact ⟨z, hs.out hx hy hz, rfl⟩ }, have hFt : ∀ x, F x ∈ t', from λ x, mem_image_of_mem _ (hf x), rcases F.exists_extension_forall_mem_of_closed_embedding hFt (hne.image _) he with ⟨G, hG, hGF⟩, set g : C(Y, ℝ) := ⟨h.symm ∘ cod_restrict G _ (λ y, ht_sub (hG y)), h.symm.continuous.comp $ continuous_subtype_mk _ G.continuous⟩, have hgG : ∀ {y a}, g y = a ↔ G y = h a, from λ y a, h.to_equiv.symm_apply_eq.trans subtype.ext_iff, refine ⟨g, λ y, _, _⟩, { rcases hG y with ⟨a, ha, hay⟩, convert ha, exact hgG.2 hay.symm }, { ext x, exact hgG.2 (congr_fun hGF _) } end /-- **Tietze extension theorem** for real-valued continuous maps, a version for a closed embedding. Let `e` be a closed embedding of a nonempty topological space `X` into a normal topological space `Y`. Let `f` be a continuous real-valued function on `X`. Then there exists a continuous real-valued function `g : C(Y, ℝ)` such that `g ∘ e = f`. -/ lemma exists_extension_of_closed_embedding (f : C(X, ℝ)) (e : X → Y) (he : closed_embedding e) : ∃ g : C(Y, ℝ), g ∘ e = f := (exists_extension_forall_mem_of_closed_embedding f (λ x, mem_univ _) univ_nonempty he).imp $ λ g, and.right /-- **Tietze extension theorem** for real-valued continuous maps, a version for a closed set. Let `s` be a closed set in a normal topological space `Y`. Let `f` be a continuous real-valued function on `s`. Let `t` be a nonempty convex set of real numbers (we use `ord_connected` instead of `convex` to automatically deduce this argument by typeclass search) such that `f x ∈ t` for all `x : s`. Then there exists a continuous real-valued function `g : C(Y, ℝ)` such that `g y ∈ t` for all `y` and `g.restrict s = f`. -/ lemma exists_restrict_eq_forall_mem_of_closed {s : set Y} (f : C(s, ℝ)) {t : set ℝ} [ord_connected t] (ht : ∀ x, f x ∈ t) (hne : t.nonempty) (hs : is_closed s) : ∃ g : C(Y, ℝ), (∀ y, g y ∈ t) ∧ g.restrict s = f := let ⟨g, hgt, hgf⟩ := exists_extension_forall_mem_of_closed_embedding f ht hne (closed_embedding_subtype_coe hs) in ⟨g, hgt, coe_injective hgf⟩ /-- **Tietze extension theorem** for real-valued continuous maps, a version for a closed set. Let `s` be a closed set in a normal topological space `Y`. Let `f` be a continuous real-valued function on `s`. Then there exists a continuous real-valued function `g : C(Y, ℝ)` such that `g.restrict s = f`. -/ lemma exists_restrict_eq_of_closed {s : set Y} (f : C(s, ℝ)) (hs : is_closed s) : ∃ g : C(Y, ℝ), g.restrict s = f := let ⟨g, hg, hgf⟩ := exists_restrict_eq_forall_mem_of_closed f (λ _, mem_univ _) univ_nonempty hs in ⟨g, hgf⟩ end continuous_map
f7c0a608fe086ae53c1a46b4cc3d7423f4ac634c
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/string/basic.lean
1b4e22de6838da593cd15fae3a3c244bf60efba8
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
2,585
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro Supplementary theorems about the `string` type. -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.list.basic import Mathlib.data.char import Mathlib.PostPort namespace Mathlib namespace string def ltb : iterator → iterator → Bool := sorry protected instance has_lt' : HasLess string := { Less := fun (s₁ s₂ : string) => ↥(ltb (mk_iterator s₁) (mk_iterator s₂)) } protected instance decidable_lt : DecidableRel Less := fun (a b : string) => bool.decidable_eq (ltb (mk_iterator a) (mk_iterator b)) tt @[simp] theorem lt_iff_to_list_lt {s₁ : string} {s₂ : string} : s₁ < s₂ ↔ to_list s₁ < to_list s₂ := sorry protected instance has_le : HasLessEq string := { LessEq := fun (s₁ s₂ : string) => ¬s₂ < s₁ } protected instance decidable_le : DecidableRel LessEq := fun (a b : string) => ne.decidable (ltb (mk_iterator b) (mk_iterator a)) tt @[simp] theorem le_iff_to_list_le {s₁ : string} {s₂ : string} : s₁ ≤ s₂ ↔ to_list s₁ ≤ to_list s₂ := iff.trans (not_congr lt_iff_to_list_lt) not_lt theorem to_list_inj {s₁ : string} {s₂ : string} : to_list s₁ = to_list s₂ ↔ s₁ = s₂ := sorry theorem nil_as_string_eq_empty : list.as_string [] = empty := rfl @[simp] theorem to_list_empty : to_list empty = [] := rfl theorem as_string_inv_to_list (s : string) : list.as_string (to_list s) = s := string_imp.cases_on s fun (s : List char) => Eq.refl (list.as_string (to_list (string_imp.mk s))) @[simp] theorem to_list_singleton (c : char) : to_list (singleton c) = [c] := rfl theorem to_list_nonempty {s : string} (h : s ≠ empty) : to_list s = head s :: to_list (popn s 1) := sorry @[simp] theorem head_empty : head empty = Inhabited.default := rfl @[simp] theorem popn_empty {n : ℕ} : popn empty n = empty := sorry protected instance linear_order : linear_order string := linear_order.mk LessEq Less sorry sorry sorry sorry string.decidable_le (fun (a b : string) => string.has_decidable_eq a b) fun (a b : string) => string.decidable_lt a b end string theorem list.to_list_inv_as_string (l : List char) : string.to_list (list.as_string l) = l := sorry @[simp] theorem list.as_string_inj {l : List char} {l' : List char} : list.as_string l = list.as_string l' ↔ l = l' := sorry theorem list.as_string_eq {l : List char} {s : string} : list.as_string l = s ↔ l = string.to_list s := sorry
ab9776137555357cc68a62ba3681756e635e9450
bb31430994044506fa42fd667e2d556327e18dfe
/src/data/nat/prime_fin.lean
85d8fedbc6a6960532e4e9ba75434f0bd60a824a
[ "Apache-2.0" ]
permissive
sgouezel/mathlib
0cb4e5335a2ba189fa7af96d83a377f83270e503
00638177efd1b2534fc5269363ebf42a7871df9a
refs/heads/master
1,674,527,483,042
1,673,665,568,000
1,673,665,568,000
119,598,202
0
0
null
1,517,348,647,000
1,517,348,646,000
null
UTF-8
Lean
false
false
1,902
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Jeremy Avigad, Mario Carneiro -/ import data.nat.factors import data.set.finite /-! # Prime numbers This file contains some results about prime numbers which depend on finiteness of sets. -/ namespace nat /-- A version of `nat.exists_infinite_primes` using the `set.infinite` predicate. -/ lemma infinite_set_of_prime : {p | prime p}.infinite := set.infinite_of_not_bdd_above not_bdd_above_set_of_prime /-- If `a`, `b` are positive, the prime divisors of `a * b` are the union of those of `a` and `b` -/ lemma factors_mul_to_finset {a b : ℕ} (ha : a ≠ 0) (hb : b ≠ 0) : (a * b).factors.to_finset = a.factors.to_finset ∪ b.factors.to_finset := (list.to_finset.ext $ λ x, (mem_factors_mul ha hb).trans list.mem_union.symm).trans $ list.to_finset_union _ _ lemma pow_succ_factors_to_finset (n k : ℕ) : (n^(k+1)).factors.to_finset = n.factors.to_finset := begin rcases eq_or_ne n 0 with rfl | hn, { simp }, induction k with k ih, { simp }, rw [pow_succ, factors_mul_to_finset hn (pow_ne_zero _ hn), ih, finset.union_idempotent] end lemma pow_factors_to_finset (n : ℕ) {k : ℕ} (hk : k ≠ 0) : (n^k).factors.to_finset = n.factors.to_finset := begin cases k, { simpa using hk }, rw pow_succ_factors_to_finset end /-- The only prime divisor of positive prime power `p^k` is `p` itself -/ lemma prime_pow_prime_divisor {p k : ℕ} (hk : k ≠ 0) (hp : prime p) : (p^k).factors.to_finset = {p} := by simp [pow_factors_to_finset p hk, factors_prime hp] lemma factors_mul_to_finset_of_coprime {a b : ℕ} (hab : coprime a b) : (a * b).factors.to_finset = a.factors.to_finset ∪ b.factors.to_finset := (list.to_finset.ext $ mem_factors_mul_of_coprime hab).trans $ list.to_finset_union _ _ end nat
ab6701abbbb83cf5ca1e6ce2f05fea1ba6e37bc4
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/analysis/normed_space/star/mul.lean
bdf88d0d85bee876a84106b24c39a2810dfea352
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
3,113
lean
/- Copyright (c) 2022 Jireh Loreaux. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jireh Loreaux -/ import analysis.normed_space.star.basic import analysis.normed_space.operator_norm /-! # The left-regular representation is an isometry for C⋆-algebras > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4.-/ open continuous_linear_map local postfix `⋆`:std.prec.max_plus := star variables (𝕜 : Type*) {E : Type*} variables [densely_normed_field 𝕜] [non_unital_normed_ring E] [star_ring E] [cstar_ring E] variables [normed_space 𝕜 E] [is_scalar_tower 𝕜 E E] [smul_comm_class 𝕜 E E] (a : E) /-- In a C⋆-algebra `E`, either unital or non-unital, multiplication on the left by `a : E` has norm equal to the norm of `a`. -/ @[simp] lemma op_nnnorm_mul : ‖mul 𝕜 E a‖₊ = ‖a‖₊ := begin rw ←Sup_closed_unit_ball_eq_nnnorm, refine cSup_eq_of_forall_le_of_forall_lt_exists_gt _ _ (λ r hr, _), { exact (metric.nonempty_closed_ball.mpr zero_le_one).image _ }, { rintro - ⟨x, hx, rfl⟩, exact ((mul 𝕜 E a).unit_le_op_norm x $ mem_closed_ball_zero_iff.mp hx).trans (op_norm_mul_apply_le 𝕜 E a) }, { have ha : 0 < ‖a‖₊ := zero_le'.trans_lt hr, rw [←inv_inv (‖a‖₊), nnreal.lt_inv_iff_mul_lt (inv_ne_zero ha.ne')] at hr, obtain ⟨k, hk₁, hk₂⟩ := normed_field.exists_lt_nnnorm_lt 𝕜 (mul_lt_mul_of_pos_right hr $ inv_pos.2 ha), refine ⟨_, ⟨k • star a, _, rfl⟩, _⟩, { simpa only [mem_closed_ball_zero_iff, norm_smul, one_mul, norm_star] using (nnreal.le_inv_iff_mul_le ha.ne').1 (one_mul ‖a‖₊⁻¹ ▸ hk₂.le : ‖k‖₊ ≤ ‖a‖₊⁻¹) }, { simp only [map_smul, nnnorm_smul, mul_apply', mul_smul_comm, cstar_ring.nnnorm_self_mul_star], rwa [←nnreal.div_lt_iff (mul_pos ha ha).ne', div_eq_mul_inv, mul_inv, ←mul_assoc] } }, end /-- In a C⋆-algebra `E`, either unital or non-unital, multiplication on the right by `a : E` has norm eqaul to the norm of `a`. -/ @[simp] lemma op_nnnorm_mul_flip : ‖(mul 𝕜 E).flip a‖₊ = ‖a‖₊ := begin rw [←Sup_unit_ball_eq_nnnorm, ←nnnorm_star, ←@op_nnnorm_mul 𝕜 E, ←Sup_unit_ball_eq_nnnorm], congr' 1, simp only [mul_apply', flip_apply], refine set.subset.antisymm _ _; rintro - ⟨b, hb, rfl⟩; refine ⟨star b, by simpa only [norm_star, mem_ball_zero_iff] using hb, _⟩, { simp only [←star_mul, nnnorm_star] }, { simpa using (nnnorm_star (star b * a)).symm } end variables (E) /-- In a C⋆-algebra `E`, either unital or non-unital, the left regular representation is an isometry. -/ lemma mul_isometry : isometry (mul 𝕜 E) := add_monoid_hom_class.isometry_of_norm _ (λ a, congr_arg coe $ op_nnnorm_mul 𝕜 a) /-- In a C⋆-algebra `E`, either unital or non-unital, the right regular anti-representation is an isometry. -/ lemma mul_flip_isometry : isometry (mul 𝕜 E).flip := add_monoid_hom_class.isometry_of_norm _ (λ a, congr_arg coe $ op_nnnorm_mul_flip 𝕜 a)
815893ba3d3d1c5c047f21d1066cbc610e5fe486
6fbf10071e62af7238f2de8f9aa83d55d8763907
/src/2.3_logic_types.lean
32cb25a78a537a4e7f677671d362b03c807f088b
[]
no_license
HasanMukati/uva-cs-dm-s19
ee5aad4568a3ca330c2738ed579c30e1308b03b0
3e7177682acdb56a2d16914e0344c10335583dcf
refs/heads/master
1,596,946,213,130
1,568,221,949,000
1,568,221,949,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,301
lean
/- Copyright 2019 Kevin Sullivan and Ben Hocking. -/ /- Every term has exactly one type in Lean. -/ namespace Types.ex1 #check 2 #check 2 + 2 def x : nat := 2 #check x #check tt #check "Hello, Lean!" #check "Hello, " ++ "Lean!" end Types.ex1 /- All terms are type checked for type correctness. The following code does not type check. -/ namespace Types.ex2 def x : nat := "Hello, Lean!" -- type error #check "Hello, Lean!" + 3 -- type error end Types.ex2 /- Proof checking in Lean is done by type checking. Propositions are types. Proofs are values of these types. If a variable is defined to be of type P, where P is a proposition, then the only kind of proof that can be bound to that variable is a proof term (a value) of type P. You can see a proof checking error in this code. -/ namespace Types.ex3 axioms (P Q : Prop) (p : P) (q : Q) def pf_P : P := p def pf_P' : P := q end Types.ex3 /- You can define your own types in Lean. We will get into this topic in detail later in the course. Each type comes with its own namespace, with the same name as the type itself. If you want to refer to constructors of a type without writing the type name as a namespace prefix, you can "open" the namespace. -/ namespace Types.ex4 inductive day : Type | Sunday : day | Monday : day | Tuesday : day | Wednesday : day | Thursday : day | Friday : day | Saturday : day #check day.Monday open day #check Monday end Types.ex4 /- Types are terms so they too have types. There are two "sorts" of types in Lean: logical types are propositions; computational types are for programming. Computation types include basic data types as well as function types. You can see here that function types are all of type "Type". -/ namespace Types.ex5a -- computational data types #check nat #check string #check bool -- computational function types #check nat → nat #check string → nat #check string → bool end Types.ex5a /- And all propostions are of type, "Prop". -/ namespace Types.ex5b #check true #check false #check 0 = 1 axioms P Q : Prop #check P #check Q #check P ∧ Q #check P ∨ Q #check P → Q #check ¬ P end Types.ex5b /- Proofs really are just values (terms) of their corresponding types. -/ namespace Terms.ex8 axioms (P : Prop) (p : P) example : P := p end Terms.ex8
fe4cc5cc523631bd3505b2b4dfabd0022f36b822
51c1a276984eccde1889df19fbc87b914cad4613
/modexp.lean
53295c2bb0852f08388fd064d1d606c551cbeb0c
[]
no_license
cipher1024/lean-modexp
6c0e996654b6a31c2e7be646072091530e4ffb9f
d779c1b9f588e86181beca26e32c4c1ae8ef1f36
refs/heads/master
1,609,627,624,569
1,510,265,500,000
1,510,265,500,000
99,388,479
0
1
null
null
null
null
UTF-8
Lean
false
false
5,660
lean
import .lib.data.fin import .lib.data.pow import data.list import data.bitvec local infix ` ^ ` := pow_nat def word_size : ℕ := 32 def window_size : ℕ := 4 def word_vals : ℕ := 2^word_size def win_vals : ℕ := 2^window_size lemma window_size_pos : window_size > 0 := of_as_true trivial lemma win_vals_gt_one : win_vals > 1 := begin change (2 : ℕ)^0 < _, unfold win_vals, apply pow_lt_pow, { apply nat.lt_succ_self, }, apply window_size_pos end @[reducible] def word := bitvec word_size @[reducible] def window := fin win_vals section defs open nat def up {n : ℕ} : fin n → fin (succ n) | ⟨i,P⟩ := ⟨i,show i < succ n, by { transitivity n, { apply P }, { apply nat.lt_succ_self } }⟩ structure bignum := (cap : ℕ) (size : fin (succ cap)) (data : array word cap) (all_zero : ∀ i, size ≤ up i → data.read i = 0) (msw_not_zero : ∀ last, fin.succ last = size → data.read last ≠ 0) end defs namespace bignum def to_nat (n : bignum) : ℕ := n.data.iterate 0 (λ i w r, r + w.to_nat * 2 ^ (i.val * word_size)) def zero : bignum := { cap := 0 , size := 0 , data := ⟨ λ i, i.elim0 ⟩ , all_zero := assume i, i.elim0 , msw_not_zero := assume i, i.elim0 } def words (p : bignum) (n : ℕ) : word := if h : n < p.cap then p.data.read ⟨n,h⟩ else 0 namespace add open nat def add_carry (p q : bignum) : ℕ → word | 0 := 0 | (succ i) := let c := (add_carry i).to_nat, x := (p.words $ succ i).to_nat, y := (q.words $ succ i).to_nat in if word_vals ≤ c + x + y then 1 else 0 def add_val (p q : bignum) (i : ℕ) : word := p.words i + p.words i + add_carry p q i def msw_aux {n} (ar : array word n) : ∀ i, i < succ n → fin (succ n) | 0 P := ⟨ _, P ⟩ | (succ i) P := if ar.read ⟨i,lt_of_succ_lt_succ P⟩ = 0 then msw_aux i (by { transitivity succ i, apply lt_succ_self, apply P }) else ⟨succ i,P⟩ def msw {n} (ar : array word n) : fin (succ n) := msw_aux ar n (lt_succ_self _) lemma msw_not_zero {n} (ar : array word n) : ∀ last, fin.succ last = msw ar → ar.read last ≠ 0 := sorry lemma msw_all_zero {n} (ar : array word n) : ∀ i, msw ar ≤ up i → ar.read i = 0 := sorry def data {n} (p q : bignum) : array word n := ⟨ λ i , add_val p q i.val ⟩ end add def add (p q : bignum) : bignum := { cap := max p.size.val q.size.val + 1 , data := add.data p q , size := add.msw (add.data p q) , msw_not_zero := add.msw_not_zero (add.data p q) , all_zero := add.msw_all_zero (add.data p q) } instance : has_add bignum := ⟨ add ⟩ theorem to_nat_add (p q : bignum) : (p + q).to_nat = p.to_nat + q.to_nat := sorry -- todo: look into setoid -- the same nat can be represented by two different bignums -- by just padding the number with zeros instance : add_monoid bignum := { zero := zero , add := add , add_zero := sorry , zero_add := sorry , add_assoc := sorry } end bignum namespace list open nat def to_nat : list window → ℕ | [] := 0 | (w :: ws) := w.val + win_vals * to_nat ws def from_nat : ℕ → list window | n := if h : n > 0 then let x := n / win_vals, y := n % win_vals in have Hv_pos : 1 < win_vals, from win_vals_gt_one, have Hlt : n * 1 < n * win_vals, from mul_lt_mul_of_pos_left Hv_pos h, have Hdec : n / win_vals < n, begin rw [div_lt_iff_lt_mul], { rw mul_one at Hlt, apply Hlt }, apply lt_trans _ Hv_pos, apply zero_lt_succ, end, (fin.of_nat y) :: from_nat x else [] lemma to_nat_from_nat (n : ℕ) : to_nat (from_nat n) = n := sorry end list namespace mod_group namespace version0 open list nat (hiding pow_add) def expmod {m : ℕ} (p : fin (succ m)) (e : list window) : fin (succ m) := e.reverse.foldl (λ r w, r^win_vals * p^w.val) 1 theorem expmod_def {m : ℕ} (p : fin (succ m)) (e : list window) : expmod p e = p^e.to_nat := begin simp [expmod,list.foldl_eq_foldr], induction e, case nil { simp [to_nat], }, case cons e es { simp [foldr,ih_1], simp [flip,to_nat,pow_add,pow_mul,pow_pow_comm], } end end version0 -- tentative namespace version1 open list @[reducible] def bignum := list word instance : has_one bignum := ⟨ [1] ⟩ def bignum.to_nat : bignum → ℕ := sorry def trunc_mul (n : ℕ) (p q : bignum) : bignum := sorry def mod (p q : bignum) : bignum := sorry def pow_table (ws : ℕ) (p : bignum) : ℕ → bignum | 0 := 1 | (nat.succ n) := trunc_mul ws p (pow_table n) def win_pow (ws : ℕ) : bignum → bignum := nat.repeat (λ _ p, trunc_mul ws p p) window_size def expmod (p : bignum) (e : list window) (m : bignum) : bignum := let ws := m.length, -- `word size` of the modulus pow_t : array bignum win_vals := array.mk (λ i, pow_table ws p i.val) in mod (e.reverse.foldl (λ r w, trunc_mul ws (win_pow ws r) (pow_t.read w)) 1) m theorem expmod_def (p : bignum) (e : list window) (m : bignum) : (expmod p e m).to_nat = p.to_nat ^ e.to_nat % m.to_nat := sorry -- def breakup : word → list window := -- sorry -- -- return `window_size` sized windows from the most significant to the least -- def windows (p : bignum) : list window := -- p.data.rev_list.bind breakup -- def from_windows (ws : list window) : bignum := -- sorry -- @[simp] -- lemma from_windows_nil -- : from_windows nil = 0 := -- sorry -- @[simp] -- lemma to_nat_zero -- : bignum.to_nat 0 = 0 := -- sorry -- lemma windows_eq_nil_imp_self_eq_zero {p : bignum} -- (h : windows p = nil) -- : p.to_nat = 0 := -- sorry -- lemma to_nat_from_windows_windows_eq_to_nat_self {p : bignum} -- : (from_windows (windows p)).to_nat = p.to_nat := -- sorry end version1 end mod_group
c8c8dbe9c01d73491cfc0cb8e4b4e8b40ef7016b
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/data/list/count.lean
abaca8d6bf0d34ab7da3f213455b016607fdf4a3
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
6,516
lean
/- Copyright (c) 2014 Parikshit Khanna. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Parikshit Khanna, Jeremy Avigad, Leonardo de Moura, Floris van Doorn, Mario Carneiro -/ import data.list.big_operators /-! # Counting in lists This file proves basic properties of `list.countp` and `list.count`, which count the number of elements of a list satisfying a predicate and equal to a given element respectively. Their definitions can be found in [`data.list.defs`](./data/list/defs). -/ open nat variables {α β : Type*} {l l₁ l₂ : list α} namespace list section countp variables (p : α → Prop) [decidable_pred p] @[simp] lemma countp_nil : countp p [] = 0 := rfl @[simp] lemma countp_cons_of_pos {a : α} (l) (pa : p a) : countp p (a::l) = countp p l + 1 := if_pos pa @[simp] lemma countp_cons_of_neg {a : α} (l) (pa : ¬ p a) : countp p (a::l) = countp p l := if_neg pa lemma length_eq_countp_add_countp (l) : length l = countp p l + countp (λ a, ¬p a) l := by induction l with x h ih; [refl, by_cases p x]; [simp only [countp_cons_of_pos _ _ h, countp_cons_of_neg (λ a, ¬p a) _ (decidable.not_not.2 h), ih, length], simp only [countp_cons_of_pos (λ a, ¬p a) _ h, countp_cons_of_neg _ _ h, ih, length]]; ac_refl lemma countp_eq_length_filter (l) : countp p l = length (filter p l) := by induction l with x l ih; [refl, by_cases (p x)]; [simp only [filter_cons_of_pos _ h, countp, ih, if_pos h], simp only [countp_cons_of_neg _ _ h, ih, filter_cons_of_neg _ h]]; refl @[simp] lemma countp_append (l₁ l₂) : countp p (l₁ ++ l₂) = countp p l₁ + countp p l₂ := by simp only [countp_eq_length_filter, filter_append, length_append] lemma countp_pos {l} : 0 < countp p l ↔ ∃ a ∈ l, p a := by simp only [countp_eq_length_filter, length_pos_iff_exists_mem, mem_filter, exists_prop] lemma length_filter_lt_length_iff_exists (l) : length (filter p l) < length l ↔ ∃ x ∈ l, ¬p x := by rw [length_eq_countp_add_countp p l, ← countp_pos, countp_eq_length_filter, lt_add_iff_pos_right] lemma sublist.countp_le (s : l₁ <+ l₂) : countp p l₁ ≤ countp p l₂ := by simpa only [countp_eq_length_filter] using length_le_of_sublist (s.filter p) @[simp] lemma countp_filter {q} [decidable_pred q] (l : list α) : countp p (filter q l) = countp (λ a, p a ∧ q a) l := by simp only [countp_eq_length_filter, filter_filter] end countp /-! ### count -/ section count variables [decidable_eq α] @[simp] lemma count_nil (a : α) : count a [] = 0 := rfl lemma count_cons (a b : α) (l : list α) : count a (b :: l) = if a = b then succ (count a l) else count a l := rfl lemma count_cons' (a b : α) (l : list α) : count a (b :: l) = count a l + (if a = b then 1 else 0) := begin rw count_cons, split_ifs; refl end @[simp] lemma count_cons_self (a : α) (l : list α) : count a (a::l) = succ (count a l) := if_pos rfl @[simp, priority 990] lemma count_cons_of_ne {a b : α} (h : a ≠ b) (l : list α) : count a (b::l) = count a l := if_neg h lemma count_tail : Π (l : list α) (a : α) (h : 0 < l.length), l.tail.count a = l.count a - ite (a = list.nth_le l 0 h) 1 0 | (_ :: _) a h := by { rw [count_cons], split_ifs; simp } lemma sublist.count_le (h : l₁ <+ l₂) (a : α) : count a l₁ ≤ count a l₂ := h.countp_le _ lemma count_le_count_cons (a b : α) (l : list α) : count a l ≤ count a (b :: l) := (sublist_cons _ _).count_le _ lemma count_singleton (a : α) : count a [a] = 1 := if_pos rfl @[simp] lemma count_append (a : α) : ∀ l₁ l₂, count a (l₁ ++ l₂) = count a l₁ + count a l₂ := countp_append _ lemma count_concat (a : α) (l : list α) : count a (concat l a) = succ (count a l) := by simp [-add_comm] lemma count_pos {a : α} {l : list α} : 0 < count a l ↔ a ∈ l := by simp only [count, countp_pos, exists_prop, exists_eq_right'] @[simp, priority 980] lemma count_eq_zero_of_not_mem {a : α} {l : list α} (h : a ∉ l) : count a l = 0 := decidable.by_contradiction $ λ h', h $ count_pos.1 (nat.pos_of_ne_zero h') lemma not_mem_of_count_eq_zero {a : α} {l : list α} (h : count a l = 0) : a ∉ l := λ h', (count_pos.2 h').ne' h @[simp] lemma count_repeat (a : α) (n : ℕ) : count a (repeat a n) = n := by rw [count, countp_eq_length_filter, filter_eq_self.2, length_repeat]; exact λ b m, (eq_of_mem_repeat m).symm lemma le_count_iff_repeat_sublist {a : α} {l : list α} {n : ℕ} : n ≤ count a l ↔ repeat a n <+ l := ⟨λ h, ((repeat_sublist_repeat a).2 h).trans $ have filter (eq a) l = repeat a (count a l), from eq_repeat.2 ⟨by simp only [count, countp_eq_length_filter], λ b m, (of_mem_filter m).symm⟩, by rw ← this; apply filter_sublist, λ h, by simpa only [count_repeat] using h.count_le a⟩ lemma repeat_count_eq_of_count_eq_length {a : α} {l : list α} (h : count a l = length l) : repeat a (count a l) = l := eq_of_sublist_of_length_eq (le_count_iff_repeat_sublist.mp (le_refl (count a l))) (eq.trans (length_repeat a (count a l)) h) @[simp] lemma count_filter {p} [decidable_pred p] {a} {l : list α} (h : p a) : count a (filter p l) = count a l := by simp only [count, countp_filter]; congr; exact set.ext (λ b, and_iff_left_of_imp (λ e, e ▸ h)) lemma count_bind {α β} [decidable_eq β] (l : list α) (f : α → list β) (x : β) : count x (l.bind f) = sum (map (count x ∘ f) l) := begin induction l with hd tl IH, { simp }, { simpa } end @[simp] lemma count_map_map {α β} [decidable_eq α] [decidable_eq β] (l : list α) (f : α → β) (hf : function.injective f) (x : α) : count (f x) (map f l) = count x l := begin induction l with y l IH generalizing x, { simp }, { rw map_cons, by_cases h : x = y, { simpa [h] using IH _ }, { simpa [h, hf.ne h] using IH _ } } end @[simp] lemma count_erase_self (a : α) : ∀ (s : list α), count a (list.erase s a) = pred (count a s) | [] := by simp | (h :: t) := begin rw erase_cons, by_cases p : h = a, { rw [if_pos p, count_cons', if_pos p.symm], simp }, { rw [if_neg p, count_cons', count_cons', if_neg (λ x : a = h, p x.symm), count_erase_self], simp } end @[simp] lemma count_erase_of_ne {a b : α} (ab : a ≠ b) : ∀ (s : list α), count a (list.erase s b) = count a s | [] := by simp | (x :: xs) := begin rw erase_cons, split_ifs with h, { rw [count_cons', h, if_neg ab], simp }, { rw [count_cons', count_cons', count_erase_of_ne] } end end count end list
3f7a1cefd19b9ba4e318aa85001836b05c433fd5
82b86ba2ae0d5aed0f01f49c46db5afec0eb2bd7
/src/Lean/Elab/App.lean
09a437349d53101c67459ffd3e225f135e03013d
[ "Apache-2.0" ]
permissive
banksonian/lean4
3a2e6b0f1eb63aa56ff95b8d07b2f851072d54dc
78da6b3aa2840693eea354a41e89fc5b212a5011
refs/heads/master
1,673,703,624,165
1,605,123,551,000
1,605,123,551,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
38,796
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Util.FindMVar import Lean.Elab.Term import Lean.Elab.Binders import Lean.Elab.SyntheticMVars namespace Lean.Elab.Term open Meta /-- Auxiliary inductive datatype for combining unelaborated syntax and already elaborated expressions. It is used to elaborate applications. -/ inductive Arg | stx (val : Syntax) | expr (val : Expr) instance : Inhabited Arg := ⟨Arg.stx (arbitrary _)⟩ instance : ToString Arg := ⟨fun | Arg.stx val => toString val | Arg.expr val => toString val⟩ /-- Named arguments created using the notation `(x := val)` -/ structure NamedArg := (ref : Syntax := Syntax.missing) (name : Name) (val : Arg) instance : ToString NamedArg := ⟨fun s => "(" ++ toString s.name ++ " := " ++ toString s.val ++ ")"⟩ instance : Inhabited NamedArg := ⟨{ name := arbitrary _, val := arbitrary _ }⟩ def throwInvalidNamedArg {α} (namedArg : NamedArg) (fn? : Option Name) : TermElabM α := withRef namedArg.ref $ match fn? with | some fn => throwError! "invalid argument name '{namedArg.name}' for function '{fn}'" | none => throwError! "invalid argument name '{namedArg.name}' for function" /-- Add a new named argument to `namedArgs`, and throw an error if it already contains a named argument with the same name. -/ def addNamedArg (namedArgs : Array NamedArg) (namedArg : NamedArg) : TermElabM (Array NamedArg) := do if namedArgs.any (namedArg.name == ·.name) then throwError! "argument '{namedArg.name}' was already set" pure $ namedArgs.push namedArg private def ensureArgType (f : Expr) (arg : Expr) (expectedType : Expr) : TermElabM Expr := do let argType ← inferType arg ensureHasTypeAux expectedType argType arg f /- Relevant definitions: ``` class CoeFun (α : Sort u) (γ : α → outParam (Sort v)) abbrev coeFun {α : Sort u} {γ : α → Sort v} (a : α) [CoeFun α γ] : γ a ``` -/ private def tryCoeFun? (α : Expr) (a : Expr) : TermElabM (Option Expr) := do let v ← mkFreshLevelMVar let type ← mkArrow α (mkSort v) let γ ← mkFreshExprMVar type let u ← getLevel α let coeFunInstType := mkAppN (Lean.mkConst `CoeFun [u, v]) #[α, γ] let mvar ← mkFreshExprMVar coeFunInstType MetavarKind.synthetic let mvarId := mvar.mvarId! try if (← synthesizeInstMVarCore mvarId) then pure $ some $ mkAppN (Lean.mkConst `coeFun [u, v]) #[α, γ, a, mvar] else pure none catch _ => pure none def synthesizeAppInstMVars (instMVars : Array MVarId) : TermElabM Unit := for mvarId in instMVars do unless (← synthesizeInstMVarCore mvarId) do registerSyntheticMVarWithCurrRef mvarId SyntheticMVarKind.typeClass namespace ElabAppArgs /- Auxiliary structure for elaborating the application `f args namedArgs`. -/ structure State := (explicit : Bool) -- true if `@` modifier was used (f : Expr) (fType : Expr) (args : List Arg) -- remaining regular arguments (namedArgs : List NamedArg) -- remaining named arguments to be processed (ellipsis : Bool := false) (expectedType? : Option Expr) (etaArgs : Array Expr := #[]) (toSetErrorCtx : Array MVarId := #[]) -- metavariables that we need the set the error context using the application being built (instMVars : Array MVarId := #[]) -- metavariables for the instance implicit arguments that have already been processed -- The following two fields are used to implement the `propagateExpectedType` heuristic. (typeMVars : Array MVarId := #[]) -- metavariables for implicit arguments of the form `{α : Sort u}` that have already been processed (alreadyPropagated : Bool := false) -- true when expectedType has already been propagated abbrev M := StateRefT State TermElabM /- Add the given metavariable to the collection of metavariables associated with instance-implicit arguments. -/ private def addInstMVar (mvarId : MVarId) : M Unit := modify fun s => { s with instMVars := s.instMVars.push mvarId } /- Try to synthesize metavariables are `instMVars` using type class resolution. The ones that cannot be synthesized yet are registered. Remark: we use this method before trying to apply coercions to function. -/ def synthesizeAppInstMVars : M Unit := do let s ← get let instMVars := s.instMVars modify fun s => { s with instMVars := #[] } Lean.Elab.Term.synthesizeAppInstMVars instMVars /- fType may become a forallE after we synthesize pending metavariables. -/ private def synthesizePendingAndNormalizeFunType : M Unit := do synthesizeAppInstMVars synthesizeSyntheticMVars let s ← get let fType ← whnfForall s.fType match fType with | Expr.forallE _ _ _ _ => modify fun s => { s with fType := fType } | _ => match (← tryCoeFun? fType s.f) with | some f => let fType ← inferType f modify fun s => { s with f := f, fType := fType } | none => for namedArg in s.namedArgs do match s.f.getAppFn with | Expr.const fn .. => throwInvalidNamedArg namedArg fn | _ => throwInvalidNamedArg namedArg none throwError! "function expected at{indentExpr s.f}\nterm has type{indentExpr fType}" /- Normalize and return the function type. -/ private def normalizeFunType : M Expr := do let s ← get let fType ← whnfForall s.fType modify fun s => { s with fType := fType } pure fType /- Return the binder name at `fType`. This method assumes `fType` is a function type. -/ private def getBindingName : M Name := return (← get).fType.bindingName! /- Return the next argument expected type. This method assumes `fType` is a function type. -/ private def getArgExpectedType : M Expr := return (← get).fType.bindingDomain! def eraseNamedArgCore (namedArgs : List NamedArg) (binderName : Name) : List NamedArg := namedArgs.filter (·.name != binderName) /- Remove named argument with name `binderName` from `namedArgs`. -/ def eraseNamedArg (binderName : Name) : M Unit := modify fun s => { s with namedArgs := eraseNamedArgCore s.namedArgs binderName } /- Return true if the next argument at `args` is of the form `_` -/ private def isNextArgHole : M Bool := do match (← get).args with | Arg.stx (Syntax.node `Lean.Parser.Term.hole _) :: _ => pure true | _ => pure false /- Add a new argument to the result. That is, `f := f arg`, update `fType`. This method assumes `fType` is a function type. -/ private def addNewArg (arg : Expr) : M Unit := modify fun s => { s with f := mkApp s.f arg, fType := s.fType.bindingBody!.instantiate1 arg } /- Elaborate the given `Arg` and add it to the result. See `addNewArg`. Recall that, `Arg` may be wrapping an already elaborated `Expr`. -/ private def elabAndAddNewArg (arg : Arg) : M Unit := do let s ← get let expectedType ← getArgExpectedType match arg with | Arg.expr val => let arg ← ensureArgType s.f val expectedType addNewArg arg | Arg.stx val => let val ← elabTerm val expectedType let arg ← ensureArgType s.f val expectedType addNewArg arg /- Return true if the given type contains `OptParam` or `AutoParams` -/ private def hasOptAutoParams (type : Expr) : M Bool := do forallTelescopeReducing type fun xs type => xs.anyM fun x => do let xType ← inferType x pure $ xType.getOptParamDefault?.isSome || xType.getAutoParamTactic?.isSome /- Return true if `fType` contains `OptParam` or `AutoParams` -/ private def fTypeHasOptAutoParams : M Bool := do hasOptAutoParams (← get).fType /- Auxiliary function for retrieving the resulting type of a function application. See `propagateExpectedType`. -/ private partial def getForallBody : Nat → List NamedArg → Expr → Option Expr | i, namedArgs, type@(Expr.forallE n d b c) => match namedArgs.find? fun (namedArg : NamedArg) => namedArg.name == n with | some _ => getForallBody i (eraseNamedArgCore namedArgs n) b | none => if !c.binderInfo.isExplicit then getForallBody i namedArgs b else if i > 0 then getForallBody (i-1) namedArgs b else if d.isAutoParam || d.isOptParam then getForallBody i namedArgs b else some type | 0, [], type => some type | _, _, _ => none /- Auxiliary method for propagating the expected type. We call it as soon as we find the first explict argument. The goal is to propagate the expected type in applications of functions such as ```lean Add.add {α : Type u} : α → α → α List.cons {α : Type u} : α → List α → List α ``` This is particularly useful when there applicable coercions. For example, assume we have a coercion from `Nat` to `Int`, and we have `(x : Nat)` and the expected type is `List Int`. Then, if we don't use this function, the elaborator will fail to elaborate ``` List.cons x [] ``` First, the elaborator creates a new metavariable `?α` for the implicit argument `{α : Type u}`. Then, when it processes `x`, it assigns `?α := Nat`, and then obtain the resultant type `List Nat` which is **not** definitionally equal to `List Int`. We solve the problem by executing this method before we elaborate the first explicit argument (`x` in this example). This method infers that the resultant type is `List ?α` and unifies it with `List Int`. Then, when we elaborate `x`, the elaborate realizes the coercion from `Nat` to `Int` must be used, and the term ``` @List.cons Int (coe x) (@List.nil Int) ``` is produced. The method will do nothing if 1- The resultant type depends on the remaining arguments (i.e., `!eTypeBody.hasLooseBVars`) 2- The resultant type does not contain any type metavariable. 3- The resultant type contains a nontype metavariable. We added conditions 2&3 to be able to restrict this method to simple functions that are "morally" in the Hindley&Milner fragment. For example, consider the following definitions ``` def foo {n m : Nat} (a : bv n) (b : bv m) : bv (n - m) ``` Now, consider ``` def test (x1 : bv 32) (x2 : bv 31) (y1 : bv 64) (y2 : bv 63) : bv 1 := foo x1 x2 = foo y1 y2 ``` When the elaborator reaches the term `foo y1 y2`, the expected type is `bv (32-31)`. If we apply this method, we would solve the unification problem `bv (?n - ?m) =?= bv (32 - 31)`, by assigning `?n := 32` and `?m := 31`. Then, the elaborator fails elaborating `y1` since `bv 64` is **not** definitionally equal to `bv 32`. -/ private def propagateExpectedType : M Unit := do let s ← get -- TODO: handle s.etaArgs.size > 0 unless s.explicit || !s.etaArgs.isEmpty || s.alreadyPropagated || s.typeMVars.isEmpty do modify fun s => { s with alreadyPropagated := true } match s.expectedType? with | none => pure () | some expectedType => let numRemainingArgs := s.args.length trace[Elab.app.propagateExpectedType]! "etaArgs.size: {s.etaArgs.size}, numRemainingArgs: {numRemainingArgs}, fType: {s.fType}" match getForallBody numRemainingArgs s.namedArgs s.fType with | none => pure () | some fTypeBody => unless fTypeBody.hasLooseBVars do let hasTypeMVar := (fTypeBody.findMVar? fun mvarId => s.typeMVars.contains mvarId).isSome let hasOnlyTypeMVar := (fTypeBody.findMVar? fun mvarId => !s.typeMVars.contains mvarId).isNone if hasTypeMVar && hasOnlyTypeMVar then unless (← hasOptAutoParams fTypeBody) do trace[Elab.app.propagateExpectedType]! "{expectedType} =?= {fTypeBody}" isDefEq expectedType fTypeBody pure () /- Create a fresh local variable with the current binder name and argument type, add it to `etaArgs` and `f`, and then execute the continuation `k`.-/ private def addEtaArg (k : M Expr) : M Expr := do let n ← getBindingName let type ← getArgExpectedType withLocalDeclD n type fun x => do modify fun s => { s with etaArgs := s.etaArgs.push x } addNewArg x k /- This method execute after all application arguments have been processed. -/ private def finalize : M Expr := do let s ← get let mut e := s.f let mut eType := s.fType -- all user explicit arguments have been consumed trace[Elab.app.finalize]! e let ref ← getRef -- Register the error context of implicits for mvarId in s.toSetErrorCtx do registerMVarErrorImplicitArgInfo mvarId ref e if !s.etaArgs.isEmpty then e ← mkLambdaFVars s.etaArgs e eType ← inferType e trace[Elab.app.finalize]! "after etaArgs, {e} : {eType}" match s.expectedType? with | none => pure () | some expectedType => trace[Elab.app.finalize]! "expected type: {expectedType}" -- Try to propagate expected type. Ignore if types are not definitionally equal, caller must handle it. isDefEq expectedType eType pure () synthesizeAppInstMVars pure e private def addImplicitArg (k : M Expr) : M Expr := do let argType ← getArgExpectedType let arg ← mkFreshExprMVar argType if (← isTypeFormer arg) then modify fun s => { s with typeMVars := s.typeMVars.push arg.mvarId!, toSetErrorCtx := s.toSetErrorCtx.push arg.mvarId! } addNewArg arg k /- Process a `fType` of the form `(x : A) → B x`. This method assume `fType` is a function type -/ private def processExplictArg (k : M Expr) : M Expr := do let s ← get match s.args with | arg::args => propagateExpectedType modify fun s => { s with args := args } elabAndAddNewArg arg k | _ => let argType ← getArgExpectedType match s.explicit, argType.getOptParamDefault?, argType.getAutoParamTactic? with | false, some defVal, _ => addNewArg defVal; k | false, _, some (Expr.const tacticDecl _ _) => let env ← getEnv let opts ← getOptions match evalSyntaxConstant env opts tacticDecl with | Except.error err => throwError err | Except.ok tacticSyntax => let tacticBlock ← `(by { $(tacticSyntax.getArgs)* }) -- tacticBlock does not have any position information. -- So, we use the current ref let ref ← getRef let tacticBlock := tacticBlock.copyInfo ref let argType := argType.getArg! 0 -- `autoParam type := by tactic` ==> `type` propagateExpectedType elabAndAddNewArg (Arg.stx tacticBlock) k | false, _, some _ => throwError "invalid autoParam, argument must be a constant" | _, _, _ => if !s.namedArgs.isEmpty then addEtaArg k else if !s.explicit then if (← fTypeHasOptAutoParams) then addEtaArg k else if (← get).ellipsis then addImplicitArg k else finalize else finalize /- Process a `fType` of the form `{x : A} → B x`. This method assume `fType` is a function type -/ private def processImplicitArg (k : M Expr) : M Expr := do if (← get).explicit then processExplictArg k else addImplicitArg k /- Process a `fType` of the form `[x : A] → B x`. This method assume `fType` is a function type -/ private def processInstImplicitArg (k : M Expr) : M Expr := do if (← get).explicit then let isHole ← isNextArgHole if isHole then /- Recall that if '@' has been used, and the argument is '_', then we still use type class resolution -/ let arg ← mkFreshExprMVar (← getArgExpectedType) MetavarKind.synthetic modify fun s => { s with args := s.args.tail! } addInstMVar arg.mvarId! addNewArg arg k else processExplictArg k else let arg ← mkFreshExprMVar (← getArgExpectedType) MetavarKind.synthetic addInstMVar arg.mvarId! addNewArg arg k /- Return true if there are regular or named arguments to be processed. -/ private def hasArgsToProcess : M Bool := do let s ← get pure $ !s.args.isEmpty || !s.namedArgs.isEmpty /- Elaborate function application arguments. -/ partial def main : M Expr := do let s ← get let fType ← normalizeFunType match fType with | Expr.forallE binderName _ _ c => let s ← get match s.namedArgs.find? fun (namedArg : NamedArg) => namedArg.name == binderName with | some namedArg => propagateExpectedType eraseNamedArg binderName elabAndAddNewArg namedArg.val main | none => match c.binderInfo with | BinderInfo.implicit => processImplicitArg main | BinderInfo.instImplicit => processInstImplicitArg main | _ => processExplictArg main | _ => if (← hasArgsToProcess) then synthesizePendingAndNormalizeFunType main else finalize end ElabAppArgs private def elabAppArgs (f : Expr) (namedArgs : Array NamedArg) (args : Array Arg) (expectedType? : Option Expr) (explicit ellipsis : Bool) : TermElabM Expr := do let fType ← inferType f let fType ← instantiateMVars fType trace[Elab.app.args]! "explicit: {explicit}, {f} : {fType}" unless namedArgs.isEmpty && args.isEmpty do tryPostponeIfMVar fType ElabAppArgs.main.run' { args := args.toList, expectedType? := expectedType?, explicit := explicit, ellipsis := ellipsis, namedArgs := namedArgs.toList, f := f, fType := fType } /-- Auxiliary inductive datatype that represents the resolution of an `LVal`. -/ inductive LValResolution | projFn (baseStructName : Name) (structName : Name) (fieldName : Name) | projIdx (structName : Name) (idx : Nat) | const (baseStructName : Name) (structName : Name) (constName : Name) | localRec (baseName : Name) (fullName : Name) (fvar : Expr) | getOp (fullName : Name) (idx : Syntax) private def throwLValError {α} (e : Expr) (eType : Expr) (msg : MessageData) : TermElabM α := throwError! "{msg}{indentExpr e}\nhas type{indentExpr eType}" /-- `findMethod? env S fName`. 1- If `env` contains `S ++ fName`, return `(S, S++fName)` 2- Otherwise if `env` contains private name `prv` for `S ++ fName`, return `(S, prv)`, o 3- Otherwise for each parent structure `S'` of `S`, we try `findMethod? env S' fname` -/ private partial def findMethod? (env : Environment) (structName fieldName : Name) : Option (Name × Name) := let fullName := structName ++ fieldName match env.find? fullName with | some _ => some (structName, fullName) | none => let fullNamePrv := mkPrivateName env fullName match env.find? fullNamePrv with | some _ => some (structName, fullNamePrv) | none => if isStructureLike env structName then (getParentStructures env structName).findSome? fun parentStructName => findMethod? env parentStructName fieldName else none private def resolveLValAux (e : Expr) (eType : Expr) (lval : LVal) : TermElabM LValResolution := do match eType.getAppFn, lval with | Expr.const structName _ _, LVal.fieldIdx idx => if idx == 0 then throwError "invalid projection, index must be greater than 0" let env ← getEnv unless isStructureLike env structName do throwLValError e eType "invalid projection, structure expected" let fieldNames := getStructureFields env structName if h : idx - 1 < fieldNames.size then if isStructure env structName then pure $ LValResolution.projFn structName structName (fieldNames.get ⟨idx - 1, h⟩) else /- `structName` was declared using `inductive` command. So, we don't projection functions for it. Thus, we use `Expr.proj` -/ pure $ LValResolution.projIdx structName (idx - 1) else throwLValError e eType msg!"invalid projection, structure has only {fieldNames.size} field(s)" | Expr.const structName _ _, LVal.fieldName fieldName => let env ← getEnv let searchEnv : Unit → TermElabM LValResolution := fun _ => do match findMethod? env structName (Name.mkSimple fieldName) with | some (baseStructName, fullName) => pure $ LValResolution.const baseStructName structName fullName | none => throwLValError e eType msg!"invalid field notation, '{fieldName}' is not a valid \"field\" because environment does not contain '{Name.mkStr structName fieldName}'" -- search local context first, then environment let searchCtx : Unit → TermElabM LValResolution := fun _ => do let fullName := Name.mkStr structName fieldName let currNamespace ← getCurrNamespace let localName := fullName.replacePrefix currNamespace Name.anonymous let lctx ← getLCtx match lctx.findFromUserName? localName with | some localDecl => if localDecl.binderInfo == BinderInfo.auxDecl then /- LVal notation is being used to make a "local" recursive call. -/ pure $ LValResolution.localRec structName fullName localDecl.toExpr else searchEnv () | none => searchEnv () if isStructure env structName then match findField? env structName (Name.mkSimple fieldName) with | some baseStructName => pure $ LValResolution.projFn baseStructName structName (Name.mkSimple fieldName) | none => searchCtx () else searchCtx () | Expr.const structName _ _, LVal.getOp idx => let env ← getEnv let fullName := Name.mkStr structName "getOp" match env.find? fullName with | some _ => pure $ LValResolution.getOp fullName idx | none => throwLValError e eType msg!"invalid [..] notation because environment does not contain '{fullName}'" | _, LVal.getOp idx => throwLValError e eType "invalid [..] notation, type is not of the form (C ...) where C is a constant" | _, _ => throwLValError e eType "invalid field notation, type is not of the form (C ...) where C is a constant" /- whnfCore + implicit consumption. Example: given `e` with `eType := {α : Type} → (fun β => List β) α `, it produces `(e ?m, List ?m)` where `?m` is fresh metavariable. -/ private partial def consumeImplicits (e eType : Expr) : TermElabM (Expr × Expr) := do let eType ← whnfCore eType match eType with | Expr.forallE n d b c => if !c.binderInfo.isExplicit then let mvar ← mkFreshExprMVar d consumeImplicits (mkApp e mvar) (b.instantiate1 mvar) else match d.getOptParamDefault? with | some defVal => consumeImplicits (mkApp e defVal) (b.instantiate1 defVal) -- TODO: we do not handle autoParams here. | _ => pure (e, eType) | _ => pure (e, eType) private partial def resolveLValLoop (lval : LVal) (e eType : Expr) (previousExceptions : Array Exception) : TermElabM (Expr × LValResolution) := do let (e, eType) ← consumeImplicits e eType tryPostponeIfMVar eType try let lvalRes ← resolveLValAux e eType lval pure (e, lvalRes) catch | ex@(Exception.error _ _) => let eType? ← unfoldDefinition? eType match eType? with | some eType => resolveLValLoop lval e eType (previousExceptions.push ex) | none => previousExceptions.forM fun ex => logException ex throw ex | ex@(Exception.internal _) => throw ex private def resolveLVal (e : Expr) (lval : LVal) : TermElabM (Expr × LValResolution) := do let eType ← inferType e resolveLValLoop lval e eType #[] private partial def mkBaseProjections (baseStructName : Name) (structName : Name) (e : Expr) : TermElabM Expr := do let env ← getEnv match getPathToBaseStructure? env baseStructName structName with | none => throwError "failed to access field in parent structure" | some path => let mut e := e for projFunName in path do let projFn ← mkConst projFunName e ← elabAppArgs projFn #[{ name := `self, val := Arg.expr e }] (args := #[]) (expectedType? := none) (explicit := false) (ellipsis := false) return e /- Auxiliary method for field notation. It tries to add `e` to `args` as the first explicit parameter which takes an element of type `(C ...)` where `C` is `baseName`. `fullName` is the name of the resolved "field" access function. It is used for reporting errors -/ private def addLValArg (baseName : Name) (fullName : Name) (e : Expr) (args : Array Arg) (namedArgs : Array NamedArg) (fType : Expr) : TermElabM (Array Arg) := forallTelescopeReducing fType fun xs _ => do let mut i := 0 let mut namedArgs := namedArgs for x in xs do let xDecl ← getLocalDecl x.fvarId! if xDecl.binderInfo.isExplicit then /- If there is named argument with name `xDecl.userName`, then we skip it. -/ match namedArgs.findIdx? (fun namedArg => namedArg.name == xDecl.userName) with | some idx => namedArgs := namedArgs.eraseIdx idx | none => let type := xDecl.type if type.consumeMData.isAppOf baseName then -- found it return args.insertAt i (Arg.expr e) -- normalize type and try again let type ← withReducible $ whnf type if type.consumeMData.isAppOf baseName then -- found it return args.insertAt i (Arg.expr e) if i < args.size then i := i + 1 else for namedArg in namedArgs do throwInvalidNamedArg namedArg fullName throwError! "invalid field notation, function '{fullName}' does not have explicit argument with type ({baseName} ...)" return args private def elabAppLValsAux (namedArgs : Array NamedArg) (args : Array Arg) (expectedType? : Option Expr) (explicit ellipsis : Bool) (f : Expr) (lvals : List LVal) : TermElabM Expr := let rec loop : Expr → List LVal → TermElabM Expr | f, [] => elabAppArgs f namedArgs args expectedType? explicit ellipsis | f, lval::lvals => do let (f, lvalRes) ← resolveLVal f lval match lvalRes with | LValResolution.projIdx structName idx => let f := mkProj structName idx f loop f lvals | LValResolution.projFn baseStructName structName fieldName => let f ← mkBaseProjections baseStructName structName f let projFn ← mkConst (baseStructName ++ fieldName) if lvals.isEmpty then let namedArgs ← addNamedArg namedArgs { name := `self, val := Arg.expr f } elabAppArgs projFn namedArgs args expectedType? explicit ellipsis else let f ← elabAppArgs projFn #[{ name := `self, val := Arg.expr f }] #[] (expectedType? := none) (explicit := false) (ellipsis := false) loop f lvals | LValResolution.const baseStructName structName constName => let f ← if baseStructName != structName then mkBaseProjections baseStructName structName f else pure f let projFn ← mkConst constName if lvals.isEmpty then let projFnType ← inferType projFn let args ← addLValArg baseStructName constName f args namedArgs projFnType elabAppArgs projFn namedArgs args expectedType? explicit ellipsis else let f ← elabAppArgs projFn #[] #[Arg.expr f] (expectedType? := none) (explicit := false) (ellipsis := false) loop f lvals | LValResolution.localRec baseName fullName fvar => if lvals.isEmpty then let fvarType ← inferType fvar let args ← addLValArg baseName fullName f args namedArgs fvarType elabAppArgs fvar namedArgs args expectedType? explicit ellipsis else let f ← elabAppArgs fvar #[] #[Arg.expr f] (expectedType? := none) (explicit := false) (ellipsis := false) loop f lvals | LValResolution.getOp fullName idx => let getOpFn ← mkConst fullName if lvals.isEmpty then let namedArgs ← addNamedArg namedArgs { name := `self, val := Arg.expr f } let namedArgs ← addNamedArg namedArgs { name := `idx, val := Arg.stx idx } elabAppArgs getOpFn namedArgs args expectedType? explicit ellipsis else let f ← elabAppArgs getOpFn #[{ name := `self, val := Arg.expr f }, { name := `idx, val := Arg.stx idx }] #[] (expectedType? := none) (explicit := false) (ellipsis := false) loop f lvals loop f lvals private def elabAppLVals (f : Expr) (lvals : List LVal) (namedArgs : Array NamedArg) (args : Array Arg) (expectedType? : Option Expr) (explicit ellipsis : Bool) : TermElabM Expr := do if !lvals.isEmpty && explicit then throwError "invalid use of field notation with `@` modifier" elabAppLValsAux namedArgs args expectedType? explicit ellipsis f lvals def elabExplicitUnivs (lvls : Array Syntax) : TermElabM (List Level) := do lvls.foldrM (fun stx lvls => do pure ((← elabLevel stx)::lvls)) [] /- Interaction between `errToSorry` and `observing`. - The method `elabTerm` catches exceptions, log them, and returns a synthetic sorry (IF `ctx.errToSorry` == true). - When we elaborate choice nodes (and overloaded identifiers), we track multiple results using the `observing x` combinator. The `observing x` executes `x` and returns a `TermElabResult`. `observing `x does not check for synthetic sorry's, just an exception. Thus, it may think `x` worked when it didn't if a synthetic sorry was introduced. We decided that checking for synthetic sorrys at `observing` is not a good solution because it would not be clear to decide what the "main" error message for the alternative is. When the result contains a synthetic `sorry`, it is not clear which error message corresponds to the `sorry`. Moreover, while executing `x`, many error messages may have been logged. Recall that we need an error per alternative at `mergeFailures`. Thus, we decided to set `errToSorry` to `false` whenever processing choice nodes and overloaded symbols. Important: we rely on the property that after `errToSorry` is set to false, no elaboration function executed by `x` will reset it to `true`. -/ private partial def elabAppFnId (fIdent : Syntax) (fExplicitUnivs : List Level) (lvals : List LVal) (namedArgs : Array NamedArg) (args : Array Arg) (expectedType? : Option Expr) (explicit ellipsis overloaded : Bool) (acc : Array TermElabResult) : TermElabM (Array TermElabResult) := do match fIdent with | Syntax.ident _ _ n preresolved => let funLVals ← withRef fIdent $ resolveName n preresolved fExplicitUnivs let overloaded := overloaded || funLVals.length > 1 -- Set `errToSorry` to `false` if `funLVals` > 1. See comment above about the interaction between `errToSorry` and `observing`. withReader (fun ctx => { ctx with errToSorry := funLVals.length == 1 && ctx.errToSorry }) do funLVals.foldlM (init := acc) fun acc ⟨f, fields⟩ => do let lvals' := fields.map LVal.fieldName let s ← observing do let e ← elabAppLVals f (lvals' ++ lvals) namedArgs args expectedType? explicit ellipsis if overloaded then ensureHasType expectedType? e else pure e pure $ acc.push s | _ => throwUnsupportedSyntax private partial def elabAppFn (f : Syntax) (lvals : List LVal) (namedArgs : Array NamedArg) (args : Array Arg) (expectedType? : Option Expr) (explicit ellipsis overloaded : Bool) (acc : Array TermElabResult) : TermElabM (Array TermElabResult) := if f.getKind == choiceKind then -- Set `errToSorry` to `false` when processing choice nodes. See comment above about the interaction between `errToSorry` and `observing`. withReader (fun ctx => { ctx with errToSorry := false }) do f.getArgs.foldlM (fun acc f => elabAppFn f lvals namedArgs args expectedType? explicit ellipsis true acc) acc else match_syntax f with | `($(e).$idx:fieldIdx) => let idx := idx.isFieldIdx?.get! elabAppFn e (LVal.fieldIdx idx :: lvals) namedArgs args expectedType? explicit ellipsis overloaded acc | `($e $.$field) => do let f ← `($(e).$field) elabAppFn f lvals namedArgs args expectedType? explicit ellipsis overloaded acc | `($(e).$field:ident) => let newLVals := field.getId.eraseMacroScopes.components.map (fun n => LVal.fieldName (toString n)) elabAppFn e (newLVals ++ lvals) namedArgs args expectedType? explicit ellipsis overloaded acc | `($e[$idx]) => elabAppFn e (LVal.getOp idx :: lvals) namedArgs args expectedType? explicit ellipsis overloaded acc | `($id:ident@$t:term) => throwError "unexpected occurrence of named pattern" | `($id:ident) => do elabAppFnId id [] lvals namedArgs args expectedType? explicit ellipsis overloaded acc | `($id:ident.{$us*}) => do let us ← elabExplicitUnivs us.getSepElems elabAppFnId id us lvals namedArgs args expectedType? explicit ellipsis overloaded acc | `(@$id:ident) => elabAppFn id lvals namedArgs args expectedType? (explicit := true) ellipsis overloaded acc | `(@$id:ident.{$us*}) => elabAppFn (f.getArg 1) lvals namedArgs args expectedType? (explicit := true) ellipsis overloaded acc | `(@$t) => throwUnsupportedSyntax -- invalid occurrence of `@` | `(_) => throwError "placeholders '_' cannot be used where a function is expected" | _ => do let catchPostpone := !overloaded /- If we are processing a choice node, then we should use `catchPostpone == false` when elaborating terms. Recall that `observing` does not catch `postponeExceptionId`. -/ if lvals.isEmpty && namedArgs.isEmpty && args.isEmpty then /- Recall that elabAppFn is used for elaborating atomics terms **and** choice nodes that may contain arbitrary terms. If they are not being used as a function, we should elaborate using the expectedType. -/ let s ← if overloaded then observing $ elabTermEnsuringType f expectedType? catchPostpone else observing $ elabTerm f expectedType? pure $ acc.push s else let s ← observing do let f ← elabTerm f none catchPostpone let e ← elabAppLVals f lvals namedArgs args expectedType? explicit ellipsis if overloaded then ensureHasType expectedType? e else pure e pure $ acc.push s private def isSuccess (candidate : TermElabResult) : Bool := match candidate with | EStateM.Result.ok _ _ => true | _ => false private def getSuccess (candidates : Array TermElabResult) : Array TermElabResult := candidates.filter isSuccess private def toMessageData (ex : Exception) : TermElabM MessageData := do let pos ← getRefPos match ex.getRef.getPos with | none => pure ex.toMessageData | some exPos => if pos == exPos then pure ex.toMessageData else let fileMap ← MonadLog.getFileMap -- Remove `MonadLog.` it is a workaround for old frontend let exPosition := fileMap.toPosition exPos pure msg!"{exPosition.line}:{exPosition.column} {ex.toMessageData}" private def toMessageList (msgs : Array MessageData) : MessageData := indentD (MessageData.joinSep msgs.toList (Format.line ++ Format.line)) private def mergeFailures {α} (failures : Array TermElabResult) : TermElabM α := do let msgs ← failures.mapM fun failure => match failure with | EStateM.Result.ok _ _ => unreachable! | EStateM.Result.error ex _ => toMessageData ex throwError! "overloaded, errors {toMessageList msgs}" private def elabAppAux (f : Syntax) (namedArgs : Array NamedArg) (args : Array Arg) (ellipsis : Bool) (expectedType? : Option Expr) : TermElabM Expr := do let candidates ← elabAppFn f [] namedArgs args expectedType? (explicit := false) (ellipsis := ellipsis) (overloaded := false) #[] if candidates.size == 1 then applyResult candidates[0] else let successes := getSuccess candidates if successes.size == 1 then let e ← applyResult successes[0] pure e else if successes.size > 1 then let lctx ← getLCtx let opts ← getOptions let msgs : Array MessageData := successes.map fun success => match success with | EStateM.Result.ok e s => MessageData.withContext { env := s.core.env, mctx := s.meta.mctx, lctx := lctx, opts := opts } e | _ => unreachable! throwErrorAt! f "ambiguous, possible interpretations {toMessageList msgs}" else withRef f $ mergeFailures candidates partial def expandApp (stx : Syntax) (pattern := false) : TermElabM (Syntax × Array NamedArg × Array Arg × Bool) := do let f := stx[0] let args := stx[1].getArgs let (args, ellipsis) := if args.back.isOfKind `Lean.Parser.Term.ellipsis then (args.pop, true) else (args, false) let (namedArgs, args) ← args.foldlM (init := (#[], #[])) fun (namedArgs, args) stx => do if stx.getKind == `Lean.Parser.Term.namedArgument then -- tparser! try ("(" >> ident >> " := ") >> termParser >> ")" let name := stx[1].getId.eraseMacroScopes let val := stx[3] let namedArgs ← addNamedArg namedArgs { ref := stx, name := name, val := Arg.stx val } pure (namedArgs, args) else if stx.getKind == `Lean.Parser.Term.ellipsis then throwErrorAt stx "unexpected '..'" else pure (namedArgs, args.push $ Arg.stx stx) pure (f, namedArgs, args, ellipsis) @[builtinTermElab app] def elabApp : TermElab := fun stx expectedType? => withoutPostponingUniverseConstraints do let (f, namedArgs, args, ellipsis) ← expandApp stx elabAppAux f namedArgs args (ellipsis := ellipsis) expectedType? private def elabAtom : TermElab := fun stx expectedType? => elabAppAux stx #[] #[] (ellipsis := false) expectedType? @[builtinTermElab ident] def elabIdent : TermElab := elabAtom @[builtinTermElab namedPattern] def elabNamedPattern : TermElab := elabAtom @[builtinTermElab explicitUniv] def elabExplicitUniv : TermElab := elabAtom @[builtinTermElab dollarProj] def expandDollarProj : TermElab := elabAtom @[builtinTermElab explicit] def elabExplicit : TermElab := fun stx expectedType? => match_syntax stx with | `(@$id:ident) => elabAtom stx expectedType? -- Recall that `elabApp` also has support for `@` | `(@$id:ident.{$us*}) => elabAtom stx expectedType? | `(@($t)) => elabTermWithoutImplicitLambdas t expectedType? -- `@` is being used just to disable implicit lambdas | `(@$t) => elabTermWithoutImplicitLambdas t expectedType? -- `@` is being used just to disable implicit lambdas | _ => throwUnsupportedSyntax @[builtinTermElab choice] def elabChoice : TermElab := elabAtom @[builtinTermElab proj] def elabProj : TermElab := elabAtom @[builtinTermElab arrayRef] def elabArrayRef : TermElab := elabAtom builtin_initialize registerTraceClass `Elab.app end Lean.Elab.Term
10de26e636dc2244db326de717fc4ae80ea1b21d
08bd4ba4ca87dba1f09d2c96a26f5d65da81f4b4
/src/Lean/Parser/Command.lean
39bffdd827e544deb7986b8fb2c0d7940a0d3679
[ "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "Apache-2.0", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
gebner/lean4
d51c4922640a52a6f7426536ea669ef18a1d9af5
8cd9ce06843c9d42d6d6dc43d3e81e3b49dfc20f
refs/heads/master
1,685,732,780,391
1,672,962,627,000
1,673,459,398,000
373,307,283
0
0
Apache-2.0
1,691,316,730,000
1,622,669,271,000
Lean
UTF-8
Lean
false
false
15,135
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Sebastian Ullrich -/ import Lean.Parser.Term import Lean.Parser.Do namespace Lean namespace Parser /-- Syntax quotation for terms. -/ @[builtin_term_parser] def Term.quot := leading_parser "`(" >> withoutPosition (incQuotDepth termParser) >> ")" @[builtin_term_parser] def Term.precheckedQuot := leading_parser "`" >> Term.quot namespace Command /-- Syntax quotation for (sequences of) commands. The identical syntax for term quotations takes priority, so ambiguous quotations like `` `($x $y) `` will be parsed as an application, not two commands. Use `` `($x:command $y:command) `` instead. Multiple commands will be put in a `` `null `` node, but a single command will not (so that you can directly match against a quotation in a command kind's elaborator). -/ @[builtin_term_parser low] def quot := leading_parser "`(" >> withoutPosition (incQuotDepth (many1Unbox commandParser)) >> ")" /- A mutual block may be broken in different cliques, we identify them using an `ident` (an element of the clique). We provide two kinds of hints to the termination checker: 1- A wellfounded relation (`p` is `termParser`) 2- A tactic for proving the recursive applications are "decreasing" (`p` is `tacticSeq`) -/ def terminationHintMany (p : Parser) := leading_parser atomic (lookahead (ident >> " => ")) >> many1Indent (group (ppLine >> ident >> " => " >> p >> optional ";")) def terminationHint1 (p : Parser) := leading_parser p def terminationHint (p : Parser) := terminationHintMany p <|> terminationHint1 p def terminationByCore := leading_parser "termination_by' " >> terminationHint termParser def decreasingBy := leading_parser "decreasing_by " >> terminationHint Tactic.tacticSeq def terminationByElement := leading_parser ppLine >> (ident <|> Term.hole) >> many (ident <|> Term.hole) >> " => " >> termParser >> optional ";" def terminationBy := leading_parser ppLine >> "termination_by " >> many1Indent terminationByElement def terminationSuffix := optional (terminationBy <|> terminationByCore) >> optional decreasingBy @[builtin_command_parser] def moduleDoc := leading_parser ppDedent <| "/-!" >> commentBody >> ppLine def namedPrio := leading_parser atomic ("(" >> nonReservedSymbol "priority") >> " := " >> withoutPosition priorityParser >> ")" def optNamedPrio := optional (ppSpace >> namedPrio) def «private» := leading_parser "private " def «protected» := leading_parser "protected " def visibility := «private» <|> «protected» def «noncomputable» := leading_parser "noncomputable " def «unsafe» := leading_parser "unsafe " def «partial» := leading_parser "partial " def «nonrec» := leading_parser "nonrec " def declModifiers (inline : Bool) := leading_parser optional docComment >> optional (Term.«attributes» >> if inline then skip else ppDedent ppLine) >> optional visibility >> optional «noncomputable» >> optional «unsafe» >> optional («partial» <|> «nonrec») def declId := leading_parser ident >> optional (".{" >> sepBy1 ident ", " >> "}") def declSig := leading_parser many (ppSpace >> (Term.binderIdent <|> Term.bracketedBinder)) >> Term.typeSpec def optDeclSig := leading_parser many (ppSpace >> (Term.binderIdent <|> Term.bracketedBinder)) >> Term.optType def declValSimple := leading_parser " :=" >> ppHardLineUnlessUngrouped >> termParser >> optional Term.whereDecls def declValEqns := leading_parser Term.matchAltsWhereDecls def whereStructField := leading_parser Term.letDecl def whereStructInst := leading_parser ppIndent ppSpace >> "where" >> sepByIndent (ppGroup whereStructField) "; " (allowTrailingSep := true) >> optional Term.whereDecls /- Remark: we should not use `Term.whereDecls` at `declVal` because `Term.whereDecls` is defined using `Term.letRecDecl` which may contain attributes. Issue #753 showns an example that fails to be parsed when we used `Term.whereDecls`. -/ def declVal := withAntiquot (mkAntiquot "declVal" `Lean.Parser.Command.declVal (isPseudoKind := true)) <| declValSimple <|> declValEqns <|> whereStructInst def «abbrev» := leading_parser "abbrev " >> declId >> ppIndent optDeclSig >> declVal >> terminationSuffix def optDefDeriving := optional (atomic ("deriving " >> notSymbol "instance") >> sepBy1 ident ", ") def «def» := leading_parser "def " >> declId >> ppIndent optDeclSig >> declVal >> optDefDeriving >> terminationSuffix def «theorem» := leading_parser "theorem " >> declId >> ppIndent declSig >> declVal >> terminationSuffix def «opaque» := leading_parser "opaque " >> declId >> ppIndent declSig >> optional declValSimple /- As `declSig` starts with a space, "instance" does not need a trailing space if we put `ppSpace` in the optional fragments. -/ def «instance» := leading_parser Term.attrKind >> "instance" >> optNamedPrio >> optional (ppSpace >> declId) >> ppIndent declSig >> declVal >> terminationSuffix def «axiom» := leading_parser "axiom " >> declId >> ppIndent declSig /- As `declSig` starts with a space, "example" does not need a trailing space. -/ def «example» := leading_parser "example" >> ppIndent optDeclSig >> declVal def ctor := leading_parser atomic (optional docComment >> "\n| ") >> ppGroup (declModifiers true >> rawIdent >> optDeclSig) def derivingClasses := sepBy1 (group (ident >> optional (" with " >> Term.structInst))) ", " def optDeriving := leading_parser optional (ppLine >> atomic ("deriving " >> notSymbol "instance") >> derivingClasses) def computedField := leading_parser declModifiers true >> ident >> " : " >> termParser >> Term.matchAlts def computedFields := leading_parser "with" >> manyIndent (ppLine >> ppGroup computedField) /-- In Lean, every concrete type other than the universes and every type constructor other than dependent arrows is an instance of a general family of type constructions known as inductive types. It is remarkable that it is possible to construct a substantial edifice of mathematics based on nothing more than the type universes, dependent arrow types, and inductive types; everything else follows from those. Intuitively, an inductive type is built up from a specified list of constructor. For example, `List α` is the list of elements of type `α`, and is defined as follows: ``` inductive List (α : Type u) where | nil | cons (head : α) (tail : List α) ``` A list of elements of type `α` is either the empty list, `nil`, or an element `head : α` followed by a list `tail : List α`. For more information about [inductive types](https://leanprover.github.io/theorem_proving_in_lean4/inductive_types.html). -/ def «inductive» := leading_parser "inductive " >> declId >> optDeclSig >> optional (symbol " :=" <|> " where") >> many ctor >> optional (ppDedent ppLine >> computedFields) >> optDeriving def classInductive := leading_parser atomic (group (symbol "class " >> "inductive ")) >> declId >> ppIndent optDeclSig >> optional (symbol " :=" <|> " where") >> many ctor >> optDeriving def structExplicitBinder := leading_parser atomic (declModifiers true >> "(") >> withoutPosition (many1 ident >> ppIndent optDeclSig >> optional (Term.binderTactic <|> Term.binderDefault)) >> ")" def structImplicitBinder := leading_parser atomic (declModifiers true >> "{") >> withoutPosition (many1 ident >> declSig) >> "}" def structInstBinder := leading_parser atomic (declModifiers true >> "[") >> withoutPosition (many1 ident >> declSig) >> "]" def structSimpleBinder := leading_parser atomic (declModifiers true >> ident) >> optDeclSig >> optional (Term.binderTactic <|> Term.binderDefault) def structFields := leading_parser manyIndent <| ppLine >> checkColGe >> ppGroup ( structExplicitBinder <|> structImplicitBinder <|> structInstBinder <|> structSimpleBinder) def structCtor := leading_parser atomic (declModifiers true >> ident >> " :: ") def structureTk := leading_parser "structure " def classTk := leading_parser "class " def «extends» := leading_parser " extends " >> sepBy1 termParser ", " def «structure» := leading_parser (structureTk <|> classTk) >> declId >> many (ppSpace >> Term.bracketedBinder) >> optional «extends» >> Term.optType >> optional ((symbol " := " <|> " where ") >> optional structCtor >> structFields) >> optDeriving @[builtin_command_parser] def declaration := leading_parser declModifiers false >> («abbrev» <|> «def» <|> «theorem» <|> «opaque» <|> «instance» <|> «axiom» <|> «example» <|> «inductive» <|> classInductive <|> «structure») @[builtin_command_parser] def «deriving» := leading_parser "deriving " >> "instance " >> derivingClasses >> " for " >> sepBy1 ident ", " @[builtin_command_parser] def noncomputableSection := leading_parser "noncomputable " >> "section " >> optional ident @[builtin_command_parser] def «section» := leading_parser "section " >> optional ident @[builtin_command_parser] def «namespace» := leading_parser "namespace " >> ident @[builtin_command_parser] def «end» := leading_parser "end " >> optional ident @[builtin_command_parser] def «variable» := leading_parser "variable" >> many1 (ppSpace >> Term.bracketedBinder) @[builtin_command_parser] def «universe» := leading_parser "universe " >> many1 ident @[builtin_command_parser] def check := leading_parser "#check " >> termParser @[builtin_command_parser] def check_failure := leading_parser "#check_failure " >> termParser -- Like `#check`, but succeeds only if term does not type check @[builtin_command_parser] def reduce := leading_parser "#reduce " >> termParser @[builtin_command_parser] def eval := leading_parser "#eval " >> termParser @[builtin_command_parser] def synth := leading_parser "#synth " >> termParser @[builtin_command_parser] def exit := leading_parser "#exit" @[builtin_command_parser] def print := leading_parser "#print " >> (ident <|> strLit) @[builtin_command_parser] def printAxioms := leading_parser "#print " >> nonReservedSymbol "axioms " >> ident @[builtin_command_parser] def «init_quot» := leading_parser "init_quot" def optionValue := nonReservedSymbol "true" <|> nonReservedSymbol "false" <|> strLit <|> numLit @[builtin_command_parser] def «set_option» := leading_parser "set_option " >> ident >> ppSpace >> optionValue def eraseAttr := leading_parser "-" >> rawIdent @[builtin_command_parser] def «attribute» := leading_parser "attribute " >> "[" >> withoutPosition (sepBy1 (eraseAttr <|> Term.attrInstance) ", ") >> "] " >> many1 ident @[builtin_command_parser] def «export» := leading_parser "export " >> ident >> " (" >> many1 ident >> ")" @[builtin_command_parser] def «import» := leading_parser "import" -- not a real command, only for error messages def openHiding := leading_parser atomic (ident >> "hiding") >> many1 (checkColGt >> ident) def openRenamingItem := leading_parser ident >> unicodeSymbol " → " " -> " >> checkColGt >> ident def openRenaming := leading_parser atomic (ident >> "renaming") >> sepBy1 openRenamingItem ", " def openOnly := leading_parser atomic (ident >> " (") >> many1 ident >> ")" def openSimple := leading_parser many1 (checkColGt >> ident) def openScoped := leading_parser "scoped " >> many1 (checkColGt >> ident) def openDecl := withAntiquot (mkAntiquot "openDecl" `Lean.Parser.Command.openDecl (isPseudoKind := true)) <| openHiding <|> openRenaming <|> openOnly <|> openSimple <|> openScoped @[builtin_command_parser] def «open» := leading_parser withPosition ("open " >> openDecl) @[builtin_command_parser] def «mutual» := leading_parser "mutual " >> many1 (ppLine >> notSymbol "end" >> commandParser) >> ppDedent (ppLine >> "end") >> terminationSuffix def initializeKeyword := leading_parser "initialize " <|> "builtin_initialize " @[builtin_command_parser] def «initialize» := leading_parser declModifiers false >> initializeKeyword >> optional (atomic (ident >> Term.typeSpec >> Term.leftArrow)) >> Term.doSeq @[builtin_command_parser] def «in» := trailing_parser withOpen (" in " >> commandParser) @[builtin_command_parser] def addDocString := leading_parser docComment >> "add_decl_doc" >> ident /-- This is an auxiliary command for generation constructor injectivity theorems for inductive types defined at `Prelude.lean`. It is meant for bootstrapping purposes only. -/ @[builtin_command_parser] def genInjectiveTheorems := leading_parser "gen_injective_theorems% " >> ident @[run_builtin_parser_attribute_hooks] abbrev declModifiersF := declModifiers false @[run_builtin_parser_attribute_hooks] abbrev declModifiersT := declModifiers true builtin_initialize register_parser_alias (kind := ``declModifiers) "declModifiers" declModifiersF register_parser_alias (kind := ``declModifiers) "nestedDeclModifiers" declModifiersT register_parser_alias declId register_parser_alias declSig register_parser_alias declVal register_parser_alias optDeclSig register_parser_alias openDecl register_parser_alias docComment end Command namespace Term /-- `open Foo in e` is like `open Foo` but scoped to a single term. It makes the given namespaces available in the term `e`. -/ @[builtin_term_parser] def «open» := leading_parser:leadPrec "open " >> Command.openDecl >> withOpenDecl (" in " >> termParser) /-- `set_option opt val in e` is like `set_option opt val` but scoped to a single term. It sets the option `opt` to the value `val` in the term `e`. -/ @[builtin_term_parser] def «set_option» := leading_parser:leadPrec "set_option " >> ident >> ppSpace >> Command.optionValue >> " in " >> termParser end Term namespace Tactic /-- `open Foo in tacs` (the tactic) acts like `open Foo` at command level, but it opens a namespace only within the tactics `tacs`. -/ @[builtin_tactic_parser] def «open» := leading_parser:leadPrec "open " >> Command.openDecl >> withOpenDecl (" in " >> tacticSeq) /-- `set_option opt val in tacs` (the tactic) acts like `set_option opt val` at the command level, but it sets the option only within the tactics `tacs`. -/ @[builtin_tactic_parser] def «set_option» := leading_parser:leadPrec "set_option " >> ident >> ppSpace >> Command.optionValue >> " in " >> tacticSeq end Tactic end Parser end Lean
635f62e4fe8d057c99afcd980f35c9b6aa3c9bfc
01ae0d022f2e2fefdaaa898938c1ac1fbce3b3ab
/categories/idempotent_completion.lean
6a60d7c9ca5d3b5fef6c6eced345ec871ae85245
[]
no_license
PatrickMassot/lean-category-theory
0f56a83464396a253c28a42dece16c93baf8ad74
ef239978e91f2e1c3b8e88b6e9c64c155dc56c99
refs/heads/master
1,629,739,187,316
1,512,422,659,000
1,512,422,659,000
113,098,786
0
0
null
1,512,424,022,000
1,512,424,022,000
null
UTF-8
Lean
false
false
5,609
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Stephen Morgan, Scott Morrison import .category import .equivalence import .functor open categories open categories.functor open categories.natural_transformation namespace categories.idempotent_completion structure Idempotent ( C : Category ) := ( object : C.Obj ) ( idempotent : C.Hom object object ) ( witness : C.compose idempotent idempotent = idempotent ) attribute [simp,ematch] Idempotent.witness local attribute [ematch] subtype.property definition IdempotentCompletion ( C: Category ) : Category := { Obj := Idempotent C, Hom := λ X Y, { f : C.Hom X.object Y.object // C.compose X.idempotent f = f ∧ C.compose f Y.idempotent = f }, identity := λ X, ⟨ X.idempotent, ♮ ⟩, compose := λ X Y Z f g, ⟨ C.compose f.val g.val, ♮ ⟩, left_identity := ♯, right_identity := ♯, associativity := ♮ } definition functor_to_IdempotentCompletion ( C : Category ) : Functor C (IdempotentCompletion C) := { onObjects := λ X, ⟨ X, C.identity X, ♮ ⟩, onMorphisms := λ _ _ f, ⟨ f, ♮ ⟩, identities := ♮, functoriality := ♮ } -- PROJECT -- definition IdempotentCompletion_functorial ( C D : Category ) : Functor (FunctorCategory C D) (FunctorCategory (IdempotentCompletion C) (IdempotentCompletion D)) := { -- onObjects := λ F, { -- onObjects := λ X, ⟨ F.onObjects X.object, F.onMorphisms X.idempotent, ♯ ⟩ , -- onMorphisms := λ X Y f, ⟨ (F.onMorphisms f.val), ♯ ⟩, -- identities := ♯, -- functoriality := ♯ -- }, -- onMorphisms := λ F G τ, { -- components := λ X, ⟨ τ.components X.object, begin tidy, end ⟩, -- naturality := ♯ -- }, -- identities := ♯, -- we've made a mistake somewhere.. -- functoriality := sorry -- } open categories.equivalence -- lemma embedding_in_IdempotentCompletition ( C: Category ) : Embedding (functor_to_IdempotentCompletion C) := -- begin -- unfold Embedding, -- split, -- begin -- tidy, -- exact f_1, -- refl, -- FIXME this really should work! -- -- tidy, -- end, -- begin -- tidy, -- PROJECT This next step seems easily automatable. -- exact congr_arg subtype.val p -- end -- end definition restrict_Functor_from_IdempotentCompletion { C D : Category } ( F : Functor (IdempotentCompletion C) D ) : Functor C D := FunctorComposition (functor_to_IdempotentCompletion C) F -- PROJECT prove these lemmas about idempotent completion -- lemma IdempotentCompletion_idempotent ( C : Category ) : -- Equivalence (IdempotentCompletion (IdempotentCompletion C)) (IdempotentCompletion C) := -- { -- functor := { -- onObjects := λ X, ⟨ X.object.object, X.idempotent.val, begin tidy, induction X, tidy, exact congr_arg subtype.val witness, end ⟩, -- onMorphisms := λ X Y f, ⟨ f.val.val, begin tidy, exact congr_arg subtype.val f_2.right, unfold_projections at f, have p := f.property.right, tidy, exact congr_arg subtype.val p, end ⟩, -- identities := ♮, -- functoriality := ♮ -- }, -- inverse := { -- onObjects := λ X, ⟨ X, ⟨ X.idempotent, ♮ ⟩, ♯ ⟩, -- onMorphisms := λ X Y f, ⟨ f, begin tidy, exact f_2.right, tidy, exact f_2.left end ⟩, -- identities := ♮, -- functoriality := ♮ -- }, -- isomorphism_1 := begin tidy, end, -- FIXME this gets stuck because we've improperly used identities automatically! -- how do we cancel attributes? -- isomorphism_2 := sorry -- } -- Oh, I guess I had originally intended that this should use the previous results... oh well. definition extend_Functor_to_IdempotentCompletion { C D : Category } ( F : Functor C (IdempotentCompletion D) ) : Functor (IdempotentCompletion C) (IdempotentCompletion D) := { onObjects := λ X, let FX := F.onObjects X.object in ⟨ FX.object, (F.onMorphisms X.idempotent).val, begin have p := F.functoriality X.idempotent X.idempotent, have p' := congr_arg subtype.val p, tidy, end ⟩, onMorphisms := λ X Y f, ⟨ (F.onMorphisms f.val).val, begin tidy, have p := F.functoriality X.idempotent f_1, have p' := congr_arg subtype.val p, rewrite f_2.right at p', exact eq.symm p', -- tidy, have p := F.functoriality f_1 Y.idempotent, have p' := congr_arg subtype.val p, rewrite f_2.left at p', exact eq.symm p', end ⟩, identities := ♯, functoriality := ♯, } -- lemma Functor_from_IdempotentCompletion_determined_by_restriction -- { C D : Category } ( F : Functor (IdempotentCompletion C) (IdempotentCompletion D) ) : -- NaturalIsomorphism (extend_Functor_to_IdempotentCompletion (restrict_Functor_from_IdempotentCompletion F)) F := -- sorry -- PROJECT idempotent completion left adjoint to the forgetful functor from categories to semicategories? end categories.idempotent_completion
17bffcc979ae4862e1ec9bd5c37a66bfe03ffd47
8b9f17008684d796c8022dab552e42f0cb6fb347
/tests/lean/run/tactic12.lean
8a1a5d7eb0ff1b40b1112d5a798c32035f81ff5d
[ "Apache-2.0" ]
permissive
chubbymaggie/lean
0d06ae25f9dd396306fb02190e89422ea94afd7b
d2c7b5c31928c98f545b16420d37842c43b4ae9a
refs/heads/master
1,611,313,622,901
1,430,266,839,000
1,430,267,083,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
271
lean
import logic open tactic theorem tst (a b : Prop) (H : ¬ a ∨ ¬ b) (Hb : b) : ¬ a ∧ b := by apply and.intro; assumption; exact (assume Ha, or.elim H (assume Hna, @absurd _ false Ha Hna) (assume Hnb, @absurd _ false Hb Hnb))
59ad926da86e445d51c6e4b441863473288ffae5
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/data/real/cau_seq.lean
86f22b57a5068d53554ab0d4cac48686c990f1e9
[ "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
25,498
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import algebra.big_operators.order /-! # Cauchy sequences A basic theory of Cauchy sequences, used in the construction of the reals and p-adic numbers. Where applicable, lemmas that will be reused in other contexts have been stated in extra generality. There are other "versions" of Cauchyness in the library, in particular Cauchy filters in topology. This is a concrete implementation that is useful for simplicity and computability reasons. ## Important definitions * `is_absolute_value`: a type class stating that `f : β → α` satisfies the axioms of an abs val * `is_cau_seq`: a predicate that says `f : ℕ → β` is Cauchy. * `cau_seq`: the type of Cauchy sequences valued in type `β` with respect to an absolute value function `abv`. ## Tags sequence, cauchy, abs val, absolute value -/ open_locale big_operators /-- A function `f` is an absolute value if it is nonnegative, zero only at 0, additive, and multiplicative. -/ class is_absolute_value {α} [discrete_linear_ordered_field α] {β} [ring β] (f : β → α) : Prop := (abv_nonneg [] : ∀ x, 0 ≤ f x) (abv_eq_zero [] : ∀ {x}, f x = 0 ↔ x = 0) (abv_add [] : ∀ x y, f (x + y) ≤ f x + f y) (abv_mul [] : ∀ x y, f (x * y) = f x * f y) namespace is_absolute_value variables {α : Type*} [discrete_linear_ordered_field α] {β : Type*} [ring β] (abv : β → α) [is_absolute_value abv] theorem abv_zero : abv 0 = 0 := (abv_eq_zero abv).2 rfl theorem abv_one' (h : (1:β) ≠ 0) : abv 1 = 1 := (mul_right_inj' $ mt (abv_eq_zero abv).1 h).1 $ by rw [← abv_mul abv, mul_one, mul_one] theorem abv_one {β : Type*} [domain β] (abv : β → α) [is_absolute_value abv] : abv 1 = 1 := abv_one' abv one_ne_zero theorem abv_pos {a : β} : 0 < abv a ↔ a ≠ 0 := by rw [lt_iff_le_and_ne, ne, eq_comm]; simp [abv_eq_zero abv, abv_nonneg abv] theorem abv_neg (a : β) : abv (-a) = abv a := by rw [← mul_self_inj_of_nonneg (abv_nonneg abv _) (abv_nonneg abv _), ← abv_mul abv, ← abv_mul abv]; simp theorem abv_sub (a b : β) : abv (a - b) = abv (b - a) := by rw [← neg_sub, abv_neg abv] theorem abv_inv {β : Type*} [field β] (abv : β → α) [is_absolute_value abv] (a : β) : abv a⁻¹ = (abv a)⁻¹ := classical.by_cases (λ h : a = 0, by simp [h, abv_zero abv]) (λ h, mul_right_cancel' (mt (abv_eq_zero abv).1 h) $ by rw [← abv_mul abv]; simp [h, mt (abv_eq_zero abv).1 h, abv_one abv]) theorem abv_div {β : Type*} [field β] (abv : β → α) [is_absolute_value abv] (a b : β) : abv (a / b) = abv a / abv b := by rw [division_def, abv_mul abv, abv_inv abv]; refl lemma abv_sub_le (a b c : β) : abv (a - c) ≤ abv (a - b) + abv (b - c) := by simpa [sub_eq_add_neg, add_assoc] using abv_add abv (a - b) (b - c) lemma sub_abv_le_abv_sub (a b : β) : abv a - abv b ≤ abv (a - b) := sub_le_iff_le_add.2 $ by simpa using abv_add abv (a - b) b lemma abs_abv_sub_le_abv_sub (a b : β) : abs (abv a - abv b) ≤ abv (a - b) := abs_sub_le_iff.2 ⟨sub_abv_le_abv_sub abv _ _, by rw abv_sub abv; apply sub_abv_le_abv_sub abv⟩ lemma abv_pow {β : Type*} [domain β] (abv : β → α) [is_absolute_value abv] (a : β) (n : ℕ) : abv (a ^ n) = abv a ^ n := by induction n; simp [abv_mul abv, pow_succ, abv_one abv, *] end is_absolute_value instance abs_is_absolute_value {α} [discrete_linear_ordered_field α] : is_absolute_value (abs : α → α) := { abv_nonneg := abs_nonneg, abv_eq_zero := λ _, abs_eq_zero, abv_add := abs_add, abv_mul := abs_mul } open is_absolute_value theorem exists_forall_ge_and {α} [linear_order α] {P Q : α → Prop} : (∃ i, ∀ j ≥ i, P j) → (∃ i, ∀ j ≥ i, Q j) → ∃ i, ∀ j ≥ i, P j ∧ Q j | ⟨a, h₁⟩ ⟨b, h₂⟩ := let ⟨c, ac, bc⟩ := exists_ge_of_linear a b in ⟨c, λ j hj, ⟨h₁ _ (le_trans ac hj), h₂ _ (le_trans bc hj)⟩⟩ section variables {α : Type*} [discrete_linear_ordered_field α] {β : Type*} [ring β] (abv : β → α) [is_absolute_value abv] theorem rat_add_continuous_lemma {ε : α} (ε0 : 0 < ε) : ∃ δ > 0, ∀ {a₁ a₂ b₁ b₂ : β}, abv (a₁ - b₁) < δ → abv (a₂ - b₂) < δ → abv (a₁ + a₂ - (b₁ + b₂)) < ε := ⟨ε / 2, half_pos ε0, λ a₁ a₂ b₁ b₂ h₁ h₂, by simpa [add_halves, sub_eq_add_neg, add_comm, add_left_comm, add_assoc] using lt_of_le_of_lt (abv_add abv _ _) (add_lt_add h₁ h₂)⟩ theorem rat_mul_continuous_lemma {ε K₁ K₂ : α} (ε0 : 0 < ε) : ∃ δ > 0, ∀ {a₁ a₂ b₁ b₂ : β}, abv a₁ < K₁ → abv b₂ < K₂ → abv (a₁ - b₁) < δ → abv (a₂ - b₂) < δ → abv (a₁ * a₂ - b₁ * b₂) < ε := begin have K0 : (0 : α) < max 1 (max K₁ K₂) := lt_of_lt_of_le zero_lt_one (le_max_left _ _), have εK := div_pos (half_pos ε0) K0, refine ⟨_, εK, λ a₁ a₂ b₁ b₂ ha₁ hb₂ h₁ h₂, _⟩, replace ha₁ := lt_of_lt_of_le ha₁ (le_trans (le_max_left _ K₂) (le_max_right 1 _)), replace hb₂ := lt_of_lt_of_le hb₂ (le_trans (le_max_right K₁ _) (le_max_right 1 _)), have := add_lt_add (mul_lt_mul' (le_of_lt h₁) hb₂ (abv_nonneg abv _) εK) (mul_lt_mul' (le_of_lt h₂) ha₁ (abv_nonneg abv _) εK), rw [← abv_mul abv, mul_comm, div_mul_cancel _ (ne_of_gt K0), ← abv_mul abv, add_halves] at this, simpa [mul_add, add_mul, sub_eq_add_neg, add_comm, add_left_comm] using lt_of_le_of_lt (abv_add abv _ _) this end theorem rat_inv_continuous_lemma {β : Type*} [field β] (abv : β → α) [is_absolute_value abv] {ε K : α} (ε0 : 0 < ε) (K0 : 0 < K) : ∃ δ > 0, ∀ {a b : β}, K ≤ abv a → K ≤ abv b → abv (a - b) < δ → abv (a⁻¹ - b⁻¹) < ε := begin have KK := mul_pos K0 K0, have εK := mul_pos ε0 KK, refine ⟨_, εK, λ a b ha hb h, _⟩, have a0 := lt_of_lt_of_le K0 ha, have b0 := lt_of_lt_of_le K0 hb, rw [inv_sub_inv ((abv_pos abv).1 a0) ((abv_pos abv).1 b0), abv_div abv, abv_mul abv, mul_comm, abv_sub abv, ← mul_div_cancel ε (ne_of_gt KK)], exact div_lt_div h (mul_le_mul hb ha (le_of_lt K0) (abv_nonneg abv _)) (le_of_lt $ mul_pos ε0 KK) KK end end /-- A sequence is Cauchy if the distance between its entries tends to zero. -/ def is_cau_seq {α : Type*} [discrete_linear_ordered_field α] {β : Type*} [ring β] (abv : β → α) (f : ℕ → β) : Prop := ∀ ε > 0, ∃ i, ∀ j ≥ i, abv (f j - f i) < ε namespace is_cau_seq variables {α : Type*} [discrete_linear_ordered_field α] {β : Type*} [ring β] {abv : β → α} [is_absolute_value abv] {f : ℕ → β} @[nolint ge_or_gt] -- see Note [nolint_ge] theorem cauchy₂ (hf : is_cau_seq abv f) {ε : α} (ε0 : 0 < ε) : ∃ i, ∀ j k ≥ i, abv (f j - f k) < ε := begin refine (hf _ (half_pos ε0)).imp (λ i hi j k ij ik, _), rw ← add_halves ε, refine lt_of_le_of_lt (abv_sub_le abv _ _ _) (add_lt_add (hi _ ij) _), rw abv_sub abv, exact hi _ ik end theorem cauchy₃ (hf : is_cau_seq abv f) {ε : α} (ε0 : 0 < ε) : ∃ i, ∀ j ≥ i, ∀ k ≥ j, abv (f k - f j) < ε := let ⟨i, H⟩ := hf.cauchy₂ ε0 in ⟨i, λ j ij k jk, H _ _ (le_trans ij jk) ij⟩ end is_cau_seq /-- `cau_seq β abv` is the type of `β`-valued Cauchy sequences, with respect to the absolute value function `abv`. -/ def cau_seq {α : Type*} [discrete_linear_ordered_field α] (β : Type*) [ring β] (abv : β → α) : Type* := {f : ℕ → β // is_cau_seq abv f} namespace cau_seq variables {α : Type*} [discrete_linear_ordered_field α] section ring variables {β : Type*} [ring β] {abv : β → α} instance : has_coe_to_fun (cau_seq β abv) := ⟨_, subtype.val⟩ @[simp] theorem mk_to_fun (f) (hf : is_cau_seq abv f) : @coe_fn (cau_seq β abv) _ ⟨f, hf⟩ = f := rfl theorem ext {f g : cau_seq β abv} (h : ∀ i, f i = g i) : f = g := subtype.eq (funext h) theorem is_cau (f : cau_seq β abv) : is_cau_seq abv f := f.2 theorem cauchy (f : cau_seq β abv) : ∀ {ε}, 0 < ε → ∃ i, ∀ j ≥ i, abv (f j - f i) < ε := f.2 /-- Given a Cauchy sequence `f`, create a Cauchy sequence from a sequence `g` with the same values as `f`. -/ def of_eq (f : cau_seq β abv) (g : ℕ → β) (e : ∀ i, f i = g i) : cau_seq β abv := ⟨g, λ ε, by rw [show g = f, from (funext e).symm]; exact f.cauchy⟩ variable [is_absolute_value abv] @[nolint ge_or_gt] -- see Note [nolint_ge] theorem cauchy₂ (f : cau_seq β abv) {ε} : 0 < ε → ∃ i, ∀ j k ≥ i, abv (f j - f k) < ε := f.2.cauchy₂ theorem cauchy₃ (f : cau_seq β abv) {ε} : 0 < ε → ∃ i, ∀ j ≥ i, ∀ k ≥ j, abv (f k - f j) < ε := f.2.cauchy₃ theorem bounded (f : cau_seq β abv) : ∃ r, ∀ i, abv (f i) < r := begin cases f.cauchy zero_lt_one with i h, let R := ∑ j in finset.range (i+1), abv (f j), have : ∀ j ≤ i, abv (f j) ≤ R, { intros j ij, change (λ j, abv (f j)) j ≤ R, apply finset.single_le_sum, { intros, apply abv_nonneg abv }, { rwa [finset.mem_range, nat.lt_succ_iff] } }, refine ⟨R + 1, λ j, _⟩, cases lt_or_le j i with ij ij, { exact lt_of_le_of_lt (this _ (le_of_lt ij)) (lt_add_one _) }, { have := lt_of_le_of_lt (abv_add abv _ _) (add_lt_add_of_le_of_lt (this _ (le_refl _)) (h _ ij)), rw [add_sub, add_comm] at this, simpa } end theorem bounded' (f : cau_seq β abv) (x : α) : ∃ r > x, ∀ i, abv (f i) < r := let ⟨r, h⟩ := f.bounded in ⟨max r (x+1), lt_of_lt_of_le (lt_add_one _) (le_max_right _ _), λ i, lt_of_lt_of_le (h i) (le_max_left _ _)⟩ instance : has_add (cau_seq β abv) := ⟨λ f g, ⟨λ i, (f i + g i : β), λ ε ε0, let ⟨δ, δ0, Hδ⟩ := rat_add_continuous_lemma abv ε0, ⟨i, H⟩ := exists_forall_ge_and (f.cauchy₃ δ0) (g.cauchy₃ δ0) in ⟨i, λ j ij, let ⟨H₁, H₂⟩ := H _ (le_refl _) in Hδ (H₁ _ ij) (H₂ _ ij)⟩⟩⟩ @[simp] theorem add_apply (f g : cau_seq β abv) (i : ℕ) : (f + g) i = f i + g i := rfl variable (abv) /-- The constant Cauchy sequence. -/ def const (x : β) : cau_seq β abv := ⟨λ i, x, λ ε ε0, ⟨0, λ j ij, by simpa [abv_zero abv] using ε0⟩⟩ variable {abv} local notation `const` := const abv @[simp] theorem const_apply (x : β) (i : ℕ) : (const x : ℕ → β) i = x := rfl theorem const_inj {x y : β} : (const x : cau_seq β abv) = const y ↔ x = y := ⟨λ h, congr_arg (λ f:cau_seq β abv, (f:ℕ→β) 0) h, congr_arg _⟩ instance : has_zero (cau_seq β abv) := ⟨const 0⟩ instance : has_one (cau_seq β abv) := ⟨const 1⟩ instance : inhabited (cau_seq β abv) := ⟨0⟩ @[simp] theorem zero_apply (i) : (0 : cau_seq β abv) i = 0 := rfl @[simp] theorem one_apply (i) : (1 : cau_seq β abv) i = 1 := rfl theorem const_add (x y : β) : const (x + y) = const x + const y := ext $ λ i, rfl instance : has_mul (cau_seq β abv) := ⟨λ f g, ⟨λ i, (f i * g i : β), λ ε ε0, let ⟨F, F0, hF⟩ := f.bounded' 0, ⟨G, G0, hG⟩ := g.bounded' 0, ⟨δ, δ0, Hδ⟩ := rat_mul_continuous_lemma abv ε0, ⟨i, H⟩ := exists_forall_ge_and (f.cauchy₃ δ0) (g.cauchy₃ δ0) in ⟨i, λ j ij, let ⟨H₁, H₂⟩ := H _ (le_refl _) in Hδ (hF j) (hG i) (H₁ _ ij) (H₂ _ ij)⟩⟩⟩ @[simp] theorem mul_apply (f g : cau_seq β abv) (i : ℕ) : (f * g) i = f i * g i := rfl theorem const_mul (x y : β) : const (x * y) = const x * const y := ext $ λ i, rfl instance : has_neg (cau_seq β abv) := ⟨λ f, of_eq (const (-1) * f) (λ x, -f x) (λ i, by simp)⟩ @[simp] theorem neg_apply (f : cau_seq β abv) (i) : (-f) i = -f i := rfl theorem const_neg (x : β) : const (-x) = -const x := ext $ λ i, rfl instance : ring (cau_seq β abv) := by refine {neg := has_neg.neg, add := (+), zero := 0, mul := (*), one := 1, ..}; { intros, apply ext, simp [mul_add, mul_assoc, add_mul, add_comm, add_left_comm] } instance {β : Type*} [comm_ring β] {abv : β → α} [is_absolute_value abv] : comm_ring (cau_seq β abv) := { mul_comm := by intros; apply ext; simp [mul_left_comm, mul_comm], ..cau_seq.ring } theorem const_sub (x y : β) : const (x - y) = const x - const y := by rw [sub_eq_add_neg, const_add, const_neg, sub_eq_add_neg] @[simp] theorem sub_apply (f g : cau_seq β abv) (i : ℕ) : (f - g) i = f i - g i := rfl /-- `lim_zero f` holds when `f` approaches 0. -/ def lim_zero {abv : β → α} (f : cau_seq β abv) : Prop := ∀ ε > 0, ∃ i, ∀ j ≥ i, abv (f j) < ε theorem add_lim_zero {f g : cau_seq β abv} (hf : lim_zero f) (hg : lim_zero g) : lim_zero (f + g) | ε ε0 := (exists_forall_ge_and (hf _ $ half_pos ε0) (hg _ $ half_pos ε0)).imp $ λ i H j ij, let ⟨H₁, H₂⟩ := H _ ij in by simpa [add_halves ε] using lt_of_le_of_lt (abv_add abv _ _) (add_lt_add H₁ H₂) theorem mul_lim_zero_right (f : cau_seq β abv) {g} (hg : lim_zero g) : lim_zero (f * g) | ε ε0 := let ⟨F, F0, hF⟩ := f.bounded' 0 in (hg _ $ div_pos ε0 F0).imp $ λ i H j ij, by have := mul_lt_mul' (le_of_lt $ hF j) (H _ ij) (abv_nonneg abv _) F0; rwa [mul_comm F, div_mul_cancel _ (ne_of_gt F0), ← abv_mul abv] at this theorem mul_lim_zero_left {f} (g : cau_seq β abv) (hg : lim_zero f) : lim_zero (f * g) | ε ε0 := let ⟨G, G0, hG⟩ := g.bounded' 0 in (hg _ $ div_pos ε0 G0).imp $ λ i H j ij, by have := mul_lt_mul'' (H _ ij) (hG j) (abv_nonneg abv _) (abv_nonneg abv _); rwa [div_mul_cancel _ (ne_of_gt G0), ← abv_mul abv] at this theorem neg_lim_zero {f : cau_seq β abv} (hf : lim_zero f) : lim_zero (-f) := by rw ← neg_one_mul; exact mul_lim_zero_right _ hf theorem sub_lim_zero {f g : cau_seq β abv} (hf : lim_zero f) (hg : lim_zero g) : lim_zero (f - g) := add_lim_zero hf (neg_lim_zero hg) theorem lim_zero_sub_rev {f g : cau_seq β abv} (hfg : lim_zero (f - g)) : lim_zero (g - f) := by simpa using neg_lim_zero hfg theorem zero_lim_zero : lim_zero (0 : cau_seq β abv) | ε ε0 := ⟨0, λ j ij, by simpa [abv_zero abv] using ε0⟩ theorem const_lim_zero {x : β} : lim_zero (const x) ↔ x = 0 := ⟨λ H, (abv_eq_zero abv).1 $ eq_of_le_of_forall_le_of_dense (abv_nonneg abv _) $ λ ε ε0, let ⟨i, hi⟩ := H _ ε0 in le_of_lt $ hi _ (le_refl _), λ e, e.symm ▸ zero_lim_zero⟩ instance equiv : setoid (cau_seq β abv) := ⟨λ f g, lim_zero (f - g), ⟨λ f, by simp [zero_lim_zero], λ f g h, by simpa using neg_lim_zero h, λ f g h fg gh, by simpa [sub_eq_add_neg, add_assoc] using add_lim_zero fg gh⟩⟩ theorem equiv_def₃ {f g : cau_seq β abv} (h : f ≈ g) {ε : α} (ε0 : 0 < ε) : ∃ i, ∀ j ≥ i, ∀ k ≥ j, abv (f k - g j) < ε := (exists_forall_ge_and (h _ $ half_pos ε0) (f.cauchy₃ $ half_pos ε0)).imp $ λ i H j ij k jk, let ⟨h₁, h₂⟩ := H _ ij in by have := lt_of_le_of_lt (abv_add abv (f j - g j) _) (add_lt_add h₁ (h₂ _ jk)); rwa [sub_add_sub_cancel', add_halves] at this theorem lim_zero_congr {f g : cau_seq β abv} (h : f ≈ g) : lim_zero f ↔ lim_zero g := ⟨λ l, by simpa using add_lim_zero (setoid.symm h) l, λ l, by simpa using add_lim_zero h l⟩ theorem abv_pos_of_not_lim_zero {f : cau_seq β abv} (hf : ¬ lim_zero f) : ∃ K > 0, ∃ i, ∀ j ≥ i, K ≤ abv (f j) := begin haveI := classical.prop_decidable, by_contra nk, refine hf (λ ε ε0, _), simp [not_forall] at nk, cases f.cauchy₃ (half_pos ε0) with i hi, rcases nk _ (half_pos ε0) i with ⟨j, ij, hj⟩, refine ⟨j, λ k jk, _⟩, have := lt_of_le_of_lt (abv_add abv _ _) (add_lt_add (hi j ij k jk) hj), rwa [sub_add_cancel, add_halves] at this end theorem of_near (f : ℕ → β) (g : cau_seq β abv) (h : ∀ ε > 0, ∃ i, ∀ j ≥ i, abv (f j - g j) < ε) : is_cau_seq abv f | ε ε0 := let ⟨i, hi⟩ := exists_forall_ge_and (h _ (half_pos $ half_pos ε0)) (g.cauchy₃ $ half_pos ε0) in ⟨i, λ j ij, begin cases hi _ (le_refl _) with h₁ h₂, rw abv_sub abv at h₁, have := lt_of_le_of_lt (abv_add abv _ _) (add_lt_add (hi _ ij).1 h₁), have := lt_of_le_of_lt (abv_add abv _ _) (add_lt_add this (h₂ _ ij)), rwa [add_halves, add_halves, add_right_comm, sub_add_sub_cancel, sub_add_sub_cancel] at this end⟩ lemma not_lim_zero_of_not_congr_zero {f : cau_seq _ abv} (hf : ¬ f ≈ 0) : ¬ lim_zero f := assume : lim_zero f, have lim_zero (f - 0), by simpa, hf this lemma mul_equiv_zero (g : cau_seq _ abv) {f : cau_seq _ abv} (hf : f ≈ 0) : g * f ≈ 0 := have lim_zero (f - 0), from hf, have lim_zero (g*f), from mul_lim_zero_right _ $ by simpa, show lim_zero (g*f - 0), by simpa lemma mul_not_equiv_zero {f g : cau_seq _ abv} (hf : ¬ f ≈ 0) (hg : ¬ g ≈ 0) : ¬ (f * g) ≈ 0 := assume : lim_zero (f*g - 0), have hlz : lim_zero (f*g), by simpa, have hf' : ¬ lim_zero f, by simpa using (show ¬ lim_zero (f - 0), from hf), have hg' : ¬ lim_zero g, by simpa using (show ¬ lim_zero (g - 0), from hg), begin rcases abv_pos_of_not_lim_zero hf' with ⟨a1, ha1, N1, hN1⟩, rcases abv_pos_of_not_lim_zero hg' with ⟨a2, ha2, N2, hN2⟩, have : 0 < a1 * a2, from mul_pos ha1 ha2, cases hlz _ this with N hN, let i := max N (max N1 N2), have hN' := hN i (le_max_left _ _), have hN1' := hN1 i (le_trans (le_max_left _ _) (le_max_right _ _)), have hN1' := hN2 i (le_trans (le_max_right _ _) (le_max_right _ _)), apply not_le_of_lt hN', change _ ≤ abv (_ * _), rw is_absolute_value.abv_mul abv, apply mul_le_mul; try { assumption }, { apply le_of_lt ha2 }, { apply is_absolute_value.abv_nonneg abv } end theorem const_equiv {x y : β} : const x ≈ const y ↔ x = y := show lim_zero _ ↔ _, by rw [← const_sub, const_lim_zero, sub_eq_zero] end ring section comm_ring variables {β : Type*} [comm_ring β] {abv : β → α} [is_absolute_value abv] lemma mul_equiv_zero' (g : cau_seq _ abv) {f : cau_seq _ abv} (hf : f ≈ 0) : f * g ≈ 0 := by rw mul_comm; apply mul_equiv_zero _ hf end comm_ring section integral_domain variables {β : Type*} [integral_domain β] (abv : β → α) [is_absolute_value abv] lemma one_not_equiv_zero : ¬ (const abv 1) ≈ (const abv 0) := assume h, have ∀ ε > 0, ∃ i, ∀ k, i ≤ k → abv (1 - 0) < ε, from h, have h1 : abv 1 ≤ 0, from le_of_not_gt $ assume h2 : 0 < abv 1, exists.elim (this _ h2) $ λ i hi, lt_irrefl (abv 1) $ by simpa using hi _ (le_refl _), have h2 : 0 ≤ abv 1, from is_absolute_value.abv_nonneg _ _, have abv 1 = 0, from le_antisymm h1 h2, have (1 : β) = 0, from (is_absolute_value.abv_eq_zero abv).1 this, absurd this one_ne_zero end integral_domain section field variables {β : Type*} [field β] {abv : β → α} [is_absolute_value abv] theorem inv_aux {f : cau_seq β abv} (hf : ¬ lim_zero f) : ∀ ε > 0, ∃ i, ∀ j ≥ i, abv ((f j)⁻¹ - (f i)⁻¹) < ε | ε ε0 := let ⟨K, K0, HK⟩ := abv_pos_of_not_lim_zero hf, ⟨δ, δ0, Hδ⟩ := rat_inv_continuous_lemma abv ε0 K0, ⟨i, H⟩ := exists_forall_ge_and HK (f.cauchy₃ δ0) in ⟨i, λ j ij, let ⟨iK, H'⟩ := H _ (le_refl _) in Hδ (H _ ij).1 iK (H' _ ij)⟩ /-- Given a Cauchy sequence `f` with nonzero limit, create a Cauchy sequence with values equal to the inverses of the values of `f`. -/ def inv (f : cau_seq β abv) (hf : ¬ lim_zero f) : cau_seq β abv := ⟨_, inv_aux hf⟩ @[simp] theorem inv_apply {f : cau_seq β abv} (hf i) : inv f hf i = (f i)⁻¹ := rfl theorem inv_mul_cancel {f : cau_seq β abv} (hf) : inv f hf * f ≈ 1 := λ ε ε0, let ⟨K, K0, i, H⟩ := abv_pos_of_not_lim_zero hf in ⟨i, λ j ij, by simpa [(abv_pos abv).1 (lt_of_lt_of_le K0 (H _ ij)), abv_zero abv] using ε0⟩ theorem const_inv {x : β} (hx : x ≠ 0) : const abv (x⁻¹) = inv (const abv x) (by rwa const_lim_zero) := ext (assume n, by simp[inv_apply, const_apply]) end field section abs local notation `const` := const abs /-- The entries of a positive Cauchy sequence eventually have a positive lower bound. -/ def pos (f : cau_seq α abs) : Prop := ∃ K > 0, ∃ i, ∀ j ≥ i, K ≤ f j theorem not_lim_zero_of_pos {f : cau_seq α abs} : pos f → ¬ lim_zero f | ⟨F, F0, hF⟩ H := let ⟨i, h⟩ := exists_forall_ge_and hF (H _ F0), ⟨h₁, h₂⟩ := h _ (le_refl _) in not_lt_of_le h₁ (abs_lt.1 h₂).2 theorem const_pos {x : α} : pos (const x) ↔ 0 < x := ⟨λ ⟨K, K0, i, h⟩, lt_of_lt_of_le K0 (h _ (le_refl _)), λ h, ⟨x, h, 0, λ j _, le_refl _⟩⟩ theorem add_pos {f g : cau_seq α abs} : pos f → pos g → pos (f + g) | ⟨F, F0, hF⟩ ⟨G, G0, hG⟩ := let ⟨i, h⟩ := exists_forall_ge_and hF hG in ⟨_, _root_.add_pos F0 G0, i, λ j ij, let ⟨h₁, h₂⟩ := h _ ij in add_le_add h₁ h₂⟩ theorem pos_add_lim_zero {f g : cau_seq α abs} : pos f → lim_zero g → pos (f + g) | ⟨F, F0, hF⟩ H := let ⟨i, h⟩ := exists_forall_ge_and hF (H _ (half_pos F0)) in ⟨_, half_pos F0, i, λ j ij, begin cases h j ij with h₁ h₂, have := add_le_add h₁ (le_of_lt (abs_lt.1 h₂).1), rwa [← sub_eq_add_neg, sub_self_div_two] at this end⟩ protected theorem mul_pos {f g : cau_seq α abs} : pos f → pos g → pos (f * g) | ⟨F, F0, hF⟩ ⟨G, G0, hG⟩ := let ⟨i, h⟩ := exists_forall_ge_and hF hG in ⟨_, _root_.mul_pos F0 G0, i, λ j ij, let ⟨h₁, h₂⟩ := h _ ij in mul_le_mul h₁ h₂ (le_of_lt G0) (le_trans (le_of_lt F0) h₁)⟩ theorem trichotomy (f : cau_seq α abs) : pos f ∨ lim_zero f ∨ pos (-f) := begin cases classical.em (lim_zero f); simp *, rcases abv_pos_of_not_lim_zero h with ⟨K, K0, hK⟩, rcases exists_forall_ge_and hK (f.cauchy₃ K0) with ⟨i, hi⟩, refine (le_total 0 (f i)).imp _ _; refine (λ h, ⟨K, K0, i, λ j ij, _⟩); have := (hi _ ij).1; cases hi _ (le_refl _) with h₁ h₂, { rwa abs_of_nonneg at this, rw abs_of_nonneg h at h₁, exact (le_add_iff_nonneg_right _).1 (le_trans h₁ $ neg_le_sub_iff_le_add'.1 $ le_of_lt (abs_lt.1 $ h₂ _ ij).1) }, { rwa abs_of_nonpos at this, rw abs_of_nonpos h at h₁, rw [← sub_le_sub_iff_right, zero_sub], exact le_trans (le_of_lt (abs_lt.1 $ h₂ _ ij).2) h₁ } end instance : has_lt (cau_seq α abs) := ⟨λ f g, pos (g - f)⟩ instance : has_le (cau_seq α abs) := ⟨λ f g, f < g ∨ f ≈ g⟩ theorem lt_of_lt_of_eq {f g h : cau_seq α abs} (fg : f < g) (gh : g ≈ h) : f < h := by simpa [sub_eq_add_neg, add_comm, add_left_comm] using pos_add_lim_zero fg (neg_lim_zero gh) theorem lt_of_eq_of_lt {f g h : cau_seq α abs} (fg : f ≈ g) (gh : g < h) : f < h := by have := pos_add_lim_zero gh (neg_lim_zero fg); rwa [← sub_eq_add_neg, sub_sub_sub_cancel_right] at this theorem lt_trans {f g h : cau_seq α abs} (fg : f < g) (gh : g < h) : f < h := by simpa [sub_eq_add_neg, add_comm, add_left_comm] using add_pos fg gh theorem lt_irrefl {f : cau_seq α abs} : ¬ f < f | h := not_lim_zero_of_pos h (by simp [zero_lim_zero]) lemma le_of_eq_of_le {f g h : cau_seq α abs} (hfg : f ≈ g) (hgh : g ≤ h) : f ≤ h := hgh.elim (or.inl ∘ cau_seq.lt_of_eq_of_lt hfg) (or.inr ∘ setoid.trans hfg) lemma le_of_le_of_eq {f g h : cau_seq α abs} (hfg : f ≤ g) (hgh : g ≈ h) : f ≤ h := hfg.elim (λ h, or.inl (cau_seq.lt_of_lt_of_eq h hgh)) (λ h, or.inr (setoid.trans h hgh)) instance : preorder (cau_seq α abs) := { lt := (<), le := λ f g, f < g ∨ f ≈ g, le_refl := λ f, or.inr (setoid.refl _), le_trans := λ f g h fg, match fg with | or.inl fg, or.inl gh := or.inl $ lt_trans fg gh | or.inl fg, or.inr gh := or.inl $ lt_of_lt_of_eq fg gh | or.inr fg, or.inl gh := or.inl $ lt_of_eq_of_lt fg gh | or.inr fg, or.inr gh := or.inr $ setoid.trans fg gh end, lt_iff_le_not_le := λ f g, ⟨λ h, ⟨or.inl h, not_or (mt (lt_trans h) lt_irrefl) (not_lim_zero_of_pos h)⟩, λ ⟨h₁, h₂⟩, h₁.resolve_right (mt (λ h, or.inr (setoid.symm h)) h₂)⟩ } theorem le_antisymm {f g : cau_seq α abs} (fg : f ≤ g) (gf : g ≤ f) : f ≈ g := fg.resolve_left (not_lt_of_le gf) theorem lt_total (f g : cau_seq α abs) : f < g ∨ f ≈ g ∨ g < f := (trichotomy (g - f)).imp_right (λ h, h.imp (λ h, setoid.symm h) (λ h, by rwa neg_sub at h)) theorem le_total (f g : cau_seq α abs) : f ≤ g ∨ g ≤ f := (or.assoc.2 (lt_total f g)).imp_right or.inl theorem const_lt {x y : α} : const x < const y ↔ x < y := show pos _ ↔ _, by rw [← const_sub, const_pos, sub_pos] theorem const_le {x y : α} : const x ≤ const y ↔ x ≤ y := by rw le_iff_lt_or_eq; exact or_congr const_lt const_equiv lemma le_of_exists {f g : cau_seq α abs} (h : ∃ i, ∀ j ≥ i, f j ≤ g j) : f ≤ g := let ⟨i, hi⟩ := h in (or.assoc.2 (cau_seq.lt_total f g)).elim id (λ hgf, false.elim (let ⟨K, hK0, j, hKj⟩ := hgf in not_lt_of_ge (hi (max i j) (le_max_left _ _)) (sub_pos.1 (lt_of_lt_of_le hK0 (hKj _ (le_max_right _ _)))))) theorem exists_gt (f : cau_seq α abs) : ∃ a : α, f < const a := let ⟨K, H⟩ := f.bounded in ⟨K + 1, 1, zero_lt_one, 0, λ i _, begin rw [sub_apply, const_apply, le_sub_iff_add_le', add_le_add_iff_right], exact le_of_lt (abs_lt.1 (H _)).2 end⟩ theorem exists_lt (f : cau_seq α abs) : ∃ a : α, const a < f := let ⟨a, h⟩ := (-f).exists_gt in ⟨-a, show pos _, by rwa [const_neg, sub_neg_eq_add, add_comm, ← sub_neg_eq_add]⟩ end abs end cau_seq
96b7d85c1c1f64df305382bd4038a4666e9783cf
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/algebra/lie/of_associative.lean
dcb1eb7120e2d0457c7c560d1fee6d72daa41dd9
[ "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
7,098
lean
/- Copyright (c) 2021 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import algebra.lie.basic import algebra.lie.subalgebra import algebra.algebra.subalgebra /-! # Lie algebras of associative algebras This file defines the Lie algebra structure that arises on an associative algebra via the ring commutator. Since the linear endomorphisms of a Lie algebra form an associative algebra, one can define the adjoint action as a morphism of Lie algebras from a Lie algebra to its linear endomorphisms. We make such a definition in this file. ## Main definitions * `lie_algebra.of_associative_algebra` * `lie_algebra.of_associative_algebra_hom` * `lie_module.to_endomorphism` * `lie_algebra.ad` * `linear_equiv.lie_conj` * `alg_equiv.to_lie_equiv` ## Tags lie algebra, ring commutator, adjoint action -/ universes u v w w₁ w₂ section of_associative variables {A : Type v} [ring A] namespace ring /-- The bracket operation for rings is the ring commutator, which captures the extent to which a ring is commutative. It is identically zero exactly when the ring is commutative. -/ @[priority 100] instance : has_bracket A A := ⟨λ x y, x*y - y*x⟩ lemma lie_def (x y : A) : ⁅x, y⁆ = x*y - y*x := rfl end ring namespace lie_ring /-- An associative ring gives rise to a Lie ring by taking the bracket to be the ring commutator. -/ @[priority 100] instance of_associative_ring : lie_ring A := { add_lie := by simp only [ring.lie_def, right_distrib, left_distrib, sub_eq_add_neg, add_comm, add_left_comm, forall_const, eq_self_iff_true, neg_add_rev], lie_add := by simp only [ring.lie_def, right_distrib, left_distrib, sub_eq_add_neg, add_comm, add_left_comm, forall_const, eq_self_iff_true, neg_add_rev], lie_self := by simp only [ring.lie_def, forall_const, sub_self], leibniz_lie := λ x y z, by { repeat { rw ring.lie_def, }, noncomm_ring, } } lemma of_associative_ring_bracket (x y : A) : ⁅x, y⁆ = x*y - y*x := rfl @[simp] lemma lie_apply {α : Type*} (f g : α → A) (a : α) : ⁅f, g⁆ a = ⁅f a, g a⁆ := rfl end lie_ring namespace lie_algebra variables {R : Type u} [comm_ring R] [algebra R A] /-- An associative algebra gives rise to a Lie algebra by taking the bracket to be the ring commutator. -/ @[priority 100] instance of_associative_algebra : lie_algebra R A := { lie_smul := λ t x y, by rw [lie_ring.of_associative_ring_bracket, lie_ring.of_associative_ring_bracket, algebra.mul_smul_comm, algebra.smul_mul_assoc, smul_sub], } /-- The map `of_associative_algebra` associating a Lie algebra to an associative algebra is functorial. -/ def of_associative_algebra_hom {B : Type w} [ring B] [algebra R B] (f : A →ₐ[R] B) : A →ₗ⁅R⁆ B := { map_lie' := λ x y, show f ⁅x,y⁆ = ⁅f x,f y⁆, by simp only [lie_ring.of_associative_ring_bracket, alg_hom.map_sub, alg_hom.map_mul], ..f.to_linear_map, } @[simp] lemma of_associative_algebra_hom_id : of_associative_algebra_hom (alg_hom.id R A) = 1 := rfl @[simp] lemma of_associative_algebra_hom_apply {B : Type w} [ring B] [algebra R B] (f : A →ₐ[R] B) (x : A) : of_associative_algebra_hom f x = f x := rfl @[simp] lemma of_associative_algebra_hom_comp {B : Type w} {C : Type w₁} [ring B] [ring C] [algebra R B] [algebra R C] (f : A →ₐ[R] B) (g : B →ₐ[R] C) : of_associative_algebra_hom (g.comp f) = (of_associative_algebra_hom g).comp (of_associative_algebra_hom f) := rfl end lie_algebra end of_associative section adjoint_action variables (R : Type u) (L : Type v) (M : Type w) variables [comm_ring R] [lie_ring L] [lie_algebra R L] [add_comm_group M] [module R M] variables [lie_ring_module L M] [lie_module R L M] /-- A Lie module yields a Lie algebra morphism into the linear endomorphisms of the module. See also `lie_module.to_module_hom`. -/ @[simps] def lie_module.to_endomorphism : L →ₗ⁅R⁆ module.End R M := { to_fun := λ x, { to_fun := λ m, ⁅x, m⁆, map_add' := lie_add x, map_smul' := λ t, lie_smul t x, }, map_add' := λ x y, by { ext m, apply add_lie, }, map_smul' := λ t x, by { ext m, apply smul_lie, }, map_lie' := λ x y, by { ext m, apply lie_lie, }, } /-- The adjoint action of a Lie algebra on itself. -/ def lie_algebra.ad : L →ₗ⁅R⁆ module.End R L := lie_module.to_endomorphism R L L @[simp] lemma lie_algebra.ad_apply (x y : L) : lie_algebra.ad R L x y = ⁅x, y⁆ := rfl open lie_algebra lemma lie_algebra.ad_eq_lmul_left_sub_lmul_right (A : Type v) [ring A] [algebra R A] : (ad R A : A → module.End R A) = algebra.lmul_left R - algebra.lmul_right R := by { ext a b, simp [lie_ring.of_associative_ring_bracket], } variables {R L} lemma lie_subalgebra.ad_comp_incl_eq (K : lie_subalgebra R L) (x : K) : (ad R L ↑x).comp (K.incl : K →ₗ[R] L) = (K.incl : K →ₗ[R] L).comp (ad R K x) := begin ext y, simp only [ad_apply, lie_hom.coe_to_linear_map, lie_subalgebra.coe_incl, linear_map.coe_comp, lie_subalgebra.coe_bracket, function.comp_app], end end adjoint_action /-- A subalgebra of an associative algebra is a Lie subalgebra of the associated Lie algebra. -/ def lie_subalgebra_of_subalgebra (R : Type u) [comm_ring R] (A : Type v) [ring A] [algebra R A] (A' : subalgebra R A) : lie_subalgebra R A := { lie_mem' := λ x y hx hy, by { change ⁅x, y⁆ ∈ A', change x ∈ A' at hx, change y ∈ A' at hy, rw lie_ring.of_associative_ring_bracket, have hxy := A'.mul_mem hx hy, have hyx := A'.mul_mem hy hx, exact submodule.sub_mem A'.to_submodule hxy hyx, }, ..A'.to_submodule } namespace linear_equiv variables {R : Type u} {M₁ : Type v} {M₂ : Type w} variables [comm_ring R] [add_comm_group M₁] [module R M₁] [add_comm_group M₂] [module R M₂] variables (e : M₁ ≃ₗ[R] M₂) /-- A linear equivalence of two modules induces a Lie algebra equivalence of their endomorphisms. -/ def lie_conj : module.End R M₁ ≃ₗ⁅R⁆ module.End R M₂ := { map_lie' := λ f g, show e.conj ⁅f, g⁆ = ⁅e.conj f, e.conj g⁆, by simp only [lie_ring.of_associative_ring_bracket, linear_map.mul_eq_comp, e.conj_comp, linear_equiv.map_sub], ..e.conj } @[simp] lemma lie_conj_apply (f : module.End R M₁) : e.lie_conj f = e.conj f := rfl @[simp] lemma lie_conj_symm : e.lie_conj.symm = e.symm.lie_conj := rfl end linear_equiv namespace alg_equiv variables {R : Type u} {A₁ : Type v} {A₂ : Type w} variables [comm_ring R] [ring A₁] [ring A₂] [algebra R A₁] [algebra R A₂] variables (e : A₁ ≃ₐ[R] A₂) /-- An equivalence of associative algebras is an equivalence of associated Lie algebras. -/ def to_lie_equiv : A₁ ≃ₗ⁅R⁆ A₂ := { to_fun := e.to_fun, map_lie' := λ x y, by simp [lie_ring.of_associative_ring_bracket], ..e.to_linear_equiv } @[simp] lemma to_lie_equiv_apply (x : A₁) : e.to_lie_equiv x = e x := rfl @[simp] lemma to_lie_equiv_symm_apply (x : A₂) : e.to_lie_equiv.symm x = e.symm x := rfl end alg_equiv
b14087cd2244aa5ff4c1f8aa5f54fc3162479ad7
3f7026ea8bef0825ca0339a275c03b911baef64d
/src/algebra/big_operators.lean
105b021c212f4f5b2c3ac529e2c233abda943bcd
[ "Apache-2.0" ]
permissive
rspencer01/mathlib
b1e3afa5c121362ef0881012cc116513ab09f18c
c7d36292c6b9234dc40143c16288932ae38fdc12
refs/heads/master
1,595,010,346,708
1,567,511,503,000
1,567,511,503,000
206,071,681
0
0
Apache-2.0
1,567,513,643,000
1,567,513,643,000
null
UTF-8
Lean
false
false
31,218
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 Some big operators for lists and finite sets. -/ import tactic.tauto data.list.basic data.finset data.nat.enat import algebra.group algebra.ordered_group algebra.group_power universes u v w variables {α : Type u} {β : Type v} {γ : Type w} theorem directed.finset_le {r : α → α → Prop} [is_trans α r] {ι} (hι : nonempty ι) {f : ι → α} (D : directed r f) (s : finset ι) : ∃ z, ∀ i ∈ s, r (f i) (f z) := show ∃ z, ∀ i ∈ s.1, r (f i) (f z), from multiset.induction_on s.1 (let ⟨z⟩ := hι in ⟨z, λ _, false.elim⟩) $ λ i s ⟨j, H⟩, let ⟨k, h₁, h₂⟩ := D i j in ⟨k, λ a h, or.cases_on (multiset.mem_cons.1 h) (λ h, h.symm ▸ h₁) (λ h, trans (H _ h) h₂)⟩ theorem finset.exists_le {α : Type u} [nonempty α] [directed_order α] (s : finset α) : ∃ M, ∀ i ∈ s, i ≤ M := directed.finset_le (by apply_instance) directed_order.directed s namespace finset variables {s s₁ s₂ : finset α} {a : α} {f g : α → β} /-- `prod s f` is the product of `f x` as `x` ranges over the elements of the finite set `s`. -/ @[to_additive] protected def prod [comm_monoid β] (s : finset α) (f : α → β) : β := (s.1.map f).prod @[to_additive] theorem prod_eq_fold [comm_monoid β] (s : finset α) (f : α → β) : s.prod f = s.fold (*) 1 f := rfl section comm_monoid variables [comm_monoid β] @[simp, to_additive] lemma prod_empty {α : Type u} {f : α → β} : (∅:finset α).prod f = 1 := rfl @[simp, to_additive] lemma prod_insert [decidable_eq α] : a ∉ s → (insert a s).prod f = f a * s.prod f := fold_insert @[simp, to_additive] lemma prod_singleton : (singleton a).prod f = f a := eq.trans fold_singleton $ mul_one _ @[simp] lemma prod_const_one : s.prod (λx, (1 : β)) = 1 := by simp only [finset.prod, multiset.map_const, multiset.prod_repeat, one_pow] @[simp] lemma sum_const_zero {β} {s : finset α} [add_comm_monoid β] : s.sum (λx, (0 : β)) = 0 := @prod_const_one _ (multiplicative β) _ _ attribute [to_additive] prod_const_one @[simp, to_additive] lemma prod_image [decidable_eq α] {s : finset γ} {g : γ → α} : (∀x∈s, ∀y∈s, g x = g y → x = y) → (s.image g).prod f = s.prod (λx, f (g x)) := fold_image @[simp, to_additive] lemma prod_map (s : finset α) (e : α ↪ γ) (f : γ → β) : (s.map e).prod f = s.prod (λa, f (e a)) := by rw [finset.prod, finset.map_val, multiset.map_map]; refl @[congr, to_additive] lemma prod_congr (h : s₁ = s₂) : (∀x∈s₂, f x = g x) → s₁.prod f = s₂.prod g := by rw [h]; exact fold_congr attribute [congr] finset.sum_congr @[to_additive] lemma prod_union_inter [decidable_eq α] : (s₁ ∪ s₂).prod f * (s₁ ∩ s₂).prod f = s₁.prod f * s₂.prod f := fold_union_inter @[to_additive] lemma prod_union [decidable_eq α] (h : s₁ ∩ s₂ = ∅) : (s₁ ∪ s₂).prod f = s₁.prod f * s₂.prod f := by rw [←prod_union_inter, h]; exact (mul_one _).symm @[to_additive] lemma prod_sdiff [decidable_eq α] (h : s₁ ⊆ s₂) : (s₂ \ s₁).prod f * s₁.prod f = s₂.prod f := by rw [←prod_union (sdiff_inter_self _ _), sdiff_union_of_subset h] @[to_additive] lemma prod_bind [decidable_eq α] {s : finset γ} {t : γ → finset α} : (∀x∈s, ∀y∈s, x ≠ y → t x ∩ t y = ∅) → (s.bind t).prod f = s.prod (λx, (t x).prod f) := by haveI := classical.dec_eq γ; exact finset.induction_on s (λ _, by simp only [bind_empty, prod_empty]) (assume x s hxs ih hd, have hd' : ∀x∈s, ∀y∈s, x ≠ y → t x ∩ t y = ∅, from assume _ hx _ hy, hd _ (mem_insert_of_mem hx) _ (mem_insert_of_mem hy), have t x ∩ finset.bind s t = ∅, from eq_empty_of_forall_not_mem $ assume a, by rw [mem_inter, mem_bind]; rintro ⟨h₁, y, hys, hy₂⟩; exact eq_empty_iff_forall_not_mem.1 (hd _ (mem_insert_self _ _) _ (mem_insert_of_mem hys) (assume h, hxs (h.symm ▸ hys))) _ (mem_inter_of_mem h₁ hy₂), by simp only [bind_insert, prod_insert hxs, prod_union this, ih hd']) @[to_additive] lemma prod_product {s : finset γ} {t : finset α} {f : γ×α → β} : (s.product t).prod f = s.prod (λx, t.prod $ λy, f (x, y)) := begin haveI := classical.dec_eq α, haveI := classical.dec_eq γ, rw [product_eq_bind, prod_bind (λ x hx y hy h, eq_empty_of_forall_not_mem _)], { congr, funext, exact prod_image (λ _ _ _ _ H, (prod.mk.inj H).2) }, simp only [mem_inter, mem_image], rintro ⟨_, _⟩ ⟨⟨_, _, _⟩, ⟨_, _, _⟩⟩, apply h, cc end @[to_additive] lemma prod_sigma {σ : α → Type*} {s : finset α} {t : Πa, finset (σ a)} {f : sigma σ → β} : (s.sigma t).prod f = s.prod (λa, (t a).prod $ λs, f ⟨a, s⟩) := by haveI := classical.dec_eq α; haveI := (λ a, classical.dec_eq (σ a)); exact calc (s.sigma t).prod f = (s.bind (λa, (t a).image (λs, sigma.mk a s))).prod f : by rw sigma_eq_bind ... = s.prod (λa, ((t a).image (λs, sigma.mk a s)).prod f) : prod_bind $ assume a₁ ha a₂ ha₂ h, eq_empty_of_forall_not_mem $ by simp only [mem_inter, mem_image]; rintro ⟨_, _⟩ ⟨⟨_, _, _⟩, ⟨_, _, _⟩⟩; apply h; cc ... = (s.prod $ λa, (t a).prod $ λs, f ⟨a, s⟩) : prod_congr rfl $ λ _ _, prod_image $ λ _ _ _ _ _, by cc @[to_additive] lemma prod_image' [decidable_eq α] {s : finset γ} {g : γ → α} (h : γ → β) (eq : ∀c∈s, f (g c) = (s.filter (λc', g c' = g c)).prod h) : (s.image g).prod f = s.prod h := begin letI := classical.dec_eq γ, rw [← image_bind_filter_eq s g] {occs := occurrences.pos [2]}, rw [finset.prod_bind], { refine finset.prod_congr rfl (assume a ha, _), rcases finset.mem_image.1 ha with ⟨b, hb, rfl⟩, exact eq b hb }, assume a₀ _ a₁ _ ne, refine disjoint_iff_inter_eq_empty.1 (disjoint_iff_ne.2 _), assume c₀ h₀ c₁ h₁, rcases mem_filter.1 h₀ with ⟨h₀, rfl⟩, rcases mem_filter.1 h₁ with ⟨h₁, rfl⟩, exact mt (congr_arg g) ne end @[to_additive] lemma prod_mul_distrib : s.prod (λx, f x * g x) = s.prod f * s.prod g := eq.trans (by rw one_mul; refl) fold_op_distrib @[to_additive] lemma prod_comm [decidable_eq γ] {s : finset γ} {t : finset α} {f : γ → α → β} : s.prod (λx, t.prod $ f x) = t.prod (λy, s.prod $ λx, f x y) := finset.induction_on s (by simp only [prod_empty, prod_const_one]) $ λ _ _ H ih, by simp only [prod_insert H, prod_mul_distrib, ih] lemma prod_hom [comm_monoid γ] (g : β → γ) [is_monoid_hom g] : s.prod (λx, g (f x)) = g (s.prod f) := eq.trans (by rw is_monoid_hom.map_one g; refl) (fold_hom $ is_monoid_hom.map_mul g) @[to_additive] lemma prod_hom_rel [comm_monoid γ] {r : β → γ → Prop} {f : α → β} {g : α → γ} {s : finset α} (h₁ : r 1 1) (h₂ : ∀a b c, r b c → r (f a * b) (g a * c)) : r (s.prod f) (s.prod g) := begin letI := classical.dec_eq α, refine finset.induction_on s h₁ (assume a s has ih, _), rw [prod_insert has, prod_insert has], exact h₂ a (s.prod f) (s.prod g) ih, end @[to_additive] lemma prod_subset (h : s₁ ⊆ s₂) (hf : ∀x∈s₂, x ∉ s₁ → f x = 1) : s₁.prod f = s₂.prod f := by haveI := classical.dec_eq α; exact have (s₂ \ s₁).prod f = (s₂ \ s₁).prod (λx, 1), from prod_congr rfl $ by simpa only [mem_sdiff, and_imp], by rw [←prod_sdiff h]; simp only [this, prod_const_one, one_mul] @[to_additive] lemma prod_filter (p : α → Prop) [decidable_pred p] (f : α → β) : (s.filter p).prod f = s.prod (λa, if p a then f a else 1) := calc (s.filter p).prod f = (s.filter p).prod (λa, if p a then f a else 1) : prod_congr rfl (assume a h, by rw [if_pos (mem_filter.1 h).2]) ... = s.prod (λa, if p a then f a else 1) : begin refine prod_subset (filter_subset s) (assume x hs h, _), rw [mem_filter, not_and] at h, exact if_neg (h hs) end @[to_additive] lemma prod_eq_single {s : finset α} {f : α → β} (a : α) (h₀ : ∀b∈s, b ≠ a → f b = 1) (h₁ : a ∉ s → f a = 1) : s.prod f = f a := by haveI := classical.dec_eq α; from classical.by_cases (assume : a ∈ s, calc s.prod f = ({a} : finset α).prod f : begin refine (prod_subset _ _).symm, { intros _ H, rwa mem_singleton.1 H }, { simpa only [mem_singleton] } end ... = f a : prod_singleton) (assume : a ∉ s, (prod_congr rfl $ λ b hb, h₀ b hb $ by rintro rfl; cc).trans $ prod_const_one.trans (h₁ this).symm) @[to_additive] lemma prod_attach {f : α → β} : s.attach.prod (λx, f x.val) = s.prod f := by haveI := classical.dec_eq α; exact calc s.attach.prod (λx, f x.val) = ((s.attach).image subtype.val).prod f : by rw [prod_image]; exact assume x _ y _, subtype.eq ... = _ : by rw [attach_image_val] @[to_additive] lemma prod_bij {s : finset α} {t : finset γ} {f : α → β} {g : γ → β} (i : Πa∈s, γ) (hi : ∀a ha, i a ha ∈ t) (h : ∀a ha, f a = g (i a ha)) (i_inj : ∀a₁ a₂ ha₁ ha₂, i a₁ ha₁ = i a₂ ha₂ → a₁ = a₂) (i_surj : ∀b∈t, ∃a ha, b = i a ha) : s.prod f = t.prod g := by haveI := classical.prop_decidable; exact calc s.prod f = s.attach.prod (λx, f x.val) : prod_attach.symm ... = s.attach.prod (λx, g (i x.1 x.2)) : prod_congr rfl $ assume x hx, h _ _ ... = (s.attach.image $ λx:{x // x ∈ s}, i x.1 x.2).prod g : (prod_image $ assume (a₁:{x // x ∈ s}) _ a₂ _ eq, subtype.eq $ i_inj a₁.1 a₂.1 a₁.2 a₂.2 eq).symm ... = t.prod g : prod_subset (by simp only [subset_iff, mem_image, mem_attach]; rintro _ ⟨⟨_, _⟩, _, rfl⟩; solve_by_elim) (assume b hb hb1, false.elim $ hb1 $ by rcases i_surj b hb with ⟨a, ha, rfl⟩; exact mem_image.2 ⟨⟨_, _⟩, mem_attach _ _, rfl⟩) @[to_additive] lemma prod_bij_ne_one {s : finset α} {t : finset γ} {f : α → β} {g : γ → β} (i : Πa∈s, f a ≠ 1 → γ) (hi₁ : ∀a h₁ h₂, i a h₁ h₂ ∈ t) (hi₂ : ∀a₁ a₂ h₁₁ h₁₂ h₂₁ h₂₂, i a₁ h₁₁ h₁₂ = i a₂ h₂₁ h₂₂ → a₁ = a₂) (hi₃ : ∀b∈t, g b ≠ 1 → ∃a h₁ h₂, b = i a h₁ h₂) (h : ∀a h₁ h₂, f a = g (i a h₁ h₂)) : s.prod f = t.prod g := by haveI := classical.prop_decidable; exact calc s.prod f = (s.filter $ λx, f x ≠ 1).prod f : (prod_subset (filter_subset _) $ by simp only [not_imp_comm, mem_filter]; exact λ _, and.intro).symm ... = (t.filter $ λx, g x ≠ 1).prod g : prod_bij (assume a ha, i a (mem_filter.mp ha).1 (mem_filter.mp ha).2) (assume a ha, (mem_filter.mp ha).elim $ λh₁ h₂, mem_filter.mpr ⟨hi₁ a h₁ h₂, λ hg, h₂ (hg ▸ h a h₁ h₂)⟩) (assume a ha, (mem_filter.mp ha).elim $ h a) (assume a₁ a₂ ha₁ ha₂, (mem_filter.mp ha₁).elim $ λha₁₁ ha₁₂, (mem_filter.mp ha₂).elim $ λha₂₁ ha₂₂, hi₂ a₁ a₂ _ _ _ _) (assume b hb, (mem_filter.mp hb).elim $ λh₁ h₂, let ⟨a, ha₁, ha₂, eq⟩ := hi₃ b h₁ h₂ in ⟨a, mem_filter.mpr ⟨ha₁, ha₂⟩, eq⟩) ... = t.prod g : (prod_subset (filter_subset _) $ by simp only [not_imp_comm, mem_filter]; exact λ _, and.intro) @[to_additive] lemma exists_ne_one_of_prod_ne_one : s.prod f ≠ 1 → ∃a∈s, f a ≠ 1 := by haveI := classical.dec_eq α; exact finset.induction_on s (λ H, (H rfl).elim) (assume a s has ih h, classical.by_cases (assume ha : f a = 1, let ⟨a, ha, hfa⟩ := ih (by rwa [prod_insert has, ha, one_mul] at h) in ⟨a, mem_insert_of_mem ha, hfa⟩) (assume hna : f a ≠ 1, ⟨a, mem_insert_self _ _, hna⟩)) @[to_additive] lemma prod_range_succ (f : ℕ → β) (n : ℕ) : (range (nat.succ n)).prod f = f n * (range n).prod f := by rw [range_succ, prod_insert not_mem_range_self] lemma prod_range_succ' (f : ℕ → β) : ∀ n : ℕ, (range (nat.succ n)).prod f = (range n).prod (f ∘ nat.succ) * f 0 | 0 := (prod_range_succ _ _).trans $ mul_comm _ _ | (n + 1) := by rw [prod_range_succ (λ m, f (nat.succ m)), mul_assoc, ← prod_range_succ']; exact prod_range_succ _ _ @[simp] lemma prod_const (b : β) : s.prod (λ a, b) = b ^ s.card := by haveI := classical.dec_eq α; exact finset.induction_on s rfl (λ a s has ih, by rw [prod_insert has, card_insert_of_not_mem has, pow_succ, ih]) lemma prod_pow (s : finset α) (n : ℕ) (f : α → β) : s.prod (λ x, f x ^ n) = s.prod f ^ n := by haveI := classical.dec_eq α; exact finset.induction_on s (by simp) (by simp [_root_.mul_pow] {contextual := tt}) lemma prod_nat_pow (s : finset α) (n : ℕ) (f : α → ℕ) : s.prod (λ x, f x ^ n) = s.prod f ^ n := by haveI := classical.dec_eq α; exact finset.induction_on s (by simp) (by simp [nat.mul_pow] {contextual := tt}) @[to_additive] lemma prod_involution {s : finset α} {f : α → β} : ∀ (g : Π a ∈ s, α) (h₁ : ∀ a ha, f a * f (g a ha) = 1) (h₂ : ∀ a ha, f a ≠ 1 → g a ha ≠ a) (h₃ : ∀ a ha, g a ha ∈ s) (h₄ : ∀ a ha, g (g a ha) (h₃ a ha) = a), s.prod f = 1 := by haveI := classical.dec_eq α; haveI := classical.dec_eq β; exact finset.strong_induction_on s (λ s ih g h₁ h₂ h₃ h₄, if hs : s = ∅ then hs.symm ▸ rfl else let ⟨x, hx⟩ := exists_mem_of_ne_empty hs in have hmem : ∀ y ∈ (s.erase x).erase (g x hx), y ∈ s, from λ y hy, (mem_of_mem_erase (mem_of_mem_erase hy)), have g_inj : ∀ {x hx y hy}, g x hx = g y hy → x = y, from λ x hx y hy h, by rw [← h₄ x hx, ← h₄ y hy]; simp [h], have ih': (erase (erase s x) (g x hx)).prod f = (1 : β) := ih ((s.erase x).erase (g x hx)) ⟨subset.trans (erase_subset _ _) (erase_subset _ _), λ h, not_mem_erase (g x hx) (s.erase x) (h (h₃ x hx))⟩ (λ y hy, g y (hmem y hy)) (λ y hy, h₁ y (hmem y hy)) (λ y hy, h₂ y (hmem y hy)) (λ y hy, mem_erase.2 ⟨λ (h : g y _ = g x hx), by simpa [g_inj h] using hy, mem_erase.2 ⟨λ (h : g y _ = x), have y = g x hx, from h₄ y (hmem y hy) ▸ by simp [h], by simpa [this] using hy, h₃ y (hmem y hy)⟩⟩) (λ y hy, h₄ y (hmem y hy)), if hx1 : f x = 1 then ih' ▸ eq.symm (prod_subset hmem (λ y hy hy₁, have y = x ∨ y = g x hx, by simp [hy] at hy₁; tauto, this.elim (λ h, h.symm ▸ hx1) (λ h, h₁ x hx ▸ h ▸ hx1.symm ▸ (one_mul _).symm))) else by rw [← insert_erase hx, prod_insert (not_mem_erase _ _), ← insert_erase (mem_erase.2 ⟨h₂ x hx hx1, h₃ x hx⟩), prod_insert (not_mem_erase _ _), ih', mul_one, h₁ x hx]) @[to_additive] lemma prod_eq_one [comm_monoid β] {f : α → β} {s : finset α} (h : ∀x∈s, f x = 1) : s.prod f = 1 := calc s.prod f = s.prod (λx, 1) : finset.prod_congr rfl h ... = 1 : finset.prod_const_one end comm_monoid attribute [to_additive] prod_hom lemma sum_smul [add_comm_monoid β] (s : finset α) (n : ℕ) (f : α → β) : s.sum (λ x, add_monoid.smul n (f x)) = add_monoid.smul n (s.sum f) := @prod_pow _ (multiplicative β) _ _ _ _ attribute [to_additive sum_smul] prod_pow @[simp] lemma sum_const [add_comm_monoid β] (b : β) : s.sum (λ a, b) = add_monoid.smul s.card b := @prod_const _ (multiplicative β) _ _ _ attribute [to_additive] prod_const lemma sum_range_succ' [add_comm_monoid β] (f : ℕ → β) : ∀ n : ℕ, (range (nat.succ n)).sum f = (range n).sum (f ∘ nat.succ) + f 0 := @prod_range_succ' (multiplicative β) _ _ attribute [to_additive] prod_range_succ' lemma sum_nat_cast [add_comm_monoid β] [has_one β] (s : finset α) (f : α → ℕ) : ↑(s.sum f) = s.sum (λa, f a : α → β) := (sum_hom _).symm lemma prod_nat_cast [comm_semiring β] (s : finset α) (f : α → ℕ) : ↑(s.prod f) = s.prod (λa, f a : α → β) := (prod_hom _).symm protected lemma sum_nat_coe_enat [decidable_eq α] (s : finset α) (f : α → ℕ) : s.sum (λ x, (f x : enat)) = (s.sum f : ℕ) := begin induction s using finset.induction with a s has ih h, { simp }, { simp [has, ih] } end lemma le_sum_of_subadditive [add_comm_monoid α] [ordered_comm_monoid β] (f : α → β) (h_zero : f 0 = 0) (h_add : ∀x y, f (x + y) ≤ f x + f y) (s : finset γ) (g : γ → α) : f (s.sum g) ≤ s.sum (λc, f (g c)) := begin refine le_trans (multiset.le_sum_of_subadditive f h_zero h_add _) _, rw [multiset.map_map], refl end lemma abs_sum_le_sum_abs [discrete_linear_ordered_field α] {f : β → α} {s : finset β} : abs (s.sum f) ≤ s.sum (λa, abs (f a)) := le_sum_of_subadditive _ abs_zero abs_add s f section comm_group variables [comm_group β] @[simp, to_additive] lemma prod_inv_distrib : s.prod (λx, (f x)⁻¹) = (s.prod f)⁻¹ := prod_hom has_inv.inv end comm_group @[simp] theorem card_sigma {σ : α → Type*} (s : finset α) (t : Π a, finset (σ a)) : card (s.sigma t) = s.sum (λ a, card (t a)) := multiset.card_sigma _ _ lemma card_bind [decidable_eq β] {s : finset α} {t : α → finset β} (h : ∀ x ∈ s, ∀ y ∈ s, x ≠ y → t x ∩ t y = ∅) : (s.bind t).card = s.sum (λ u, card (t u)) := calc (s.bind t).card = (s.bind t).sum (λ _, 1) : by simp ... = s.sum (λ a, (t a).sum (λ _, 1)) : finset.sum_bind h ... = s.sum (λ u, card (t u)) : by simp lemma card_bind_le [decidable_eq β] {s : finset α} {t : α → finset β} : (s.bind t).card ≤ s.sum (λ a, (t a).card) := by haveI := classical.dec_eq α; exact finset.induction_on s (by simp) (λ a s has ih, calc ((insert a s).bind t).card ≤ (t a).card + (s.bind t).card : by rw bind_insert; exact finset.card_union_le _ _ ... ≤ (insert a s).sum (λ a, card (t a)) : by rw sum_insert has; exact add_le_add_left ih _) lemma gsmul_sum [add_comm_group β] {f : α → β} {s : finset α} (z : ℤ) : gsmul z (s.sum f) = s.sum (λa, gsmul z (f a)) := (finset.sum_hom (gsmul z)).symm end finset namespace finset variables {s s₁ s₂ : finset α} {f g : α → β} {b : β} {a : α} @[simp] lemma sum_sub_distrib [add_comm_group β] : s.sum (λx, f x - g x) = s.sum f - s.sum g := sum_add_distrib.trans $ congr_arg _ sum_neg_distrib section semiring variables [semiring β] lemma sum_mul : s.sum f * b = s.sum (λx, f x * b) := (sum_hom (λx, x * b)).symm lemma mul_sum : b * s.sum f = s.sum (λx, b * f x) := (sum_hom (λx, b * x)).symm end semiring section comm_semiring variables [decidable_eq α] [comm_semiring β] lemma prod_eq_zero (ha : a ∈ s) (h : f a = 0) : s.prod f = 0 := calc s.prod f = (insert a (erase s a)).prod f : by rw insert_erase ha ... = 0 : by rw [prod_insert (not_mem_erase _ _), h, zero_mul] lemma prod_sum {δ : α → Type*} [∀a, decidable_eq (δ a)] {s : finset α} {t : Πa, finset (δ a)} {f : Πa, δ a → β} : s.prod (λa, (t a).sum (λb, f a b)) = (s.pi t).sum (λp, s.attach.prod (λx, f x.1 (p x.1 x.2))) := begin induction s using finset.induction with a s ha ih, { rw [pi_empty, sum_singleton], refl }, { have h₁ : ∀x ∈ t a, ∀y ∈ t a, ∀h : x ≠ y, image (pi.cons s a x) (pi s t) ∩ image (pi.cons s a y) (pi s t) = ∅, { assume x hx y hy h, apply eq_empty_of_forall_not_mem, simp only [mem_inter, mem_image], rintro p₁ ⟨⟨p₂, hp, eq⟩, ⟨p₃, hp₃, rfl⟩⟩, have : pi.cons s a x p₂ a (mem_insert_self _ _) = pi.cons s a y p₃ a (mem_insert_self _ _), { rw [eq] }, rw [pi.cons_same, pi.cons_same] at this, exact h this }, rw [prod_insert ha, pi_insert ha, ih, sum_mul, sum_bind h₁], refine sum_congr rfl (λ b _, _), have h₂ : ∀p₁∈pi s t, ∀p₂∈pi s t, pi.cons s a b p₁ = pi.cons s a b p₂ → p₁ = p₂, from assume p₁ h₁ p₂ h₂ eq, injective_pi_cons ha eq, rw [sum_image h₂, mul_sum], refine sum_congr rfl (λ g _, _), rw [attach_insert, prod_insert, prod_image], { simp only [pi.cons_same], congr', ext ⟨v, hv⟩, congr', exact (pi.cons_ne (by rintro rfl; exact ha hv)).symm }, { exact λ _ _ _ _, subtype.eq ∘ subtype.mk.inj }, { simp only [mem_image], rintro ⟨⟨_, hm⟩, _, rfl⟩, exact ha hm } } end end comm_semiring section integral_domain /- add integral_semi_domain to support nat and ennreal -/ variables [decidable_eq α] [integral_domain β] lemma prod_eq_zero_iff : s.prod f = 0 ↔ (∃a∈s, f a = 0) := finset.induction_on s ⟨not.elim one_ne_zero, λ ⟨_, H, _⟩, H.elim⟩ $ λ a s ha ih, by rw [prod_insert ha, mul_eq_zero_iff_eq_zero_or_eq_zero, bex_def, exists_mem_insert, ih, ← bex_def] end integral_domain section ordered_comm_monoid variables [decidable_eq α] [ordered_comm_monoid β] lemma sum_le_sum : (∀x∈s, f x ≤ g x) → s.sum f ≤ s.sum g := finset.induction_on s (λ _, le_refl _) $ assume a s ha ih h, have f a + s.sum f ≤ g a + s.sum g, from add_le_add' (h _ (mem_insert_self _ _)) (ih $ assume x hx, h _ $ mem_insert_of_mem hx), by simpa only [sum_insert ha] lemma sum_nonneg (h : ∀x∈s, 0 ≤ f x) : 0 ≤ s.sum f := le_trans (by rw [sum_const_zero]) (sum_le_sum h) lemma sum_nonpos (h : ∀x∈s, f x ≤ 0) : s.sum f ≤ 0 := le_trans (sum_le_sum h) (by rw [sum_const_zero]) lemma sum_le_sum_of_subset_of_nonneg (h : s₁ ⊆ s₂) (hf : ∀x∈s₂, x ∉ s₁ → 0 ≤ f x) : s₁.sum f ≤ s₂.sum f := calc s₁.sum f ≤ (s₂ \ s₁).sum f + s₁.sum f : le_add_of_nonneg_left' $ sum_nonneg $ by simpa only [mem_sdiff, and_imp] ... = (s₂ \ s₁ ∪ s₁).sum f : (sum_union (sdiff_inter_self _ _)).symm ... = s₂.sum f : by rw [sdiff_union_of_subset h] lemma sum_eq_zero_iff_of_nonneg : (∀x∈s, 0 ≤ f x) → (s.sum f = 0 ↔ ∀x∈s, f x = 0) := finset.induction_on s (λ _, ⟨λ _ _, false.elim, λ _, rfl⟩) $ λ a s ha ih H, have ∀ x ∈ s, 0 ≤ f x, from λ _, H _ ∘ mem_insert_of_mem, by rw [sum_insert ha, add_eq_zero_iff' (H _ $ mem_insert_self _ _) (sum_nonneg this), forall_mem_insert, ih this] lemma single_le_sum (hf : ∀x∈s, 0 ≤ f x) {a} (h : a ∈ s) : f a ≤ s.sum f := have (singleton a).sum f ≤ s.sum f, from sum_le_sum_of_subset_of_nonneg (λ x e, (mem_singleton.1 e).symm ▸ h) (λ x h _, hf x h), by rwa sum_singleton at this end ordered_comm_monoid section canonically_ordered_monoid variables [decidable_eq α] [canonically_ordered_monoid β] [@decidable_rel β (≤)] lemma sum_le_sum_of_subset (h : s₁ ⊆ s₂) : s₁.sum f ≤ s₂.sum f := sum_le_sum_of_subset_of_nonneg h $ assume x h₁ h₂, zero_le _ lemma sum_le_sum_of_ne_zero (h : ∀x∈s₁, f x ≠ 0 → x ∈ s₂) : s₁.sum f ≤ s₂.sum f := calc s₁.sum f = (s₁.filter (λx, f x = 0)).sum f + (s₁.filter (λx, f x ≠ 0)).sum f : by rw [←sum_union, filter_union_filter_neg_eq]; apply filter_inter_filter_neg_eq ... ≤ s₂.sum f : add_le_of_nonpos_of_le' (sum_nonpos $ by simp only [mem_filter, and_imp]; exact λ _ _, le_of_eq) (sum_le_sum_of_subset $ by simpa only [subset_iff, mem_filter, and_imp]) end canonically_ordered_monoid section linear_ordered_comm_ring variables [decidable_eq α] [linear_ordered_comm_ring β] /- this is also true for a ordered commutative multiplicative monoid -/ lemma prod_nonneg {s : finset α} {f : α → β} (h0 : ∀(x ∈ s), 0 ≤ f x) : 0 ≤ s.prod f := begin induction s using finset.induction with a s has ih h, { simp [zero_le_one] }, { simp [has], apply mul_nonneg, apply h0 a (mem_insert_self a s), exact ih (λ x H, h0 x (mem_insert_of_mem H)) } end /- this is also true for a ordered commutative multiplicative monoid -/ lemma prod_pos {s : finset α} {f : α → β} (h0 : ∀(x ∈ s), 0 < f x) : 0 < s.prod f := begin induction s using finset.induction with a s has ih h, { simp [zero_lt_one] }, { simp [has], apply mul_pos, apply h0 a (mem_insert_self a s), exact ih (λ x H, h0 x (mem_insert_of_mem H)) } end /- this is also true for a ordered commutative multiplicative monoid -/ lemma prod_le_prod {s : finset α} {f g : α → β} (h0 : ∀(x ∈ s), 0 ≤ f x) (h1 : ∀(x ∈ s), f x ≤ g x) : s.prod f ≤ s.prod g := begin induction s using finset.induction with a s has ih h, { simp }, { simp [has], apply mul_le_mul, exact h1 a (mem_insert_self a s), apply ih (λ x H, h0 _ _) (λ x H, h1 _ _); exact (mem_insert_of_mem H), apply prod_nonneg (λ x H, h0 x (mem_insert_of_mem H)), apply le_trans (h0 a (mem_insert_self a s)) (h1 a (mem_insert_self a s)) } end end linear_ordered_comm_ring @[simp] lemma card_pi [decidable_eq α] {δ : α → Type*} (s : finset α) (t : Π a, finset (δ a)) : (s.pi t).card = s.prod (λ a, card (t a)) := multiset.card_pi _ _ @[simp] lemma prod_range_id_eq_fact (n : ℕ) : ((range n.succ).erase 0).prod (λ x, x) = nat.fact n := calc ((range n.succ).erase 0).prod (λ x, x) = (range n).prod nat.succ : eq.symm (prod_bij (λ x _, nat.succ x) (λ a h₁, mem_erase.2 ⟨nat.succ_ne_zero _, mem_range.2 $ nat.succ_lt_succ $ by simpa using h₁⟩) (by simp) (λ _ _ _ _, nat.succ_inj) (λ b h, have b.pred.succ = b, from nat.succ_pred_eq_of_pos $ by simp [nat.pos_iff_ne_zero] at *; tauto, ⟨nat.pred b, mem_range.2 $ nat.lt_of_succ_lt_succ (by simp [*] at *), this.symm⟩)) ... = nat.fact n : by induction n; simp [*, range_succ] end finset section geom_sum open finset theorem geom_sum_mul_add [semiring α] (x : α) : ∀ (n : ℕ), ((range n).sum (λ i, (x+1)^i)) * x + 1 = (x+1)^n | 0 := by simp | (n+1) := calc (range (n + 1)).sum (λi, (x + 1) ^ i) * x + 1 = (x + 1)^n * x + (((range n).sum (λ i, (x+1)^i)) * x + 1) : by simp [range_add_one, add_mul] ... = (x + 1)^n * x + (x + 1)^n : by rw geom_sum_mul_add n ... = (x + 1) ^ (n + 1) : by simp [pow_add, mul_add] theorem geom_sum_mul [ring α] (x : α) (n : ℕ) : ((range n).sum (λ i, x^i)) * (x-1) = x^n-1 := have _ := geom_sum_mul_add (x-1) n, by rw [sub_add_cancel] at this; rw [← this, add_sub_cancel] theorem geom_sum [division_ring α] {x : α} (h : x ≠ 1) (n : ℕ) : (range n).sum (λ i, x^i) = (x^n-1)/(x-1) := have x - 1 ≠ 0, by simp [*, -sub_eq_add_neg, sub_eq_iff_eq_add] at *, by rw [← geom_sum_mul, mul_div_cancel _ this] lemma geom_sum_inv [division_ring α] {x : α} (hx1 : x ≠ 1) (hx0 : x ≠ 0) (n : ℕ) : (range n).sum (λ m, x⁻¹ ^ m) = (x - 1)⁻¹ * (x - x⁻¹ ^ n * x) := have h₁ : x⁻¹ ≠ 1, by rwa [inv_eq_one_div, ne.def, div_eq_iff_mul_eq hx0, one_mul], have h₂ : x⁻¹ - 1 ≠ 0, from mt sub_eq_zero.1 h₁, have h₃ : x - 1 ≠ 0, from mt sub_eq_zero.1 hx1, have h₄ : x * x⁻¹ ^ n = x⁻¹ ^ n * x, from nat.cases_on n (by simp) (λ _, by conv { to_rhs, rw [pow_succ', mul_assoc, inv_mul_cancel hx0, mul_one] }; rw [pow_succ, ← mul_assoc, mul_inv_cancel hx0, one_mul]), by rw [geom_sum h₁, div_eq_iff_mul_eq h₂, ← domain.mul_left_inj h₃, ← mul_assoc, ← mul_assoc, mul_inv_cancel h₃]; simp [mul_add, add_mul, mul_inv_cancel hx0, mul_assoc, h₄] end geom_sum namespace finset section gauss_sum /-- Gauss' summation formula -/ lemma sum_range_id_mul_two : ∀(n : ℕ), (finset.range n).sum (λi, i) * 2 = n * (n - 1) | 0 := rfl | 1 := rfl | ((n + 1) + 1) := begin rw [sum_range_succ, add_mul, sum_range_id_mul_two (n + 1), mul_comm, two_mul, nat.add_sub_cancel, nat.add_sub_cancel, mul_comm _ n], simp only [add_mul, one_mul, add_comm, add_assoc, add_left_comm] end /-- Gauss' summation formula -/ lemma sum_range_id (n : ℕ) : (finset.range n).sum (λi, i) = (n * (n - 1)) / 2 := by rw [← sum_range_id_mul_two n, nat.mul_div_cancel]; exact dec_trivial end gauss_sum lemma card_eq_sum_ones (s : finset α) : s.card = s.sum (λ _, 1) := by simp end finset section group open list variables [group α] [group β] @[to_additive] theorem is_group_hom.map_prod (f : α → β) [is_group_hom f] (l : list α) : f (prod l) = prod (map f l) := by induction l; simp only [*, is_mul_hom.map_mul f, is_group_hom.map_one f, prod_nil, prod_cons, map] theorem is_group_anti_hom.map_prod (f : α → β) [is_group_anti_hom f] (l : list α) : f (prod l) = prod (map f (reverse l)) := by induction l with hd tl ih; [exact is_group_anti_hom.map_one f, simp only [prod_cons, is_group_anti_hom.map_mul f, ih, reverse_cons, map_append, prod_append, map_singleton, prod_cons, prod_nil, mul_one]] theorem inv_prod : ∀ l : list α, (prod l)⁻¹ = prod (map (λ x, x⁻¹) (reverse l)) := λ l, @is_group_anti_hom.map_prod _ _ _ _ _ inv_is_group_anti_hom l -- TODO there is probably a cleaner proof of this end group section comm_group variables [comm_group α] [comm_group β] (f : α → β) [is_group_hom f] @[to_additive] lemma is_group_hom.map_multiset_prod (m : multiset α) : f m.prod = (m.map f).prod := quotient.induction_on m $ assume l, by simp [is_group_hom.map_prod f l] @[to_additive] lemma is_group_hom.map_finset_prod (g : γ → α) (s : finset γ) : f (s.prod g) = s.prod (f ∘ g) := show f (s.val.map g).prod = (s.val.map (f ∘ g)).prod, by rw [is_group_hom.map_multiset_prod f]; simp end comm_group @[to_additive is_add_group_hom_finset_sum] lemma is_group_hom_finset_prod {α β γ} [group α] [comm_group β] (s : finset γ) (f : γ → α → β) [∀c, is_group_hom (f c)] : is_group_hom (λa, s.prod (λc, f c a)) := { map_mul := assume a b, by simp only [λc, is_mul_hom.map_mul (f c), finset.prod_mul_distrib] } attribute [instance] is_group_hom_finset_prod is_add_group_hom_finset_sum namespace multiset variables [decidable_eq α] @[simp] lemma to_finset_sum_count_eq (s : multiset α) : s.to_finset.sum (λa, s.count a) = s.card := multiset.induction_on s rfl (assume a s ih, calc (to_finset (a :: s)).sum (λx, count x (a :: s)) = (to_finset (a :: s)).sum (λx, (if x = a then 1 else 0) + count x s) : finset.sum_congr rfl $ λ _ _, by split_ifs; [simp only [h, count_cons_self, nat.one_add], simp only [count_cons_of_ne h, zero_add]] ... = card (a :: s) : begin by_cases a ∈ s.to_finset, { have : (to_finset s).sum (λx, ite (x = a) 1 0) = (finset.singleton a).sum (λx, ite (x = a) 1 0), { apply (finset.sum_subset _ _).symm, { intros _ H, rwa mem_singleton.1 H }, { exact λ _ _ H, if_neg (mt finset.mem_singleton.2 H) } }, rw [to_finset_cons, finset.insert_eq_of_mem h, finset.sum_add_distrib, ih, this, finset.sum_singleton, if_pos rfl, add_comm, card_cons] }, { have ha : a ∉ s, by rwa mem_to_finset at h, have : (to_finset s).sum (λx, ite (x = a) 1 0) = (to_finset s).sum (λx, 0), from finset.sum_congr rfl (λ x hx, if_neg $ by rintro rfl; cc), rw [to_finset_cons, finset.sum_insert h, if_pos rfl, finset.sum_add_distrib, this, finset.sum_const_zero, ih, count_eq_zero_of_not_mem ha, zero_add, add_comm, card_cons] } end) end multiset
c04bc9d272d6a6c9fcec4536829fa1c26259d849
4727251e0cd73359b15b664c3170e5d754078599
/src/order/lattice_intervals.lean
ba6cce6b5c81328a8fc26b88f0b84cd73e256ef3
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
5,211
lean
/- Copyright (c) 2020 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson -/ import order.bounds /-! # Intervals in Lattices In this file, we provide instances of lattice structures on intervals within lattices. Some of them depend on the order of the endpoints of the interval, and thus are not made global instances. These are probably not all of the lattice instances that could be placed on these intervals, but more can be added easily along the same lines when needed. ## Main definitions In the following, `*` can represent either `c`, `o`, or `i`. * `set.Ic*.order_bot` * `set.Ii*.semillatice_inf` * `set.I*c.order_top` * `set.I*c.semillatice_inf` * `set.I**.lattice` * `set.Iic.bounded_order`, within an `order_bot` * `set.Ici.bounded_order`, within an `order_top` -/ variable {α : Type*} namespace set namespace Ico variables {a b : α} instance [semilattice_inf α] : semilattice_inf (Ico a b) := subtype.semilattice_inf (λ x y hx hy, ⟨le_inf hx.1 hy.1, lt_of_le_of_lt inf_le_left hx.2⟩) /-- `Ico a b` has a bottom element whenever `a < b`. -/ @[reducible] protected def order_bot [partial_order α] (h : a < b) : order_bot (Ico a b) := (is_least_Ico h).order_bot end Ico namespace Iio instance [semilattice_inf α] {a : α} : semilattice_inf (Iio a) := subtype.semilattice_inf (λ x y hx hy, lt_of_le_of_lt inf_le_left hx) end Iio namespace Ioc variables {a b : α} instance [semilattice_sup α] : semilattice_sup (Ioc a b) := subtype.semilattice_sup (λ x y hx hy, ⟨lt_of_lt_of_le hx.1 le_sup_left, sup_le hx.2 hy.2⟩) /-- `Ioc a b` has a top element whenever `a < b`. -/ @[reducible] protected def order_top [partial_order α] (h : a < b) : order_top (Ioc a b) := (is_greatest_Ioc h).order_top end Ioc namespace Iio instance [semilattice_sup α] {a : α} : semilattice_sup (Ioi a) := subtype.semilattice_sup (λ x y hx hy, lt_of_lt_of_le hx le_sup_left) end Iio namespace Iic variables {a : α} instance [semilattice_inf α] : semilattice_inf (Iic a) := subtype.semilattice_inf (λ x y hx hy, le_trans inf_le_left hx) instance [semilattice_sup α] : semilattice_sup (Iic a) := subtype.semilattice_sup (λ x y hx hy, sup_le hx hy) instance [lattice α] : lattice (Iic a) := { .. Iic.semilattice_inf, .. Iic.semilattice_sup } instance [preorder α] : order_top (Iic a) := { top := ⟨a, le_refl a⟩, le_top := λ x, x.prop } @[simp] lemma coe_top [preorder α] {a : α} : ↑(⊤ : Iic a) = a := rfl instance [preorder α] [order_bot α] : order_bot (Iic a) := { bot := ⟨⊥, bot_le⟩, bot_le := λ ⟨_,_⟩, subtype.mk_le_mk.2 bot_le } @[simp] lemma coe_bot [preorder α] [order_bot α] {a : α} : ↑(⊥ : Iic a) = (⊥ : α) := rfl instance [partial_order α] [no_min_order α] {a : α} : no_min_order (Iic a) := ⟨λ x, let ⟨y, hy⟩ := exists_lt x.1 in ⟨⟨y, le_trans hy.le x.2⟩, hy⟩ ⟩ instance [preorder α] [order_bot α] : bounded_order (Iic a) := { .. Iic.order_top, .. Iic.order_bot } end Iic namespace Ici variables {a : α} instance [semilattice_inf α] : semilattice_inf (Ici a) := subtype.semilattice_inf (λ x y hx hy, le_inf hx hy) instance [semilattice_sup α] : semilattice_sup (Ici a) := subtype.semilattice_sup (λ x y hx hy, le_trans hx le_sup_left) instance [lattice α] : lattice (Ici a) := { .. Ici.semilattice_inf, .. Ici.semilattice_sup } instance [preorder α] : order_bot (Ici a) := { bot := ⟨a, le_refl a⟩, bot_le := λ x, x.prop } @[simp] lemma coe_bot [preorder α] {a : α} : ↑(⊥ : Ici a) = a := rfl instance [preorder α] [order_top α] : order_top (Ici a) := { top := ⟨⊤, le_top⟩, le_top := λ ⟨_,_⟩, subtype.mk_le_mk.2 le_top } @[simp] lemma coe_top [preorder α] [order_top α] {a : α} : ↑(⊤ : Ici a) = (⊤ : α) := rfl instance [partial_order α] [no_max_order α] {a : α} : no_max_order (Ici a) := ⟨λ x, let ⟨y, hy⟩ := exists_gt x.1 in ⟨⟨y, le_trans x.2 hy.le⟩, hy⟩ ⟩ instance [preorder α] [order_top α] : bounded_order (Ici a) := { .. Ici.order_top, .. Ici.order_bot } end Ici namespace Icc instance [semilattice_inf α] {a b : α} : semilattice_inf (Icc a b) := subtype.semilattice_inf (λ x y hx hy, ⟨le_inf hx.1 hy.1, le_trans inf_le_left hx.2⟩) instance [semilattice_sup α] {a b : α} : semilattice_sup (Icc a b) := subtype.semilattice_sup (λ x y hx hy, ⟨le_trans hx.1 le_sup_left, sup_le hx.2 hy.2⟩) instance [lattice α] {a b : α} : lattice (Icc a b) := { .. Icc.semilattice_inf, .. Icc.semilattice_sup } /-- `Icc a b` has a bottom element whenever `a ≤ b`. -/ @[reducible] protected def order_bot [preorder α] {a b : α} (h : a ≤ b) : order_bot (Icc a b) := (is_least_Icc h).order_bot /-- `Icc a b` has a top element whenever `a ≤ b`. -/ @[reducible] protected def order_top [preorder α] {a b : α} (h : a ≤ b) : order_top (Icc a b) := (is_greatest_Icc h).order_top /-- `Icc a b` is a `bounded_order` whenever `a ≤ b`. -/ @[reducible] protected def bounded_order [preorder α] {a b : α} (h : a ≤ b) : bounded_order (Icc a b) := { .. Icc.order_top h, .. Icc.order_bot h } end Icc end set
d5c08557d201a711e379d06565743ecc816fea2e
367134ba5a65885e863bdc4507601606690974c1
/src/order/category/omega_complete_partial_order.lean
570f8ac3950842fa84f2ed9e6c1ac55681923523
[ "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,971
lean
/- Copyright (c) 2020 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Simon Hudon -/ import order.omega_complete_partial_order import order.category.Preorder import category_theory.limits.shapes.products import category_theory.limits.shapes.equalizers import category_theory.limits.constructions.limits_of_products_and_equalizers /-! # Category of types with a omega complete partial order In this file, we bundle the class `omega_complete_partial_order` into a concrete category and prove that continuous functions also form a `omega_complete_partial_order`. ## Main definitions * `ωCPO` * an instance of `category` and `concrete_category` -/ open category_theory universes u v /-- The category of types with a omega complete partial order. -/ def ωCPO : Type (u+1) := bundled omega_complete_partial_order namespace ωCPO open omega_complete_partial_order instance : bundled_hom @continuous_hom := { to_fun := @continuous_hom.to_fun, id := @continuous_hom.id, comp := @continuous_hom.comp, hom_ext := @continuous_hom.coe_inj } attribute [derive [has_coe_to_sort, large_category, concrete_category]] ωCPO /-- Construct a bundled ωCPO from the underlying type and typeclass. -/ def of (α : Type*) [omega_complete_partial_order α] : ωCPO := bundled.of α instance : inhabited ωCPO := ⟨of punit⟩ instance (α : ωCPO) : omega_complete_partial_order α := α.str section open category_theory.limits namespace has_products /-- The pi-type gives a cone for a product. -/ def product {J : Type v} (f : J → ωCPO.{v}) : fan f := fan.mk (of (Π j, f j)) (λ j, continuous_hom.of_mono (pi.monotone_apply j : _) (λ c, rfl)) /-- The pi-type is a limit cone for the product. -/ def is_product (J : Type v) (f : J → ωCPO) : is_limit (product f) := { lift := λ s, ⟨λ t j, s.π.app j t, λ x y h j, (s.π.app j).monotone h, λ x, funext (λ j, (s.π.app j).continuous x)⟩, uniq' := λ s m w, begin ext t j, change m t j = s.π.app j t, rw ← w j, refl, end }. instance (J : Type v) (f : J → ωCPO.{v}) : has_product f := has_limit.mk ⟨_, is_product _ f⟩ end has_products instance omega_complete_partial_order_equalizer {α β : Type*} [omega_complete_partial_order α] [omega_complete_partial_order β] (f g : α →𝒄 β) : omega_complete_partial_order {a : α // f a = g a} := omega_complete_partial_order.subtype _ $ λ c hc, begin rw [f.continuous, g.continuous], congr' 1, ext, apply hc _ ⟨_, rfl⟩, end namespace has_equalizers /-- The equalizer inclusion function as a `continuous_hom`. -/ def equalizer_ι {α β : Type*} [omega_complete_partial_order α] [omega_complete_partial_order β] (f g : α →𝒄 β) : {a : α // f a = g a} →𝒄 α := continuous_hom.of_mono (preorder_hom.subtype.val _) (λ c, rfl) /-- A construction of the equalizer fork. -/ def equalizer {X Y : ωCPO.{v}} (f g : X ⟶ Y) : fork f g := @fork.of_ι _ _ _ _ _ _ (ωCPO.of {a // f a = g a}) (equalizer_ι f g) (continuous_hom.ext _ _ (λ x, x.2)) /-- The equalizer fork is a limit. -/ def is_equalizer {X Y : ωCPO.{v}} (f g : X ⟶ Y) : is_limit (equalizer f g) := fork.is_limit.mk' _ $ λ s, ⟨{ to_fun := λ x, ⟨s.ι x, by apply continuous_hom.congr_fun s.condition⟩, monotone' := λ x y h, s.ι.monotone h, cont := λ x, subtype.ext (s.ι.continuous x) }, by { ext, refl }, λ m hm, begin ext, apply continuous_hom.congr_fun hm, end⟩ end has_equalizers instance : has_products ωCPO.{v} := λ J, { has_limit := λ F, has_limit_of_iso discrete.nat_iso_functor.symm } instance {X Y : ωCPO.{v}} (f g : X ⟶ Y) : has_limit (parallel_pair f g) := has_limit.mk ⟨_, has_equalizers.is_equalizer f g⟩ instance : has_equalizers ωCPO.{v} := has_equalizers_of_has_limit_parallel_pair _ instance : has_limits ωCPO.{v} := limits_from_equalizers_and_products end end ωCPO
25ed57ee3cf0260c4976c6068797362ed58c9335
b7f22e51856f4989b970961f794f1c435f9b8f78
/hott/algebra/category/category.hlean
9b18f7e161a7f964b38e1137e1359827ba3be918
[ "Apache-2.0" ]
permissive
soonhokong/lean
cb8aa01055ffe2af0fb99a16b4cda8463b882cd1
38607e3eb57f57f77c0ac114ad169e9e4262e24f
refs/heads/master
1,611,187,284,081
1,450,766,737,000
1,476,122,547,000
11,513,992
2
0
null
1,401,763,102,000
1,374,182,235,000
C++
UTF-8
Lean
false
false
5,095
hlean
/- Copyright (c) 2014 Jakob von Raumer. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jakob von Raumer -/ import .iso open iso is_equiv equiv eq is_trunc sigma /- A category is a precategory extended by a witness that the function from paths to isomorphisms is an equivalence. -/ namespace category /- TODO: restructure this. Should is_univalent be a class with as argument (C : Precategory). Or is that problematic if we want to apply this to cases where e.g. a b are functors, and we need to synthesize ? : precategory (functor C D). -/ definition is_univalent [class] {ob : Type} (C : precategory ob) := Π(a b : ob), is_equiv (iso_of_eq : a = b → a ≅ b) definition is_equiv_of_is_univalent [instance] {ob : Type} [C : precategory ob] [H : is_univalent C] (a b : ob) : is_equiv (iso_of_eq : a = b → a ≅ b) := H a b structure category [class] (ob : Type) extends parent : precategory ob := mk' :: (iso_of_path_equiv : is_univalent parent) -- Remark: category and precategory are classes. So, the structure command -- does not create a coercion between them automatically. -- This coercion is needed for definitions such as category_eq_of_equiv -- without it, we would have to explicitly use category.to_precategory attribute category.to_precategory [coercion] abbreviation iso_of_path_equiv := @category.iso_of_path_equiv attribute category.iso_of_path_equiv [instance] definition category.mk [reducible] [unfold 2] {ob : Type} (C : precategory ob) (H : is_univalent C) : category ob := precategory.rec_on C category.mk' H section basic variables {ob : Type} [C : category ob] include C -- Make iso_of_path_equiv a class instance attribute iso_of_path_equiv [instance] definition eq_equiv_iso [constructor] (a b : ob) : (a = b) ≃ (a ≅ b) := equiv.mk iso_of_eq _ definition eq_of_iso [reducible] {a b : ob} : a ≅ b → a = b := iso_of_eq⁻¹ᶠ definition iso_of_eq_eq_of_iso {a b : ob} (p : a ≅ b) : iso_of_eq (eq_of_iso p) = p := right_inv iso_of_eq p definition hom_of_eq_eq_of_iso {a b : ob} (p : a ≅ b) : hom_of_eq (eq_of_iso p) = to_hom p := ap to_hom !iso_of_eq_eq_of_iso definition inv_of_eq_eq_of_iso {a b : ob} (p : a ≅ b) : inv_of_eq (eq_of_iso p) = to_inv p := ap to_inv !iso_of_eq_eq_of_iso theorem eq_of_iso_refl {a : ob} : eq_of_iso (iso.refl a) = idp := inv_eq_of_eq idp theorem eq_of_iso_trans {a b c : ob} (p : a ≅ b) (q : b ≅ c) : eq_of_iso (p ⬝i q) = eq_of_iso p ⬝ eq_of_iso q := begin apply inv_eq_of_eq, apply eq.inverse, apply concat, apply iso_of_eq_con, apply concat, apply ap (λ x, x ⬝i _), apply iso_of_eq_eq_of_iso, apply ap (λ x, _ ⬝i x), apply iso_of_eq_eq_of_iso end definition is_trunc_1_ob : is_trunc 1 ob := begin apply is_trunc_succ_intro, intro a b, fapply is_trunc_is_equiv_closed, exact (@eq_of_iso _ _ a b), apply is_equiv_inv, end end basic -- Bundled version of categories -- we don't use Category.carrier explicitly, but rather use Precategory.carrier (to_Precategory C) structure Category : Type := (carrier : Type) (struct : category carrier) attribute Category.struct [instance] [coercion] definition Category.to_Precategory [constructor] [coercion] [reducible] (C : Category) : Precategory := Precategory.mk (Category.carrier C) _ definition category.Mk [constructor] [reducible] := Category.mk definition category.MK [constructor] [reducible] (C : Precategory) (H : is_univalent C) : Category := Category.mk C (category.mk C H) definition Category.eta (C : Category) : Category.mk C C = C := Category.rec (λob c, idp) C protected definition category.sigma_char.{u v} [constructor] (ob : Type) : category.{u v} ob ≃ Σ(C : precategory.{u v} ob), is_univalent C := begin fapply equiv.MK, { intro x, induction x, constructor, assumption}, { intro y, induction y with y1 y2, induction y1, constructor, assumption}, { intro y, induction y with y1 y2, induction y1, reflexivity}, { intro x, induction x, reflexivity} end definition category_eq {ob : Type} {C D : category ob} (p : Π{a b}, @hom ob C a b = @hom ob D a b) (q : Πa b c g f, cast p (@comp ob C a b c g f) = @comp ob D a b c (cast p g) (cast p f)) : C = D := begin apply eq_of_fn_eq_fn !category.sigma_char, fapply sigma_eq, { induction C, induction D, esimp, exact precategory_eq @p q}, { unfold is_univalent, apply is_prop.elimo}, end definition category_eq_of_equiv {ob : Type} {C D : category ob} (p : Π⦃a b⦄, @hom ob C a b ≃ @hom ob D a b) (q : Π{a b c} g f, p (@comp ob C a b c g f) = @comp ob D a b c (p g) (p f)) : C = D := begin fapply category_eq, { intro a b, exact ua !@p}, { intros, refine !cast_ua ⬝ !q ⬝ _, unfold [category.to_precategory], apply ap011 !@category.comp !cast_ua⁻¹ᵖ !cast_ua⁻¹ᵖ}, end -- TODO: Category_eq['] end category
7305d3bf8fa7ab23c2e186f865d64325bf1b98a8
5ca7b1b12d14c4742e29366312ba2c2ef8201b21
/experiments/tactic_mathematician.lean
af0b35ab59c6cdd511a7591cd70a6d8d56e6ff18
[ "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
878
lean
-- this is how structure_helper works. I liked my name -- better though -- `i_checked_all_teh_axioms` namespace tactic.interactive open tactic meta def replace_special_names : name → name | `add := `has_add.add | n := n meta def i_checked_all_teh_axioms : tactic unit := do t ← target, env ← get_env, match t with | expr.app (expr.const sn _) e := match env.structure_fields sn with | some l := do n :: _ ← tactic.open_namespaces, let lf := l.map replace_special_names, v ← lf.mmap resolve_name, let s : structure_instance_info := { struct := some sn, field_names := l, field_values := v, }, e ← to_expr $ pexpr.mk_structure_instance s, tactic.exact e | none := fail "goal not a structure" end | _ := fail "unsupported goal" end end tactic.interactive
c6fcc880cdbdee7b91db15e9b5f32ae5c0ad2f0e
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/number_theory/padics/hensel.lean
88d82eda6ebd265b6f4b132e0dc5afdc463dac0d
[ "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
20,631
lean
/- Copyright (c) 2018 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis -/ import analysis.specific_limits.basic import data.polynomial.identities import number_theory.padics.padic_integers import topology.algebra.polynomial import topology.metric_space.cau_seq_filter /-! # Hensel's lemma on ℤ_p This file proves Hensel's lemma on ℤ_p, roughly following Keith Conrad's writeup: <http://www.math.uconn.edu/~kconrad/blurbs/gradnumthy/hensel.pdf> Hensel's lemma gives a simple condition for the existence of a root of a polynomial. The proof and motivation are described in the paper [R. Y. Lewis, *A formal proof of Hensel's lemma over the p-adic integers*][lewis2019]. ## References * <http://www.math.uconn.edu/~kconrad/blurbs/gradnumthy/hensel.pdf> * [R. Y. Lewis, *A formal proof of Hensel's lemma over the p-adic integers*][lewis2019] * <https://en.wikipedia.org/wiki/Hensel%27s_lemma> ## Tags p-adic, p adic, padic, p-adic integer -/ noncomputable theory open_locale classical topological_space -- We begin with some general lemmas that are used below in the computation. lemma padic_polynomial_dist {p : ℕ} [fact p.prime] (F : polynomial ℤ_[p]) (x y : ℤ_[p]) : ‖F.eval x - F.eval y‖ ≤ ‖x - y‖ := let ⟨z, hz⟩ := F.eval_sub_factor x y in calc ‖F.eval x - F.eval y‖ = ‖z‖ * ‖x - y‖ : by simp [hz] ... ≤ 1 * ‖x - y‖ : mul_le_mul_of_nonneg_right (padic_int.norm_le_one _) (norm_nonneg _) ... = ‖x - y‖ : by simp open filter metric private lemma comp_tendsto_lim {p : ℕ} [fact p.prime] {F : polynomial ℤ_[p]} (ncs : cau_seq ℤ_[p] norm) : tendsto (λ i, F.eval (ncs i)) at_top (𝓝 (F.eval ncs.lim)) := F.continuous_at.tendsto.comp ncs.tendsto_limit section parameters {p : ℕ} [fact p.prime] {ncs : cau_seq ℤ_[p] norm} {F : polynomial ℤ_[p]} {a : ℤ_[p]} (ncs_der_val : ∀ n, ‖F.derivative.eval (ncs n)‖ = ‖F.derivative.eval a‖) include ncs_der_val private lemma ncs_tendsto_const : tendsto (λ i, ‖F.derivative.eval (ncs i)‖) at_top (𝓝 ‖F.derivative.eval a‖) := by convert tendsto_const_nhds; ext; rw ncs_der_val private lemma ncs_tendsto_lim : tendsto (λ i, ‖F.derivative.eval (ncs i)‖) at_top (𝓝 (‖F.derivative.eval ncs.lim‖)) := tendsto.comp (continuous_iff_continuous_at.1 continuous_norm _) (comp_tendsto_lim _) private lemma norm_deriv_eq : ‖F.derivative.eval ncs.lim‖ = ‖F.derivative.eval a‖ := tendsto_nhds_unique ncs_tendsto_lim ncs_tendsto_const end section parameters {p : ℕ} [fact p.prime] {ncs : cau_seq ℤ_[p] norm} {F : polynomial ℤ_[p]} (hnorm : tendsto (λ i, ‖F.eval (ncs i)‖) at_top (𝓝 0)) include hnorm private lemma tendsto_zero_of_norm_tendsto_zero : tendsto (λ i, F.eval (ncs i)) at_top (𝓝 0) := tendsto_iff_norm_tendsto_zero.2 (by simpa using hnorm) lemma limit_zero_of_norm_tendsto_zero : F.eval ncs.lim = 0 := tendsto_nhds_unique (comp_tendsto_lim _) tendsto_zero_of_norm_tendsto_zero end section hensel open nat parameters {p : ℕ} [fact p.prime] {F : polynomial ℤ_[p]} {a : ℤ_[p]} (hnorm : ‖F.eval a‖ < ‖F.derivative.eval a‖^2) (hnsol : F.eval a ≠ 0) include hnorm /-- `T` is an auxiliary value that is used to control the behavior of the polynomial `F`. -/ private def T : ℝ := ‖(F.eval a / (F.derivative.eval a)^2 : ℚ_[p])‖ private lemma deriv_sq_norm_pos : 0 < ‖F.derivative.eval a‖ ^ 2 := lt_of_le_of_lt (norm_nonneg _) hnorm private lemma deriv_sq_norm_ne_zero : ‖F.derivative.eval a‖^2 ≠ 0 := ne_of_gt deriv_sq_norm_pos private lemma deriv_norm_ne_zero : ‖F.derivative.eval a‖ ≠ 0 := λ h, deriv_sq_norm_ne_zero (by simp [*, sq]) private lemma deriv_norm_pos : 0 < ‖F.derivative.eval a‖ := lt_of_le_of_ne (norm_nonneg _) (ne.symm deriv_norm_ne_zero) private lemma deriv_ne_zero : F.derivative.eval a ≠ 0 := mt norm_eq_zero.2 deriv_norm_ne_zero private lemma T_def : T = ‖F.eval a‖ / ‖F.derivative.eval a‖^2 := by simp [T, ← padic_int.norm_def] private lemma T_lt_one : T < 1 := let h := (div_lt_one deriv_sq_norm_pos).2 hnorm in by rw T_def; apply h private lemma T_nonneg : 0 ≤ T := norm_nonneg _ private lemma T_pow_nonneg (n : ℕ) : 0 ≤ T ^ n := pow_nonneg T_nonneg _ private lemma T_pow {n : ℕ} (hn : n ≠ 0) : T ^ n < 1 := pow_lt_one T_nonneg T_lt_one hn private lemma T_pow' (n : ℕ) : T ^ (2 ^ n) < 1 := T_pow (pow_ne_zero _ two_ne_zero) /-- We will construct a sequence of elements of ℤ_p satisfying successive values of `ih`. -/ private def ih (n : ℕ) (z : ℤ_[p]) : Prop := ‖F.derivative.eval z‖ = ‖F.derivative.eval a‖ ∧ ‖F.eval z‖ ≤ ‖F.derivative.eval a‖^2 * T ^ (2^n) private lemma ih_0 : ih 0 a := ⟨ rfl, by simp [T_def, mul_div_cancel' _ (ne_of_gt (deriv_sq_norm_pos hnorm))] ⟩ private lemma calc_norm_le_one {n : ℕ} {z : ℤ_[p]} (hz : ih n z) : ‖(↑(F.eval z) : ℚ_[p]) / ↑(F.derivative.eval z)‖ ≤ 1 := calc ‖(↑(F.eval z) : ℚ_[p]) / ↑(F.derivative.eval z)‖ = ‖(↑(F.eval z) : ℚ_[p])‖ / ‖(↑(F.derivative.eval z) : ℚ_[p])‖ : norm_div _ _ ... = ‖F.eval z‖ / ‖F.derivative.eval a‖ : by simp [hz.1] ... ≤ ‖F.derivative.eval a‖^2 * T^(2^n) / ‖F.derivative.eval a‖ : (div_le_div_right deriv_norm_pos).2 hz.2 ... = ‖F.derivative.eval a‖ * T^(2^n) : div_sq_cancel _ _ ... ≤ 1 : mul_le_one (padic_int.norm_le_one _) (T_pow_nonneg _) (le_of_lt (T_pow' _)) private lemma calc_deriv_dist {z z' z1 : ℤ_[p]} (hz' : z' = z - z1) (hz1 : ‖z1‖ = ‖F.eval z‖ / ‖F.derivative.eval a‖) {n} (hz : ih n z) : ‖F.derivative.eval z' - F.derivative.eval z‖ < ‖F.derivative.eval a‖ := calc ‖F.derivative.eval z' - F.derivative.eval z‖ ≤ ‖z' - z‖ : padic_polynomial_dist _ _ _ ... = ‖z1‖ : by simp only [sub_eq_add_neg, add_assoc, hz', add_add_neg_cancel'_right, norm_neg] ... = ‖F.eval z‖ / ‖F.derivative.eval a‖ : hz1 ... ≤ ‖F.derivative.eval a‖^2 * T^(2^n) / ‖F.derivative.eval a‖ : (div_le_div_right deriv_norm_pos).2 hz.2 ... = ‖F.derivative.eval a‖ * T^(2^n) : div_sq_cancel _ _ ... < ‖F.derivative.eval a‖ : (mul_lt_iff_lt_one_right deriv_norm_pos).2 (T_pow' _) private def calc_eval_z' {z z' z1 : ℤ_[p]} (hz' : z' = z - z1) {n} (hz : ih n z) (h1 : ‖(↑(F.eval z) : ℚ_[p]) / ↑(F.derivative.eval z)‖ ≤ 1) (hzeq : z1 = ⟨_, h1⟩) : {q : ℤ_[p] // F.eval z' = q * z1^2} := begin have hdzne : F.derivative.eval z ≠ 0 := mt norm_eq_zero.2 (by rw hz.1; apply deriv_norm_ne_zero; assumption), have hdzne' : (↑(F.derivative.eval z) : ℚ_[p]) ≠ 0 := λ h, hdzne (subtype.ext_iff_val.2 h), obtain ⟨q, hq⟩ := F.binom_expansion z (-z1), have : ‖(↑(F.derivative.eval z) * (↑(F.eval z) / ↑(F.derivative.eval z)) : ℚ_[p])‖ ≤ 1, { rw padic_norm_e.mul, exact mul_le_one (padic_int.norm_le_one _) (norm_nonneg _) h1 }, have : F.derivative.eval z * (-z1) = -F.eval z, { calc F.derivative.eval z * (-z1) = (F.derivative.eval z) * -⟨↑(F.eval z) / ↑(F.derivative.eval z), h1⟩ : by rw [hzeq] ... = -((F.derivative.eval z) * ⟨↑(F.eval z) / ↑(F.derivative.eval z), h1⟩) : mul_neg _ _ ... = -(⟨↑(F.derivative.eval z) * (↑(F.eval z) / ↑(F.derivative.eval z)), this⟩) : subtype.ext $ by simp only [padic_int.coe_neg, padic_int.coe_mul, subtype.coe_mk] ... = -(F.eval z) : by simp only [mul_div_cancel' _ hdzne', subtype.coe_eta] }, exact ⟨q, by simpa only [sub_eq_add_neg, this, hz', add_right_neg, neg_sq, zero_add] using hq⟩, end private def calc_eval_z'_norm {z z' z1 : ℤ_[p]} {n} (hz : ih n z) {q} (heq : F.eval z' = q * z1^2) (h1 : ‖(↑(F.eval z) : ℚ_[p]) / ↑(F.derivative.eval z)‖ ≤ 1) (hzeq : z1 = ⟨_, h1⟩) : ‖F.eval z'‖ ≤ ‖F.derivative.eval a‖^2 * T^(2^(n+1)) := calc ‖F.eval z'‖ = ‖q‖ * ‖z1‖^2 : by simp [heq] ... ≤ 1 * ‖z1‖^2 : mul_le_mul_of_nonneg_right (padic_int.norm_le_one _) (pow_nonneg (norm_nonneg _) _) ... = ‖F.eval z‖^2 / ‖F.derivative.eval a‖^2 : by simp [hzeq, hz.1, div_pow] ... ≤ (‖F.derivative.eval a‖^2 * T^(2^n))^2 / ‖F.derivative.eval a‖^2 : (div_le_div_right deriv_sq_norm_pos).2 (pow_le_pow_of_le_left (norm_nonneg _) hz.2 _) ... = (‖F.derivative.eval a‖^2)^2 * (T^(2^n))^2 / ‖F.derivative.eval a‖^2 : by simp only [mul_pow] ... = ‖F.derivative.eval a‖^2 * (T^(2^n))^2 : div_sq_cancel _ _ ... = ‖F.derivative.eval a‖^2 * T^(2^(n + 1)) : by rw [←pow_mul, pow_succ' 2] set_option eqn_compiler.zeta true /-- Given `z : ℤ_[p]` satisfying `ih n z`, construct `z' : ℤ_[p]` satisfying `ih (n+1) z'`. We need the hypothesis `ih n z`, since otherwise `z'` is not necessarily an integer. -/ private def ih_n {n : ℕ} {z : ℤ_[p]} (hz : ih n z) : {z' : ℤ_[p] // ih (n+1) z'} := have h1 : ‖(↑(F.eval z) : ℚ_[p]) / ↑(F.derivative.eval z)‖ ≤ 1, from calc_norm_le_one hz, let z1 : ℤ_[p] := ⟨_, h1⟩, z' : ℤ_[p] := z - z1 in ⟨ z', have hdist : ‖F.derivative.eval z' - F.derivative.eval z‖ < ‖F.derivative.eval a‖, from calc_deriv_dist rfl (by simp [z1, hz.1]) hz, have hfeq : ‖F.derivative.eval z'‖ = ‖F.derivative.eval a‖, begin rw [sub_eq_add_neg, ← hz.1, ←norm_neg (F.derivative.eval z)] at hdist, have := padic_int.norm_eq_of_norm_add_lt_right hdist, rwa [norm_neg, hz.1] at this end, let ⟨q, heq⟩ := calc_eval_z' rfl hz h1 rfl in have hnle : ‖F.eval z'‖ ≤ ‖F.derivative.eval a‖^2 * T^(2^(n+1)), from calc_eval_z'_norm hz heq h1 rfl, ⟨hfeq, hnle⟩⟩ set_option eqn_compiler.zeta false -- why doesn't "noncomputable theory" stick here? private noncomputable def newton_seq_aux : Π n : ℕ, {z : ℤ_[p] // ih n z} | 0 := ⟨a, ih_0⟩ | (k+1) := ih_n (newton_seq_aux k).2 private def newton_seq (n : ℕ) : ℤ_[p] := (newton_seq_aux n).1 private lemma newton_seq_deriv_norm (n : ℕ) : ‖F.derivative.eval (newton_seq n)‖ = ‖F.derivative.eval a‖ := (newton_seq_aux n).2.1 private lemma newton_seq_norm_le (n : ℕ) : ‖F.eval (newton_seq n)‖ ≤ ‖F.derivative.eval a‖^2 * T ^ (2^n) := (newton_seq_aux n).2.2 private lemma newton_seq_norm_eq (n : ℕ) : ‖newton_seq (n+1) - newton_seq n‖ = ‖F.eval (newton_seq n)‖ / ‖F.derivative.eval (newton_seq n)‖ := by simp [newton_seq, newton_seq_aux, ih_n, sub_eq_add_neg, add_comm] private lemma newton_seq_succ_dist (n : ℕ) : ‖newton_seq (n+1) - newton_seq n‖ ≤ ‖F.derivative.eval a‖ * T^(2^n) := calc ‖newton_seq (n+1) - newton_seq n‖ = ‖F.eval (newton_seq n)‖ / ‖F.derivative.eval (newton_seq n)‖ : newton_seq_norm_eq _ ... = ‖F.eval (newton_seq n)‖ / ‖F.derivative.eval a‖ : by rw newton_seq_deriv_norm ... ≤ ‖F.derivative.eval a‖^2 * T ^ (2^n) / ‖F.derivative.eval a‖ : (div_le_div_right deriv_norm_pos).2 (newton_seq_norm_le _) ... = ‖F.derivative.eval a‖ * T^(2^n) : div_sq_cancel _ _ include hnsol private lemma T_pos : T > 0 := begin rw T_def, exact div_pos (norm_pos_iff.2 hnsol) (deriv_sq_norm_pos hnorm) end private lemma newton_seq_succ_dist_weak (n : ℕ) : ‖newton_seq (n+2) - newton_seq (n+1)‖ < ‖F.eval a‖ / ‖F.derivative.eval a‖ := have 2 ≤ 2^(n+1), from have _, from pow_le_pow (by norm_num : 1 ≤ 2) (nat.le_add_left _ _ : 1 ≤ n + 1), by simpa using this, calc ‖newton_seq (n+2) - newton_seq (n+1)‖ ≤ ‖F.derivative.eval a‖ * T^(2^(n+1)) : newton_seq_succ_dist _ ... ≤ ‖F.derivative.eval a‖ * T^2 : mul_le_mul_of_nonneg_left (pow_le_pow_of_le_one (norm_nonneg _) (le_of_lt T_lt_one) this) (norm_nonneg _) ... < ‖F.derivative.eval a‖ * T^1 : mul_lt_mul_of_pos_left (pow_lt_pow_of_lt_one T_pos T_lt_one (by norm_num)) deriv_norm_pos ... = ‖F.eval a‖ / ‖F.derivative.eval a‖ : begin rw [T, sq, pow_one, norm_div, ←mul_div_assoc, padic_norm_e.mul], apply mul_div_mul_left, apply deriv_norm_ne_zero; assumption end private lemma newton_seq_dist_aux (n : ℕ) : ∀ k : ℕ, ‖newton_seq (n + k) - newton_seq n‖ ≤ ‖F.derivative.eval a‖ * T^(2^n) | 0 := by simp [T_pow_nonneg hnorm, mul_nonneg] | (k+1) := have 2^n ≤ 2^(n+k), by {apply pow_le_pow, norm_num, apply nat.le_add_right}, calc ‖newton_seq (n + (k + 1)) - newton_seq n‖ = ‖newton_seq ((n + k) + 1) - newton_seq n‖ : by rw add_assoc ... = ‖(newton_seq ((n + k) + 1) - newton_seq (n+k)) + (newton_seq (n+k) - newton_seq n)‖ : by rw ←sub_add_sub_cancel ... ≤ max (‖newton_seq ((n + k) + 1) - newton_seq (n+k)‖) (‖newton_seq (n+k) - newton_seq n‖) : padic_int.nonarchimedean _ _ ... ≤ max (‖F.derivative.eval a‖ * T^(2^((n + k)))) (‖F.derivative.eval a‖ * T^(2^n)) : max_le_max (newton_seq_succ_dist _) (newton_seq_dist_aux _) ... = ‖F.derivative.eval a‖ * T^(2^n) : max_eq_right $ mul_le_mul_of_nonneg_left (pow_le_pow_of_le_one (norm_nonneg _) (le_of_lt T_lt_one) this) (norm_nonneg _) private lemma newton_seq_dist {n k : ℕ} (hnk : n ≤ k) : ‖newton_seq k - newton_seq n‖ ≤ ‖F.derivative.eval a‖ * T^(2^n) := have hex : ∃ m, k = n + m, from exists_eq_add_of_le hnk, let ⟨_, hex'⟩ := hex in by rw hex'; apply newton_seq_dist_aux; assumption private lemma newton_seq_dist_to_a : ∀ n : ℕ, 0 < n → ‖newton_seq n - a‖ = ‖F.eval a‖ / ‖F.derivative.eval a‖ | 1 h := by simp [sub_eq_add_neg, add_assoc, newton_seq, newton_seq_aux, ih_n] | (k+2) h := have hlt : ‖newton_seq (k+2) - newton_seq (k+1)‖ < ‖newton_seq (k+1) - a‖, by rw newton_seq_dist_to_a (k+1) (succ_pos _); apply newton_seq_succ_dist_weak; assumption, have hne' : ‖newton_seq (k + 2) - newton_seq (k+1)‖ ≠ ‖newton_seq (k+1) - a‖, from ne_of_lt hlt, calc ‖newton_seq (k + 2) - a‖ = ‖(newton_seq (k + 2) - newton_seq (k+1)) + (newton_seq (k+1) - a)‖ : by rw ←sub_add_sub_cancel ... = max (‖newton_seq (k + 2) - newton_seq (k+1)‖) (‖newton_seq (k+1) - a‖) : padic_int.norm_add_eq_max_of_ne hne' ... = ‖newton_seq (k+1) - a‖ : max_eq_right_of_lt hlt ... = ‖polynomial.eval a F‖ / ‖polynomial.eval a (polynomial.derivative F)‖ : newton_seq_dist_to_a (k+1) (succ_pos _) private lemma bound' : tendsto (λ n : ℕ, ‖F.derivative.eval a‖ * T^(2^n)) at_top (𝓝 0) := begin rw ←mul_zero (‖F.derivative.eval a‖), exact tendsto_const_nhds.mul (tendsto.comp (tendsto_pow_at_top_nhds_0_of_lt_1 (norm_nonneg _) (T_lt_one hnorm)) (nat.tendsto_pow_at_top_at_top_of_one_lt (by norm_num))) end private lemma bound : ∀ {ε}, ε > 0 → ∃ N : ℕ, ∀ {n}, n ≥ N → ‖F.derivative.eval a‖ * T^(2^n) < ε := begin have := bound' hnorm hnsol, simp [tendsto, nhds] at this, intros ε hε, cases this (ball 0 ε) (mem_ball_self hε) (is_open_ball) with N hN, existsi N, intros n hn, simpa [abs_of_nonneg (T_nonneg _)] using hN _ hn end private lemma bound'_sq : tendsto (λ n : ℕ, ‖F.derivative.eval a‖^2 * T^(2^n)) at_top (𝓝 0) := begin rw [←mul_zero (‖F.derivative.eval a‖), sq], simp only [mul_assoc], apply tendsto.mul, { apply tendsto_const_nhds }, { apply bound', assumption } end private theorem newton_seq_is_cauchy : is_cau_seq norm newton_seq := begin intros ε hε, cases bound hnorm hnsol hε with N hN, existsi N, intros j hj, apply lt_of_le_of_lt, { apply newton_seq_dist _ _ hj, assumption }, { apply hN, exact le_rfl } end private def newton_cau_seq : cau_seq ℤ_[p] norm := ⟨_, newton_seq_is_cauchy⟩ private def soln : ℤ_[p] := newton_cau_seq.lim private lemma soln_spec {ε : ℝ} (hε : ε > 0) : ∃ (N : ℕ), ∀ {i : ℕ}, i ≥ N → ‖soln - newton_cau_seq i‖ < ε := setoid.symm (cau_seq.equiv_lim newton_cau_seq) _ hε private lemma soln_deriv_norm : ‖F.derivative.eval soln‖ = ‖F.derivative.eval a‖ := norm_deriv_eq newton_seq_deriv_norm private lemma newton_seq_norm_tendsto_zero : tendsto (λ i, ‖F.eval (newton_cau_seq i)‖) at_top (𝓝 0) := squeeze_zero (λ _, norm_nonneg _) newton_seq_norm_le bound'_sq private lemma newton_seq_dist_tendsto : tendsto (λ n, ‖newton_cau_seq n - a‖) at_top (𝓝 (‖F.eval a‖ / ‖F.derivative.eval a‖)) := tendsto_const_nhds.congr' $ eventually_at_top.2 ⟨1, λ _ hx, (newton_seq_dist_to_a _ hx).symm⟩ private lemma newton_seq_dist_tendsto' : tendsto (λ n, ‖newton_cau_seq n - a‖) at_top (𝓝 ‖soln - a‖) := (continuous_norm.tendsto _).comp (newton_cau_seq.tendsto_limit.sub tendsto_const_nhds) private lemma soln_dist_to_a : ‖soln - a‖ = ‖F.eval a‖ / ‖F.derivative.eval a‖ := tendsto_nhds_unique newton_seq_dist_tendsto' newton_seq_dist_tendsto private lemma soln_dist_to_a_lt_deriv : ‖soln - a‖ < ‖F.derivative.eval a‖ := begin rw [soln_dist_to_a, div_lt_iff], { rwa sq at hnorm }, { apply deriv_norm_pos, assumption } end private lemma eval_soln : F.eval soln = 0 := limit_zero_of_norm_tendsto_zero newton_seq_norm_tendsto_zero private lemma soln_unique (z : ℤ_[p]) (hev : F.eval z = 0) (hnlt : ‖z - a‖ < ‖F.derivative.eval a‖) : z = soln := have soln_dist : ‖z - soln‖ < ‖F.derivative.eval a‖, from calc ‖z - soln‖ = ‖(z - a) + (a - soln)‖ : by rw sub_add_sub_cancel ... ≤ max (‖z - a‖) (‖a - soln‖) : padic_int.nonarchimedean _ _ ... < ‖F.derivative.eval a‖ : max_lt hnlt (norm_sub_rev soln a ▸ soln_dist_to_a_lt_deriv), let h := z - soln, ⟨q, hq⟩ := F.binom_expansion soln h in have (F.derivative.eval soln + q * h) * h = 0, from eq.symm (calc 0 = F.eval (soln + h) : by simp [hev, h] ... = F.derivative.eval soln * h + q * h^2 : by rw [hq, eval_soln, zero_add] ... = (F.derivative.eval soln + q * h) * h : by rw [sq, right_distrib, mul_assoc]), have h = 0, from by_contradiction $ λ hne, have F.derivative.eval soln + q * h = 0, from (eq_zero_or_eq_zero_of_mul_eq_zero this).resolve_right hne, have F.derivative.eval soln = (-q) * h, by simpa using eq_neg_of_add_eq_zero_left this, lt_irrefl ‖F.derivative.eval soln‖ (calc ‖F.derivative.eval soln‖ = ‖(-q) * h‖ : by rw this ... ≤ 1 * ‖h‖ : by { rw padic_int.norm_mul, exact mul_le_mul_of_nonneg_right (padic_int.norm_le_one _) (norm_nonneg _) } ... = ‖z - soln‖ : by simp [h] ... < ‖F.derivative.eval soln‖ : by rw soln_deriv_norm; apply soln_dist), eq_of_sub_eq_zero (by rw ←this; refl) end hensel variables {p : ℕ} [fact p.prime] {F : polynomial ℤ_[p]} {a : ℤ_[p]} private lemma a_soln_is_unique (ha : F.eval a = 0) (z' : ℤ_[p]) (hz' : F.eval z' = 0) (hnormz' : ‖z' - a‖ < ‖F.derivative.eval a‖) : z' = a := let h := z' - a, ⟨q, hq⟩ := F.binom_expansion a h in have (F.derivative.eval a + q * h) * h = 0, from eq.symm (calc 0 = F.eval (a + h) : show 0 = F.eval (a + (z' - a)), by rw add_comm; simp [hz'] ... = F.derivative.eval a * h + q * h^2 : by rw [hq, ha, zero_add] ... = (F.derivative.eval a + q * h) * h : by rw [sq, right_distrib, mul_assoc]), have h = 0, from by_contradiction $ λ hne, have F.derivative.eval a + q * h = 0, from (eq_zero_or_eq_zero_of_mul_eq_zero this).resolve_right hne, have F.derivative.eval a = (-q) * h, by simpa using eq_neg_of_add_eq_zero_left this, lt_irrefl ‖F.derivative.eval a‖ (calc ‖F.derivative.eval a‖ = ‖q‖*‖h‖ : by simp [this] ... ≤ 1*‖h‖ : mul_le_mul_of_nonneg_right (padic_int.norm_le_one _) (norm_nonneg _) ... < ‖F.derivative.eval a‖ : by simpa [h]), eq_of_sub_eq_zero (by rw ←this; refl) variable (hnorm : ‖F.eval a‖ < ‖F.derivative.eval a‖^2) include hnorm private lemma a_is_soln (ha : F.eval a = 0) : F.eval a = 0 ∧ ‖a - a‖ < ‖F.derivative.eval a‖ ∧ ‖F.derivative.eval a‖ = ‖F.derivative.eval a‖ ∧ ∀ z', F.eval z' = 0 → ‖z' - a‖ < ‖F.derivative.eval a‖ → z' = a := ⟨ha, by simp [deriv_ne_zero hnorm], rfl, a_soln_is_unique ha⟩ lemma hensels_lemma : ∃ z : ℤ_[p], F.eval z = 0 ∧ ‖z - a‖ < ‖F.derivative.eval a‖ ∧ ‖F.derivative.eval z‖ = ‖F.derivative.eval a‖ ∧ ∀ z', F.eval z' = 0 → ‖z' - a‖ < ‖F.derivative.eval a‖ → z' = z := if ha : F.eval a = 0 then ⟨a, a_is_soln hnorm ha⟩ else by refine ⟨soln _ _, eval_soln _ _, soln_dist_to_a_lt_deriv _ _, soln_deriv_norm _ _, soln_unique _ _⟩; assumption
c39ebee6be23930473607b3b13aa3a479615c9d4
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/ring_theory/flat.lean
0bbee1cab74cf43530395abc1d9c3cf483df1e92
[ "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,645
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 linear_algebra.dimension import ring_theory.noetherian import ring_theory.algebra_tower /-! # Flat modules A module `M` over a commutative ring `R` is *flat* if for all finitely generated ideals `I` of `R`, the canonical map `I ⊗ M →ₗ M` is injective. This is equivalent to the claim that for all injective `R`-linear maps `f : M₁ → M₂` the induced map `M₁ ⊗ M → M₂ ⊗ M` is injective. See <https://stacks.math.columbia.edu/tag/00HD>. This result is not yet formalised. ## Main declaration * `module.flat`: the predicate asserting that an `R`-module `M` is flat. ## TODO * Show that tensoring with a flat module preserves injective morphisms. Show that this is equivalent to be flat. See <https://stacks.math.columbia.edu/tag/00HD>. To do this, it is probably a good idea to think about a suitable categorical induction principle that should be applied to the category of `R`-modules, and that will take care of the administrative side of the proof. * Define flat `R`-algebras * Define flat ring homomorphisms - Show that the identity is flat - Show that composition of flat morphisms is flat * Show that flatness is stable under base change (aka extension of scalars) For base change, it will be very useful to have a "characteristic predicate" instead of relying on the construction `A ⊗ B`. Indeed, such a predicate should allow us to treat both `polynomial A` and `A ⊗ polynomial R` as the base change of `polynomial R` to `A`. (Similar examples exist with `fin n → R`, `R × R`, `ℤ[i] ⊗ ℝ`, etc...) * Generalize flatness to noncommutative rings. -/ namespace module open function (injective) open linear_map (lsmul) open_locale tensor_product /-- An `R`-module `M` is flat if for all finitely generated ideals `I` of `R`, the canonical map `I ⊗ M →ₗ M` is injective. -/ class flat (R M : Type*) [comm_ring R] [add_comm_group M] [module R M] : Prop := (out : ∀ ⦃I : ideal R⦄ (hI : I.fg), injective (tensor_product.lift ((lsmul R M).comp I.subtype))) namespace flat open tensor_product linear_map submodule instance self (R : Type*) [comm_ring R] : flat R R := ⟨begin intros I hI, rw ← equiv.injective_comp (tensor_product.rid R I).symm.to_equiv, convert subtype.coe_injective using 1, ext x, simp only [function.comp_app, linear_equiv.coe_to_equiv, rid_symm_apply, comp_apply, mul_one, lift.tmul, subtype_apply, algebra.id.smul_eq_mul, lsmul_apply] end⟩ end flat end module
42ec2bb419e46f331d262d98e69ecfc7eeddb63b
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/polynomial/eval.lean
fe34d31f7346152fe5b410bdbc3b113ec8ee9e8f
[]
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
25,104
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Jens Wagemaker -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.polynomial.induction import Mathlib.data.polynomial.degree.definitions import Mathlib.deprecated.ring import Mathlib.PostPort universes u v u_1 u_2 w y namespace Mathlib /-! # Theory of univariate polynomials The main defs here are `eval₂`, `eval`, and `map`. We give several lemmas about their interaction with each other and with module operations. -/ namespace polynomial /-- 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₂ {R : Type u} {S : Type v} [semiring R] [semiring S] (f : R →+* S) (x : S) (p : polynomial R) : S := finsupp.sum p fun (e : ℕ) (a : R) => coe_fn f a * x ^ e theorem eval₂_eq_sum {R : Type u} {S : Type v} [semiring R] {p : polynomial R} [semiring S] {f : R →+* S} {x : S} : eval₂ f x p = finsupp.sum p fun (e : ℕ) (a : R) => coe_fn f a * x ^ e := rfl theorem eval₂_eq_lift_nc {R : Type u} {S : Type v} [semiring R] [semiring S] {f : R →+* S} {x : S} : eval₂ f x = ⇑(add_monoid_algebra.lift_nc (↑f) (coe_fn (powers_hom S) x)) := rfl theorem eval₂_congr {R : Type u_1} {S : Type u_2} [semiring R] [semiring S] {f : R →+* S} {g : R →+* S} {s : S} {t : S} {φ : polynomial R} {ψ : polynomial R} : f = g → s = t → φ = ψ → eval₂ f s φ = eval₂ g t ψ := fun (ᾰ : f = g) (ᾰ_1 : s = t) (ᾰ_2 : φ = ψ) => Eq._oldrec (Eq._oldrec (Eq._oldrec (Eq.refl (eval₂ f s φ)) ᾰ_2) ᾰ_1) ᾰ @[simp] theorem eval₂_zero {R : Type u} {S : Type v} [semiring R] [semiring S] (f : R →+* S) (x : S) : eval₂ f x 0 = 0 := finsupp.sum_zero_index @[simp] theorem eval₂_C {R : Type u} {S : Type v} {a : R} [semiring R] [semiring S] (f : R →+* S) (x : S) : eval₂ f x (coe_fn C a) = coe_fn f a := sorry @[simp] theorem eval₂_X {R : Type u} {S : Type v} [semiring R] [semiring S] (f : R →+* S) (x : S) : eval₂ f x X = x := sorry @[simp] theorem eval₂_monomial {R : Type u} {S : Type v} [semiring R] [semiring S] (f : R →+* S) (x : S) {n : ℕ} {r : R} : eval₂ f x (coe_fn (monomial n) r) = coe_fn f r * x ^ n := sorry @[simp] theorem eval₂_X_pow {R : Type u} {S : Type v} [semiring R] [semiring S] (f : R →+* S) (x : S) {n : ℕ} : eval₂ f x (X ^ n) = x ^ n := sorry @[simp] theorem eval₂_add {R : Type u} {S : Type v} [semiring R] {p : polynomial R} {q : polynomial R} [semiring S] (f : R →+* S) (x : S) : eval₂ f x (p + q) = eval₂ f x p + eval₂ f x q := sorry @[simp] theorem eval₂_one {R : Type u} {S : Type v} [semiring R] [semiring S] (f : R →+* S) (x : S) : eval₂ f x 1 = 1 := eq.mpr (id (Eq._oldrec (Eq.refl (eval₂ f x 1 = 1)) (Eq.symm C_1))) (eq.mpr (id (Eq._oldrec (Eq.refl (eval₂ f x (coe_fn C 1) = 1)) (eval₂_C f x))) (eq.mpr (id (Eq._oldrec (Eq.refl (coe_fn f 1 = 1)) (ring_hom.map_one f))) (Eq.refl 1))) @[simp] theorem eval₂_bit0 {R : Type u} {S : Type v} [semiring R] {p : polynomial R} [semiring S] (f : R →+* S) (x : S) : eval₂ f x (bit0 p) = bit0 (eval₂ f x p) := sorry @[simp] theorem eval₂_bit1 {R : Type u} {S : Type v} [semiring R] {p : polynomial R} [semiring S] (f : R →+* S) (x : S) : eval₂ f x (bit1 p) = bit1 (eval₂ f x p) := sorry @[simp] theorem eval₂_smul {R : Type u} {S : Type v} [semiring R] [semiring S] (g : R →+* S) (p : polynomial R) (x : S) {s : R} : eval₂ g x (s • p) = coe_fn g s • eval₂ g x p := sorry @[simp] theorem eval₂_C_X {R : Type u} [semiring R] {p : polynomial R} : eval₂ C X p = p := sorry protected instance eval₂.is_add_monoid_hom {R : Type u} {S : Type v} [semiring R] [semiring S] (f : R →+* S) (x : S) : is_add_monoid_hom (eval₂ f x) := is_add_monoid_hom.mk (eval₂_zero f x) @[simp] theorem eval₂_nat_cast {R : Type u} {S : Type v} [semiring R] [semiring S] (f : R →+* S) (x : S) (n : ℕ) : eval₂ f x ↑n = ↑n := sorry theorem eval₂_sum {R : Type u} {S : Type v} {T : Type w} [semiring R] [semiring S] (f : R →+* S) [semiring T] (p : polynomial T) (g : ℕ → T → polynomial R) (x : S) : eval₂ f x (finsupp.sum p g) = finsupp.sum p fun (n : ℕ) (a : T) => eval₂ f x (g n a) := sorry theorem eval₂_finset_sum {R : Type u} {S : Type v} {ι : Type y} [semiring R] [semiring S] (f : R →+* S) (s : finset ι) (g : ι → polynomial R) (x : S) : eval₂ f x (finset.sum s fun (i : ι) => g i) = finset.sum s fun (i : ι) => eval₂ f x (g i) := sorry theorem eval₂_mul_noncomm {R : Type u} {S : Type v} [semiring R] {p : polynomial R} {q : polynomial R} [semiring S] (f : R →+* S) (x : S) (hf : ∀ (k : ℕ), commute (coe_fn f (coeff q k)) x) : eval₂ f x (p * q) = eval₂ f x p * eval₂ f x q := sorry @[simp] theorem eval₂_mul_X {R : Type u} {S : Type v} [semiring R] {p : polynomial R} [semiring S] (f : R →+* S) (x : S) : eval₂ f x (p * X) = eval₂ f x p * x := sorry @[simp] theorem eval₂_X_mul {R : Type u} {S : Type v} [semiring R] {p : polynomial R} [semiring S] (f : R →+* S) (x : S) : eval₂ f x (X * p) = eval₂ f x p * x := eq.mpr (id (Eq._oldrec (Eq.refl (eval₂ f x (X * p) = eval₂ f x p * x)) X_mul)) (eq.mpr (id (Eq._oldrec (Eq.refl (eval₂ f x (p * X) = eval₂ f x p * x)) (eval₂_mul_X f x))) (Eq.refl (eval₂ f x p * x))) theorem eval₂_mul_C' {R : Type u} {S : Type v} {a : R} [semiring R] {p : polynomial R} [semiring S] (f : R →+* S) (x : S) (h : commute (coe_fn f a) x) : eval₂ f x (p * coe_fn C a) = eval₂ f x p * coe_fn f a := sorry theorem eval₂_list_prod_noncomm {R : Type u} {S : Type v} [semiring R] [semiring S] (f : R →+* S) (x : S) (ps : List (polynomial R)) (hf : ∀ (p : polynomial R), p ∈ ps → ∀ (k : ℕ), commute (coe_fn f (coeff p k)) x) : eval₂ f x (list.prod ps) = list.prod (list.map (eval₂ f x) ps) := sorry /-- `eval₂` as a `ring_hom` for noncommutative rings -/ def eval₂_ring_hom' {R : Type u} {S : Type v} [semiring R] [semiring S] (f : R →+* S) (x : S) (hf : ∀ (a : R), commute (coe_fn f a) x) : polynomial R →+* S := ring_hom.mk (eval₂ f x) (eval₂_one f x) sorry (eval₂_zero f x) sorry /-! We next prove that eval₂ is multiplicative as long as target ring is commutative (even if the source ring is not). -/ @[simp] theorem eval₂_mul {R : Type u} {S : Type v} [semiring R] {p : polynomial R} {q : polynomial R} [comm_semiring S] (f : R →+* S) (x : S) : eval₂ f x (p * q) = eval₂ f x p * eval₂ f x q := eval₂_mul_noncomm f x fun (k : ℕ) => commute.all (coe_fn f (coeff q k)) x theorem eval₂_mul_eq_zero_of_left {R : Type u} {S : Type v} [semiring R] {p : polynomial R} [comm_semiring S] (f : R →+* S) (x : S) (q : polynomial R) (hp : eval₂ f x p = 0) : eval₂ f x (p * q) = 0 := eq.mpr (id (Eq._oldrec (Eq.refl (eval₂ f x (p * q) = 0)) (eval₂_mul f x))) (mul_eq_zero_of_left hp (eval₂ f x q)) theorem eval₂_mul_eq_zero_of_right {R : Type u} {S : Type v} [semiring R] {q : polynomial R} [comm_semiring S] (f : R →+* S) (x : S) (p : polynomial R) (hq : eval₂ f x q = 0) : eval₂ f x (p * q) = 0 := eq.mpr (id (Eq._oldrec (Eq.refl (eval₂ f x (p * q) = 0)) (eval₂_mul f x))) (mul_eq_zero_of_right (eval₂ f x p) hq) protected instance eval₂.is_semiring_hom {R : Type u} {S : Type v} [semiring R] [comm_semiring S] (f : R →+* S) (x : S) : is_semiring_hom (eval₂ f x) := is_semiring_hom.mk (eval₂_zero f x) (eval₂_one f x) (fun (_x _x_1 : polynomial R) => eval₂_add f x) fun (_x _x_1 : polynomial R) => eval₂_mul f x /-- `eval₂` as a `ring_hom` -/ def eval₂_ring_hom {R : Type u} {S : Type v} [semiring R] [comm_semiring S] (f : R →+* S) (x : S) : polynomial R →+* S := ring_hom.of (eval₂ f x) @[simp] theorem coe_eval₂_ring_hom {R : Type u} {S : Type v} [semiring R] [comm_semiring S] (f : R →+* S) (x : S) : ⇑(eval₂_ring_hom f x) = eval₂ f x := rfl theorem eval₂_pow {R : Type u} {S : Type v} [semiring R] {p : polynomial R} [comm_semiring S] (f : R →+* S) (x : S) (n : ℕ) : eval₂ f x (p ^ n) = eval₂ f x p ^ n := ring_hom.map_pow (eval₂_ring_hom f x) p n theorem eval₂_eq_sum_range {R : Type u} {S : Type v} [semiring R] {p : polynomial R} [comm_semiring S] (f : R →+* S) (x : S) : eval₂ f x p = finset.sum (finset.range (nat_degree p + 1)) fun (i : ℕ) => coe_fn f (coeff p i) * x ^ i := sorry theorem eval₂_eq_sum_range' {R : Type u} {S : Type v} [semiring R] [comm_semiring S] (f : R →+* S) {p : polynomial R} {n : ℕ} (hn : nat_degree p < n) (x : S) : eval₂ f x p = finset.sum (finset.range n) fun (i : ℕ) => coe_fn f (coeff p i) * x ^ i := sorry /-- `eval x p` is the evaluation of the polynomial `p` at `x` -/ def eval {R : Type u} [semiring R] : R → polynomial R → R := eval₂ (ring_hom.id R) theorem eval_eq_sum {R : Type u} [semiring R] {p : polynomial R} {x : R} : eval x p = finsupp.sum p fun (e : ℕ) (a : R) => a * x ^ e := rfl @[simp] theorem eval_C {R : Type u} {a : R} [semiring R] {x : R} : eval x (coe_fn C a) = a := eval₂_C (ring_hom.id R) x @[simp] theorem eval_nat_cast {R : Type u} [semiring R] {x : R} {n : ℕ} : eval x ↑n = ↑n := sorry @[simp] theorem eval_X {R : Type u} [semiring R] {x : R} : eval x X = x := eval₂_X (ring_hom.id R) x @[simp] theorem eval_monomial {R : Type u} [semiring R] {x : R} {n : ℕ} {a : R} : eval x (coe_fn (monomial n) a) = a * x ^ n := eval₂_monomial (ring_hom.id R) x @[simp] theorem eval_zero {R : Type u} [semiring R] {x : R} : eval x 0 = 0 := eval₂_zero (ring_hom.id R) x @[simp] theorem eval_add {R : Type u} [semiring R] {p : polynomial R} {q : polynomial R} {x : R} : eval x (p + q) = eval x p + eval x q := eval₂_add (ring_hom.id R) x @[simp] theorem eval_one {R : Type u} [semiring R] {x : R} : eval x 1 = 1 := eval₂_one (ring_hom.id R) x @[simp] theorem eval_bit0 {R : Type u} [semiring R] {p : polynomial R} {x : R} : eval x (bit0 p) = bit0 (eval x p) := eval₂_bit0 (ring_hom.id R) x @[simp] theorem eval_bit1 {R : Type u} [semiring R] {p : polynomial R} {x : R} : eval x (bit1 p) = bit1 (eval x p) := eval₂_bit1 (ring_hom.id R) x @[simp] theorem eval_smul {R : Type u} [semiring R] (p : polynomial R) (x : R) {s : R} : eval x (s • p) = s • eval x p := eval₂_smul (ring_hom.id R) p x theorem eval_sum {R : Type u} [semiring R] (p : polynomial R) (f : ℕ → R → polynomial R) (x : R) : eval x (finsupp.sum p f) = finsupp.sum p fun (n : ℕ) (a : R) => eval x (f n a) := eval₂_sum (ring_hom.id R) p f x theorem eval_finset_sum {R : Type u} {ι : Type y} [semiring R] (s : finset ι) (g : ι → polynomial R) (x : R) : eval x (finset.sum s fun (i : ι) => g i) = finset.sum s fun (i : ι) => eval x (g i) := eval₂_finset_sum (ring_hom.id R) s (fun (i : ι) => g i) x /-- `is_root p x` implies `x` is a root of `p`. The evaluation of `p` at `x` is zero -/ def is_root {R : Type u} [semiring R] (p : polynomial R) (a : R) := eval a p = 0 protected instance is_root.decidable {R : Type u} {a : R} [semiring R] {p : polynomial R} [DecidableEq R] : Decidable (is_root p a) := eq.mpr sorry (_inst_2 (eval a p) 0) @[simp] theorem is_root.def {R : Type u} {a : R} [semiring R] {p : polynomial R} : is_root p a ↔ eval a p = 0 := iff.rfl theorem coeff_zero_eq_eval_zero {R : Type u} [semiring R] (p : polynomial R) : coeff p 0 = eval 0 p := sorry theorem zero_is_root_of_coeff_zero_eq_zero {R : Type u} [semiring R] {p : polynomial R} (hp : coeff p 0 = 0) : is_root p 0 := eq.mp (Eq._oldrec (Eq.refl (coeff p 0 = 0)) (coeff_zero_eq_eval_zero p)) hp /-- The composition of polynomials as a polynomial. -/ def comp {R : Type u} [semiring R] (p : polynomial R) (q : polynomial R) : polynomial R := eval₂ C q p theorem comp_eq_sum_left {R : Type u} [semiring R] {p : polynomial R} {q : polynomial R} : comp p q = finsupp.sum p fun (e : ℕ) (a : R) => coe_fn C a * q ^ e := rfl @[simp] theorem comp_X {R : Type u} [semiring R] {p : polynomial R} : comp p X = p := sorry @[simp] theorem X_comp {R : Type u} [semiring R] {p : polynomial R} : comp X p = p := eval₂_X C p @[simp] theorem comp_C {R : Type u} {a : R} [semiring R] {p : polynomial R} : comp p (coe_fn C a) = coe_fn C (eval a p) := sorry @[simp] theorem C_comp {R : Type u} {a : R} [semiring R] {p : polynomial R} : comp (coe_fn C a) p = coe_fn C a := eval₂_C C p @[simp] theorem comp_zero {R : Type u} [semiring R] {p : polynomial R} : comp p 0 = coe_fn C (eval 0 p) := eq.mpr (id (Eq._oldrec (Eq.refl (comp p 0 = coe_fn C (eval 0 p))) (Eq.symm C_0))) (eq.mpr (id (Eq._oldrec (Eq.refl (comp p (coe_fn C 0) = coe_fn C (eval 0 p))) comp_C)) (Eq.refl (coe_fn C (eval 0 p)))) @[simp] theorem zero_comp {R : Type u} [semiring R] {p : polynomial R} : comp 0 p = 0 := eq.mpr (id (Eq._oldrec (Eq.refl (comp 0 p = 0)) (Eq.symm C_0))) (eq.mpr (id (Eq._oldrec (Eq.refl (comp (coe_fn C 0) p = coe_fn C 0)) C_comp)) (Eq.refl (coe_fn C 0))) @[simp] theorem comp_one {R : Type u} [semiring R] {p : polynomial R} : comp p 1 = coe_fn C (eval 1 p) := eq.mpr (id (Eq._oldrec (Eq.refl (comp p 1 = coe_fn C (eval 1 p))) (Eq.symm C_1))) (eq.mpr (id (Eq._oldrec (Eq.refl (comp p (coe_fn C 1) = coe_fn C (eval 1 p))) comp_C)) (Eq.refl (coe_fn C (eval 1 p)))) @[simp] theorem one_comp {R : Type u} [semiring R] {p : polynomial R} : comp 1 p = 1 := eq.mpr (id (Eq._oldrec (Eq.refl (comp 1 p = 1)) (Eq.symm C_1))) (eq.mpr (id (Eq._oldrec (Eq.refl (comp (coe_fn C 1) p = coe_fn C 1)) C_comp)) (Eq.refl (coe_fn C 1))) @[simp] theorem add_comp {R : Type u} [semiring R] {p : polynomial R} {q : polynomial R} {r : polynomial R} : comp (p + q) r = comp p r + comp q r := eval₂_add C r @[simp] theorem mul_comp {R : Type u_1} [comm_semiring R] (p : polynomial R) (q : polynomial R) (r : polynomial R) : comp (p * q) r = comp p r * comp q r := eval₂_mul C r @[simp] theorem bit0_comp {R : Type u} [semiring R] {p : polynomial R} {q : polynomial R} : comp (bit0 p) q = bit0 (comp p q) := sorry @[simp] theorem bit1_comp {R : Type u} [semiring R] {p : polynomial R} {q : polynomial R} : comp (bit1 p) q = bit1 (comp p q) := sorry theorem comp_assoc {R : Type u_1} [comm_semiring R] (φ : polynomial R) (ψ : polynomial R) (χ : polynomial R) : comp (comp φ ψ) χ = comp φ (comp ψ χ) := sorry /-- `map f p` maps a polynomial `p` across a ring hom `f` -/ def map {R : Type u} {S : Type v} [semiring R] [semiring S] (f : R →+* S) : polynomial R → polynomial S := eval₂ (ring_hom.comp C f) X protected instance is_semiring_hom_C_f {R : Type u} {S : Type v} [semiring R] [semiring S] (f : R →+* S) : is_semiring_hom (⇑C ∘ ⇑f) := is_semiring_hom.comp ⇑f ⇑C @[simp] theorem map_C {R : Type u} {S : Type v} {a : R} [semiring R] [semiring S] (f : R →+* S) : map f (coe_fn C a) = coe_fn C (coe_fn f a) := eval₂_C (ring_hom.comp C f) X @[simp] theorem map_X {R : Type u} {S : Type v} [semiring R] [semiring S] (f : R →+* S) : map f X = X := eval₂_X (ring_hom.comp C f) X @[simp] theorem map_monomial {R : Type u} {S : Type v} [semiring R] [semiring S] (f : R →+* S) {n : ℕ} {a : R} : map f (coe_fn (monomial n) a) = coe_fn (monomial n) (coe_fn f a) := sorry @[simp] theorem map_zero {R : Type u} {S : Type v} [semiring R] [semiring S] (f : R →+* S) : map f 0 = 0 := eval₂_zero (ring_hom.comp C f) X @[simp] theorem map_add {R : Type u} {S : Type v} [semiring R] {p : polynomial R} {q : polynomial R} [semiring S] (f : R →+* S) : map f (p + q) = map f p + map f q := eval₂_add (ring_hom.comp C f) X @[simp] theorem map_one {R : Type u} {S : Type v} [semiring R] [semiring S] (f : R →+* S) : map f 1 = 1 := eval₂_one (ring_hom.comp C f) X @[simp] theorem map_nat_cast {R : Type u} {S : Type v} [semiring R] [semiring S] (f : R →+* S) (n : ℕ) : map f ↑n = ↑n := sorry @[simp] theorem coeff_map {R : Type u} {S : Type v} [semiring R] {p : polynomial R} [semiring S] (f : R →+* S) (n : ℕ) : coeff (map f p) n = coe_fn f (coeff p n) := sorry theorem map_map {R : Type u} {S : Type v} {T : Type w} [semiring R] [semiring S] (f : R →+* S) [semiring T] (g : S →+* T) (p : polynomial R) : map g (map f p) = map (ring_hom.comp g f) p := sorry @[simp] theorem map_id {R : Type u} [semiring R] {p : polynomial R} : map (ring_hom.id R) p = p := sorry theorem eval₂_eq_eval_map {R : Type u} {S : Type v} [semiring R] {p : polynomial R} [semiring S] (f : R →+* S) {x : S} : eval₂ f x p = eval x (map f p) := sorry theorem map_injective {R : Type u} {S : Type v} [semiring R] [semiring S] (f : R →+* S) (hf : function.injective ⇑f) : function.injective (map f) := sorry theorem map_surjective {R : Type u} {S : Type v} [semiring R] [semiring S] (f : R →+* S) (hf : function.surjective ⇑f) : function.surjective (map f) := sorry theorem map_monic_eq_zero_iff {R : Type u} {S : Type v} [semiring R] {p : polynomial R} [semiring S] {f : R →+* S} (hp : monic p) : map f p = 0 ↔ ∀ (x : R), coe_fn f x = 0 := sorry theorem map_monic_ne_zero {R : Type u} {S : Type v} [semiring R] {p : polynomial R} [semiring S] {f : R →+* S} (hp : monic p) [nontrivial S] : map f p ≠ 0 := fun (h : map f p = 0) => ring_hom.map_one_ne_zero f (iff.mp (map_monic_eq_zero_iff hp) h 1) -- If the rings were commutative, we could prove this just using `eval₂_mul`. -- TODO this proof is just a hack job on the proof of `eval₂_mul`, -- using that `X` is central. It should probably be golfed! @[simp] theorem map_mul {R : Type u} {S : Type v} [semiring R] {p : polynomial R} {q : polynomial R} [semiring S] (f : R →+* S) : map f (p * q) = map f p * map f q := sorry protected instance map.is_semiring_hom {R : Type u} {S : Type v} [semiring R] [semiring S] (f : R →+* S) : is_semiring_hom (map f) := is_semiring_hom.mk (eval₂_zero (ring_hom.comp C f) X) (eval₂_one (ring_hom.comp C f) X) (fun (_x _x_1 : polynomial R) => eval₂_add (ring_hom.comp C f) X) fun (_x _x_1 : polynomial R) => map_mul f /-- `polynomial.map` as a `ring_hom` -/ def map_ring_hom {R : Type u} {S : Type v} [semiring R] [semiring S] (f : R →+* S) : polynomial R →+* polynomial S := ring_hom.mk (map f) sorry sorry sorry sorry @[simp] theorem coe_map_ring_hom {R : Type u} {S : Type v} [semiring R] [semiring S] (f : R →+* S) : ⇑(map_ring_hom f) = map f := rfl theorem map_list_prod {R : Type u} {S : Type v} [semiring R] [semiring S] (f : R →+* S) (L : List (polynomial R)) : map f (list.prod L) = list.prod (list.map (map f) L) := Eq.symm (list.prod_hom L (monoid_hom.of (map f))) @[simp] theorem map_pow {R : Type u} {S : Type v} [semiring R] {p : polynomial R} [semiring S] (f : R →+* S) (n : ℕ) : map f (p ^ n) = map f p ^ n := is_monoid_hom.map_pow (map f) p n theorem mem_map_range {R : Type u} {S : Type v} [semiring R] [semiring S] (f : R →+* S) {p : polynomial S} : p ∈ set.range (map f) ↔ ∀ (n : ℕ), coeff p n ∈ set.range ⇑f := sorry theorem eval₂_map {R : Type u} {S : Type v} {T : Type w} [semiring R] {p : polynomial R} [semiring S] (f : R →+* S) [semiring T] (g : S →+* T) (x : T) : eval₂ g x (map f p) = eval₂ (ring_hom.comp g f) x p := sorry theorem eval_map {R : Type u} {S : Type v} [semiring R] {p : polynomial R} [semiring S] (f : R →+* S) (x : S) : eval x (map f p) = eval₂ f x p := eval₂_map f (ring_hom.id S) x theorem map_sum {R : Type u} {S : Type v} [semiring R] [semiring S] (f : R →+* S) {ι : Type u_1} (g : ι → polynomial R) (s : finset ι) : map f (finset.sum s fun (i : ι) => g i) = finset.sum s fun (i : ι) => map f (g i) := Eq.symm (finset.sum_hom s (map f)) /-! After having set up the basic theory of `eval₂`, `eval`, `comp`, and `map`, we make `eval₂` irreducible. Perhaps we can make the others irreducible too? -/ -- TODO: Here we need commutativity in both `S` and `T`? theorem hom_eval₂ {R : Type u} {S : Type v} {T : Type w} [semiring R] (p : polynomial R) [comm_semiring S] [comm_semiring T] (f : R →+* S) (g : S →+* T) (x : S) : coe_fn g (eval₂ f x p) = eval₂ (ring_hom.comp g f) (coe_fn g x) p := sorry @[simp] theorem eval_mul {R : Type u} [comm_semiring R] {p : polynomial R} {q : polynomial R} {x : R} : eval x (p * q) = eval x p * eval x q := eval₂_mul (ring_hom.id R) x protected instance eval.is_semiring_hom {R : Type u} [comm_semiring R] {x : R} : is_semiring_hom (eval x) := eval₂.is_semiring_hom (ring_hom.id R) x @[simp] theorem eval_pow {R : Type u} [comm_semiring R] {p : polynomial R} {x : R} (n : ℕ) : eval x (p ^ n) = eval x p ^ n := eval₂_pow (ring_hom.id R) x n theorem eval₂_hom {R : Type u} {S : Type v} [comm_semiring R] {p : polynomial R} [comm_semiring S] (f : R →+* S) (x : R) : eval₂ f (coe_fn f x) p = coe_fn f (eval x p) := ring_hom.comp_id f ▸ Eq.symm (hom_eval₂ p (ring_hom.id R) f x) theorem root_mul_left_of_is_root {R : Type u} {a : R} [comm_semiring R] (p : polynomial R) {q : polynomial R} : is_root q a → is_root (p * q) a := sorry theorem root_mul_right_of_is_root {R : Type u} {a : R} [comm_semiring R] {p : polynomial R} (q : polynomial R) : is_root p a → is_root (p * q) a := sorry /-- Polynomial evaluation commutes with finset.prod -/ theorem eval_prod {R : Type u} [comm_semiring R] {ι : Type u_1} (s : finset ι) (p : ι → polynomial R) (x : R) : eval x (finset.prod s fun (j : ι) => p j) = finset.prod s fun (j : ι) => eval x (p j) := sorry theorem map_multiset_prod {R : Type u} {S : Type v} [comm_semiring R] [comm_semiring S] (f : R →+* S) (m : multiset (polynomial R)) : map f (multiset.prod m) = multiset.prod (multiset.map (map f) m) := Eq.symm (multiset.prod_hom m (monoid_hom.of (map f))) theorem map_prod {R : Type u} {S : Type v} [comm_semiring R] [comm_semiring S] (f : R →+* S) {ι : Type u_1} (g : ι → polynomial R) (s : finset ι) : map f (finset.prod s fun (i : ι) => g i) = finset.prod s fun (i : ι) => map f (g i) := Eq.symm (finset.prod_hom s (map f)) theorem support_map_subset {R : Type u} {S : Type v} [comm_semiring R] [comm_semiring S] (f : R →+* S) (p : polynomial R) : finsupp.support (map f p) ⊆ finsupp.support p := sorry theorem map_comp {R : Type u} {S : Type v} [comm_semiring R] [comm_semiring S] (f : R →+* S) (p : polynomial R) (q : polynomial R) : map f (comp p q) = comp (map f p) (map f q) := sorry -- @[simp] -- lemma C_eq_int_cast (n : ℤ) : C ↑n = (n : polynomial R) := -- (C : R →+* _).map_int_cast n theorem C_neg {R : Type u} {a : R} [ring R] : coe_fn C (-a) = -coe_fn C a := ring_hom.map_neg C a theorem C_sub {R : Type u} {a : R} {b : R} [ring R] : coe_fn C (a - b) = coe_fn C a - coe_fn C b := ring_hom.map_sub C a b protected instance map.is_ring_hom {R : Type u} [ring R] {S : Type u_1} [ring S] (f : R →+* S) : is_ring_hom (map f) := is_ring_hom.of_semiring (map f) @[simp] theorem map_sub {R : Type u} [ring R] {p : polynomial R} {q : polynomial R} {S : Type u_1} [ring S] (f : R →+* S) : map f (p - q) = map f p - map f q := is_ring_hom.map_sub (map f) @[simp] theorem map_neg {R : Type u} [ring R] {p : polynomial R} {S : Type u_1} [ring S] (f : R →+* S) : map f (-p) = -map f p := is_ring_hom.map_neg (map f) @[simp] theorem map_int_cast {R : Type u} [ring R] {S : Type u_1} [ring S] (f : R →+* S) (n : ℤ) : map f ↑n = ↑n := ring_hom.map_int_cast (ring_hom.of (map f)) n @[simp] theorem eval_int_cast {R : Type u} [ring R] {n : ℤ} {x : R} : eval x ↑n = ↑n := sorry @[simp] theorem eval₂_neg {R : Type u} [ring R] {p : polynomial R} {S : Type u_1} [ring S] (f : R →+* S) {x : S} : eval₂ f x (-p) = -eval₂ f x p := sorry @[simp] theorem eval₂_sub {R : Type u} [ring R] {p : polynomial R} {q : polynomial R} {S : Type u_1} [ring S] (f : R →+* S) {x : S} : eval₂ f x (p - q) = eval₂ f x p - eval₂ f x q := sorry @[simp] theorem eval_neg {R : Type u} [ring R] (p : polynomial R) (x : R) : eval x (-p) = -eval x p := eval₂_neg (ring_hom.id R) @[simp] theorem eval_sub {R : Type u} [ring R] (p : polynomial R) (q : polynomial R) (x : R) : eval x (p - q) = eval x p - eval x q := eval₂_sub (ring_hom.id R) theorem root_X_sub_C {R : Type u} {a : R} {b : R} [ring R] : is_root (X - coe_fn C a) b ↔ a = b := sorry @[simp] theorem neg_comp {R : Type u} [ring R] {p : polynomial R} {q : polynomial R} : comp (-p) q = -comp p q := eval₂_neg C @[simp] theorem sub_comp {R : Type u} [ring R] {p : polynomial R} {q : polynomial R} {r : polynomial R} : comp (p - q) r = comp p r - comp q r := eval₂_sub C protected instance eval₂.is_ring_hom {R : Type u} [comm_ring R] {S : Type u_1} [comm_ring S] (f : R →+* S) {x : S} : is_ring_hom (eval₂ f x) := is_ring_hom.of_semiring (eval₂ f x) protected instance eval.is_ring_hom {R : Type u} [comm_ring R] {x : R} : is_ring_hom (eval x) := eval₂.is_ring_hom (ring_hom.id R)
2a0ab520a5100d9dffd6701500f6df5f71ff4063
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/data/nat/totient.lean
00895c070e20effc3792042d3b435de71e93e0cc
[ "Apache-2.0" ]
permissive
fpvandoorn/mathlib
b21ab4068db079cbb8590b58fda9cc4bc1f35df4
b3433a51ea8bc07c4159c1073838fc0ee9b8f227
refs/heads/master
1,624,791,089,608
1,556,715,231,000
1,556,715,231,000
165,722,980
5
0
Apache-2.0
1,552,657,455,000
1,547,494,646,000
Lean
UTF-8
Lean
false
false
3,633
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import algebra.big_operators data.nat.gcd open finset namespace nat def totient (n : ℕ) : ℕ := ((range n).filter (nat.coprime n)).card local notation `φ` := totient lemma totient_le (n : ℕ) : φ n ≤ n := calc totient n ≤ (range n).card : card_le_of_subset (filter_subset _) ... = n : card_range _ lemma totient_pos : ∀ {n : ℕ}, 0 < n → 0 < φ n | 0 := dec_trivial | 1 := dec_trivial | (n+2) := λ h, card_pos.2 (mt eq_empty_iff_forall_not_mem.1 (not_forall_of_exists_not ⟨1, not_not.2 $ mem_filter.2 ⟨mem_range.2 dec_trivial, by simp [coprime]⟩⟩)) lemma sum_totient (n : ℕ) : ((range n.succ).filter (∣ n)).sum φ = n := if hn0 : n = 0 then by rw hn0; refl else calc ((range n.succ).filter (∣ n)).sum φ = ((range n.succ).filter (∣ n)).sum (λ d, ((range (n / d)).filter (λ m, gcd (n / d) m = 1)).card) : eq.symm $ sum_bij (λ d _, n / d) (λ d hd, mem_filter.2 ⟨mem_range.2 $ lt_succ_of_le $ nat.div_le_self _ _, by conv {to_rhs, rw ← nat.mul_div_cancel' (mem_filter.1 hd).2}; simp⟩) (λ _ _, rfl) (λ a b ha hb h, have ha : a * (n / a) = n, from nat.mul_div_cancel' (mem_filter.1 ha).2, have (n / a) > 0, from nat.pos_of_ne_zero (λ h, by simp [*, lt_irrefl] at *), by rw [← nat.mul_right_inj this, ha, h, nat.mul_div_cancel' (mem_filter.1 hb).2]) (λ b hb, have hb : b < n.succ ∧ b ∣ n, by simpa [-range_succ] using hb, have hbn : (n / b) ∣ n, from ⟨b, by rw nat.div_mul_cancel hb.2⟩, have hnb0 : (n / b) ≠ 0, from λ h, by simpa [h, ne.symm hn0] using nat.div_mul_cancel hbn, ⟨n / b, mem_filter.2 ⟨mem_range.2 $ lt_succ_of_le $ nat.div_le_self _ _, hbn⟩, by rw [← nat.mul_right_inj (nat.pos_of_ne_zero hnb0), nat.mul_div_cancel' hb.2, nat.div_mul_cancel hbn]⟩) ... = ((range n.succ).filter (∣ n)).sum (λ d, ((range n).filter (λ m, gcd n m = d)).card) : sum_congr rfl (λ d hd, have hd : d ∣ n, from (mem_filter.1 hd).2, have hd0 : 0 < d, from nat.pos_of_ne_zero (λ h, hn0 (eq_zero_of_zero_dvd $ h ▸ hd)), card_congr (λ m hm, d * m) (λ m hm, have hm : m < n / d ∧ gcd (n / d) m = 1, by simpa using hm, mem_filter.2 ⟨mem_range.2 $ nat.mul_div_cancel' hd ▸ (mul_lt_mul_left hd0).2 hm.1, by rw [← nat.mul_div_cancel' hd, gcd_mul_left, hm.2, mul_one]⟩) (λ a b ha hb h, (nat.mul_left_inj hd0).1 h) (λ b hb, have hb : b < n ∧ gcd n b = d, by simpa using hb, ⟨b / d, mem_filter.2 ⟨mem_range.2 ((mul_lt_mul_left (show 0 < d, from hb.2 ▸ hb.2.symm ▸ hd0)).1 (by rw [← hb.2, nat.mul_div_cancel' (gcd_dvd_left _ _), nat.mul_div_cancel' (gcd_dvd_right _ _)]; exact hb.1)), hb.2 ▸ coprime_div_gcd_div_gcd (hb.2.symm ▸ hd0)⟩, hb.2 ▸ nat.mul_div_cancel' (gcd_dvd_right _ _)⟩)) ... = ((filter (∣ n) (range n.succ)).bind (λ d, (range n).filter (λ m, gcd n m = d))).card : (card_bind (by simp [finset.ext]; cc)).symm ... = (range n).card : congr_arg card (finset.ext.2 (λ m, ⟨by finish, λ hm, have h : m < n, from mem_range.1 hm, mem_bind.2 ⟨gcd n m, mem_filter.2 ⟨mem_range.2 (lt_succ_of_le (le_of_dvd (lt_of_le_of_lt (nat.zero_le _) h) (gcd_dvd_left _ _))), gcd_dvd_left _ _⟩, mem_filter.2 ⟨hm, rfl⟩⟩⟩)) ... = n : card_range _ end nat
923feb75bbe8a574fa5da1a2b8f234f4b125161d
abd85493667895c57a7507870867b28124b3998f
/src/linear_algebra/bilinear_form.lean
bc7f3b3e3e7b0a83d48154ad3ab7d80f0cd89361
[ "Apache-2.0" ]
permissive
pechersky/mathlib
d56eef16bddb0bfc8bc552b05b7270aff5944393
f1df14c2214ee114c9738e733efd5de174deb95d
refs/heads/master
1,666,714,392,571
1,591,747,567,000
1,591,747,567,000
270,557,274
0
0
Apache-2.0
1,591,597,975,000
1,591,597,974,000
null
UTF-8
Lean
false
false
25,557
lean
/- Copyright (c) 2018 Andreas Swerdlow. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Andreas Swerdlow -/ import linear_algebra.matrix import linear_algebra.tensor_product /-! # Bilinear form This file defines a bilinear form over a module. Basic ideas such as orthogonality are also introduced, as well as reflexivive, symmetric and alternating bilinear forms. Adjoints of linear maps with respect to a bilinear form are also introduced. A bilinear form on an R-module M, is a function from M x M to R, that is linear in both arguments ## Notations Given any term B of type bilin_form, due to a coercion, can use the notation B x y to refer to the function field, ie. B x y = B.bilin x y. ## References * <https://en.wikipedia.org/wiki/Bilinear_form> ## Tags Bilinear form, -/ universes u v w /-- A bilinear form over a module -/ structure bilin_form (R : Type u) (M : Type v) [ring R] [add_comm_group M] [module R M] := (bilin : M → M → R) (bilin_add_left : ∀ (x y z : M), bilin (x + y) z = bilin x z + bilin y z) (bilin_smul_left : ∀ (a : R) (x y : M), bilin (a • x) y = a * (bilin x y)) (bilin_add_right : ∀ (x y z : M), bilin x (y + z) = bilin x y + bilin x z) (bilin_smul_right : ∀ (a : R) (x y : M), bilin x (a • y) = a * (bilin x y)) /-- A map with two arguments that is linear in both is a bilinear form -/ def linear_map.to_bilin {R : Type u} {M : Type v} [comm_ring R] [add_comm_group M] [module R M] (f : M →ₗ[R] M →ₗ[R] R) : bilin_form R M := { bilin := λ x y, f x y, bilin_add_left := λ x y z, (linear_map.map_add f x y).symm ▸ linear_map.add_apply (f x) (f y) z, bilin_smul_left := λ a x y, by {rw linear_map.map_smul, rw linear_map.smul_apply, rw smul_eq_mul}, bilin_add_right := λ x y z, linear_map.map_add (f x) y z, bilin_smul_right := λ a x y, linear_map.map_smul (f x) a y } namespace bilin_form variables {R : Type u} {M : Type v} [ring R] [add_comm_group M] [module R M] {B : bilin_form R M} instance : has_coe_to_fun (bilin_form R M) := ⟨_, λ B, B.bilin⟩ @[simp] lemma coe_fn_mk (f : M → M → R) (h₁ h₂ h₃ h₄) : (bilin_form.mk f h₁ h₂ h₃ h₄ : M → M → R) = f := rfl lemma coe_fn_congr : Π {x x' y y' : M}, x = x' → y = y' → B x y = B x' y' | _ _ _ _ rfl rfl := rfl lemma add_left (x y z : M) : B (x + y) z = B x z + B y z := bilin_add_left B x y z lemma smul_left (a : R) (x y : M) : B (a • x) y = a * (B x y) := bilin_smul_left B a x y lemma add_right (x y z : M) : B x (y + z) = B x y + B x z := bilin_add_right B x y z lemma smul_right (a : R) (x y : M) : B x (a • y) = a * (B x y) := bilin_smul_right B a x y lemma zero_left (x : M) : B 0 x = 0 := by {rw [←@zero_smul R _ _ _ _ (0 : M), smul_left, zero_mul]} lemma zero_right (x : M) : B x 0 = 0 := by rw [←@zero_smul _ _ _ _ _ (0 : M), smul_right, ring.zero_mul] lemma neg_left (x y : M) : B (-x) y = -(B x y) := by rw [←@neg_one_smul R _ _, smul_left, neg_one_mul] lemma neg_right (x y : M) : B x (-y) = -(B x y) := by rw [←@neg_one_smul R _ _, smul_right, neg_one_mul] lemma sub_left (x y z : M) : B (x - y) z = B x z - B y z := by rw [sub_eq_add_neg, add_left, neg_left]; refl lemma sub_right (x y z : M) : B x (y - z) = B x y - B x z := by rw [sub_eq_add_neg, add_right, neg_right]; refl variable {D : bilin_form R M} @[ext] lemma ext (H : ∀ (x y : M), B x y = D x y) : B = D := by {cases B, cases D, congr, funext, exact H _ _} instance : add_comm_group (bilin_form R M) := { add := λ B D, { bilin := λ x y, B x y + D x y, bilin_add_left := λ x y z, by {rw add_left, rw add_left, ac_refl}, bilin_smul_left := λ a x y, by {rw [smul_left, smul_left, mul_add]}, bilin_add_right := λ x y z, by {rw add_right, rw add_right, ac_refl}, bilin_smul_right := λ a x y, by {rw [smul_right, smul_right, mul_add]} }, add_assoc := by {intros, ext, unfold coe_fn has_coe_to_fun.coe bilin coe_fn has_coe_to_fun.coe bilin, rw add_assoc}, zero := { bilin := λ x y, 0, bilin_add_left := λ x y z, (add_zero 0).symm, bilin_smul_left := λ a x y, (mul_zero a).symm, bilin_add_right := λ x y z, (zero_add 0).symm, bilin_smul_right := λ a x y, (mul_zero a).symm }, zero_add := by {intros, ext, unfold coe_fn has_coe_to_fun.coe bilin, rw zero_add}, add_zero := by {intros, ext, unfold coe_fn has_coe_to_fun.coe bilin, rw add_zero}, neg := λ B, { bilin := λ x y, - (B.1 x y), bilin_add_left := λ x y z, by rw [bilin_add_left, neg_add], bilin_smul_left := λ a x y, by rw [bilin_smul_left, mul_neg_eq_neg_mul_symm], bilin_add_right := λ x y z, by rw [bilin_add_right, neg_add], bilin_smul_right := λ a x y, by rw [bilin_smul_right, mul_neg_eq_neg_mul_symm] }, add_left_neg := by {intros, ext, unfold coe_fn has_coe_to_fun.coe bilin, rw neg_add_self}, add_comm := by {intros, ext, unfold coe_fn has_coe_to_fun.coe bilin, rw add_comm} } lemma add_apply (x y : M) : (B + D) x y = B x y + D x y := rfl lemma neg_apply (x y : M) : (-B) x y = -(B x y) := rfl instance : inhabited (bilin_form R M) := ⟨0⟩ section variables {R₂ : Type*} [comm_ring R₂] [module R₂ M] (F : bilin_form R₂ M) (f : M → M) instance to_module : module R₂ (bilin_form R₂ M) := { smul := λ c B, { bilin := λ x y, c * B x y, bilin_add_left := λ x y z, by {unfold coe_fn has_coe_to_fun.coe bilin, rw [bilin_add_left, left_distrib]}, bilin_smul_left := λ a x y, by {unfold coe_fn has_coe_to_fun.coe bilin, rw [bilin_smul_left, ←mul_assoc, mul_comm c, mul_assoc]}, bilin_add_right := λ x y z, by {unfold coe_fn has_coe_to_fun.coe bilin, rw [bilin_add_right, left_distrib]}, bilin_smul_right := λ a x y, by {unfold coe_fn has_coe_to_fun.coe bilin, rw [bilin_smul_right, ←mul_assoc, mul_comm c, mul_assoc]} }, smul_add := λ c B D, by {ext, unfold coe_fn has_coe_to_fun.coe bilin, rw left_distrib}, add_smul := λ c B D, by {ext, unfold coe_fn has_coe_to_fun.coe bilin, rw right_distrib}, mul_smul := λ a c D, by {ext, unfold coe_fn has_coe_to_fun.coe bilin, rw mul_assoc}, one_smul := λ B, by {ext, unfold coe_fn has_coe_to_fun.coe bilin, rw one_mul}, zero_smul := λ B, by {ext, unfold coe_fn has_coe_to_fun.coe bilin, rw zero_mul}, smul_zero := λ B, by {ext, unfold coe_fn has_coe_to_fun.coe bilin, rw mul_zero} } lemma smul_apply (a : R₂) (x y : M) : (a • F) x y = a • (F x y) := rfl /-- `B.to_linear_map` applies B on the left argument, then the right. -/ def to_linear_map : M →ₗ[R₂] M →ₗ[R₂] R₂ := linear_map.mk₂ R₂ F.1 (bilin_add_left F) (bilin_smul_left F) (bilin_add_right F) (bilin_smul_right F) /-- Bilinear forms are equivalent to maps with two arguments that is linear in both. -/ def bilin_linear_map_equiv : (bilin_form R₂ M) ≃ₗ[R₂] (M →ₗ[R₂] M →ₗ[R₂] R₂) := { to_fun := to_linear_map, add := λ B D, rfl, smul := λ a B, rfl, inv_fun := linear_map.to_bilin, left_inv := λ B, by {ext, refl}, right_inv := λ B, by {ext, refl} } @[norm_cast] lemma coe_fn_to_linear_map (x : M) : ⇑(F.to_linear_map x) = F x := rfl lemma map_sum_left {α} (B : bilin_form R₂ M) (t : finset α) (g : α → M) (w : M) : B (t.sum g) w = t.sum (λ i, B (g i) w) := show B.to_linear_map (t.sum g) w = t.sum (λ i, B (g i) w), by { rw [B.to_linear_map.map_sum, linear_map.coe_fn_sum, finset.sum_apply], refl } lemma map_sum_right {α} (B : bilin_form R₂ M) (t : finset α) (g : α → M) (v : M) : B v (t.sum g) = t.sum (λ i, B v (g i)) := (B.to_linear_map v).map_sum end section comp variables {N : Type w} [add_comm_group N] [module R N] /-- Apply a linear map on the left and right argument of a bilinear form. -/ def comp (B : bilin_form R N) (l r : M →ₗ[R] N) : bilin_form R M := { bilin := λ x y, B (l x) (r y), bilin_add_left := λ x y z, by simp [add_left], bilin_smul_left := λ x y z, by simp [smul_left], bilin_add_right := λ x y z, by simp [add_right], bilin_smul_right := λ x y z, by simp [smul_right] } /-- Apply a linear map to the left argument of a bilinear form. -/ def comp_left (B : bilin_form R M) (f : M →ₗ[R] M) : bilin_form R M := B.comp f linear_map.id /-- Apply a linear map to the right argument of a bilinear form. -/ def comp_right (B : bilin_form R M) (f : M →ₗ[R] M) : bilin_form R M := B.comp linear_map.id f @[simp] lemma comp_left_comp_right (B : bilin_form R M) (l r : M →ₗ[R] M) : (B.comp_left l).comp_right r = B.comp l r := rfl @[simp] lemma comp_right_comp_left (B : bilin_form R M) (l r : M →ₗ[R] M) : (B.comp_right r).comp_left l = B.comp l r := rfl @[simp] lemma comp_apply (B : bilin_form R N) (l r : M →ₗ[R] N) (v w) : B.comp l r v w = B (l v) (r w) := rfl @[simp] lemma comp_left_apply (B : bilin_form R M) (f : M →ₗ[R] M) (v w) : B.comp_left f v w = B (f v) w := rfl @[simp] lemma comp_right_apply (B : bilin_form R M) (f : M →ₗ[R] M) (v w) : B.comp_right f v w = B v (f w) := rfl end comp section lin_mul_lin variables {R₂ : Type*} [comm_ring R₂] [module R₂ M] {N : Type w} [add_comm_group N] [module R₂ N] /-- `lin_mul_lin f g` is the bilinear form mapping `x` and `y` to `f x * g y` -/ def lin_mul_lin (f g : M →ₗ[R₂] R₂) : bilin_form R₂ M := { bilin := λ x y, f x * g y, bilin_add_left := λ x y z, by simp [add_mul], bilin_smul_left := λ x y z, by simp [mul_assoc], bilin_add_right := λ x y z, by simp [mul_add], bilin_smul_right := λ x y z, by simp [mul_left_comm] } variables {f g : M →ₗ[R₂] R₂} @[simp] lemma lin_mul_lin_apply (x y) : lin_mul_lin f g x y = f x * g y := rfl @[simp] lemma lin_mul_lin_comp (l r : N →ₗ[R₂] M) : (lin_mul_lin f g).comp l r = lin_mul_lin (f.comp l) (g.comp r) := rfl @[simp] lemma lin_mul_lin_comp_left (l : M →ₗ[R₂] M) : (lin_mul_lin f g).comp_left l = lin_mul_lin (f.comp l) g := rfl @[simp] lemma lin_mul_lin_comp_right (r : M →ₗ[R₂] M) : (lin_mul_lin f g).comp_right r = lin_mul_lin f (g.comp r) := rfl end lin_mul_lin /-- The proposition that two elements of a bilinear form space are orthogonal -/ def is_ortho (B : bilin_form R M) (x y : M) : Prop := B x y = 0 lemma ortho_zero (x : M) : is_ortho B (0 : M) x := zero_left x section variables {R₃ : Type*} [domain R₃] [module R₃ M] {G : bilin_form R₃ M} theorem ortho_smul_left {x y : M} {a : R₃} (ha : a ≠ 0) : (is_ortho G x y) ↔ (is_ortho G (a • x) y) := begin dunfold is_ortho, split; intro H, { rw [smul_left, H, ring.mul_zero] }, { rw [smul_left, mul_eq_zero] at H, cases H, { trivial }, { exact H }} end theorem ortho_smul_right {x y : M} {a : R₃} (ha : a ≠ 0) : (is_ortho G x y) ↔ (is_ortho G x (a • y)) := begin dunfold is_ortho, split; intro H, { rw [smul_right, H, ring.mul_zero] }, { rw [smul_right, mul_eq_zero] at H, cases H, { trivial }, { exact H }} end end end bilin_form section matrix variables {R : Type u} [comm_ring R] variables {n o : Type w} [fintype n] [fintype o] open bilin_form finset matrix open_locale matrix /-- The linear map from `matrix n n R` to bilinear forms on `n → R`. -/ def matrix.to_bilin_formₗ : matrix n n R →ₗ[R] bilin_form R (n → R) := { to_fun := λ M, { bilin := λ v w, (row v ⬝ M ⬝ col w) ⟨⟩ ⟨⟩, bilin_add_left := λ x y z, by simp [matrix.add_mul], bilin_smul_left := λ a x y, by simp, bilin_add_right := λ x y z, by simp [matrix.mul_add], bilin_smul_right := λ a x y, by simp }, add := λ f g, by { ext, simp [add_apply, matrix.mul_add, matrix.add_mul] }, smul := λ f g, by { ext, simp [smul_apply] } } /-- The map from `matrix n n R` to bilinear forms on `n → R`. -/ def matrix.to_bilin_form : matrix n n R → bilin_form R (n → R) := matrix.to_bilin_formₗ.to_fun lemma matrix.to_bilin_form_apply (M : matrix n n R) (v w : n → R) : (M.to_bilin_form : (n → R) → (n → R) → R) v w = (row v ⬝ M ⬝ col w) ⟨⟩ ⟨⟩ := rfl variables [decidable_eq n] [decidable_eq o] /-- The linear map from bilinear forms on `n → R` to `matrix n n R`. -/ def bilin_form.to_matrixₗ : bilin_form R (n → R) →ₗ[R] matrix n n R := { to_fun := λ B i j, B (λ n, if n = i then 1 else 0) (λ n, if n = j then 1 else 0), add := λ f g, rfl, smul := λ f g, rfl } /-- The map from bilinear forms on `n → R` to `matrix n n R`. -/ def bilin_form.to_matrix : bilin_form R (n → R) → matrix n n R := bilin_form.to_matrixₗ.to_fun lemma bilin_form.to_matrix_apply (B : bilin_form R (n → R)) (i j : n) : B.to_matrix i j = B (λ n, if n = i then 1 else 0) (λ n, if n = j then 1 else 0) := rfl lemma bilin_form.to_matrix_smul (B : bilin_form R (n → R)) (x : R) : (x • B).to_matrix = x • B.to_matrix := by { ext, refl } open bilin_form lemma bilin_form.to_matrix_comp (B : bilin_form R (n → R)) (l r : (o → R) →ₗ[R] (n → R)) : (B.comp l r).to_matrix = l.to_matrixᵀ ⬝ B.to_matrix ⬝ r.to_matrix := begin ext i j, simp only [to_matrix_apply, comp_apply, mul_val, sum_mul], have sum_smul_eq : Π (f : (o → R) →ₗ[R] (n → R)) (i : o), f (λ n, ite (n = i) 1 0) = univ.sum (λ k, f.to_matrix k i • λ n, ite (n = k) (1 : R) 0), { intros f i, ext j, change f (λ n, ite (n = i) 1 0) j = univ.sum (λ k n, f.to_matrix k i * ite (n = k) (1 : R) 0) j, simp [linear_map.to_matrix, linear_map.to_matrixₗ, eq_comm] }, simp_rw [sum_smul_eq, map_sum_right, map_sum_left, smul_right, mul_comm, smul_left], refl end lemma bilin_form.to_matrix_comp_left (B : bilin_form R (n → R)) (f : (n → R) →ₗ[R] (n → R)) : (B.comp_left f).to_matrix = f.to_matrixᵀ ⬝ B.to_matrix := by simp [comp_left, bilin_form.to_matrix_comp] lemma bilin_form.to_matrix_comp_right (B : bilin_form R (n → R)) (f : (n → R) →ₗ[R] (n → R)) : (B.comp_right f).to_matrix = B.to_matrix ⬝ f.to_matrix := by simp [comp_right, bilin_form.to_matrix_comp] lemma bilin_form.mul_to_matrix_mul (B : bilin_form R (n → R)) (M : matrix o n R) (N : matrix n o R) : M ⬝ B.to_matrix ⬝ N = (B.comp (Mᵀ.to_lin) (N.to_lin)).to_matrix := by { ext, simp [B.to_matrix_comp (Mᵀ.to_lin) (N.to_lin), to_lin_to_matrix] } lemma bilin_form.mul_to_matrix (B : bilin_form R (n → R)) (M : matrix n n R) : M ⬝ B.to_matrix = (B.comp_left (Mᵀ.to_lin)).to_matrix := by { ext, simp [B.to_matrix_comp_left (Mᵀ.to_lin), to_lin_to_matrix] } lemma bilin_form.to_matrix_mul (B : bilin_form R (n → R)) (M : matrix n n R) : B.to_matrix ⬝ M = (B.comp_right (M.to_lin)).to_matrix := by { ext, simp [B.to_matrix_comp_right (M.to_lin), to_lin_to_matrix] } @[simp] lemma to_matrix_to_bilin_form (B : bilin_form R (n → R)) : B.to_matrix.to_bilin_form = B := begin ext, rw [matrix.to_bilin_form_apply, B.mul_to_matrix_mul, bilin_form.to_matrix_apply, comp_apply], { apply coe_fn_congr; ext; simp [mul_vec], }, { apply_instance, }, end @[simp] lemma to_bilin_form_to_matrix (M : matrix n n R) : M.to_bilin_form.to_matrix = M := by { ext, simp [bilin_form.to_matrix_apply, matrix.to_bilin_form_apply, mul_val], } /-- Bilinear forms are linearly equivalent to matrices. -/ def bilin_form_equiv_matrix : bilin_form R (n → R) ≃ₗ[R] matrix n n R := { inv_fun := matrix.to_bilin_form, left_inv := to_matrix_to_bilin_form, right_inv := to_bilin_form_to_matrix, ..bilin_form.to_matrixₗ } end matrix namespace refl_bilin_form open refl_bilin_form bilin_form variables {R : Type*} {M : Type*} [ring R] [add_comm_group M] [module R M] {B : bilin_form R M} /-- The proposition that a bilinear form is reflexive -/ def is_refl (B : bilin_form R M) : Prop := ∀ (x y : M), B x y = 0 → B y x = 0 variable (H : is_refl B) lemma eq_zero : ∀ {x y : M}, B x y = 0 → B y x = 0 := λ x y, H x y lemma ortho_sym {x y : M} : is_ortho B x y ↔ is_ortho B y x := ⟨eq_zero H, eq_zero H⟩ end refl_bilin_form namespace sym_bilin_form open sym_bilin_form bilin_form variables {R : Type*} {M : Type*} [ring R] [add_comm_group M] [module R M] {B : bilin_form R M} /-- The proposition that a bilinear form is symmetric -/ def is_sym (B : bilin_form R M) : Prop := ∀ (x y : M), B x y = B y x variable (H : is_sym B) lemma sym (x y : M) : B x y = B y x := H x y lemma is_refl : refl_bilin_form.is_refl B := λ x y H1, H x y ▸ H1 lemma ortho_sym {x y : M} : is_ortho B x y ↔ is_ortho B y x := refl_bilin_form.ortho_sym (is_refl H) end sym_bilin_form namespace alt_bilin_form open alt_bilin_form bilin_form variables {R : Type*} {M : Type*} [ring R] [add_comm_group M] [module R M] {B : bilin_form R M} /-- The proposition that a bilinear form is alternating -/ def is_alt (B : bilin_form R M) : Prop := ∀ (x : M), B x x = 0 variable (H : is_alt B) include H lemma self_eq_zero (x : M) : B x x = 0 := H x lemma neg (x y : M) : - B x y = B y x := begin have H1 : B (x + y) (x + y) = 0, { exact self_eq_zero H (x + y) }, rw [add_left, add_right, add_right, self_eq_zero H, self_eq_zero H, ring.zero_add, ring.add_zero, add_eq_zero_iff_neg_eq] at H1, exact H1, end end alt_bilin_form namespace bilin_form section linear_adjoints variables {R : Type u} [comm_ring R] variables {M : Type v} [add_comm_group M] [module R M] variables {M₂ : Type v} [add_comm_group M₂] [module R M₂] variables (B B' : bilin_form R M) (B₂ : bilin_form R M₂) variables (f f' : M →ₗ[R] M₂) (g g' : M₂ →ₗ[R] M) /-- Given a pair of modules equipped with bilinear forms, this is the condition for a pair of maps between them to be mutually adjoint. -/ def is_adjoint_pair := ∀ ⦃x y⦄, B₂ (f x) y = B x (g y) variables {B B' B₂ f f' g g'} lemma is_adjoint_pair.eq (h : is_adjoint_pair B B₂ f g) : ∀ {x y}, B₂ (f x) y = B x (g y) := h lemma is_adjoint_pair_iff_comp_left_eq_comp_right (f g : module.End R M) : is_adjoint_pair B B' f g ↔ B'.comp_left f = B.comp_right g := begin split; intros h, { ext x y, rw [comp_left_apply, comp_right_apply], apply h, }, { intros x y, rw [←comp_left_apply, ←comp_right_apply], rw h, }, end lemma is_adjoint_pair_zero : is_adjoint_pair B B₂ 0 0 := λ x y, by simp only [bilin_form.zero_left, bilin_form.zero_right, linear_map.zero_apply] lemma is_adjoint_pair_id : is_adjoint_pair B B 1 1 := λ x y, rfl lemma is_adjoint_pair.add (h : is_adjoint_pair B B₂ f g) (h' : is_adjoint_pair B B₂ f' g') : is_adjoint_pair B B₂ (f + f') (g + g') := λ x y, by rw [linear_map.add_apply, linear_map.add_apply, add_left, add_right, h, h'] lemma is_adjoint_pair.sub (h : is_adjoint_pair B B₂ f g) (h' : is_adjoint_pair B B₂ f' g') : is_adjoint_pair B B₂ (f - f') (g - g') := λ x y, by rw [linear_map.sub_apply, linear_map.sub_apply, sub_left, sub_right, h, h'] lemma is_adjoint_pair.smul (c : R) (h : is_adjoint_pair B B₂ f g) : is_adjoint_pair B B₂ (c • f) (c • g) := λ x y, by rw [linear_map.smul_apply, linear_map.smul_apply, smul_left, smul_right, h] lemma is_adjoint_pair.comp {M₃ : Type v} [add_comm_group M₃] [module R M₃] {B₃ : bilin_form R M₃} {f' : M₂ →ₗ[R] M₃} {g' : M₃ →ₗ[R] M₂} (h : is_adjoint_pair B B₂ f g) (h' : is_adjoint_pair B₂ B₃ f' g') : is_adjoint_pair B B₃ (f'.comp f) (g.comp g') := λ x y, by rw [linear_map.comp_apply, linear_map.comp_apply, h', h] lemma is_adjoint_pair.mul {f g f' g' : module.End R M} (h : is_adjoint_pair B B f g) (h' : is_adjoint_pair B B f' g') : is_adjoint_pair B B (f * f') (g' * g) := λ x y, by rw [linear_map.mul_app, linear_map.mul_app, h, h'] variables (B B' B₂) /-- The condition for an endomorphism to be "self-adjoint" with respect to a pair of bilinear forms on the underlying module. In the case that these two forms are identical, this is the usual concept of self adjointness. In the case that one of the forms is the negation of the other, this is the usual concept of skew adjointness. -/ def is_pair_self_adjoint (f : module.End R M) := is_adjoint_pair B B' f f /-- The set of pair-self-adjoint endomorphisms are a submodule of the type of all endomorphisms. -/ def is_pair_self_adjoint_submodule : submodule R (module.End R M) := { carrier := { f | is_pair_self_adjoint B B' f }, zero := is_adjoint_pair_zero, add := λ f g hf hg, hf.add hg, smul := λ c f h, h.smul c, } /-- An endomorphism of a module is self-adjoint with respect to a bilinear form if it serves as an adjoint for itself. -/ def is_self_adjoint (f : module.End R M) := is_adjoint_pair B B f f /-- An endomorphism of a module is skew-adjoint with respect to a bilinear form if its negation serves as an adjoint. -/ def is_skew_adjoint (f : module.End R M) := is_adjoint_pair B B f (-f) lemma is_skew_adjoint_iff_neg_self_adjoint (f : module.End R M) : B.is_skew_adjoint f ↔ is_adjoint_pair (-B) B f f := show (∀ x y, B (f x) y = B x ((-f) y)) ↔ ∀ x y, B (f x) y = (-B) x (f y), by simp only [linear_map.neg_apply, bilin_form.neg_apply, bilin_form.neg_right] /-- The set of self-adjoint endomorphisms of a module with bilinear form is a submodule. (In fact it is a Jordan subalgebra.) -/ def self_adjoint_submodule := is_pair_self_adjoint_submodule B B @[simp] lemma mem_self_adjoint_submodule (f : module.End R M) : f ∈ B.self_adjoint_submodule ↔ B.is_self_adjoint f := iff.rfl /-- The set of skew-adjoint endomorphisms of a module with bilinear form is a submodule. (In fact it is a Lie subalgebra.) -/ def skew_adjoint_submodule := is_pair_self_adjoint_submodule (-B) B @[simp] lemma mem_skew_adjoint_submodule (f : module.End R M) : f ∈ B.skew_adjoint_submodule ↔ B.is_skew_adjoint f := by { rw is_skew_adjoint_iff_neg_self_adjoint, exact iff.rfl, } end linear_adjoints end bilin_form section matrix_adjoints open_locale matrix variables {R : Type u} [comm_ring R] variables {n : Type w} [fintype n] variables (J J₂ A B : matrix n n R) /-- The condition for the square matrices `A`, `B` to be an adjoint pair with respect to the square matrices `J`, `J₂`. -/ def matrix.is_adjoint_pair := Aᵀ ⬝ J₂ = J ⬝ B /-- The condition for a square matrix `A` to be self-adjoint with respect to the square matrix `J`. -/ def matrix.is_self_adjoint := matrix.is_adjoint_pair J J A A /-- The condition for a square matrix `A` to be skew-adjoint with respect to the square matrix `J`. -/ def matrix.is_skew_adjoint := matrix.is_adjoint_pair J J A (-A) lemma matrix_is_adjoint_pair_bilin_form : matrix.is_adjoint_pair J J₂ A B ↔ bilin_form.is_adjoint_pair J.to_bilin_form J₂.to_bilin_form A.to_lin B.to_lin := begin classical, rw bilin_form.is_adjoint_pair_iff_comp_left_eq_comp_right, have h : ∀ (B B' : bilin_form R (n → R)), B = B' ↔ B.to_matrix = B'.to_matrix := λ B B', by { split; intros h, { rw h, }, { rw [←to_matrix_to_bilin_form B, h, to_matrix_to_bilin_form B'], }, }, rw [h, J₂.to_bilin_form.to_matrix_comp_left A.to_lin, J.to_bilin_form.to_matrix_comp_right B.to_lin, to_lin_to_matrix, to_lin_to_matrix, to_bilin_form_to_matrix, to_bilin_form_to_matrix], refl, end variables [decidable_eq n] /-- Given a pair of square matrices `J`, `J₂` defining bilinear forms on the free module, there is a natural embedding from the corresponding submodule of pair-self-adjoint endomorphisms into the module of matrices. -/ def pair_self_adjoint_matrices_linear_embedding : bilin_form.is_pair_self_adjoint_submodule J.to_bilin_form J₂.to_bilin_form →ₗ[R] matrix n n R := linear_equiv_matrix'.to_linear_map.comp (bilin_form.is_pair_self_adjoint_submodule J.to_bilin_form J₂.to_bilin_form).subtype lemma pair_self_adjoint_matrices_linear_embedding_apply (f : bilin_form.is_pair_self_adjoint_submodule J.to_bilin_form J₂.to_bilin_form) : (pair_self_adjoint_matrices_linear_embedding J J₂ : _ →ₗ _) f = (f : module.End R (n → R)).to_matrix := rfl lemma pair_self_adjoint_matrices_linear_embedding_injective : function.injective (pair_self_adjoint_matrices_linear_embedding J J₂) := λ f g h, by { apply set_coe.ext, exact linear_equiv_matrix'.injective h, } /-- The submodule of pair-self-adjoint matrices with respect to bilinear forms corresponding to given matrices `J`, `J₂`. -/ def pair_self_adjoint_matrices_submodule : submodule R (matrix n n R) := (pair_self_adjoint_matrices_linear_embedding J J₂).range @[simp] lemma mem_pair_self_adjoint_matrices_submodule : A ∈ (pair_self_adjoint_matrices_submodule J J₂) ↔ matrix.is_adjoint_pair J J₂ A A := begin change A ∈ (pair_self_adjoint_matrices_linear_embedding J J₂).range ↔ matrix.is_adjoint_pair J J₂ A A, rw [matrix_is_adjoint_pair_bilin_form, linear_map.mem_range], simp only [pair_self_adjoint_matrices_linear_embedding_apply], split, { rintros ⟨⟨A', hA'⟩, h⟩, rw ←h, rw to_matrix_to_lin, exact hA', }, { intros h, exact ⟨⟨A.to_lin, h⟩, to_lin_to_matrix⟩, }, end /-- The submodule of self-adjoint matrices with respect to the bilinear form corresponding to the matrix `J`. -/ def self_adjoint_matrices_submodule : submodule R (matrix n n R) := pair_self_adjoint_matrices_submodule J J /-- The submodule of skew-adjoint matrices with respect to the bilinear form corresponding to the matrix `J`. -/ def skew_adjoint_matrices_submodule : submodule R (matrix n n R) := pair_self_adjoint_matrices_submodule (-J) J end matrix_adjoints
fcb09137d06237f0cd7ed434eb718ca7a5049445
f57749ca63d6416f807b770f67559503fdb21001
/hott/init/tactic.hlean
e7d4db9a1ed3561248c57c96c2128e9d09de03f5
[ "Apache-2.0" ]
permissive
aliassaf/lean
bd54e85bed07b1ff6f01396551867b2677cbc6ac
f9b069b6a50756588b309b3d716c447004203152
refs/heads/master
1,610,982,152,948
1,438,916,029,000
1,438,916,029,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
6,732
hlean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura This is just a trick to embed the 'tactic language' as a Lean expression. We should view 'tactic' as automation that when execute produces a term. tactic.builtin is just a "dummy" for creating the definitions that are actually implemented in C++ -/ prelude import init.datatypes init.reserved_notation init.num inductive tactic : Type := builtin : tactic namespace tactic -- Remark the following names are not arbitrary, the tactic module -- uses them when converting Lean expressions into actual tactic objects. -- The bultin 'by' construct triggers the process of converting a -- a term of type 'tactic' into a tactic that sythesizes a term definition and_then (t1 t2 : tactic) : tactic := builtin definition or_else (t1 t2 : tactic) : tactic := builtin definition append (t1 t2 : tactic) : tactic := builtin definition interleave (t1 t2 : tactic) : tactic := builtin definition par (t1 t2 : tactic) : tactic := builtin definition fixpoint (f : tactic → tactic) : tactic := builtin definition repeat (t : tactic) : tactic := builtin definition at_most (t : tactic) (k : num) : tactic := builtin definition discard (t : tactic) (k : num) : tactic := builtin definition focus_at (t : tactic) (i : num) : tactic := builtin definition try_for (t : tactic) (ms : num) : tactic := builtin definition all_goals (t : tactic) : tactic := builtin definition now : tactic := builtin definition assumption : tactic := builtin definition eassumption : tactic := builtin definition state : tactic := builtin definition fail : tactic := builtin definition id : tactic := builtin definition beta : tactic := builtin definition info : tactic := builtin definition whnf : tactic := builtin definition contradiction : tactic := builtin definition exfalso : tactic := builtin definition congruence : tactic := builtin definition rotate_left (k : num) := builtin definition rotate_right (k : num) := builtin definition rotate (k : num) := rotate_left k -- This is just a trick to embed expressions into tactics. -- The nested expressions are "raw". They tactic should -- elaborate them when it is executed. inductive expr : Type := builtin : expr inductive expr_list : Type := | nil : expr_list | cons : expr → expr_list → expr_list -- auxiliary type used to mark optional list of arguments definition opt_expr_list := expr_list -- auxiliary types used to mark that the expression is suppose to be an identifier, optional, or a list. definition identifier := expr definition identifier_list := expr_list definition opt_identifier_list := expr_list -- Marker for instructing the parser to parse it as '?(using <expr>)' definition using_expr := expr -- Constant used to denote the case were no expression was provided definition none_expr : expr := expr.builtin definition apply (e : expr) : tactic := builtin definition eapply (e : expr) : tactic := builtin definition fapply (e : expr) : tactic := builtin definition rename (a b : identifier) : tactic := builtin definition intro (e : identifier_list) : tactic := builtin definition generalize_tac (e : expr) (id : identifier) : tactic := builtin definition clear (e : identifier_list) : tactic := builtin definition revert (e : identifier_list) : tactic := builtin definition refine (e : expr) : tactic := builtin definition exact (e : expr) : tactic := builtin -- Relaxed version of exact that does not enforce goal type definition rexact (e : expr) : tactic := builtin definition check_expr (e : expr) : tactic := builtin definition trace (s : string) : tactic := builtin -- rewrite_tac is just a marker for the builtin 'rewrite' notation -- used to create instances of this tactic. definition rewrite_tac (e : expr_list) : tactic := builtin definition xrewrite_tac (e : expr_list) : tactic := builtin definition krewrite_tac (e : expr_list) : tactic := builtin -- simp_tac is just a marker for the builtin 'simp' notation -- used to create instances of this tactic. -- Arguments: -- - e : additional rewrites to be considered -- - n : add rewrites from the give namespaces -- - x : exclude the give global rewrites -- - t : tactic for discharging conditions -- - l : location definition simp_tac (e : expr_list) (n : identifier_list) (x : identifier_list) (t : option tactic) (l : expr) : tactic := builtin -- with_options_tac is just a marker for the builtin 'with_options' notation definition with_options_tac (o : expr) (t : tactic) : tactic := builtin definition cases (h : expr) (ids : opt_identifier_list) : tactic := builtin definition induction (h : expr) (rec : using_expr) (ids : opt_identifier_list) : tactic := builtin definition intros (ids : opt_identifier_list) : tactic := builtin definition generalizes (es : expr_list) : tactic := builtin definition clears (ids : identifier_list) : tactic := builtin definition reverts (ids : identifier_list) : tactic := builtin definition change (e : expr) : tactic := builtin definition assert_hypothesis (id : identifier) (e : expr) : tactic := builtin definition lettac (id : identifier) (e : expr) : tactic := builtin definition constructor (k : option num) : tactic := builtin definition fconstructor (k : option num) : tactic := builtin definition existsi (e : expr) : tactic := builtin definition split : tactic := builtin definition left : tactic := builtin definition right : tactic := builtin definition injection (e : expr) (ids : opt_identifier_list) : tactic := builtin definition subst (ids : identifier_list) : tactic := builtin definition substvars : tactic := builtin definition reflexivity : tactic := builtin definition symmetry : tactic := builtin definition transitivity (e : expr) : tactic := builtin definition try (t : tactic) : tactic := or_else t id definition repeat1 (t : tactic) : tactic := and_then t (repeat t) definition focus (t : tactic) : tactic := focus_at t 0 definition determ (t : tactic) : tactic := at_most t 1 definition trivial : tactic := or_else (apply eq.refl) assumption definition do (n : num) (t : tactic) : tactic := nat.rec id (λn t', and_then t t') (nat.of_num n) end tactic tactic_infixl `;`:15 := tactic.and_then tactic_notation `(` h `|` r:(foldl `|` (e r, tactic.or_else r e) h) `)` := r
112da6b5a8fe89a3b26548ca1eada5302cefd1ba
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/order/semiconj_Sup.lean
40060cfd95e0835ad16d4bac71e5abc2f99639ad
[]
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
5,890
lean
/- Copyright (c) 2020 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Yury G. Kudryashov -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.order.conditionally_complete_lattice import Mathlib.logic.function.conjugate import Mathlib.order.ord_continuous import Mathlib.data.equiv.mul_add import Mathlib.PostPort universes u_1 u_2 u_3 namespace Mathlib /-! # Semiconjugate by `Sup` In this file we prove two facts about semiconjugate (families of) functions. First, if an order isomorphism `fa : α → α` is semiconjugate to an order embedding `fb : β → β` by `g : α → β`, then `fb` is semiconjugate to `fa` by `y ↦ Sup {x | g x ≤ y}`, see `semiconj.symm_adjoint`. Second, consider two actions `f₁ f₂ : G → α → α` of a group on a complete lattice by order isomorphisms. Then the map `x ↦ ⨆ g : G, (f₁ g)⁻¹ (f₂ g x)` semiconjugates each `f₁ g'` to `f₂ g'`, see `function.Sup_div_semiconj`. In the case of a conditionally complete lattice, a similar statement holds true under an additional assumption that each set `{(f₁ g)⁻¹ (f₂ g x) | g : G}` is bounded above, see `function.cSup_div_semiconj`. The lemmas come from [Étienne Ghys, Groupes d'homeomorphismes du cercle et cohomologie bornee][ghys87:groupes], Proposition 2.1 and 5.4 respectively. In the paper they are formulated for homeomorphisms of the circle, so in order to apply results from this file one has to lift these homeomorphisms to the real line first. -/ /-- We say that `g : β → α` is an order right adjoint function for `f : α → β` if it sends each `y` to a least upper bound for `{x | f x ≤ y}`. If `α` is a partial order, and `f : α → β` has a right adjoint, then this right adjoint is unique. -/ def is_order_right_adjoint {α : Type u_1} {β : Type u_2} [preorder α] [preorder β] (f : α → β) (g : β → α) := ∀ (y : β), is_lub (set_of fun (x : α) => f x ≤ y) (g y) theorem is_order_right_adjoint_Sup {α : Type u_1} {β : Type u_2} [complete_lattice α] [preorder β] (f : α → β) : is_order_right_adjoint f fun (y : β) => Sup (set_of fun (x : α) => f x ≤ y) := fun (y : β) => is_lub_Sup (set_of fun (x : α) => f x ≤ y) theorem is_order_right_adjoint_cSup {α : Type u_1} {β : Type u_2} [conditionally_complete_lattice α] [preorder β] (f : α → β) (hne : ∀ (y : β), ∃ (x : α), f x ≤ y) (hbdd : ∀ (y : β), ∃ (b : α), ∀ (x : α), f x ≤ y → x ≤ b) : is_order_right_adjoint f fun (y : β) => Sup (set_of fun (x : α) => f x ≤ y) := fun (y : β) => is_lub_cSup (hne y) (hbdd y) theorem is_order_right_adjoint.unique {α : Type u_1} {β : Type u_2} [partial_order α] [preorder β] {f : α → β} {g₁ : β → α} {g₂ : β → α} (h₁ : is_order_right_adjoint f g₁) (h₂ : is_order_right_adjoint f g₂) : g₁ = g₂ := funext fun (y : β) => is_lub.unique (h₁ y) (h₂ y) theorem is_order_right_adjoint.right_mono {α : Type u_1} {β : Type u_2} [preorder α] [preorder β] {f : α → β} {g : β → α} (h : is_order_right_adjoint f g) : monotone g := fun (y₁ y₂ : β) (hy : y₁ ≤ y₂) => is_lub.mono (h y₁) (h y₂) fun (x : α) (hx : x ∈ set_of fun (x : α) => f x ≤ y₁) => le_trans hx hy namespace function /-- If an order automorphism `fa` is semiconjugate to an order embedding `fb` by a function `g` and `g'` is an order right adjoint of `g` (i.e. `g' y = Sup {x | f x ≤ y}`), then `fb` is semiconjugate to `fa` by `g'`. This is a version of Proposition 2.1 from [Étienne Ghys, Groupes d'homeomorphismes du cercle et cohomologie bornee][ghys87:groupes]. -/ theorem semiconj.symm_adjoint {α : Type u_1} {β : Type u_2} [partial_order α] [preorder β] {fa : α ≃o α} {fb : β ↪o β} {g : α → β} (h : semiconj g ⇑fa ⇑fb) {g' : β → α} (hg' : is_order_right_adjoint g g') : semiconj g' ⇑fb ⇑fa := sorry theorem semiconj_of_is_lub {α : Type u_1} {G : Type u_3} [partial_order α] [group G] (f₁ : G →* α ≃o α) (f₂ : G →* α ≃o α) {h : α → α} (H : ∀ (x : α), is_lub (set.range fun (g' : G) => coe_fn (coe_fn f₁ g'⁻¹) (coe_fn (coe_fn f₂ g') x)) (h x)) (g : G) : semiconj h ⇑(coe_fn f₂ g) ⇑(coe_fn f₁ g) := sorry /-- Consider two actions `f₁ f₂ : G → α → α` of a group on a complete lattice by order isomorphisms. Then the map `x ↦ ⨆ g : G, (f₁ g)⁻¹ (f₂ g x)` semiconjugates each `f₁ g'` to `f₂ g'`. This is a version of Proposition 5.4 from [Étienne Ghys, Groupes d'homeomorphismes du cercle et cohomologie bornee][ghys87:groupes]. -/ theorem Sup_div_semiconj {α : Type u_1} {G : Type u_3} [complete_lattice α] [group G] (f₁ : G →* α ≃o α) (f₂ : G →* α ≃o α) (g : G) : semiconj (fun (x : α) => supr fun (g' : G) => coe_fn (coe_fn f₁ g'⁻¹) (coe_fn (coe_fn f₂ g') x)) ⇑(coe_fn f₂ g) ⇑(coe_fn f₁ g) := semiconj_of_is_lub f₁ f₂ (fun (x : α) => is_lub_supr) g /-- Consider two actions `f₁ f₂ : G → α → α` of a group on a conditionally complete lattice by order isomorphisms. Suppose that each set $s(x)=\{f_1(g)^{-1} (f_2(g)(x)) | g \in G\}$ is bounded above. Then the map `x ↦ Sup s(x)` semiconjugates each `f₁ g'` to `f₂ g'`. This is a version of Proposition 5.4 from [Étienne Ghys, Groupes d'homeomorphismes du cercle et cohomologie bornee][ghys87:groupes]. -/ theorem cSup_div_semiconj {α : Type u_1} {G : Type u_3} [conditionally_complete_lattice α] [group G] (f₁ : G →* α ≃o α) (f₂ : G →* α ≃o α) (hbdd : ∀ (x : α), bdd_above (set.range fun (g : G) => coe_fn (coe_fn f₁ g⁻¹) (coe_fn (coe_fn f₂ g) x))) (g : G) : semiconj (fun (x : α) => supr fun (g' : G) => coe_fn (coe_fn f₁ g'⁻¹) (coe_fn (coe_fn f₂ g') x)) ⇑(coe_fn f₂ g) ⇑(coe_fn f₁ g) := sorry
3b37294b342e0c301ef80d6a9e6294a306a705fb
471bedbd023d35c9d078c2f936dd577ace7f5813
/library/system/io.lean
b8fb0f5e1eec1bdb223161ed411acce3ccf805c4
[ "Apache-2.0" ]
permissive
lambdaxymox/lean
e06f0fa503666df827edd9867d7f49ca017aae64
fc13c8c72a15dab71a2c2b31410c2cadc3526bd7
refs/heads/master
1,666,785,407,985
1,666,153,673,000
1,666,153,673,000
310,165,986
0
0
Apache-2.0
1,604,542,096,000
1,604,542,095,000
null
UTF-8
Lean
false
false
8,995
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Luke Nelson, Jared Roesch and Leonardo de Moura -/ import system.io_interface /- The following constants have a builtin implementation -/ constant io_core : Type → Type → Type /- Auxiliary definition used in the builtin implementation of monad_io_random_impl -/ def io_rand_nat : std_gen → nat → nat → nat × std_gen := rand_nat @[instance] constant monad_io_impl : monad_io io_core @[instance] constant monad_io_terminal_impl : monad_io_terminal io_core @[instance] constant monad_io_net_system_impl : monad_io_net_system io_core @[instance] constant monad_io_file_system_impl : monad_io_file_system io_core @[instance] meta constant monad_io_serial_impl : monad_io_serial io_core @[instance] constant monad_io_environment_impl : monad_io_environment io_core @[instance] constant monad_io_process_impl : monad_io_process io_core @[instance] constant monad_io_random_impl : monad_io_random io_core instance io_core_is_monad (e : Type) : monad (io_core e) := monad_io_is_monad io_core e instance io_core_is_monad_fail : monad_fail (io_core io.error) := monad_io_is_monad_fail io_core instance io_core_is_alternative : alternative (io_core io.error) := monad_io_is_alternative io_core @[reducible] def io (α : Type) := io_core io.error α namespace io /- Remark: the following definitions can be generalized and defined for any (m : Type -> Type -> Type) that implements the required type classes. However, the generalized versions are very inconvenient to use, (example: `#eval io.put_str "hello world"` does not work because we don't have enough information to infer `m`.). -/ def iterate {e α} (a : α) (f : α → io_core e (option α)) : io_core e α := monad_io.iterate e α a f def forever {e} (a : io_core e unit) : io_core e unit := iterate () $ λ _, a >> return (some ()) -- TODO(Leo): delete after we merge #1881 def catch {e₁ e₂ α} (a : io_core e₁ α) (b : e₁ → io_core e₂ α) : io_core e₂ α := monad_io.catch e₁ e₂ α a b def finally {α e} (a : io_core e α) (cleanup : io_core e unit) : io_core e α := do res ← catch (sum.inr <$> a) (return ∘ sum.inl), cleanup, match res with | sum.inr res := return res | sum.inl error := monad_io.fail _ _ error end protected def fail {α : Type} (s : string) : io α := monad_io.fail _ _ (io.error.other s) def put_str : string → io unit := monad_io_terminal.put_str def put_str_ln (s : string) : io unit := put_str s >> put_str "\n" def get_line : io string := monad_io_terminal.get_line def cmdline_args : io (list string) := return (monad_io_terminal.cmdline_args io_core) def print {α} [has_to_string α] (s : α) : io unit := put_str ∘ to_string $ s def print_ln {α} [has_to_string α] (s : α) : io unit := print s >> put_str "\n" def handle : Type := monad_io.handle io_core def mk_file_handle (s : string) (m : mode) (bin : bool := ff) : io handle := monad_io_file_system.mk_file_handle s m bin def stdin : io handle := monad_io_file_system.stdin def stderr : io handle := monad_io_file_system.stderr def stdout : io handle := monad_io_file_system.stdout meta def serialize : handle → expr → io unit := monad_io_serial.serialize meta def deserialize : handle → io expr := monad_io_serial.deserialize namespace env def get (env_var : string) : io (option string) := monad_io_environment.get_env env_var /-- get the current working directory -/ def get_cwd : io string := monad_io_environment.get_cwd /-- set the current working directory -/ def set_cwd (cwd : string) : io unit := monad_io_environment.set_cwd cwd end env namespace net def socket : Type := monad_io_net_system.socket io_core def listen : string → nat → io socket := monad_io_net_system.listen def accept : socket → io socket := monad_io_net_system.accept def connect : string → io socket := monad_io_net_system.connect def recv : socket → nat → io char_buffer := monad_io_net_system.recv def send : socket → char_buffer → io unit := monad_io_net_system.send def close : socket → io unit := monad_io_net_system.close end net namespace fs def is_eof : handle → io bool := monad_io_file_system.is_eof def flush : handle → io unit := monad_io_file_system.flush def close : handle → io unit := monad_io_file_system.close def read : handle → nat → io char_buffer := monad_io_file_system.read def write : handle → char_buffer → io unit := monad_io_file_system.write def get_char (h : handle) : io char := do b ← read h 1, if h : b.size = 1 then return $ b.read ⟨0, h.symm ▸ nat.zero_lt_one⟩ else io.fail "get_char failed" def get_line : handle → io char_buffer := monad_io_file_system.get_line def put_char (h : handle) (c : char) : io unit := write h (mk_buffer.push_back c) def put_str (h : handle) (s : string) : io unit := write h (mk_buffer.append_string s) def put_str_ln (h : handle) (s : string) : io unit := put_str h s >> put_str h "\n" def read_to_end (h : handle) : io char_buffer := iterate mk_buffer $ λ r, do done ← is_eof h, if done then return none else do c ← read h 1024, return $ some (r ++ c) def read_file (s : string) (bin := ff) : io char_buffer := do h ← mk_file_handle s io.mode.read bin, read_to_end h def file_exists : string → io bool := monad_io_file_system.file_exists def dir_exists : string → io bool := monad_io_file_system.dir_exists def remove : string → io unit := monad_io_file_system.remove def rename : string → string → io unit := monad_io_file_system.rename def mkdir (path : string) (recursive : bool := ff) : io bool := monad_io_file_system.mkdir path recursive def rmdir : string → io bool := monad_io_file_system.rmdir end fs namespace proc def child : Type := monad_io_process.child io_core def child.stdin : child → handle := monad_io_process.stdin def child.stdout : child → handle := monad_io_process.stdout def child.stderr : child → handle := monad_io_process.stderr def spawn (p : io.process.spawn_args) : io child := monad_io_process.spawn p def wait (c : child) : io nat := monad_io_process.wait c def sleep (n : nat) : io unit := monad_io_process.sleep n end proc def set_rand_gen : std_gen → io unit := monad_io_random.set_rand_gen def rand (lo : nat := std_range.1) (hi : nat := std_range.2) : io nat := monad_io_random.rand lo hi end io meta constant format.print_using : format → options → io unit meta definition format.print (fmt : format) : io unit := format.print_using fmt options.mk meta definition pp_using {α : Type} [has_to_format α] (a : α) (o : options) : io unit := format.print_using (to_fmt a) o meta definition pp {α : Type} [has_to_format α] (a : α) : io unit := format.print (to_fmt a) /-- Run the external process specified by `args`. The process will run to completion with its output captured by a pipe, and read into `string` which is then returned. -/ def io.cmd (args : io.process.spawn_args) : io string := do child ← io.proc.spawn { stdout := io.process.stdio.piped, ..args }, buf ← io.fs.read_to_end child.stdout, io.fs.close child.stdout, exitv ← io.proc.wait child, when (exitv ≠ 0) $ io.fail $ "process exited with status " ++ repr exitv, return buf.to_string /-- This is the "back door" into the `io` monad, allowing IO computation to be performed during tactic execution. For this to be safe, the IO computation should be ideally free of side effects and independent of its environment. This primitive is used to invoke external tools (e.g., SAT and SMT solvers) from a tactic. -/ meta constant tactic.unsafe_run_io {α : Type} : io α → tactic α /-- Execute the given tactic with a tactic_state object that contains: - The current environment in the virtual machine. - The current set of options in the virtual machine. - Empty metavariable and local contexts. - One single goal of the form `⊢ true`. This action is mainly useful for writing tactics that inspect the environment. -/ meta constant io.run_tactic {α : Type} (a : tactic α) : io α /-- Similarly to `tactic.unsafe_run_io`, this gives an unsafe backdoor to run io inside a pure function. If `unsafe_perform_io` is used to perform side-effects, users need to take the following precautions: - Use `@[noinline]` attribute in any function to invokes `tactic.unsafe_perform_io`. Reason: if the call is inlined, the IO may be performed more than once. - Set `set_option compiler.cse false` before any function that invokes `tactic.unsafe_perform_io`. This option disables common subexpression elimination. Common subexpression elimination might combine two side effects that were meant to be separate. TODO[Leo]: add `[noinline]` attribute and option `compiler.cse`. -/ meta constant io.unsafe_perform_io {α : Type} (a : io α) : except io.error α
7e35b2b4c00465d6b31f2a8dbbd93e1798c6513f
67190c9aacc0cac64fb4463d93e84c696a5be896
/Exercises/9. First Order Logic in Lean.lean
a2707d56964a2f23b18202ca184d3cd4bfdb9a10
[]
no_license
lucasresck/Discrete-Mathematics
ffbaf55943e7ce2c7bc50cef7e3ef66a0212f738
0a08081c5f393e5765259d3f1253c3a6dd043dac
refs/heads/master
1,596,627,857,734
1,573,411,500,000
1,573,411,500,000
212,489,764
0
0
null
null
null
null
UTF-8
Lean
false
false
2,947
lean
section variable A : Type variable f : A → A variable P : A → Prop variable h : ∀ x, P x → P (f x) -- Show the following: example : ∀ y, P y → P (f (f y)) := assume y, have h1 : P y → P (f y), from h y, have h2 : P (f y) → P (f (f y)), from h (f y), show P y → P (f (f y)), from assume h4 : P y, have h5 : P (f y), from h1 h4, show P (f (f y)), from h2 h5 end section variable U : Type variables A B : U → Prop example : (∀ x, A x ∧ B x) → ∀ x, A x := assume h1 : ∀ x, A x ∧ B x, assume y, have h2 : A y ∧ B y, from h1 y, show A y, from h2.left end section variable U : Type variables A B C : U → Prop variable h1 : ∀ x, A x ∨ B x variable h2 : ∀ x, A x → C x variable h3 : ∀ x, B x → C x example : ∀ x, C x := assume y, show C y, from have h4 : A y ∨ B y, from h1 y, or.elim h4 (assume h5 : A y, have h6 : A y → C y, from h2 y, show C y, from h6 h5) (assume h5 : B y, have h6 : B y → C y, from h3 y, show C y, from h6 h5) end open classical -- not needed, but you can use it -- This is an exercise from Chapter 4. Use it as an axiom here. axiom not_iff_not_self (P : Prop) : ¬ (P ↔ ¬ P) example (Q : Prop) : ¬ (Q ↔ ¬ Q) := not_iff_not_self Q section variable Person : Type variable shaves : Person → Person → Prop variable barber : Person variable h : ∀ x, shaves barber x ↔ ¬ shaves x x -- Show the following: example : false := have h3 : shaves barber barber ↔ ¬ shaves barber barber, from h barber, have h2 : ¬ shaves barber barber, from assume h4 : shaves barber barber, have h5 : ¬ shaves barber barber, from iff.elim_left h3 h4, show false, from h5 h4, have h1 : shaves barber barber, from iff.elim_right h3 h2, show false, from h2 h1 end section variable U : Type variables A B : U → Prop example : (∃ x, A x) → ∃ x, A x ∨ B x := assume h1 : ∃ x, A x, show ∃ x, A x ∨ B x, from exists.elim h1 (assume y (h2 : A y), have h3 : A y ∨ B y, from or.inl h2, show ∃ x, A x ∨ B x, from exists.intro y h3) end section variable U : Type variables A B : U → Prop variable h1 : ∀ x, A x → B x variable h2 : ∃ x, A x example : ∃ x, B x := show ∃ x, B x, from exists.elim h2 (assume y (h3 : A y), have h4 : A y → B y, from h1 y, have h5 : B y, from h4 h3, show ∃ x, B x, from exists.intro y h5) end section variable U : Type variables A B C : U → Prop example (h1 : ∃ x, A x ∧ B x) (h2 : ∀ x, B x → C x) : ∃ x, A x ∧ C x := exists.elim h1 (assume y (h3 : A y ∧ B y), have h4 : A y, from h3.left, have h5 : B y, from h3.right, have h6 : B y → C y, from h2 y, have h7 : C y, from h6 h5, have h8 : A y ∧ C y, from and.intro h4 h7, exists.intro y h8) end
94245c8c7619c80f5f743b6c2560c31a36784518
57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d
/src/Lean/Elab/SyntheticMVars.lean
6ae22292a764a2353c6573b1f09d2641af1c53d1
[ "Apache-2.0" ]
permissive
collares/lean4
861a9269c4592bce49b71059e232ff0bfe4594cc
52a4f535d853a2c7c7eea5fee8a4fa04c682c1ee
refs/heads/master
1,691,419,031,324
1,618,678,138,000
1,618,678,138,000
358,989,750
0
0
Apache-2.0
1,618,696,333,000
1,618,696,333,000
null
UTF-8
Lean
false
false
17,649
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Sebastian Ullrich -/ import Lean.Util.ForEachExpr import Lean.Elab.Term import Lean.Elab.Tactic.Basic namespace Lean.Elab.Term open Tactic (TacticM evalTactic getUnsolvedGoals) open Meta /-- Auxiliary function used to implement `synthesizeSyntheticMVars`. -/ private def resumeElabTerm (stx : Syntax) (expectedType? : Option Expr) (errToSorry := true) : TermElabM Expr := -- Remark: if `ctx.errToSorry` is already false, then we don't enable it. Recall tactics disable `errToSorry` withReader (fun ctx => { ctx with errToSorry := ctx.errToSorry && errToSorry }) do elabTerm stx expectedType? false /-- Try to elaborate `stx` that was postponed by an elaboration method using `Expection.postpone`. It returns `true` if it succeeded, and `false` otherwise. It is used to implement `synthesizeSyntheticMVars`. -/ private def resumePostponed (savedContext : SavedContext) (stx : Syntax) (mvarId : MVarId) (postponeOnError : Bool) : TermElabM Bool := withRef stx <| withMVarContext mvarId do let s ← get try withSavedContext savedContext do let mvarDecl ← getMVarDecl mvarId let expectedType ← instantiateMVars mvarDecl.type withInfoHole mvarId do let result ← resumeElabTerm stx expectedType (!postponeOnError) /- We must ensure `result` has the expected type because it is the one expected by the method that postponed stx. That is, the method does not have an opportunity to check whether `result` has the expected type or not. -/ let result ← withRef stx <| ensureHasType expectedType result /- We must perform `occursCheck` here since `result` may contain `mvarId` when it has synthetic `sorry`s. -/ if (← occursCheck mvarId result) then assignExprMVar mvarId result return true else return false catch | ex@(Exception.internal id _) => if id == postponeExceptionId then set s return false else throw ex | ex@(Exception.error _ _) => if postponeOnError then set s return false else logException ex return true /-- Similar to `synthesizeInstMVarCore`, but makes sure that `instMVar` local context and instances are used. It also logs any error message produced. -/ private def synthesizePendingInstMVar (instMVar : MVarId) : TermElabM Bool := withMVarContext instMVar do try synthesizeInstMVarCore instMVar catch | ex@(Exception.error _ _) => logException ex; return true | _ => unreachable! /-- Similar to `synthesizePendingInstMVar`, but generates type mismatch error message. Remark: `eNew` is of the form `@coe ... mvar`, where `mvar` is the metavariable for the `CoeT ...` instance. If `mvar` can be synthesized, then assign `auxMVarId := (expandCoe eNew)`. -/ private def synthesizePendingCoeInstMVar (auxMVarId : MVarId) (errorMsgHeader? : Option String) (eNew : Expr) (expectedType : Expr) (eType : Expr) (e : Expr) (f? : Option Expr) : TermElabM Bool := do let instMVarId := eNew.appArg!.mvarId! withMVarContext instMVarId do if (← isDefEq expectedType eType) then /- This case may seem counterintuitive since we created the coercion because the `isDefEq expectedType eType` test failed before. However, it may succeed here because we have more information, for example, metavariables occurring at `expectedType` and `eType` may have been assigned. -/ if (← occursCheck auxMVarId e) then assignExprMVar auxMVarId e return true else return false try if (← synthesizeCoeInstMVarCore instMVarId) then let eNew ← expandCoe eNew if (← occursCheck auxMVarId eNew) then assignExprMVar auxMVarId eNew return true return false catch | Exception.error _ msg => throwTypeMismatchError errorMsgHeader? expectedType eType e f? msg | _ => unreachable! /-- Try to synthesize a value for `mvarId` using the given default instance. Return `some (val, mvarDecls)` if successful, where `val` is the value assigned to `mvarId`, and `mvarDecls` is a list of new type class instances that need to be synthesized. -/ private def tryToSynthesizeUsingDefaultInstance (mvarId : MVarId) (defaultInstance : Name) : TermElabM (Option (Expr × List SyntheticMVarDecl)) := commitWhenSome? do let candidate ← mkConstWithFreshMVarLevels defaultInstance let (mvars, bis, _) ← forallMetaTelescopeReducing (← inferType candidate) let candidate := mkAppN candidate mvars trace[Elab.resume] "trying default instance for {mkMVar mvarId} := {candidate}" if (← isDefEqGuarded (mkMVar mvarId) candidate) then -- Succeeded. Collect new TC problems let mut result := [] for i in [:bis.size] do if bis[i] == BinderInfo.instImplicit then result := { mvarId := mvars[i].mvarId!, stx := (← getRef), kind := SyntheticMVarKind.typeClass } :: result trace[Elab.resume] "worked" return some (candidate, result) else return none private def tryToSynthesizeUsingDefaultInstances (mvarId : MVarId) (prio : Nat) : TermElabM (Option (Expr × List SyntheticMVarDecl)) := withMVarContext mvarId do let mvarType := (← Meta.getMVarDecl mvarId).type match (← isClass? mvarType) with | none => return none | some className => match (← getDefaultInstances className) with | [] => return none | defaultInstances => for (defaultInstance, instPrio) in defaultInstances do if instPrio == prio then match (← tryToSynthesizeUsingDefaultInstance mvarId defaultInstance) with | some result => return some result | none => continue return none /- Used to implement `synthesizeUsingDefault`. This method only consider default instances with the given priority. -/ private def synthesizeUsingDefaultPrio (prio : Nat) : TermElabM Bool := do let rec visit (syntheticMVars : List SyntheticMVarDecl) (syntheticMVarsNew : List SyntheticMVarDecl) : TermElabM Bool := do match syntheticMVars with | [] => return false | mvarDecl :: mvarDecls => match mvarDecl.kind with | SyntheticMVarKind.typeClass => match (← withRef mvarDecl.stx <| tryToSynthesizeUsingDefaultInstances mvarDecl.mvarId prio) with | none => visit mvarDecls (mvarDecl :: syntheticMVarsNew) | some (val, newMVarDecls) => for newMVarDecl in newMVarDecls do -- Register that `newMVarDecl.mvarId`s are implicit arguments of the value assigned to `mvarDecl.mvarId` registerMVarErrorImplicitArgInfo newMVarDecl.mvarId (← getRef) val let syntheticMVarsNew := newMVarDecls ++ syntheticMVarsNew let syntheticMVarsNew := mvarDecls.reverse ++ syntheticMVarsNew modify fun s => { s with syntheticMVars := syntheticMVarsNew } return true | _ => visit mvarDecls (mvarDecl :: syntheticMVarsNew) /- Recall that s.syntheticMVars is essentially a stack. The first metavariable was the last one created. We want to apply the default instance in reverse creation order. Otherwise, `toString 0` will produce a `OfNat String _` cannot be synthesized error. -/ visit (← get).syntheticMVars.reverse [] /-- Apply default value to any pending synthetic metavariable of kind `SyntheticMVarKind.withDefault` Return true if something was synthesized. -/ private def synthesizeUsingDefault : TermElabM Bool := do let prioSet ← getDefaultInstancesPriorities /- Recall that `prioSet` is stored in descending order -/ for prio in prioSet do if (← synthesizeUsingDefaultPrio prio) then return true return false /-- Report an error for each synthetic metavariable that could not be resolved. -/ private def reportStuckSyntheticMVars : TermElabM Unit := do let syntheticMVars ← modifyGet fun s => (s.syntheticMVars, { s with syntheticMVars := [] }) for mvarSyntheticDecl in syntheticMVars do withRef mvarSyntheticDecl.stx do match mvarSyntheticDecl.kind with | SyntheticMVarKind.typeClass => withMVarContext mvarSyntheticDecl.mvarId do let mvarDecl ← getMVarDecl mvarSyntheticDecl.mvarId unless (← get).messages.hasErrors do throwError "typeclass instance problem is stuck, it is often due to metavariables{indentExpr mvarDecl.type}" | SyntheticMVarKind.coe header eNew expectedType eType e f? => let mvarId := eNew.appArg!.mvarId! withMVarContext mvarId do let mvarDecl ← getMVarDecl mvarId throwTypeMismatchError header expectedType eType e f? (some ("failed to create type class instance for " ++ indentExpr mvarDecl.type)) | _ => unreachable! -- TODO handle other cases. private def getSomeSynthethicMVarsRef : TermElabM Syntax := do let s ← get match s.syntheticMVars.find? fun (mvarDecl : SyntheticMVarDecl) => !mvarDecl.stx.getPos?.isNone with | some mvarDecl => return mvarDecl.stx | none => return Syntax.missing mutual partial def liftTacticElabM {α} (mvarId : MVarId) (x : TacticM α) : TermElabM α := withMVarContext mvarId do let savedSyntheticMVars := (← get).syntheticMVars modify fun s => { s with syntheticMVars := [] } try let a ← x.run' { main := mvarId } { goals := [mvarId] } synthesizeSyntheticMVars (mayPostpone := false) pure a finally modify fun s => { s with syntheticMVars := savedSyntheticMVars } partial def runTactic (mvarId : MVarId) (tacticCode : Syntax) : TermElabM Unit := do /- Recall, `tacticCode` is the whole `by ...` expression. We store the `by` because in the future we want to save the initial state information at the `by` position. -/ let code := tacticCode[1] modifyThe Meta.State fun s => { s with mctx := s.mctx.instantiateMVarDeclMVars mvarId } let remainingGoals ← withInfoHole mvarId do liftTacticElabM mvarId do evalTactic code; getUnsolvedGoals unless remainingGoals.isEmpty do reportUnsolvedGoals remainingGoals /-- Try to synthesize the given pending synthetic metavariable. -/ private partial def synthesizeSyntheticMVar (mvarSyntheticDecl : SyntheticMVarDecl) (postponeOnError : Bool) (runTactics : Bool) : TermElabM Bool := withRef mvarSyntheticDecl.stx do match mvarSyntheticDecl.kind with | SyntheticMVarKind.typeClass => synthesizePendingInstMVar mvarSyntheticDecl.mvarId | SyntheticMVarKind.coe header? eNew expectedType eType e f? => synthesizePendingCoeInstMVar mvarSyntheticDecl.mvarId header? eNew expectedType eType e f? -- NOTE: actual processing at `synthesizeSyntheticMVarsAux` | SyntheticMVarKind.postponed savedContext => resumePostponed savedContext mvarSyntheticDecl.stx mvarSyntheticDecl.mvarId postponeOnError | SyntheticMVarKind.tactic tacticCode savedContext => withSavedContext savedContext do if runTactics then runTactic mvarSyntheticDecl.mvarId tacticCode return true else return false /-- Try to synthesize the current list of pending synthetic metavariables. Return `true` if at least one of them was synthesized. -/ private partial def synthesizeSyntheticMVarsStep (postponeOnError : Bool) (runTactics : Bool) : TermElabM Bool := do let ctx ← read traceAtCmdPos `Elab.resuming fun _ => m!"resuming synthetic metavariables, mayPostpone: {ctx.mayPostpone}, postponeOnError: {postponeOnError}" let syntheticMVars := (← get).syntheticMVars let numSyntheticMVars := syntheticMVars.length -- We reset `syntheticMVars` because new synthetic metavariables may be created by `synthesizeSyntheticMVar`. modify fun s => { s with syntheticMVars := [] } -- Recall that `syntheticMVars` is a list where head is the most recent pending synthetic metavariable. -- We use `filterRevM` instead of `filterM` to make sure we process the synthetic metavariables using the order they were created. -- It would not be incorrect to use `filterM`. let remainingSyntheticMVars ← syntheticMVars.filterRevM fun mvarDecl => do -- We use `traceM` because we want to make sure the metavar local context is used to trace the message traceM `Elab.postpone (withMVarContext mvarDecl.mvarId do addMessageContext m!"resuming {mkMVar mvarDecl.mvarId}") let succeeded ← synthesizeSyntheticMVar mvarDecl postponeOnError runTactics trace[Elab.postpone] if succeeded then fmt "succeeded" else fmt "not ready yet" pure !succeeded -- Merge new synthetic metavariables with `remainingSyntheticMVars`, i.e., metavariables that still couldn't be synthesized modify fun s => { s with syntheticMVars := s.syntheticMVars ++ remainingSyntheticMVars } return numSyntheticMVars != remainingSyntheticMVars.length /-- Try to process pending synthetic metavariables. If `mayPostpone == false`, then `syntheticMVars` is `[]` after executing this method. It keeps executing `synthesizeSyntheticMVarsStep` while progress is being made. If `mayPostpone == false`, then it applies default instances to `SyntheticMVarKind.typeClass` (if available) metavariables that are still unresolved, and then tries to resolve metavariables with `mayPostpone == false`. That is, we force them to produce error messages and/or commit to a "best option". If, after that, we still haven't made progress, we report "stuck" errors. -/ partial def synthesizeSyntheticMVars (mayPostpone := true) : TermElabM Unit := let rec loop (u : Unit) : TermElabM Unit := do withRef (← getSomeSynthethicMVarsRef) <| withIncRecDepth do unless (← get).syntheticMVars.isEmpty do if ← synthesizeSyntheticMVarsStep (postponeOnError := false) (runTactics := false) then loop () else if !mayPostpone then /- Resume pending metavariables with "elaboration postponement" disabled. We postpone elaboration errors in this step by setting `postponeOnError := true`. Example: ``` #check let x := ⟨1, 2⟩; Prod.fst x ``` The term `⟨1, 2⟩` can't be elaborated because the expected type is not know. The `x` at `Prod.fst x` is not elaborated because the type of `x` is not known. When we execute the following step with "elaboration postponement" disabled, the elaborator fails at `⟨1, 2⟩` and postpones it, and succeeds at `x` and learns that its type must be of the form `Prod ?α ?β`. Recall that we postponed `x` at `Prod.fst x` because its type it is not known. We the type of `x` may learn later its type and it may contain implicit and/or auto arguments. By disabling postponement, we are essentially giving up the opportunity of learning `x`s type and assume it does not have implict and/or auto arguments. -/ if ← withoutPostponing <| synthesizeSyntheticMVarsStep (postponeOnError := true) (runTactics := false) then loop () else if ← synthesizeUsingDefault then loop () else if ← withoutPostponing <| synthesizeSyntheticMVarsStep (postponeOnError := false) (runTactics := false) then loop () else if ← synthesizeSyntheticMVarsStep (postponeOnError := false) (runTactics := true) then loop () else reportStuckSyntheticMVars loop () end def synthesizeSyntheticMVarsNoPostponing : TermElabM Unit := synthesizeSyntheticMVars (mayPostpone := false) /- Keep invoking `synthesizeUsingDefault` until it returns false. -/ private partial def synthesizeUsingDefaultLoop : TermElabM Unit := do if (← synthesizeUsingDefault) then synthesizeSyntheticMVars (mayPostpone := true) synthesizeUsingDefaultLoop def synthesizeSyntheticMVarsUsingDefault : TermElabM Unit := do synthesizeSyntheticMVars (mayPostpone := true) synthesizeUsingDefaultLoop private partial def withSynthesizeImp {α} (k : TermElabM α) (mayPostpone : Bool) : TermElabM α := do let syntheticMVarsSaved := (← get).syntheticMVars modify fun s => { s with syntheticMVars := [] } try let a ← k synthesizeSyntheticMVars mayPostpone if mayPostpone then synthesizeUsingDefaultLoop return a finally modify fun s => { s with syntheticMVars := s.syntheticMVars ++ syntheticMVarsSaved } /-- Execute `k`, and synthesize pending synthetic metavariables created while executing `k` are solved. If `mayPostpone == false`, then all of them must be synthesized. Remark: even if `mayPostpone == true`, the method still uses `synthesizeUsingDefault` -/ @[inline] def withSynthesize [MonadFunctorT TermElabM m] [Monad m] (k : m α) (mayPostpone := false) : m α := monadMap (m := TermElabM) (withSynthesizeImp . mayPostpone) k /-- Elaborate `stx`, and make sure all pending synthetic metavariables created while elaborating `stx` are solved. -/ def elabTermAndSynthesize (stx : Syntax) (expectedType? : Option Expr) : TermElabM Expr := withRef stx do instantiateMVars (← withSynthesize <| elabTerm stx expectedType?) end Lean.Elab.Term
a29404ec718e0692f601b5d9f9d1c09003ac2125
761fea1362b10b4c588c2dfc0ae90c70b119e35d
/src/main.lean
9bbf9bd134ecd358f0ef0f992047e60c86f5534b
[]
no_license
holtzermann17/mm-lean
382a29fca5245f97cf488c525ed0c9594917f73b
a9130d71ed448f62df28d4128043b707bad85ccd
refs/heads/master
1,588,477,413,982
1,553,885,046,000
1,553,885,046,000
178,404,617
0
0
null
1,553,863,829,000
1,553,863,828,000
null
UTF-8
Lean
false
false
3,551
lean
/- Copyright (c) 2017 Minchao Wu. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Minchao Wu -/ import system.io provers.ljt provers.tableaux mathematica lambda extract_consts -- _target.deps.relevance_filter.k_nn open tactic expr io mathematica name task mmexpr @[simp] lemma set_distrib_right {α} (s t u : set α) : s ∩ (t ∪ u) = (s ∩ t) ∪ (s ∩ u) := set.ext $ λ v, ⟨λ h, begin cases h.2, left, constructor, apply h.1, assumption, right, constructor, apply h.1, assumption end, λ h, begin cases h, constructor, apply h.1, left, apply h.2, constructor, apply h.1, right, apply h.2 end⟩ namespace tactic meta def solve_fully_aux {α : Type} (ex : expr) (tac : tactic α) : tactic (α × expr) := do (a, e) ← solve_aux ex tac, e' ← instantiate_mvars e, guard $ bnot e'.has_meta_var, return (a, e') end tactic meta def peek_type (e : expr) : tactic string := infer_type e >>= λ t, return $ to_string t meta def write_string (s : string) : tactic unit := unsafe_run_io $ write_file "temp.txt" s io.mode.write meta def mm_check : expr → tactic unit := λ e, peek_type e >>= λ s, write_string s meta def mm_write (s : name) (b := ff) : tactic unit := get_decl s >>= λ e, write_string $ cond b e.value.to_string (form_of_expr e.value) meta def mm_prover : tactic unit := intuit <|> glivenko /-- Solve goal using mm_prover and unfold listed constants in the resulting proof -/ meta def mm_prover_unfold (to_unfold : list name) : tactic unit := do t ← target, (_, pf) ← tactic.solve_fully_aux t mm_prover, dunfold to_unfold pf {fail_if_unchanged := ff} >>= apply >> skip meta def preprocess (mm_fml : string) : tactic expr := do m ← parse_mmexpr_tac $ string.to_char_buffer mm_fml, pexpr_of_mmexpr trans_env.empty m >>= to_expr meta def translate (mm_fml : string) : tactic string := do f ← preprocess mm_fml >>= pp, return f.to_string meta def prove_using_tac (tac : tactic unit) (mm_fml : string) (b := ff) : tactic string := (do e ← preprocess mm_fml, (_, pf) ← tactic.solve_fully_aux e tac, return $ if b then form_of_expr pf else pf.to_string) <|> return "failed" meta def prove_mm_prop_fml (mm_fml : string) (b := ff) : tactic string := prove_using_tac (intros >> mm_prover_unfold ljt_lemmas) mm_fml b meta def mk_smt_simp_lemmas : tactic simp_lemmas := local_context >>= simp_lemmas.append simp_lemmas.mk meta def mm_smt (mm_fml : string) (b := ff) : tactic string := prove_using_tac (intros >> using_smt (do s ← mk_smt_simp_lemmas, simp_target s [] {fail_if_unchanged := ff})) mm_fml b meta def elaborate (mm_fml : string) (b := ff) : tactic string := (do e ← preprocess mm_fml, return $ if b then form_of_expr e else e.to_string) <|> return "failed to elaborate" meta def type_check (mm_fml : string) (b := ff) : tactic string := (do e ← preprocess mm_fml >>= infer_type, return $ if b then form_of_expr e else e.to_string) <|> return "failed to typecheck" --------------------------------------------------------------------------------- meta def normalize_set (mm_fml : string) (b := ff) : tactic string := do e ← preprocess mm_fml, s ← simp_lemmas.mk_default, pt ← simplify s [] e {fail_if_unchanged := ff} `eq failed >>= pp, return $ pt.to_string meta def normalize_set_lemmas (mm_fml : string) (b := ff) : tactic string := do e ← preprocess mm_fml, s ← simp_lemmas.mk_default, pt ← simplify s [] e {fail_if_unchanged := ff} `eq failed, print_lemmas_used pt.2
65c860db452b22f6e00d2c47c596fc908664c6c6
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebra/order/monoid/units.lean
07a43cda6279b7362cbf90f87dfc0b68eb653927
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
1,562
lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura, Mario Carneiro, Johannes Hölzl -/ import order.hom.basic import order.min_max import algebra.group.units /-! # Units in ordered monoids -/ variables {α : Type*} namespace units @[to_additive] instance [monoid α] [preorder α] : preorder αˣ := preorder.lift (coe : αˣ → α) @[simp, norm_cast, to_additive] theorem coe_le_coe [monoid α] [preorder α] {a b : αˣ} : (a : α) ≤ b ↔ a ≤ b := iff.rfl @[simp, norm_cast, to_additive] theorem coe_lt_coe [monoid α] [preorder α] {a b : αˣ} : (a : α) < b ↔ a < b := iff.rfl @[to_additive] instance [monoid α] [partial_order α] : partial_order αˣ := partial_order.lift coe units.ext @[to_additive] instance [monoid α] [linear_order α] : linear_order αˣ := linear_order.lift' coe units.ext /-- `coe : αˣ → α` as an order embedding. -/ @[to_additive "`coe : add_units α → α` as an order embedding.", simps { fully_applied := ff }] def order_embedding_coe [monoid α] [linear_order α] : αˣ ↪o α := ⟨⟨coe, ext⟩, λ _ _, iff.rfl⟩ @[simp, norm_cast, to_additive] theorem max_coe [monoid α] [linear_order α] {a b : αˣ} : (↑(max a b) : α) = max a b := monotone.map_max order_embedding_coe.monotone @[simp, norm_cast, to_additive] theorem min_coe [monoid α] [linear_order α] {a b : αˣ} : (↑(min a b) : α) = min a b := monotone.map_min order_embedding_coe.monotone end units
7b776bc959d99200895c2cffc47572c53203b2d9
bd30db067473b7b7ccac89486f0faf854379c3f8
/mm_dependencies.lean
075b52c44dd8cc8639762ff9ffe00511a2bddcf5
[]
no_license
danieljmchugh/lean_arm_memory_model
e661a986f933d4868928062cb47e9d88f0316c7d
bf53a6c1509d22127f990b030d6f3ab57266dc92
refs/heads/main
1,687,711,084,222
1,626,487,537,000
1,626,487,537,000
386,810,582
0
0
null
null
null
null
UTF-8
Lean
false
false
1,652
lean
-- Armv8 memory model: Dependency defintions import mm_basic_defs /- ######################## Dependency definitions ######################## -/ def address_dependency (dtr : event → event → Prop) : event → event → Prop := λ r₁ e₂, is_read r₁ ∧ in_program_order r₁ e₂ ∧ dtr r₁ e₂ def data_dependency (dtr : event → event → Prop) : event → event → Prop := λ r₁ w₂, is_read r₁ ∧ is_write w₂ ∧ in_program_order r₁ w₂ ∧ dtr r₁ w₂ def control_dependency (dtr : event → event → Prop) : event → event → Prop := λ r₁ e₂, is_read r₁ ∧ in_program_order r₁ e₂ ∧ dtr r₁ e₂ def dependency_ordered_before (dtr : event → event → Prop) : event → event → Prop := λ r₁ e₂, is_read r₁ ∧ same_ob r₁ e₂ ∧ in_program_order r₁ e₂ ∧ (address_dependency dtr r₁ e₂ ∨ data_dependency dtr r₁ e₂) ∨ (is_write e₂ ∧ control_dependency dtr r₁ e₂) ∨ (is_write e₂ ∧ ∃ e₃, in_program_order e₂ e₃ ∧ address_dependency dtr r₁ e₃ ) ∨ (∃ w₃, is_write w₃ ∧ local_read_succ w₃ e₂ ∧ (address_dependency dtr r₁ w₃ ∨ data_dependency dtr r₁ w₃ )) def locally_ordered_before (dtr : event → event → Prop) : event → event → Prop := tc (λ e₁ e₂, (same_ob e₁ e₂) ∧ (local_write_succ e₁ e₂) ∨ (dependency_ordered_before dtr e₁ e₂)) -- ∨ aob -- ∨ bob def ordered_before (co dtr : event → event → Prop ) : event → event → Prop := tc (λ e₁ e₂, observed_by co e₁ e₂ ∨ locally_ordered_before dtr e₁ e₂)
5c13e1fd794de21e16a3cba6509090b9b010b722
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/measure_theory/measure/ae_measurable.lean
5a97a8502d46f2d88f64d33bebd5f343cdd2c5f2
[ "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
15,152
lean
/- Copyright (c) 2021 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import measure_theory.measure.measure_space /-! # Almost everywhere measurable functions A function is almost everywhere measurable if it coincides almost everywhere with a measurable function. This property, called `ae_measurable f μ`, is defined in the file `measure_space_def`. We discuss several of its properties that are analogous to properties of measurable functions. -/ open measure_theory measure_theory.measure filter set function open_locale measure_theory filter classical ennreal interval variables {ι α β γ δ R : Type*} {m0 : measurable_space α} [measurable_space β] [measurable_space γ] [measurable_space δ] {f g : α → β} {μ ν : measure α} include m0 section @[nontriviality, measurability] lemma subsingleton.ae_measurable [subsingleton α] : ae_measurable f μ := subsingleton.measurable.ae_measurable @[nontriviality, measurability] lemma ae_measurable_of_subsingleton_codomain [subsingleton β] : ae_measurable f μ := (measurable_of_subsingleton_codomain f).ae_measurable @[simp, measurability] lemma ae_measurable_zero_measure : ae_measurable f (0 : measure α) := begin nontriviality α, inhabit α, exact ⟨λ x, f default, measurable_const, rfl⟩ end namespace ae_measurable lemma mono_measure (h : ae_measurable f μ) (h' : ν ≤ μ) : ae_measurable f ν := ⟨h.mk f, h.measurable_mk, eventually.filter_mono (ae_mono h') h.ae_eq_mk⟩ lemma mono_set {s t} (h : s ⊆ t) (ht : ae_measurable f (μ.restrict t)) : ae_measurable f (μ.restrict s) := ht.mono_measure (restrict_mono h le_rfl) protected lemma mono' (h : ae_measurable f μ) (h' : ν ≪ μ) : ae_measurable f ν := ⟨h.mk f, h.measurable_mk, h' h.ae_eq_mk⟩ lemma ae_mem_imp_eq_mk {s} (h : ae_measurable f (μ.restrict s)) : ∀ᵐ x ∂μ, x ∈ s → f x = h.mk f x := ae_imp_of_ae_restrict h.ae_eq_mk lemma ae_inf_principal_eq_mk {s} (h : ae_measurable f (μ.restrict s)) : f =ᶠ[μ.ae ⊓ 𝓟 s] h.mk f := le_ae_restrict h.ae_eq_mk @[measurability] lemma sum_measure [countable ι] {μ : ι → measure α} (h : ∀ i, ae_measurable f (μ i)) : ae_measurable f (sum μ) := begin nontriviality β, inhabit β, set s : ι → set α := λ i, to_measurable (μ i) {x | f x ≠ (h i).mk f x}, have hsμ : ∀ i, μ i (s i) = 0, { intro i, rw measure_to_measurable, exact (h i).ae_eq_mk }, have hsm : measurable_set (⋂ i, s i), from measurable_set.Inter (λ i, measurable_set_to_measurable _ _), have hs : ∀ i x, x ∉ s i → f x = (h i).mk f x, { intros i x hx, contrapose! hx, exact subset_to_measurable _ _ hx }, set g : α → β := (⋂ i, s i).piecewise (const α default) f, refine ⟨g, measurable_of_restrict_of_restrict_compl hsm _ _, ae_sum_iff.mpr $ λ i, _⟩, { rw [restrict_piecewise], simp only [set.restrict, const], exact measurable_const }, { rw [restrict_piecewise_compl, compl_Inter], intros t ht, refine ⟨⋃ i, ((h i).mk f ⁻¹' t) ∩ (s i)ᶜ, measurable_set.Union $ λ i, (measurable_mk _ ht).inter (measurable_set_to_measurable _ _).compl, _⟩, ext ⟨x, hx⟩, simp only [mem_preimage, mem_Union, subtype.coe_mk, set.restrict, mem_inter_iff, mem_compl_iff] at hx ⊢, split, { rintro ⟨i, hxt, hxs⟩, rwa hs _ _ hxs }, { rcases hx with ⟨i, hi⟩, rw hs _ _ hi, exact λ h, ⟨i, h, hi⟩ } }, { refine measure_mono_null (λ x (hx : f x ≠ g x), _) (hsμ i), contrapose! hx, refine (piecewise_eq_of_not_mem _ _ _ _).symm, exact λ h, hx (mem_Inter.1 h i) } end @[simp] lemma _root_.ae_measurable_sum_measure_iff [countable ι] {μ : ι → measure α} : ae_measurable f (sum μ) ↔ ∀ i, ae_measurable f (μ i) := ⟨λ h i, h.mono_measure (le_sum _ _), sum_measure⟩ @[simp] lemma _root_.ae_measurable_add_measure_iff : ae_measurable f (μ + ν) ↔ ae_measurable f μ ∧ ae_measurable f ν := by { rw [← sum_cond, ae_measurable_sum_measure_iff, bool.forall_bool, and.comm], refl } @[measurability] lemma add_measure {f : α → β} (hμ : ae_measurable f μ) (hν : ae_measurable f ν) : ae_measurable f (μ + ν) := ae_measurable_add_measure_iff.2 ⟨hμ, hν⟩ @[measurability] protected lemma Union [countable ι] {s : ι → set α} (h : ∀ i, ae_measurable f (μ.restrict (s i))) : ae_measurable f (μ.restrict (⋃ i, s i)) := (sum_measure h).mono_measure $ restrict_Union_le @[simp] lemma _root_.ae_measurable_Union_iff [countable ι] {s : ι → set α} : ae_measurable f (μ.restrict (⋃ i, s i)) ↔ ∀ i, ae_measurable f (μ.restrict (s i)) := ⟨λ h i, h.mono_measure $ restrict_mono (subset_Union _ _) le_rfl, ae_measurable.Union⟩ @[simp] lemma _root_.ae_measurable_union_iff {s t : set α} : ae_measurable f (μ.restrict (s ∪ t)) ↔ ae_measurable f (μ.restrict s) ∧ ae_measurable f (μ.restrict t) := by simp only [union_eq_Union, ae_measurable_Union_iff, bool.forall_bool, cond, and.comm] @[measurability] lemma smul_measure [monoid R] [distrib_mul_action R ℝ≥0∞] [is_scalar_tower R ℝ≥0∞ ℝ≥0∞] (h : ae_measurable f μ) (c : R) : ae_measurable f (c • μ) := ⟨h.mk f, h.measurable_mk, ae_smul_measure h.ae_eq_mk c⟩ lemma comp_ae_measurable {f : α → δ} {g : δ → β} (hg : ae_measurable g (μ.map f)) (hf : ae_measurable f μ) : ae_measurable (g ∘ f) μ := ⟨hg.mk g ∘ hf.mk f, hg.measurable_mk.comp hf.measurable_mk, (ae_eq_comp hf hg.ae_eq_mk).trans ((hf.ae_eq_mk).fun_comp (mk g hg))⟩ lemma comp_measurable {f : α → δ} {g : δ → β} (hg : ae_measurable g (μ.map f)) (hf : measurable f) : ae_measurable (g ∘ f) μ := hg.comp_ae_measurable hf.ae_measurable lemma comp_quasi_measure_preserving {ν : measure δ} {f : α → δ} {g : δ → β} (hg : ae_measurable g ν) (hf : quasi_measure_preserving f μ ν) : ae_measurable (g ∘ f) μ := (hg.mono' hf.absolutely_continuous).comp_measurable hf.measurable lemma map_map_of_ae_measurable {g : β → γ} {f : α → β} (hg : ae_measurable g (measure.map f μ)) (hf : ae_measurable f μ) : (μ.map f).map g = μ.map (g ∘ f) := begin ext1 s hs, let g' := hg.mk g, have A : map g (map f μ) = map g' (map f μ), { apply measure_theory.measure.map_congr, exact hg.ae_eq_mk }, have B : map (g ∘ f) μ = map (g' ∘ f) μ, { apply measure_theory.measure.map_congr, exact ae_of_ae_map hf hg.ae_eq_mk }, simp only [A, B, hs, hg.measurable_mk.ae_measurable.comp_ae_measurable hf, hg.measurable_mk, hg.measurable_mk hs, hf, map_apply, map_apply_of_ae_measurable], refl, end @[measurability] lemma prod_mk {f : α → β} {g : α → γ} (hf : ae_measurable f μ) (hg : ae_measurable g μ) : ae_measurable (λ x, (f x, g x)) μ := ⟨λ a, (hf.mk f a, hg.mk g a), hf.measurable_mk.prod_mk hg.measurable_mk, eventually_eq.prod_mk hf.ae_eq_mk hg.ae_eq_mk⟩ lemma exists_ae_eq_range_subset (H : ae_measurable f μ) {t : set β} (ht : ∀ᵐ x ∂μ, f x ∈ t) (h₀ : t.nonempty) : ∃ g, measurable g ∧ range g ⊆ t ∧ f =ᵐ[μ] g := begin let s : set α := to_measurable μ {x | f x = H.mk f x ∧ f x ∈ t}ᶜ, let g : α → β := piecewise s (λ x, h₀.some) (H.mk f), refine ⟨g, _, _, _⟩, { exact measurable.piecewise (measurable_set_to_measurable _ _) measurable_const H.measurable_mk }, { rintros _ ⟨x, rfl⟩, by_cases hx : x ∈ s, { simpa [g, hx] using h₀.some_mem }, { simp only [g, hx, piecewise_eq_of_not_mem, not_false_iff], contrapose! hx, apply subset_to_measurable, simp only [hx, mem_compl_iff, mem_set_of_eq, not_and, not_false_iff, implies_true_iff] {contextual := tt} } }, { have A : μ (to_measurable μ {x | f x = H.mk f x ∧ f x ∈ t}ᶜ) = 0, { rw [measure_to_measurable, ← compl_mem_ae_iff, compl_compl], exact H.ae_eq_mk.and ht }, filter_upwards [compl_mem_ae_iff.2 A] with x hx, rw mem_compl_iff at hx, simp only [g, hx, piecewise_eq_of_not_mem, not_false_iff], contrapose! hx, apply subset_to_measurable, simp only [hx, mem_compl_iff, mem_set_of_eq, false_and, not_false_iff] } end lemma exists_measurable_nonneg {β} [preorder β] [has_zero β] {mβ : measurable_space β} {f : α → β} (hf : ae_measurable f μ) (f_nn : ∀ᵐ t ∂μ, 0 ≤ f t) : ∃ g, measurable g ∧ 0 ≤ g ∧ f =ᵐ[μ] g := begin obtain ⟨G, hG_meas, hG_mem, hG_ae_eq⟩ := hf.exists_ae_eq_range_subset f_nn ⟨0, le_rfl⟩, exact ⟨G, hG_meas, λ x, hG_mem (mem_range_self x), hG_ae_eq⟩, end lemma subtype_mk (h : ae_measurable f μ) {s : set β} {hfs : ∀ x, f x ∈ s} : ae_measurable (cod_restrict f s hfs) μ := begin nontriviality α, inhabit α, obtain ⟨g, g_meas, hg, fg⟩ : ∃ (g : α → β), measurable g ∧ range g ⊆ s ∧ f =ᵐ[μ] g := h.exists_ae_eq_range_subset (eventually_of_forall hfs) ⟨_, hfs default⟩, refine ⟨cod_restrict g s (λ x, hg (mem_range_self _)), measurable.subtype_mk g_meas, _⟩, filter_upwards [fg] with x hx, simpa [subtype.ext_iff], end protected lemma null_measurable (h : ae_measurable f μ) : null_measurable f μ := let ⟨g, hgm, hg⟩ := h in hgm.null_measurable.congr hg.symm end ae_measurable lemma ae_measurable_interval_oc_iff [linear_order α] {f : α → β} {a b : α} : (ae_measurable f $ μ.restrict $ Ι a b) ↔ (ae_measurable f $ μ.restrict $ Ioc a b) ∧ (ae_measurable f $ μ.restrict $ Ioc b a) := by rw [interval_oc_eq_union, ae_measurable_union_iff] lemma ae_measurable_iff_measurable [μ.is_complete] : ae_measurable f μ ↔ measurable f := ⟨λ h, h.null_measurable.measurable_of_complete, λ h, h.ae_measurable⟩ lemma measurable_embedding.ae_measurable_map_iff {g : β → γ} (hf : measurable_embedding f) : ae_measurable g (μ.map f) ↔ ae_measurable (g ∘ f) μ := begin refine ⟨λ H, H.comp_measurable hf.measurable, _⟩, rintro ⟨g₁, hgm₁, heq⟩, rcases hf.exists_measurable_extend hgm₁ (λ x, ⟨g x⟩) with ⟨g₂, hgm₂, rfl⟩, exact ⟨g₂, hgm₂, hf.ae_map_iff.2 heq⟩ end lemma measurable_embedding.ae_measurable_comp_iff {g : β → γ} (hg : measurable_embedding g) {μ : measure α} : ae_measurable (g ∘ f) μ ↔ ae_measurable f μ := begin refine ⟨λ H, _, hg.measurable.comp_ae_measurable⟩, suffices : ae_measurable ((range_splitting g ∘ range_factorization g) ∘ f) μ, by rwa [(right_inverse_range_splitting hg.injective).comp_eq_id] at this, exact hg.measurable_range_splitting.comp_ae_measurable H.subtype_mk end lemma ae_measurable_restrict_iff_comap_subtype {s : set α} (hs : measurable_set s) {μ : measure α} {f : α → β} : ae_measurable f (μ.restrict s) ↔ ae_measurable (f ∘ coe : s → β) (comap coe μ) := by rw [← map_comap_subtype_coe hs, (measurable_embedding.subtype_coe hs).ae_measurable_map_iff] @[simp, to_additive] lemma ae_measurable_one [has_one β] : ae_measurable (λ a : α, (1 : β)) μ := measurable_one.ae_measurable @[simp] lemma ae_measurable_smul_measure_iff {c : ℝ≥0∞} (hc : c ≠ 0) : ae_measurable f (c • μ) ↔ ae_measurable f μ := ⟨λ h, ⟨h.mk f, h.measurable_mk, (ae_smul_measure_iff hc).1 h.ae_eq_mk⟩, λ h, ⟨h.mk f, h.measurable_mk, (ae_smul_measure_iff hc).2 h.ae_eq_mk⟩⟩ lemma ae_measurable_of_ae_measurable_trim {α} {m m0 : measurable_space α} {μ : measure α} (hm : m ≤ m0) {f : α → β} (hf : ae_measurable f (μ.trim hm)) : ae_measurable f μ := ⟨hf.mk f, measurable.mono hf.measurable_mk hm le_rfl, ae_eq_of_ae_eq_trim hf.ae_eq_mk⟩ lemma ae_measurable_restrict_of_measurable_subtype {s : set α} (hs : measurable_set s) (hf : measurable (λ x : s, f x)) : ae_measurable f (μ.restrict s) := (ae_measurable_restrict_iff_comap_subtype hs).2 hf.ae_measurable lemma ae_measurable_map_equiv_iff (e : α ≃ᵐ β) {f : β → γ} : ae_measurable f (μ.map e) ↔ ae_measurable (f ∘ e) μ := e.measurable_embedding.ae_measurable_map_iff end lemma ae_measurable.restrict (hfm : ae_measurable f μ) {s} : ae_measurable f (μ.restrict s) := ⟨ae_measurable.mk f hfm, hfm.measurable_mk, ae_restrict_of_ae hfm.ae_eq_mk⟩ lemma ae_measurable_Ioi_of_forall_Ioc {β} {mβ : measurable_space β} [linear_order α] [(at_top : filter α).is_countably_generated] {x : α} {g : α → β} (g_meas : ∀ t > x, ae_measurable g (μ.restrict (Ioc x t))) : ae_measurable g (μ.restrict (Ioi x)) := begin haveI : nonempty α := ⟨x⟩, haveI : (at_top : filter α).ne_bot := at_top_ne_bot, obtain ⟨u, hu_tendsto⟩ := exists_seq_tendsto (at_top : filter α), have Ioi_eq_Union : Ioi x = ⋃ n : ℕ, Ioc x (u n), { rw Union_Ioc_eq_Ioi_self_iff.mpr _, rw tendsto_at_top_at_top at hu_tendsto, exact λ y _, ⟨(hu_tendsto y).some, (hu_tendsto y).some_spec (hu_tendsto y).some le_rfl⟩, }, rw [Ioi_eq_Union, ae_measurable_Union_iff], intros n, cases lt_or_le x (u n), { exact g_meas (u n) h, }, { rw Ioc_eq_empty (not_lt.mpr h), simp only [measure.restrict_empty], exact ae_measurable_zero_measure, }, end variables [has_zero β] lemma ae_measurable_indicator_iff {s} (hs : measurable_set s) : ae_measurable (indicator s f) μ ↔ ae_measurable f (μ.restrict s) := begin split, { intro h, exact (h.mono_measure measure.restrict_le_self).congr (indicator_ae_eq_restrict hs) }, { intro h, refine ⟨indicator s (h.mk f), h.measurable_mk.indicator hs, _⟩, have A : s.indicator f =ᵐ[μ.restrict s] s.indicator (ae_measurable.mk f h) := (indicator_ae_eq_restrict hs).trans (h.ae_eq_mk.trans $ (indicator_ae_eq_restrict hs).symm), have B : s.indicator f =ᵐ[μ.restrict sᶜ] s.indicator (ae_measurable.mk f h) := (indicator_ae_eq_restrict_compl hs).trans (indicator_ae_eq_restrict_compl hs).symm, exact ae_of_ae_restrict_of_ae_restrict_compl _ A B }, end @[measurability] lemma ae_measurable.indicator (hfm : ae_measurable f μ) {s} (hs : measurable_set s) : ae_measurable (s.indicator f) μ := (ae_measurable_indicator_iff hs).mpr hfm.restrict lemma measure_theory.measure.restrict_map_of_ae_measurable {f : α → δ} (hf : ae_measurable f μ) {s : set δ} (hs : measurable_set s) : (μ.map f).restrict s = (μ.restrict $ f ⁻¹' s).map f := calc (μ.map f).restrict s = (μ.map (hf.mk f)).restrict s : by { congr' 1, apply measure.map_congr hf.ae_eq_mk } ... = (μ.restrict $ (hf.mk f) ⁻¹' s).map (hf.mk f) : measure.restrict_map hf.measurable_mk hs ... = (μ.restrict $ (hf.mk f) ⁻¹' s).map f : measure.map_congr (ae_restrict_of_ae (hf.ae_eq_mk.symm)) ... = (μ.restrict $ f ⁻¹' s).map f : begin apply congr_arg, ext1 t ht, simp only [ht, measure.restrict_apply], apply measure_congr, apply (eventually_eq.refl _ _).inter (hf.ae_eq_mk.symm.preimage s) end lemma measure_theory.measure.map_mono_of_ae_measurable {f : α → δ} (h : μ ≤ ν) (hf : ae_measurable f ν) : μ.map f ≤ ν.map f := λ s hs, by simpa [hf, hs, hf.mono_measure h] using measure.le_iff'.1 h (f ⁻¹' s)
da38ab45c602ce2b1b091d099c94e2eb1365d570
63abd62053d479eae5abf4951554e1064a4c45b4
/src/analysis/normed_space/finite_dimension.lean
f4fc589728e55e2fe97dd89e86c9d245f3adcae2
[ "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
20,439
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import analysis.normed_space.operator_norm import topology.bases import linear_algebra.finite_dimensional import tactic.omega /-! # Finite dimensional normed spaces over complete fields Over a complete nondiscrete field, in finite dimension, all norms are equivalent and all linear maps are continuous. Moreover, a finite-dimensional subspace is always complete and closed. ## Main results: * `linear_map.continuous_of_finite_dimensional` : a linear map on a finite-dimensional space over a complete field is continuous. * `finite_dimensional.complete` : a finite-dimensional space over a complete field is complete. This is not registered as an instance, as the field would be an unknown metavariable in typeclass resolution. * `submodule.closed_of_finite_dimensional` : a finite-dimensional subspace over a complete field is closed * `finite_dimensional.proper` : a finite-dimensional space over a proper field is proper. This is not registered as an instance, as the field would be an unknown metavariable in typeclass resolution. It is however registered as an instance for `𝕜 = ℝ` and `𝕜 = ℂ`. As properness implies completeness, there is no need to also register `finite_dimensional.complete` on `ℝ` or `ℂ`. ## Implementation notes The fact that all norms are equivalent is not written explicitly, as it would mean having two norms on a single space, which is not the way type classes work. However, if one has a finite-dimensional vector space `E` with a norm, and a copy `E'` of this type with another norm, then the identities from `E` to `E'` and from `E'`to `E` are continuous thanks to `linear_map.continuous_of_finite_dimensional`. This gives the desired norm equivalence. -/ universes u v w x open set finite_dimensional topological_space open_locale classical big_operators noncomputable theory /-- A linear map on `ι → 𝕜` (where `ι` is a fintype) is continuous -/ lemma linear_map.continuous_on_pi {ι : Type w} [fintype ι] {𝕜 : Type u} [normed_field 𝕜] {E : Type v} [add_comm_group E] [vector_space 𝕜 E] [topological_space E] [topological_add_group E] [topological_vector_space 𝕜 E] (f : (ι → 𝕜) →ₗ[𝕜] E) : continuous f := begin -- for the proof, write `f` in the standard basis, and use that each coordinate is a continuous -- function. have : (f : (ι → 𝕜) → E) = (λx, ∑ i : ι, x i • (f (λj, if i = j then 1 else 0))), by { ext x, exact f.pi_apply_eq_sum_univ x }, rw this, refine continuous_finset_sum _ (λi hi, _), exact (continuous_apply i).smul continuous_const end section complete_field variables {𝕜 : Type u} [nondiscrete_normed_field 𝕜] {E : Type v} [normed_group E] [normed_space 𝕜 E] {F : Type w} [normed_group F] [normed_space 𝕜 F] {F' : Type x} [add_comm_group F'] [vector_space 𝕜 F'] [topological_space F'] [topological_add_group F'] [topological_vector_space 𝕜 F'] [complete_space 𝕜] /-- In finite dimension over a complete field, the canonical identification (in terms of a basis) with `𝕜^n` together with its sup norm is continuous. This is the nontrivial part in the fact that all norms are equivalent in finite dimension. This statement is superceded by the fact that every linear map on a finite-dimensional space is continuous, in `linear_map.continuous_of_finite_dimensional`. -/ lemma continuous_equiv_fun_basis {ι : Type v} [fintype ι] (ξ : ι → E) (hξ : is_basis 𝕜 ξ) : continuous hξ.equiv_fun := begin unfreezingI { induction hn : fintype.card ι with n IH generalizing ι E }, { apply linear_map.continuous_of_bound _ 0 (λx, _), have : hξ.equiv_fun x = 0, by { ext i, exact (fintype.card_eq_zero_iff.1 hn i).elim }, change ∥hξ.equiv_fun x∥ ≤ 0 * ∥x∥, rw this, simp [norm_nonneg] }, { haveI : finite_dimensional 𝕜 E := of_fintype_basis hξ, -- first step: thanks to the inductive assumption, any n-dimensional subspace is equivalent -- to a standard space of dimension n, hence it is complete and therefore closed. have H₁ : ∀s : submodule 𝕜 E, findim 𝕜 s = n → is_closed (s : set E), { assume s s_dim, rcases exists_is_basis_finite 𝕜 s with ⟨b, b_basis, b_finite⟩, letI : fintype b := finite.fintype b_finite, have U : uniform_embedding b_basis.equiv_fun.symm.to_equiv, { have : fintype.card b = n, by { rw ← s_dim, exact (findim_eq_card_basis b_basis).symm }, have : continuous b_basis.equiv_fun := IH (subtype.val : b → s) b_basis this, exact b_basis.equiv_fun.symm.uniform_embedding (linear_map.continuous_on_pi _) this }, have : is_complete (s : set E), from complete_space_coe_iff_is_complete.1 ((complete_space_congr U).1 (by apply_instance)), exact this.is_closed }, -- second step: any linear form is continuous, as its kernel is closed by the first step have H₂ : ∀f : E →ₗ[𝕜] 𝕜, continuous f, { assume f, have : findim 𝕜 f.ker = n ∨ findim 𝕜 f.ker = n.succ, { have Z := f.findim_range_add_findim_ker, rw [findim_eq_card_basis hξ, hn] at Z, have : findim 𝕜 f.range = 0 ∨ findim 𝕜 f.range = 1, { have I : ∀(k : ℕ), k ≤ 1 ↔ k = 0 ∨ k = 1, by omega manual, have : findim 𝕜 f.range ≤ findim 𝕜 𝕜 := submodule.findim_le _, rwa [findim_of_field, I] at this }, cases this, { rw this at Z, right, simpa using Z }, { left, rw [this, add_comm, nat.add_one] at Z, exact nat.succ.inj Z } }, have : is_closed (f.ker : set E), { cases this, { exact H₁ _ this }, { have : f.ker = ⊤, by { apply eq_top_of_findim_eq, rw [findim_eq_card_basis hξ, hn, this] }, simp [this] } }, exact linear_map.continuous_iff_is_closed_ker.2 this }, -- third step: applying the continuity to the linear form corresponding to a coefficient in the -- basis decomposition, deduce that all such coefficients are controlled in terms of the norm have : ∀i:ι, ∃C, 0 ≤ C ∧ ∀(x:E), ∥hξ.equiv_fun x i∥ ≤ C * ∥x∥, { assume i, let f : E →ₗ[𝕜] 𝕜 := (linear_map.proj i).comp hξ.equiv_fun, let f' : E →L[𝕜] 𝕜 := { cont := H₂ f, ..f }, exact ⟨∥f'∥, norm_nonneg _, λx, continuous_linear_map.le_op_norm f' x⟩ }, -- fourth step: combine the bound on each coefficient to get a global bound and the continuity choose C0 hC0 using this, let C := ∑ i, C0 i, have C_nonneg : 0 ≤ C := finset.sum_nonneg (λi hi, (hC0 i).1), have C0_le : ∀i, C0 i ≤ C := λi, finset.single_le_sum (λj hj, (hC0 j).1) (finset.mem_univ _), apply linear_map.continuous_of_bound _ C (λx, _), rw pi_norm_le_iff, { exact λi, le_trans ((hC0 i).2 x) (mul_le_mul_of_nonneg_right (C0_le i) (norm_nonneg _)) }, { exact mul_nonneg C_nonneg (norm_nonneg _) } } end /-- Any linear map on a finite dimensional space over a complete field is continuous. -/ theorem linear_map.continuous_of_finite_dimensional [finite_dimensional 𝕜 E] (f : E →ₗ[𝕜] F') : continuous f := begin -- for the proof, go to a model vector space `b → 𝕜` thanks to `continuous_equiv_fun_basis`, and -- argue that all linear maps there are continuous. rcases exists_is_basis_finite 𝕜 E with ⟨b, b_basis, b_finite⟩, letI : fintype b := finite.fintype b_finite, have A : continuous b_basis.equiv_fun := continuous_equiv_fun_basis _ b_basis, have B : continuous (f.comp (b_basis.equiv_fun.symm : (b → 𝕜) →ₗ[𝕜] E)) := linear_map.continuous_on_pi _, have : continuous ((f.comp (b_basis.equiv_fun.symm : (b → 𝕜) →ₗ[𝕜] E)) ∘ b_basis.equiv_fun) := B.comp A, convert this, ext x, dsimp, rw linear_equiv.symm_apply_apply end /-- The continuous linear map induced by a linear map on a finite dimensional space -/ def linear_map.to_continuous_linear_map [finite_dimensional 𝕜 E] (f : E →ₗ[𝕜] F') : E →L[𝕜] F' := { cont := f.continuous_of_finite_dimensional, ..f } /-- The continuous linear equivalence induced by a linear equivalence on a finite dimensional space. -/ def linear_equiv.to_continuous_linear_equiv [finite_dimensional 𝕜 E] (e : E ≃ₗ[𝕜] F) : E ≃L[𝕜] F := { continuous_to_fun := e.to_linear_map.continuous_of_finite_dimensional, continuous_inv_fun := begin haveI : finite_dimensional 𝕜 F := e.finite_dimensional, exact e.symm.to_linear_map.continuous_of_finite_dimensional end, ..e } variables {ι : Type*} [fintype ι] /-- Construct a continuous linear map given the value at a finite basis. -/ def is_basis.constrL {v : ι → E} (hv : is_basis 𝕜 v) (f : ι → F) : E →L[𝕜] F := by haveI : finite_dimensional 𝕜 E := finite_dimensional.of_fintype_basis hv; exact (hv.constr f).to_continuous_linear_map @[simp, norm_cast] lemma is_basis.coe_constrL {v : ι → E} (hv : is_basis 𝕜 v) (f : ι → F) : (hv.constrL f : E →ₗ[𝕜] F) = hv.constr f := rfl /-- The continuous linear equivalence between a vector space over `𝕜` with a finite basis and functions from its basis indexing type to `𝕜`. -/ def is_basis.equiv_funL {v : ι → E} (hv : is_basis 𝕜 v) : E ≃L[𝕜] (ι → 𝕜) := { continuous_to_fun := begin haveI : finite_dimensional 𝕜 E := finite_dimensional.of_fintype_basis hv, apply linear_map.continuous_of_finite_dimensional, end, continuous_inv_fun := begin change continuous hv.equiv_fun.symm.to_fun, apply linear_map.continuous_of_finite_dimensional, end, ..hv.equiv_fun } @[simp] lemma is_basis.constrL_apply {v : ι → E} (hv : is_basis 𝕜 v) (f : ι → F) (e : E) : (hv.constrL f) e = ∑ i, (hv.equiv_fun e i) • f i := hv.constr_apply_fintype _ _ @[simp] lemma is_basis.constrL_basis {v : ι → E} (hv : is_basis 𝕜 v) (f : ι → F) (i : ι) : (hv.constrL f) (v i) = f i := constr_basis _ lemma is_basis.sup_norm_le_norm {v : ι → E} (hv : is_basis 𝕜 v) : ∃ C > (0 : ℝ), ∀ e : E, ∑ i, ∥hv.equiv_fun e i∥ ≤ C * ∥e∥ := begin set φ := hv.equiv_funL.to_continuous_linear_map, set C := ∥φ∥ * (fintype.card ι), use [max C 1, lt_of_lt_of_le (zero_lt_one) (le_max_right C 1)], intros e, calc ∑ i, ∥φ e i∥ ≤ ∑ i : ι, ∥φ e∥ : by { apply finset.sum_le_sum, exact λ i hi, norm_le_pi_norm (φ e) i } ... = ∥φ e∥*(fintype.card ι) : by simpa only [mul_comm, finset.sum_const, nsmul_eq_mul] ... ≤ ∥φ∥ * ∥e∥ * (fintype.card ι) : mul_le_mul_of_nonneg_right (φ.le_op_norm e) (fintype.card ι).cast_nonneg ... = ∥φ∥ * (fintype.card ι) * ∥e∥ : by ring ... ≤ max C 1 * ∥e∥ : mul_le_mul_of_nonneg_right (le_max_left _ _) (norm_nonneg _) end lemma is_basis.op_norm_le {ι : Type*} [fintype ι] {v : ι → E} (hv : is_basis 𝕜 v) : ∃ C > (0 : ℝ), ∀ {u : E →L[𝕜] F} {M : ℝ}, 0 ≤ M → (∀ i, ∥u (v i)∥ ≤ M) → ∥u∥ ≤ C*M := begin obtain ⟨C, C_pos, hC⟩ : ∃ C > (0 : ℝ), ∀ (e : E), ∑ i, ∥hv.equiv_fun e i∥ ≤ C * ∥e∥, from hv.sup_norm_le_norm, use [C, C_pos], intros u M hM hu, apply u.op_norm_le_bound (mul_nonneg (le_of_lt C_pos) hM), intros e, calc ∥u e∥ = ∥u (∑ i, hv.equiv_fun e i • v i)∥ : by conv_lhs { rw ← hv.equiv_fun_total e } ... = ∥∑ i, (hv.equiv_fun e i) • (u $ v i)∥ : by simp [u.map_sum, linear_map.map_smul] ... ≤ ∑ i, ∥(hv.equiv_fun e i) • (u $ v i)∥ : norm_sum_le _ _ ... = ∑ i, ∥hv.equiv_fun e i∥ * ∥u (v i)∥ : by simp only [norm_smul] ... ≤ ∑ i, ∥hv.equiv_fun e i∥ * M : finset.sum_le_sum (λ i hi, mul_le_mul_of_nonneg_left (hu i) (norm_nonneg _)) ... = (∑ i, ∥hv.equiv_fun e i∥) * M : finset.sum_mul.symm ... ≤ C * ∥e∥ * M : mul_le_mul_of_nonneg_right (hC e) hM ... = C * M * ∥e∥ : by ring end instance [finite_dimensional 𝕜 E] [second_countable_topology F] : second_countable_topology (E →L[𝕜] F) := begin set d := finite_dimensional.findim 𝕜 E, suffices : ∀ ε > (0 : ℝ), ∃ n : (E →L[𝕜] F) → fin d → ℕ, ∀ (f g : E →L[𝕜] F), n f = n g → dist f g ≤ ε, from metric.second_countable_of_countable_discretization (λ ε ε_pos, ⟨fin d → ℕ, by apply_instance, this ε ε_pos⟩), intros ε ε_pos, obtain ⟨u : ℕ → F, hu : dense_range u⟩ := exists_dense_seq F, obtain ⟨v : fin d → E, hv : is_basis 𝕜 v⟩ := finite_dimensional.fin_basis 𝕜 E, obtain ⟨C : ℝ, C_pos : 0 < C, hC : ∀ {φ : E →L[𝕜] F} {M : ℝ}, 0 ≤ M → (∀ i, ∥φ (v i)∥ ≤ M) → ∥φ∥ ≤ C * M⟩ := hv.op_norm_le, have h_2C : 0 < 2*C := mul_pos zero_lt_two C_pos, have hε2C : 0 < ε/(2*C) := div_pos ε_pos h_2C, have : ∀ φ : E →L[𝕜] F, ∃ n : fin d → ℕ, ∥φ - (hv.constrL $ u ∘ n)∥ ≤ ε/2, { intros φ, have : ∀ i, ∃ n, ∥φ (v i) - u n∥ ≤ ε/(2*C), { simp only [norm_sub_rev], intro i, have : φ (v i) ∈ closure (range u) := hu _, obtain ⟨n, hn⟩ : ∃ n, ∥u n - φ (v i)∥ < ε / (2 * C), { rw mem_closure_iff_nhds_basis metric.nhds_basis_ball at this, specialize this (ε/(2*C)) hε2C, simpa [dist_eq_norm] }, exact ⟨n, le_of_lt hn⟩ }, choose n hn using this, use n, replace hn : ∀ i : fin d, ∥(φ - (hv.constrL $ u ∘ n)) (v i)∥ ≤ ε / (2 * C), by simp [hn], have : C * (ε / (2 * C)) = ε/2, { rw [eq_div_iff (two_ne_zero : (2 : ℝ) ≠ 0), mul_comm, ← mul_assoc, mul_div_cancel' _ (ne_of_gt h_2C)] }, specialize hC (le_of_lt hε2C) hn, rwa this at hC }, choose n hn using this, set Φ := λ φ : E →L[𝕜] F, (hv.constrL $ u ∘ (n φ)), change ∀ z, dist z (Φ z) ≤ ε/2 at hn, use n, intros x y hxy, calc dist x y ≤ dist x (Φ x) + dist (Φ x) y : dist_triangle _ _ _ ... = dist x (Φ x) + dist y (Φ y) : by simp [Φ, hxy, dist_comm] ... ≤ ε : by linarith [hn x, hn y] end /-- Any finite-dimensional vector space over a complete field is complete. We do not register this as an instance to avoid an instance loop when trying to prove the completeness of `𝕜`, and the search for `𝕜` as an unknown metavariable. Declare the instance explicitly when needed. -/ variables (𝕜 E) lemma finite_dimensional.complete [finite_dimensional 𝕜 E] : complete_space E := begin rcases exists_is_basis_finite 𝕜 E with ⟨b, b_basis, b_finite⟩, letI : fintype b := finite.fintype b_finite, have : uniform_embedding b_basis.equiv_fun.symm := linear_equiv.uniform_embedding _ (linear_map.continuous_of_finite_dimensional _) (linear_map.continuous_of_finite_dimensional _), change uniform_embedding b_basis.equiv_fun.symm.to_equiv at this, exact (complete_space_congr this).1 (by apply_instance) end variables {𝕜 E} /-- A finite-dimensional subspace is complete. -/ lemma submodule.complete_of_finite_dimensional (s : submodule 𝕜 E) [finite_dimensional 𝕜 s] : is_complete (s : set E) := complete_space_coe_iff_is_complete.1 (finite_dimensional.complete 𝕜 s) /-- A finite-dimensional subspace is closed. -/ lemma submodule.closed_of_finite_dimensional (s : submodule 𝕜 E) [finite_dimensional 𝕜 s] : is_closed (s : set E) := s.complete_of_finite_dimensional.is_closed lemma continuous_linear_map.exists_right_inverse_of_surjective [finite_dimensional 𝕜 F] (f : E →L[𝕜] F) (hf : f.range = ⊤) : ∃ g : F →L[𝕜] E, f.comp g = continuous_linear_map.id 𝕜 F := let ⟨g, hg⟩ := (f : E →ₗ[𝕜] F).exists_right_inverse_of_surjective hf in ⟨g.to_continuous_linear_map, continuous_linear_map.ext $ linear_map.ext_iff.1 hg⟩ lemma closed_embedding_smul_left {c : E} (hc : c ≠ 0) : closed_embedding (λ x : 𝕜, x • c) := begin haveI : finite_dimensional 𝕜 (submodule.span 𝕜 {c}) := finite_dimensional.span_of_finite 𝕜 (finite_singleton c), have m1 : closed_embedding (coe : submodule.span 𝕜 {c} → E) := (submodule.span 𝕜 {c}).closed_of_finite_dimensional.closed_embedding_subtype_coe, have m2 : closed_embedding (linear_equiv.to_span_nonzero_singleton 𝕜 E c hc : 𝕜 → submodule.span 𝕜 {c}) := (continuous_linear_equiv.to_span_nonzero_singleton 𝕜 c hc).to_homeomorph.closed_embedding, exact m1.comp m2 end /- `smul` is a closed map in the first argument. -/ lemma is_closed_map_smul_left (c : E) : is_closed_map (λ x : 𝕜, x • c) := begin by_cases hc : c = 0, { simp_rw [hc, smul_zero], exact is_closed_map_const }, { exact (closed_embedding_smul_left hc).is_closed_map } end end complete_field section proper_field variables (𝕜 : Type u) [nondiscrete_normed_field 𝕜] (E : Type v) [normed_group E] [normed_space 𝕜 E] [proper_space 𝕜] /-- Any finite-dimensional vector space over a proper field is proper. We do not register this as an instance to avoid an instance loop when trying to prove the properness of `𝕜`, and the search for `𝕜` as an unknown metavariable. Declare the instance explicitly when needed. -/ lemma finite_dimensional.proper [finite_dimensional 𝕜 E] : proper_space E := begin rcases exists_is_basis_finite 𝕜 E with ⟨b, b_basis, b_finite⟩, letI : fintype b := finite.fintype b_finite, let e := b_basis.equiv_fun, let f : E →L[𝕜] (b → 𝕜) := { cont := linear_map.continuous_of_finite_dimensional _, ..e.to_linear_map }, refine metric.proper_image_of_proper e.symm (linear_map.continuous_of_finite_dimensional _) _ (∥f∥) (λx y, _), { exact equiv.range_eq_univ e.symm.to_equiv }, { have A : e (e.symm x) = x := linear_equiv.apply_symm_apply _ _, have B : e (e.symm y) = y := linear_equiv.apply_symm_apply _ _, conv_lhs { rw [← A, ← B] }, change dist (f (e.symm x)) (f (e.symm y)) ≤ ∥f∥ * dist (e.symm x) (e.symm y), unfreezingI { exact f.lipschitz.dist_le_mul _ _ } } end end proper_field /- Over the real numbers, we can register the previous statement as an instance as it will not cause problems in instance resolution since the properness of `ℝ` is already known. -/ instance finite_dimensional.proper_real (E : Type u) [normed_group E] [normed_space ℝ E] [finite_dimensional ℝ E] : proper_space E := finite_dimensional.proper ℝ E attribute [instance, priority 900] finite_dimensional.proper_real /-- In a finite dimensional vector space over `ℝ`, the series `∑ x, ∥f x∥` is unconditionally summable if and only if the series `∑ x, f x` is unconditionally summable. One implication holds in any complete normed space, while the other holds only in finite dimensional spaces. -/ lemma summable_norm_iff {α E : Type*} [normed_group E] [normed_space ℝ E] [finite_dimensional ℝ E] {f : α → E} : summable (λ x, ∥f x∥) ↔ summable f := begin refine ⟨summable_of_summable_norm, λ hf, _⟩, -- First we use a finite basis to reduce the problem to the case `E = fin N → ℝ` suffices : ∀ {N : ℕ} {g : α → fin N → ℝ}, summable g → summable (λ x, ∥g x∥), { rcases fin_basis ℝ E with ⟨v, hv⟩, set e := hv.equiv_funL, have : summable (λ x, ∥e (f x)∥) := this (e.summable.2 hf), refine summable_of_norm_bounded _ (this.mul_left ↑(nnnorm (e.symm : (fin (findim ℝ E) → ℝ) →L[ℝ] E))) (λ i, _), simpa using (e.symm : (fin (findim ℝ E) → ℝ) →L[ℝ] E).le_op_norm (e $ f i) }, unfreezingI { clear_dependent E }, -- Now we deal with `g : α → fin N → ℝ` intros N g hg, have : ∀ i, summable (λ x, ∥g x i∥) := λ i, (pi.summable.1 hg i).abs, refine summable_of_norm_bounded _ (summable_sum (λ i (hi : i ∈ finset.univ), this i)) (λ x, _), rw [norm_norm, pi_norm_le_iff], { refine λ i, finset.single_le_sum (λ i hi, _) (finset.mem_univ i), exact norm_nonneg (g x i) }, { exact finset.sum_nonneg (λ _ _, norm_nonneg _) } end
4d7cb9e836c40d3a4c4f18ca6f2c75f8e8c8f6a7
ce6917c5bacabee346655160b74a307b4a5ab620
/src/ch5/ex0107.lean
eec37f2657efbad38e4e3b5c67a7de7ce90b69ff
[]
no_license
Ailrun/Theorem_Proving_in_Lean
ae6a23f3c54d62d401314d6a771e8ff8b4132db2
2eb1b5caf93c6a5a555c79e9097cf2ba5a66cf68
refs/heads/master
1,609,838,270,467
1,586,846,743,000
1,586,846,743,000
240,967,761
1
0
null
null
null
null
UTF-8
Lean
false
false
105
lean
theorem test (p q : Prop) (hp : p) (hq : q) : p ∧ q ∧ p := by exact and.intro hp (and.intro hq hp)
a2d0d48c7b5e3ae2fdd1104a617e2c35c3e51b17
457f81fc5fdc4314d484cd7eec72126cf2a780dc
/myfirst.lean
d5b5215ee89d191fbddf3bd9bb544cbadcb2e665
[]
no_license
hyeyoungshin/LEAN
51d49c84342f67147a6769b8da693057a76a9fa4
c708f97179ca693a6beb9b808335af1db3bf17a4
refs/heads/master
1,584,404,806,178
1,526,102,802,000
1,526,102,802,000
133,116,781
0
0
null
null
null
null
UTF-8
Lean
false
false
1,604
lean
/- Lean is an implementation of a logical foundation known as dependent type theory. Specifically, it implements a version of dependent type theory known as the Calculus of Inductive Constructions. Dependent type theory serves as a foundational language, allowing us to describe all sorts of objects and prove things about them. The foundational language fixes the meaning of the objects we introduce, and the small carefully written kernel "type checks" these objects, meaning it ensures the things we prove are correct. -/ a#check "hello world!" inductive nat : Type | zero : nat | succ : nat -> nat def add : nat -> nat -> nat | m nat.zero := m | m (nat.succ n) := nat.succ (add m n) def double (n : ℕ) : ℕ := n + n #check (27 + 9) * 33 #check[(1,2), (3,4), (5,6)] ++ [(7,8), (9,10)] #check double #print double /- Lean can reason about abstract objects as well as it can reason about concrete ones. Putting the declarations in a `section` delimits their scope. -/ section variables (G : Type) [group G] variables g1 g2 : G #check g2^-1 * g1 * g2 end /- An important feature of dependent type theory is that every expression has a computational interpretation, which is to say, there are rules that specify how they can be *reduced* to a normal form. Moreover, expressions in a computationally pure fragment of the language evaluate to values in the way you would expect. For example, assuming the definition does not depend on nonconstructive components in an essential way, every closed term of type ℕ evalutates to a numeral. -/ #eval (27+9)*33
b96ce73685f2483e9f3100d747f050a1337e6164
d8820d2c92be8052d13f9c8f8c483a6e15c5f566
/src/M40002/complete.lean
be0a169ec331acd6dbbf97d247d455eb3db8f942
[]
no_license
JasonKYi/M4000x_LEAN_formalisation
4a19b84f6d0fe2e214485b8532e21cd34996c4b1
6e99793f2fcbe88596e27644f430e46aa2a464df
refs/heads/master
1,599,755,414,708
1,589,494,604,000
1,589,494,604,000
221,759,483
8
1
null
1,589,494,605,000
1,573,755,201,000
Lean
UTF-8
Lean
false
false
8,554
lean
-- begin header import M40002.countability namespace completeness variables {X Y : Type} -- end header /- Sub-section The Completeness Axiom -/ /- Theorem If a set $S ⊂ ℝ$ has maximums $a$ and $b$, then $a = b$, i.e. the maximum of a set is unique. -/ theorem unique_max (S : set ℝ) : ∀ a b ∈ S, (∀ x ∈ S, x ≤ a ∧ x ≤ b) → a = b := begin intros a b ha hb hc, have : a ≤ b := (hc a ha).right, cases lt_or_eq_of_le this, {have : b ≤ a := (hc b hb).left, rw ←not_lt at this, contradiction }, {assumption} end /- Theorem If a set $S ⊂ ℝ$ has minimums $a$ and $b$, then $a = b$, i.e. the minimum of a set is unique. -/ theorem neg_set_min (S : set ℝ) (s : ℝ) (h0 : s ∈ S) (h1 : ∀ x ∈ S, x ≤ s): ∀ x ∈ {t : ℝ | -t ∈ S}, -s ≤ x ∧ -s ∈ {t : ℝ | -t ∈ S} := begin intros x hx, split, {rwa neg_le, rw set.mem_set_of_eq at hx, apply h1, assumption }, {rwa set.mem_set_of_eq, simpa } end /- Definition A set $S ⊂ ℝ$ is bounded above if and only if $∃ M ∈ ℝ, ∀ s ∈ S, s ≤ M$ -/ def bounded_above (S : set ℝ) := ∃ M : ℝ, ∀ s ∈ S, s ≤ M /- Definition We call $M$ a upper bound of $S ⊂ ℝ$ if and only if $∀ s ∈ S, s ≤ M$. -/ def upper_bound (S : set ℝ) (M : ℝ) := ∀ s ∈ S, s ≤ M /- We can deduce some properties straight away from these definitions. -/ /- Corollary A set $S ⊂ ℝ$ is bounded above if and only if there exists a $M ∈ ℝ$, $M$ is an upper bound of $S$ -/ theorem bdd_above_iff_have_upr_bd (S : set ℝ) : (∃ M : ℝ, upper_bound S M) ↔ bounded_above S := by {split, all_goals {rintro ⟨M, hM⟩, use M, assumption} } /- Corollary If $S$ has an upperbound $M$, then $∀ x ∈ R, x ≥ M$ implies $x$ is a upper bound of $S$ -/ theorem bigger_upperbound (S : set ℝ) (s : ℝ) (h : upper_bound S s) : ∀ x : ℝ, s ≤ x → upper_bound S x := by {intros x hx y hy, from le_trans (h y hy) hx} /- We will define lower bounds and bounded below in a similar fashion. -/ /- Definition A set $S ⊂ ℝ$ is bounded below if and only if $∃ M ∈ ℝ, ∀ s ∈ S, s ≥ M$ -/ def bounded_below (S : set ℝ) := ∃ M : ℝ, ∀ s ∈ S, M ≤ s /- Definition We call $M$ a lower bound of $S ⊂ ℝ$ if and only if $∀ s ∈ S, s ≥ M$. -/ def lower_bound (S : set ℝ) (M : ℝ) := ∀ s ∈ S, M ≤ s /- Corollary A set $S ⊂ ℝ$ is bounded below if and only if there exists a $M ∈ ℝ$, $M$ is an lower bound of $S$ -/ theorem bdd_below_iff_have_lwr_bd (S : set ℝ) : (∃ M : ℝ, lower_bound S M) ↔ bounded_below S := by {split, all_goals {rintro ⟨M, hM⟩, use M, assumption} } /- Exercise If $s ∈ ℝ$ is an upper bound of a set $S ⊂ ℝ$, then $-s$ is a lower bound of the set ${t ∈ ℝ | -t ∈ S}$. -/ theorem upr_bd_neg_set_lwr_bd (S : set ℝ) (s : ℝ) : upper_bound S s ↔ lower_bound {t : ℝ | -t ∈ S} (-s) := begin split, all_goals {intros h x hx}, {rw set.mem_set_of_eq at hx, suffices : (-x) ≤ s, rwa neg_le, from h (-x) hx }, unfold lower_bound at h, suffices : (-s) ≤ (-x), simp at this, assumption, have : (-x) ∈ {t : ℝ | -t ∈ S} := by {rwa set.mem_set_of_eq, simp, assumption}, from h (-x) this end /- Definition We call a set $S ⊂ ℝ$ bounded if it is bounded above and below. -/ def bounded (S : set ℝ) := bounded_above S ∧ bounded_below S -- Okay, so I've switched around the definition of supremums but dw, the two definitions are equiv. def sup (S : set ℝ) (x : ℝ) := upper_bound S x ∧ (∀ y : ℝ, y < x → ¬ (upper_bound S y)) -- Check out sup_def for the definition from the lecture notes def inf (S : set ℝ) (x : ℝ) := lower_bound S x ∧ (∀ y : ℝ, x < y → ¬ (lower_bound S y)) -- Exercise 2.24 theorem unique_sup (S : set ℝ) : ∀ a b ∈ S, sup S a ∧ sup S b → a = b := begin rintros a b ha hb ⟨⟨bda, supa⟩, ⟨bdb,supb⟩⟩, have hc : ∀ s ∈ S, s ≤ a ∧ s ≤ b := by {intros s hs, from ⟨bda s hs, bdb s hs⟩}, from unique_max S a b ha hb hc end theorem sup_non_empty (S : set ℝ) (s : ℝ) (h : sup S s) : S ≠ ∅ := begin cases h with ha hb, intro, have hc : upper_bound S (s - 1) := by {intros x hx, rw a at hx, simp at hx, contradiction }, have hd : s - 1 < s := by linarith, replace hb : ¬ upper_bound S (s - 1) := by {apply hb (s - 1) hd}, contradiction end theorem neg_set_inf (S : set ℝ) (s : ℝ) (h : sup S s) : inf {t : ℝ | -t ∈ S} (-s) := begin cases h with hbd hlub, split, {intros x hx, apply classical.by_contradiction, intro h, push_neg at h, have : -s ≤ x := by {rw neg_le, from (hbd (-x) hx)}, apply not_le_of_lt h, assumption }, {intros y hy hlbd, have : upper_bound S (-y) := by {intros x hx, apply classical.by_contradiction, intro h, push_neg at h, unfold lower_bound at hlbd, have : y ≤ -x := by {replace hx : -x ∈ {t : ℝ | -t ∈ S}, rw set.mem_set_of_eq, simp, assumption, from hlbd (-x) hx }, apply not_le_of_lt h, rwa le_neg }, replace hy : -y < s := by {rwa neg_lt}, from hlub (-y) hy this } end theorem sup_def (S : set ℝ) (s : ℝ) : sup S s ↔ upper_bound S s ∧ ∀ x : ℝ, (upper_bound S x → s ≤ x) := begin split, {rintros ⟨ha, hb⟩, split, {intros x hx, from ha x hx }, {intros x hx, suffices : ¬ x < s, revert this, simp, intro, apply hb x, repeat {assumption}} }, {rintros ⟨ha, hb⟩, split, {assumption}, {intros x hx hc, replace hx : ¬ s ≤ x := by {push_neg, assumption}, from hx (hb x hc) } } end theorem inf_def (S : set ℝ) (s : ℝ) : inf S s ↔ lower_bound S s ∧ ∀ x : ℝ, (lower_bound S x → x ≤ s) := begin -- proof essentially identical to that of sup_def split, {rintros ⟨ha, hb⟩, split, {intros x hx, from ha x hx }, {intros x hx, suffices : ¬ s < x, revert this, simp, intro, apply hb x, repeat {assumption}} }, {rintros ⟨ha, hb⟩, split, {assumption}, {intros x hx hc, replace hx : ¬ x ≤ s := by {push_neg, assumption}, from hx (hb x hc) } } end -- Defining the Completeness axiom axiom completeness (S : set ℝ) (h : bounded_above S) (h1 : S ≠ ∅) : ∃ s : ℝ, sup S s lemma neg_bdd_above_of_bdd_below {S : set ℝ} (h : bounded_below S) : bounded_above {t | -t ∈ S} := begin -- Since S is bounded below let b be its lower. cases h with b hb, -- I now claim that -b is a lower bound of {t | -t ∈ S}. refine ⟨-b, λ s hs, _⟩, -- Let -s ∈ S. But then from b being an lower bound of S, b ≤ -s → s ≤ -b as required! linarith [hb (-s) hs] end open set -- Exercise 2.29 theorem completeness_below (S : set ℝ) (h : bounded_below S) (h1 : S ≠ ∅) : ∃ s : ℝ, inf S s := begin -- As we have S is not an empty set, there exists s ∈ S. cases ne_empty_iff_nonempty.1 h1 with s hs, -- Now let's consider the set T := {t : ℝ | -t ∈ S}. -- This set is bounded above by our previous lemma so by completeness, it has a supremum (lets call it b). cases completeness {t : ℝ | -t ∈ S} (neg_bdd_above_of_bdd_below h) (ne_empty_iff_nonempty.2 ⟨-s, by simp [hs]⟩) with b hb, -- I claim that -b is the infimum of S. refine ⟨-b, _⟩, -- As we have previously proven that if s is the supremum of S then -s is the infimum of {t : ℝ | -t ∈ S}, -- it suffices to show that S = {t : ℝ | -t ∈ {t : ℝ | -t ∈ S}}. But this is trivial, so we are done! convert neg_set_inf {t : ℝ | -t ∈ S} _ _, simp, exact hb end open classical -- Mentimeter Q 9 theorem equality_def (a x : ℝ) : (∀ ε : ℝ, 0 < ε → abs (x - a) < ε) ↔ x = a := begin -- Since this is an if and only if question we need to prove both directions of the equation. split, -- Let use prove the forward direction first. -- Suppose otherwise. Then x ≠ a. intro h, by_contra h1, -- It suffices to prove abs (x - a) < abs (x - a) since that's obviously false. suffices : abs (x - a) < abs (x - a), linarith, -- So, by choosing ε = abs (x - a), the contradiction follows easily. refine h _ (abs_pos_iff.2 $ λ h2, _), rw sub_eq_zero at h2, contradiction, -- For the other direction it is much easier. -- If x = a then abs (x - a) = 0 < ε by construction so we are done! intro h, rw h, simp end end completeness
ca5f8de843dce022d3bfa885464ea174e0c7332d
853df553b1d6ca524e3f0a79aedd32dde5d27ec3
/src/data/padics/hensel.lean
49738f346a4705697e71ea9cc2e04c26e9f533f5
[ "Apache-2.0" ]
permissive
DanielFabian/mathlib
efc3a50b5dde303c59eeb6353ef4c35a345d7112
f520d07eba0c852e96fe26da71d85bf6d40fcc2a
refs/heads/master
1,668,739,922,971
1,595,201,756,000
1,595,201,756,000
279,469,476
0
0
null
1,594,696,604,000
1,594,696,604,000
null
UTF-8
Lean
false
false
21,453
lean
/- Copyright (c) 2018 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis -/ import data.padics.padic_integers import topology.metric_space.cau_seq_filter import analysis.specific_limits import topology.algebra.polynomial /-! # Hensel's lemma on ℤ_p This file proves Hensel's lemma on ℤ_p, roughly following Keith Conrad's writeup: <http://www.math.uconn.edu/~kconrad/blurbs/gradnumthy/hensel.pdf> Hensel's lemma gives a simple condition for the existence of a root of a polynomial. The proof and motivation are described in the paper [R. Y. Lewis, *A formal proof of Hensel's lemma over the p-adic integers*][lewis2019]. ## References * <http://www.math.uconn.edu/~kconrad/blurbs/gradnumthy/hensel.pdf> * [R. Y. Lewis, *A formal proof of Hensel's lemma over the p-adic integers*][lewis2019] * <https://en.wikipedia.org/wiki/Hensel%27s_lemma> ## Tags p-adic, p adic, padic, p-adic integer -/ noncomputable theory open_locale classical topological_space -- We begin with some general lemmas that are used below in the computation. lemma padic_polynomial_dist {p : ℕ} [fact p.prime] (F : polynomial ℤ_[p]) (x y : ℤ_[p]) : ∥F.eval x - F.eval y∥ ≤ ∥x - y∥ := let ⟨z, hz⟩ := F.eval_sub_factor x y in calc ∥F.eval x - F.eval y∥ = ∥z∥ * ∥x - y∥ : by simp [hz] ... ≤ 1 * ∥x - y∥ : mul_le_mul_of_nonneg_right (padic_norm_z.le_one _) (norm_nonneg _) ... = ∥x - y∥ : by simp open filter metric private lemma comp_tendsto_lim {p : ℕ} [fact p.prime] {F : polynomial ℤ_[p]} (ncs : cau_seq ℤ_[p] norm) : tendsto (λ i, F.eval (ncs i)) at_top (𝓝 (F.eval ncs.lim)) := (F.continuous_eval.tendsto _).comp ncs.tendsto_limit section parameters {p : ℕ} [fact p.prime] {ncs : cau_seq ℤ_[p] norm} {F : polynomial ℤ_[p]} {a : ℤ_[p]} (ncs_der_val : ∀ n, ∥F.derivative.eval (ncs n)∥ = ∥F.derivative.eval a∥) include ncs_der_val private lemma ncs_tendsto_const : tendsto (λ i, ∥F.derivative.eval (ncs i)∥) at_top (𝓝 ∥F.derivative.eval a∥) := by convert tendsto_const_nhds; ext; rw ncs_der_val private lemma ncs_tendsto_lim : tendsto (λ i, ∥F.derivative.eval (ncs i)∥) at_top (𝓝 (∥F.derivative.eval ncs.lim∥)) := tendsto.comp (continuous_iff_continuous_at.1 continuous_norm _) (comp_tendsto_lim _) private lemma norm_deriv_eq : ∥F.derivative.eval ncs.lim∥ = ∥F.derivative.eval a∥ := tendsto_nhds_unique at_top_ne_bot ncs_tendsto_lim ncs_tendsto_const end section parameters {p : ℕ} [fact p.prime] {ncs : cau_seq ℤ_[p] norm} {F : polynomial ℤ_[p]} (hnorm : tendsto (λ i, ∥F.eval (ncs i)∥) at_top (𝓝 0)) include hnorm private lemma tendsto_zero_of_norm_tendsto_zero : tendsto (λ i, F.eval (ncs i)) at_top (𝓝 0) := tendsto_iff_norm_tendsto_zero.2 (by simpa using hnorm) lemma limit_zero_of_norm_tendsto_zero : F.eval ncs.lim = 0 := tendsto_nhds_unique at_top_ne_bot (comp_tendsto_lim _) tendsto_zero_of_norm_tendsto_zero end section hensel open nat parameters {p : ℕ} [fact p.prime] {F : polynomial ℤ_[p]} {a : ℤ_[p]} (hnorm : ∥F.eval a∥ < ∥F.derivative.eval a∥^2) (hnsol : F.eval a ≠ 0) include hnorm /-- `T` is an auxiliary value that is used to control the behavior of the polynomial `F`. -/ private def T : ℝ := ∥(F.eval a / (F.derivative.eval a)^2 : ℚ_[p])∥ private lemma deriv_sq_norm_pos : 0 < ∥F.derivative.eval a∥ ^ 2 := lt_of_le_of_lt (norm_nonneg _) hnorm private lemma deriv_sq_norm_ne_zero : ∥F.derivative.eval a∥^2 ≠ 0 := ne_of_gt deriv_sq_norm_pos private lemma deriv_norm_ne_zero : ∥F.derivative.eval a∥ ≠ 0 := λ h, deriv_sq_norm_ne_zero (by simp [*, _root_.pow_two]) private lemma deriv_norm_pos : 0 < ∥F.derivative.eval a∥ := lt_of_le_of_ne (norm_nonneg _) (ne.symm deriv_norm_ne_zero) private lemma deriv_ne_zero : F.derivative.eval a ≠ 0 := mt norm_eq_zero.2 deriv_norm_ne_zero private lemma T_def : T = ∥F.eval a∥ / ∥F.derivative.eval a∥^2 := calc T = ∥F.eval a∥ / ∥((F.derivative.eval a)^2 : ℚ_[p])∥ : normed_field.norm_div _ _ ... = ∥F.eval a∥ / ∥(F.derivative.eval a)^2∥ : by simp [norm, padic_norm_z] ... = ∥F.eval a∥ / ∥(F.derivative.eval a)∥^2 : by simp [pow, monoid.pow] private lemma T_lt_one : T < 1 := let h := (div_lt_one_iff_lt deriv_sq_norm_pos).2 hnorm in by rw T_def; apply h private lemma T_pow {n : ℕ} (hn : n > 0) : T ^ n < 1 := have T ^ n ≤ T ^ 1, from pow_le_pow_of_le_one (norm_nonneg _) (le_of_lt T_lt_one) (succ_le_of_lt hn), lt_of_le_of_lt (by simpa) T_lt_one private lemma T_pow' (n : ℕ) : T ^ (2 ^ n) < 1 := (T_pow (nat.pow_pos (by norm_num) _)) private lemma T_pow_nonneg (n : ℕ) : T ^ n ≥ 0 := pow_nonneg (norm_nonneg _) _ /-- We will construct a sequence of elements of ℤ_p satisfying successive values of `ih`. -/ private def ih (n : ℕ) (z : ℤ_[p]) : Prop := ∥F.derivative.eval z∥ = ∥F.derivative.eval a∥ ∧ ∥F.eval z∥ ≤ ∥F.derivative.eval a∥^2 * T ^ (2^n) private lemma ih_0 : ih 0 a := ⟨ rfl, by simp [T_def, mul_div_cancel' _ (ne_of_gt (deriv_sq_norm_pos hnorm))] ⟩ private lemma calc_norm_le_one {n : ℕ} {z : ℤ_[p]} (hz : ih n z) : ∥(↑(F.eval z) : ℚ_[p]) / ↑(F.derivative.eval z)∥ ≤ 1 := calc ∥(↑(F.eval z) : ℚ_[p]) / ↑(F.derivative.eval z)∥ = ∥(↑(F.eval z) : ℚ_[p])∥ / ∥(↑(F.derivative.eval z) : ℚ_[p])∥ : normed_field.norm_div _ _ ... = ∥F.eval z∥ / ∥F.derivative.eval a∥ : by simp [hz.1] ... ≤ ∥F.derivative.eval a∥^2 * T^(2^n) / ∥F.derivative.eval a∥ : (div_le_div_right deriv_norm_pos).2 hz.2 ... = ∥F.derivative.eval a∥ * T^(2^n) : div_sq_cancel (ne_of_gt deriv_norm_pos) _ ... ≤ 1 : mul_le_one (padic_norm_z.le_one _) (T_pow_nonneg _) (le_of_lt (T_pow' _)) private lemma calc_deriv_dist {z z' z1 : ℤ_[p]} (hz' : z' = z - z1) (hz1 : ∥z1∥ = ∥F.eval z∥ / ∥F.derivative.eval a∥) {n} (hz : ih n z) : ∥F.derivative.eval z' - F.derivative.eval z∥ < ∥F.derivative.eval a∥ := calc ∥F.derivative.eval z' - F.derivative.eval z∥ ≤ ∥z' - z∥ : padic_polynomial_dist _ _ _ ... = ∥z1∥ : by simp only [sub_eq_add_neg, add_assoc, hz', add_add_neg_cancel'_right, norm_neg] ... = ∥F.eval z∥ / ∥F.derivative.eval a∥ : hz1 ... ≤ ∥F.derivative.eval a∥^2 * T^(2^n) / ∥F.derivative.eval a∥ : (div_le_div_right deriv_norm_pos).2 hz.2 ... = ∥F.derivative.eval a∥ * T^(2^n) : div_sq_cancel deriv_norm_ne_zero _ ... < ∥F.derivative.eval a∥ : (mul_lt_iff_lt_one_right deriv_norm_pos).2 (T_pow (pow_pos (by norm_num) _)) private def calc_eval_z' {z z' z1 : ℤ_[p]} (hz' : z' = z - z1) {n} (hz : ih n z) (h1 : ∥(↑(F.eval z) : ℚ_[p]) / ↑(F.derivative.eval z)∥ ≤ 1) (hzeq : z1 = ⟨_, h1⟩) : {q : ℤ_[p] // F.eval z' = q * z1^2} := have hdzne' : (↑(F.derivative.eval z) : ℚ_[p]) ≠ 0, from have hdzne : F.derivative.eval z ≠ 0, from mt norm_eq_zero.2 (by rw hz.1; apply deriv_norm_ne_zero; assumption), λ h, hdzne $ subtype.ext_iff_val.2 h, let ⟨q, hq⟩ := F.binom_expansion z (-z1) in have ∥(↑(F.derivative.eval z) * (↑(F.eval z) / ↑(F.derivative.eval z)) : ℚ_[p])∥ ≤ 1, by {rw padic_norm_e.mul, apply mul_le_one, apply padic_norm_z.le_one, apply norm_nonneg, apply h1}, have F.derivative.eval z * (-z1) = -F.eval z, from calc F.derivative.eval z * (-z1) = (F.derivative.eval z) * -⟨↑(F.eval z) / ↑(F.derivative.eval z), h1⟩ : by rw [hzeq] ... = -((F.derivative.eval z) * ⟨↑(F.eval z) / ↑(F.derivative.eval z), h1⟩) : by simp [subtype.ext_iff_val] ... = -(⟨↑(F.derivative.eval z) * (↑(F.eval z) / ↑(F.derivative.eval z)), this⟩) : subtype.ext_iff_val.2 $ by simp ... = -(F.eval z) : by simp [mul_div_cancel' _ hdzne'], have heq : F.eval z' = q * z1^2, by simpa [this, hz'] using hq, ⟨q, heq⟩ private def calc_eval_z'_norm {z z' z1 : ℤ_[p]} {n} (hz : ih n z) {q} (heq : F.eval z' = q * z1^2) (h1 : ∥(↑(F.eval z) : ℚ_[p]) / ↑(F.derivative.eval z)∥ ≤ 1) (hzeq : z1 = ⟨_, h1⟩) : ∥F.eval z'∥ ≤ ∥F.derivative.eval a∥^2 * T^(2^(n+1)) := calc ∥F.eval z'∥ = ∥q∥ * ∥z1∥^2 : by simp [heq] ... ≤ 1 * ∥z1∥^2 : mul_le_mul_of_nonneg_right (padic_norm_z.le_one _) (pow_nonneg (norm_nonneg _) _) ... = ∥F.eval z∥^2 / ∥F.derivative.eval a∥^2 : by simp [hzeq, hz.1, div_pow] ... ≤ (∥F.derivative.eval a∥^2 * T^(2^n))^2 / ∥F.derivative.eval a∥^2 : (div_le_div_right deriv_sq_norm_pos).2 (pow_le_pow_of_le_left (norm_nonneg _) hz.2 _) ... = (∥F.derivative.eval a∥^2)^2 * (T^(2^n))^2 / ∥F.derivative.eval a∥^2 : by simp only [_root_.mul_pow] ... = ∥F.derivative.eval a∥^2 * (T^(2^n))^2 : div_sq_cancel deriv_sq_norm_ne_zero _ ... = ∥F.derivative.eval a∥^2 * T^(2^(n + 1)) : by rw [←pow_mul]; refl set_option eqn_compiler.zeta true /-- Given `z : ℤ_[p]` satisfying `ih n z`, construct `z' : ℤ_[p]` satisfying `ih (n+1) z'`. We need the hypothesis `ih n z`, since otherwise `z'` is not necessarily an integer. -/ private def ih_n {n : ℕ} {z : ℤ_[p]} (hz : ih n z) : {z' : ℤ_[p] // ih (n+1) z'} := have h1 : ∥(↑(F.eval z) : ℚ_[p]) / ↑(F.derivative.eval z)∥ ≤ 1, from calc_norm_le_one hz, let z1 : ℤ_[p] := ⟨_, h1⟩, z' : ℤ_[p] := z - z1 in ⟨ z', have hdist : ∥F.derivative.eval z' - F.derivative.eval z∥ < ∥F.derivative.eval a∥, from calc_deriv_dist rfl (by simp [z1, hz.1]) hz, have hfeq : ∥F.derivative.eval z'∥ = ∥F.derivative.eval a∥, begin rw [sub_eq_add_neg, ← hz.1, ←norm_neg (F.derivative.eval z)] at hdist, have := padic_norm_z.eq_of_norm_add_lt_right hdist, rwa [norm_neg, hz.1] at this end, let ⟨q, heq⟩ := calc_eval_z' rfl hz h1 rfl in have hnle : ∥F.eval z'∥ ≤ ∥F.derivative.eval a∥^2 * T^(2^(n+1)), from calc_eval_z'_norm hz heq h1 rfl, ⟨hfeq, hnle⟩⟩ set_option eqn_compiler.zeta false -- why doesn't "noncomputable theory" stick here? private noncomputable def newton_seq_aux : Π n : ℕ, {z : ℤ_[p] // ih n z} | 0 := ⟨a, ih_0⟩ | (k+1) := ih_n (newton_seq_aux k).2 private def newton_seq (n : ℕ) : ℤ_[p] := (newton_seq_aux n).1 private lemma newton_seq_deriv_norm (n : ℕ) : ∥F.derivative.eval (newton_seq n)∥ = ∥F.derivative.eval a∥ := (newton_seq_aux n).2.1 private lemma newton_seq_norm_le (n : ℕ) : ∥F.eval (newton_seq n)∥ ≤ ∥F.derivative.eval a∥^2 * T ^ (2^n) := (newton_seq_aux n).2.2 private lemma newton_seq_norm_eq (n : ℕ) : ∥newton_seq (n+1) - newton_seq n∥ = ∥F.eval (newton_seq n)∥ / ∥F.derivative.eval (newton_seq n)∥ := by simp [newton_seq, newton_seq_aux, ih_n, sub_eq_add_neg, add_comm] private lemma newton_seq_succ_dist (n : ℕ) : ∥newton_seq (n+1) - newton_seq n∥ ≤ ∥F.derivative.eval a∥ * T^(2^n) := calc ∥newton_seq (n+1) - newton_seq n∥ = ∥F.eval (newton_seq n)∥ / ∥F.derivative.eval (newton_seq n)∥ : newton_seq_norm_eq _ ... = ∥F.eval (newton_seq n)∥ / ∥F.derivative.eval a∥ : by rw newton_seq_deriv_norm ... ≤ ∥F.derivative.eval a∥^2 * T ^ (2^n) / ∥F.derivative.eval a∥ : (div_le_div_right deriv_norm_pos).2 (newton_seq_norm_le _) ... = ∥F.derivative.eval a∥ * T^(2^n) : div_sq_cancel (ne_of_gt deriv_norm_pos) _ include hnsol private lemma T_pos : T > 0 := begin rw T_def, exact div_pos_of_pos_of_pos (norm_pos_iff.2 hnsol) (deriv_sq_norm_pos hnorm) end private lemma newton_seq_succ_dist_weak (n : ℕ) : ∥newton_seq (n+2) - newton_seq (n+1)∥ < ∥F.eval a∥ / ∥F.derivative.eval a∥ := have 2 ≤ 2^(n+1), from have _, from pow_le_pow (by norm_num : 1 ≤ 2) (nat.le_add_left _ _ : 1 ≤ n + 1), by simpa using this, calc ∥newton_seq (n+2) - newton_seq (n+1)∥ ≤ ∥F.derivative.eval a∥ * T^(2^(n+1)) : newton_seq_succ_dist _ ... ≤ ∥F.derivative.eval a∥ * T^2 : mul_le_mul_of_nonneg_left (pow_le_pow_of_le_one (norm_nonneg _) (le_of_lt T_lt_one) this) (norm_nonneg _) ... < ∥F.derivative.eval a∥ * T^1 : mul_lt_mul_of_pos_left (pow_lt_pow_of_lt_one T_pos T_lt_one (by norm_num)) deriv_norm_pos ... = ∥F.eval a∥ / ∥F.derivative.eval a∥ : begin rw [T, _root_.pow_two, _root_.pow_one, normed_field.norm_div, ←mul_div_assoc, padic_norm_e.mul], apply mul_div_mul_left, apply deriv_norm_ne_zero; assumption end private lemma newton_seq_dist_aux (n : ℕ) : ∀ k : ℕ, ∥newton_seq (n + k) - newton_seq n∥ ≤ ∥F.derivative.eval a∥ * T^(2^n) | 0 := begin simp, apply mul_nonneg, {apply norm_nonneg}, {apply T_pow_nonneg} end | (k+1) := have 2^n ≤ 2^(n+k), by {rw [←nat.pow_eq_pow, ←nat.pow_eq_pow], apply pow_le_pow, norm_num, apply nat.le_add_right}, calc ∥newton_seq (n + (k + 1)) - newton_seq n∥ = ∥newton_seq ((n + k) + 1) - newton_seq n∥ : by rw add_assoc ... = ∥(newton_seq ((n + k) + 1) - newton_seq (n+k)) + (newton_seq (n+k) - newton_seq n)∥ : by rw ←sub_add_sub_cancel ... ≤ max (∥newton_seq ((n + k) + 1) - newton_seq (n+k)∥) (∥newton_seq (n+k) - newton_seq n∥) : padic_norm_z.nonarchimedean _ _ ... ≤ max (∥F.derivative.eval a∥ * T^(2^((n + k)))) (∥F.derivative.eval a∥ * T^(2^n)) : max_le_max (newton_seq_succ_dist _) (newton_seq_dist_aux _) ... = ∥F.derivative.eval a∥ * T^(2^n) : max_eq_right $ mul_le_mul_of_nonneg_left (pow_le_pow_of_le_one (norm_nonneg _) (le_of_lt T_lt_one) this) (norm_nonneg _) private lemma newton_seq_dist {n k : ℕ} (hnk : n ≤ k) : ∥newton_seq k - newton_seq n∥ ≤ ∥F.derivative.eval a∥ * T^(2^n) := have hex : ∃ m, k = n + m, from exists_eq_add_of_le hnk, let ⟨_, hex'⟩ := hex in by rw hex'; apply newton_seq_dist_aux; assumption private lemma newton_seq_dist_to_a : ∀ n : ℕ, 0 < n → ∥newton_seq n - a∥ = ∥F.eval a∥ / ∥F.derivative.eval a∥ | 1 h := by simp [sub_eq_add_neg, add_assoc, newton_seq, newton_seq_aux, ih_n]; apply normed_field.norm_div | (k+2) h := have hlt : ∥newton_seq (k+2) - newton_seq (k+1)∥ < ∥newton_seq (k+1) - a∥, by rw newton_seq_dist_to_a (k+1) (succ_pos _); apply newton_seq_succ_dist_weak; assumption, have hne' : ∥newton_seq (k + 2) - newton_seq (k+1)∥ ≠ ∥newton_seq (k+1) - a∥, from ne_of_lt hlt, calc ∥newton_seq (k + 2) - a∥ = ∥(newton_seq (k + 2) - newton_seq (k+1)) + (newton_seq (k+1) - a)∥ : by rw ←sub_add_sub_cancel ... = max (∥newton_seq (k + 2) - newton_seq (k+1)∥) (∥newton_seq (k+1) - a∥) : padic_norm_z.add_eq_max_of_ne hne' ... = ∥newton_seq (k+1) - a∥ : max_eq_right_of_lt hlt ... = ∥polynomial.eval a F∥ / ∥polynomial.eval a (polynomial.derivative F)∥ : newton_seq_dist_to_a (k+1) (succ_pos _) private lemma bound' : tendsto (λ n : ℕ, ∥F.derivative.eval a∥ * T^(2^n)) at_top (𝓝 0) := begin rw ←mul_zero (∥F.derivative.eval a∥), exact tendsto_const_nhds.mul (tendsto.comp (tendsto_pow_at_top_nhds_0_of_lt_1 (norm_nonneg _) (T_lt_one hnorm)) (nat.tendsto_pow_at_top_at_top_of_one_lt (by norm_num))) end private lemma bound : ∀ {ε}, ε > 0 → ∃ N : ℕ, ∀ {n}, n ≥ N → ∥F.derivative.eval a∥ * T^(2^n) < ε := have mtn : ∀ n : ℕ, ∥polynomial.eval a (polynomial.derivative F)∥ * T ^ (2 ^ n) ≥ 0, from λ n, mul_nonneg (norm_nonneg _) (T_pow_nonneg _), begin have := bound' hnorm hnsol, simp [tendsto, nhds] at this, intros ε hε, cases this (ball 0 ε) (mem_ball_self hε) (is_open_ball) with N hN, existsi N, intros n hn, simpa [normed_field.norm_mul, real.norm_eq_abs, abs_of_nonneg (mtn n)] using hN _ hn end private lemma bound'_sq : tendsto (λ n : ℕ, ∥F.derivative.eval a∥^2 * T^(2^n)) at_top (𝓝 0) := begin rw [←mul_zero (∥F.derivative.eval a∥), _root_.pow_two], simp only [mul_assoc], apply tendsto.mul, { apply tendsto_const_nhds }, { apply bound', assumption } end private theorem newton_seq_is_cauchy : is_cau_seq norm newton_seq := begin intros ε hε, cases bound hnorm hnsol hε with N hN, existsi N, intros j hj, apply lt_of_le_of_lt, { apply newton_seq_dist _ _ hj, assumption }, { apply hN, apply le_refl } end private def newton_cau_seq : cau_seq ℤ_[p] norm := ⟨_, newton_seq_is_cauchy⟩ private def soln : ℤ_[p] := newton_cau_seq.lim private lemma soln_spec {ε : ℝ} (hε : ε > 0) : ∃ (N : ℕ), ∀ {i : ℕ}, i ≥ N → ∥soln - newton_cau_seq i∥ < ε := setoid.symm (cau_seq.equiv_lim newton_cau_seq) _ hε private lemma soln_deriv_norm : ∥F.derivative.eval soln∥ = ∥F.derivative.eval a∥ := norm_deriv_eq newton_seq_deriv_norm private lemma newton_seq_norm_tendsto_zero : tendsto (λ i, ∥F.eval (newton_cau_seq i)∥) at_top (𝓝 0) := squeeze_zero (λ _, norm_nonneg _) newton_seq_norm_le bound'_sq private lemma newton_seq_dist_tendsto : tendsto (λ n, ∥newton_cau_seq n - a∥) at_top (𝓝 (∥F.eval a∥ / ∥F.derivative.eval a∥)) := tendsto_const_nhds.congr' $ eventually_at_top.2 ⟨1, λ _ hx, (newton_seq_dist_to_a _ hx).symm⟩ private lemma newton_seq_dist_tendsto' : tendsto (λ n, ∥newton_cau_seq n - a∥) at_top (𝓝 ∥soln - a∥) := (continuous_norm.tendsto _).comp (newton_cau_seq.tendsto_limit.sub tendsto_const_nhds) private lemma soln_dist_to_a : ∥soln - a∥ = ∥F.eval a∥ / ∥F.derivative.eval a∥ := tendsto_nhds_unique at_top_ne_bot newton_seq_dist_tendsto' newton_seq_dist_tendsto private lemma soln_dist_to_a_lt_deriv : ∥soln - a∥ < ∥F.derivative.eval a∥ := begin rw soln_dist_to_a, apply div_lt_of_mul_lt_of_pos, { apply deriv_norm_pos; assumption }, { rwa _root_.pow_two at hnorm } end private lemma eval_soln : F.eval soln = 0 := limit_zero_of_norm_tendsto_zero newton_seq_norm_tendsto_zero private lemma soln_unique (z : ℤ_[p]) (hev : F.eval z = 0) (hnlt : ∥z - a∥ < ∥F.derivative.eval a∥) : z = soln := have soln_dist : ∥z - soln∥ < ∥F.derivative.eval a∥, from calc ∥z - soln∥ = ∥(z - a) + (a - soln)∥ : by rw sub_add_sub_cancel ... ≤ max (∥z - a∥) (∥a - soln∥) : padic_norm_z.nonarchimedean _ _ ... < ∥F.derivative.eval a∥ : max_lt hnlt (by rw norm_sub_rev; apply soln_dist_to_a_lt_deriv), let h := z - soln, ⟨q, hq⟩ := F.binom_expansion soln h in have (F.derivative.eval soln + q * h) * h = 0, from eq.symm (calc 0 = F.eval (soln + h) : by simp [hev, h] ... = F.derivative.eval soln * h + q * h^2 : by rw [hq, eval_soln, zero_add] ... = (F.derivative.eval soln + q * h) * h : by rw [_root_.pow_two, right_distrib, mul_assoc]), have h = 0, from by_contradiction $ λ hne, have F.derivative.eval soln + q * h = 0, from (eq_zero_or_eq_zero_of_mul_eq_zero this).resolve_right hne, have F.derivative.eval soln = (-q) * h, by simpa using eq_neg_of_add_eq_zero this, lt_irrefl ∥F.derivative.eval soln∥ (calc ∥F.derivative.eval soln∥ = ∥(-q) * h∥ : by rw this ... ≤ 1 * ∥h∥ : by rw [padic_norm_z.mul]; exact mul_le_mul_of_nonneg_right (padic_norm_z.le_one _) (norm_nonneg _) ... = ∥z - soln∥ : by simp [h] ... < ∥F.derivative.eval soln∥ : by rw soln_deriv_norm; apply soln_dist), eq_of_sub_eq_zero (by rw ←this; refl) end hensel variables {p : ℕ} [fact p.prime] {F : polynomial ℤ_[p]} {a : ℤ_[p]} private lemma a_soln_is_unique (ha : F.eval a = 0) (z' : ℤ_[p]) (hz' : F.eval z' = 0) (hnormz' : ∥z' - a∥ < ∥F.derivative.eval a∥) : z' = a := let h := z' - a, ⟨q, hq⟩ := F.binom_expansion a h in have (F.derivative.eval a + q * h) * h = 0, from eq.symm (calc 0 = F.eval (a + h) : show 0 = F.eval (a + (z' - a)), by rw add_comm; simp [hz'] ... = F.derivative.eval a * h + q * h^2 : by rw [hq, ha, zero_add] ... = (F.derivative.eval a + q * h) * h : by rw [_root_.pow_two, right_distrib, mul_assoc]), have h = 0, from by_contradiction $ λ hne, have F.derivative.eval a + q * h = 0, from (eq_zero_or_eq_zero_of_mul_eq_zero this).resolve_right hne, have F.derivative.eval a = (-q) * h, by simpa using eq_neg_of_add_eq_zero this, lt_irrefl ∥F.derivative.eval a∥ (calc ∥F.derivative.eval a∥ = ∥q∥*∥h∥ : by simp [this] ... ≤ 1*∥h∥ : mul_le_mul_of_nonneg_right (padic_norm_z.le_one _) (norm_nonneg _) ... < ∥F.derivative.eval a∥ : by simpa [h]), eq_of_sub_eq_zero (by rw ←this; refl) variable (hnorm : ∥F.eval a∥ < ∥F.derivative.eval a∥^2) include hnorm private lemma a_is_soln (ha : F.eval a = 0) : F.eval a = 0 ∧ ∥a - a∥ < ∥F.derivative.eval a∥ ∧ ∥F.derivative.eval a∥ = ∥F.derivative.eval a∥ ∧ ∀ z', F.eval z' = 0 → ∥z' - a∥ < ∥F.derivative.eval a∥ → z' = a := ⟨ha, by simp; apply deriv_norm_pos; apply hnorm, rfl, a_soln_is_unique ha⟩ lemma hensels_lemma : ∃ z : ℤ_[p], F.eval z = 0 ∧ ∥z - a∥ < ∥F.derivative.eval a∥ ∧ ∥F.derivative.eval z∥ = ∥F.derivative.eval a∥ ∧ ∀ z', F.eval z' = 0 → ∥z' - a∥ < ∥F.derivative.eval a∥ → z' = z := if ha : F.eval a = 0 then ⟨a, a_is_soln hnorm ha⟩ else by refine ⟨soln _ _, eval_soln _ _, soln_dist_to_a_lt_deriv _ _, soln_deriv_norm _ _, soln_unique _ _⟩; assumption
03c1774de4bdc48e7eab7b1b4e6dcb43262dc796
1fd908b06e3f9c1252cb2285ada1102623a67f72
/init/meta/basic_tactics.lean
439454dded9a3a05bf758fb60ddef32a67d7be97
[ "Apache-2.0" ]
permissive
avigad/hott3
609a002849182721e7c7ae536d9f1e2956d6d4d3
f64750cd2de7a81e87d4828246d1369d59f16f43
refs/heads/master
1,629,027,243,322
1,510,946,717,000
1,510,946,717,000
103,570,461
0
0
null
1,505,415,620,000
1,505,415,620,000
null
UTF-8
Lean
false
false
2,828
lean
/- Copyright (c) 2017 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn -/ universes u v w namespace list open tactic meta def mmap_filter {α : Type u} {β : Type v} (f : α → tactic (option β)) : list α → tactic (list β) | [] := return [] | (x :: xs) := do oy ← f x, ys ← mmap_filter xs, some y ← return oy | return ys, return $ y :: ys end list namespace option /-- The mmap for options. -/ def mmap {m : Type u → Type v} [monad m] {α : Type w} {β : Type u} (f : α → m β) : option α → m (option β) | none := return none | (some x) := do y ← f x, return $ some y def iget {α : Type u} [inhabited α] : option α → α | none := default α | (some x) := x end option namespace expr variable {elab : bool} /-- returns a list of names, binder_info's and domains and the conclusion of the expression -/ meta def destruct_pis : expr elab → list name × list binder_info × list (expr elab) × expr elab | (pi n bi a b) := let (ns, bis, es, e) := destruct_pis b in (n::ns, bi::bis, a::es, e) | a := ([], [], [], a) instance inhabited_binder_info : inhabited binder_info := ⟨binder_info.default⟩ end expr namespace tactic open expr open interaction_monad interaction_monad.result /-- executes t₂ when tactic t₁ fails. After t₂ is executed, do_on_failure fails with the error message given by t₂ -/ meta def do_on_failure {α : Type _} (t₁ : tactic α) (t₂ : format → tactic format) : tactic α := λ s, match t₁ s with | (exception (some f) pos s') := (t₂ (f ()) >>= λx, exception (some $ λ_, x) pos) s' | (exception none pos s') := exception none pos s' | (interaction_monad.result.success a s') := interaction_monad.result.success a s' end /-- change the error message on failure of t₁ -/ meta def change_failure {α : Type _} (t₁ : tactic α) (t₂ : format → format) : tactic α := do_on_failure t₁ $ return ∘ t₂ /-- If t₁ fails, also trace the failure -/ meta def trace_failure {α : Type _} (t₁ : tactic α) : tactic α := do_on_failure t₁ $ λfmt, trace fmt >> return fmt namespace interactive open lean lean.parser interactive local postfix `?`:9001 := optional meta def fconstructor : tactic unit := tactic.fconstructor meta def infer : tactic unit := apply_instance private meta def generalize_arg_p : pexpr → parser (pexpr × name) | (app (app (macro _ [const `hott.eq _ ]) h) (local_const x _ _ _)) := pure (h, x) | _ := fail "parse error" meta def hgeneralize (h : parse ident?) (p : parse $ tk ":" *> with_desc "expr = id" (parser.pexpr 0 >>= generalize_arg_p)) : tactic unit := tactic.interactive.generalize h p meta def trace_failure : itactic → tactic unit := tactic.trace_failure end interactive end tactic
c6d3f7597cb88a51960b15c6918df30e70773385
4bcaca5dc83d49803f72b7b5920b75b6e7d9de2d
/stage0/src/Lean/Elab/Structure.lean
644bdab7410c48d5812d48377589c47f68cd4ffb
[ "Apache-2.0" ]
permissive
subfish-zhou/leanprover-zh_CN.github.io
30b9fba9bd790720bd95764e61ae796697d2f603
8b2985d4a3d458ceda9361ac454c28168d920d3f
refs/heads/master
1,689,709,967,820
1,632,503,056,000
1,632,503,056,000
409,962,097
1
0
null
null
null
null
UTF-8
Lean
false
false
44,162
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Parser.Command import Lean.Meta.Closure import Lean.Meta.SizeOf import Lean.Meta.Injective import Lean.Meta.Structure import Lean.Meta.AppBuilder import Lean.Elab.Command import Lean.Elab.DeclModifiers import Lean.Elab.DeclUtil import Lean.Elab.Inductive import Lean.Elab.DeclarationRange import Lean.Elab.Binders namespace Lean.Elab.Command open Meta /- Recall that the `structure command syntax is ``` leading_parser (structureTk <|> classTk) >> declId >> many Term.bracketedBinder >> optional «extends» >> Term.optType >> optional (" := " >> optional structCtor >> structFields) ``` -/ structure StructCtorView where ref : Syntax modifiers : Modifiers inferMod : Bool -- true if `{}` is used in the constructor declaration name : Name declName : Name structure StructFieldView where ref : Syntax modifiers : Modifiers binderInfo : BinderInfo inferMod : Bool declName : Name name : Name binders : Syntax type? : Option Syntax value? : Option Syntax structure StructView where ref : Syntax modifiers : Modifiers scopeLevelNames : List Name -- All `universe` declarations in the current scope allUserLevelNames : List Name -- `scopeLevelNames` ++ explicit universe parameters provided in the `structure` command isClass : Bool declName : Name scopeVars : Array Expr -- All `variable` declaration in the current scope params : Array Expr -- Explicit parameters provided in the `structure` command parents : Array Syntax type : Syntax ctor : StructCtorView fields : Array StructFieldView inductive StructFieldKind where | newField | copiedField | fromParent | subobject deriving Inhabited, BEq structure StructFieldInfo where name : Name declName : Name -- Remark: for `fromParent` fields, `declName` is only relevant in the generation of auxiliary "default value" functions. fvar : Expr kind : StructFieldKind inferMod : Bool := false value? : Option Expr := none deriving Inhabited def StructFieldInfo.isFromParent (info : StructFieldInfo) : Bool := match info.kind with | StructFieldKind.fromParent => true | _ => false def StructFieldInfo.isSubobject (info : StructFieldInfo) : Bool := match info.kind with | StructFieldKind.subobject => true | _ => false /- Auxiliary declaration for `mkProjections` -/ structure ProjectionInfo where declName : Name inferMod : Bool structure ElabStructResult where decl : Declaration projInfos : List ProjectionInfo projInstances : List Name -- projections (to parent classes) that must be marked as instances. mctx : MetavarContext lctx : LocalContext localInsts : LocalInstances defaultAuxDecls : Array (Name × Expr × Expr) private def defaultCtorName := `mk /- The structure constructor syntax is ``` leading_parser try (declModifiers >> ident >> optional inferMod >> " :: ") ``` -/ private def expandCtor (structStx : Syntax) (structModifiers : Modifiers) (structDeclName : Name) : TermElabM StructCtorView := do let useDefault := do let declName := structDeclName ++ defaultCtorName addAuxDeclarationRanges declName structStx[2] structStx[2] pure { ref := structStx, modifiers := {}, inferMod := false, name := defaultCtorName, declName } if structStx[5].isNone then useDefault else let optCtor := structStx[5][1] if optCtor.isNone then useDefault else let ctor := optCtor[0] withRef ctor do let ctorModifiers ← elabModifiers ctor[0] checkValidCtorModifier ctorModifiers if ctorModifiers.isPrivate && structModifiers.isPrivate then throwError "invalid 'private' constructor in a 'private' structure" if ctorModifiers.isProtected && structModifiers.isPrivate then throwError "invalid 'protected' constructor in a 'private' structure" let inferMod := !ctor[2].isNone let name := ctor[1].getId let declName := structDeclName ++ name let declName ← applyVisibility ctorModifiers.visibility declName addDocString' declName ctorModifiers.docString? addAuxDeclarationRanges declName ctor[1] ctor[1] pure { ref := ctor, name, modifiers := ctorModifiers, inferMod, declName } def checkValidFieldModifier (modifiers : Modifiers) : TermElabM Unit := do if modifiers.isNoncomputable then throwError "invalid use of 'noncomputable' in field declaration" if modifiers.isPartial then throwError "invalid use of 'partial' in field declaration" if modifiers.isUnsafe then throwError "invalid use of 'unsafe' in field declaration" if modifiers.attrs.size != 0 then throwError "invalid use of attributes in field declaration" /- ``` def structExplicitBinder := leading_parser atomic (declModifiers true >> "(") >> many1 ident >> optional inferMod >> optDeclSig >> optional (Term.binderTactic <|> Term.binderDefault) >> ")" def structImplicitBinder := leading_parser atomic (declModifiers true >> "{") >> many1 ident >> optional inferMod >> declSig >> "}" def structInstBinder := leading_parser atomic (declModifiers true >> "[") >> many1 ident >> optional inferMod >> declSig >> "]" def structSimpleBinder := leading_parser atomic (declModifiers true >> ident) >> optional inferMod >> optDeclSig >> optional (Term.binderTactic <|> Term.binderDefault) def structFields := leading_parser many (structExplicitBinder <|> structImplicitBinder <|> structInstBinder) ``` -/ private def expandFields (structStx : Syntax) (structModifiers : Modifiers) (structDeclName : Name) : TermElabM (Array StructFieldView) := let fieldBinders := if structStx[5].isNone then #[] else structStx[5][2][0].getArgs fieldBinders.foldlM (init := #[]) fun (views : Array StructFieldView) fieldBinder => withRef fieldBinder do let mut fieldBinder := fieldBinder if fieldBinder.getKind == ``Parser.Command.structSimpleBinder then fieldBinder := Syntax.node ``Parser.Command.structExplicitBinder #[ fieldBinder[0], mkAtomFrom fieldBinder "(", mkNullNode #[ fieldBinder[1] ], fieldBinder[2], fieldBinder[3], fieldBinder[4], mkAtomFrom fieldBinder ")" ] let k := fieldBinder.getKind let binfo ← if k == ``Parser.Command.structExplicitBinder then pure BinderInfo.default else if k == ``Parser.Command.structImplicitBinder then pure BinderInfo.implicit else if k == ``Parser.Command.structInstBinder then pure BinderInfo.instImplicit else throwError "unexpected kind of structure field" let fieldModifiers ← elabModifiers fieldBinder[0] checkValidFieldModifier fieldModifiers if fieldModifiers.isPrivate && structModifiers.isPrivate then throwError "invalid 'private' field in a 'private' structure" if fieldModifiers.isProtected && structModifiers.isPrivate then throwError "invalid 'protected' field in a 'private' structure" let inferMod := !fieldBinder[3].isNone let (binders, type?) ← if binfo == BinderInfo.default then let (binders, type?) := expandOptDeclSig fieldBinder[4] let optBinderTacticDefault := fieldBinder[5] if optBinderTacticDefault.isNone then pure (binders, type?) else if optBinderTacticDefault[0].getKind != ``Parser.Term.binderTactic then pure (binders, type?) else let binderTactic := optBinderTacticDefault[0] match type? with | none => throwErrorAt binderTactic "invalid field declaration, type must be provided when auto-param (tactic) is used" | some type => let tac := binderTactic[2] let name ← Term.declareTacticSyntax tac -- The tactic should be for binders+type. -- It is safe to reset the binders to a "null" node since there is no value to be elaborated let type ← `(forall $(binders.getArgs):bracketedBinder*, $type) let type ← `(autoParam $type $(mkIdentFrom tac name)) pure (mkNullNode, some type) else let (binders, type) := expandDeclSig fieldBinder[4] pure (binders, some type) let value? ← if binfo != BinderInfo.default then pure none else let optBinderTacticDefault := fieldBinder[5] -- trace[Elab.struct] ">>> {optBinderTacticDefault}" if optBinderTacticDefault.isNone then pure none else if optBinderTacticDefault[0].getKind == ``Parser.Term.binderTactic then pure none else -- binderDefault := leading_parser " := " >> termParser pure (some optBinderTacticDefault[0][1]) let idents := fieldBinder[2].getArgs idents.foldlM (init := views) fun (views : Array StructFieldView) ident => withRef ident do let name := ident.getId.eraseMacroScopes unless name.isAtomic do throwErrorAt ident "invalid field name '{name.eraseMacroScopes}', field names must be atomic" let declName := structDeclName ++ name let declName ← applyVisibility fieldModifiers.visibility declName addDocString' declName fieldModifiers.docString? return views.push { ref := ident modifiers := fieldModifiers binderInfo := binfo inferMod declName name binders type? value? } private def validStructType (type : Expr) : Bool := match type with | Expr.sort .. => true | _ => false private def findFieldInfo? (infos : Array StructFieldInfo) (fieldName : Name) : Option StructFieldInfo := infos.find? fun info => info.name == fieldName private def containsFieldName (infos : Array StructFieldInfo) (fieldName : Name) : Bool := (findFieldInfo? infos fieldName).isSome private def updateFieldInfoVal (infos : Array StructFieldInfo) (fieldName : Name) (value : Expr) : Array StructFieldInfo := infos.map fun info => if info.name == fieldName then { info with value? := value } else info register_builtin_option structureDiamondWarning : Bool := { defValue := false descr := "enable/disable warning messages for structure diamonds" } /-- Return `some fieldName` if field `fieldName` of the parent structure `parentStructName` is already in `infos` -/ private def findExistingField? (infos : Array StructFieldInfo) (parentStructName : Name) : CoreM (Option Name) := do let fieldNames := getStructureFieldsFlattened (← getEnv) parentStructName for fieldName in fieldNames do if containsFieldName infos fieldName then return some fieldName return none private partial def processSubfields (structDeclName : Name) (parentFVar : Expr) (parentStructName : Name) (subfieldNames : Array Name) (infos : Array StructFieldInfo) (k : Array StructFieldInfo → TermElabM α) : TermElabM α := go 0 infos where go (i : Nat) (infos : Array StructFieldInfo) := do if h : i < subfieldNames.size then let subfieldName := subfieldNames.get ⟨i, h⟩ if containsFieldName infos subfieldName then throwError "field '{subfieldName}' from '{parentStructName}' has already been declared" let val ← mkProjection parentFVar subfieldName let type ← inferType val withLetDecl subfieldName type val fun subfieldFVar => /- The following `declName` is only used for creating the `_default` auxiliary declaration name when its default value is overwritten in the structure. If the default value is not overwritten, then its value is irrelevant. -/ let declName := structDeclName ++ subfieldName let infos := infos.push { name := subfieldName, declName, fvar := subfieldFVar, kind := StructFieldKind.fromParent } go (i+1) infos else k infos /-- Return `some (structName, fieldName, struct)` if `e` is a projection function application -/ private def isProjFnApp? (e : Expr) : MetaM (Option (Name × Name × Expr)) := do match e.getAppFn with | Expr.const declName .. => match (← getProjectionFnInfo? declName) with | some { ctorName := ctorName, numParams := n, .. } => if declName.isStr && e.getAppNumArgs == n+1 then let ConstantInfo.ctorInfo ctorVal ← getConstInfo ctorName | unreachable! return some (ctorVal.induct, declName.getString!, e.appArg!) else return none | _ => return none | _ => return none /-- Return `some fieldName`, if `e` is an expression that represents an access to field `fieldName` of the structure `s`. The name of the structure type must be `structName`. -/ private partial def isProjectionOf? (e : Expr) (structName : Name) (s : Expr) : MetaM (Option Name) := do if let some (baseStructName, fieldName, e) ← isProjFnApp? e then if let some path ← visit e #[] then if let some path' := getPathToBaseStructure? (← getEnv) baseStructName structName then if path'.toArray == path.reverse then return some fieldName return none where visit (e : Expr) (path : Array Name) : MetaM (Option (Array Name)) := do if e == s then return some path -- Check whether `e` is a `toParent` field if let some (_, _, e') ← isProjFnApp? e then visit e' (path.push e.getAppFn.constName!) else return none /-- Auxiliary method for `copyNewFieldsFrom`. -/ private def getFieldType (infos : Array StructFieldInfo) (parentStructName : Name) (parentType : Expr) (fieldName : Name) : MetaM Expr := do withLocalDeclD (← mkFreshId) parentType fun parent => do let proj ← mkProjection parent fieldName let projType ← inferType proj /- Eliminate occurrences of `parent`. This may happen when structure contains dependent fields. -/ let visit (e : Expr) : MetaM TransformStep := do if let some fieldName ← isProjectionOf? e parentStructName parent then -- trace[Meta.debug] "field '{fieldName}' of {e}" match (← findFieldInfo? infos fieldName) with | some existingFieldInfo => return TransformStep.done existingFieldInfo.fvar | none => throwError "unexpected field access {indentExpr e}" else return TransformStep.done e Meta.transform projType (post := visit) private def toVisibility (fieldInfo : StructureFieldInfo) : CoreM Visibility := do if isProtected (← getEnv) fieldInfo.projFn then return Visibility.protected else if isPrivateName fieldInfo.projFn then return Visibility.private else return Visibility.regular abbrev FieldMap := NameMap Expr -- Map from field name to expression representing the field /-- Reduce projetions of the structures in `structNames` -/ private def reduceProjs (e : Expr) (structNames : NameSet) : MetaM Expr := let reduce (e : Expr) : MetaM TransformStep := do match (← reduceProjOf? e structNames.contains) with | some v => return TransformStep.done v | _ => return TransformStep.done e transform e (post := reduce) /-- Copy the default value for field `fieldName` set at structure `structName`. The arguments for the `_default` auxiliary function are provided by `fieldMap`. Recall some of the entries in `fieldMap` are constructor applications, and they needed to be reduced using `reduceProjs`. Otherwise, the produced default value may be "cyclic". That is, we reduce projections of the structures in `expandedStructNames`. Here is an example that shows why the reduction is needed. ``` structure A where a : Nat structure B where a : Nat b : Nat c : Nat structure C extends B where d : Nat c := b + d structure D extends A, C #print D.c._default ``` Without the reduction, it produces ``` def D.c._default : A → Nat → Nat → Nat → Nat := fun toA b c d => id ({ a := toA.a, b := b, c := c : B }.b + d) ``` -/ private partial def copyDefaultValue? (fieldMap : FieldMap) (expandedStructNames : NameSet) (structName : Name) (fieldName : Name) : TermElabM (Option Expr) := do match getDefaultFnForField? (← getEnv) structName fieldName with | none => return none | some defaultFn => let cinfo ← getConstInfo defaultFn let us ← mkFreshLevelMVarsFor cinfo go? (cinfo.instantiateValueLevelParams us) where failed : TermElabM (Option Expr) := do logWarning s!"ignoring default value for field '{fieldName}' defined at '{structName}'" return none go? (e : Expr) : TermElabM (Option Expr) := do match e with | Expr.lam n d b c => if c.binderInfo.isExplicit then let fieldName := n match fieldMap.find? n with | none => failed | some val => let valType ← inferType val if (← isDefEq valType d) then go? (b.instantiate1 val) else failed else let arg ← mkFreshExprMVar d go? (b.instantiate1 arg) | e => let r := if e.isAppOfArity ``id 2 then e.appArg! else e return some (← reduceProjs (← instantiateMVars e.appArg!) expandedStructNames) private partial def copyNewFieldsFrom (structDeclName : Name) (infos : Array StructFieldInfo) (parentType : Expr) (k : Array StructFieldInfo → TermElabM α) : TermElabM α := do copyFields infos {} parentType fun infos _ _ => k infos where copyFields (infos : Array StructFieldInfo) (expandedStructNames : NameSet) (parentType : Expr) (k : Array StructFieldInfo → FieldMap → NameSet → TermElabM α) : TermElabM α := do let parentStructName ← getStructureName parentType let fieldNames := getStructureFields (← getEnv) parentStructName let rec copy (i : Nat) (infos : Array StructFieldInfo) (fieldMap : FieldMap) (expandedStructNames : NameSet) : TermElabM α := do if h : i < fieldNames.size then let fieldName := fieldNames.get ⟨i, h⟩ let fieldType ← getFieldType infos parentStructName parentType fieldName match (← findFieldInfo? infos fieldName) with | some existingFieldInfo => let existingFieldType ← inferType existingFieldInfo.fvar unless (← isDefEq fieldType existingFieldType) do throwError "parent field type mismatch, field '{fieldName}' from parent '{parentStructName}' {← mkHasTypeButIsExpectedMsg fieldType existingFieldType}" /- Remark: if structure has a default value for this field, it will be set at the `processOveriddenDefaultValues` below. -/ copy (i+1) infos (fieldMap.insert fieldName existingFieldInfo.fvar) expandedStructNames | none => let some fieldInfo ← getFieldInfo? (← getEnv) parentStructName fieldName | unreachable! let addNewField : TermElabM α := do let value? ← copyDefaultValue? fieldMap expandedStructNames parentStructName fieldName withLocalDecl fieldName fieldInfo.binderInfo fieldType fun fieldFVar => do let fieldDeclName := structDeclName ++ fieldName let fieldDeclName ← applyVisibility (← toVisibility fieldInfo) fieldDeclName let infos := infos.push { name := fieldName, declName := fieldDeclName, fvar := fieldFVar, value?, kind := StructFieldKind.copiedField, inferMod := fieldInfo.inferMod } copy (i+1) infos (fieldMap.insert fieldName fieldFVar) expandedStructNames if fieldInfo.subobject?.isSome then let fieldParentStructName ← getStructureName fieldType if (← findExistingField? infos fieldParentStructName).isSome then -- See comment at `copyDefaultValue?` let expandedStructNames := expandedStructNames.insert fieldParentStructName copyFields infos expandedStructNames fieldType fun infos nestedFieldMap expandedStructNames => do let fieldVal ← mkCompositeField fieldType nestedFieldMap trace[Meta.debug] "composite, {fieldName} := {fieldVal}" copy (i+1) infos (fieldMap.insert fieldName fieldVal) expandedStructNames else addNewField else addNewField else let infos ← processOveriddenDefaultValues infos fieldMap expandedStructNames parentStructName k infos fieldMap expandedStructNames copy 0 infos {} expandedStructNames processOveriddenDefaultValues (infos : Array StructFieldInfo) (fieldMap : FieldMap) (expandedStructNames : NameSet) (parentStructName : Name) : TermElabM (Array StructFieldInfo) := infos.mapM fun info => do match (← copyDefaultValue? fieldMap expandedStructNames parentStructName info.name) with | some value => return { info with value? := value } | none => return info mkCompositeField (parentType : Expr) (fieldMap : FieldMap) : TermElabM Expr := do let env ← getEnv let Expr.const parentStructName us _ ← pure parentType.getAppFn | unreachable! let parentCtor := getStructureCtor env parentStructName let mut result := mkAppN (mkConst parentCtor.name us) parentType.getAppArgs for fieldName in getStructureFields env parentStructName do match fieldMap.find? fieldName with | some val => result := mkApp result val | none => throwError "failed to copied fields from parent structure{indentExpr parentType}" -- TODO improve error message return result private partial def mkToParentName (parentStructName : Name) (p : Name → Bool) : Name := do let base := Name.mkSimple $ "to" ++ parentStructName.eraseMacroScopes.getString! if p base then base else let rec go (i : Nat) : Name := let curr := base.appendIndexAfter i if p curr then curr else go (i+1) go 1 private partial def withParents (view : StructView) (k : Array StructFieldInfo → Array Expr → TermElabM α) : TermElabM α := do go 0 #[] #[] where go (i : Nat) (infos : Array StructFieldInfo) (copiedParents : Array Expr) : TermElabM α := do if h : i < view.parents.size then let parentStx := view.parents.get ⟨i, h⟩ withRef parentStx do let parentType ← Term.elabType parentStx let parentStructName ← getStructureName parentType if let some existingFieldName ← findExistingField? infos parentStructName then if structureDiamondWarning.get (← getOptions) then logWarning s!"field '{existingFieldName}' from '{parentStructName}' has already been declared" copyNewFieldsFrom view.declName infos parentType fun infos => go (i+1) infos (copiedParents.push parentType) -- TODO: if `class`, then we need to create a let-decl that stores the local instance for the `parentStructure` else let env ← getEnv let subfieldNames := getStructureFieldsFlattened env parentStructName let toParentName := mkToParentName parentStructName fun n => !containsFieldName infos n && !subfieldNames.contains n let binfo := if view.isClass && isClass env parentStructName then BinderInfo.instImplicit else BinderInfo.default withLocalDecl toParentName binfo parentType fun parentFVar => let infos := infos.push { name := toParentName, declName := view.declName ++ toParentName, fvar := parentFVar, kind := StructFieldKind.subobject } processSubfields view.declName parentFVar parentStructName subfieldNames infos fun infos => go (i+1) infos copiedParents else k infos copiedParents private def elabFieldTypeValue (view : StructFieldView) : TermElabM (Option Expr × Option Expr) := do Term.withAutoBoundImplicit <| Term.elabBinders view.binders.getArgs fun params => do match view.type? with | none => match view.value? with | none => return (none, none) | some valStx => Term.synthesizeSyntheticMVarsNoPostponing let params ← Term.addAutoBoundImplicits params let value ← Term.elabTerm valStx none let value ← mkLambdaFVars params value return (none, value) | some typeStx => let type ← Term.elabType typeStx Term.synthesizeSyntheticMVarsNoPostponing let params ← Term.addAutoBoundImplicits params match view.value? with | none => let type ← mkForallFVars params type return (type, none) | some valStx => let value ← Term.elabTermEnsuringType valStx type Term.synthesizeSyntheticMVarsNoPostponing let type ← mkForallFVars params type let value ← mkLambdaFVars params value return (type, value) private partial def withFields (views : Array StructFieldView) (infos : Array StructFieldInfo) (k : Array StructFieldInfo → TermElabM α) : TermElabM α := do go 0 {} infos where go (i : Nat) (defaultValsOverridden : NameSet) (infos : Array StructFieldInfo) : TermElabM α := do if h : i < views.size then let view := views.get ⟨i, h⟩ withRef view.ref do match findFieldInfo? infos view.name with | none => let (type?, value?) ← elabFieldTypeValue view match type?, value? with | none, none => throwError "invalid field, type expected" | some type, _ => withLocalDecl view.name view.binderInfo type fun fieldFVar => let infos := infos.push { name := view.name, declName := view.declName, fvar := fieldFVar, value? := value?, kind := StructFieldKind.newField, inferMod := view.inferMod } go (i+1) defaultValsOverridden infos | none, some value => let type ← inferType value withLocalDecl view.name view.binderInfo type fun fieldFVar => let infos := infos.push { name := view.name, declName := view.declName, fvar := fieldFVar, value? := value, kind := StructFieldKind.newField, inferMod := view.inferMod } go (i+1) defaultValsOverridden infos | some info => let updateDefaultValue (fromParent : Bool) : TermElabM α := do match view.value? with | none => throwError "field '{view.name}' has been declared in parent structure" | some valStx => if let some type := view.type? then throwErrorAt type "omit field '{view.name}' type to set default value" else if defaultValsOverridden.contains info.name then throwError "field '{view.name}' new default value has already been set" let defaultValsOverridden := defaultValsOverridden.insert info.name let mut valStx := valStx if view.binders.getArgs.size > 0 then valStx ← `(fun $(view.binders.getArgs)* => $valStx:term) let fvarType ← inferType info.fvar let value ← Term.elabTermEnsuringType valStx fvarType let infos := updateFieldInfoVal infos info.name value go (i+1) defaultValsOverridden infos match info.kind with | StructFieldKind.newField => throwError "field '{view.name}' has already been declared" | StructFieldKind.subobject => throwError "unexpected subobject field reference" -- improve error message | StructFieldKind.copiedField => updateDefaultValue false | StructFieldKind.fromParent => updateDefaultValue true else k infos private def getResultUniverse (type : Expr) : TermElabM Level := do let type ← whnf type match type with | Expr.sort u _ => pure u | _ => throwError "unexpected structure resulting type" private def collectUsed (params : Array Expr) (fieldInfos : Array StructFieldInfo) : StateRefT CollectFVars.State MetaM Unit := do params.forM fun p => do let type ← inferType p Term.collectUsedFVars type fieldInfos.forM fun info => do let fvarType ← inferType info.fvar Term.collectUsedFVars fvarType match info.value? with | none => pure () | some value => Term.collectUsedFVars value private def removeUnused (scopeVars : Array Expr) (params : Array Expr) (fieldInfos : Array StructFieldInfo) : TermElabM (LocalContext × LocalInstances × Array Expr) := do let (_, used) ← (collectUsed params fieldInfos).run {} Term.removeUnused scopeVars used private def withUsed {α} (scopeVars : Array Expr) (params : Array Expr) (fieldInfos : Array StructFieldInfo) (k : Array Expr → TermElabM α) : TermElabM α := do let (lctx, localInsts, vars) ← removeUnused scopeVars params fieldInfos withLCtx lctx localInsts <| k vars private def levelMVarToParamFVar (fvar : Expr) : StateRefT Nat TermElabM Unit := do let type ← inferType fvar discard <| Term.levelMVarToParam' type private def levelMVarToParamFVars (fvars : Array Expr) : StateRefT Nat TermElabM Unit := fvars.forM levelMVarToParamFVar private def levelMVarToParamAux (scopeVars : Array Expr) (params : Array Expr) (fieldInfos : Array StructFieldInfo) : StateRefT Nat TermElabM (Array StructFieldInfo) := do levelMVarToParamFVars scopeVars levelMVarToParamFVars params fieldInfos.mapM fun info => do levelMVarToParamFVar info.fvar match info.value? with | none => pure info | some value => let value ← Term.levelMVarToParam' value pure { info with value? := value } private def levelMVarToParam (scopeVars : Array Expr) (params : Array Expr) (fieldInfos : Array StructFieldInfo) : TermElabM (Array StructFieldInfo) := (levelMVarToParamAux scopeVars params fieldInfos).run' 1 private partial def collectUniversesFromFields (r : Level) (rOffset : Nat) (fieldInfos : Array StructFieldInfo) : TermElabM (Array Level) := do fieldInfos.foldlM (init := #[]) fun (us : Array Level) (info : StructFieldInfo) => do let type ← inferType info.fvar let u ← getLevel type let u ← instantiateLevelMVars u accLevelAtCtor u r rOffset us private def updateResultingUniverse (fieldInfos : Array StructFieldInfo) (type : Expr) : TermElabM Expr := do let r ← getResultUniverse type let rOffset : Nat := r.getOffset let r : Level := r.getLevelOffset match r with | Level.mvar mvarId _ => let us ← collectUniversesFromFields r rOffset fieldInfos let rNew := mkResultUniverse us rOffset assignLevelMVar mvarId rNew instantiateMVars type | _ => throwError "failed to compute resulting universe level of structure, provide universe explicitly" private def collectLevelParamsInFVar (s : CollectLevelParams.State) (fvar : Expr) : TermElabM CollectLevelParams.State := do let type ← inferType fvar let type ← instantiateMVars type return collectLevelParams s type private def collectLevelParamsInFVars (fvars : Array Expr) (s : CollectLevelParams.State) : TermElabM CollectLevelParams.State := fvars.foldlM collectLevelParamsInFVar s private def collectLevelParamsInStructure (structType : Expr) (scopeVars : Array Expr) (params : Array Expr) (fieldInfos : Array StructFieldInfo) : TermElabM (Array Name) := do let s := collectLevelParams {} structType let s ← collectLevelParamsInFVars scopeVars s let s ← collectLevelParamsInFVars params s let s ← fieldInfos.foldlM (init := s) fun s info => collectLevelParamsInFVar s info.fvar return s.params private def addCtorFields (fieldInfos : Array StructFieldInfo) : Nat → Expr → TermElabM Expr | 0, type => pure type | i+1, type => do let info := fieldInfos[i] let decl ← Term.getFVarLocalDecl! info.fvar let type ← instantiateMVars type let type := type.abstract #[info.fvar] match info.kind with | StructFieldKind.fromParent => let val := decl.value addCtorFields fieldInfos i (type.instantiate1 val) | _ => addCtorFields fieldInfos i (mkForall decl.userName decl.binderInfo decl.type type) private def mkCtor (view : StructView) (levelParams : List Name) (params : Array Expr) (fieldInfos : Array StructFieldInfo) : TermElabM Constructor := withRef view.ref do let type := mkAppN (mkConst view.declName (levelParams.map mkLevelParam)) params let type ← addCtorFields fieldInfos fieldInfos.size type let type ← mkForallFVars params type let type ← instantiateMVars type let type := type.inferImplicit params.size !view.ctor.inferMod -- trace[Meta.debug] "ctor type {type}" pure { name := view.ctor.declName, type } @[extern "lean_mk_projections"] private constant mkProjections (env : Environment) (structName : Name) (projs : List ProjectionInfo) (isClass : Bool) : Except KernelException Environment private def addProjections (structName : Name) (projs : List ProjectionInfo) (isClass : Bool) : TermElabM Unit := do let env ← getEnv match mkProjections env structName projs isClass with | Except.ok env => setEnv env | Except.error ex => throwKernelException ex private def registerStructure (structName : Name) (infos : Array StructFieldInfo) : TermElabM Unit := do let fields ← infos.filterMapM fun info => do if info.kind == StructFieldKind.fromParent then return none else return some { fieldName := info.name projFn := info.declName inferMod := info.inferMod binderInfo := (← getFVarLocalDecl info.fvar).binderInfo subobject? := if info.kind == StructFieldKind.subobject then match (← getEnv).find? info.declName with | some (ConstantInfo.defnInfo val) => match val.type.getForallBody.getAppFn with | Expr.const parentName .. => some parentName | _ => panic! "ill-formed structure" | _ => panic! "ill-formed environment" else none } modifyEnv fun env => Lean.registerStructure env { structName, fields } private def mkAuxConstructions (declName : Name) : TermElabM Unit := do let env ← getEnv let hasUnit := env.contains `PUnit let hasEq := env.contains `Eq let hasHEq := env.contains `HEq mkRecOn declName if hasUnit then mkCasesOn declName if hasUnit && hasEq && hasHEq then mkNoConfusion declName private def addDefaults (lctx : LocalContext) (defaultAuxDecls : Array (Name × Expr × Expr)) : TermElabM Unit := do let localInsts ← getLocalInstances withLCtx lctx localInsts do defaultAuxDecls.forM fun (declName, type, value) => do let value ← instantiateMVars value if value.hasExprMVar then throwError "invalid default value for field, it contains metavariables{indentExpr value}" /- The identity function is used as "marker". -/ let value ← mkId value discard <| mkAuxDefinition declName type value (zeta := true) setReducibleAttribute declName private partial def mkCoercionToCopiedParent (levelParams : List Name) (params : Array Expr) (view : StructView) (parentType : Expr) : MetaM Unit := do let env ← getEnv let structName := view.declName let sourceFieldNames := getStructureFieldsFlattened env structName let structType ← mkAppN (Lean.mkConst structName (levelParams.map mkLevelParam)) params let Expr.const parentStructName us _ ← pure parentType.getAppFn | unreachable! let binfo := if view.isClass && isClass env parentStructName then BinderInfo.instImplicit else BinderInfo.default withLocalDecl `self binfo structType fun source => do let declType ← instantiateMVars (← mkForallFVars params (← mkForallFVars #[source] parentType)) let declType := declType.inferImplicit params.size true let rec copyFields (parentType : Expr) : MetaM Expr := do let Expr.const parentStructName us _ ← pure parentType.getAppFn | unreachable! let parentCtor := getStructureCtor env parentStructName let mut result := mkAppN (mkConst parentCtor.name us) parentType.getAppArgs for fieldName in getStructureFields env parentStructName do if sourceFieldNames.contains fieldName then let fieldVal ← mkProjection source fieldName result := mkApp result fieldVal else -- fieldInfo must be a field of `parentStructName` let some fieldInfo ← getFieldInfo? env parentStructName fieldName | unreachable! if fieldInfo.subobject?.isNone then throwError "failed to build coercion to parent structure" let resultType ← whnfD (← inferType result) unless resultType.isForall do throwError "failed to build coercion to parent structure, unexpect type{indentExpr resultType}" let fieldVal ← copyFields resultType.bindingDomain! result := mkApp result fieldVal return result let declVal ← instantiateMVars (← mkLambdaFVars params (← mkLambdaFVars #[source] (← copyFields parentType))) let declName := structName ++ mkToParentName (← getStructureName parentType) fun n => !env.contains (structName ++ n) addAndCompile <| Declaration.defnDecl { name := declName levelParams := levelParams type := declType value := declVal hints := ReducibilityHints.abbrev safety := if view.modifiers.isUnsafe then DefinitionSafety.unsafe else DefinitionSafety.safe } if binfo.isInstImplicit then addInstance declName AttributeKind.global (eval_prio default) else setReducibleAttribute declName private def elabStructureView (view : StructView) : TermElabM Unit := do view.fields.forM fun field => do if field.declName == view.ctor.declName then throwErrorAt field.ref "invalid field name '{field.name}', it is equal to structure constructor name" addAuxDeclarationRanges field.declName field.ref field.ref let numExplicitParams := view.params.size let type ← Term.elabType view.type unless validStructType type do throwErrorAt view.type "expected Type" withRef view.ref do withParents view fun fieldInfos copiedParents => do withFields view.fields fieldInfos fun fieldInfos => do Term.synthesizeSyntheticMVarsNoPostponing let u ← getResultUniverse type let inferLevel ← shouldInferResultUniverse u withUsed view.scopeVars view.params fieldInfos fun scopeVars => do let numParams := scopeVars.size + numExplicitParams let fieldInfos ← levelMVarToParam scopeVars view.params fieldInfos let type ← withRef view.ref do if inferLevel then updateResultingUniverse fieldInfos type else checkResultingUniverse (← getResultUniverse type) pure type trace[Elab.structure] "type: {type}" let usedLevelNames ← collectLevelParamsInStructure type scopeVars view.params fieldInfos match sortDeclLevelParams view.scopeLevelNames view.allUserLevelNames usedLevelNames with | Except.error msg => withRef view.ref <| throwError msg | Except.ok levelParams => let params := scopeVars ++ view.params let ctor ← mkCtor view levelParams params fieldInfos let type ← mkForallFVars params type let type ← instantiateMVars type let indType := { name := view.declName, type := type, ctors := [ctor] : InductiveType } let decl := Declaration.inductDecl levelParams params.size [indType] view.modifiers.isUnsafe Term.ensureNoUnassignedMVars decl addDecl decl let projInfos := (fieldInfos.filter fun (info : StructFieldInfo) => !info.isFromParent).toList.map fun (info : StructFieldInfo) => { declName := info.declName, inferMod := info.inferMod : ProjectionInfo } addProjections view.declName projInfos view.isClass registerStructure view.declName fieldInfos mkAuxConstructions view.declName let instParents ← fieldInfos.filterM fun info => do let decl ← Term.getFVarLocalDecl! info.fvar pure (info.isSubobject && decl.binderInfo.isInstImplicit) let projInstances := instParents.toList.map fun info => info.declName Term.applyAttributesAt view.declName view.modifiers.attrs AttributeApplicationTime.afterTypeChecking projInstances.forM fun declName => addInstance declName AttributeKind.global (eval_prio default) copiedParents.forM fun parent => mkCoercionToCopiedParent levelParams params view parent let lctx ← getLCtx let fieldsWithDefault := fieldInfos.filter fun info => info.value?.isSome let defaultAuxDecls ← fieldsWithDefault.mapM fun info => do let type ← inferType info.fvar pure (mkDefaultFnOfProjFn info.declName, type, info.value?.get!) /- The `lctx` and `defaultAuxDecls` are used to create the auxiliary "default value" declarations The parameters `params` for these definitions must be marked as implicit, and all others as explicit. -/ let lctx := params.foldl (init := lctx) fun (lctx : LocalContext) (p : Expr) => lctx.setBinderInfo p.fvarId! BinderInfo.implicit let lctx := fieldInfos.foldl (init := lctx) fun (lctx : LocalContext) (info : StructFieldInfo) => if info.isFromParent then lctx -- `fromParent` fields are elaborated as let-decls, and are zeta-expanded when creating "default value" auxiliary functions else lctx.setBinderInfo info.fvar.fvarId! BinderInfo.default addDefaults lctx defaultAuxDecls /- leading_parser (structureTk <|> classTk) >> declId >> many Term.bracketedBinder >> optional «extends» >> Term.optType >> " := " >> optional structCtor >> structFields >> optDeriving where def «extends» := leading_parser " extends " >> sepBy1 termParser ", " def typeSpec := leading_parser " : " >> termParser def optType : Parser := optional typeSpec def structFields := leading_parser many (structExplicitBinder <|> structImplicitBinder <|> structInstBinder) def structCtor := leading_parser try (declModifiers >> ident >> optional inferMod >> " :: ") -/ def elabStructure (modifiers : Modifiers) (stx : Syntax) : CommandElabM Unit := do checkValidInductiveModifier modifiers let isClass := stx[0].getKind == ``Parser.Command.classTk let modifiers := if isClass then modifiers.addAttribute { name := `class } else modifiers let declId := stx[1] let params := stx[2].getArgs let exts := stx[3] let parents := if exts.isNone then #[] else exts[0][1].getSepArgs let optType := stx[4] let derivingClassViews ← getOptDerivingClasses stx[6] let type ← if optType.isNone then `(Sort _) else pure optType[0][1] let declName ← runTermElabM none fun scopeVars => do let scopeLevelNames ← Term.getLevelNames let ⟨name, declName, allUserLevelNames⟩ ← Elab.expandDeclId (← getCurrNamespace) scopeLevelNames declId modifiers addDeclarationRanges declName stx Term.withDeclName declName do let ctor ← expandCtor stx modifiers declName let fields ← expandFields stx modifiers declName Term.withLevelNames allUserLevelNames <| Term.withAutoBoundImplicit <| Term.elabBinders params fun params => do Term.synthesizeSyntheticMVarsNoPostponing let params ← Term.addAutoBoundImplicits params let allUserLevelNames ← Term.getLevelNames elabStructureView { ref := stx modifiers scopeLevelNames allUserLevelNames declName isClass scopeVars params parents type ctor fields } unless isClass do mkSizeOfInstances declName mkInjectiveTheorems declName return declName derivingClassViews.forM fun view => view.applyHandlers #[declName] builtin_initialize registerTraceClass `Elab.structure end Lean.Elab.Command
78c73c77d735eeb2f847012b3e91f34a7dbd6603
9dc8cecdf3c4634764a18254e94d43da07142918
/src/group_theory/subgroup/basic.lean
e48c5119b27b08f8fef6d53f790b663bbbf9ea4d
[ "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
131,778
lean
/- Copyright (c) 2020 Kexing Ying. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kexing Ying -/ import group_theory.submonoid.pointwise import group_theory.submonoid.membership import group_theory.submonoid.centralizer import algebra.group.conj import algebra.module.basic import order.atoms import order.sup_indep /-! # Subgroups This file defines multiplicative and additive subgroups as an extension of submonoids, in a bundled form (unbundled subgroups are in `deprecated/subgroups.lean`). We prove subgroups of a group form a complete lattice, and results about images and preimages of subgroups under group homomorphisms. The bundled subgroups use bundled monoid homomorphisms. There are also theorems about the subgroups generated by an element or a subset of a group, defined both inductively and as the infimum of the set of subgroups containing a given element/subset. Special thanks goes to Amelia Livingston and Yury Kudryashov for their help and inspiration. ## Main definitions Notation used here: - `G N` are `group`s - `A` is an `add_group` - `H K` are `subgroup`s of `G` or `add_subgroup`s of `A` - `x` is an element of type `G` or type `A` - `f g : N →* G` are group homomorphisms - `s k` are sets of elements of type `G` Definitions in the file: * `subgroup G` : the type of subgroups of a group `G` * `add_subgroup A` : the type of subgroups of an additive group `A` * `complete_lattice (subgroup G)` : the subgroups of `G` form a complete lattice * `subgroup.closure k` : the minimal subgroup that includes the set `k` * `subgroup.subtype` : the natural group homomorphism from a subgroup of group `G` to `G` * `subgroup.gi` : `closure` forms a Galois insertion with the coercion to set * `subgroup.comap H f` : the preimage of a subgroup `H` along the group homomorphism `f` is also a subgroup * `subgroup.map f H` : the image of a subgroup `H` along the group homomorphism `f` is also a subgroup * `subgroup.prod H K` : the product of subgroups `H`, `K` of groups `G`, `N` respectively, `H × K` is a subgroup of `G × N` * `monoid_hom.range f` : the range of the group homomorphism `f` is a subgroup * `monoid_hom.ker f` : the kernel of a group homomorphism `f` is the subgroup of elements `x : G` such that `f x = 1` * `monoid_hom.eq_locus f g` : given group homomorphisms `f`, `g`, the elements of `G` such that `f x = g x` form a subgroup of `G` * `is_simple_group G` : a class indicating that a group has exactly two normal subgroups ## Implementation notes Subgroup inclusion is denoted `≤` rather than `⊆`, although `∈` is defined as membership of a subgroup's underlying set. ## Tags subgroup, subgroups -/ open_locale big_operators pointwise variables {G : Type*} [group G] variables {A : Type*} [add_group A] section subgroup_class /-- `inv_mem_class S G` states `S` is a type of subsets `s ⊆ G` closed under inverses. -/ class inv_mem_class (S G : Type*) [has_inv G] [set_like S G] := (inv_mem : ∀ {s : S} {x}, x ∈ s → x⁻¹ ∈ s) export inv_mem_class (inv_mem) /-- `neg_mem_class S G` states `S` is a type of subsets `s ⊆ G` closed under negation. -/ class neg_mem_class (S G : Type*) [has_neg G] [set_like S G] := (neg_mem : ∀ {s : S} {x}, x ∈ s → -x ∈ s) export neg_mem_class (neg_mem) /-- `subgroup_class S G` states `S` is a type of subsets `s ⊆ G` that are subgroups of `G`. -/ class subgroup_class (S G : Type*) [div_inv_monoid G] [set_like S G] extends submonoid_class S G := (inv_mem : ∀ {s : S} {x}, x ∈ s → x⁻¹ ∈ s) /-- `add_subgroup_class S G` states `S` is a type of subsets `s ⊆ G` that are additive subgroups of `G`. -/ class add_subgroup_class (S G : Type*) [sub_neg_monoid G] [set_like S G] extends add_submonoid_class S G := (neg_mem : ∀ {s : S} {x}, x ∈ s → -x ∈ s) attribute [to_additive] inv_mem_class subgroup_class variables (M S : Type*) [div_inv_monoid M] [set_like S M] [hSM : subgroup_class S M] include hSM @[to_additive, priority 100] -- See note [lower instance priority] instance subgroup_class.to_inv_mem_class : inv_mem_class S M := { .. hSM } variables {S M} {H K : S} /-- A subgroup is closed under division. -/ @[to_additive "An additive subgroup is closed under subtraction."] theorem div_mem {x y : M} (hx : x ∈ H) (hy : y ∈ H) : x / y ∈ H := by rw [div_eq_mul_inv]; exact mul_mem hx (inv_mem hy) @[to_additive] lemma zpow_mem {x : M} (hx : x ∈ K) : ∀ n : ℤ, x ^ n ∈ K | (n : ℕ) := by { rw [zpow_coe_nat], exact pow_mem hx n } | -[1+ n] := by { rw [zpow_neg_succ_of_nat], exact inv_mem (pow_mem hx n.succ) } omit hSM variables [set_like S G] [hSG : subgroup_class S G] include hSG @[simp, to_additive] theorem inv_mem_iff {x : G} : x⁻¹ ∈ H ↔ x ∈ H := ⟨λ h, inv_inv x ▸ inv_mem h, inv_mem⟩ @[to_additive] lemma div_mem_comm_iff {a b : G} : a / b ∈ H ↔ b / a ∈ H := by rw [← inv_mem_iff, div_eq_mul_inv, div_eq_mul_inv, mul_inv_rev, inv_inv] @[simp, to_additive] theorem inv_coe_set : (H : set G)⁻¹ = H := by { ext, simp } @[simp, to_additive] lemma exists_inv_mem_iff_exists_mem {P : G → Prop} : (∃ (x : G), x ∈ H ∧ P x⁻¹) ↔ ∃ x ∈ H, P x := by split; { rintros ⟨x, x_in, hx⟩, exact ⟨x⁻¹, inv_mem x_in, by simp [hx]⟩ } @[to_additive] lemma mul_mem_cancel_right {x y : G} (h : x ∈ H) : y * x ∈ H ↔ y ∈ H := ⟨λ hba, by simpa using mul_mem hba (inv_mem h), λ hb, mul_mem hb h⟩ @[to_additive] lemma mul_mem_cancel_left {x y : G} (h : x ∈ H) : x * y ∈ H ↔ y ∈ H := ⟨λ hab, by simpa using mul_mem (inv_mem h) hab, mul_mem h⟩ namespace subgroup_class omit hSG include hSM /-- A subgroup of a group inherits an inverse. -/ @[to_additive "An additive subgroup of a `add_group` inherits an inverse."] instance has_inv : has_inv H := ⟨λ a, ⟨a⁻¹, inv_mem a.2⟩⟩ /-- A subgroup of a group inherits a division -/ @[to_additive "An additive subgroup of an `add_group` inherits a subtraction."] instance has_div : has_div H := ⟨λ a b, ⟨a / b, div_mem a.2 b.2⟩⟩ omit hSM /-- An additive subgroup of an `add_group` inherits an integer scaling. -/ instance _root_.add_subgroup_class.has_zsmul {M S} [sub_neg_monoid M] [set_like S M] [add_subgroup_class S M] {H : S} : has_smul ℤ H := ⟨λ n a, ⟨n • a, zsmul_mem a.2 n⟩⟩ include hSM /-- A subgroup of a group inherits an integer power. -/ @[to_additive] instance has_zpow : has_pow H ℤ := ⟨λ a n, ⟨a ^ n, zpow_mem a.2 n⟩⟩ @[simp, norm_cast, to_additive] lemma coe_inv (x : H) : ↑(x⁻¹ : H) = (x⁻¹ : M) := rfl @[simp, norm_cast, to_additive] lemma coe_div (x y : H) : (↑(x / y) : M) = ↑x / ↑y := rfl omit hSM variables (H) include hSG /-- A subgroup of a group inherits a group structure. -/ @[to_additive "An additive subgroup of an `add_group` inherits an `add_group` structure.", priority 75] -- Prefer subclasses of `group` over subclasses of `subgroup_class`. instance to_group : group H := subtype.coe_injective.group _ rfl (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) omit hSG /-- A subgroup of a `comm_group` is a `comm_group`. -/ @[to_additive "An additive subgroup of an `add_comm_group` is an `add_comm_group`.", priority 75] -- Prefer subclasses of `comm_group` over subclasses of `subgroup_class`. instance to_comm_group {G : Type*} [comm_group G] [set_like S G] [subgroup_class S G] : comm_group H := subtype.coe_injective.comm_group _ rfl (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) /-- A subgroup of an `ordered_comm_group` is an `ordered_comm_group`. -/ @[to_additive "An additive subgroup of an `add_ordered_comm_group` is an `add_ordered_comm_group`.", priority 75] -- Prefer subclasses of `group` over subclasses of `subgroup_class`. instance to_ordered_comm_group {G : Type*} [ordered_comm_group G] [set_like S G] [subgroup_class S G] : ordered_comm_group H := subtype.coe_injective.ordered_comm_group _ rfl (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) /-- A subgroup of a `linear_ordered_comm_group` is a `linear_ordered_comm_group`. -/ @[to_additive "An additive subgroup of a `linear_ordered_add_comm_group` is a `linear_ordered_add_comm_group`.", priority 75] -- Prefer subclasses of `group` over subclasses of `subgroup_class`. instance to_linear_ordered_comm_group {G : Type*} [linear_ordered_comm_group G] [set_like S G] [subgroup_class S G] : linear_ordered_comm_group H := subtype.coe_injective.linear_ordered_comm_group _ rfl (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) include hSG /-- The natural group hom from a subgroup of group `G` to `G`. -/ @[to_additive "The natural group hom from an additive subgroup of `add_group` `G` to `G`."] def subtype : H →* G := ⟨coe, rfl, λ _ _, rfl⟩ @[simp, to_additive] theorem coe_subtype : (subtype H : H → G) = coe := rfl variables {H} @[simp, norm_cast, to_additive coe_smul] lemma coe_pow (x : H) (n : ℕ) : ((x ^ n : H) : G) = x ^ n := (subtype H : H →* G).map_pow _ _ @[simp, norm_cast, to_additive] lemma coe_zpow (x : H) (n : ℤ) : ((x ^ n : H) : G) = x ^ n := (subtype H : H →* G).map_zpow _ _ /-- The inclusion homomorphism from a subgroup `H` contained in `K` to `K`. -/ @[to_additive "The inclusion homomorphism from a additive subgroup `H` contained in `K` to `K`."] def inclusion {H K : S} (h : H ≤ K) : H →* K := monoid_hom.mk' (λ x, ⟨x, h x.prop⟩) (λ ⟨a, ha⟩ ⟨b, hb⟩, rfl) @[simp, to_additive] lemma inclusion_self (x : H) : inclusion le_rfl x = x := by { cases x, refl } @[simp, to_additive] lemma inclusion_mk {h : H ≤ K} (x : G) (hx : x ∈ H) : inclusion h ⟨x, hx⟩ = ⟨x, h hx⟩ := rfl @[to_additive] lemma inclusion_right (h : H ≤ K) (x : K) (hx : (x : G) ∈ H) : inclusion h ⟨x, hx⟩ = x := by { cases x, refl } @[simp] lemma inclusion_inclusion {L : S} (hHK : H ≤ K) (hKL : K ≤ L) (x : H) : inclusion hKL (inclusion hHK x) = inclusion (hHK.trans hKL) x := by { cases x, refl } @[simp, to_additive] lemma coe_inclusion {H K : S} {h : H ≤ K} (a : H) : (inclusion h a : G) = a := by { cases a, simp only [inclusion, set_like.coe_mk, monoid_hom.mk'_apply] } @[simp, to_additive] lemma subtype_comp_inclusion {H K : S} (hH : H ≤ K) : (subtype K).comp (inclusion hH) = subtype H := by { ext, simp only [monoid_hom.comp_apply, coe_subtype, coe_inclusion] } end subgroup_class end subgroup_class set_option old_structure_cmd true /-- A subgroup of a group `G` is a subset containing 1, closed under multiplication and closed under multiplicative inverse. -/ structure subgroup (G : Type*) [group G] extends submonoid G := (inv_mem' {x} : x ∈ carrier → x⁻¹ ∈ carrier) /-- An additive subgroup of an additive group `G` is a subset containing 0, closed under addition and additive inverse. -/ structure add_subgroup (G : Type*) [add_group G] extends add_submonoid G:= (neg_mem' {x} : x ∈ carrier → -x ∈ carrier) attribute [to_additive] subgroup attribute [to_additive add_subgroup.to_add_submonoid] subgroup.to_submonoid /-- Reinterpret a `subgroup` as a `submonoid`. -/ add_decl_doc subgroup.to_submonoid /-- Reinterpret an `add_subgroup` as an `add_submonoid`. -/ add_decl_doc add_subgroup.to_add_submonoid namespace subgroup @[to_additive] instance : set_like (subgroup G) G := { coe := subgroup.carrier, coe_injective' := λ p q h, by cases p; cases q; congr' } @[to_additive] instance : subgroup_class (subgroup G) G := { mul_mem := subgroup.mul_mem', one_mem := subgroup.one_mem', inv_mem := subgroup.inv_mem' } @[simp, to_additive] lemma mem_carrier {s : subgroup G} {x : G} : x ∈ s.carrier ↔ x ∈ s := iff.rfl @[simp, to_additive] lemma mem_mk {s : set G} {x : G} (h_one) (h_mul) (h_inv) : x ∈ mk s h_one h_mul h_inv ↔ x ∈ s := iff.rfl @[simp, to_additive] lemma coe_set_mk {s : set G} (h_one) (h_mul) (h_inv) : (mk s h_one h_mul h_inv : set G) = s := rfl @[simp, to_additive] lemma mk_le_mk {s t : set G} (h_one) (h_mul) (h_inv) (h_one') (h_mul') (h_inv') : mk s h_one h_mul h_inv ≤ mk t h_one' h_mul' h_inv' ↔ s ⊆ t := iff.rfl /-- See Note [custom simps projection] -/ @[to_additive "See Note [custom simps projection]"] def simps.coe (S : subgroup G) : set G := S initialize_simps_projections subgroup (carrier → coe) initialize_simps_projections add_subgroup (carrier → coe) @[simp, to_additive] lemma coe_to_submonoid (K : subgroup G) : (K.to_submonoid : set G) = K := rfl @[simp, to_additive] lemma mem_to_submonoid (K : subgroup G) (x : G) : x ∈ K.to_submonoid ↔ x ∈ K := iff.rfl @[to_additive] instance (K : subgroup G) [d : decidable_pred (∈ K)] [fintype G] : fintype K := show fintype {g : G // g ∈ K}, from infer_instance @[to_additive] theorem to_submonoid_injective : function.injective (to_submonoid : subgroup G → submonoid G) := λ p q h, set_like.ext'_iff.2 (show _, from set_like.ext'_iff.1 h) @[simp, to_additive] theorem to_submonoid_eq {p q : subgroup G} : p.to_submonoid = q.to_submonoid ↔ p = q := to_submonoid_injective.eq_iff @[to_additive, mono] lemma to_submonoid_strict_mono : strict_mono (to_submonoid : subgroup G → submonoid G) := λ _ _, id attribute [mono] add_subgroup.to_add_submonoid_strict_mono @[to_additive, mono] lemma to_submonoid_mono : monotone (to_submonoid : subgroup G → submonoid G) := to_submonoid_strict_mono.monotone attribute [mono] add_subgroup.to_add_submonoid_mono @[simp, to_additive] lemma to_submonoid_le {p q : subgroup G} : p.to_submonoid ≤ q.to_submonoid ↔ p ≤ q := iff.rfl end subgroup /-! ### Conversion to/from `additive`/`multiplicative` -/ section mul_add /-- Supgroups of a group `G` are isomorphic to additive subgroups of `additive G`. -/ @[simps] def subgroup.to_add_subgroup : subgroup G ≃o add_subgroup (additive G) := { to_fun := λ S, { neg_mem' := λ _, S.inv_mem', ..S.to_submonoid.to_add_submonoid }, inv_fun := λ S, { inv_mem' := λ _, S.neg_mem', ..S.to_add_submonoid.to_submonoid' }, left_inv := λ x, by cases x; refl, right_inv := λ x, by cases x; refl, map_rel_iff' := λ a b, iff.rfl, } /-- Additive subgroup of an additive group `additive G` are isomorphic to subgroup of `G`. -/ abbreviation add_subgroup.to_subgroup' : add_subgroup (additive G) ≃o subgroup G := subgroup.to_add_subgroup.symm /-- Additive supgroups of an additive group `A` are isomorphic to subgroups of `multiplicative A`. -/ @[simps] def add_subgroup.to_subgroup : add_subgroup A ≃o subgroup (multiplicative A) := { to_fun := λ S, { inv_mem' := λ _, S.neg_mem', ..S.to_add_submonoid.to_submonoid }, inv_fun := λ S, { neg_mem' := λ _, S.inv_mem', ..S.to_submonoid.to_add_submonoid' }, left_inv := λ x, by cases x; refl, right_inv := λ x, by cases x; refl, map_rel_iff' := λ a b, iff.rfl, } /-- Subgroups of an additive group `multiplicative A` are isomorphic to additive subgroups of `A`. -/ abbreviation subgroup.to_add_subgroup' : subgroup (multiplicative A) ≃o add_subgroup A := add_subgroup.to_subgroup.symm end mul_add namespace subgroup variables (H K : subgroup G) /-- Copy of a subgroup with a new `carrier` equal to the old one. Useful to fix definitional equalities.-/ @[to_additive "Copy of an additive subgroup with a new `carrier` equal to the old one. Useful to fix definitional equalities"] protected def copy (K : subgroup G) (s : set G) (hs : s = K) : subgroup G := { carrier := s, one_mem' := hs.symm ▸ K.one_mem', mul_mem' := λ _ _, hs.symm ▸ K.mul_mem', inv_mem' := λ _, hs.symm ▸ K.inv_mem' } @[simp, to_additive] lemma coe_copy (K : subgroup G) (s : set G) (hs : s = ↑K) : (K.copy s hs : set G) = s := rfl @[to_additive] lemma copy_eq (K : subgroup G) (s : set G) (hs : s = ↑K) : K.copy s hs = K := set_like.coe_injective hs /-- Two subgroups are equal if they have the same elements. -/ @[ext, to_additive "Two `add_subgroup`s are equal if they have the same elements."] theorem ext {H K : subgroup G} (h : ∀ x, x ∈ H ↔ x ∈ K) : H = K := set_like.ext h /-- A subgroup contains the group's 1. -/ @[to_additive "An `add_subgroup` contains the group's 0."] protected theorem one_mem : (1 : G) ∈ H := one_mem _ /-- A subgroup is closed under multiplication. -/ @[to_additive "An `add_subgroup` is closed under addition."] protected theorem mul_mem {x y : G} : x ∈ H → y ∈ H → x * y ∈ H := mul_mem /-- A subgroup is closed under inverse. -/ @[to_additive "An `add_subgroup` is closed under inverse."] protected theorem inv_mem {x : G} : x ∈ H → x⁻¹ ∈ H := inv_mem /-- A subgroup is closed under division. -/ @[to_additive "An `add_subgroup` is closed under subtraction."] protected theorem div_mem {x y : G} (hx : x ∈ H) (hy : y ∈ H) : x / y ∈ H := div_mem hx hy @[to_additive] protected theorem inv_mem_iff {x : G} : x⁻¹ ∈ H ↔ x ∈ H := inv_mem_iff @[to_additive] protected lemma div_mem_comm_iff {a b : G} : a / b ∈ H ↔ b / a ∈ H := div_mem_comm_iff @[to_additive] protected theorem inv_coe_set : (H : set G)⁻¹ = H := by { ext, simp } @[to_additive] protected lemma exists_inv_mem_iff_exists_mem (K : subgroup G) {P : G → Prop} : (∃ (x : G), x ∈ K ∧ P x⁻¹) ↔ ∃ x ∈ K, P x := exists_inv_mem_iff_exists_mem @[to_additive] protected lemma mul_mem_cancel_right {x y : G} (h : x ∈ H) : y * x ∈ H ↔ y ∈ H := mul_mem_cancel_right h @[to_additive] protected lemma mul_mem_cancel_left {x y : G} (h : x ∈ H) : x * y ∈ H ↔ y ∈ H := mul_mem_cancel_left h /-- Product of a list of elements in a subgroup is in the subgroup. -/ @[to_additive "Sum of a list of elements in an `add_subgroup` is in the `add_subgroup`."] protected lemma list_prod_mem {l : list G} : (∀ x ∈ l, x ∈ K) → l.prod ∈ K := list_prod_mem /-- Product of a multiset of elements in a subgroup of a `comm_group` is in the subgroup. -/ @[to_additive "Sum of a multiset of elements in an `add_subgroup` of an `add_comm_group` is in the `add_subgroup`."] protected lemma multiset_prod_mem {G} [comm_group G] (K : subgroup G) (g : multiset G) : (∀ a ∈ g, a ∈ K) → g.prod ∈ K := multiset_prod_mem g @[to_additive] lemma multiset_noncomm_prod_mem (K : subgroup G) (g : multiset G) (comm : ∀ (x ∈ g) (y ∈ g), commute x y) : (∀ a ∈ g, a ∈ K) → g.noncomm_prod comm ∈ K := K.to_submonoid.multiset_noncomm_prod_mem g comm /-- Product of elements of a subgroup of a `comm_group` indexed by a `finset` is in the subgroup. -/ @[to_additive "Sum of elements in an `add_subgroup` of an `add_comm_group` indexed by a `finset` is in the `add_subgroup`."] protected lemma prod_mem {G : Type*} [comm_group G] (K : subgroup G) {ι : Type*} {t : finset ι} {f : ι → G} (h : ∀ c ∈ t, f c ∈ K) : ∏ c in t, f c ∈ K := prod_mem h @[to_additive] lemma noncomm_prod_mem (K : subgroup G) {ι : Type*} {t : finset ι} {f : ι → G} (comm : ∀ (x ∈ t) (y ∈ t), commute (f x) (f y)) : (∀ c ∈ t, f c ∈ K) → t.noncomm_prod f comm ∈ K := K.to_submonoid.noncomm_prod_mem t f comm @[to_additive add_subgroup.nsmul_mem] protected lemma pow_mem {x : G} (hx : x ∈ K) : ∀ n : ℕ, x ^ n ∈ K := pow_mem hx @[to_additive] protected lemma zpow_mem {x : G} (hx : x ∈ K) : ∀ n : ℤ, x ^ n ∈ K := zpow_mem hx /-- Construct a subgroup from a nonempty set that is closed under division. -/ @[to_additive "Construct a subgroup from a nonempty set that is closed under subtraction"] def of_div (s : set G) (hsn : s.nonempty) (hs : ∀ x y ∈ s, x * y⁻¹ ∈ s) : subgroup G := have one_mem : (1 : G) ∈ s, from let ⟨x, hx⟩ := hsn in by simpa using hs x hx x hx, have inv_mem : ∀ x, x ∈ s → x⁻¹ ∈ s, from λ x hx, by simpa using hs 1 one_mem x hx, { carrier := s, one_mem' := one_mem, inv_mem' := inv_mem, mul_mem' := λ x y hx hy, by simpa using hs x hx y⁻¹ (inv_mem y hy) } /-- A subgroup of a group inherits a multiplication. -/ @[to_additive "An `add_subgroup` of an `add_group` inherits an addition."] instance has_mul : has_mul H := H.to_submonoid.has_mul /-- A subgroup of a group inherits a 1. -/ @[to_additive "An `add_subgroup` of an `add_group` inherits a zero."] instance has_one : has_one H := H.to_submonoid.has_one /-- A subgroup of a group inherits an inverse. -/ @[to_additive "A `add_subgroup` of a `add_group` inherits an inverse."] instance has_inv : has_inv H := ⟨λ a, ⟨a⁻¹, H.inv_mem a.2⟩⟩ /-- A subgroup of a group inherits a division -/ @[to_additive "An `add_subgroup` of an `add_group` inherits a subtraction."] instance has_div : has_div H := ⟨λ a b, ⟨a / b, H.div_mem a.2 b.2⟩⟩ /-- An `add_subgroup` of an `add_group` inherits a natural scaling. -/ instance _root_.add_subgroup.has_nsmul {G} [add_group G] {H : add_subgroup G} : has_smul ℕ H := ⟨λ n a, ⟨n • a, H.nsmul_mem a.2 n⟩⟩ /-- A subgroup of a group inherits a natural power -/ @[to_additive] instance has_npow : has_pow H ℕ := ⟨λ a n, ⟨a ^ n, H.pow_mem a.2 n⟩⟩ /-- An `add_subgroup` of an `add_group` inherits an integer scaling. -/ instance _root_.add_subgroup.has_zsmul {G} [add_group G] {H : add_subgroup G} : has_smul ℤ H := ⟨λ n a, ⟨n • a, H.zsmul_mem a.2 n⟩⟩ /-- A subgroup of a group inherits an integer power -/ @[to_additive] instance has_zpow : has_pow H ℤ := ⟨λ a n, ⟨a ^ n, H.zpow_mem a.2 n⟩⟩ @[simp, norm_cast, to_additive] lemma coe_mul (x y : H) : (↑(x * y) : G) = ↑x * ↑y := rfl @[simp, norm_cast, to_additive] lemma coe_one : ((1 : H) : G) = 1 := rfl @[simp, norm_cast, to_additive] lemma coe_inv (x : H) : ↑(x⁻¹ : H) = (x⁻¹ : G) := rfl @[simp, norm_cast, to_additive] lemma coe_div (x y : H) : (↑(x / y) : G) = ↑x / ↑y := rfl @[simp, norm_cast, to_additive] lemma coe_mk (x : G) (hx : x ∈ H) : ((⟨x, hx⟩ : H) : G) = x := rfl @[simp, norm_cast, to_additive] lemma coe_pow (x : H) (n : ℕ) : ((x ^ n : H) : G) = x ^ n := rfl @[simp, norm_cast, to_additive] lemma coe_zpow (x : H) (n : ℤ) : ((x ^ n : H) : G) = x ^ n := rfl /-- A subgroup of a group inherits a group structure. -/ @[to_additive "An `add_subgroup` of an `add_group` inherits an `add_group` structure."] instance to_group {G : Type*} [group G] (H : subgroup G) : group H := subtype.coe_injective.group _ rfl (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) /-- A subgroup of a `comm_group` is a `comm_group`. -/ @[to_additive "An `add_subgroup` of an `add_comm_group` is an `add_comm_group`."] instance to_comm_group {G : Type*} [comm_group G] (H : subgroup G) : comm_group H := subtype.coe_injective.comm_group _ rfl (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) /-- A subgroup of an `ordered_comm_group` is an `ordered_comm_group`. -/ @[to_additive "An `add_subgroup` of an `add_ordered_comm_group` is an `add_ordered_comm_group`."] instance to_ordered_comm_group {G : Type*} [ordered_comm_group G] (H : subgroup G) : ordered_comm_group H := subtype.coe_injective.ordered_comm_group _ rfl (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) /-- A subgroup of a `linear_ordered_comm_group` is a `linear_ordered_comm_group`. -/ @[to_additive "An `add_subgroup` of a `linear_ordered_add_comm_group` is a `linear_ordered_add_comm_group`."] instance to_linear_ordered_comm_group {G : Type*} [linear_ordered_comm_group G] (H : subgroup G) : linear_ordered_comm_group H := subtype.coe_injective.linear_ordered_comm_group _ rfl (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) /-- The natural group hom from a subgroup of group `G` to `G`. -/ @[to_additive "The natural group hom from an `add_subgroup` of `add_group` `G` to `G`."] def subtype : H →* G := ⟨coe, rfl, λ _ _, rfl⟩ @[simp, to_additive] theorem coe_subtype : ⇑H.subtype = coe := rfl @[simp, norm_cast, to_additive] theorem coe_list_prod (l : list H) : (l.prod : G) = (l.map coe).prod := submonoid_class.coe_list_prod l @[simp, norm_cast, to_additive] theorem coe_multiset_prod {G} [comm_group G] (H : subgroup G) (m : multiset H) : (m.prod : G) = (m.map coe).prod := submonoid_class.coe_multiset_prod m @[simp, norm_cast, to_additive] theorem coe_finset_prod {ι G} [comm_group G] (H : subgroup G) (f : ι → H) (s : finset ι) : ↑(∏ i in s, f i) = (∏ i in s, f i : G) := submonoid_class.coe_finset_prod f s /-- The inclusion homomorphism from a subgroup `H` contained in `K` to `K`. -/ @[to_additive "The inclusion homomorphism from a additive subgroup `H` contained in `K` to `K`."] def inclusion {H K : subgroup G} (h : H ≤ K) : H →* K := monoid_hom.mk' (λ x, ⟨x, h x.prop⟩) (λ ⟨a, ha⟩ ⟨b, hb⟩, rfl) @[simp, to_additive] lemma coe_inclusion {H K : subgroup G} {h : H ≤ K} (a : H) : (inclusion h a : G) = a := by { cases a, simp only [inclusion, coe_mk, monoid_hom.mk'_apply] } @[to_additive] lemma inclusion_injective {H K : subgroup G} (h : H ≤ K) : function.injective $ inclusion h := set.inclusion_injective h @[simp, to_additive] lemma subtype_comp_inclusion {H K : subgroup G} (hH : H ≤ K) : K.subtype.comp (inclusion hH) = H.subtype := by { ext, simp } /-- The subgroup `G` of the group `G`. -/ @[to_additive "The `add_subgroup G` of the `add_group G`."] instance : has_top (subgroup G) := ⟨{ inv_mem' := λ _ _, set.mem_univ _ , .. (⊤ : submonoid G) }⟩ /-- The top subgroup is isomorphic to the group. This is the group version of `submonoid.top_equiv`. -/ @[to_additive "The top additive subgroup is isomorphic to the additive group. This is the additive group version of `add_submonoid.top_equiv`.", simps] def top_equiv : (⊤ : subgroup G) ≃* G := submonoid.top_equiv /-- The trivial subgroup `{1}` of an group `G`. -/ @[to_additive "The trivial `add_subgroup` `{0}` of an `add_group` `G`."] instance : has_bot (subgroup G) := ⟨{ inv_mem' := λ _, by simp *, .. (⊥ : submonoid G) }⟩ @[to_additive] instance : inhabited (subgroup G) := ⟨⊥⟩ @[simp, to_additive] lemma mem_bot {x : G} : x ∈ (⊥ : subgroup G) ↔ x = 1 := iff.rfl @[simp, to_additive] lemma mem_top (x : G) : x ∈ (⊤ : subgroup G) := set.mem_univ x @[simp, to_additive] lemma coe_top : ((⊤ : subgroup G) : set G) = set.univ := rfl @[simp, to_additive] lemma coe_bot : ((⊥ : subgroup G) : set G) = {1} := rfl @[to_additive] instance : unique (⊥ : subgroup G) := ⟨⟨1⟩, λ g, subtype.ext g.2⟩ @[to_additive] lemma eq_bot_iff_forall : H = ⊥ ↔ ∀ x ∈ H, x = (1 : G) := begin rw set_like.ext'_iff, simp only [coe_bot, set.eq_singleton_iff_unique_mem, set_like.mem_coe, H.one_mem, true_and], end @[to_additive] lemma eq_bot_of_subsingleton [subsingleton H] : H = ⊥ := begin rw subgroup.eq_bot_iff_forall, intros y hy, rw [← subgroup.coe_mk H y hy, subsingleton.elim (⟨y, hy⟩ : H) 1, subgroup.coe_one], end @[to_additive] lemma coe_eq_univ {H : subgroup G} : (H : set G) = set.univ ↔ H = ⊤ := (set_like.ext'_iff.trans (by refl)).symm @[to_additive] lemma coe_eq_singleton {H : subgroup G} : (∃ g : G, (H : set G) = {g}) ↔ H = ⊥ := ⟨λ ⟨g, hg⟩, by { haveI : subsingleton (H : set G) := by { rw hg, apply_instance }, exact H.eq_bot_of_subsingleton }, λ h, ⟨1, set_like.ext'_iff.mp h⟩⟩ @[to_additive] instance fintype_bot : fintype (⊥ : subgroup G) := ⟨{1}, by {rintro ⟨x, ⟨hx⟩⟩, exact finset.mem_singleton_self _}⟩ /- curly brackets `{}` are used here instead of instance brackets `[]` because the instance in a goal is often not the same as the one inferred by type class inference. -/ @[simp, to_additive] lemma card_bot {_ : fintype ↥(⊥ : subgroup G)} : fintype.card (⊥ : subgroup G) = 1 := fintype.card_eq_one_iff.2 ⟨⟨(1 : G), set.mem_singleton 1⟩, λ ⟨y, hy⟩, subtype.eq $ subgroup.mem_bot.1 hy⟩ @[to_additive] lemma eq_top_of_card_eq [fintype H] [fintype G] (h : fintype.card H = fintype.card G) : H = ⊤ := begin haveI : fintype (H : set G) := ‹fintype H›, rw [set_like.ext'_iff, coe_top, ← finset.coe_univ, ← (H : set G).coe_to_finset, finset.coe_inj, ← finset.card_eq_iff_eq_univ, ← h, set.to_finset_card], congr end @[to_additive] lemma eq_top_of_le_card [fintype H] [fintype G] (h : fintype.card G ≤ fintype.card H) : H = ⊤ := eq_top_of_card_eq H (le_antisymm (fintype.card_le_of_injective coe subtype.coe_injective) h) @[to_additive] lemma eq_bot_of_card_le [fintype H] (h : fintype.card H ≤ 1) : H = ⊥ := let _ := fintype.card_le_one_iff_subsingleton.mp h in by exactI eq_bot_of_subsingleton H @[to_additive] lemma eq_bot_of_card_eq [fintype H] (h : fintype.card H = 1) : H = ⊥ := H.eq_bot_of_card_le (le_of_eq h) @[to_additive] lemma nontrivial_iff_exists_ne_one (H : subgroup G) : nontrivial H ↔ ∃ x ∈ H, x ≠ (1:G) := subtype.nontrivial_iff_exists_ne (λ x, x ∈ H) (1 : H) /-- A subgroup is either the trivial subgroup or nontrivial. -/ @[to_additive "A subgroup is either the trivial subgroup or nontrivial."] lemma bot_or_nontrivial (H : subgroup G) : H = ⊥ ∨ nontrivial H := begin classical, by_cases h : ∀ x ∈ H, x = (1 : G), { left, exact H.eq_bot_iff_forall.mpr h }, { right, simp only [not_forall] at h, simpa only [nontrivial_iff_exists_ne_one] } end /-- A subgroup is either the trivial subgroup or contains a non-identity element. -/ @[to_additive "A subgroup is either the trivial subgroup or contains a nonzero element."] lemma bot_or_exists_ne_one (H : subgroup G) : H = ⊥ ∨ ∃ x ∈ H, x ≠ (1:G) := begin convert H.bot_or_nontrivial, rw nontrivial_iff_exists_ne_one end @[to_additive] lemma card_le_one_iff_eq_bot [fintype H] : fintype.card H ≤ 1 ↔ H = ⊥ := ⟨λ h, (eq_bot_iff_forall _).2 (λ x hx, by simpa [subtype.ext_iff] using fintype.card_le_one_iff.1 h ⟨x, hx⟩ 1), λ h, by simp [h]⟩ @[to_additive] lemma one_lt_card_iff_ne_bot [fintype H] : 1 < fintype.card H ↔ H ≠ ⊥ := lt_iff_not_le.trans H.card_le_one_iff_eq_bot.not /-- The inf of two subgroups is their intersection. -/ @[to_additive "The inf of two `add_subgroups`s is their intersection."] instance : has_inf (subgroup G) := ⟨λ H₁ H₂, { inv_mem' := λ _ ⟨hx, hx'⟩, ⟨H₁.inv_mem hx, H₂.inv_mem hx'⟩, .. H₁.to_submonoid ⊓ H₂.to_submonoid }⟩ @[simp, to_additive] lemma coe_inf (p p' : subgroup G) : ((p ⊓ p' : subgroup G) : set G) = p ∩ p' := rfl @[simp, to_additive] lemma mem_inf {p p' : subgroup G} {x : G} : x ∈ p ⊓ p' ↔ x ∈ p ∧ x ∈ p' := iff.rfl @[to_additive] instance : has_Inf (subgroup G) := ⟨λ s, { inv_mem' := λ x hx, set.mem_bInter $ λ i h, i.inv_mem (by apply set.mem_Inter₂.1 hx i h), .. (⨅ S ∈ s, subgroup.to_submonoid S).copy (⋂ S ∈ s, ↑S) (by simp) }⟩ @[simp, norm_cast, to_additive] lemma coe_Inf (H : set (subgroup G)) : ((Inf H : subgroup G) : set G) = ⋂ s ∈ H, ↑s := rfl @[simp, to_additive] lemma mem_Inf {S : set (subgroup G)} {x : G} : x ∈ Inf S ↔ ∀ p ∈ S, x ∈ p := set.mem_Inter₂ @[to_additive] lemma mem_infi {ι : Sort*} {S : ι → subgroup G} {x : G} : (x ∈ ⨅ i, S i) ↔ ∀ i, x ∈ S i := by simp only [infi, mem_Inf, set.forall_range_iff] @[simp, norm_cast, to_additive] lemma coe_infi {ι : Sort*} {S : ι → subgroup G} : (↑(⨅ i, S i) : set G) = ⋂ i, S i := by simp only [infi, coe_Inf, set.bInter_range] /-- Subgroups of a group form a complete lattice. -/ @[to_additive "The `add_subgroup`s of an `add_group` form a complete lattice."] instance : complete_lattice (subgroup G) := { bot := (⊥), bot_le := λ S x hx, (mem_bot.1 hx).symm ▸ S.one_mem, top := (⊤), le_top := λ S x hx, mem_top x, inf := (⊓), le_inf := λ a b c ha hb x hx, ⟨ha hx, hb hx⟩, inf_le_left := λ a b x, and.left, inf_le_right := λ a b x, and.right, .. complete_lattice_of_Inf (subgroup G) $ λ s, is_glb.of_image (λ H K, show (H : set G) ≤ K ↔ H ≤ K, from set_like.coe_subset_coe) is_glb_binfi } @[to_additive] lemma mem_sup_left {S T : subgroup G} : ∀ {x : G}, x ∈ S → x ∈ S ⊔ T := show S ≤ S ⊔ T, from le_sup_left @[to_additive] lemma mem_sup_right {S T : subgroup G} : ∀ {x : G}, x ∈ T → x ∈ S ⊔ T := show T ≤ S ⊔ T, from le_sup_right @[to_additive] lemma mul_mem_sup {S T : subgroup G} {x y : G} (hx : x ∈ S) (hy : y ∈ T) : x * y ∈ S ⊔ T := (S ⊔ T).mul_mem (mem_sup_left hx) (mem_sup_right hy) @[to_additive] lemma mem_supr_of_mem {ι : Sort*} {S : ι → subgroup G} (i : ι) : ∀ {x : G}, x ∈ S i → x ∈ supr S := show S i ≤ supr S, from le_supr _ _ @[to_additive] lemma mem_Sup_of_mem {S : set (subgroup G)} {s : subgroup G} (hs : s ∈ S) : ∀ {x : G}, x ∈ s → x ∈ Sup S := show s ≤ Sup S, from le_Sup hs @[simp, to_additive] lemma subsingleton_iff : subsingleton (subgroup G) ↔ subsingleton G := ⟨ λ h, by exactI ⟨λ x y, have ∀ i : G, i = 1 := λ i, mem_bot.mp $ subsingleton.elim (⊤ : subgroup G) ⊥ ▸ mem_top i, (this x).trans (this y).symm⟩, λ h, by exactI ⟨λ x y, subgroup.ext $ λ i, subsingleton.elim 1 i ▸ by simp [subgroup.one_mem]⟩⟩ @[simp, to_additive] lemma nontrivial_iff : nontrivial (subgroup G) ↔ nontrivial G := not_iff_not.mp ( (not_nontrivial_iff_subsingleton.trans subsingleton_iff).trans not_nontrivial_iff_subsingleton.symm) @[to_additive] instance [subsingleton G] : unique (subgroup G) := ⟨⟨⊥⟩, λ a, @subsingleton.elim _ (subsingleton_iff.mpr ‹_›) a _⟩ @[to_additive] instance [nontrivial G] : nontrivial (subgroup G) := nontrivial_iff.mpr ‹_› @[to_additive] lemma eq_top_iff' : H = ⊤ ↔ ∀ x : G, x ∈ H := eq_top_iff.trans ⟨λ h m, h $ mem_top m, λ h m _, h m⟩ /-- The `subgroup` generated by a set. -/ @[to_additive "The `add_subgroup` generated by a set"] def closure (k : set G) : subgroup G := Inf {K | k ⊆ K} variable {k : set G} @[to_additive] lemma mem_closure {x : G} : x ∈ closure k ↔ ∀ K : subgroup G, k ⊆ K → x ∈ K := mem_Inf /-- The subgroup generated by a set includes the set. -/ @[simp, to_additive "The `add_subgroup` generated by a set includes the set."] lemma subset_closure : k ⊆ closure k := λ x hx, mem_closure.2 $ λ K hK, hK hx @[to_additive] lemma not_mem_of_not_mem_closure {P : G} (hP : P ∉ closure k) : P ∉ k := λ h, hP (subset_closure h) open set /-- A subgroup `K` includes `closure k` if and only if it includes `k`. -/ @[simp, to_additive "An additive subgroup `K` includes `closure k` if and only if it includes `k`"] lemma closure_le : closure k ≤ K ↔ k ⊆ K := ⟨subset.trans subset_closure, λ h, Inf_le h⟩ @[to_additive] lemma closure_eq_of_le (h₁ : k ⊆ K) (h₂ : K ≤ closure k) : closure k = K := le_antisymm ((closure_le $ K).2 h₁) h₂ /-- An induction principle for closure membership. If `p` holds for `1` and all elements of `k`, and is preserved under multiplication and inverse, then `p` holds for all elements of the closure of `k`. -/ @[elab_as_eliminator, to_additive "An induction principle for additive closure membership. If `p` holds for `0` and all elements of `k`, and is preserved under addition and inverses, then `p` holds for all elements of the additive closure of `k`."] lemma closure_induction {p : G → Prop} {x} (h : x ∈ closure k) (Hk : ∀ x ∈ k, p x) (H1 : p 1) (Hmul : ∀ x y, p x → p y → p (x * y)) (Hinv : ∀ x, p x → p x⁻¹) : p x := (@closure_le _ _ ⟨p, Hmul, H1, Hinv⟩ _).2 Hk h /-- A dependent version of `subgroup.closure_induction`. -/ @[elab_as_eliminator, to_additive "A dependent version of `add_subgroup.closure_induction`. "] lemma closure_induction' {p : Π x, x ∈ closure k → Prop} (Hs : ∀ x (h : x ∈ k), p x (subset_closure h)) (H1 : p 1 (one_mem _)) (Hmul : ∀ x hx y hy, p x hx → p y hy → p (x * y) (mul_mem hx hy)) (Hinv : ∀ x hx, p x hx → p x⁻¹ (inv_mem hx)) {x} (hx : x ∈ closure k) : p x hx := begin refine exists.elim _ (λ (hx : x ∈ closure k) (hc : p x hx), hc), exact closure_induction hx (λ x hx, ⟨_, Hs x hx⟩) ⟨_, H1⟩ (λ x y ⟨hx', hx⟩ ⟨hy', hy⟩, ⟨_, Hmul _ _ _ _ hx hy⟩) (λ x ⟨hx', hx⟩, ⟨_, Hinv _ _ hx⟩), end /-- An induction principle for closure membership for predicates with two arguments. -/ @[elab_as_eliminator, to_additive "An induction principle for additive closure membership, for predicates with two arguments."] lemma closure_induction₂ {p : G → G → Prop} {x} {y : G} (hx : x ∈ closure k) (hy : y ∈ closure k) (Hk : ∀ (x ∈ k) (y ∈ k), p x y) (H1_left : ∀ x, p 1 x) (H1_right : ∀ x, p x 1) (Hmul_left : ∀ x₁ x₂ y, p x₁ y → p x₂ y → p (x₁ * x₂) y) (Hmul_right : ∀ x y₁ y₂, p x y₁ → p x y₂ → p x (y₁ * y₂)) (Hinv_left : ∀ x y, p x y → p x⁻¹ y) (Hinv_right : ∀ x y, p x y → p x y⁻¹) : p x y := closure_induction hx (λ x xk, closure_induction hy (Hk x xk) (H1_right x) (Hmul_right x) (Hinv_right x)) (H1_left y) (λ z z', Hmul_left z z' y) (λ z, Hinv_left z y) @[simp, to_additive] lemma closure_closure_coe_preimage {k : set G} : closure ((coe : closure k → G) ⁻¹' k) = ⊤ := eq_top_iff.2 $ λ x, subtype.rec_on x $ λ x hx _, begin refine closure_induction' (λ g hg, _) _ (λ g₁ g₂ hg₁ hg₂, _) (λ g hg, _) hx, { exact subset_closure hg }, { exact one_mem _ }, { exact mul_mem }, { exact inv_mem } end /-- If all the elements of a set `s` commute, then `closure s` is a commutative group. -/ @[to_additive "If all the elements of a set `s` commute, then `closure s` is an additive commutative group."] def closure_comm_group_of_comm {k : set G} (hcomm : ∀ (x ∈ k) (y ∈ k), x * y = y * x) : comm_group (closure k) := { mul_comm := λ x y, begin ext, simp only [subgroup.coe_mul], refine closure_induction₂ x.prop y.prop hcomm (λ x, by simp only [mul_one, one_mul]) (λ x, by simp only [mul_one, one_mul]) (λ x y z h₁ h₂, by rw [mul_assoc, h₂, ←mul_assoc, h₁, mul_assoc]) (λ x y z h₁ h₂, by rw [←mul_assoc, h₁, mul_assoc, h₂, ←mul_assoc]) (λ x y h, by rw [inv_mul_eq_iff_eq_mul, ←mul_assoc, h, mul_assoc, mul_inv_self, mul_one]) (λ x y h, by rw [mul_inv_eq_iff_eq_mul, mul_assoc, h, ←mul_assoc, inv_mul_self, one_mul]) end, ..(closure k).to_group } variable (G) /-- `closure` forms a Galois insertion with the coercion to set. -/ @[to_additive "`closure` forms a Galois insertion with the coercion to set."] protected def gi : galois_insertion (@closure G _) coe := { choice := λ s _, closure s, gc := λ s t, @closure_le _ _ t s, le_l_u := λ s, subset_closure, choice_eq := λ s h, rfl } variable {G} /-- Subgroup closure of a set is monotone in its argument: if `h ⊆ k`, then `closure h ≤ closure k`. -/ @[to_additive "Additive subgroup closure of a set is monotone in its argument: if `h ⊆ k`, then `closure h ≤ closure k`"] lemma closure_mono ⦃h k : set G⦄ (h' : h ⊆ k) : closure h ≤ closure k := (subgroup.gi G).gc.monotone_l h' /-- Closure of a subgroup `K` equals `K`. -/ @[simp, to_additive "Additive closure of an additive subgroup `K` equals `K`"] lemma closure_eq : closure (K : set G) = K := (subgroup.gi G).l_u_eq K @[simp, to_additive] lemma closure_empty : closure (∅ : set G) = ⊥ := (subgroup.gi G).gc.l_bot @[simp, to_additive] lemma closure_univ : closure (univ : set G) = ⊤ := @coe_top G _ ▸ closure_eq ⊤ @[to_additive] lemma closure_union (s t : set G) : closure (s ∪ t) = closure s ⊔ closure t := (subgroup.gi G).gc.l_sup @[to_additive] lemma closure_Union {ι} (s : ι → set G) : closure (⋃ i, s i) = ⨆ i, closure (s i) := (subgroup.gi G).gc.l_supr @[to_additive] lemma closure_eq_bot_iff (G : Type*) [group G] (S : set G) : closure S = ⊥ ↔ S ⊆ {1} := by { rw [← le_bot_iff], exact closure_le _} @[to_additive] lemma supr_eq_closure {ι : Sort*} (p : ι → subgroup G) : (⨆ i, p i) = closure (⋃ i, (p i : set G)) := by simp_rw [closure_Union, closure_eq] /-- The subgroup generated by an element of a group equals the set of integer number powers of the element. -/ @[to_additive /-"The `add_subgroup` generated by an element of an `add_group` equals the set of natural number multiples of the element."-/] lemma mem_closure_singleton {x y : G} : y ∈ closure ({x} : set G) ↔ ∃ n : ℤ, x ^ n = y := begin refine ⟨λ hy, closure_induction hy _ _ _ _, λ ⟨n, hn⟩, hn ▸ zpow_mem (subset_closure $ mem_singleton x) n⟩, { intros y hy, rw [eq_of_mem_singleton hy], exact ⟨1, zpow_one x⟩ }, { exact ⟨0, zpow_zero x⟩ }, { rintros _ _ ⟨n, rfl⟩ ⟨m, rfl⟩, exact ⟨n + m, zpow_add x n m⟩ }, rintros _ ⟨n, rfl⟩, exact ⟨-n, zpow_neg x n⟩ end @[to_additive] lemma closure_singleton_one : closure ({1} : set G) = ⊥ := by simp [eq_bot_iff_forall, mem_closure_singleton] @[simp, to_additive] lemma inv_subset_closure (S : set G) : S⁻¹ ⊆ closure S := begin intros s hs, rw [set_like.mem_coe, ←subgroup.inv_mem_iff], exact subset_closure (mem_inv.mp hs), end @[simp, to_additive] lemma closure_inv (S : set G) : closure S⁻¹ = closure S := begin refine le_antisymm ((subgroup.closure_le _).2 _) ((subgroup.closure_le _).2 _), { exact inv_subset_closure S }, { simpa only [inv_inv] using inv_subset_closure S⁻¹ }, end @[to_additive] lemma closure_to_submonoid (S : set G) : (closure S).to_submonoid = submonoid.closure (S ∪ S⁻¹) := begin refine le_antisymm _ (submonoid.closure_le.2 _), { intros x hx, refine closure_induction hx (λ x hx, submonoid.closure_mono (subset_union_left S S⁻¹) (submonoid.subset_closure hx)) (submonoid.one_mem _) (λ x y hx hy, submonoid.mul_mem _ hx hy) (λ x hx, _), rwa [←submonoid.mem_closure_inv, set.union_inv, inv_inv, set.union_comm] }, { simp only [true_and, coe_to_submonoid, union_subset_iff, subset_closure, inv_subset_closure] } end @[to_additive] lemma closure_induction_left {p : G → Prop} {x : G} (h : x ∈ closure k) (H1 : p 1) (Hmul : ∀ (x ∈ k) y, p y → p (x * y)) (Hinv : ∀ (x ∈ k) y, p y → p (x⁻¹ * y)) : p x := let key := le_of_eq (closure_to_submonoid k) in submonoid.closure_induction_left (key h) H1 (λ x hx, hx.elim (Hmul x) (λ hx y hy, (congr_arg _ (inv_inv x)).mp (Hinv x⁻¹ hx y hy))) @[to_additive] lemma closure_induction_right {p : G → Prop} {x : G} (h : x ∈ closure k) (H1 : p 1) (Hmul : ∀ x (y ∈ k), p x → p (x * y)) (Hinv : ∀ x (y ∈ k), p x → p (x * y⁻¹)) : p x := let key := le_of_eq (closure_to_submonoid k) in submonoid.closure_induction_right (key h) H1 (λ x y hy, hy.elim (Hmul x y) (λ hy hx, (congr_arg _ (inv_inv y)).mp (Hinv x y⁻¹ hy hx))) /-- An induction principle for closure membership. If `p` holds for `1` and all elements of `k` and their inverse, and is preserved under multiplication, then `p` holds for all elements of the closure of `k`. -/ @[to_additive "An induction principle for additive closure membership. If `p` holds for `0` and all elements of `k` and their negation, and is preserved under addition, then `p` holds for all elements of the additive closure of `k`."] lemma closure_induction'' {p : G → Prop} {x} (h : x ∈ closure k) (Hk : ∀ x ∈ k, p x) (Hk_inv : ∀ x ∈ k, p x⁻¹) (H1 : p 1) (Hmul : ∀ x y, p x → p y → p (x * y)) : p x := closure_induction_left h H1 (λ x hx y hy, Hmul x y (Hk x hx) hy) (λ x hx y hy, Hmul x⁻¹ y (Hk_inv x hx) hy) /-- An induction principle for elements of `⨆ i, S i`. If `C` holds for `1` and all elements of `S i` for all `i`, and is preserved under multiplication, then it holds for all elements of the supremum of `S`. -/ @[elab_as_eliminator, to_additive /-" An induction principle for elements of `⨆ i, S i`. If `C` holds for `0` and all elements of `S i` for all `i`, and is preserved under addition, then it holds for all elements of the supremum of `S`. "-/] lemma supr_induction {ι : Sort*} (S : ι → subgroup G) {C : G → Prop} {x : G} (hx : x ∈ ⨆ i, S i) (hp : ∀ i (x ∈ S i), C x) (h1 : C 1) (hmul : ∀ x y, C x → C y → C (x * y)) : C x := begin rw supr_eq_closure at hx, refine closure_induction'' hx (λ x hx, _) (λ x hx, _) h1 hmul, { obtain ⟨i, hi⟩ := set.mem_Union.mp hx, exact hp _ _ hi, }, { obtain ⟨i, hi⟩ := set.mem_Union.mp hx, exact hp _ _ (inv_mem hi), }, end /-- A dependent version of `subgroup.supr_induction`. -/ @[elab_as_eliminator, to_additive /-"A dependent version of `add_subgroup.supr_induction`. "-/] lemma supr_induction' {ι : Sort*} (S : ι → subgroup G) {C : Π x, (x ∈ ⨆ i, S i) → Prop} (hp : ∀ i (x ∈ S i), C x (mem_supr_of_mem i ‹_›)) (h1 : C 1 (one_mem _)) (hmul : ∀ x y hx hy, C x hx → C y hy → C (x * y) (mul_mem ‹_› ‹_›)) {x : G} (hx : x ∈ ⨆ i, S i) : C x hx := begin refine exists.elim _ (λ (hx : x ∈ ⨆ i, S i) (hc : C x hx), hc), refine supr_induction S hx (λ i x hx, _) _ (λ x y, _), { exact ⟨_, hp _ _ hx⟩ }, { exact ⟨_, h1⟩ }, { rintro ⟨_, Cx⟩ ⟨_, Cy⟩, refine ⟨_, hmul _ _ _ _ Cx Cy⟩ }, end @[to_additive] lemma mem_supr_of_directed {ι} [hι : nonempty ι] {K : ι → subgroup G} (hK : directed (≤) K) {x : G} : x ∈ (supr K : subgroup G) ↔ ∃ i, x ∈ K i := begin refine ⟨_, λ ⟨i, hi⟩, (set_like.le_def.1 $ le_supr K i) hi⟩, suffices : x ∈ closure (⋃ i, (K i : set G)) → ∃ i, x ∈ K i, by simpa only [closure_Union, closure_eq (K _)] using this, refine (λ hx, closure_induction hx (λ _, mem_Union.1) _ _ _), { exact hι.elim (λ i, ⟨i, (K i).one_mem⟩) }, { rintros x y ⟨i, hi⟩ ⟨j, hj⟩, rcases hK i j with ⟨k, hki, hkj⟩, exact ⟨k, mul_mem (hki hi) (hkj hj)⟩ }, rintros _ ⟨i, hi⟩, exact ⟨i, inv_mem hi⟩ end @[to_additive] lemma coe_supr_of_directed {ι} [nonempty ι] {S : ι → subgroup G} (hS : directed (≤) S) : ((⨆ i, S i : subgroup G) : set G) = ⋃ i, ↑(S i) := set.ext $ λ x, by simp [mem_supr_of_directed hS] @[to_additive] lemma mem_Sup_of_directed_on {K : set (subgroup G)} (Kne : K.nonempty) (hK : directed_on (≤) K) {x : G} : x ∈ Sup K ↔ ∃ s ∈ K, x ∈ s := begin haveI : nonempty K := Kne.to_subtype, simp only [Sup_eq_supr', mem_supr_of_directed hK.directed_coe, set_coe.exists, subtype.coe_mk] end variables {N : Type*} [group N] {P : Type*} [group P] /-- The preimage of a subgroup along a monoid homomorphism is a subgroup. -/ @[to_additive "The preimage of an `add_subgroup` along an `add_monoid` homomorphism is an `add_subgroup`."] def comap {N : Type*} [group N] (f : G →* N) (H : subgroup N) : subgroup G := { carrier := (f ⁻¹' H), inv_mem' := λ a ha, show f a⁻¹ ∈ H, by rw f.map_inv; exact H.inv_mem ha, .. H.to_submonoid.comap f } @[simp, to_additive] lemma coe_comap (K : subgroup N) (f : G →* N) : (K.comap f : set G) = f ⁻¹' K := rfl @[simp, to_additive] lemma mem_comap {K : subgroup N} {f : G →* N} {x : G} : x ∈ K.comap f ↔ f x ∈ K := iff.rfl @[to_additive] lemma comap_mono {f : G →* N} {K K' : subgroup N} : K ≤ K' → comap f K ≤ comap f K' := preimage_mono @[to_additive] lemma comap_comap (K : subgroup P) (g : N →* P) (f : G →* N) : (K.comap g).comap f = K.comap (g.comp f) := rfl /-- The image of a subgroup along a monoid homomorphism is a subgroup. -/ @[to_additive "The image of an `add_subgroup` along an `add_monoid` homomorphism is an `add_subgroup`."] def map (f : G →* N) (H : subgroup G) : subgroup N := { carrier := (f '' H), inv_mem' := by { rintros _ ⟨x, hx, rfl⟩, exact ⟨x⁻¹, H.inv_mem hx, f.map_inv x⟩ }, .. H.to_submonoid.map f } @[simp, to_additive] lemma coe_map (f : G →* N) (K : subgroup G) : (K.map f : set N) = f '' K := rfl @[simp, to_additive] lemma mem_map {f : G →* N} {K : subgroup G} {y : N} : y ∈ K.map f ↔ ∃ x ∈ K, f x = y := mem_image_iff_bex @[to_additive] lemma mem_map_of_mem (f : G →* N) {K : subgroup G} {x : G} (hx : x ∈ K) : f x ∈ K.map f := mem_image_of_mem f hx @[to_additive] lemma apply_coe_mem_map (f : G →* N) (K : subgroup G) (x : K) : f x ∈ K.map f := mem_map_of_mem f x.prop @[to_additive] lemma map_mono {f : G →* N} {K K' : subgroup G} : K ≤ K' → map f K ≤ map f K' := image_subset _ @[simp, to_additive] lemma map_id : K.map (monoid_hom.id G) = K := set_like.coe_injective $ image_id _ @[to_additive] lemma map_map (g : N →* P) (f : G →* N) : (K.map f).map g = K.map (g.comp f) := set_like.coe_injective $ image_image _ _ _ @[simp, to_additive] lemma map_one_eq_bot : K.map (1 : G →* N) = ⊥ := eq_bot_iff.mpr $ by { rintros x ⟨y, _ , rfl⟩, simp } @[to_additive] lemma mem_map_equiv {f : G ≃* N} {K : subgroup G} {x : N} : x ∈ K.map f.to_monoid_hom ↔ f.symm x ∈ K := @set.mem_image_equiv _ _ ↑K f.to_equiv x @[to_additive] lemma mem_map_iff_mem {f : G →* N} (hf : function.injective f) {K : subgroup G} {x : G} : f x ∈ K.map f ↔ x ∈ K := hf.mem_set_image @[to_additive] lemma map_equiv_eq_comap_symm (f : G ≃* N) (K : subgroup G) : K.map f.to_monoid_hom = K.comap f.symm.to_monoid_hom := set_like.coe_injective (f.to_equiv.image_eq_preimage K) @[to_additive] lemma comap_equiv_eq_map_symm (f : N ≃* G) (K : subgroup G) : K.comap f.to_monoid_hom = K.map f.symm.to_monoid_hom := (map_equiv_eq_comap_symm f.symm K).symm @[to_additive] lemma map_le_iff_le_comap {f : G →* N} {K : subgroup G} {H : subgroup N} : K.map f ≤ H ↔ K ≤ H.comap f := image_subset_iff @[to_additive] lemma gc_map_comap (f : G →* N) : galois_connection (map f) (comap f) := λ _ _, map_le_iff_le_comap @[to_additive] lemma map_sup (H K : subgroup G) (f : G →* N) : (H ⊔ K).map f = H.map f ⊔ K.map f := (gc_map_comap f).l_sup @[to_additive] lemma map_supr {ι : Sort*} (f : G →* N) (s : ι → subgroup G) : (supr s).map f = ⨆ i, (s i).map f := (gc_map_comap f).l_supr @[to_additive] lemma comap_sup_comap_le (H K : subgroup N) (f : G →* N) : comap f H ⊔ comap f K ≤ comap f (H ⊔ K) := monotone.le_map_sup (λ _ _, comap_mono) H K @[to_additive] lemma supr_comap_le {ι : Sort*} (f : G →* N) (s : ι → subgroup N) : (⨆ i, (s i).comap f) ≤ (supr s).comap f := monotone.le_map_supr (λ _ _, comap_mono) @[to_additive] lemma comap_inf (H K : subgroup N) (f : G →* N) : (H ⊓ K).comap f = H.comap f ⊓ K.comap f := (gc_map_comap f).u_inf @[to_additive] lemma comap_infi {ι : Sort*} (f : G →* N) (s : ι → subgroup N) : (infi s).comap f = ⨅ i, (s i).comap f := (gc_map_comap f).u_infi @[to_additive] lemma map_inf_le (H K : subgroup G) (f : G →* N) : map f (H ⊓ K) ≤ map f H ⊓ map f K := le_inf (map_mono inf_le_left) (map_mono inf_le_right) @[to_additive] lemma map_inf_eq (H K : subgroup G) (f : G →* N) (hf : function.injective f) : map f (H ⊓ K) = map f H ⊓ map f K := begin rw ← set_like.coe_set_eq, simp [set.image_inter hf], end @[simp, to_additive] lemma map_bot (f : G →* N) : (⊥ : subgroup G).map f = ⊥ := (gc_map_comap f).l_bot @[simp, to_additive] lemma map_top_of_surjective (f : G →* N) (h : function.surjective f) : subgroup.map f ⊤ = ⊤ := by {rw eq_top_iff, intros x hx, obtain ⟨y, hy⟩ := (h x), exact ⟨y, trivial, hy⟩ } @[simp, to_additive] lemma comap_top (f : G →* N) : (⊤ : subgroup N).comap f = ⊤ := (gc_map_comap f).u_top @[simp, to_additive] lemma comap_subtype_self_eq_top {G : Type*} [group G] {H : subgroup G} : comap H.subtype H = ⊤ := by { ext, simp } @[simp, to_additive] lemma comap_subtype_inf_left {H K : subgroup G} : comap H.subtype (H ⊓ K) = comap H.subtype K := ext $ λ x, and_iff_right_of_imp (λ _, x.prop) @[simp, to_additive] lemma comap_subtype_inf_right {H K : subgroup G} : comap K.subtype (H ⊓ K) = comap K.subtype H := ext $ λ x, and_iff_left_of_imp (λ _, x.prop) /-- If `H ≤ K`, then `H` as a subgroup of `K` is isomorphic to `H`. -/ @[to_additive "If `H ≤ K`, then `H` as a subgroup of `K` is isomorphic to `H`.", simps] def comap_subtype_equiv_of_le {G : Type*} [group G] {H K : subgroup G} (h : H ≤ K) : H.comap K.subtype ≃* H := { to_fun := λ g, ⟨g.1, g.2⟩, inv_fun := λ g, ⟨⟨g.1, h g.2⟩, g.2⟩, left_inv := λ g, subtype.ext (subtype.ext rfl), right_inv := λ g, subtype.ext rfl, map_mul' := λ g h, rfl } /-- For any subgroups `H` and `K`, view `H ⊓ K` as a subgroup of `K`. -/ @[to_additive "For any subgroups `H` and `K`, view `H ⊓ K` as a subgroup of `K`."] def subgroup_of (H K : subgroup G) : subgroup K := H.comap K.subtype @[to_additive] lemma coe_subgroup_of (H K : subgroup G) : (H.subgroup_of K : set K) = K.subtype ⁻¹' H := rfl @[to_additive] lemma mem_subgroup_of {H K : subgroup G} {h : K} : h ∈ H.subgroup_of K ↔ (h : G) ∈ H := iff.rfl @[to_additive] lemma subgroup_of_map_subtype (H K : subgroup G) : (H.subgroup_of K).map K.subtype = H ⊓ K := set_like.ext' begin convert set.image_preimage_eq_inter_range, simp only [subtype.range_coe_subtype, coe_subtype, coe_inf], refl, end @[simp, to_additive] lemma bot_subgroup_of : (⊥ : subgroup G).subgroup_of H = ⊥ := eq.symm (subgroup.ext (λ g, subtype.ext_iff)) @[simp, to_additive] lemma top_subgroup_of : (⊤ : subgroup G).subgroup_of H = ⊤ := rfl @[to_additive] lemma subgroup_of_bot_eq_bot : H.subgroup_of ⊥ = ⊥ := subsingleton.elim _ _ @[to_additive] lemma subgroup_of_bot_eq_top : H.subgroup_of ⊥ = ⊤ := subsingleton.elim _ _ @[simp, to_additive] lemma subgroup_of_self : H.subgroup_of H = ⊤ := top_le_iff.mp (λ g hg, g.2) /-- Given `subgroup`s `H`, `K` of groups `G`, `N` respectively, `H × K` as a subgroup of `G × N`. -/ @[to_additive prod "Given `add_subgroup`s `H`, `K` of `add_group`s `A`, `B` respectively, `H × K` as an `add_subgroup` of `A × B`."] def prod (H : subgroup G) (K : subgroup N) : subgroup (G × N) := { inv_mem' := λ _ hx, ⟨H.inv_mem' hx.1, K.inv_mem' hx.2⟩, .. submonoid.prod H.to_submonoid K.to_submonoid} @[to_additive coe_prod] lemma coe_prod (H : subgroup G) (K : subgroup N) : (H.prod K : set (G × N)) = H ×ˢ K := rfl @[to_additive mem_prod] lemma mem_prod {H : subgroup G} {K : subgroup N} {p : G × N} : p ∈ H.prod K ↔ p.1 ∈ H ∧ p.2 ∈ K := iff.rfl @[to_additive prod_mono] lemma prod_mono : ((≤) ⇒ (≤) ⇒ (≤)) (@prod G _ N _) (@prod G _ N _) := λ s s' hs t t' ht, set.prod_mono hs ht @[to_additive prod_mono_right] lemma prod_mono_right (K : subgroup G) : monotone (λ t : subgroup N, K.prod t) := prod_mono (le_refl K) @[to_additive prod_mono_left] lemma prod_mono_left (H : subgroup N) : monotone (λ K : subgroup G, K.prod H) := λ s₁ s₂ hs, prod_mono hs (le_refl H) @[to_additive prod_top] lemma prod_top (K : subgroup G) : K.prod (⊤ : subgroup N) = K.comap (monoid_hom.fst G N) := ext $ λ x, by simp [mem_prod, monoid_hom.coe_fst] @[to_additive top_prod] lemma top_prod (H : subgroup N) : (⊤ : subgroup G).prod H = H.comap (monoid_hom.snd G N) := ext $ λ x, by simp [mem_prod, monoid_hom.coe_snd] @[simp, to_additive top_prod_top] lemma top_prod_top : (⊤ : subgroup G).prod (⊤ : subgroup N) = ⊤ := (top_prod _).trans $ comap_top _ @[to_additive] lemma bot_prod_bot : (⊥ : subgroup G).prod (⊥ : subgroup N) = ⊥ := set_like.coe_injective $ by simp [coe_prod, prod.one_eq_mk] @[to_additive le_prod_iff] lemma le_prod_iff {H : subgroup G} {K : subgroup N} {J : subgroup (G × N)} : J ≤ H.prod K ↔ map (monoid_hom.fst G N) J ≤ H ∧ map (monoid_hom.snd G N) J ≤ K := by simpa only [← subgroup.to_submonoid_le] using submonoid.le_prod_iff @[to_additive prod_le_iff] lemma prod_le_iff {H : subgroup G} {K : subgroup N} {J : subgroup (G × N)} : H.prod K ≤ J ↔ map (monoid_hom.inl G N) H ≤ J ∧ map (monoid_hom.inr G N) K ≤ J := by simpa only [← subgroup.to_submonoid_le] using submonoid.prod_le_iff @[simp, to_additive prod_eq_bot_iff] lemma prod_eq_bot_iff {H : subgroup G} {K : subgroup N} : H.prod K = ⊥ ↔ H = ⊥ ∧ K = ⊥ := by simpa only [← subgroup.to_submonoid_eq] using submonoid.prod_eq_bot_iff /-- Product of subgroups is isomorphic to their product as groups. -/ @[to_additive prod_equiv "Product of additive subgroups is isomorphic to their product as additive groups"] def prod_equiv (H : subgroup G) (K : subgroup N) : H.prod K ≃* H × K := { map_mul' := λ x y, rfl, .. equiv.set.prod ↑H ↑K } section pi variables {η : Type*} {f : η → Type*} -- defined here and not in group_theory.submonoid.operations to have access to algebra.group.pi /-- A version of `set.pi` for submonoids. Given an index set `I` and a family of submodules `s : Π i, submonoid f i`, `pi I s` is the submonoid of dependent functions `f : Π i, f i` such that `f i` belongs to `pi I s` whenever `i ∈ I`. -/ @[to_additive " A version of `set.pi` for `add_submonoid`s. Given an index set `I` and a family of submodules `s : Π i, add_submonoid f i`, `pi I s` is the `add_submonoid` of dependent functions `f : Π i, f i` such that `f i` belongs to `pi I s` whenever `i ∈ I`. -/ "] def _root_.submonoid.pi [∀ i, mul_one_class (f i)] (I : set η) (s : Π i, submonoid (f i)) : submonoid (Π i, f i) := { carrier := I.pi (λ i, (s i).carrier), one_mem' := λ i _ , (s i).one_mem, mul_mem' := λ p q hp hq i hI, (s i).mul_mem (hp i hI) (hq i hI) } variables [∀ i, group (f i)] /-- A version of `set.pi` for subgroups. Given an index set `I` and a family of submodules `s : Π i, subgroup f i`, `pi I s` is the subgroup of dependent functions `f : Π i, f i` such that `f i` belongs to `pi I s` whenever `i ∈ I`. -/ @[to_additive " A version of `set.pi` for `add_subgroup`s. Given an index set `I` and a family of submodules `s : Π i, add_subgroup f i`, `pi I s` is the `add_subgroup` of dependent functions `f : Π i, f i` such that `f i` belongs to `pi I s` whenever `i ∈ I`. -/ "] def pi (I : set η) (H : Π i, subgroup (f i)) : subgroup (Π i, f i) := { submonoid.pi I (λ i, (H i).to_submonoid) with inv_mem' := λ p hp i hI, (H i).inv_mem (hp i hI) } @[to_additive] lemma coe_pi (I : set η) (H : Π i, subgroup (f i)) : (pi I H : set (Π i, f i)) = set.pi I (λ i, (H i : set (f i))) := rfl @[to_additive] lemma mem_pi (I : set η) {H : Π i, subgroup (f i)} {p : Π i, f i} : p ∈ pi I H ↔ (∀ i : η, i ∈ I → p i ∈ H i) := iff.rfl @[to_additive] lemma pi_top (I : set η) : pi I (λ i, (⊤ : subgroup (f i))) = ⊤ := ext $ λ x, by simp [mem_pi] @[to_additive] lemma pi_empty (H : Π i, subgroup (f i)): pi ∅ H = ⊤ := ext $ λ x, by simp [mem_pi] @[to_additive] lemma pi_bot : pi set.univ (λ i, (⊥ : subgroup (f i))) = ⊥ := (eq_bot_iff_forall _).mpr $ λ p hp, by { simp only [mem_pi, mem_bot] at *, ext j, exact hp j trivial, } @[to_additive] lemma le_pi_iff {I : set η} {H : Π i, subgroup (f i)} {J : subgroup (Π i, f i)} : J ≤ pi I H ↔ (∀ i : η , i ∈ I → map (pi.eval_monoid_hom f i) J ≤ H i) := begin split, { intros h i hi, rintros _ ⟨x, hx, rfl⟩, exact (h hx) _ hi, }, { intros h x hx i hi, refine h i hi ⟨_, hx, rfl⟩, } end @[simp, to_additive] lemma mul_single_mem_pi [decidable_eq η] {I : set η} {H : Π i, subgroup (f i)} (i : η) (x : f i) : pi.mul_single i x ∈ pi I H ↔ (i ∈ I → x ∈ H i) := begin split, { intros h hi, simpa using h i hi, }, { intros h j hj, by_cases heq : j = i, { subst heq, simpa using h hj, }, { simp [heq, one_mem], }, } end @[to_additive] lemma pi_mem_of_mul_single_mem_aux [decidable_eq η] (I : finset η) {H : subgroup (Π i, f i) } (x : Π i, f i) (h1 : ∀ i, i ∉ I → x i = 1) (h2 : ∀ i, i ∈ I → pi.mul_single i (x i) ∈ H ) : x ∈ H := begin induction I using finset.induction_on with i I hnmem ih generalizing x, { convert one_mem H, ext i, exact (h1 i (not_mem_empty i)) }, { have : x = function.update x i 1 * pi.mul_single i (x i), { ext j, by_cases heq : j = i, { subst heq, simp, }, { simp [heq], }, }, rw this, clear this, apply mul_mem, { apply ih; clear ih, { intros j hj, by_cases heq : j = i, { subst heq, simp, }, { simp [heq], apply h1 j, simpa [heq] using hj, } }, { intros j hj, have : j ≠ i, by { rintro rfl, contradiction }, simp [this], exact h2 _ (finset.mem_insert_of_mem hj), }, }, { apply h2, simp, } } end @[to_additive] lemma pi_mem_of_mul_single_mem [finite η] [decidable_eq η] {H : subgroup (Π i, f i)} (x : Π i, f i) (h : ∀ i, pi.mul_single i (x i) ∈ H) : x ∈ H := by { casesI nonempty_fintype η, exact pi_mem_of_mul_single_mem_aux finset.univ x (by simp) (λ i _, h i) } /-- For finite index types, the `subgroup.pi` is generated by the embeddings of the groups. -/ @[to_additive "For finite index types, the `subgroup.pi` is generated by the embeddings of the additive groups."] lemma pi_le_iff [decidable_eq η] [finite η] {H : Π i, subgroup (f i)} {J : subgroup (Π i, f i)} : pi univ H ≤ J ↔ ∀ i : η, map (monoid_hom.single f i) (H i) ≤ J := begin split, { rintros h i _ ⟨x, hx, rfl⟩, apply h, simpa using hx }, { exact λ h x hx, pi_mem_of_mul_single_mem x (λ i, h i (mem_map_of_mem _ (hx i trivial))), } end @[to_additive] lemma pi_eq_bot_iff (H : Π i, subgroup (f i)) : pi set.univ H = ⊥ ↔ ∀ i, H i = ⊥ := begin classical, simp only [eq_bot_iff_forall], split, { intros h i x hx, have : monoid_hom.single f i x = 1 := h (monoid_hom.single f i x) ((mul_single_mem_pi i x).mpr (λ _, hx)), simpa using congr_fun this i, }, { exact λ h x hx, funext (λ i, h _ _ (hx i trivial)), }, end end pi /-- A subgroup is normal if whenever `n ∈ H`, then `g * n * g⁻¹ ∈ H` for every `g : G` -/ structure normal : Prop := (conj_mem : ∀ n, n ∈ H → ∀ g : G, g * n * g⁻¹ ∈ H) attribute [class] normal end subgroup namespace add_subgroup /-- An add_subgroup is normal if whenever `n ∈ H`, then `g + n - g ∈ H` for every `g : G` -/ structure normal (H : add_subgroup A) : Prop := (conj_mem [] : ∀ n, n ∈ H → ∀ g : A, g + n + -g ∈ H) attribute [to_additive add_subgroup.normal] subgroup.normal attribute [class] normal end add_subgroup namespace subgroup variables {H K : subgroup G} @[priority 100, to_additive] instance normal_of_comm {G : Type*} [comm_group G] (H : subgroup G) : H.normal := ⟨by simp [mul_comm, mul_left_comm]⟩ namespace normal variable (nH : H.normal) @[to_additive] lemma mem_comm {a b : G} (h : a * b ∈ H) : b * a ∈ H := have a⁻¹ * (a * b) * a⁻¹⁻¹ ∈ H, from nH.conj_mem (a * b) h a⁻¹, by simpa @[to_additive] lemma mem_comm_iff {a b : G} : a * b ∈ H ↔ b * a ∈ H := ⟨nH.mem_comm, nH.mem_comm⟩ end normal variables (H) /-- A subgroup is characteristic if it is fixed by all automorphisms. Several equivalent conditions are provided by lemmas of the form `characteristic.iff...` -/ structure characteristic : Prop := (fixed : ∀ ϕ : G ≃* G, H.comap ϕ.to_monoid_hom = H) attribute [class] characteristic @[priority 100] instance normal_of_characteristic [h : H.characteristic] : H.normal := ⟨λ a ha b, (set_like.ext_iff.mp (h.fixed (mul_aut.conj b)) a).mpr ha⟩ end subgroup namespace add_subgroup variables (H : add_subgroup A) /-- A add_subgroup is characteristic if it is fixed by all automorphisms. Several equivalent conditions are provided by lemmas of the form `characteristic.iff...` -/ structure characteristic : Prop := (fixed : ∀ ϕ : A ≃+ A, H.comap ϕ.to_add_monoid_hom = H) attribute [to_additive add_subgroup.characteristic] subgroup.characteristic attribute [class] characteristic @[priority 100] instance normal_of_characteristic [h : H.characteristic] : H.normal := ⟨λ a ha b, (set_like.ext_iff.mp (h.fixed (add_aut.conj b)) a).mpr ha⟩ end add_subgroup namespace subgroup variables {H K : subgroup G} @[to_additive] lemma characteristic_iff_comap_eq : H.characteristic ↔ ∀ ϕ : G ≃* G, H.comap ϕ.to_monoid_hom = H := ⟨characteristic.fixed, characteristic.mk⟩ @[to_additive] lemma characteristic_iff_comap_le : H.characteristic ↔ ∀ ϕ : G ≃* G, H.comap ϕ.to_monoid_hom ≤ H := characteristic_iff_comap_eq.trans ⟨λ h ϕ, le_of_eq (h ϕ), λ h ϕ, le_antisymm (h ϕ) (λ g hg, h ϕ.symm ((congr_arg (∈ H) (ϕ.symm_apply_apply g)).mpr hg))⟩ @[to_additive] lemma characteristic_iff_le_comap : H.characteristic ↔ ∀ ϕ : G ≃* G, H ≤ H.comap ϕ.to_monoid_hom := characteristic_iff_comap_eq.trans ⟨λ h ϕ, ge_of_eq (h ϕ), λ h ϕ, le_antisymm (λ g hg, (congr_arg (∈ H) (ϕ.symm_apply_apply g)).mp (h ϕ.symm hg)) (h ϕ)⟩ @[to_additive] lemma characteristic_iff_map_eq : H.characteristic ↔ ∀ ϕ : G ≃* G, H.map ϕ.to_monoid_hom = H := begin simp_rw map_equiv_eq_comap_symm, exact characteristic_iff_comap_eq.trans ⟨λ h ϕ, h ϕ.symm, λ h ϕ, h ϕ.symm⟩, end @[to_additive] lemma characteristic_iff_map_le : H.characteristic ↔ ∀ ϕ : G ≃* G, H.map ϕ.to_monoid_hom ≤ H := begin simp_rw map_equiv_eq_comap_symm, exact characteristic_iff_comap_le.trans ⟨λ h ϕ, h ϕ.symm, λ h ϕ, h ϕ.symm⟩, end @[to_additive] lemma characteristic_iff_le_map : H.characteristic ↔ ∀ ϕ : G ≃* G, H ≤ H.map ϕ.to_monoid_hom := begin simp_rw map_equiv_eq_comap_symm, exact characteristic_iff_le_comap.trans ⟨λ h ϕ, h ϕ.symm, λ h ϕ, h ϕ.symm⟩, end @[to_additive] instance bot_characteristic : characteristic (⊥ : subgroup G) := characteristic_iff_le_map.mpr (λ ϕ, bot_le) @[to_additive] instance top_characteristic : characteristic (⊤ : subgroup G) := characteristic_iff_map_le.mpr (λ ϕ, le_top) variable (G) /-- The center of a group `G` is the set of elements that commute with everything in `G` -/ @[to_additive "The center of an additive group `G` is the set of elements that commute with everything in `G`"] def center : subgroup G := { carrier := set.center G, inv_mem' := λ a, set.inv_mem_center, .. submonoid.center G } @[to_additive] lemma coe_center : ↑(center G) = set.center G := rfl @[simp, to_additive] lemma center_to_submonoid : (center G).to_submonoid = submonoid.center G := rfl variable {G} @[to_additive] lemma mem_center_iff {z : G} : z ∈ center G ↔ ∀ g, g * z = z * g := iff.rfl instance decidable_mem_center [decidable_eq G] [fintype G] : decidable_pred (∈ center G) := λ _, decidable_of_iff' _ mem_center_iff @[to_additive] instance center_characteristic : (center G).characteristic := begin refine characteristic_iff_comap_le.mpr (λ ϕ g hg h, _), rw [←ϕ.injective.eq_iff, ϕ.map_mul, ϕ.map_mul], exact hg (ϕ h), end lemma _root_.comm_group.center_eq_top {G : Type*} [comm_group G] : center G = ⊤ := by { rw [eq_top_iff'], intros x y, exact mul_comm y x } /-- A group is commutative if the center is the whole group -/ def _root_.group.comm_group_of_center_eq_top (h : center G = ⊤) : comm_group G := { mul_comm := by { rw eq_top_iff' at h, intros x y, exact h y x }, .. (_ : group G) } variables {G} (H) section normalizer /-- The `normalizer` of `H` is the largest subgroup of `G` inside which `H` is normal. -/ @[to_additive "The `normalizer` of `H` is the largest subgroup of `G` inside which `H` is normal."] def normalizer : subgroup G := { carrier := {g : G | ∀ n, n ∈ H ↔ g * n * g⁻¹ ∈ H}, one_mem' := by simp, mul_mem' := λ a b (ha : ∀ n, n ∈ H ↔ a * n * a⁻¹ ∈ H) (hb : ∀ n, n ∈ H ↔ b * n * b⁻¹ ∈ H) n, by { rw [hb, ha], simp [mul_assoc] }, inv_mem' := λ a (ha : ∀ n, n ∈ H ↔ a * n * a⁻¹ ∈ H) n, by { rw [ha (a⁻¹ * n * a⁻¹⁻¹)], simp [mul_assoc] } } -- variant for sets. -- TODO should this replace `normalizer`? /-- The `set_normalizer` of `S` is the subgroup of `G` whose elements satisfy `g*S*g⁻¹=S` -/ @[to_additive "The `set_normalizer` of `S` is the subgroup of `G` whose elements satisfy `g+S-g=S`."] def set_normalizer (S : set G) : subgroup G := { carrier := {g : G | ∀ n, n ∈ S ↔ g * n * g⁻¹ ∈ S}, one_mem' := by simp, mul_mem' := λ a b (ha : ∀ n, n ∈ S ↔ a * n * a⁻¹ ∈ S) (hb : ∀ n, n ∈ S ↔ b * n * b⁻¹ ∈ S) n, by { rw [hb, ha], simp [mul_assoc] }, inv_mem' := λ a (ha : ∀ n, n ∈ S ↔ a * n * a⁻¹ ∈ S) n, by { rw [ha (a⁻¹ * n * a⁻¹⁻¹)], simp [mul_assoc] } } lemma mem_normalizer_fintype {S : set G} [finite S] {x : G} (h : ∀ n, n ∈ S → x * n * x⁻¹ ∈ S) : x ∈ subgroup.set_normalizer S := by haveI := classical.prop_decidable; casesI nonempty_fintype S; haveI := set.fintype_image S (λ n, x * n * x⁻¹); exact λ n, ⟨h n, λ h₁, have heq : (λ n, x * n * x⁻¹) '' S = S := set.eq_of_subset_of_card_le (λ n ⟨y, hy⟩, hy.2 ▸ h y hy.1) (by rw set.card_image_of_injective S conj_injective), have x * n * x⁻¹ ∈ (λ n, x * n * x⁻¹) '' S := heq.symm ▸ h₁, let ⟨y, hy⟩ := this in conj_injective hy.2 ▸ hy.1⟩ variable {H} @[to_additive] lemma mem_normalizer_iff {g : G} : g ∈ H.normalizer ↔ ∀ h, h ∈ H ↔ g * h * g⁻¹ ∈ H := iff.rfl @[to_additive] lemma mem_normalizer_iff'' {g : G} : g ∈ H.normalizer ↔ ∀ h : G, h ∈ H ↔ g⁻¹ * h * g ∈ H := by rw [←inv_mem_iff, mem_normalizer_iff, inv_inv] @[to_additive] lemma mem_normalizer_iff' {g : G} : g ∈ H.normalizer ↔ ∀ n, n * g ∈ H ↔ g * n ∈ H := ⟨λ h n, by rw [h, mul_assoc, mul_inv_cancel_right], λ h n, by rw [mul_assoc, ←h, inv_mul_cancel_right]⟩ @[to_additive] lemma le_normalizer : H ≤ normalizer H := λ x xH n, by rw [H.mul_mem_cancel_right (H.inv_mem xH), H.mul_mem_cancel_left xH] @[priority 100, to_additive] instance normal_in_normalizer : (H.comap H.normalizer.subtype).normal := ⟨λ x xH g, by simpa using (g.2 x).1 xH⟩ @[to_additive] lemma normalizer_eq_top : H.normalizer = ⊤ ↔ H.normal := eq_top_iff.trans ⟨λ h, ⟨λ a ha b, (h (mem_top b) a).mp ha⟩, λ h a ha b, ⟨λ hb, h.conj_mem b hb a, λ hb, by rwa [h.mem_comm_iff, inv_mul_cancel_left] at hb⟩⟩ @[to_additive] lemma center_le_normalizer : center G ≤ H.normalizer := λ x hx y, by simp [← mem_center_iff.mp hx y, mul_assoc] open_locale classical @[to_additive] lemma le_normalizer_of_normal [hK : (H.comap K.subtype).normal] (HK : H ≤ K) : K ≤ H.normalizer := λ x hx y, ⟨λ yH, hK.conj_mem ⟨y, HK yH⟩ yH ⟨x, hx⟩, λ yH, by simpa [mem_comap, mul_assoc] using hK.conj_mem ⟨x * y * x⁻¹, HK yH⟩ yH ⟨x⁻¹, K.inv_mem hx⟩⟩ variables {N : Type*} [group N] /-- The preimage of the normalizer is contained in the normalizer of the preimage. -/ @[to_additive "The preimage of the normalizer is contained in the normalizer of the preimage."] lemma le_normalizer_comap (f : N →* G) : H.normalizer.comap f ≤ (H.comap f).normalizer := λ x, begin simp only [mem_normalizer_iff, mem_comap], assume h n, simp [h (f n)] end /-- The image of the normalizer is contained in the normalizer of the image. -/ @[to_additive "The image of the normalizer is contained in the normalizer of the image."] lemma le_normalizer_map (f : G →* N) : H.normalizer.map f ≤ (H.map f).normalizer := λ _, begin simp only [and_imp, exists_prop, mem_map, exists_imp_distrib, mem_normalizer_iff], rintros x hx rfl n, split, { rintros ⟨y, hy, rfl⟩, use [x * y * x⁻¹, (hx y).1 hy], simp }, { rintros ⟨y, hyH, hy⟩, use [x⁻¹ * y * x], rw [hx], simp [hy, hyH, mul_assoc] } end variable (G) /-- Every proper subgroup `H` of `G` is a proper normal subgroup of the normalizer of `H` in `G`. -/ def _root_.normalizer_condition := ∀ (H : subgroup G), H < ⊤ → H < normalizer H variable {G} /-- Alternative phrasing of the normalizer condition: Only the full group is self-normalizing. This may be easier to work with, as it avoids inequalities and negations. -/ lemma _root_.normalizer_condition_iff_only_full_group_self_normalizing : normalizer_condition G ↔ ∀ (H : subgroup G), H.normalizer = H → H = ⊤ := begin apply forall_congr, intro H, simp only [lt_iff_le_and_ne, le_normalizer, true_and, le_top, ne.def], tauto!, end variable (H) /-- In a group that satisifes the normalizer condition, every maximal subgroup is normal -/ lemma normalizer_condition.normal_of_coatom (hnc : normalizer_condition G) (hmax : is_coatom H) : H.normal := normalizer_eq_top.mp (hmax.2 _ (hnc H (lt_top_iff_ne_top.mpr hmax.1))) end normalizer section centralizer /-- The `centralizer` of `H` is the subgroup of `g : G` commuting with every `h : H`. -/ @[to_additive "The `centralizer` of `H` is the additive subgroup of `g : G` commuting with every `h : H`."] def centralizer : subgroup G := { carrier := set.centralizer H, inv_mem' := λ g, set.inv_mem_centralizer, .. submonoid.centralizer ↑H } variables {H} @[to_additive] lemma mem_centralizer_iff {g : G} : g ∈ H.centralizer ↔ ∀ h ∈ H, h * g = g * h := iff.rfl @[to_additive] lemma mem_centralizer_iff_commutator_eq_one {g : G} : g ∈ H.centralizer ↔ ∀ h ∈ H, h * g * h⁻¹ * g⁻¹ = 1 := by simp only [mem_centralizer_iff, mul_inv_eq_iff_eq_mul, one_mul] @[to_additive] lemma centralizer_top : centralizer ⊤ = center G := set_like.ext' (set.centralizer_univ G) @[to_additive] lemma le_centralizer_iff : H ≤ K.centralizer ↔ K ≤ H.centralizer := ⟨λ h x hx y hy, (h hy x hx).symm, λ h x hx y hy, (h hy x hx).symm⟩ @[to_additive] lemma centralizer_le (h : H ≤ K) : centralizer K ≤ centralizer H := submonoid.centralizer_le h @[to_additive] instance subgroup.centralizer.characteristic [hH : H.characteristic] : H.centralizer.characteristic := begin refine subgroup.characteristic_iff_comap_le.mpr (λ ϕ g hg h hh, ϕ.injective _), rw [map_mul, map_mul], exact hg (ϕ h) (subgroup.characteristic_iff_le_comap.mp hH ϕ hh), end end centralizer /-- Commutivity of a subgroup -/ structure is_commutative : Prop := (is_comm : _root_.is_commutative H (*)) attribute [class] is_commutative /-- Commutivity of an additive subgroup -/ structure _root_.add_subgroup.is_commutative (H : add_subgroup A) : Prop := (is_comm : _root_.is_commutative H (+)) attribute [to_additive add_subgroup.is_commutative] subgroup.is_commutative attribute [class] add_subgroup.is_commutative /-- A commutative subgroup is commutative. -/ @[to_additive "A commutative subgroup is commutative."] instance is_commutative.comm_group [h : H.is_commutative] : comm_group H := { mul_comm := h.is_comm.comm, .. H.to_group } instance center.is_commutative : (center G).is_commutative := ⟨⟨λ a b, subtype.ext (b.2 a)⟩⟩ @[to_additive] instance map_is_commutative {G' : Type*} [group G'] (f : G →* G') [H.is_commutative] : (H.map f).is_commutative := ⟨⟨begin rintros ⟨-, a, ha, rfl⟩ ⟨-, b, hb, rfl⟩, rw [subtype.ext_iff, coe_mul, coe_mul, subtype.coe_mk, subtype.coe_mk, ←map_mul, ←map_mul], exact congr_arg f (subtype.ext_iff.mp (mul_comm ⟨a, ha⟩ ⟨b, hb⟩)), end⟩⟩ @[to_additive] lemma comap_injective_is_commutative {G' : Type*} [group G'] {f : G' →* G} (hf : function.injective f) [H.is_commutative] : (H.comap f).is_commutative := ⟨⟨λ a b, subtype.ext begin have := mul_comm (⟨f a, a.2⟩ : H) (⟨f b, b.2⟩ : H), rwa [subtype.ext_iff, coe_mul, coe_mul, coe_mk, coe_mk, ←map_mul, ←map_mul, hf.eq_iff] at this, end⟩⟩ @[to_additive] instance subgroup_of_is_commutative [H.is_commutative] : (H.subgroup_of K).is_commutative := H.comap_injective_is_commutative subtype.coe_injective end subgroup namespace group variables {s : set G} /-- Given a set `s`, `conjugates_of_set s` is the set of all conjugates of the elements of `s`. -/ def conjugates_of_set (s : set G) : set G := ⋃ a ∈ s, conjugates_of a lemma mem_conjugates_of_set_iff {x : G} : x ∈ conjugates_of_set s ↔ ∃ a ∈ s, is_conj a x := set.mem_Union₂ theorem subset_conjugates_of_set : s ⊆ conjugates_of_set s := λ (x : G) (h : x ∈ s), mem_conjugates_of_set_iff.2 ⟨x, h, is_conj.refl _⟩ theorem conjugates_of_set_mono {s t : set G} (h : s ⊆ t) : conjugates_of_set s ⊆ conjugates_of_set t := set.bUnion_subset_bUnion_left h lemma conjugates_subset_normal {N : subgroup G} [tn : N.normal] {a : G} (h : a ∈ N) : conjugates_of a ⊆ N := by { rintros a hc, obtain ⟨c, rfl⟩ := is_conj_iff.1 hc, exact tn.conj_mem a h c } theorem conjugates_of_set_subset {s : set G} {N : subgroup G} [N.normal] (h : s ⊆ N) : conjugates_of_set s ⊆ N := set.Union₂_subset (λ x H, conjugates_subset_normal (h H)) /-- The set of conjugates of `s` is closed under conjugation. -/ lemma conj_mem_conjugates_of_set {x c : G} : x ∈ conjugates_of_set s → (c * x * c⁻¹ ∈ conjugates_of_set s) := λ H, begin rcases (mem_conjugates_of_set_iff.1 H) with ⟨a,h₁,h₂⟩, exact mem_conjugates_of_set_iff.2 ⟨a, h₁, h₂.trans (is_conj_iff.2 ⟨c,rfl⟩)⟩, end end group namespace subgroup open group variable {s : set G} /-- The normal closure of a set `s` is the subgroup closure of all the conjugates of elements of `s`. It is the smallest normal subgroup containing `s`. -/ def normal_closure (s : set G) : subgroup G := closure (conjugates_of_set s) theorem conjugates_of_set_subset_normal_closure : conjugates_of_set s ⊆ normal_closure s := subset_closure theorem subset_normal_closure : s ⊆ normal_closure s := set.subset.trans subset_conjugates_of_set conjugates_of_set_subset_normal_closure theorem le_normal_closure {H : subgroup G} : H ≤ normal_closure ↑H := λ _ h, subset_normal_closure h /-- The normal closure of `s` is a normal subgroup. -/ instance normal_closure_normal : (normal_closure s).normal := ⟨λ n h g, begin refine subgroup.closure_induction h (λ x hx, _) _ (λ x y ihx ihy, _) (λ x ihx, _), { exact (conjugates_of_set_subset_normal_closure (conj_mem_conjugates_of_set hx)) }, { simpa using (normal_closure s).one_mem }, { rw ← conj_mul, exact mul_mem ihx ihy }, { rw ← conj_inv, exact inv_mem ihx } end⟩ /-- The normal closure of `s` is the smallest normal subgroup containing `s`. -/ theorem normal_closure_le_normal {N : subgroup G} [N.normal] (h : s ⊆ N) : normal_closure s ≤ N := begin assume a w, refine closure_induction w (λ x hx, _) _ (λ x y ihx ihy, _) (λ x ihx, _), { exact (conjugates_of_set_subset h hx) }, { exact one_mem _ }, { exact mul_mem ihx ihy }, { exact inv_mem ihx } end lemma normal_closure_subset_iff {N : subgroup G} [N.normal] : s ⊆ N ↔ normal_closure s ≤ N := ⟨normal_closure_le_normal, set.subset.trans (subset_normal_closure)⟩ theorem normal_closure_mono {s t : set G} (h : s ⊆ t) : normal_closure s ≤ normal_closure t := normal_closure_le_normal (set.subset.trans h subset_normal_closure) theorem normal_closure_eq_infi : normal_closure s = ⨅ (N : subgroup G) (_ : normal N) (hs : s ⊆ N), N := le_antisymm (le_infi (λ N, le_infi (λ hN, by exactI le_infi (normal_closure_le_normal)))) (infi_le_of_le (normal_closure s) (infi_le_of_le (by apply_instance) (infi_le_of_le subset_normal_closure le_rfl))) @[simp] theorem normal_closure_eq_self (H : subgroup G) [H.normal] : normal_closure ↑H = H := le_antisymm (normal_closure_le_normal rfl.subset) (le_normal_closure) @[simp] theorem normal_closure_idempotent : normal_closure ↑(normal_closure s) = normal_closure s := normal_closure_eq_self _ theorem closure_le_normal_closure {s : set G} : closure s ≤ normal_closure s := by simp only [subset_normal_closure, closure_le] @[simp] theorem normal_closure_closure_eq_normal_closure {s : set G} : normal_closure ↑(closure s) = normal_closure s := le_antisymm (normal_closure_le_normal closure_le_normal_closure) (normal_closure_mono subset_closure) /-- The normal core of a subgroup `H` is the largest normal subgroup of `G` contained in `H`, as shown by `subgroup.normal_core_eq_supr`. -/ def normal_core (H : subgroup G) : subgroup G := { carrier := {a : G | ∀ b : G, b * a * b⁻¹ ∈ H}, one_mem' := λ a, by rw [mul_one, mul_inv_self]; exact H.one_mem, inv_mem' := λ a h b, (congr_arg (∈ H) conj_inv).mp (H.inv_mem (h b)), mul_mem' := λ a b ha hb c, (congr_arg (∈ H) conj_mul).mp (H.mul_mem (ha c) (hb c)) } lemma normal_core_le (H : subgroup G) : H.normal_core ≤ H := λ a h, by { rw [←mul_one a, ←inv_one, ←one_mul a], exact h 1 } instance normal_core_normal (H : subgroup G) : H.normal_core.normal := ⟨λ a h b c, by rw [mul_assoc, mul_assoc, ←mul_inv_rev, ←mul_assoc, ←mul_assoc]; exact h (c * b)⟩ lemma normal_le_normal_core {H : subgroup G} {N : subgroup G} [hN : N.normal] : N ≤ H.normal_core ↔ N ≤ H := ⟨ge_trans H.normal_core_le, λ h_le n hn g, h_le (hN.conj_mem n hn g)⟩ lemma normal_core_mono {H K : subgroup G} (h : H ≤ K) : H.normal_core ≤ K.normal_core := normal_le_normal_core.mpr (H.normal_core_le.trans h) lemma normal_core_eq_supr (H : subgroup G) : H.normal_core = ⨆ (N : subgroup G) (_ : normal N) (hs : N ≤ H), N := le_antisymm (le_supr_of_le H.normal_core (le_supr_of_le H.normal_core_normal (le_supr_of_le H.normal_core_le le_rfl))) (supr_le (λ N, supr_le (λ hN, supr_le (by exactI normal_le_normal_core.mpr)))) @[simp] lemma normal_core_eq_self (H : subgroup G) [H.normal] : H.normal_core = H := le_antisymm H.normal_core_le (normal_le_normal_core.mpr le_rfl) @[simp] theorem normal_core_idempotent (H : subgroup G) : H.normal_core.normal_core = H.normal_core := H.normal_core.normal_core_eq_self end subgroup namespace monoid_hom variables {N : Type*} {P : Type*} [group N] [group P] (K : subgroup G) open subgroup /-- The range of a monoid homomorphism from a group is a subgroup. -/ @[to_additive "The range of an `add_monoid_hom` from an `add_group` is an `add_subgroup`."] def range (f : G →* N) : subgroup N := subgroup.copy ((⊤ : subgroup G).map f) (set.range f) (by simp [set.ext_iff]) @[to_additive] instance decidable_mem_range (f : G →* N) [fintype G] [decidable_eq N] : decidable_pred (∈ f.range) := λ x, fintype.decidable_exists_fintype @[simp, to_additive] lemma coe_range (f : G →* N) : (f.range : set N) = set.range f := rfl @[simp, to_additive] lemma mem_range {f : G →* N} {y : N} : y ∈ f.range ↔ ∃ x, f x = y := iff.rfl @[to_additive] lemma range_eq_map (f : G →* N) : f.range = (⊤ : subgroup G).map f := by ext; simp /-- The canonical surjective group homomorphism `G →* f(G)` induced by a group homomorphism `G →* N`. -/ @[to_additive "The canonical surjective `add_group` homomorphism `G →+ f(G)` induced by a group homomorphism `G →+ N`."] def range_restrict (f : G →* N) : G →* f.range := cod_restrict f _ $ λ x, ⟨x, rfl⟩ @[simp, to_additive] lemma coe_range_restrict (f : G →* N) (g : G) : (f.range_restrict g : N) = f g := rfl @[to_additive] lemma range_restrict_surjective (f : G →* N) : function.surjective f.range_restrict := λ ⟨_, g, rfl⟩, ⟨g, rfl⟩ @[to_additive] lemma map_range (g : N →* P) (f : G →* N) : f.range.map g = (g.comp f).range := by rw [range_eq_map, range_eq_map]; exact (⊤ : subgroup G).map_map g f @[to_additive] lemma range_top_iff_surjective {N} [group N] {f : G →* N} : f.range = (⊤ : subgroup N) ↔ function.surjective f := set_like.ext'_iff.trans $ iff.trans (by rw [coe_range, coe_top]) set.range_iff_surjective /-- The range of a surjective monoid homomorphism is the whole of the codomain. -/ @[to_additive "The range of a surjective `add_monoid` homomorphism is the whole of the codomain."] lemma range_top_of_surjective {N} [group N] (f : G →* N) (hf : function.surjective f) : f.range = (⊤ : subgroup N) := range_top_iff_surjective.2 hf @[simp, to_additive] lemma range_one : (1 : G →* N).range = ⊥ := set_like.ext $ λ x, by simpa using @comm _ (=) _ 1 x @[simp, to_additive] lemma _root_.subgroup.subtype_range (H : subgroup G) : H.subtype.range = H := by { rw [range_eq_map, ← set_like.coe_set_eq, coe_map, subgroup.coe_subtype], ext, simp } @[simp, to_additive] lemma _root_.subgroup.inclusion_range {H K : subgroup G} (h_le : H ≤ K) : (inclusion h_le).range = H.subgroup_of K := subgroup.ext (λ g, set.ext_iff.mp (set.range_inclusion h_le) g) @[to_additive] lemma subgroup_of_range_eq_of_le {G₁ G₂ : Type*} [group G₁] [group G₂] {K : subgroup G₂} (f : G₁ →* G₂) (h : f.range ≤ K) : f.range.subgroup_of K = (f.cod_restrict K (λ x, h ⟨x, rfl⟩)).range := begin ext k, refine exists_congr _, simp [subtype.ext_iff], end /-- Computable alternative to `monoid_hom.of_injective`. -/ @[to_additive /-"Computable alternative to `add_monoid_hom.of_injective`."-/] def of_left_inverse {f : G →* N} {g : N →* G} (h : function.left_inverse g f) : G ≃* f.range := { to_fun := f.range_restrict, inv_fun := g ∘ f.range.subtype, left_inv := h, right_inv := by { rintros ⟨x, y, rfl⟩, apply subtype.ext, rw [coe_range_restrict, function.comp_apply, subgroup.coe_subtype, subtype.coe_mk, h] }, .. f.range_restrict } @[simp, to_additive] lemma of_left_inverse_apply {f : G →* N} {g : N →* G} (h : function.left_inverse g f) (x : G) : ↑(of_left_inverse h x) = f x := rfl @[simp, to_additive] lemma of_left_inverse_symm_apply {f : G →* N} {g : N →* G} (h : function.left_inverse g f) (x : f.range) : (of_left_inverse h).symm x = g x := rfl /-- The range of an injective group homomorphism is isomorphic to its domain. -/ @[to_additive /-"The range of an injective additive group homomorphism is isomorphic to its domain."-/ ] noncomputable def of_injective {f : G →* N} (hf : function.injective f) : G ≃* f.range := (mul_equiv.of_bijective (f.cod_restrict f.range (λ x, ⟨x, rfl⟩)) ⟨λ x y h, hf (subtype.ext_iff.mp h), by { rintros ⟨x, y, rfl⟩, exact ⟨y, rfl⟩ }⟩) @[to_additive] lemma of_injective_apply {f : G →* N} (hf : function.injective f) {x : G} : ↑(of_injective hf x) = f x := rfl section ker variables {M : Type*} [mul_one_class M] /-- The multiplicative kernel of a monoid homomorphism is the subgroup of elements `x : G` such that `f x = 1` -/ @[to_additive "The additive kernel of an `add_monoid` homomorphism is the `add_subgroup` of elements such that `f x = 0`"] def ker (f : G →* M) : subgroup G := { inv_mem' := λ x (hx : f x = 1), calc f x⁻¹ = f x * f x⁻¹ : by rw [hx, one_mul] ... = f (x * x⁻¹) : by rw [f.map_mul] ... = f 1 : by rw [mul_right_inv] ... = 1 : f.map_one, ..f.mker } @[to_additive] lemma mem_ker (f : G →* M) {x : G} : x ∈ f.ker ↔ f x = 1 := iff.rfl @[to_additive] lemma coe_ker (f : G →* M) : (f.ker : set G) = (f : G → M) ⁻¹' {1} := rfl @[to_additive] lemma eq_iff (f : G →* N) {x y : G} : f x = f y ↔ y⁻¹ * x ∈ f.ker := by rw [f.mem_ker, f.map_mul, f.map_inv, inv_mul_eq_one, eq_comm] @[to_additive] instance decidable_mem_ker [decidable_eq M] (f : G →* M) : decidable_pred (∈ f.ker) := λ x, decidable_of_iff (f x = 1) f.mem_ker @[to_additive] lemma comap_ker (g : N →* P) (f : G →* N) : g.ker.comap f = (g.comp f).ker := rfl @[simp, to_additive] lemma comap_bot (f : G →* N) : (⊥ : subgroup N).comap f = f.ker := rfl @[to_additive] lemma range_restrict_ker (f : G →* N) : ker (range_restrict f) = ker f := begin ext, change (⟨f x, _⟩ : range f) = ⟨1, _⟩ ↔ f x = 1, simp only [], end @[simp, to_additive] lemma ker_one : (1 : G →* M).ker = ⊤ := by { ext, simp [mem_ker] } @[to_additive] lemma ker_eq_bot_iff (f : G →* N) : f.ker = ⊥ ↔ function.injective f := begin split, { intros h x y hxy, rwa [←mul_inv_eq_one, ←map_inv, ←map_mul, ←mem_ker, h, mem_bot, mul_inv_eq_one] at hxy }, { exact λ h, le_bot_iff.mp (λ x hx, h (hx.trans f.map_one.symm)) }, end @[simp, to_additive] lemma _root_.subgroup.ker_subtype (H : subgroup G) : H.subtype.ker = ⊥ := H.subtype.ker_eq_bot_iff.mpr subtype.coe_injective @[simp, to_additive] lemma _root_.subgroup.ker_inclusion {H K : subgroup G} (h : H ≤ K) : (inclusion h).ker = ⊥ := (inclusion h).ker_eq_bot_iff.mpr (set.inclusion_injective h) @[to_additive] lemma prod_map_comap_prod {G' : Type*} {N' : Type*} [group G'] [group N'] (f : G →* N) (g : G' →* N') (S : subgroup N) (S' : subgroup N') : (S.prod S').comap (prod_map f g) = (S.comap f).prod (S'.comap g) := set_like.coe_injective $ set.preimage_prod_map_prod f g _ _ @[to_additive] lemma ker_prod_map {G' : Type*} {N' : Type*} [group G'] [group N'] (f : G →* N) (g : G' →* N') : (prod_map f g).ker = f.ker.prod g.ker := by rw [←comap_bot, ←comap_bot, ←comap_bot, ←prod_map_comap_prod, bot_prod_bot] end ker /-- The subgroup of elements `x : G` such that `f x = g x` -/ @[to_additive "The additive subgroup of elements `x : G` such that `f x = g x`"] def eq_locus (f g : G →* N) : subgroup G := { inv_mem' := λ x (hx : f x = g x), show f x⁻¹ = g x⁻¹, by rw [f.map_inv, g.map_inv, hx], .. eq_mlocus f g} /-- If two monoid homomorphisms are equal on a set, then they are equal on its subgroup closure. -/ @[to_additive "If two monoid homomorphisms are equal on a set, then they are equal on its subgroup closure."] lemma eq_on_closure {f g : G →* N} {s : set G} (h : set.eq_on f g s) : set.eq_on f g (closure s) := show closure s ≤ f.eq_locus g, from (closure_le _).2 h @[to_additive] lemma eq_of_eq_on_top {f g : G →* N} (h : set.eq_on f g (⊤ : subgroup G)) : f = g := ext $ λ x, h trivial @[to_additive] lemma eq_of_eq_on_dense {s : set G} (hs : closure s = ⊤) {f g : G →* N} (h : s.eq_on f g) : f = g := eq_of_eq_on_top $ hs ▸ eq_on_closure h @[to_additive] lemma gclosure_preimage_le (f : G →* N) (s : set N) : closure (f ⁻¹' s) ≤ (closure s).comap f := (closure_le _).2 $ λ x hx, by rw [set_like.mem_coe, mem_comap]; exact subset_closure hx /-- The image under a monoid homomorphism of the subgroup generated by a set equals the subgroup generated by the image of the set. -/ @[to_additive "The image under an `add_monoid` hom of the `add_subgroup` generated by a set equals the `add_subgroup` generated by the image of the set."] lemma map_closure (f : G →* N) (s : set G) : (closure s).map f = closure (f '' s) := set.image_preimage.l_comm_of_u_comm (subgroup.gc_map_comap f) (subgroup.gi N).gc (subgroup.gi G).gc (λ t, rfl) -- this instance can't go just after the definition of `mrange` because `fintype` is -- not imported at that stage /-- The range of a finite monoid under a monoid homomorphism is finite. Note: this instance can form a diamond with `subtype.fintype` in the presence of `fintype N`. -/ @[to_additive "The range of a finite additive monoid under an additive monoid homomorphism is finite. Note: this instance can form a diamond with `subtype.fintype` or `subgroup.fintype` in the presence of `fintype N`."] instance fintype_mrange {M N : Type*} [monoid M] [monoid N] [fintype M] [decidable_eq N] (f : M →* N) : fintype (mrange f) := set.fintype_range f /-- The range of a finite group under a group homomorphism is finite. Note: this instance can form a diamond with `subtype.fintype` or `subgroup.fintype` in the presence of `fintype N`. -/ @[to_additive "The range of a finite additive group under an additive group homomorphism is finite. Note: this instance can form a diamond with `subtype.fintype` or `subgroup.fintype` in the presence of `fintype N`."] instance fintype_range [fintype G] [decidable_eq N] (f : G →* N) : fintype (range f) := set.fintype_range f end monoid_hom namespace subgroup variables {N : Type*} [group N] (H : subgroup G) @[to_additive] lemma map_eq_bot_iff {f : G →* N} : H.map f = ⊥ ↔ H ≤ f.ker := begin rw eq_bot_iff, split, { exact λ h x hx, h ⟨x, hx, rfl⟩ }, { intros h x hx, obtain ⟨y, hy, rfl⟩ := hx, exact h hy }, end @[to_additive] lemma map_eq_bot_iff_of_injective {f : G →* N} (hf : function.injective f) : H.map f = ⊥ ↔ H = ⊥ := by rw [map_eq_bot_iff, f.ker_eq_bot_iff.mpr hf, le_bot_iff] end subgroup namespace subgroup open monoid_hom variables {N : Type*} [group N] (f : G →* N) @[to_additive] lemma map_le_range (H : subgroup G) : map f H ≤ f.range := (range_eq_map f).symm ▸ map_mono le_top @[to_additive] lemma map_subtype_le {H : subgroup G} (K : subgroup H) : K.map H.subtype ≤ H := (K.map_le_range H.subtype).trans (le_of_eq H.subtype_range) @[to_additive] lemma ker_le_comap (H : subgroup N) : f.ker ≤ comap f H := (comap_bot f) ▸ comap_mono bot_le @[to_additive] lemma map_comap_le (H : subgroup N) : map f (comap f H) ≤ H := (gc_map_comap f).l_u_le _ @[to_additive] lemma le_comap_map (H : subgroup G) : H ≤ comap f (map f H) := (gc_map_comap f).le_u_l _ @[to_additive] lemma map_comap_eq (H : subgroup N) : map f (comap f H) = f.range ⊓ H := set_like.ext' begin convert set.image_preimage_eq_inter_range, simp [set.inter_comm], end @[to_additive] lemma comap_map_eq (H : subgroup G) : comap f (map f H) = H ⊔ f.ker := begin refine le_antisymm _ (sup_le (le_comap_map _ _) (ker_le_comap _ _)), intros x hx, simp only [exists_prop, mem_map, mem_comap] at hx, rcases hx with ⟨y, hy, hy'⟩, rw ← mul_inv_cancel_left y x, exact mul_mem_sup hy (by simp [mem_ker, hy']), end @[to_additive] lemma map_comap_eq_self {f : G →* N} {H : subgroup N} (h : H ≤ f.range) : map f (comap f H) = H := by rwa [map_comap_eq, inf_eq_right] @[to_additive] lemma map_comap_eq_self_of_surjective {f : G →* N} (h : function.surjective f) (H : subgroup N) : map f (comap f H) = H := map_comap_eq_self ((range_top_of_surjective _ h).symm ▸ le_top) @[to_additive] lemma comap_le_comap_of_le_range {f : G →* N} {K L : subgroup N} (hf : K ≤ f.range) : K.comap f ≤ L.comap f ↔ K ≤ L := ⟨(map_comap_eq_self hf).ge.trans ∘ map_le_iff_le_comap.mpr, comap_mono⟩ @[to_additive] lemma comap_le_comap_of_surjective {f : G →* N} {K L : subgroup N} (hf : function.surjective f) : K.comap f ≤ L.comap f ↔ K ≤ L := comap_le_comap_of_le_range (le_top.trans (f.range_top_of_surjective hf).ge) @[to_additive] lemma comap_lt_comap_of_surjective {f : G →* N} {K L : subgroup N} (hf : function.surjective f) : K.comap f < L.comap f ↔ K < L := by simp_rw [lt_iff_le_not_le, comap_le_comap_of_surjective hf] @[to_additive] lemma comap_injective {f : G →* N} (h : function.surjective f) : function.injective (comap f) := λ K L, by simp only [le_antisymm_iff, comap_le_comap_of_surjective h, imp_self] @[to_additive] lemma comap_map_eq_self {f : G →* N} {H : subgroup G} (h : f.ker ≤ H) : comap f (map f H) = H := by rwa [comap_map_eq, sup_eq_left] @[to_additive] lemma comap_map_eq_self_of_injective {f : G →* N} (h : function.injective f) (H : subgroup G) : comap f (map f H) = H := comap_map_eq_self (((ker_eq_bot_iff _).mpr h).symm ▸ bot_le) @[to_additive] lemma map_le_map_iff_of_injective {f : G →* N} (hf : function.injective f) {H K : subgroup G} : H.map f ≤ K.map f ↔ H ≤ K := ⟨(congr_arg2 (≤) (H.comap_map_eq_self_of_injective hf) (K.comap_map_eq_self_of_injective hf)).mp ∘ comap_mono, map_mono⟩ @[simp, to_additive] lemma map_subtype_le_map_subtype {G' : subgroup G} {H K : subgroup G'} : H.map G'.subtype ≤ K.map G'.subtype ↔ H ≤ K := map_le_map_iff_of_injective subtype.coe_injective @[to_additive] lemma map_injective {f : G →* N} (h : function.injective f) : function.injective (map f) := λ K L hKL, by { apply_fun comap f at hKL, simpa [comap_map_eq_self_of_injective h] using hKL } @[to_additive] lemma map_eq_comap_of_inverse {f : G →* N} {g : N →* G} (hl : function.left_inverse g f) (hr : function.right_inverse g f) (H : subgroup G) : map f H = comap g H := set_like.ext' $ by rw [coe_map, coe_comap, set.image_eq_preimage_of_inverse hl hr] /-- Given `f(A) = f(B)`, `ker f ≤ A`, and `ker f ≤ B`, deduce that `A = B`. -/ @[to_additive "Given `f(A) = f(B)`, `ker f ≤ A`, and `ker f ≤ B`, deduce that `A = B`."] lemma map_injective_of_ker_le {H K : subgroup G} (hH : f.ker ≤ H) (hK : f.ker ≤ K) (hf : map f H = map f K) : H = K := begin apply_fun comap f at hf, rwa [comap_map_eq, comap_map_eq, sup_of_le_left hH, sup_of_le_left hK] at hf, end @[to_additive] lemma comap_sup_eq_of_le_range {H K : subgroup N} (hH : H ≤ f.range) (hK : K ≤ f.range) : comap f H ⊔ comap f K = comap f (H ⊔ K) := map_injective_of_ker_le f ((ker_le_comap f H).trans le_sup_left) (ker_le_comap f (H ⊔ K)) (by rw [map_comap_eq, map_sup, map_comap_eq, map_comap_eq, inf_eq_right.mpr hH, inf_eq_right.mpr hK, inf_eq_right.mpr (sup_le hH hK)]) @[to_additive] lemma comap_sup_eq (H K : subgroup N) (hf : function.surjective f) : comap f H ⊔ comap f K = comap f (H ⊔ K) := comap_sup_eq_of_le_range f (le_top.trans (ge_of_eq (f.range_top_of_surjective hf))) (le_top.trans (ge_of_eq (f.range_top_of_surjective hf))) @[to_additive] lemma sup_subgroup_of_eq {H K L : subgroup G} (hH : H ≤ L) (hK : K ≤ L) : H.subgroup_of L ⊔ K.subgroup_of L = (H ⊔ K).subgroup_of L := comap_sup_eq_of_le_range L.subtype (hH.trans (ge_of_eq L.subtype_range)) (hK.trans (ge_of_eq L.subtype_range)) /-- A subgroup is isomorphic to its image under an injective function -/ @[to_additive "An additive subgroup is isomorphic to its image under an injective function"] noncomputable def equiv_map_of_injective (H : subgroup G) (f : G →* N) (hf : function.injective f) : H ≃* H.map f := { map_mul' := λ _ _, subtype.ext (f.map_mul _ _), ..equiv.set.image f H hf } @[simp, to_additive] lemma coe_equiv_map_of_injective_apply (H : subgroup G) (f : G →* N) (hf : function.injective f) (h : H) : (equiv_map_of_injective H f hf h : N) = f h := rfl /-- The preimage of the normalizer is equal to the normalizer of the preimage of a surjective function. -/ @[to_additive "The preimage of the normalizer is equal to the normalizer of the preimage of a surjective function."] lemma comap_normalizer_eq_of_surjective (H : subgroup G) {f : N →* G} (hf : function.surjective f) : H.normalizer.comap f = (H.comap f).normalizer := le_antisymm (le_normalizer_comap f) begin assume x hx, simp only [mem_comap, mem_normalizer_iff] at *, assume n, rcases hf n with ⟨y, rfl⟩, simp [hx y] end @[to_additive] lemma comap_normalizer_eq_of_injective_of_le_range {N : Type*} [group N] (H : subgroup G) {f : N →* G} (hf : function.injective f) (h : H.normalizer ≤ f.range) : comap f H.normalizer = (comap f H).normalizer := begin apply (subgroup.map_injective hf), rw map_comap_eq_self h, apply le_antisymm, { refine (le_trans (le_of_eq _) (map_mono (le_normalizer_comap _))), rewrite map_comap_eq_self h, }, { refine (le_trans (le_normalizer_map f) (le_of_eq _)), rewrite map_comap_eq_self (le_trans le_normalizer h), } end @[to_additive] lemma comap_subtype_normalizer_eq {H N : subgroup G} (h : H.normalizer ≤ N) : comap N.subtype H.normalizer = (comap N.subtype H).normalizer := begin apply comap_normalizer_eq_of_injective_of_le_range, exact subtype.coe_injective, simpa, end /-- The image of the normalizer is equal to the normalizer of the image of an isomorphism. -/ @[to_additive "The image of the normalizer is equal to the normalizer of the image of an isomorphism."] lemma map_equiv_normalizer_eq (H : subgroup G) (f : G ≃* N) : H.normalizer.map f.to_monoid_hom = (H.map f.to_monoid_hom).normalizer := begin ext x, simp only [mem_normalizer_iff, mem_map_equiv], rw [f.to_equiv.forall_congr], simp end /-- The image of the normalizer is equal to the normalizer of the image of a bijective function. -/ @[to_additive "The image of the normalizer is equal to the normalizer of the image of a bijective function."] lemma map_normalizer_eq_of_bijective (H : subgroup G) {f : G →* N} (hf : function.bijective f) : H.normalizer.map f = (H.map f).normalizer := map_equiv_normalizer_eq H (mul_equiv.of_bijective f hf) end subgroup namespace monoid_hom variables {G₁ G₂ G₃ : Type*} [group G₁] [group G₂] [group G₃] variables (f : G₁ →* G₂) (f_inv : G₂ → G₁) /-- Auxiliary definition used to define `lift_of_right_inverse` -/ @[to_additive "Auxiliary definition used to define `lift_of_right_inverse`"] def lift_of_right_inverse_aux (hf : function.right_inverse f_inv f) (g : G₁ →* G₃) (hg : f.ker ≤ g.ker) : G₂ →* G₃ := { to_fun := λ b, g (f_inv b), map_one' := hg (hf 1), map_mul' := begin intros x y, rw [← g.map_mul, ← mul_inv_eq_one, ← g.map_inv, ← g.map_mul, ← g.mem_ker], apply hg, rw [f.mem_ker, f.map_mul, f.map_inv, mul_inv_eq_one, f.map_mul], simp only [hf _], end } @[simp, to_additive] lemma lift_of_right_inverse_aux_comp_apply (hf : function.right_inverse f_inv f) (g : G₁ →* G₃) (hg : f.ker ≤ g.ker) (x : G₁) : (f.lift_of_right_inverse_aux f_inv hf g hg) (f x) = g x := begin dsimp [lift_of_right_inverse_aux], rw [← mul_inv_eq_one, ← g.map_inv, ← g.map_mul, ← g.mem_ker], apply hg, rw [f.mem_ker, f.map_mul, f.map_inv, mul_inv_eq_one], simp only [hf _], end /-- `lift_of_right_inverse f hf g hg` is the unique group homomorphism `φ` * such that `φ.comp f = g` (`monoid_hom.lift_of_right_inverse_comp`), * where `f : G₁ →+* G₂` has a right_inverse `f_inv` (`hf`), * and `g : G₂ →+* G₃` satisfies `hg : f.ker ≤ g.ker`. See `monoid_hom.eq_lift_of_right_inverse` for the uniqueness lemma. ``` G₁. | \ f | \ g | \ v \⌟ G₂----> G₃ ∃!φ ``` -/ @[to_additive "`lift_of_right_inverse f f_inv hf g hg` is the unique additive group homomorphism `φ` * such that `φ.comp f = g` (`add_monoid_hom.lift_of_right_inverse_comp`), * where `f : G₁ →+ G₂` has a right_inverse `f_inv` (`hf`), * and `g : G₂ →+ G₃` satisfies `hg : f.ker ≤ g.ker`. See `add_monoid_hom.eq_lift_of_right_inverse` for the uniqueness lemma. ``` G₁. | \\ f | \\ g | \\ v \\⌟ G₂----> G₃ ∃!φ ```"] def lift_of_right_inverse (hf : function.right_inverse f_inv f) : {g : G₁ →* G₃ // f.ker ≤ g.ker} ≃ (G₂ →* G₃) := { to_fun := λ g, f.lift_of_right_inverse_aux f_inv hf g.1 g.2, inv_fun := λ φ, ⟨φ.comp f, λ x hx, (mem_ker _).mpr $ by simp [(mem_ker _).mp hx]⟩, left_inv := λ g, by { ext, simp only [comp_apply, lift_of_right_inverse_aux_comp_apply, subtype.coe_mk, subtype.val_eq_coe], }, right_inv := λ φ, by { ext b, simp [lift_of_right_inverse_aux, hf b], } } /-- A non-computable version of `monoid_hom.lift_of_right_inverse` for when no computable right inverse is available, that uses `function.surj_inv`. -/ @[simp, to_additive "A non-computable version of `add_monoid_hom.lift_of_right_inverse` for when no computable right inverse is available."] noncomputable abbreviation lift_of_surjective (hf : function.surjective f) : {g : G₁ →* G₃ // f.ker ≤ g.ker} ≃ (G₂ →* G₃) := f.lift_of_right_inverse (function.surj_inv hf) (function.right_inverse_surj_inv hf) @[simp, to_additive] lemma lift_of_right_inverse_comp_apply (hf : function.right_inverse f_inv f) (g : {g : G₁ →* G₃ // f.ker ≤ g.ker}) (x : G₁) : (f.lift_of_right_inverse f_inv hf g) (f x) = g x := f.lift_of_right_inverse_aux_comp_apply f_inv hf g.1 g.2 x @[simp, to_additive] lemma lift_of_right_inverse_comp (hf : function.right_inverse f_inv f) (g : {g : G₁ →* G₃ // f.ker ≤ g.ker}) : (f.lift_of_right_inverse f_inv hf g).comp f = g := monoid_hom.ext $ f.lift_of_right_inverse_comp_apply f_inv hf g @[to_additive] lemma eq_lift_of_right_inverse (hf : function.right_inverse f_inv f) (g : G₁ →* G₃) (hg : f.ker ≤ g.ker) (h : G₂ →* G₃) (hh : h.comp f = g) : h = (f.lift_of_right_inverse f_inv hf ⟨g, hg⟩) := begin simp_rw ←hh, exact ((f.lift_of_right_inverse f_inv hf).apply_symm_apply _).symm, end end monoid_hom variables {N : Type*} [group N] -- Here `H.normal` is an explicit argument so we can use dot notation with `comap`. @[to_additive] lemma subgroup.normal.comap {H : subgroup N} (hH : H.normal) (f : G →* N) : (H.comap f).normal := ⟨λ _, by simp [subgroup.mem_comap, hH.conj_mem] {contextual := tt}⟩ @[priority 100, to_additive] instance subgroup.normal_comap {H : subgroup N} [nH : H.normal] (f : G →* N) : (H.comap f).normal := nH.comap _ @[priority 100, to_additive] instance monoid_hom.normal_ker (f : G →* N) : f.ker.normal := by { rw [←f.comap_bot], apply_instance } @[priority 100, to_additive] instance subgroup.normal_inf (H N : subgroup G) [hN : N.normal] : ((H ⊓ N).comap H.subtype).normal := ⟨λ x hx g, begin simp only [subgroup.mem_inf, coe_subtype, subgroup.mem_comap] at hx, simp only [subgroup.coe_mul, subgroup.mem_inf, coe_subtype, subgroup.coe_inv, subgroup.mem_comap], exact ⟨H.mul_mem (H.mul_mem g.2 hx.1) (H.inv_mem g.2), hN.1 x hx.2 g⟩, end⟩ namespace subgroup /-- The subgroup generated by an element. -/ def zpowers (g : G) : subgroup G := subgroup.copy (zpowers_hom G g).range (set.range ((^) g : ℤ → G)) rfl @[simp] lemma mem_zpowers (g : G) : g ∈ zpowers g := ⟨1, zpow_one _⟩ lemma zpowers_eq_closure (g : G) : zpowers g = closure {g} := by { ext, exact mem_closure_singleton.symm } @[simp] lemma range_zpowers_hom (g : G) : (zpowers_hom G g).range = zpowers g := rfl lemma zpowers_subset {a : G} {K : subgroup G} (h : a ∈ K) : zpowers a ≤ K := λ x hx, match x, hx with _, ⟨i, rfl⟩ := K.zpow_mem h i end lemma mem_zpowers_iff {g h : G} : h ∈ zpowers g ↔ ∃ (k : ℤ), g ^ k = h := iff.rfl @[simp] lemma forall_zpowers {x : G} {p : zpowers x → Prop} : (∀ g, p g) ↔ ∀ m : ℤ, p ⟨x ^ m, m, rfl⟩ := set.forall_subtype_range_iff @[simp] lemma exists_zpowers {x : G} {p : zpowers x → Prop} : (∃ g, p g) ↔ ∃ m : ℤ, p ⟨x ^ m, m, rfl⟩ := set.exists_subtype_range_iff lemma forall_mem_zpowers {x : G} {p : G → Prop} : (∀ g ∈ zpowers x, p g) ↔ ∀ m : ℤ, p (x ^ m) := set.forall_range_iff lemma exists_mem_zpowers {x : G} {p : G → Prop} : (∃ g ∈ zpowers x, p g) ↔ ∃ m : ℤ, p (x ^ m) := set.exists_range_iff end subgroup namespace add_subgroup /-- The subgroup generated by an element. -/ def zmultiples (a : A) : add_subgroup A := add_subgroup.copy (zmultiples_hom A a).range (set.range ((• a) : ℤ → A)) rfl @[simp] lemma range_zmultiples_hom (a : A) : (zmultiples_hom A a).range = zmultiples a := rfl attribute [to_additive add_subgroup.zmultiples] subgroup.zpowers attribute [to_additive add_subgroup.mem_zmultiples] subgroup.mem_zpowers attribute [to_additive add_subgroup.zmultiples_eq_closure] subgroup.zpowers_eq_closure attribute [to_additive add_subgroup.range_zmultiples_hom] subgroup.range_zpowers_hom attribute [to_additive add_subgroup.zmultiples_subset] subgroup.zpowers_subset attribute [to_additive add_subgroup.mem_zmultiples_iff] subgroup.mem_zpowers_iff attribute [to_additive add_subgroup.forall_zmultiples] subgroup.forall_zpowers attribute [to_additive add_subgroup.forall_mem_zmultiples] subgroup.forall_mem_zpowers attribute [to_additive add_subgroup.exists_zmultiples] subgroup.exists_zpowers attribute [to_additive add_subgroup.exists_mem_zmultiples] subgroup.exists_mem_zpowers end add_subgroup lemma int.mem_zmultiples_iff {a b : ℤ} : b ∈ add_subgroup.zmultiples a ↔ a ∣ b := exists_congr (λ k, by rw [mul_comm, eq_comm, ← smul_eq_mul]) lemma of_mul_image_zpowers_eq_zmultiples_of_mul { x : G } : additive.of_mul '' ((subgroup.zpowers x) : set G) = add_subgroup.zmultiples (additive.of_mul x) := begin ext y, split, { rintro ⟨z, ⟨m, hm⟩, hz2⟩, use m, simp only, rwa [← of_mul_zpow, hm] }, { rintros ⟨n, hn⟩, refine ⟨x ^ n, ⟨n, rfl⟩, _⟩, rwa of_mul_zpow } end lemma of_add_image_zmultiples_eq_zpowers_of_add {x : A} : multiplicative.of_add '' ((add_subgroup.zmultiples x) : set A) = subgroup.zpowers (multiplicative.of_add x) := begin symmetry, rw equiv.eq_image_iff_symm_image_eq, exact of_mul_image_zpowers_eq_zmultiples_of_mul, end namespace subgroup @[to_additive zmultiples_is_commutative] instance zpowers_is_commutative (g : G) : (zpowers g).is_commutative := ⟨⟨λ ⟨_, _, h₁⟩ ⟨_, _, h₂⟩, by rw [subtype.ext_iff, coe_mul, coe_mul, subtype.coe_mk, subtype.coe_mk, ←h₁, ←h₂, zpow_mul_comm]⟩⟩ @[simp, to_additive zmultiples_le] lemma zpowers_le {g : G} {H : subgroup G} : zpowers g ≤ H ↔ g ∈ H := by rw [zpowers_eq_closure, closure_le, set.singleton_subset_iff, set_like.mem_coe] @[simp, to_additive zmultiples_eq_bot] lemma zpowers_eq_bot {g : G} : zpowers g = ⊥ ↔ g = 1 := by rw [eq_bot_iff, zpowers_le, mem_bot] @[simp, to_additive zmultiples_zero_eq_bot] lemma zpowers_one_eq_bot : subgroup.zpowers (1 : G) = ⊥ := subgroup.zpowers_eq_bot.mpr rfl @[to_additive] lemma centralizer_closure (S : set G) : (closure S).centralizer = ⨅ g ∈ S, (zpowers g).centralizer := le_antisymm (le_infi $ λ g, le_infi $ λ hg, centralizer_le $ zpowers_le.2 $ subset_closure hg) $ le_centralizer_iff.1 $ (closure_le _).2 $ λ g, set_like.mem_coe.2 ∘ zpowers_le.1 ∘ le_centralizer_iff.1 ∘ infi_le_of_le g ∘ infi_le _ end subgroup namespace monoid_hom variables {G' : Type*} [group G'] /-- The `monoid_hom` from the preimage of a subgroup to itself. -/ @[to_additive "the `add_monoid_hom` from the preimage of an additive subgroup to itself.", simps] def subgroup_comap (f : G →* G') (H' : subgroup G') : H'.comap f →* H' := f.submonoid_comap H'.to_submonoid /-- The `monoid_hom` from a subgroup to its image. -/ @[to_additive "the `add_monoid_hom` from an additive subgroup to its image", simps] def subgroup_map (f : G →* G') (H : subgroup G) : H →* H.map f := f.submonoid_map H.to_submonoid @[to_additive] lemma subgroup_map_surjective (f : G →* G') (H : subgroup G) : function.surjective (f.subgroup_map H) := f.submonoid_map_surjective H.to_submonoid end monoid_hom namespace mul_equiv variables {H K : subgroup G} /-- Makes the identity isomorphism from a proof two subgroups of a multiplicative group are equal. -/ @[to_additive "Makes the identity additive isomorphism from a proof two subgroups of an additive group are equal."] def subgroup_congr (h : H = K) : H ≃* K := { map_mul' := λ _ _, rfl, ..equiv.set_congr $ congr_arg _ h } /-- A `mul_equiv` `φ` between two groups `G` and `G'` induces a `mul_equiv` between a subgroup `H ≤ G` and the subgroup `φ(H) ≤ G'`. -/ @[to_additive "An `add_equiv` `φ` between two additive groups `G` and `G'` induces an `add_equiv` between a subgroup `H ≤ G` and the subgroup `φ(H) ≤ G'`. "] def subgroup_map {G'} [group G'] (e : G ≃* G') (H : subgroup G) : H ≃* H.map e.to_monoid_hom := e.submonoid_map H.to_submonoid end mul_equiv -- TODO : ↥(⊤ : subgroup H) ≃* H ? namespace subgroup variables {C : Type*} [comm_group C] {s t : subgroup C} {x : C} @[to_additive] lemma mem_sup : x ∈ s ⊔ t ↔ ∃ (y ∈ s) (z ∈ t), y * z = x := ⟨λ h, begin rw [← closure_eq s, ← closure_eq t, ← closure_union] at h, apply closure_induction h, { rintro y (h | h), { exact ⟨y, h, 1, t.one_mem, by simp⟩ }, { exact ⟨1, s.one_mem, y, h, by simp⟩ } }, { exact ⟨1, s.one_mem, 1, ⟨t.one_mem, mul_one 1⟩⟩ }, { rintro _ _ ⟨y₁, hy₁, z₁, hz₁, rfl⟩ ⟨y₂, hy₂, z₂, hz₂, rfl⟩, exact ⟨_, mul_mem hy₁ hy₂, _, mul_mem hz₁ hz₂, by simp [mul_assoc]; cc⟩ }, { rintro _ ⟨y, hy, z, hz, rfl⟩, exact ⟨_, inv_mem hy, _, inv_mem hz, mul_comm z y ▸ (mul_inv_rev z y).symm⟩ } end, by rintro ⟨y, hy, z, hz, rfl⟩; exact mul_mem_sup hy hz⟩ @[to_additive] lemma mem_sup' : x ∈ s ⊔ t ↔ ∃ (y : s) (z : t), (y:C) * z = x := mem_sup.trans $ by simp only [set_like.exists, coe_mk] @[to_additive] lemma mem_closure_pair {x y z : C} : z ∈ closure ({x, y} : set C) ↔ ∃ m n : ℤ, x ^ m * y ^ n = z := begin rw [←set.singleton_union, subgroup.closure_union, mem_sup], simp_rw [exists_prop, mem_closure_singleton, exists_exists_eq_and], end @[to_additive] instance : is_modular_lattice (subgroup C) := ⟨λ x y z xz a ha, begin rw [mem_inf, mem_sup] at ha, rcases ha with ⟨⟨b, hb, c, hc, rfl⟩, haz⟩, rw mem_sup, refine ⟨b, hb, c, mem_inf.2 ⟨hc, _⟩, rfl⟩, rw ← inv_mul_cancel_left b c, apply z.mul_mem (z.inv_mem (xz hb)) haz, end⟩ end subgroup section variables (G) (A) /-- A `group` is simple when it has exactly two normal `subgroup`s. -/ class is_simple_group extends nontrivial G : Prop := (eq_bot_or_eq_top_of_normal : ∀ H : subgroup G, H.normal → H = ⊥ ∨ H = ⊤) /-- An `add_group` is simple when it has exactly two normal `add_subgroup`s. -/ class is_simple_add_group extends nontrivial A : Prop := (eq_bot_or_eq_top_of_normal : ∀ H : add_subgroup A, H.normal → H = ⊥ ∨ H = ⊤) attribute [to_additive] is_simple_group variables {G} {A} @[to_additive] lemma subgroup.normal.eq_bot_or_eq_top [is_simple_group G] {H : subgroup G} (Hn : H.normal) : H = ⊥ ∨ H = ⊤ := is_simple_group.eq_bot_or_eq_top_of_normal H Hn namespace is_simple_group @[to_additive] instance {C : Type*} [comm_group C] [is_simple_group C] : is_simple_order (subgroup C) := ⟨λ H, H.normal_of_comm.eq_bot_or_eq_top⟩ open _root_.subgroup @[to_additive] lemma is_simple_group_of_surjective {H : Type*} [group H] [is_simple_group G] [nontrivial H] (f : G →* H) (hf : function.surjective f) : is_simple_group H := ⟨nontrivial.exists_pair_ne, λ H iH, begin refine ((iH.comap f).eq_bot_or_eq_top).imp (λ h, _) (λ h, _), { rw [←map_bot f, ←h, map_comap_eq_self_of_surjective hf] }, { rw [←comap_top f] at h, exact comap_injective hf h } end⟩ end is_simple_group end namespace subgroup section pointwise @[to_additive] lemma closure_mul_le (S T : set G) : closure (S * T) ≤ closure S ⊔ closure T := Inf_le $ λ x ⟨s, t, hs, ht, hx⟩, hx ▸ (closure S ⊔ closure T).mul_mem (set_like.le_def.mp le_sup_left $ subset_closure hs) (set_like.le_def.mp le_sup_right $ subset_closure ht) @[to_additive] lemma sup_eq_closure (H K : subgroup G) : H ⊔ K = closure (H * K) := le_antisymm (sup_le (λ h hh, subset_closure ⟨h, 1, hh, K.one_mem, mul_one h⟩) (λ k hk, subset_closure ⟨1, k, H.one_mem, hk, one_mul k⟩)) (by conv_rhs { rw [← closure_eq H, ← closure_eq K] }; apply closure_mul_le) @[to_additive] private def mul_normal_aux (H N : subgroup G) [hN : N.normal] : subgroup G := { carrier := (H : set G) * N, one_mem' := ⟨1, 1, H.one_mem, N.one_mem, by rw mul_one⟩, mul_mem' := λ a b ⟨h, n, hh, hn, ha⟩ ⟨h', n', hh', hn', hb⟩, ⟨h * h', h'⁻¹ * n * h' * n', H.mul_mem hh hh', N.mul_mem (by simpa using hN.conj_mem _ hn h'⁻¹) hn', by simp [← ha, ← hb, mul_assoc]⟩, inv_mem' := λ x ⟨h, n, hh, hn, hx⟩, ⟨h⁻¹, h * n⁻¹ * h⁻¹, H.inv_mem hh, hN.conj_mem _ (N.inv_mem hn) h, by rw [mul_assoc h, inv_mul_cancel_left, ← hx, mul_inv_rev]⟩ } /-- The carrier of `H ⊔ N` is just `↑H * ↑N` (pointwise set product) when `N` is normal. -/ @[to_additive "The carrier of `H ⊔ N` is just `↑H + ↑N` (pointwise set addition) when `N` is normal."] lemma mul_normal (H N : subgroup G) [N.normal] : (↑(H ⊔ N) : set G) = H * N := set.subset.antisymm (show H ⊔ N ≤ mul_normal_aux H N, by { rw sup_eq_closure, apply Inf_le _, dsimp, refl }) ((sup_eq_closure H N).symm ▸ subset_closure) @[to_additive] private def normal_mul_aux (N H : subgroup G) [hN : N.normal] : subgroup G := { carrier := (N : set G) * H, one_mem' := ⟨1, 1, N.one_mem, H.one_mem, by rw mul_one⟩, mul_mem' := λ a b ⟨n, h, hn, hh, ha⟩ ⟨n', h', hn', hh', hb⟩, ⟨n * (h * n' * h⁻¹), h * h', N.mul_mem hn (hN.conj_mem _ hn' _), H.mul_mem hh hh', by simp [← ha, ← hb, mul_assoc]⟩, inv_mem' := λ x ⟨n, h, hn, hh, hx⟩, ⟨h⁻¹ * n⁻¹ * h, h⁻¹, by simpa using hN.conj_mem _ (N.inv_mem hn) h⁻¹, H.inv_mem hh, by rw [mul_inv_cancel_right, ← mul_inv_rev, hx]⟩ } /-- The carrier of `N ⊔ H` is just `↑N * ↑H` (pointwise set product) when `N` is normal. -/ @[to_additive "The carrier of `N ⊔ H` is just `↑N + ↑H` (pointwise set addition) when `N` is normal."] lemma normal_mul (N H : subgroup G) [N.normal] : (↑(N ⊔ H) : set G) = N * H := set.subset.antisymm (show N ⊔ H ≤ normal_mul_aux N H, by { rw sup_eq_closure, apply Inf_le _, dsimp, refl }) ((sup_eq_closure N H).symm ▸ subset_closure) @[to_additive] lemma mul_inf_assoc (A B C : subgroup G) (h : A ≤ C) : (A : set G) * ↑(B ⊓ C) = (A * B) ⊓ C := begin ext, simp only [coe_inf, set.inf_eq_inter, set.mem_mul, set.mem_inter_iff], split, { rintros ⟨y, z, hy, ⟨hzB, hzC⟩, rfl⟩, refine ⟨_, mul_mem (h hy) hzC⟩, exact ⟨y, z, hy, hzB, rfl⟩ }, rintros ⟨⟨y, z, hy, hz, rfl⟩, hyz⟩, refine ⟨y, z, hy, ⟨hz, _⟩, rfl⟩, suffices : y⁻¹ * (y * z) ∈ C, { simpa }, exact mul_mem (inv_mem (h hy)) hyz end @[to_additive] lemma inf_mul_assoc (A B C : subgroup G) (h : C ≤ A) : ((A ⊓ B : subgroup G) : set G) * C = A ⊓ (B * C) := begin ext, simp only [coe_inf, set.inf_eq_inter, set.mem_mul, set.mem_inter_iff], split, { rintros ⟨y, z, ⟨hyA, hyB⟩, hz, rfl⟩, refine ⟨A.mul_mem hyA (h hz), _⟩, exact ⟨y, z, hyB, hz, rfl⟩ }, rintros ⟨hyz, y, z, hy, hz, rfl⟩, refine ⟨y, z, ⟨_, hy⟩, hz, rfl⟩, suffices : (y * z) * z⁻¹ ∈ A, { simpa }, exact mul_mem hyz (inv_mem (h hz)) end end pointwise section subgroup_normal @[to_additive] lemma normal_subgroup_of_iff {H K : subgroup G} (hHK : H ≤ K) : (H.subgroup_of K).normal ↔ ∀ h k, h ∈ H → k ∈ K → k * h * k⁻¹ ∈ H := ⟨λ hN h k hH hK, hN.conj_mem ⟨h, hHK hH⟩ hH ⟨k, hK⟩, λ hN, { conj_mem := λ h hm k, (hN h.1 k.1 hm k.2) }⟩ @[to_additive] instance prod_subgroup_of_prod_normal {H₁ K₁ : subgroup G} {H₂ K₂ : subgroup N} [h₁ : (H₁.subgroup_of K₁).normal] [h₂ : (H₂.subgroup_of K₂).normal] : ((H₁.prod H₂).subgroup_of (K₁.prod K₂)).normal := { conj_mem := λ n hgHK g, ⟨h₁.conj_mem ⟨(n : G × N).fst, (mem_prod.mp n.2).1⟩ hgHK.1 ⟨(g : G × N).fst, (mem_prod.mp g.2).1⟩, h₂.conj_mem ⟨(n : G × N).snd, (mem_prod.mp n.2).2⟩ hgHK.2 ⟨(g : G × N).snd, (mem_prod.mp g.2).2⟩⟩ } @[to_additive] instance prod_normal (H : subgroup G) (K : subgroup N) [hH : H.normal] [hK : K.normal] : (H.prod K).normal := { conj_mem := λ n hg g, ⟨hH.conj_mem n.fst (subgroup.mem_prod.mp hg).1 g.fst, hK.conj_mem n.snd (subgroup.mem_prod.mp hg).2 g.snd⟩ } @[to_additive] lemma inf_subgroup_of_inf_normal_of_right (A B' B : subgroup G) (hB : B' ≤ B) [hN : (B'.subgroup_of B).normal] : ((A ⊓ B').subgroup_of (A ⊓ B)).normal := { conj_mem := λ n hn g, ⟨mul_mem (mul_mem (mem_inf.1 g.2).1 (mem_inf.1 n.2).1) (inv_mem (mem_inf.1 g.2).1), (normal_subgroup_of_iff hB).mp hN n g hn.2 (mem_inf.mp g.2).2⟩ } @[to_additive] lemma inf_subgroup_of_inf_normal_of_left {A' A : subgroup G} (B : subgroup G) (hA : A' ≤ A) [hN : (A'.subgroup_of A).normal] : ((A' ⊓ B).subgroup_of (A ⊓ B)).normal := { conj_mem := λ n hn g, ⟨(normal_subgroup_of_iff hA).mp hN n g hn.1 (mem_inf.mp g.2).1, mul_mem (mul_mem (mem_inf.1 g.2).2 (mem_inf.1 n.2).2) (inv_mem (mem_inf.1 g.2).2)⟩ } instance sup_normal (H K : subgroup G) [hH : H.normal] [hK : K.normal] : (H ⊔ K).normal := { conj_mem := λ n hmem g, begin change n ∈ ↑(H ⊔ K) at hmem, change g * n * g⁻¹ ∈ ↑(H ⊔ K), rw [normal_mul, set.mem_mul] at *, rcases hmem with ⟨h, k, hh, hk, rfl⟩, refine ⟨g * h * g⁻¹, g * k * g⁻¹, hH.conj_mem h hh g, hK.conj_mem k hk g, _⟩, simp end } @[to_additive] instance normal_inf_normal (H K : subgroup G) [hH : H.normal] [hK : K.normal] : (H ⊓ K).normal := { conj_mem := λ n hmem g, by { rw mem_inf at *, exact ⟨hH.conj_mem n hmem.1 g, hK.conj_mem n hmem.2 g⟩ } } @[to_additive] lemma subgroup_of_sup (A A' B : subgroup G) (hA : A ≤ B) (hA' : A' ≤ B) : (A ⊔ A').subgroup_of B = A.subgroup_of B ⊔ A'.subgroup_of B := begin refine map_injective_of_ker_le B.subtype (ker_le_comap _ _) (le_trans (ker_le_comap B.subtype _) le_sup_left) _, { simp only [subgroup_of, map_comap_eq, map_sup, subtype_range], rw [inf_of_le_right (sup_le hA hA'), inf_of_le_right hA', inf_of_le_right hA] }, end @[to_additive] lemma subgroup_normal.mem_comm {H K : subgroup G} (hK : H ≤ K) [hN : (H.subgroup_of K).normal] {a b : G} (hb : b ∈ K) (h : a * b ∈ H) : b * a ∈ H := begin have := (normal_subgroup_of_iff hK).mp hN (a * b) b h hb, rwa [mul_assoc, mul_assoc, mul_right_inv, mul_one] at this, end /-- Elements of disjoint, normal subgroups commute. -/ @[to_additive "Elements of disjoint, normal subgroups commute."] lemma commute_of_normal_of_disjoint (H₁ H₂ : subgroup G) (hH₁ : H₁.normal) (hH₂ : H₂.normal) (hdis : disjoint H₁ H₂) (x y : G) (hx : x ∈ H₁) (hy : y ∈ H₂) : commute x y := begin suffices : x * y * x⁻¹ * y⁻¹ = 1, { show x * y = y * x, by { rw [mul_assoc, mul_eq_one_iff_eq_inv] at this, simpa } }, apply hdis, split, { suffices : x * (y * x⁻¹ * y⁻¹) ∈ H₁, by simpa [mul_assoc], exact H₁.mul_mem hx (hH₁.conj_mem _ (H₁.inv_mem hx) _) }, { show x * y * x⁻¹ * y⁻¹ ∈ H₂, apply H₂.mul_mem _ (H₂.inv_mem hy), apply (hH₂.conj_mem _ hy), } end end subgroup_normal @[to_additive] lemma disjoint_def {H₁ H₂ : subgroup G} : disjoint H₁ H₂ ↔ ∀ {x : G}, x ∈ H₁ → x ∈ H₂ → x = 1 := show (∀ x, x ∈ H₁ ∧ x ∈ H₂ → x ∈ ({1} : set G)) ↔ _, by simp @[to_additive] lemma disjoint_def' {H₁ H₂ : subgroup G} : disjoint H₁ H₂ ↔ ∀ {x y : G}, x ∈ H₁ → y ∈ H₂ → x = y → x = 1 := disjoint_def.trans ⟨λ h x y hx hy hxy, h hx $ hxy.symm ▸ hy, λ h x hx hx', h hx hx' rfl⟩ @[to_additive] lemma disjoint_iff_mul_eq_one {H₁ H₂ : subgroup G} : disjoint H₁ H₂ ↔ ∀ {x y : G}, x ∈ H₁ → y ∈ H₂ → x * y = 1 → x = 1 ∧ y = 1 := disjoint_def'.trans ⟨λ h x y hx hy hxy, let hx1 : x = 1 := h hx (H₂.inv_mem hy) (eq_inv_iff_mul_eq_one.mpr hxy) in ⟨hx1, by simpa [hx1] using hxy⟩, λ h x y hx hy hxy, (h hx (H₂.inv_mem hy) (mul_inv_eq_one.mpr hxy)).1 ⟩ /-- `finset.noncomm_prod` is “injective” in `f` if `f` maps into independent subgroups. This generalizes (one direction of) `subgroup.disjoint_iff_mul_eq_one`. -/ @[to_additive "`finset.noncomm_sum` is “injective” in `f` if `f` maps into independent subgroups. This generalizes (one direction of) `add_subgroup.disjoint_iff_add_eq_zero`. "] lemma eq_one_of_noncomm_prod_eq_one_of_independent {ι : Type*} (s : finset ι) (f : ι → G) (comm : ∀ (x ∈ s) (y ∈ s), commute (f x) (f y)) (K : ι → subgroup G) (hind : complete_lattice.independent K) (hmem : ∀ (x ∈ s), f x ∈ K x) (heq1 : s.noncomm_prod f comm = 1) : ∀ (i ∈ s), f i = 1 := begin classical, revert heq1, induction s using finset.induction_on with i s hnmem ih, { simp, }, { simp only [finset.forall_mem_insert] at comm hmem, specialize ih (λ x hx, (comm.2 x hx).2) hmem.2, have hmem_bsupr: s.noncomm_prod f (λ x hx, (comm.2 x hx).2) ∈ ⨆ (i ∈ (s : set ι)), K i, { refine subgroup.noncomm_prod_mem _ _ _, intros x hx, have : K x ≤ ⨆ (i ∈ (s : set ι)), K i := le_supr₂ x hx, exact this (hmem.2 x hx), }, intro heq1, rw finset.noncomm_prod_insert_of_not_mem _ _ _ _ hnmem at heq1, have hnmem' : i ∉ (s : set ι), by simpa, obtain ⟨heq1i : f i = 1, heq1S : s.noncomm_prod f _ = 1⟩ := subgroup.disjoint_iff_mul_eq_one.mp (hind.disjoint_bsupr hnmem') hmem.1 hmem_bsupr heq1, specialize ih heq1S, intros i h, simp only [finset.mem_insert] at h, rcases h with ⟨rfl | _⟩, { exact heq1i }, { exact (ih _ h), } } end end subgroup namespace is_conj open subgroup lemma normal_closure_eq_top_of {N : subgroup G} [hn : N.normal] {g g' : G} {hg : g ∈ N} {hg' : g' ∈ N} (hc : is_conj g g') (ht : normal_closure ({⟨g, hg⟩} : set N) = ⊤) : normal_closure ({⟨g', hg'⟩} : set N) = ⊤ := begin obtain ⟨c, rfl⟩ := is_conj_iff.1 hc, have h : ∀ x : N, (mul_aut.conj c) x ∈ N, { rintro ⟨x, hx⟩, exact hn.conj_mem _ hx c }, have hs : function.surjective (((mul_aut.conj c).to_monoid_hom.restrict N).cod_restrict _ h), { rintro ⟨x, hx⟩, refine ⟨⟨c⁻¹ * x * c, _⟩, _⟩, { have h := hn.conj_mem _ hx c⁻¹, rwa [inv_inv] at h }, simp only [monoid_hom.cod_restrict_apply, mul_equiv.coe_to_monoid_hom, mul_aut.conj_apply, coe_mk, monoid_hom.restrict_apply, subtype.mk_eq_mk, ← mul_assoc, mul_inv_self, one_mul], rw [mul_assoc, mul_inv_self, mul_one] }, have ht' := map_mono (eq_top_iff.1 ht), rw [← monoid_hom.range_eq_map, monoid_hom.range_top_of_surjective _ hs] at ht', refine eq_top_iff.2 (le_trans ht' (map_le_iff_le_comap.2 (normal_closure_le_normal _))), rw [set.singleton_subset_iff, set_like.mem_coe], simp only [monoid_hom.cod_restrict_apply, mul_equiv.coe_to_monoid_hom, mul_aut.conj_apply, coe_mk, monoid_hom.restrict_apply, mem_comap], exact subset_normal_closure (set.mem_singleton _), end end is_conj /-! ### Actions by `subgroup`s These are just copies of the definitions about `submonoid` starting from `submonoid.mul_action`. -/ section actions namespace subgroup variables {α β : Type*} /-- The action by a subgroup is the action by the underlying group. -/ @[to_additive /-"The additive action by an add_subgroup is the action by the underlying add_group. "-/] instance [mul_action G α] (S : subgroup G) : mul_action S α := S.to_submonoid.mul_action @[to_additive] lemma smul_def [mul_action G α] {S : subgroup G} (g : S) (m : α) : g • m = (g : G) • m := rfl @[to_additive] instance smul_comm_class_left [mul_action G β] [has_smul α β] [smul_comm_class G α β] (S : subgroup G) : smul_comm_class S α β := S.to_submonoid.smul_comm_class_left @[to_additive] instance smul_comm_class_right [has_smul α β] [mul_action G β] [smul_comm_class α G β] (S : subgroup G) : smul_comm_class α S β := S.to_submonoid.smul_comm_class_right /-- Note that this provides `is_scalar_tower S G G` which is needed by `smul_mul_assoc`. -/ instance [has_smul α β] [mul_action G α] [mul_action G β] [is_scalar_tower G α β] (S : subgroup G) : is_scalar_tower S α β := S.to_submonoid.is_scalar_tower instance [mul_action G α] [has_faithful_smul G α] (S : subgroup G) : has_faithful_smul S α := S.to_submonoid.has_faithful_smul /-- The action by a subgroup is the action by the underlying group. -/ instance [add_monoid α] [distrib_mul_action G α] (S : subgroup G) : distrib_mul_action S α := S.to_submonoid.distrib_mul_action /-- The action by a subgroup is the action by the underlying group. -/ instance [monoid α] [mul_distrib_mul_action G α] (S : subgroup G) : mul_distrib_mul_action S α := S.to_submonoid.mul_distrib_mul_action /-- The center of a group acts commutatively on that group. -/ instance center.smul_comm_class_left : smul_comm_class (center G) G G := submonoid.center.smul_comm_class_left /-- The center of a group acts commutatively on that group. -/ instance center.smul_comm_class_right : smul_comm_class G (center G) G := submonoid.center.smul_comm_class_right end subgroup end actions /-! ### Mul-opposite subgroups -/ section mul_opposite namespace subgroup /-- A subgroup `H` of `G` determines a subgroup `H.opposite` of the opposite group `Gᵐᵒᵖ`. -/ @[to_additive "An additive subgroup `H` of `G` determines an additive subgroup `H.opposite` of the opposite additive group `Gᵃᵒᵖ`."] def opposite : subgroup G ≃ subgroup Gᵐᵒᵖ := { to_fun := λ H, { carrier := mul_opposite.unop ⁻¹' (H : set G), one_mem' := H.one_mem, mul_mem' := λ a b ha hb, H.mul_mem hb ha, inv_mem' := λ a, H.inv_mem }, inv_fun := λ H, { carrier := mul_opposite.op ⁻¹' (H : set Gᵐᵒᵖ), one_mem' := H.one_mem, mul_mem' := λ a b ha hb, H.mul_mem hb ha, inv_mem' := λ a, H.inv_mem }, left_inv := λ H, set_like.coe_injective rfl, right_inv := λ H, set_like.coe_injective rfl } /-- Bijection between a subgroup `H` and its opposite. -/ @[to_additive "Bijection between an additive subgroup `H` and its opposite.", simps] def opposite_equiv (H : subgroup G) : H ≃ H.opposite := mul_opposite.op_equiv.subtype_equiv $ λ _, iff.rfl @[to_additive] instance (H : subgroup G) [encodable H] : encodable H.opposite := encodable.of_equiv H H.opposite_equiv.symm @[to_additive] instance (H : subgroup G) [countable H] : countable H.opposite := countable.of_equiv H H.opposite_equiv @[to_additive] lemma smul_opposite_mul {H : subgroup G} (x g : G) (h : H.opposite) : h • (g * x) = g * (h • x) := begin cases h, simp [(•), mul_assoc], end @[to_additive] lemma smul_opposite_image_mul_preimage {H : subgroup G} (g : G) (h : H.opposite) (s : set G) : (λ y, h • y) '' (has_mul.mul g ⁻¹' s) = has_mul.mul g ⁻¹' ((λ y, h • y) '' s) := by { ext x, cases h, simp [(•), mul_assoc] } end subgroup end mul_opposite /-! ### Saturated subgroups -/ section saturated namespace subgroup /-- A subgroup `H` of `G` is *saturated* if for all `n : ℕ` and `g : G` with `g^n ∈ H` we have `n = 0` or `g ∈ H`. -/ @[to_additive "An additive subgroup `H` of `G` is *saturated* if for all `n : ℕ` and `g : G` with `n•g ∈ H` we have `n = 0` or `g ∈ H`."] def saturated (H : subgroup G) : Prop := ∀ ⦃n g⦄, g ^ n ∈ H → n = 0 ∨ g ∈ H @[to_additive] lemma saturated_iff_npow {H : subgroup G} : saturated H ↔ (∀ (n : ℕ) (g : G), g ^ n ∈ H → n = 0 ∨ g ∈ H) := iff.rfl @[to_additive] lemma saturated_iff_zpow {H : subgroup G} : saturated H ↔ (∀ (n : ℤ) (g : G), g ^ n ∈ H → n = 0 ∨ g ∈ H) := begin split, { rintros hH ⟨n⟩ g hgn, { simp only [int.coe_nat_eq_zero, int.of_nat_eq_coe, zpow_coe_nat] at hgn ⊢, exact hH hgn }, { suffices : g ^ (n+1) ∈ H, { refine (hH this).imp _ id, simp only [is_empty.forall_iff, nat.succ_ne_zero], }, simpa only [inv_mem_iff, zpow_neg_succ_of_nat] using hgn, } }, { intros h n g hgn, specialize h n g, simp only [int.coe_nat_eq_zero, zpow_coe_nat] at h, apply h hgn } end end subgroup namespace add_subgroup lemma ker_saturated {A₁ A₂ : Type*} [add_comm_group A₁] [add_comm_group A₂] [no_zero_smul_divisors ℕ A₂] (f : A₁ →+ A₂) : (f.ker).saturated := begin intros n g hg, simpa only [f.mem_ker, nsmul_eq_smul, f.map_nsmul, smul_eq_zero] using hg end end add_subgroup end saturated
6f737c0ea13a635f77e71fde8ad3bd1a910d367e
3dc4623269159d02a444fe898d33e8c7e7e9461b
/.github/workflows/project_1_a_decrire/foncteur/foncteur_affine_line/foncteur_droite_affine.lean
dd6804db4bfcd626da2588ef8f970d9012dd143e
[]
no_license
Or7ando/lean
cc003e6c41048eae7c34aa6bada51c9e9add9e66
d41169cf4e416a0d42092fb6bdc14131cee9dd15
refs/heads/master
1,650,600,589,722
1,587,262,906,000
1,587,262,906,000
255,387,160
0
0
null
null
null
null
UTF-8
Lean
false
false
1,034
lean
import category_theory.functor_category -- this transitively imports import algebra.category.CommRing.basic import algebra.ring open CommRing open is_ring_hom open nat universes v u -- the order matters (see below) /-- ## Category of Commutative Ring : Functor A. ## Define a functor. We first define two functions : ## 1. obj' ## 2. map' ## construction ! --/ lemma power_commute_with_morph (A B : CommRing)(f : A ⟶ B)(n : ℕ) : ∀ x : A, f( x^n ) = (f x)^n := λ x, nat.rec_on n (show f(x^0) = (f x)^0, {rw [pow_zero x,pow_zero (f x)], exact map_one f,}) (assume n, assume rec_hyp : f(x^n) = (f(x))^n, show f(x^(n+1)) = (f(x))^(n+1),{rw [pow_succ x n,pow_succ (f(x)) n,← rec_hyp],exact map_mul (f)}) def A_obj' (R : CommRing) : Type v := R def A_map' (X Y : CommRing)( f : ring_hom X Y) :A_obj' X → A_obj' Y := begin intros x, use f x, end def A : CommRing ⥤ Type v := { obj := A_obj', map := A_map', } #print A
c5854e984871f321a0d2482df4104e94c5bd71d5
592ee40978ac7604005a4e0d35bbc4b467389241
/Library/generated/mathscheme-lean/Ringoid.lean
f5864fb65a28920113852224e78125f5437a1e4e
[]
no_license
ysharoda/Deriving-Definitions
3e149e6641fae440badd35ac110a0bd705a49ad2
dfecb27572022de3d4aa702cae8db19957523a59
refs/heads/master
1,679,127,857,700
1,615,939,007,000
1,615,939,007,000
229,785,731
4
0
null
null
null
null
UTF-8
Lean
false
false
8,700
lean
import init.data.nat.basic import init.data.fin.basic import data.vector import .Prelude open Staged open nat open fin open vector section Ringoid structure Ringoid (A : Type) : Type := (times : (A → (A → A))) (plus : (A → (A → A))) (leftDistributive_times_plus : (∀ {x y z : A} , (times x (plus y z)) = (plus (times x y) (times x z)))) (rightDistributive_times_plus : (∀ {x y z : A} , (times (plus y z) x) = (plus (times y x) (times z x)))) open Ringoid structure Sig (AS : Type) : Type := (timesS : (AS → (AS → AS))) (plusS : (AS → (AS → AS))) structure Product (A : Type) : Type := (timesP : ((Prod A A) → ((Prod A A) → (Prod A A)))) (plusP : ((Prod A A) → ((Prod A A) → (Prod A A)))) (leftDistributive_times_plusP : (∀ {xP yP zP : (Prod A A)} , (timesP xP (plusP yP zP)) = (plusP (timesP xP yP) (timesP xP zP)))) (rightDistributive_times_plusP : (∀ {xP yP zP : (Prod A A)} , (timesP (plusP yP zP) xP) = (plusP (timesP yP xP) (timesP zP xP)))) structure Hom {A1 : Type} {A2 : Type} (Ri1 : (Ringoid A1)) (Ri2 : (Ringoid A2)) : Type := (hom : (A1 → A2)) (pres_times : (∀ {x1 x2 : A1} , (hom ((times Ri1) x1 x2)) = ((times Ri2) (hom x1) (hom x2)))) (pres_plus : (∀ {x1 x2 : A1} , (hom ((plus Ri1) x1 x2)) = ((plus Ri2) (hom x1) (hom x2)))) structure RelInterp {A1 : Type} {A2 : Type} (Ri1 : (Ringoid A1)) (Ri2 : (Ringoid A2)) : Type 1 := (interp : (A1 → (A2 → Type))) (interp_times : (∀ {x1 x2 : A1} {y1 y2 : A2} , ((interp x1 y1) → ((interp x2 y2) → (interp ((times Ri1) x1 x2) ((times Ri2) y1 y2)))))) (interp_plus : (∀ {x1 x2 : A1} {y1 y2 : A2} , ((interp x1 y1) → ((interp x2 y2) → (interp ((plus Ri1) x1 x2) ((plus Ri2) y1 y2)))))) inductive RingoidTerm : Type | timesL : (RingoidTerm → (RingoidTerm → RingoidTerm)) | plusL : (RingoidTerm → (RingoidTerm → RingoidTerm)) open RingoidTerm inductive ClRingoidTerm (A : Type) : Type | sing : (A → ClRingoidTerm) | timesCl : (ClRingoidTerm → (ClRingoidTerm → ClRingoidTerm)) | plusCl : (ClRingoidTerm → (ClRingoidTerm → ClRingoidTerm)) open ClRingoidTerm inductive OpRingoidTerm (n : ℕ) : Type | v : ((fin n) → OpRingoidTerm) | timesOL : (OpRingoidTerm → (OpRingoidTerm → OpRingoidTerm)) | plusOL : (OpRingoidTerm → (OpRingoidTerm → OpRingoidTerm)) open OpRingoidTerm inductive OpRingoidTerm2 (n : ℕ) (A : Type) : Type | v2 : ((fin n) → OpRingoidTerm2) | sing2 : (A → OpRingoidTerm2) | timesOL2 : (OpRingoidTerm2 → (OpRingoidTerm2 → OpRingoidTerm2)) | plusOL2 : (OpRingoidTerm2 → (OpRingoidTerm2 → OpRingoidTerm2)) open OpRingoidTerm2 def simplifyCl {A : Type} : ((ClRingoidTerm A) → (ClRingoidTerm A)) | (timesCl x1 x2) := (timesCl (simplifyCl x1) (simplifyCl x2)) | (plusCl x1 x2) := (plusCl (simplifyCl x1) (simplifyCl x2)) | (sing x1) := (sing x1) def simplifyOpB {n : ℕ} : ((OpRingoidTerm n) → (OpRingoidTerm n)) | (timesOL x1 x2) := (timesOL (simplifyOpB x1) (simplifyOpB x2)) | (plusOL x1 x2) := (plusOL (simplifyOpB x1) (simplifyOpB x2)) | (v x1) := (v x1) def simplifyOp {n : ℕ} {A : Type} : ((OpRingoidTerm2 n A) → (OpRingoidTerm2 n A)) | (timesOL2 x1 x2) := (timesOL2 (simplifyOp x1) (simplifyOp x2)) | (plusOL2 x1 x2) := (plusOL2 (simplifyOp x1) (simplifyOp x2)) | (v2 x1) := (v2 x1) | (sing2 x1) := (sing2 x1) def evalB {A : Type} : ((Ringoid A) → (RingoidTerm → A)) | Ri (timesL x1 x2) := ((times Ri) (evalB Ri x1) (evalB Ri x2)) | Ri (plusL x1 x2) := ((plus Ri) (evalB Ri x1) (evalB Ri x2)) def evalCl {A : Type} : ((Ringoid A) → ((ClRingoidTerm A) → A)) | Ri (sing x1) := x1 | Ri (timesCl x1 x2) := ((times Ri) (evalCl Ri x1) (evalCl Ri x2)) | Ri (plusCl x1 x2) := ((plus Ri) (evalCl Ri x1) (evalCl Ri x2)) def evalOpB {A : Type} {n : ℕ} : ((Ringoid A) → ((vector A n) → ((OpRingoidTerm n) → A))) | Ri vars (v x1) := (nth vars x1) | Ri vars (timesOL x1 x2) := ((times Ri) (evalOpB Ri vars x1) (evalOpB Ri vars x2)) | Ri vars (plusOL x1 x2) := ((plus Ri) (evalOpB Ri vars x1) (evalOpB Ri vars x2)) def evalOp {A : Type} {n : ℕ} : ((Ringoid A) → ((vector A n) → ((OpRingoidTerm2 n A) → A))) | Ri vars (v2 x1) := (nth vars x1) | Ri vars (sing2 x1) := x1 | Ri vars (timesOL2 x1 x2) := ((times Ri) (evalOp Ri vars x1) (evalOp Ri vars x2)) | Ri vars (plusOL2 x1 x2) := ((plus Ri) (evalOp Ri vars x1) (evalOp Ri vars x2)) def inductionB {P : (RingoidTerm → Type)} : ((∀ (x1 x2 : RingoidTerm) , ((P x1) → ((P x2) → (P (timesL x1 x2))))) → ((∀ (x1 x2 : RingoidTerm) , ((P x1) → ((P x2) → (P (plusL x1 x2))))) → (∀ (x : RingoidTerm) , (P x)))) | ptimesl pplusl (timesL x1 x2) := (ptimesl _ _ (inductionB ptimesl pplusl x1) (inductionB ptimesl pplusl x2)) | ptimesl pplusl (plusL x1 x2) := (pplusl _ _ (inductionB ptimesl pplusl x1) (inductionB ptimesl pplusl x2)) def inductionCl {A : Type} {P : ((ClRingoidTerm A) → Type)} : ((∀ (x1 : A) , (P (sing x1))) → ((∀ (x1 x2 : (ClRingoidTerm A)) , ((P x1) → ((P x2) → (P (timesCl x1 x2))))) → ((∀ (x1 x2 : (ClRingoidTerm A)) , ((P x1) → ((P x2) → (P (plusCl x1 x2))))) → (∀ (x : (ClRingoidTerm A)) , (P x))))) | psing ptimescl ppluscl (sing x1) := (psing x1) | psing ptimescl ppluscl (timesCl x1 x2) := (ptimescl _ _ (inductionCl psing ptimescl ppluscl x1) (inductionCl psing ptimescl ppluscl x2)) | psing ptimescl ppluscl (plusCl x1 x2) := (ppluscl _ _ (inductionCl psing ptimescl ppluscl x1) (inductionCl psing ptimescl ppluscl x2)) def inductionOpB {n : ℕ} {P : ((OpRingoidTerm n) → Type)} : ((∀ (fin : (fin n)) , (P (v fin))) → ((∀ (x1 x2 : (OpRingoidTerm n)) , ((P x1) → ((P x2) → (P (timesOL x1 x2))))) → ((∀ (x1 x2 : (OpRingoidTerm n)) , ((P x1) → ((P x2) → (P (plusOL x1 x2))))) → (∀ (x : (OpRingoidTerm n)) , (P x))))) | pv ptimesol pplusol (v x1) := (pv x1) | pv ptimesol pplusol (timesOL x1 x2) := (ptimesol _ _ (inductionOpB pv ptimesol pplusol x1) (inductionOpB pv ptimesol pplusol x2)) | pv ptimesol pplusol (plusOL x1 x2) := (pplusol _ _ (inductionOpB pv ptimesol pplusol x1) (inductionOpB pv ptimesol pplusol x2)) def inductionOp {n : ℕ} {A : Type} {P : ((OpRingoidTerm2 n A) → Type)} : ((∀ (fin : (fin n)) , (P (v2 fin))) → ((∀ (x1 : A) , (P (sing2 x1))) → ((∀ (x1 x2 : (OpRingoidTerm2 n A)) , ((P x1) → ((P x2) → (P (timesOL2 x1 x2))))) → ((∀ (x1 x2 : (OpRingoidTerm2 n A)) , ((P x1) → ((P x2) → (P (plusOL2 x1 x2))))) → (∀ (x : (OpRingoidTerm2 n A)) , (P x)))))) | pv2 psing2 ptimesol2 pplusol2 (v2 x1) := (pv2 x1) | pv2 psing2 ptimesol2 pplusol2 (sing2 x1) := (psing2 x1) | pv2 psing2 ptimesol2 pplusol2 (timesOL2 x1 x2) := (ptimesol2 _ _ (inductionOp pv2 psing2 ptimesol2 pplusol2 x1) (inductionOp pv2 psing2 ptimesol2 pplusol2 x2)) | pv2 psing2 ptimesol2 pplusol2 (plusOL2 x1 x2) := (pplusol2 _ _ (inductionOp pv2 psing2 ptimesol2 pplusol2 x1) (inductionOp pv2 psing2 ptimesol2 pplusol2 x2)) def stageB : (RingoidTerm → (Staged RingoidTerm)) | (timesL x1 x2) := (stage2 timesL (codeLift2 timesL) (stageB x1) (stageB x2)) | (plusL x1 x2) := (stage2 plusL (codeLift2 plusL) (stageB x1) (stageB x2)) def stageCl {A : Type} : ((ClRingoidTerm A) → (Staged (ClRingoidTerm A))) | (sing x1) := (Now (sing x1)) | (timesCl x1 x2) := (stage2 timesCl (codeLift2 timesCl) (stageCl x1) (stageCl x2)) | (plusCl x1 x2) := (stage2 plusCl (codeLift2 plusCl) (stageCl x1) (stageCl x2)) def stageOpB {n : ℕ} : ((OpRingoidTerm n) → (Staged (OpRingoidTerm n))) | (v x1) := (const (code (v x1))) | (timesOL x1 x2) := (stage2 timesOL (codeLift2 timesOL) (stageOpB x1) (stageOpB x2)) | (plusOL x1 x2) := (stage2 plusOL (codeLift2 plusOL) (stageOpB x1) (stageOpB x2)) def stageOp {n : ℕ} {A : Type} : ((OpRingoidTerm2 n A) → (Staged (OpRingoidTerm2 n A))) | (sing2 x1) := (Now (sing2 x1)) | (v2 x1) := (const (code (v2 x1))) | (timesOL2 x1 x2) := (stage2 timesOL2 (codeLift2 timesOL2) (stageOp x1) (stageOp x2)) | (plusOL2 x1 x2) := (stage2 plusOL2 (codeLift2 plusOL2) (stageOp x1) (stageOp x2)) structure StagedRepr (A : Type) (Repr : (Type → Type)) : Type := (timesT : ((Repr A) → ((Repr A) → (Repr A)))) (plusT : ((Repr A) → ((Repr A) → (Repr A)))) end Ringoid
4f671978ca826208e5d467563a5dd156f7e01e80
cf39355caa609c0f33405126beee2739aa3cb77e
/library/init/data/sigma/default.lean
d8a28c1786933ec4263af02f4fd9b9cd668807ea
[ "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
221
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.data.sigma.basic init.data.sigma.lex
283801831ba6df6c7a4c952f94388ff4d67244c8
367134ba5a65885e863bdc4507601606690974c1
/src/category_theory/filtered.lean
f25d8c8dc7cfd71b62de0a2df01f64e5cd36dde3
[ "Apache-2.0" ]
permissive
kodyvajjha/mathlib
9bead00e90f68269a313f45f5561766cfd8d5cad
b98af5dd79e13a38d84438b850a2e8858ec21284
refs/heads/master
1,624,350,366,310
1,615,563,062,000
1,615,563,062,000
162,666,963
0
0
Apache-2.0
1,545,367,651,000
1,545,367,651,000
null
UTF-8
Lean
false
false
9,840
lean
/- Copyright (c) 2019 Reid Barton. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Reid Barton -/ import category_theory.fin_category import category_theory.limits.cones import category_theory.adjunction.basic import order.bounded_lattice /-! # Filtered categories A category is filtered if every finite diagram admits a cocone. We give a simple characterisation of this condition as 1. for every pair of objects there exists another object "to the right", 2. for every pair of parallel morphisms there exists a morphism to the right so the compositions are equal, and 3. there exists some object. Filtered colimits are often better behaved than arbitrary colimits. See `category_theory/limits/types` for some details. Filtered categories are nice because colimits indexed by filtered categories tend to be easier to describe than general colimits (and often often preserved by functors). In this file we show that any functor from a finite category to a filtered category admits a cocone: * `cocone_nonempty [fin_category J] [is_filtered C] (F : J ⥤ C) : nonempty (cocone F)` More generally, for any finite collection of objects and morphisms between them in a filtered category (even if not closed under composition) there exists some object `Z` receiving maps from all of them, so that all the triangles (one edge from the finite set, two from morphisms to `Z`) commute. This formulation is often more useful in practice. We give two variants, `sup_exists'`, which takes a single finset of objects, and a finset of morphisms (bundled with their sources and targets), and `sup_exists`, which takes a finset of objects, and an indexed family (indexed by source and target) of finsets of morphisms. ## Future work * Finite limits commute with filtered colimits * Forgetful functors for algebraic categories typically preserve filtered colimits. -/ universes v v₁ u u₁-- declare the `v`'s first; see `category_theory.category` for an explanation namespace category_theory variables (C : Type u) [category.{v} C] /-- A category `is_filtered_or_empty` if 1. for every pair of objects there exists another object "to the right", and 2. for every pair of parallel morphisms there exists a morphism to the right so the compositions are equal. -/ class is_filtered_or_empty : Prop := (cocone_objs : ∀ (X Y : C), ∃ Z (f : X ⟶ Z) (g : Y ⟶ Z), true) (cocone_maps : ∀ ⦃X Y : C⦄ (f g : X ⟶ Y), ∃ Z (h : Y ⟶ Z), f ≫ h = g ≫ h) /-- A category `is_filtered` if 1. for every pair of objects there exists another object "to the right", 2. for every pair of parallel morphisms there exists a morphism to the right so the compositions are equal, and 3. there exists some object. See https://stacks.math.columbia.edu/tag/002V. (They also define a diagram being filtered.) -/ class is_filtered extends is_filtered_or_empty C : Prop := [nonempty : nonempty C] @[priority 100] instance is_filtered_or_empty_of_semilattice_sup (α : Type u) [semilattice_sup α] : is_filtered_or_empty α := { cocone_objs := λ X Y, ⟨X ⊔ Y, hom_of_le le_sup_left, hom_of_le le_sup_right, trivial⟩, cocone_maps := λ X Y f g, ⟨Y, 𝟙 _, (by ext)⟩, } @[priority 100] instance is_filtered_of_semilattice_sup_top (α : Type u) [semilattice_sup_top α] : is_filtered α := { nonempty := ⟨⊤⟩, ..category_theory.is_filtered_or_empty_of_semilattice_sup α } namespace is_filtered variables {C} [is_filtered C] /-- `max j j'` is an arbitrary choice of object to the right of both `j` and `j'`, whose existence is ensured by `is_filtered`. -/ noncomputable def max (j j' : C) : C := (is_filtered_or_empty.cocone_objs j j').some /-- `left_to_max j j'` is an arbitrarily choice of morphism from `j` to `max j j'`, whose existence is ensured by `is_filtered`. -/ noncomputable def left_to_max (j j' : C) : j ⟶ max j j' := (is_filtered_or_empty.cocone_objs j j').some_spec.some /-- `right_to_max j j'` is an arbitrarily choice of morphism from `j'` to `max j j'`, whose existence is ensured by `is_filtered`. -/ noncomputable def right_to_max (j j' : C) : j' ⟶ max j j' := (is_filtered_or_empty.cocone_objs j j').some_spec.some_spec.some /-- `coeq f f'`, for morphisms `f f' : j ⟶ j'`, is an arbitrary choice of object which admits a morphism `coeq_hom f f' : j' ⟶ coeq f f'` such that `coeq_condition : f ≫ coeq_hom f f' = f' ≫ coeq_hom f f'`. Its existence is ensured by `is_filtered`. -/ noncomputable def coeq {j j' : C} (f f' : j ⟶ j') : C := (is_filtered_or_empty.cocone_maps f f').some /-- `coeq_hom f f'`, for morphisms `f f' : j ⟶ j'`, is an arbitrary choice of morphism `coeq_hom f f' : j' ⟶ coeq f f'` such that `coeq_condition : f ≫ coeq_hom f f' = f' ≫ coeq_hom f f'`. Its existence is ensured by `is_filtered`. -/ noncomputable def coeq_hom {j j' : C} (f f' : j ⟶ j') : j' ⟶ coeq f f' := (is_filtered_or_empty.cocone_maps f f').some_spec.some /-- `coeq_condition f f'`, for morphisms `f f' : j ⟶ j'`, is the proof that `f ≫ coeq_hom f f' = f' ≫ coeq_hom f f'`. -/ @[simp, reassoc] lemma coeq_condition {j j' : C} (f f' : j ⟶ j') : f ≫ coeq_hom f f' = f' ≫ coeq_hom f f' := (is_filtered_or_empty.cocone_maps f f').some_spec.some_spec open category_theory.limits /-- Any finite collection of objects in a filtered category has an object "to the right". -/ lemma sup_objs_exists (O : finset C) : ∃ (S : C), ∀ {X}, X ∈ O → _root_.nonempty (X ⟶ S) := begin classical, apply finset.induction_on O, { exact ⟨is_filtered.nonempty.some, (by rintros - ⟨⟩)⟩, }, { rintros X O' nm ⟨S', w'⟩, use max X S', rintros Y mY, by_cases h : X = Y, { subst h, exact ⟨left_to_max _ _⟩, }, { exact ⟨(w' (by finish)).some ≫ right_to_max _ _⟩, }, } end variables (O : finset C) (H : finset (Σ' (X Y : C) (mX : X ∈ O) (mY : Y ∈ O), X ⟶ Y)) /-- Given any `finset` of objects `{X, ...}` and indexed collection of `finset`s of morphisms `{f, ...}` in `C`, there exists an object `S`, with a morphism `T X : X ⟶ S` from each `X`, such that the triangles commute: `f ≫ T X = T Y`, for `f : X ⟶ Y` in the `finset`. -/ lemma sup_exists : ∃ (S : C) (T : Π {X : C}, X ∈ O → (X ⟶ S)), ∀ {X Y : C} (mX : X ∈ O) (mY : Y ∈ O) {f : X ⟶ Y}, (⟨X, Y, mX, mY, f⟩ : (Σ' (X Y : C) (mX : X ∈ O) (mY : Y ∈ O), X ⟶ Y)) ∈ H → f ≫ T mY = T mX := begin classical, apply finset.induction_on H, { obtain ⟨S, f⟩ := sup_objs_exists O, refine ⟨S, λ X mX, (f mX).some, _⟩, rintros - - - - - ⟨⟩, }, { rintros ⟨X, Y, mX, mY, f⟩ H' nmf ⟨S', T', w'⟩, refine ⟨coeq (f ≫ T' mY) (T' mX), λ Z mZ, T' mZ ≫ coeq_hom (f ≫ T' mY) (T' mX), _⟩, intros X' Y' mX' mY' f' mf', rw [←category.assoc], by_cases h : X = X' ∧ Y = Y', { rcases h with ⟨rfl, rfl⟩, by_cases hf : f = f', { subst hf, apply coeq_condition, }, { rw @w' _ _ mX mY f' (by simpa [hf ∘ eq.symm] using mf') }, }, { rw @w' _ _ mX' mY' f' (by finish), }, }, end /-- An arbitrary choice of object "to the right" of a finite collection of objects `O` and morphisms `H`, making all the triangles commute. -/ noncomputable def sup : C := (sup_exists O H).some /-- The morphisms to `sup O H`. -/ noncomputable def to_sup {X : C} (m : X ∈ O) : X ⟶ sup O H := (sup_exists O H).some_spec.some m /-- The triangles of consisting of a morphism in `H` and the maps to `sup O H` commute. -/ lemma to_sup_commutes {X Y : C} (mX : X ∈ O) (mY : Y ∈ O) {f : X ⟶ Y} (mf : (⟨X, Y, mX, mY, f⟩ : Σ' (X Y : C) (mX : X ∈ O) (mY : Y ∈ O), X ⟶ Y) ∈ H) : f ≫ to_sup O H mY = to_sup O H mX := (sup_exists O H).some_spec.some_spec mX mY mf variables {J : Type v} [small_category J] [fin_category J] /-- If we have `is_filtered C`, then for any functor `F : J ⥤ C` with `fin_category J`, there exists a cocone over `F`. -/ lemma cocone_nonempty (F : J ⥤ C) : _root_.nonempty (cocone F) := begin classical, let O := (finset.univ.image F.obj), let H : finset (Σ' (X Y : C) (mX : X ∈ O) (mY : Y ∈ O), X ⟶ Y) := finset.univ.bUnion (λ X : J, finset.univ.bUnion (λ Y : J, finset.univ.image (λ f : X ⟶ Y, ⟨F.obj X, F.obj Y, by simp, by simp, F.map f⟩))), obtain ⟨Z, f, w⟩ := sup_exists O H, refine ⟨⟨Z, ⟨λ X, f (by simp), _⟩⟩⟩, intros j j' g, dsimp, simp only [category.comp_id], apply w, simp only [finset.mem_univ, finset.mem_bUnion, exists_and_distrib_left, exists_prop_of_true, finset.mem_image], exact ⟨j, rfl, j', g, (by simp)⟩, end /-- An arbitrary choice of cocone over `F : J ⥤ C`, for `fin_category J` and `is_filtered C`. -/ noncomputable def cocone (F : J ⥤ C) : cocone F := (cocone_nonempty F).some variables {D : Type u₁} [category.{v₁} D] /-- If `C` is filtered, and we have a functor `R : C ⥤ D` with a left adjoint, then `D` is filtered. -/ lemma of_right_adjoint {L : D ⥤ C} {R : C ⥤ D} (h : L ⊣ R) : is_filtered D := { cocone_objs := λ X Y, ⟨_, h.hom_equiv _ _ (left_to_max _ _), h.hom_equiv _ _ (right_to_max _ _), ⟨⟩⟩, cocone_maps := λ X Y f g, ⟨_, h.hom_equiv _ _ (coeq_hom _ _), by rw [← h.hom_equiv_naturality_left, ← h.hom_equiv_naturality_left, coeq_condition]⟩, nonempty := is_filtered.nonempty.map R.obj } /-- If `C` is filtered, and we have a right adjoint functor `R : C ⥤ D`, then `D` is filtered. -/ lemma of_is_right_adjoint (R : C ⥤ D) [is_right_adjoint R] : is_filtered D := of_right_adjoint (adjunction.of_right_adjoint R) /-- Being filtered is preserved by equivalence of categories. -/ lemma of_equivalence (h : C ≌ D) : is_filtered D := of_right_adjoint h.symm.to_adjunction end is_filtered end category_theory
70097eb652916588f28bf1a77d123624c2e83751
87a08a8e9b222ec02f3327dca4ae24590c1b3de9
/src/topology/constructions.lean
829571ae2d52858c89600636e07a3d5221378278
[ "Apache-2.0" ]
permissive
naussicaa/mathlib
86d05223517a39e80920549a8052f9cf0e0b77b8
1ef2c2df20cf45c21675d855436228c7ae02d47a
refs/heads/master
1,592,104,950,080
1,562,073,069,000
1,562,073,069,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
49,004
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Patrick Massot Constructions of new topological spaces from old ones: product, sum, subtype, quotient, list, vector -/ import topology.maps topology.subset_properties topology.separation topology.bases noncomputable theory open set filter lattice local attribute [instance] classical.prop_decidable variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} section prod open topological_space variables [topological_space α] [topological_space β] [topological_space γ] lemma continuous_fst : continuous (@prod.fst α β) := continuous_inf_dom_left continuous_induced_dom lemma continuous_snd : continuous (@prod.snd α β) := continuous_inf_dom_right continuous_induced_dom lemma continuous.prod_mk {f : γ → α} {g : γ → β} (hf : continuous f) (hg : continuous g) : continuous (λx, prod.mk (f x) (g x)) := continuous_inf_rng (continuous_induced_rng hf) (continuous_induced_rng hg) lemma continuous_swap : continuous (prod.swap : α × β → β × α) := continuous.prod_mk continuous_snd continuous_fst lemma is_open_prod {s : set α} {t : set β} (hs : is_open s) (ht : is_open t) : is_open (set.prod s t) := is_open_inter (continuous_fst s hs) (continuous_snd t ht) lemma nhds_prod_eq {a : α} {b : β} : nhds (a, b) = filter.prod (nhds a) (nhds b) := by rw [filter.prod, prod.topological_space, nhds_inf, nhds_induced_eq_comap, nhds_induced_eq_comap] instance [topological_space α] [discrete_topology α] [topological_space β] [discrete_topology β] : discrete_topology (α × β) := ⟨eq_of_nhds_eq_nhds $ assume ⟨a, b⟩, by rw [nhds_prod_eq, nhds_discrete α, nhds_discrete β, nhds_bot, filter.prod_pure_pure]⟩ lemma prod_mem_nhds_sets {s : set α} {t : set β} {a : α} {b : β} (ha : s ∈ nhds a) (hb : t ∈ nhds b) : set.prod s t ∈ nhds (a, b) := by rw [nhds_prod_eq]; exact prod_mem_prod ha hb lemma nhds_swap (a : α) (b : β) : nhds (a, b) = (nhds (b, a)).map prod.swap := by rw [nhds_prod_eq, filter.prod_comm, nhds_prod_eq]; refl lemma tendsto_prod_mk_nhds {γ} {a : α} {b : β} {f : filter γ} {ma : γ → α} {mb : γ → β} (ha : tendsto ma f (nhds a)) (hb : tendsto mb f (nhds b)) : tendsto (λc, (ma c, mb c)) f (nhds (a, b)) := by rw [nhds_prod_eq]; exact filter.tendsto.prod_mk ha hb lemma continuous_within_at.prod {f : α → β} {g : α → γ} {s : set α} {x : α} (hf : continuous_within_at f s x) (hg : continuous_within_at g s x) : continuous_within_at (λx, (f x, g x)) s x := tendsto_prod_mk_nhds hf hg lemma continuous_at.prod {f : α → β} {g : α → γ} {x : α} (hf : continuous_at f x) (hg : continuous_at g x) : continuous_at (λx, (f x, g x)) x := tendsto_prod_mk_nhds hf hg lemma continuous_on.prod {f : α → β} {g : α → γ} {s : set α} (hf : continuous_on f s) (hg : continuous_on g s) : continuous_on (λx, (f x, g x)) s := λx hx, continuous_within_at.prod (hf x hx) (hg x hx) lemma prod_generate_from_generate_from_eq {s : set (set α)} {t : set (set β)} (hs : ⋃₀ s = univ) (ht : ⋃₀ t = univ) : @prod.topological_space α β (generate_from s) (generate_from t) = generate_from {g | ∃u∈s, ∃v∈t, g = set.prod u v} := let G := generate_from {g | ∃u∈s, ∃v∈t, g = set.prod u v} in le_antisymm (le_generate_from $ assume g ⟨u, hu, v, hv, g_eq⟩, g_eq.symm ▸ @is_open_prod _ _ (generate_from s) (generate_from t) _ _ (generate_open.basic _ hu) (generate_open.basic _ hv)) (le_inf (coinduced_le_iff_le_induced.mp $ le_generate_from $ assume u hu, have (⋃v∈t, set.prod u v) = prod.fst ⁻¹' u, from calc (⋃v∈t, set.prod u v) = set.prod u univ : set.ext $ assume ⟨a, b⟩, by rw ← ht; simp [and.left_comm] {contextual:=tt} ... = prod.fst ⁻¹' u : by simp [set.prod, preimage], show G.is_open (prod.fst ⁻¹' u), from this ▸ @is_open_Union _ _ G _ $ assume v, @is_open_Union _ _ G _ $ assume hv, generate_open.basic _ ⟨_, hu, _, hv, rfl⟩) (coinduced_le_iff_le_induced.mp $ le_generate_from $ assume v hv, have (⋃u∈s, set.prod u v) = prod.snd ⁻¹' v, from calc (⋃u∈s, set.prod u v) = set.prod univ v: set.ext $ assume ⟨a, b⟩, by rw [←hs]; by_cases b ∈ v; simp [h] {contextual:=tt} ... = prod.snd ⁻¹' v : by simp [set.prod, preimage], show G.is_open (prod.snd ⁻¹' v), from this ▸ @is_open_Union _ _ G _ $ assume u, @is_open_Union _ _ G _ $ assume hu, generate_open.basic _ ⟨_, hu, _, hv, rfl⟩)) lemma prod_eq_generate_from [tα : topological_space α] [tβ : topological_space β] : prod.topological_space = generate_from {g | ∃(s:set α) (t:set β), is_open s ∧ is_open t ∧ g = set.prod s t} := le_antisymm (le_generate_from $ assume g ⟨s, t, hs, ht, g_eq⟩, g_eq.symm ▸ is_open_prod hs ht) (le_inf (ball_image_of_ball $ λt ht, generate_open.basic _ ⟨t, univ, by simpa [set.prod_eq] using ht⟩) (ball_image_of_ball $ λt ht, generate_open.basic _ ⟨univ, t, by simpa [set.prod_eq] using ht⟩)) lemma is_open_prod_iff {s : set (α×β)} : is_open s ↔ (∀a b, (a, b) ∈ s → ∃u v, is_open u ∧ is_open v ∧ a ∈ u ∧ b ∈ v ∧ set.prod u v ⊆ s) := begin rw [is_open_iff_nhds], simp [nhds_prod_eq, mem_prod_iff], simp [mem_nhds_sets_iff], exact forall_congr (assume a, ball_congr $ assume b h, ⟨assume ⟨u', ⟨u, us, uo, au⟩, v', ⟨v, vs, vo, bv⟩, h⟩, ⟨u, uo, v, vo, au, bv, subset.trans (set.prod_mono us vs) h⟩, assume ⟨u, uo, v, vo, au, bv, h⟩, ⟨u, ⟨u, subset.refl u, uo, au⟩, v, ⟨v, subset.refl v, vo, bv⟩, h⟩⟩) end lemma closure_prod_eq {s : set α} {t : set β} : closure (set.prod s t) = set.prod (closure s) (closure t) := set.ext $ assume ⟨a, b⟩, have filter.prod (nhds a) (nhds b) ⊓ principal (set.prod s t) = filter.prod (nhds a ⊓ principal s) (nhds b ⊓ principal t), by rw [←prod_inf_prod, prod_principal_principal], by simp [closure_eq_nhds, nhds_prod_eq, this]; exact prod_neq_bot lemma mem_closure2 [topological_space α] [topological_space β] [topological_space γ] {s : set α} {t : set β} {u : set γ} {f : α → β → γ} {a : α} {b : β} (hf : continuous (λp:α×β, f p.1 p.2)) (ha : a ∈ closure s) (hb : b ∈ closure t) (hu : ∀a b, a ∈ s → b ∈ t → f a b ∈ u) : f a b ∈ closure u := have (a, b) ∈ closure (set.prod s t), by rw [closure_prod_eq]; from ⟨ha, hb⟩, show (λp:α×β, f p.1 p.2) (a, b) ∈ closure u, from mem_closure hf this $ assume ⟨a, b⟩ ⟨ha, hb⟩, hu a b ha hb lemma is_closed_prod [topological_space α] [topological_space β] {s₁ : set α} {s₂ : set β} (h₁ : is_closed s₁) (h₂ : is_closed s₂) : is_closed (set.prod s₁ s₂) := closure_eq_iff_is_closed.mp $ by simp [h₁, h₂, closure_prod_eq, closure_eq_of_is_closed] protected lemma is_open_map.prod [topological_space α] [topological_space β] [topological_space γ] [topological_space δ] {f : α → β} {g : γ → δ} (hf : is_open_map f) (hg : is_open_map g) : is_open_map (λ p : α × γ, (f p.1, g p.2)) := begin rw [is_open_map_iff_nhds_le], rintros ⟨a, b⟩, rw [nhds_prod_eq, nhds_prod_eq, ← filter.prod_map_map_eq], exact filter.prod_mono ((is_open_map_iff_nhds_le f).1 hf a) ((is_open_map_iff_nhds_le g).1 hg b) end section tube_lemma def nhds_contain_boxes (s : set α) (t : set β) : Prop := ∀ (n : set (α × β)) (hn : is_open n) (hp : set.prod s t ⊆ n), ∃ (u : set α) (v : set β), is_open u ∧ is_open v ∧ s ⊆ u ∧ t ⊆ v ∧ set.prod u v ⊆ n lemma nhds_contain_boxes.symm {s : set α} {t : set β} : nhds_contain_boxes s t → nhds_contain_boxes t s := assume H n hn hp, let ⟨u, v, uo, vo, su, tv, p⟩ := H (prod.swap ⁻¹' n) (continuous_swap n hn) (by rwa [←image_subset_iff, prod.swap, image_swap_prod]) in ⟨v, u, vo, uo, tv, su, by rwa [←image_subset_iff, prod.swap, image_swap_prod] at p⟩ lemma nhds_contain_boxes.comm {s : set α} {t : set β} : nhds_contain_boxes s t ↔ nhds_contain_boxes t s := iff.intro nhds_contain_boxes.symm nhds_contain_boxes.symm lemma nhds_contain_boxes_of_singleton {x : α} {y : β} : nhds_contain_boxes ({x} : set α) ({y} : set β) := assume n hn hp, let ⟨u, v, uo, vo, xu, yv, hp'⟩ := is_open_prod_iff.mp hn x y (hp $ by simp) in ⟨u, v, uo, vo, by simpa, by simpa, hp'⟩ lemma nhds_contain_boxes_of_compact {s : set α} (hs : compact s) (t : set β) (H : ∀ x ∈ s, nhds_contain_boxes ({x} : set α) t) : nhds_contain_boxes s t := assume n hn hp, have ∀x : subtype s, ∃uv : set α × set β, is_open uv.1 ∧ is_open uv.2 ∧ {↑x} ⊆ uv.1 ∧ t ⊆ uv.2 ∧ set.prod uv.1 uv.2 ⊆ n, from assume ⟨x, hx⟩, have set.prod {x} t ⊆ n, from subset.trans (prod_mono (by simpa) (subset.refl _)) hp, let ⟨ux,vx,H1⟩ := H x hx n hn this in ⟨⟨ux,vx⟩,H1⟩, let ⟨uvs, h⟩ := classical.axiom_of_choice this in have us_cover : s ⊆ ⋃i, (uvs i).1, from assume x hx, set.subset_Union _ ⟨x,hx⟩ (by simpa using (h ⟨x,hx⟩).2.2.1), let ⟨s0, _, s0_fin, s0_cover⟩ := compact_elim_finite_subcover_image hs (λi _, (h i).1) $ by rw bUnion_univ; exact us_cover in let u := ⋃(i ∈ s0), (uvs i).1 in let v := ⋂(i ∈ s0), (uvs i).2 in have is_open u, from is_open_bUnion (λi _, (h i).1), have is_open v, from is_open_bInter s0_fin (λi _, (h i).2.1), have t ⊆ v, from subset_bInter (λi _, (h i).2.2.2.1), have set.prod u v ⊆ n, from assume ⟨x',y'⟩ ⟨hx',hy'⟩, have ∃i ∈ s0, x' ∈ (uvs i).1, by simpa using hx', let ⟨i,is0,hi⟩ := this in (h i).2.2.2.2 ⟨hi, (bInter_subset_of_mem is0 : v ⊆ (uvs i).2) hy'⟩, ⟨u, v, ‹is_open u›, ‹is_open v›, s0_cover, ‹t ⊆ v›, ‹set.prod u v ⊆ n›⟩ lemma generalized_tube_lemma {s : set α} (hs : compact s) {t : set β} (ht : compact t) {n : set (α × β)} (hn : is_open n) (hp : set.prod s t ⊆ n) : ∃ (u : set α) (v : set β), is_open u ∧ is_open v ∧ s ⊆ u ∧ t ⊆ v ∧ set.prod u v ⊆ n := have _, from nhds_contain_boxes_of_compact hs t $ assume x _, nhds_contain_boxes.symm $ nhds_contain_boxes_of_compact ht {x} $ assume y _, nhds_contain_boxes_of_singleton, this n hn hp end tube_lemma lemma is_closed_diagonal [topological_space α] [t2_space α] : is_closed {p:α×α | p.1 = p.2} := is_closed_iff_nhds.mpr $ assume ⟨a₁, a₂⟩ h, eq_of_nhds_neq_bot $ assume : nhds a₁ ⊓ nhds a₂ = ⊥, h $ let ⟨t₁, ht₁, t₂, ht₂, (h' : t₁ ∩ t₂ ⊆ ∅)⟩ := by rw [←empty_in_sets_eq_bot, mem_inf_sets] at this; exact this in begin change t₁ ∈ nhds a₁ at ht₁, change t₂ ∈ nhds a₂ at ht₂, rw [nhds_prod_eq, ←empty_in_sets_eq_bot], apply filter.sets_of_superset, apply inter_mem_inf_sets (prod_mem_prod ht₁ ht₂) (mem_principal_sets.mpr (subset.refl _)), exact assume ⟨x₁, x₂⟩ ⟨⟨hx₁, hx₂⟩, (heq : x₁ = x₂)⟩, show false, from @h' x₁ ⟨hx₁, heq.symm ▸ hx₂⟩ end lemma is_closed_eq [topological_space α] [t2_space α] [topological_space β] {f g : β → α} (hf : continuous f) (hg : continuous g) : is_closed {x:β | f x = g x} := continuous_iff_is_closed.mp (hf.prod_mk hg) _ is_closed_diagonal lemma diagonal_eq_range_diagonal_map : {p:α×α | p.1 = p.2} = range (λx, (x,x)) := ext $ assume p, iff.intro (assume h, ⟨p.1, prod.ext_iff.2 ⟨rfl, h⟩⟩) (assume ⟨x, hx⟩, show p.1 = p.2, by rw ←hx) lemma prod_subset_compl_diagonal_iff_disjoint {s t : set α} : set.prod s t ⊆ - {p:α×α | p.1 = p.2} ↔ s ∩ t = ∅ := by rw [eq_empty_iff_forall_not_mem, subset_compl_comm, diagonal_eq_range_diagonal_map, range_subset_iff]; simp lemma compact_compact_separated [t2_space α] {s t : set α} (hs : compact s) (ht : compact t) (hst : s ∩ t = ∅) : ∃u v : set α, is_open u ∧ is_open v ∧ s ⊆ u ∧ t ⊆ v ∧ u ∩ v = ∅ := by simp only [prod_subset_compl_diagonal_iff_disjoint.symm] at ⊢ hst; exact generalized_tube_lemma hs ht is_closed_diagonal hst lemma closed_of_compact [t2_space α] (s : set α) (hs : compact s) : is_closed s := is_open_compl_iff.mpr $ is_open_iff_forall_mem_open.mpr $ assume x hx, let ⟨u, v, uo, vo, su, xv, uv⟩ := compact_compact_separated hs (compact_singleton : compact {x}) (by rwa [inter_comm, ←subset_compl_iff_disjoint, singleton_subset_iff]) in have v ⊆ -s, from subset_compl_comm.mp (subset.trans su (subset_compl_iff_disjoint.mpr uv)), ⟨v, this, vo, by simpa using xv⟩ lemma locally_compact_of_compact_nhds [topological_space α] [t2_space α] (h : ∀ x : α, ∃ s, s ∈ nhds x ∧ compact s) : locally_compact_space α := ⟨assume x n hn, let ⟨u, un, uo, xu⟩ := mem_nhds_sets_iff.mp hn in let ⟨k, kx, kc⟩ := h x in -- K is compact but not necessarily contained in N. -- K \ U is again compact and doesn't contain x, so -- we may find open sets V, W separating x from K \ U. -- Then K \ W is a compact neighborhood of x contained in U. let ⟨v, w, vo, wo, xv, kuw, vw⟩ := compact_compact_separated compact_singleton (compact_diff kc uo) (by rw [singleton_inter_eq_empty]; exact λ h, h.2 xu) in have wn : -w ∈ nhds x, from mem_nhds_sets_iff.mpr ⟨v, subset_compl_iff_disjoint.mpr vw, vo, singleton_subset_iff.mp xv⟩, ⟨k - w, filter.inter_mem_sets kx wn, subset.trans (diff_subset_comm.mp kuw) un, compact_diff kc wo⟩⟩ instance locally_compact_of_compact [topological_space α] [t2_space α] [compact_space α] : locally_compact_space α := locally_compact_of_compact_nhds (assume x, ⟨univ, mem_nhds_sets is_open_univ trivial, compact_univ⟩) -- We can't make this an instance because it could cause an instance loop. lemma normal_of_compact_t2 [topological_space α] [compact_space α] [t2_space α] : normal_space α := begin refine ⟨assume s t hs ht st, _⟩, simp only [disjoint_iff], exact compact_compact_separated (compact_of_closed hs) (compact_of_closed ht) st.eq_bot end /- TODO: more fine grained instances for first_countable_topology, separable_space, t2_space, ... -/ instance [second_countable_topology α] [second_countable_topology β] : second_countable_topology (α × β) := ⟨let ⟨a, ha₁, ha₂, ha₃, ha₄, ha₅⟩ := is_open_generated_countable_inter α in let ⟨b, hb₁, hb₂, hb₃, hb₄, hb₅⟩ := is_open_generated_countable_inter β in ⟨{g | ∃u∈a, ∃v∈b, g = set.prod u v}, have {g | ∃u∈a, ∃v∈b, g = set.prod u v} = (⋃u∈a, ⋃v∈b, {set.prod u v}), by apply set.ext; simp, by rw [this]; exact (countable_bUnion ha₁ $ assume u hu, countable_bUnion hb₁ $ by simp), by rw [ha₅, hb₅, prod_generate_from_generate_from_eq ha₄ hb₄]⟩⟩ lemma compact_prod (s : set α) (t : set β) (ha : compact s) (hb : compact t) : compact (set.prod s t) := begin rw compact_iff_ultrafilter_le_nhds at ha hb ⊢, intros f hf hfs, rw le_principal_iff at hfs, rcases ha (map prod.fst f) (ultrafilter_map hf) (le_principal_iff.2 (mem_map_sets_iff.2 ⟨_, hfs, image_subset_iff.2 (λ s h, h.1)⟩)) with ⟨a, sa, ha⟩, rcases hb (map prod.snd f) (ultrafilter_map hf) (le_principal_iff.2 (mem_map_sets_iff.2 ⟨_, hfs, image_subset_iff.2 (λ s h, h.2)⟩)) with ⟨b, tb, hb⟩, rw map_le_iff_le_comap at ha hb, refine ⟨⟨a, b⟩, ⟨sa, tb⟩, _⟩, rw nhds_prod_eq, exact le_inf ha hb end instance [compact_space α] [compact_space β] : compact_space (α × β) := ⟨begin have A : compact (set.prod (univ : set α) (univ : set β)) := compact_prod univ univ compact_univ compact_univ, have : set.prod (univ : set α) (univ : set β) = (univ : set (α × β)) := by simp, rwa this at A, end⟩ end prod section sum variables [topological_space α] [topological_space β] [topological_space γ] lemma continuous_inl : continuous (@sum.inl α β) := continuous_sup_rng_left continuous_coinduced_rng lemma continuous_inr : continuous (@sum.inr α β) := continuous_sup_rng_right continuous_coinduced_rng lemma continuous_sum_rec {f : α → γ} {g : β → γ} (hf : continuous f) (hg : continuous g) : @continuous (α ⊕ β) γ _ _ (@sum.rec α β (λ_, γ) f g) := continuous_sup_dom hf hg lemma embedding_inl : embedding (@sum.inl α β) := ⟨λ _ _, sum.inl.inj_iff.mp, begin unfold sum.topological_space, apply le_antisymm, { rw ← coinduced_le_iff_le_induced, exact lattice.le_sup_left }, { intros u hu, existsi (sum.inl '' u), change (is_open (sum.inl ⁻¹' (@sum.inl α β '' u)) ∧ is_open (sum.inr ⁻¹' (@sum.inl α β '' u))) ∧ sum.inl ⁻¹' (sum.inl '' u) = u, have : sum.inl ⁻¹' (@sum.inl α β '' u) = u := preimage_image_eq u (λ _ _, sum.inl.inj_iff.mp), rw this, have : sum.inr ⁻¹' (@sum.inl α β '' u) = ∅ := eq_empty_iff_forall_not_mem.mpr (assume a ⟨b, _, h⟩, sum.inl_ne_inr h), rw this, exact ⟨⟨hu, is_open_empty⟩, rfl⟩ } end⟩ lemma embedding_inr : embedding (@sum.inr α β) := ⟨λ _ _, sum.inr.inj_iff.mp, begin unfold sum.topological_space, apply le_antisymm, { rw ← coinduced_le_iff_le_induced, exact lattice.le_sup_right }, { intros u hu, existsi (sum.inr '' u), change (is_open (sum.inl ⁻¹' (@sum.inr α β '' u)) ∧ is_open (sum.inr ⁻¹' (@sum.inr α β '' u))) ∧ sum.inr ⁻¹' (sum.inr '' u) = u, have : sum.inl ⁻¹' (@sum.inr α β '' u) = ∅ := eq_empty_iff_forall_not_mem.mpr (assume b ⟨a, _, h⟩, sum.inr_ne_inl h), rw this, have : sum.inr ⁻¹' (@sum.inr α β '' u) = u := preimage_image_eq u (λ _ _, sum.inr.inj_iff.mp), rw this, exact ⟨⟨is_open_empty, hu⟩, rfl⟩ } end⟩ instance [topological_space α] [topological_space β] [compact_space α] [compact_space β] : compact_space (α ⊕ β) := ⟨begin have A : compact (@sum.inl α β '' univ) := compact_image compact_univ continuous_inl, have B : compact (@sum.inr α β '' univ) := compact_image compact_univ continuous_inr, have C := compact_union_of_compact A B, have : (@sum.inl α β '' univ) ∪ (@sum.inr α β '' univ) = univ := by ext; cases x; simp, rwa this at C, end⟩ end sum section subtype variables [topological_space α] [topological_space β] [topological_space γ] {p : α → Prop} lemma embedding_graph {f : α → β} (hf : continuous f) : embedding (λx, (x, f x)) := embedding_of_embedding_compose (continuous_id.prod_mk hf) continuous_fst embedding_id lemma embedding_subtype_val : embedding (@subtype.val α p) := ⟨subtype.val_injective, rfl⟩ lemma continuous_subtype_val : continuous (@subtype.val α p) := continuous_induced_dom lemma continuous_subtype_mk {f : β → α} (hp : ∀x, p (f x)) (h : continuous f) : continuous (λx, (⟨f x, hp x⟩ : subtype p)) := continuous_induced_rng h lemma continuous_inclusion {s t : set α} (h : s ⊆ t) : continuous (inclusion h) := continuous_subtype_mk _ continuous_subtype_val lemma continuous_at_subtype_val [topological_space α] {p : α → Prop} {a : subtype p} : continuous_at subtype.val a := continuous_iff_continuous_at.mp continuous_subtype_val _ lemma map_nhds_subtype_val_eq {a : α} (ha : p a) (h : {a | p a} ∈ nhds a) : map (@subtype.val α p) (nhds ⟨a, ha⟩) = nhds a := map_nhds_induced_eq (by simp [subtype.val_image, h]) lemma nhds_subtype_eq_comap {a : α} {h : p a} : nhds (⟨a, h⟩ : subtype p) = comap subtype.val (nhds a) := nhds_induced_eq_comap lemma tendsto_subtype_rng [topological_space α] {p : α → Prop} {b : filter β} {f : β → subtype p} : ∀{a:subtype p}, tendsto f b (nhds a) ↔ tendsto (λx, subtype.val (f x)) b (nhds a.val) | ⟨a, ha⟩ := by rw [nhds_subtype_eq_comap, tendsto_comap_iff] lemma continuous_subtype_nhds_cover {ι : Sort*} {f : α → β} {c : ι → α → Prop} (c_cover : ∀x:α, ∃i, {x | c i x} ∈ nhds x) (f_cont : ∀i, continuous (λ(x : subtype (c i)), f x.val)) : continuous f := continuous_iff_continuous_at.mpr $ assume x, let ⟨i, (c_sets : {x | c i x} ∈ nhds x)⟩ := c_cover x in let x' : subtype (c i) := ⟨x, mem_of_nhds c_sets⟩ in calc map f (nhds x) = map f (map subtype.val (nhds x')) : congr_arg (map f) (map_nhds_subtype_val_eq _ $ c_sets).symm ... = map (λx:subtype (c i), f x.val) (nhds x') : rfl ... ≤ nhds (f x) : continuous_iff_continuous_at.mp (f_cont i) x' lemma continuous_subtype_is_closed_cover {ι : Sort*} {f : α → β} (c : ι → α → Prop) (h_lf : locally_finite (λi, {x | c i x})) (h_is_closed : ∀i, is_closed {x | c i x}) (h_cover : ∀x, ∃i, c i x) (f_cont : ∀i, continuous (λ(x : subtype (c i)), f x.val)) : continuous f := continuous_iff_is_closed.mpr $ assume s hs, have ∀i, is_closed (@subtype.val α {x | c i x} '' (f ∘ subtype.val ⁻¹' s)), from assume i, embedding_is_closed embedding_subtype_val (by simp [subtype.val_range]; exact h_is_closed i) (continuous_iff_is_closed.mp (f_cont i) _ hs), have is_closed (⋃i, @subtype.val α {x | c i x} '' (f ∘ subtype.val ⁻¹' s)), from is_closed_Union_of_locally_finite (locally_finite_subset h_lf $ assume i x ⟨⟨x', hx'⟩, _, heq⟩, heq ▸ hx') this, have f ⁻¹' s = (⋃i, @subtype.val α {x | c i x} '' (f ∘ subtype.val ⁻¹' s)), begin apply set.ext, have : ∀ (x : α), f x ∈ s ↔ ∃ (i : ι), c i x ∧ f x ∈ s := λ x, ⟨λ hx, let ⟨i, hi⟩ := h_cover x in ⟨i, hi, hx⟩, λ ⟨i, hi, hx⟩, hx⟩, simp [and.comm, and.left_comm], simpa [(∘)], end, by rwa [this] lemma closure_subtype {x : {a // p a}} {s : set {a // p a}}: x ∈ closure s ↔ x.val ∈ closure (subtype.val '' s) := closure_induced $ assume x y, subtype.eq lemma compact_iff_compact_image_of_embedding {s : set α} {f : α → β} (hf : embedding f) : compact s ↔ compact (f '' s) := iff.intro (assume h, compact_image h hf.continuous) $ assume h, begin rw compact_iff_ultrafilter_le_nhds at ⊢ h, intros u hu us', let u' : filter β := map f u, have : u' ≤ principal (f '' s), begin rw [map_le_iff_le_comap, comap_principal], convert us', exact preimage_image_eq _ hf.1 end, rcases h u' (ultrafilter_map hu) this with ⟨_, ⟨a, ha, ⟨⟩⟩, _⟩, refine ⟨a, ha, _⟩, rwa [hf.2, nhds_induced_eq_comap, ←map_le_iff_le_comap] end lemma compact_iff_compact_in_subtype {s : set {a // p a}} : compact s ↔ compact (subtype.val '' s) := compact_iff_compact_image_of_embedding embedding_subtype_val lemma compact_iff_compact_univ {s : set α} : compact s ↔ compact (univ : set (subtype s)) := by rw [compact_iff_compact_in_subtype, image_univ, subtype.val_range]; refl lemma compact_iff_compact_space {s : set α} : compact s ↔ compact_space s := compact_iff_compact_univ.trans ⟨λ h, ⟨h⟩, @compact_space.compact_univ _ _⟩ end subtype section quotient variables [topological_space α] [topological_space β] [topological_space γ] variables {r : α → α → Prop} {s : setoid α} lemma quotient_map_quot_mk : quotient_map (@quot.mk α r) := ⟨quot.exists_rep, rfl⟩ lemma continuous_quot_mk : continuous (@quot.mk α r) := continuous_coinduced_rng lemma continuous_quot_lift {f : α → β} (hr : ∀ a b, r a b → f a = f b) (h : continuous f) : continuous (quot.lift f hr : quot r → β) := continuous_coinduced_dom h lemma quotient_map_quotient_mk : quotient_map (@quotient.mk α s) := quotient_map_quot_mk lemma continuous_quotient_mk : continuous (@quotient.mk α s) := continuous_coinduced_rng lemma continuous_quotient_lift {f : α → β} (hs : ∀ a b, a ≈ b → f a = f b) (h : continuous f) : continuous (quotient.lift f hs : quotient s → β) := continuous_coinduced_dom h instance quot.compact_space {r : α → α → Prop} [topological_space α] [compact_space α] : compact_space (quot r) := ⟨begin have : quot.mk r '' univ = univ, by rw [image_univ, range_iff_surjective]; exact quot.exists_rep, rw ←this, exact compact_image compact_univ continuous_quot_mk end⟩ instance quotient.compact_space {s : setoid α} [topological_space α] [compact_space α] : compact_space (quotient s) := quot.compact_space end quotient section pi variables {ι : Type*} {π : ι → Type*} open topological_space lemma continuous_pi [topological_space α] [∀i, topological_space (π i)] {f : α → Πi:ι, π i} (h : ∀i, continuous (λa, f a i)) : continuous f := continuous_infi_rng $ assume i, continuous_induced_rng $ h i lemma continuous_apply [∀i, topological_space (π i)] (i : ι) : continuous (λp:Πi, π i, p i) := continuous_infi_dom continuous_induced_dom lemma nhds_pi [t : ∀i, topological_space (π i)] {a : Πi, π i} : nhds a = (⨅i, comap (λx, x i) (nhds (a i))) := calc nhds a = (⨅i, @nhds _ (@topological_space.induced _ _ (λx:Πi, π i, x i) (t i)) a) : nhds_infi ... = (⨅i, comap (λx, x i) (nhds (a i))) : by simp [nhds_induced_eq_comap] /-- Tychonoff's theorem -/ lemma compact_pi_infinite [∀i, topological_space (π i)] {s : Πi:ι, set (π i)} : (∀i, compact (s i)) → compact {x : Πi:ι, π i | ∀i, x i ∈ s i} := begin simp [compact_iff_ultrafilter_le_nhds, nhds_pi], exact assume h f hf hfs, let p : Πi:ι, filter (π i) := λi, map (λx:Πi:ι, π i, x i) f in have ∀i:ι, ∃a, a∈s i ∧ p i ≤ nhds a, from assume i, h i (p i) (ultrafilter_map hf) $ show (λx:Πi:ι, π i, x i) ⁻¹' s i ∈ f.sets, from mem_sets_of_superset hfs $ assume x (hx : ∀i, x i ∈ s i), hx i, let ⟨a, ha⟩ := classical.axiom_of_choice this in ⟨a, assume i, (ha i).left, assume i, map_le_iff_le_comap.mp $ (ha i).right⟩ end lemma is_open_set_pi [∀a, topological_space (π a)] {i : set ι} {s : Πa, set (π a)} (hi : finite i) (hs : ∀a∈i, is_open (s a)) : is_open (pi i s) := by rw [pi_def]; exact (is_open_bInter hi $ assume a ha, continuous_apply a _ $ hs a ha) lemma pi_eq_generate_from [∀a, topological_space (π a)] : Pi.topological_space = generate_from {g | ∃(s:Πa, set (π a)) (i : finset ι), (∀a∈i, is_open (s a)) ∧ g = pi ↑i s} := le_antisymm (le_generate_from $ assume g ⟨s, i, hi, eq⟩, eq.symm ▸ is_open_set_pi (finset.finite_to_set _) hi) (le_infi $ assume a s ⟨t, ht, s_eq⟩, generate_open.basic _ $ ⟨function.update (λa, univ) a t, {a}, by simpa using ht, by ext f; simp [s_eq.symm, pi]⟩) lemma pi_generate_from_eq {g : Πa, set (set (π a))} : @Pi.topological_space ι π (λa, generate_from (g a)) = generate_from {t | ∃(s:Πa, set (π a)) (i : finset ι), (∀a∈i, s a ∈ g a) ∧ t = pi ↑i s} := let G := {t | ∃(s:Πa, set (π a)) (i : finset ι), (∀a∈i, s a ∈ g a) ∧ t = pi ↑i s} in begin rw [pi_eq_generate_from], refine le_antisymm (generate_from_mono _) (le_generate_from _), exact assume s ⟨t, i, ht, eq⟩, ⟨t, i, assume a ha, generate_open.basic _ (ht a ha), eq⟩, { rintros s ⟨t, i, hi, rfl⟩, rw [pi_def], apply is_open_bInter (finset.finite_to_set _), assume a ha, show ((generate_from G).coinduced (λf:Πa, π a, f a)).is_open (t a), refine le_generate_from _ _ (hi a ha), exact assume s hs, generate_open.basic _ ⟨function.update (λa, univ) a s, {a}, by simp [hs]⟩ } end lemma pi_generate_from_eq_fintype {g : Πa, set (set (π a))} [fintype ι] (hg : ∀a, ⋃₀ g a = univ) : @Pi.topological_space ι π (λa, generate_from (g a)) = generate_from {t | ∃(s:Πa, set (π a)), (∀a, s a ∈ g a) ∧ t = pi univ s} := let G := {t | ∃(s:Πa, set (π a)), (∀a, s a ∈ g a) ∧ t = pi univ s} in begin rw [pi_generate_from_eq], refine le_antisymm (generate_from_mono _) (le_generate_from _), exact assume s ⟨t, ht, eq⟩, ⟨t, finset.univ, by simp [ht, eq]⟩, { rintros s ⟨t, i, ht, rfl⟩, apply is_open_iff_forall_mem_open.2 _, assume f hf, choose c hc using show ∀a, ∃s, s ∈ g a ∧ f a ∈ s, { assume a, have : f a ∈ ⋃₀ g a, { rw [hg], apply mem_univ }, simpa }, refine ⟨pi univ (λa, if a ∈ i then t a else (c : Πa, set (π a)) a), _, _, _⟩, { simp [pi_if] }, { refine generate_open.basic _ ⟨_, assume a, _, rfl⟩, by_cases a ∈ i; simp [*, pi] at * }, { have : f ∈ pi {a | a ∉ i} c, { simp [*, pi] at * }, simpa [pi_if, hf] } } end instance second_countable_topology_fintype [fintype ι] [t : ∀a, topological_space (π a)] [sc : ∀a, second_countable_topology (π a)] : second_countable_topology (∀a, π a) := have ∀i, ∃b : set (set (π i)), countable b ∧ ∅ ∉ b ∧ is_topological_basis b, from assume a, @is_open_generated_countable_inter (π a) _ (sc a), let ⟨g, hg⟩ := classical.axiom_of_choice this in have t = (λa, generate_from (g a)), from funext $ assume a, (hg a).2.2.2.2, begin constructor, refine ⟨pi univ '' pi univ g, countable_image _ _, _⟩, { suffices : countable {f : Πa, set (π a) | ∀a, f a ∈ g a}, { simpa [pi] }, exact countable_pi (assume i, (hg i).1), }, rw [this, pi_generate_from_eq_fintype], { congr' 1, ext f, simp [pi, eq_comm] }, exact assume a, (hg a).2.2.2.1 end instance pi.compact [∀i:ι, topological_space (π i)] [∀i:ι, compact_space (π i)] : compact_space (Πi, π i) := ⟨begin have A : compact {x : Πi:ι, π i | ∀i, x i ∈ (univ : set (π i))} := compact_pi_infinite (λi, compact_univ), have : {x : Πi:ι, π i | ∀i, x i ∈ (univ : set (π i))} = univ := by ext; simp, rwa this at A, end⟩ end pi section sigma variables {ι : Type*} {σ : ι → Type*} [Π i, topological_space (σ i)] open lattice lemma continuous_sigma_mk {i : ι} : continuous (@sigma.mk ι σ i) := continuous_supr_rng continuous_coinduced_rng lemma is_open_sigma_iff {s : set (sigma σ)} : is_open s ↔ ∀ i, is_open (sigma.mk i ⁻¹' s) := by simp only [is_open_supr_iff, is_open_coinduced] lemma is_closed_sigma_iff {s : set (sigma σ)} : is_closed s ↔ ∀ i, is_closed (sigma.mk i ⁻¹' s) := is_open_sigma_iff lemma is_open_map_sigma_mk {i : ι} : is_open_map (@sigma.mk ι σ i) := begin intros s hs, rw is_open_sigma_iff, intro j, classical, by_cases h : i = j, { subst j, convert hs, exact set.preimage_image_eq _ injective_sigma_mk }, { convert is_open_empty, apply set.eq_empty_of_subset_empty, rintro x ⟨y, _, hy⟩, have : i = j, by cc, contradiction } end lemma is_open_range_sigma_mk {i : ι} : is_open (set.range (@sigma.mk ι σ i)) := by { rw ←set.image_univ, exact is_open_map_sigma_mk _ is_open_univ } lemma is_closed_map_sigma_mk {i : ι} : is_closed_map (@sigma.mk ι σ i) := begin intros s hs, rw is_closed_sigma_iff, intro j, classical, by_cases h : i = j, { subst j, convert hs, exact set.preimage_image_eq _ injective_sigma_mk }, { convert is_closed_empty, apply set.eq_empty_of_subset_empty, rintro x ⟨y, _, hy⟩, have : i = j, by cc, contradiction } end lemma is_closed_sigma_mk {i : ι} : is_closed (set.range (@sigma.mk ι σ i)) := by { rw ←set.image_univ, exact is_closed_map_sigma_mk _ is_closed_univ } lemma closed_embedding_sigma_mk {i : ι} : closed_embedding (@sigma.mk ι σ i) := closed_embedding_of_continuous_injective_closed continuous_sigma_mk injective_sigma_mk is_closed_map_sigma_mk lemma embedding_sigma_mk {i : ι} : embedding (@sigma.mk ι σ i) := closed_embedding_sigma_mk.1 /-- A map out of a sum type is continuous if its restriction to each summand is. -/ lemma continuous_sigma [topological_space β] {f : sigma σ → β} (h : ∀ i, continuous (λ a, f ⟨i, a⟩)) : continuous f := continuous_supr_dom (λ i, continuous_coinduced_dom (h i)) lemma continuous_sigma_map {κ : Type*} {τ : κ → Type*} [Π k, topological_space (τ k)] {f₁ : ι → κ} {f₂ : Π i, σ i → τ (f₁ i)} (hf : ∀ i, continuous (f₂ i)) : continuous (sigma.map f₁ f₂) := continuous_sigma $ λ i, show continuous (λ a, sigma.mk (f₁ i) (f₂ i a)), from continuous_sigma_mk.comp (hf i) /-- The sum of embeddings is an embedding. -/ lemma embedding_sigma_map {τ : ι → Type*} [Π i, topological_space (τ i)] {f : Π i, σ i → τ i} (hf : ∀ i, embedding (f i)) : embedding (sigma.map id f) := begin refine ⟨injective_sigma_map function.injective_id (λ i, (hf i).1), _⟩, refine le_antisymm (continuous_iff_le_induced.mp (continuous_sigma_map (λ i, (hf i).continuous))) _, intros s hs, replace hs := is_open_sigma_iff.mp hs, have : ∀ i, ∃ t, is_open t ∧ f i ⁻¹' t = sigma.mk i ⁻¹' s, { intro i, apply is_open_induced_iff.mp, convert hs i, exact (hf i).2.symm }, choose t ht using this, apply is_open_induced_iff.mpr, refine ⟨⋃ i, sigma.mk i '' t i, is_open_Union (λ i, is_open_map_sigma_mk _ (ht i).1), _⟩, ext p, rcases p with ⟨i, x⟩, change (sigma.mk i (f i x) ∈ ⋃ (i : ι), sigma.mk i '' t i) ↔ x ∈ sigma.mk i ⁻¹' s, rw [←(ht i).2, mem_Union], split, { rintro ⟨j, hj⟩, rw mem_image at hj, rcases hj with ⟨y, hy₁, hy₂⟩, rcases sigma.mk.inj_iff.mp hy₂ with ⟨rfl, hy⟩, replace hy := eq_of_heq hy, subst y, exact hy₁ }, { intro hx, use i, rw mem_image, exact ⟨f i x, hx, rfl⟩ } end end sigma namespace list variables [topological_space α] [topological_space β] lemma tendsto_cons' {a : α} {l : list α} : tendsto (λp:α×list α, list.cons p.1 p.2) ((nhds a).prod (nhds l)) (nhds (a :: l)) := by rw [nhds_cons, tendsto, map_prod]; exact le_refl _ lemma tendsto_cons {f : α → β} {g : α → list β} {a : _root_.filter α} {b : β} {l : list β} (hf : tendsto f a (nhds b)) (hg : tendsto g a (nhds l)): tendsto (λa, list.cons (f a) (g a)) a (nhds (b :: l)) := tendsto_cons'.comp (tendsto.prod_mk hf hg) lemma tendsto_cons_iff [topological_space β] {f : list α → β} {b : _root_.filter β} {a : α} {l : list α} : tendsto f (nhds (a :: l)) b ↔ tendsto (λp:α×list α, f (p.1 :: p.2)) ((nhds a).prod (nhds l)) b := have nhds (a :: l) = ((nhds a).prod (nhds l)).map (λp:α×list α, (p.1 :: p.2)), begin simp only [nhds_cons, filter.prod_eq, (filter.map_def _ _).symm, (filter.seq_eq_filter_seq _ _).symm], simp [-filter.seq_eq_filter_seq, -filter.map_def, (∘)] with functor_norm, end, by rw [this, filter.tendsto_map'_iff] lemma tendsto_nhds [topological_space β] {f : list α → β} {r : list α → _root_.filter β} (h_nil : tendsto f (pure []) (r [])) (h_cons : ∀l a, tendsto f (nhds l) (r l) → tendsto (λp:α×list α, f (p.1 :: p.2)) ((nhds a).prod (nhds l)) (r (a::l))) : ∀l, tendsto f (nhds l) (r l) | [] := by rwa [nhds_nil] | (a::l) := by rw [tendsto_cons_iff]; exact h_cons l a (tendsto_nhds l) lemma continuous_at_length [topological_space α] : ∀(l : list α), continuous_at list.length l := begin simp only [continuous_at, nhds_discrete], refine tendsto_nhds _ _, { exact tendsto_pure_pure _ _ }, { assume l a ih, dsimp only [list.length], refine tendsto.comp (tendsto_pure_pure (λx, x + 1) _) _, refine tendsto.comp ih tendsto_snd } end lemma tendsto_insert_nth' {a : α} : ∀{n : ℕ} {l : list α}, tendsto (λp:α×list α, insert_nth n p.1 p.2) ((nhds a).prod (nhds l)) (nhds (insert_nth n a l)) | 0 l := tendsto_cons' | (n+1) [] := suffices tendsto (λa, []) (nhds a) (nhds ([] : list α)), by simpa [nhds_nil, tendsto, map_prod, -filter.pure_def, (∘), insert_nth], tendsto_const_nhds | (n+1) (a'::l) := have (nhds a).prod (nhds (a' :: l)) = ((nhds a).prod ((nhds a').prod (nhds l))).map (λp:α×α×list α, (p.1, p.2.1 :: p.2.2)), begin simp only [nhds_cons, filter.prod_eq, (filter.map_def _ _).symm, (filter.seq_eq_filter_seq _ _).symm], simp [-filter.seq_eq_filter_seq, -filter.map_def, (∘)] with functor_norm end, begin rw [this, tendsto_map'_iff], exact tendsto_cons (tendsto_fst.comp tendsto_snd) ((@tendsto_insert_nth' n l).comp (tendsto.prod_mk tendsto_fst (tendsto_snd.comp tendsto_snd))) end lemma tendsto_insert_nth {n : ℕ} {a : α} {l : list α} {f : β → α} {g : β → list α} {b : _root_.filter β} (hf : tendsto f b (nhds a)) (hg : tendsto g b (nhds l)) : tendsto (λb:β, insert_nth n (f b) (g b)) b (nhds (insert_nth n a l)) := tendsto_insert_nth'.comp (tendsto.prod_mk hf hg) lemma continuous_insert_nth {n : ℕ} : continuous (λp:α×list α, insert_nth n p.1 p.2) := continuous_iff_continuous_at.mpr $ assume ⟨a, l⟩, by rw [continuous_at, nhds_prod_eq]; exact tendsto_insert_nth' lemma tendsto_remove_nth : ∀{n : ℕ} {l : list α}, tendsto (λl, remove_nth l n) (nhds l) (nhds (remove_nth l n)) | _ [] := by rw [nhds_nil]; exact tendsto_pure_nhds _ _ | 0 (a::l) := by rw [tendsto_cons_iff]; exact tendsto_snd | (n+1) (a::l) := begin rw [tendsto_cons_iff], dsimp [remove_nth], exact tendsto_cons tendsto_fst ((@tendsto_remove_nth n l).comp tendsto_snd) end lemma continuous_remove_nth {n : ℕ} : continuous (λl : list α, remove_nth l n) := continuous_iff_continuous_at.mpr $ assume a, tendsto_remove_nth end list namespace vector open list filter instance (n : ℕ) [topological_space α] : topological_space (vector α n) := by unfold vector; apply_instance lemma cons_val {n : ℕ} {a : α} : ∀{v : vector α n}, (a :: v).val = a :: v.val | ⟨l, hl⟩ := rfl lemma tendsto_cons [topological_space α] {n : ℕ} {a : α} {l : vector α n}: tendsto (λp:α×vector α n, vector.cons p.1 p.2) ((nhds a).prod (nhds l)) (nhds (a :: l)) := by simp [tendsto_subtype_rng, cons_val]; exact tendsto_cons tendsto_fst (tendsto.comp continuous_at_subtype_val tendsto_snd) lemma tendsto_insert_nth [topological_space α] {n : ℕ} {i : fin (n+1)} {a:α} : ∀{l:vector α n}, tendsto (λp:α×vector α n, insert_nth p.1 i p.2) ((nhds a).prod (nhds l)) (nhds (insert_nth a i l)) | ⟨l, hl⟩ := begin rw [insert_nth, tendsto_subtype_rng], simp [insert_nth_val], exact list.tendsto_insert_nth tendsto_fst (tendsto.comp continuous_at_subtype_val tendsto_snd : _) end lemma continuous_insert_nth' [topological_space α] {n : ℕ} {i : fin (n+1)} : continuous (λp:α×vector α n, insert_nth p.1 i p.2) := continuous_iff_continuous_at.mpr $ assume ⟨a, l⟩, by rw [continuous_at, nhds_prod_eq]; exact tendsto_insert_nth lemma continuous_insert_nth [topological_space α] [topological_space β] {n : ℕ} {i : fin (n+1)} {f : β → α} {g : β → vector α n} (hf : continuous f) (hg : continuous g) : continuous (λb, insert_nth (f b) i (g b)) := continuous_insert_nth'.comp (continuous.prod_mk hf hg) lemma continuous_at_remove_nth [topological_space α] {n : ℕ} {i : fin (n+1)} : ∀{l:vector α (n+1)}, continuous_at (remove_nth i) l | ⟨l, hl⟩ := -- ∀{l:vector α (n+1)}, tendsto (remove_nth i) (nhds l) (nhds (remove_nth i l)) --| ⟨l, hl⟩ := begin rw [continuous_at, remove_nth, tendsto_subtype_rng], simp [remove_nth_val], exact tendsto.comp list.tendsto_remove_nth continuous_at_subtype_val end lemma continuous_remove_nth [topological_space α] {n : ℕ} {i : fin (n+1)} : continuous (remove_nth i : vector α (n+1) → vector α n) := continuous_iff_continuous_at.mpr $ assume ⟨a, l⟩, continuous_at_remove_nth end vector namespace dense_embedding variables [topological_space α] [topological_space β] [topological_space γ] [topological_space δ] /-- The product of two dense embeddings is a dense embedding -/ protected def prod {e₁ : α → β} {e₂ : γ → δ} (de₁ : dense_embedding e₁) (de₂ : dense_embedding e₂) : dense_embedding (λ(p : α × γ), (e₁ p.1, e₂ p.2)) := { dense_embedding . dense := have closure (range (λ(p : α × γ), (e₁ p.1, e₂ p.2))) = set.prod (closure (range e₁)) (closure (range e₂)), by rw [←closure_prod_eq, prod_range_range_eq], assume ⟨b, d⟩, begin rw [this], simp, constructor, apply de₁.dense, apply de₂.dense end, inj := assume ⟨x₁, x₂⟩ ⟨y₁, y₂⟩, by simp; exact assume h₁ h₂, ⟨de₁.inj h₁, de₂.inj h₂⟩, induced := assume ⟨a, b⟩, by rw [nhds_prod_eq, nhds_prod_eq, ←prod_comap_comap_eq, de₁.induced, de₂.induced] } def subtype_emb (p : α → Prop) {e : α → β} (de : dense_embedding e) (x : {x // p x}) : {x // x ∈ closure (e '' {x | p x})} := ⟨e x.1, subset_closure $ mem_image_of_mem e x.2⟩ protected def subtype (p : α → Prop) {e : α → β} (de : dense_embedding e) : dense_embedding (de.subtype_emb p) := { dense_embedding . dense := assume ⟨x, hx⟩, closure_subtype.mpr $ have (λ (x : {x // p x}), e (x.val)) = e ∘ subtype.val, from rfl, begin rw ← image_univ, simp [(image_comp _ _ _).symm, (∘), subtype_emb, -image_univ], rw [this, image_comp, subtype.val_image], simp, assumption end, inj := assume ⟨x, hx⟩ ⟨y, hy⟩ h, subtype.eq $ de.inj $ @@congr_arg subtype.val h, induced := assume ⟨x, hx⟩, by simp [subtype_emb, nhds_subtype_eq_comap, comap_comap_comp, (∘), (de.induced x).symm] } end dense_embedding lemma is_closed_property [topological_space α] [topological_space β] {e : α → β} {p : β → Prop} (he : closure (range e) = univ) (hp : is_closed {x | p x}) (h : ∀a, p (e a)) : ∀b, p b := have univ ⊆ {b | p b}, from calc univ = closure (range e) : he.symm ... ⊆ closure {b | p b} : closure_mono $ range_subset_iff.mpr h ... = _ : closure_eq_of_is_closed hp, assume b, this trivial lemma is_closed_property2 [topological_space α] [topological_space β] {e : α → β} {p : β → β → Prop} (he : dense_embedding e) (hp : is_closed {q:β×β | p q.1 q.2}) (h : ∀a₁ a₂, p (e a₁) (e a₂)) : ∀b₁ b₂, p b₁ b₂ := have ∀q:β×β, p q.1 q.2, from is_closed_property (he.prod he).closure_range hp $ assume a, h _ _, assume b₁ b₂, this ⟨b₁, b₂⟩ lemma is_closed_property3 [topological_space α] [topological_space β] {e : α → β} {p : β → β → β → Prop} (he : dense_embedding e) (hp : is_closed {q:β×β×β | p q.1 q.2.1 q.2.2}) (h : ∀a₁ a₂ a₃, p (e a₁) (e a₂) (e a₃)) : ∀b₁ b₂ b₃, p b₁ b₂ b₃ := have ∀q:β×β×β, p q.1 q.2.1 q.2.2, from is_closed_property (he.prod $ he.prod he).closure_range hp $ assume ⟨a₁, a₂, a₃⟩, h _ _ _, assume b₁ b₂ b₃, this ⟨b₁, b₂, b₃⟩ lemma mem_closure_of_continuous [topological_space α] [topological_space β] {f : α → β} {a : α} {s : set α} {t : set β} (hf : continuous f) (ha : a ∈ closure s) (h : ∀a∈s, f a ∈ closure t) : f a ∈ closure t := calc f a ∈ f '' closure s : mem_image_of_mem _ ha ... ⊆ closure (f '' s) : image_closure_subset_closure_image hf ... ⊆ closure (closure t) : closure_mono $ image_subset_iff.mpr $ h ... ⊆ closure t : begin rw [closure_eq_of_is_closed], exact subset.refl _, exact is_closed_closure end lemma mem_closure_of_continuous2 [topological_space α] [topological_space β] [topological_space γ] {f : α → β → γ} {a : α} {b : β} {s : set α} {t : set β} {u : set γ} (hf : continuous (λp:α×β, f p.1 p.2)) (ha : a ∈ closure s) (hb : b ∈ closure t) (h : ∀a∈s, ∀b∈t, f a b ∈ closure u) : f a b ∈ closure u := have (a,b) ∈ closure (set.prod s t), by simp [closure_prod_eq, ha, hb], show f (a, b).1 (a, b).2 ∈ closure u, from @mem_closure_of_continuous (α×β) _ _ _ (λp:α×β, f p.1 p.2) (a,b) _ u hf this $ assume ⟨p₁, p₂⟩ ⟨h₁, h₂⟩, h p₁ h₁ p₂ h₂ /-- α and β are homeomorph, also called topological isomoph -/ structure homeomorph (α : Type*) (β : Type*) [topological_space α] [topological_space β] extends α ≃ β := (continuous_to_fun : continuous to_fun) (continuous_inv_fun : continuous inv_fun) infix ` ≃ₜ `:50 := homeomorph namespace homeomorph variables [topological_space α] [topological_space β] [topological_space γ] [topological_space δ] instance : has_coe_to_fun (α ≃ₜ β) := ⟨λ_, α → β, λe, e.to_equiv⟩ lemma coe_eq_to_equiv (h : α ≃ₜ β) (a : α) : h a = h.to_equiv a := rfl protected def refl (α : Type*) [topological_space α] : α ≃ₜ α := { continuous_to_fun := continuous_id, continuous_inv_fun := continuous_id, .. equiv.refl α } protected def trans (h₁ : α ≃ₜ β) (h₂ : β ≃ₜ γ) : α ≃ₜ γ := { continuous_to_fun := h₂.continuous_to_fun.comp h₁.continuous_to_fun, continuous_inv_fun := h₁.continuous_inv_fun.comp h₂.continuous_inv_fun, .. equiv.trans h₁.to_equiv h₂.to_equiv } protected def symm (h : α ≃ₜ β) : β ≃ₜ α := { continuous_to_fun := h.continuous_inv_fun, continuous_inv_fun := h.continuous_to_fun, .. h.to_equiv.symm } protected def continuous (h : α ≃ₜ β) : continuous h := h.continuous_to_fun lemma symm_comp_self (h : α ≃ₜ β) : ⇑h.symm ∘ ⇑h = id := funext $ assume a, h.to_equiv.left_inv a lemma self_comp_symm (h : α ≃ₜ β) : ⇑h ∘ ⇑h.symm = id := funext $ assume a, h.to_equiv.right_inv a lemma range_coe (h : α ≃ₜ β) : range h = univ := eq_univ_of_forall $ assume b, ⟨h.symm b, congr_fun h.self_comp_symm b⟩ lemma image_symm (h : α ≃ₜ β) : image h.symm = preimage h := image_eq_preimage_of_inverse h.symm.to_equiv.left_inv h.symm.to_equiv.right_inv lemma preimage_symm (h : α ≃ₜ β) : preimage h.symm = image h := (image_eq_preimage_of_inverse h.to_equiv.left_inv h.to_equiv.right_inv).symm lemma induced_eq {α : Type*} {β : Type*} [tα : topological_space α] [tβ : topological_space β] (h : α ≃ₜ β) : tβ.induced h = tα := le_antisymm (calc topological_space.induced ⇑h tβ ≤ _ : induced_mono (coinduced_le_iff_le_induced.1 h.symm.continuous) ... ≤ tα : by rw [induced_compose, symm_comp_self, induced_id] ; exact le_refl _) (coinduced_le_iff_le_induced.1 h.continuous) lemma coinduced_eq {α : Type*} {β : Type*} [tα : topological_space α] [tβ : topological_space β] (h : α ≃ₜ β) : tα.coinduced h = tβ := le_antisymm h.continuous begin have : (tβ.coinduced h.symm).coinduced h ≤ tα.coinduced h := coinduced_mono h.symm.continuous, rwa [coinduced_compose, self_comp_symm, coinduced_id] at this, end lemma compact_image {s : set α} (h : α ≃ₜ β) : compact (h '' s) ↔ compact s := ⟨λ hs, by have := compact_image hs h.symm.continuous; rwa [← image_comp, symm_comp_self, image_id] at this, λ hs, compact_image hs h.continuous⟩ lemma compact_preimage {s : set β} (h : α ≃ₜ β) : compact (h ⁻¹' s) ↔ compact s := by rw ← image_symm; exact h.symm.compact_image protected lemma embedding (h : α ≃ₜ β) : embedding h := ⟨h.to_equiv.injective, h.induced_eq.symm⟩ protected lemma dense_embedding (h : α ≃ₜ β) : dense_embedding h := { dense := assume a, by rw [h.range_coe, closure_univ]; trivial, inj := h.to_equiv.injective, induced := assume a, by rw [← nhds_induced_eq_comap, h.induced_eq] } protected lemma is_open_map (h : α ≃ₜ β) : is_open_map h := begin assume s, rw ← h.preimage_symm, exact h.symm.continuous s end protected lemma quotient_map (h : α ≃ₜ β) : quotient_map h := ⟨h.to_equiv.surjective, h.coinduced_eq.symm⟩ def prod_congr (h₁ : α ≃ₜ β) (h₂ : γ ≃ₜ δ) : (α × γ) ≃ₜ (β × δ) := { continuous_to_fun := continuous.prod_mk (h₁.continuous.comp continuous_fst) (h₂.continuous.comp continuous_snd), continuous_inv_fun := continuous.prod_mk (h₁.symm.continuous.comp continuous_fst) (h₂.symm.continuous.comp continuous_snd), .. h₁.to_equiv.prod_congr h₂.to_equiv } section variables (α β γ) def prod_comm : (α × β) ≃ₜ (β × α) := { continuous_to_fun := continuous.prod_mk continuous_snd continuous_fst, continuous_inv_fun := continuous.prod_mk continuous_snd continuous_fst, .. equiv.prod_comm α β } def prod_assoc : ((α × β) × γ) ≃ₜ (α × (β × γ)) := { continuous_to_fun := continuous.prod_mk (continuous_fst.comp continuous_fst) (continuous.prod_mk (continuous_snd.comp continuous_fst) continuous_snd), continuous_inv_fun := continuous.prod_mk (continuous.prod_mk continuous_fst (continuous_fst.comp continuous_snd)) (continuous_snd.comp continuous_snd), .. equiv.prod_assoc α β γ } end end homeomorph
4f16434fed28b5f55e250b0268cf3e22dfbe729b
6dc0c8ce7a76229dd81e73ed4474f15f88a9e294
/tests/lean/run/ac_expr.lean
7835a76ff21ae6e071806ee95c110b91c16e821a
[ "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
5,269
lean
import Std inductive Expr where | var (i : Nat) | op (lhs rhs : Expr) deriving Inhabited, Repr def List.getIdx : List α → Nat → α → α | [], i, u => u | a::as, 0, u => a | a::as, i+1, u => getIdx as i u structure Context (α : Type u) where op : α → α → α unit : α assoc : (a b c : α) → op (op a b) c = op a (op b c) comm : (a b : α) → op a b = op b a vars : List α theorem Context.left_comm (ctx : Context α) (a b c : α) : ctx.op a (ctx.op b c) = ctx.op b (ctx.op a c) := by rw [← ctx.assoc, ctx.comm a b, ctx.assoc] def Expr.denote (ctx : Context α) : Expr → α | Expr.op a b => ctx.op (denote ctx a) (denote ctx b) | Expr.var i => ctx.vars.getIdx i ctx.unit theorem Expr.denote_op (ctx : Context α) (a b : Expr) : denote ctx (Expr.op a b) = ctx.op (denote ctx a) (denote ctx b) := rfl def Expr.concat : Expr → Expr → Expr | Expr.op a b, c => Expr.op a (concat b c) | Expr.var i, c => Expr.op (Expr.var i) c theorem Expr.denote_concat (ctx : Context α) (a b : Expr) : denote ctx (concat a b) = denote ctx (Expr.op a b) := by induction a with | var i => rfl | op _ _ _ ih => simp [denote, ih, ctx.assoc] def Expr.flat : Expr → Expr | Expr.op a b => concat (flat a) (flat b) | Expr.var i => Expr.var i theorem Expr.denote_flat (ctx : Context α) (e : Expr) : denote ctx (flat e) = denote ctx e := by induction e with | Expr.var i => rfl | Expr.op a b ih₁ ih₂ => simp [flat, denote, denote_concat, ih₁, ih₂] theorem Expr.eq_of_flat (ctx : Context α) (a b : Expr) (h : flat a = flat b) : denote ctx a = denote ctx b := by have h := congrArg (denote ctx) h simp [denote_flat] at h assumption def Expr.length : Expr → Nat | op a b => 1 + b.length | _ => 1 def Expr.sort (e : Expr) : Expr := loop e.length e where loop : Nat → Expr → Expr | fuel+1, Expr.op a e => let (e₁, e₂) := swap a e Expr.op e₁ (loop fuel e₂) | _, e => e swap : Expr → Expr → Expr × Expr | Expr.var i, Expr.op (Expr.var j) e => if i > j then let (e₁, e₂) := swap (Expr.var j) e (e₁, Expr.op (Expr.var i) e₂) else let (e₁, e₂) := swap (Expr.var i) e (e₁, Expr.op (Expr.var j) e₂) | Expr.var i, Expr.var j => if i > j then (Expr.var j, Expr.var i) else (Expr.var i, Expr.var j) | e₁, e₂ => (e₁, e₂) theorem Expr.denote_sort (ctx : Context α) (e : Expr) : denote ctx (sort e) = denote ctx e := by apply denote_loop where denote_loop (n : Nat) (e : Expr) : denote ctx (sort.loop n e) = denote ctx e := by induction n generalizing e with | zero => rfl | succ n ih => match e with | var _ => rfl | op a b => simp [denote, sort.loop] match h:sort.swap a b with | (r₁, r₂) => have hs := denote_swap a b rw [h] at hs simp [denote] at hs simp [denote, ih] assumption denote_swap (e₁ e₂ : Expr) : denote ctx (Expr.op (sort.swap e₁ e₂).1 (sort.swap e₁ e₂).2) = denote ctx (Expr.op e₁ e₂) := by induction e₂ generalizing e₁ with | op a b ih' ih => clear ih' cases e₁ with | var i => cases a with | var j => byCases h : i > j focus simp [sort.swap, h] match h:sort.swap (var j) b with | (r₁, r₂) => simp; rw [denote_op (a := var i), ← ih]; simp [h, denote]; rw [Context.left_comm] focus simp [sort.swap, h] match h:sort.swap (var i) b with | (r₁, r₂) => simp rw [denote_op (a := var i), denote_op (a := var j), Context.left_comm, ← denote_op (a := var i), ← ih] simp [h, denote] rw [Context.left_comm] | _ => rfl | _ => rfl | var j => cases e₁ with | var i => byCases h : i > j focus simp [sort.swap, h, denote, Context.comm] focus simp [sort.swap, h] | _ => rfl theorem Expr.eq_of_sort_flat (ctx : Context α) (a b : Expr) (h : sort (flat a) = sort (flat b)) : denote ctx a = denote ctx b := by have h := congrArg (denote ctx) h simp [denote_flat, denote_sort] at h assumption theorem ex₁ (x₁ x₂ x₃ x₄ : Nat) : (x₁ + x₂) + (x₃ + x₄) = x₁ + x₂ + x₃ + x₄ := Expr.eq_of_flat { op := Nat.add assoc := Nat.add_assoc comm := Nat.add_comm unit := Nat.zero vars := [x₁, x₂, x₃, x₄] } (Expr.op (Expr.op (Expr.var 0) (Expr.var 1)) (Expr.op (Expr.var 2) (Expr.var 3))) (Expr.op (Expr.op (Expr.op (Expr.var 0) (Expr.var 1)) (Expr.var 2)) (Expr.var 3)) rfl theorem ex₂ (x₁ x₂ x₃ x₄ : Nat) : (x₁ + x₂) + (x₃ + x₄) = x₃ + x₁ + x₂ + x₄ := Expr.eq_of_sort_flat { op := Nat.add assoc := Nat.add_assoc comm := Nat.add_comm unit := Nat.zero vars := [x₁, x₂, x₃, x₄] } (Expr.op (Expr.op (Expr.var 0) (Expr.var 1)) (Expr.op (Expr.var 2) (Expr.var 3))) (Expr.op (Expr.op (Expr.op (Expr.var 2) (Expr.var 0)) (Expr.var 1)) (Expr.var 3)) rfl #print ex₂
40a38676cfd9a7f10ed7a297e146e3b007c0dc6d
5e60919d574b821fabd9387be5589c0c4d3f3fe2
/src/meta/tactic.lean
6667f94b99ded5d8338846e247c1af8bfb1ac0dc
[]
no_license
unitb/unitb-pointers
3fc72b873377a12e3f677ccd30143fc001a56c63
c057420c1e72bba00181bc6db30cf369ef2bfd23
refs/heads/master
1,629,969,967,065
1,511,386,892,000
1,511,386,892,000
110,323,164
0
0
null
null
null
null
UTF-8
Lean
false
false
1,610
lean
import util.control.monad namespace rb_map variables {k : Type} variables {α : Type} variables {β : Type} variables {γ : Type} variables [has_ordering k] private def list_zip_with (f : k → α → β → γ) : list (k × α) → list (k × β) → list (k × γ) | ((k₀,x)::xs) ((k₁,y)::ys) := match has_ordering.cmp k₀ k₁ with | ordering.gt := list_zip_with xs ((k₁,y)::ys) | ordering.lt := list_zip_with ((k₀,x)::xs) ys | ordering.eq := (k₀,f k₀ x y) :: list_zip_with xs ys end | _ _ := [ ] meta def zip_with (f : k → α → β → γ) (m₀ : rb_map k α) (m₁ : rb_map k β) : rb_map k γ := rb_map.of_list (list_zip_with f m₀.to_list m₁.to_list) end rb_map namespace lean.parser open lean list nat applicative variables {α : Type} meta def sep_by1 (sep : parser unit) (p : parser α) : parser (list α) := cons <$> p <*> many (sep *> p) meta def sep_by_exactly : ℕ → parser unit → parser α → parser (list α) | 0 _ _ := pure [ ] | (succ n) s p := (::) <$> p <*> replicate n (s *> p) end lean.parser meta def name.primed : name → name | (name.mk_string x y) := name.mk_string (x ++ "'") y | x := x meta def name.unprimed : name → name | (name.mk_string x y) := name.mk_string x.pop_back y | x := x namespace tactic meta def trace_type (tag : string) (e : expr) : tactic unit := do e' ← tactic.pp e, t' ← infer_type e >>= tactic.pp, trace format!"* {tag} \n - {e'} \n : {t'}" meta def primed_local : expr → tactic expr | (expr.local_const _ n bi t) := mk_local' n.primed bi t | _ := fail "not a local constant" end tactic
e72a997b95a22664ad3f1a694ac28621468a662c
205f0fc16279a69ea36e9fd158e3a97b06834ce2
/src/00_Introduction/04_axioms.lean
f414a540b9241e56499aa6633efc71a3c1707c8a
[]
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
6,819
lean
/- *** Axioms *** -/ /- In a mathematical or logical system, some propositions are taken to be true unconditionally: without the need for any prior "input" proofs. An inference rule that requires no proof inputs, and that nevertheless lets you judge some proposition to be true, is called an axiom. We also use the term, axiom, to refer to the proposition that is the conclusion of the rule, and that is thereby judged true unconditionally. An axiom viewed as an inference rule with no proofs/judgements as inputs would be written with no proof/judgment premises/arguments above the line. For example, if we were to take the proposition, 0 = 0, as an axiom, we could write it like this: <---- note the absence of premises ----- 0 = 0 What this says then is that without having proved or judged any other propositions to be true you can nevertheless assume that 0 = 0 is true. Equivalently, without providing any proofs of other propositions as arguments, this rule will still hand you back a proof of 0 = 0, thereby justifying the judgment that 0 = 0 is true. In this case, you could say that the logic includes 0 = 0 as an axiom. -/ /- It would not be convenient, however, to include a separate axiom in a logic for every individual natural number. We'd end up with an infinity of such axioms, and that would be problematical for the definition of the semantics of the logic. What we would like is to have a single inference rule that covers an infinity of special cases. Indeed, we'd like to have a rule that defines that everything is equal to itself, not matter what value, or what type of value it is. -/ /- ** An inference rule for equality in general ** -/ /- Intuitively you would suppose that the proposition, 0 = 0, should be true in any reasonable logical system. There are two ways a logic could make this happen. The first is that the logic could provide 0 = 0 as an axiom, as we just discussed. That'd be ok, but then we'd need similar axioms for every other number. We'd also need similar axioms for every object of every other type: person, car, plant, atom, book, idea, etc. We end up with a pretty unwieldy (and infinite) set of axioms. Moreover, if we were ever to define a new type of objects (e.g., digital pets), we'd have to extend the logic with similar inference rules for every value of the new type. (Fido = Fido, Spot = Spot, Kitty = Kitty, etc). What would be much better would be to have just one inference rule that basically allow us to conclude that *any* object, or value, of any type whatsoever is always equal to itself (and that nothing else is ever equal to that object). It'd go something like this: if T is any "type" (such as natural number, car, person), and t is any object or value of that type, T (e.g., 0 is a value of type "natural number", or "nat"), then you can unconditionally conclude that t = t is true. We could write this inference rule something like this: T: Type, t : T -------------- (eq.refl) pf: t = t In English, "if you're given that T is a (any) type and t is a value of that type, then the eq_reflexive inference rule derives a proof of t = t. In informal English, you could say, 'for any t (of any type_, t = t by the reflexive property of equality". So there: *that* is the fundamental reason why 0 = 0. It's an essential property of the equality relation (on any type). (Detail: This notion of equality is called Leibniz equality.) EXERCISE: Why exactly can this rule never be used to derive a proof of the proposition that 0 = 1? -/ /- * Type judgments * -/ /- Above the line in this inference rule, we meet a new kind of judgment here: a type judgment. If X is some type, and x is a value of that type, X, we can denote this fact by writing x : X. We read this as "x is of type X." -/ /- * The types of types * -/ /- The Lean tool that you're using here is based on a foundational theory called type theory. In type theory, every object (or value) has a single type. Every parameter, such as an argument to a function. has a type. Every expression has a type. In Lean you can check the type of an expression by using the #check command. Note that ℕ is math shorthand for the type of natural numbers, i.e., non-negative integers (thus zero on up). Hover your mouse over the #check commands to see what are the types of 0, "Hi!", and tt in Lean. -/ #check 0 #check "Hi!" #check tt /- Here's the key idea: types are values, too! It thus follows that a type must have a type. So what is the type of a type? Answer: If T is a type, then it's type is called "Type". -/ /- EXERCISE: Use the #check command the see what is the type of nat, bool, and string. -/ /- So, if T is some type, then we'd write the type judgment, "T : Type". And if T is a type, and t a value of type, T, then we'd also write t : T. -/ /- With all that out of the way, we can once again write and now more fully understand the inference rule for equality that we really want. T: Type, t : T -------------- (eq-reflexive) pf: t = t Those are now type judgments above the line. You can understand this inference rule as saying this: "if you give me a T that is a type (e.g., bool, nat, string), and if you also give me a value, t, of type, T, (e.g., 0 or true), then I will give you back a proof that t = t. This single inference rule thus defines a very sensible notion of equality for all values of all types that exist or might ever be defined. So now, rather than a separate axiom for 0 = 0, another one for 1 = 1, another for true = true, and yet another for Fido = Fido, so forth, we now have a single inference rule that gives them all just as special cases. We are given this inference rule as something close to an axiom, in the sense that the only "proofs" it requires requires as inputs are proofs that T is a type and t is a value of that type. Where do these proofs come from? They come from the Lean type checker! Now as we've seen, give a value, t, of some type, T, Lean can tell us what T is. The #check command tells us the type of any value or expression. This is helpful because it means that in principle, we could re-write the inference rule as follows, where the curly braces around { T : Type } means that we don't have to give a value of T explicitly when we apply the eq-reflexivity inference rule, because T can be inferred from t. { T: Type }, t: T ----------------- (eq-refl) pf: t = t In Lean, the eq-reflexivity rule is formalized in this way and is called eq.refl. It takes one value, t, infers T from it, and returns a proof that that t equals itself! -/ #check eq.refl 0 -- rfl #check eq.refl "Hello Lean!" #check eq.refl tt #check eq.refl bool -- even types are values #check eq.refl (0 = 0) -- including propositions!
3bb455cc2b4e3263fe9fe3ce9998b0c2ae4a386c
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/tactic2.lean
fc8664d6834fc8a96917d670d9f1dac6130d3bb8
[ "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
108
lean
import logic open tactic theorem tst {A B : Prop} (H1 : A) (H2 : B) : A := by state; assumption check tst
9dc2fea82d48c8eea0e814bb1b43dcdf88ac0d3d
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/assert_tac1.lean
b49179aad1b3aba04a0dc58abae614bfc6dc0b82
[ "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
607
lean
open tactic definition tst1 (a : nat) : a = a := by do define `x (expr.const `nat []), trace_state, a ← get_local `a, exact a, x ← get_local `x, mk_app `eq.refl [x] >>= exact #print tst1 definition tst2 (a : nat) : a = a := by do define `x (expr.const `nat []), a ← get_local `a, exact a, trace "------------", trace_state, get_local `x >>= revert, intro `y, trace_state, y ← get_local `y, mk_app `eq.refl [y] >>= exact #print tst2 definition tst3 (a : nat) : a = a := begin let x : nat, exact a, revert x, intro y, apply eq.refl y end
1ef1133617388b3016a96bb021f33d3320d3e39d
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/topology/algebra/group_auto.lean
320c9d1ce28ec3b194e2100d501fc06fcc7c85fc
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
20,211
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Patrick Massot -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.order.filter.pointwise import Mathlib.group_theory.quotient_group import Mathlib.topology.algebra.monoid import Mathlib.topology.homeomorph import Mathlib.PostPort universes w u l u_1 x u_2 namespace Mathlib /-! # Theory of topological groups This file defines the following typeclasses: * `topological_group`, `topological_add_group`: multiplicative and additive topological groups, i.e., groups with continuous `(*)` and `(⁻¹)` / `(+)` and `(-)`; * `has_continuous_sub G` means that `G` has a continuous subtraction operation. There is an instance deducing `has_continuous_sub` from `topological_group` but we use a separate typeclass because, e.g., `ℕ` and `ℝ≥0` have continuous subtraction but are not additive groups. We also define `homeomorph` versions of several `equiv`s: `homeomorph.mul_left`, `homeomorph.mul_right`, `homeomorph.inv`, and prove a few facts about neighbourhood filters in groups. ## Tags topological space, group, topological group -/ /-! ### Groups with continuous multiplication In this section we prove a few statements about groups with continuous `(*)`. -/ /-- Multiplication from the left in a topological group as a homeomorphism. -/ protected def homeomorph.add_left {G : Type w} [topological_space G] [add_group G] [has_continuous_add G] (a : G) : G ≃ₜ G := homeomorph.mk (equiv.mk (equiv.to_fun (equiv.add_left a)) (equiv.inv_fun (equiv.add_left a)) sorry sorry) @[simp] theorem homeomorph.coe_mul_left {G : Type w} [topological_space G] [group G] [has_continuous_mul G] (a : G) : ⇑(homeomorph.mul_left a) = Mul.mul a := rfl theorem homeomorph.add_left_symm {G : Type w} [topological_space G] [add_group G] [has_continuous_add G] (a : G) : homeomorph.symm (homeomorph.add_left a) = homeomorph.add_left (-a) := homeomorph.ext fun (x : G) => Eq.refl (coe_fn (homeomorph.symm (homeomorph.add_left a)) x) theorem is_open_map_mul_left {G : Type w} [topological_space G] [group G] [has_continuous_mul G] (a : G) : is_open_map fun (x : G) => a * x := homeomorph.is_open_map (homeomorph.mul_left a) theorem is_closed_map_mul_left {G : Type w} [topological_space G] [group G] [has_continuous_mul G] (a : G) : is_closed_map fun (x : G) => a * x := homeomorph.is_closed_map (homeomorph.mul_left a) /-- Multiplication from the right in a topological group as a homeomorphism. -/ protected def homeomorph.mul_right {G : Type w} [topological_space G] [group G] [has_continuous_mul G] (a : G) : G ≃ₜ G := homeomorph.mk (equiv.mk (equiv.to_fun (equiv.mul_right a)) (equiv.inv_fun (equiv.mul_right a)) sorry sorry) theorem is_open_map_add_right {G : Type w} [topological_space G] [add_group G] [has_continuous_add G] (a : G) : is_open_map fun (x : G) => x + a := homeomorph.is_open_map (homeomorph.add_right a) theorem is_closed_map_mul_right {G : Type w} [topological_space G] [group G] [has_continuous_mul G] (a : G) : is_closed_map fun (x : G) => x * a := homeomorph.is_closed_map (homeomorph.mul_right a) theorem is_open_map_div_right {G : Type w} [topological_space G] [group G] [has_continuous_mul G] (a : G) : is_open_map fun (x : G) => x / a := sorry theorem is_closed_map_div_right {G : Type w} [topological_space G] [group G] [has_continuous_mul G] (a : G) : is_closed_map fun (x : G) => x / a := sorry /-! ### Topological groups A topological group is a group in which the multiplication and inversion operations are continuous. Topological additive groups are defined in the same way. Equivalently, we can require that the division operation `λ x y, x * y⁻¹` (resp., subtraction) is continuous. -/ /-- A topological (additive) group is a group in which the addition and negation operations are continuous. -/ class topological_add_group (G : Type u) [topological_space G] [add_group G] extends has_continuous_add G where continuous_neg : continuous fun (a : G) => -a /-- A topological group is a group in which the multiplication and inversion operations are continuous. -/ class topological_group (G : Type u_1) [topological_space G] [group G] extends has_continuous_mul G where continuous_inv : continuous has_inv.inv theorem continuous_on_neg {G : Type w} [topological_space G] [add_group G] [topological_add_group G] {s : set G} : continuous_on Neg.neg s := continuous.continuous_on continuous_neg theorem continuous_within_at_neg {G : Type w} [topological_space G] [add_group G] [topological_add_group G] {s : set G} {x : G} : continuous_within_at Neg.neg s x := continuous.continuous_within_at continuous_neg theorem continuous_at_inv {G : Type w} [topological_space G] [group G] [topological_group G] {x : G} : continuous_at has_inv.inv x := continuous.continuous_at continuous_inv theorem tendsto_neg {G : Type w} [topological_space G] [add_group G] [topological_add_group G] (a : G) : filter.tendsto Neg.neg (nhds a) (nhds (-a)) := continuous_at_neg /-- If a function converges to a value in a multiplicative topological group, then its inverse converges to the inverse of this value. For the version in normed fields assuming additionally that the limit is nonzero, use `tendsto.inv'`. -/ theorem filter.tendsto.inv {α : Type u} {G : Type w} [topological_space G] [group G] [topological_group G] {f : α → G} {l : filter α} {y : G} (h : filter.tendsto f l (nhds y)) : filter.tendsto (fun (x : α) => f x⁻¹) l (nhds (y⁻¹)) := filter.tendsto.comp (continuous.tendsto continuous_inv y) h theorem continuous.inv {α : Type u} {G : Type w} [topological_space G] [group G] [topological_group G] [topological_space α] {f : α → G} (hf : continuous f) : continuous fun (x : α) => f x⁻¹ := continuous.comp continuous_inv hf theorem continuous_on.inv {α : Type u} {G : Type w} [topological_space G] [group G] [topological_group G] [topological_space α] {f : α → G} {s : set α} (hf : continuous_on f s) : continuous_on (fun (x : α) => f x⁻¹) s := continuous.comp_continuous_on continuous_inv hf theorem continuous_within_at.inv {α : Type u} {G : Type w} [topological_space G] [group G] [topological_group G] [topological_space α] {f : α → G} {s : set α} {x : α} (hf : continuous_within_at f s x) : continuous_within_at (fun (x : α) => f x⁻¹) s x := filter.tendsto.inv hf protected instance prod.topological_add_group {G : Type w} {H : Type x} [topological_space G] [add_group G] [topological_add_group G] [topological_space H] [add_group H] [topological_add_group H] : topological_add_group (G × H) := topological_add_group.mk (continuous.prod_map continuous_neg continuous_neg) /-- Inversion in a topological group as a homeomorphism. -/ protected def homeomorph.neg (G : Type w) [topological_space G] [add_group G] [topological_add_group G] : G ≃ₜ G := homeomorph.mk (equiv.mk (equiv.to_fun (equiv.neg G)) (equiv.inv_fun (equiv.neg G)) sorry sorry) theorem nhds_zero_symm (G : Type w) [topological_space G] [add_group G] [topological_add_group G] : filter.comap Neg.neg (nhds 0) = nhds 0 := Eq.trans (homeomorph.comap_nhds_eq (homeomorph.neg G) 0) (congr_arg nhds neg_zero) /-- The map `(x, y) ↦ (x, xy)` as a homeomorphism. This is a shear mapping. -/ protected def homeomorph.shear_add_right (G : Type w) [topological_space G] [add_group G] [topological_add_group G] : G × G ≃ₜ G × G := homeomorph.mk (equiv.mk (equiv.to_fun (equiv.prod_shear (equiv.refl G) equiv.add_left)) (equiv.inv_fun (equiv.prod_shear (equiv.refl G) equiv.add_left)) sorry sorry) @[simp] theorem homeomorph.shear_mul_right_coe (G : Type w) [topological_space G] [group G] [topological_group G] : ⇑(homeomorph.shear_mul_right G) = fun (z : G × G) => (prod.fst z, prod.fst z * prod.snd z) := rfl @[simp] theorem homeomorph.shear_mul_right_symm_coe (G : Type w) [topological_space G] [group G] [topological_group G] : ⇑(homeomorph.symm (homeomorph.shear_mul_right G)) = fun (z : G × G) => (prod.fst z, prod.fst z⁻¹ * prod.snd z) := rfl theorem inv_closure {G : Type w} [topological_space G] [group G] [topological_group G] (s : set G) : closure s⁻¹ = closure (s⁻¹) := homeomorph.preimage_closure (homeomorph.inv G) s theorem exists_nhds_half_neg {G : Type w} [topological_space G] [add_group G] [topological_add_group G] {s : set G} (hs : s ∈ nhds 0) : ∃ (V : set G), ∃ (H : V ∈ nhds 0), ∀ (v : G), v ∈ V → ∀ (w : G), w ∈ V → v - w ∈ s := sorry theorem nhds_translation_mul_inv {G : Type w} [topological_space G] [group G] [topological_group G] (x : G) : filter.comap (fun (y : G) => y * (x⁻¹)) (nhds 1) = nhds x := sorry @[simp] theorem map_mul_left_nhds {G : Type w} [topological_space G] [group G] [topological_group G] (x : G) (y : G) : filter.map (Mul.mul x) (nhds y) = nhds (x * y) := homeomorph.map_nhds_eq (homeomorph.mul_left x) y theorem map_mul_left_nhds_one {G : Type w} [topological_space G] [group G] [topological_group G] (x : G) : filter.map (Mul.mul x) (nhds 1) = nhds x := sorry theorem topological_group.ext {G : Type u_1} [group G] {t : topological_space G} {t' : topological_space G} (tg : topological_group G) (tg' : topological_group G) (h : nhds 1 = nhds 1) : t = t' := sorry theorem topological_group.of_nhds_aux {G : Type u_1} [group G] [topological_space G] (hinv : filter.tendsto (fun (x : G) => x⁻¹) (nhds 1) (nhds 1)) (hleft : ∀ (x₀ : G), nhds x₀ = filter.map (fun (x : G) => x₀ * x) (nhds 1)) (hconj : ∀ (x₀ : G), filter.map (fun (x : G) => x₀ * x * (x₀⁻¹)) (nhds 1) ≤ nhds 1) : continuous fun (x : G) => x⁻¹ := sorry theorem topological_add_group.of_nhds_zero' {G : Type (max u_1 u_2)} [add_group G] [topological_space G] (hmul : filter.tendsto (function.uncurry Add.add) (filter.prod (nhds 0) (nhds 0)) (nhds 0)) (hinv : filter.tendsto (fun (x : G) => -x) (nhds 0) (nhds 0)) (hleft : ∀ (x₀ : G), nhds x₀ = filter.map (fun (x : G) => x₀ + x) (nhds 0)) (hright : ∀ (x₀ : G), nhds x₀ = filter.map (fun (x : G) => x + x₀) (nhds 0)) : topological_add_group G := sorry theorem topological_add_group.of_nhds_zero {G : Type (max u_1 u_2)} [add_group G] [topological_space G] (hmul : filter.tendsto (function.uncurry Add.add) (filter.prod (nhds 0) (nhds 0)) (nhds 0)) (hinv : filter.tendsto (fun (x : G) => -x) (nhds 0) (nhds 0)) (hleft : ∀ (x₀ : G), nhds x₀ = filter.map (fun (x : G) => x₀ + x) (nhds 0)) (hconj : ∀ (x₀ : G), filter.tendsto (fun (x : G) => x₀ + x + -x₀) (nhds 0) (nhds 0)) : topological_add_group G := topological_add_group.mk (topological_add_group.of_nhds_aux hinv hleft hconj) theorem topological_add_group.of_comm_of_nhds_zero {G : Type (max u_1 u_2)} [add_comm_group G] [topological_space G] (hmul : filter.tendsto (function.uncurry Add.add) (filter.prod (nhds 0) (nhds 0)) (nhds 0)) (hinv : filter.tendsto (fun (x : G) => -x) (nhds 0) (nhds 0)) (hleft : ∀ (x₀ : G), nhds x₀ = filter.map (fun (x : G) => x₀ + x) (nhds 0)) : topological_add_group G := sorry protected instance quotient_group.quotient.topological_space {G : Type u_1} [group G] [topological_space G] (N : subgroup G) : topological_space (quotient_group.quotient N) := quotient.topological_space theorem quotient_group.is_open_map_coe {G : Type w} [topological_space G] [group G] [topological_group G] (N : subgroup G) : is_open_map coe := sorry protected instance topological_add_group_quotient {G : Type w} [topological_space G] [add_group G] [topological_add_group G] (N : add_subgroup G) [add_subgroup.normal N] : topological_add_group (quotient_add_group.quotient N) := topological_add_group.mk (eq.mpr ((fun (f f_1 : quotient_add_group.quotient N → quotient_add_group.quotient N) (e_3 : f = f_1) => congr_arg continuous e_3) Neg.neg (quotient.lift (coe ∘ fun (a : G) => -a) (quotient_add_group.div_inv_monoid._proof_5 N)) (Eq.refl Neg.neg)) (continuous_quotient_lift (quotient_add_group.div_inv_monoid._proof_5 N) (continuous.comp continuous_quot_mk continuous_neg))) /-- A typeclass saying that `λ p : G × G, p.1 - p.2` is a continuous function. This property automatically holds for topological additive groups but it also holds, e.g., for `ℝ≥0`. -/ class has_continuous_sub (G : Type u_1) [topological_space G] [Sub G] where continuous_sub : continuous fun (p : G × G) => prod.fst p - prod.snd p protected instance topological_add_group.to_has_continuous_sub {G : Type w} [topological_space G] [add_group G] [topological_add_group G] : has_continuous_sub G := has_continuous_sub.mk (eq.mpr (id ((fun (f f_1 : G × G → G) (e_3 : f = f_1) => congr_arg continuous e_3) (fun (p : G × G) => prod.fst p - prod.snd p) (fun (p : G × G) => prod.fst p + -prod.snd p) (funext fun (p : G × G) => sub_eq_add_neg (prod.fst p) (prod.snd p)))) (continuous.add continuous_fst (continuous.neg continuous_snd))) theorem filter.tendsto.sub {α : Type u} {G : Type w} [topological_space G] [Sub G] [has_continuous_sub G] {f : α → G} {g : α → G} {l : filter α} {a : G} {b : G} (hf : filter.tendsto f l (nhds a)) (hg : filter.tendsto g l (nhds b)) : filter.tendsto (fun (x : α) => f x - g x) l (nhds (a - b)) := filter.tendsto.comp (continuous.tendsto continuous_sub (a, b)) (filter.tendsto.prod_mk_nhds hf hg) theorem continuous.sub {α : Type u} {G : Type w} [topological_space G] [Sub G] [has_continuous_sub G] [topological_space α] {f : α → G} {g : α → G} (hf : continuous f) (hg : continuous g) : continuous fun (x : α) => f x - g x := continuous.comp continuous_sub (continuous.prod_mk hf hg) theorem continuous_within_at.sub {α : Type u} {G : Type w} [topological_space G] [Sub G] [has_continuous_sub G] [topological_space α] {f : α → G} {g : α → G} {s : set α} {x : α} (hf : continuous_within_at f s x) (hg : continuous_within_at g s x) : continuous_within_at (fun (x : α) => f x - g x) s x := filter.tendsto.sub hf hg theorem continuous_on.sub {α : Type u} {G : Type w} [topological_space G] [Sub G] [has_continuous_sub G] [topological_space α] {f : α → G} {g : α → G} {s : set α} (hf : continuous_on f s) (hg : continuous_on g s) : continuous_on (fun (x : α) => f x - g x) s := fun (x : α) (hx : x ∈ s) => continuous_within_at.sub (hf x hx) (hg x hx) theorem nhds_translation {G : Type w} [topological_space G] [add_group G] [topological_add_group G] (x : G) : filter.comap (fun (y : G) => y - x) (nhds 0) = nhds x := sorry /-- additive group with a neighbourhood around 0. Only used to construct a topology and uniform space. This is currently only available for commutative groups, but it can be extended to non-commutative groups too. -/ class add_group_with_zero_nhd (G : Type u) extends add_comm_group G where Z : filter G zero_Z : pure 0 ≤ Z sub_Z : filter.tendsto (fun (p : G × G) => prod.fst p - prod.snd p) (filter.prod Z Z) Z namespace add_group_with_zero_nhd protected instance topological_space (G : Type w) [add_group_with_zero_nhd G] : topological_space G := topological_space.mk_of_nhds fun (a : G) => filter.map (fun (x : G) => x + a) (Z G) theorem neg_Z {G : Type w} [add_group_with_zero_nhd G] : filter.tendsto (fun (a : G) => -a) (Z G) (Z G) := sorry theorem add_Z {G : Type w} [add_group_with_zero_nhd G] : filter.tendsto (fun (p : G × G) => prod.fst p + prod.snd p) (filter.prod (Z G) (Z G)) (Z G) := sorry theorem exists_Z_half {G : Type w} [add_group_with_zero_nhd G] {s : set G} (hs : s ∈ Z G) : ∃ (V : set G), ∃ (H : V ∈ Z G), ∀ (v : G), v ∈ V → ∀ (w : G), w ∈ V → v + w ∈ s := sorry theorem nhds_eq {G : Type w} [add_group_with_zero_nhd G] (a : G) : nhds a = filter.map (fun (x : G) => x + a) (Z G) := sorry theorem nhds_zero_eq_Z {G : Type w} [add_group_with_zero_nhd G] : nhds 0 = Z G := sorry protected instance has_continuous_add {G : Type w} [add_group_with_zero_nhd G] : has_continuous_add G := has_continuous_add.mk (iff.mpr continuous_iff_continuous_at fun (_x : G × G) => sorry) protected instance topological_add_group {G : Type w} [add_group_with_zero_nhd G] : topological_add_group G := sorry end add_group_with_zero_nhd theorem is_open.add_left {G : Type w} [topological_space G] [add_group G] [topological_add_group G] {s : set G} {t : set G} : is_open t → is_open (s + t) := fun (ht : is_open t) => eq.mpr (id (Eq._oldrec (Eq.refl (is_open (s + t))) (Eq.symm set.Union_add_left_image))) (is_open_Union fun (a : G) => is_open_Union fun (ha : a ∈ s) => (fun (a : G) => is_open_map_add_left a t ht) a) theorem is_open.add_right {G : Type w} [topological_space G] [add_group G] [topological_add_group G] {s : set G} {t : set G} : is_open s → is_open (s + t) := fun (hs : is_open s) => eq.mpr (id (Eq._oldrec (Eq.refl (is_open (s + t))) (Eq.symm set.Union_add_right_image))) (is_open_Union fun (a : G) => is_open_Union fun (ha : a ∈ t) => (fun (a : G) => is_open_map_add_right a s hs) a) theorem topological_group.t1_space (G : Type w) [topological_space G] [group G] [topological_group G] (h : is_closed (singleton 1)) : t1_space G := sorry theorem topological_group.regular_space (G : Type w) [topological_space G] [group G] [topological_group G] [t1_space G] : regular_space G := sorry theorem topological_group.t2_space (G : Type w) [topological_space G] [group G] [topological_group G] [t1_space G] : t2_space G := regular_space.t2_space G /-! Some results about an open set containing the product of two sets in a topological group. -/ /-- Given a compact set `K` inside an open set `U`, there is a open neighborhood `V` of `1` such that `KV ⊆ U`. -/ theorem compact_open_separated_add {G : Type w} [topological_space G] [add_group G] [topological_add_group G] {K : set G} {U : set G} (hK : is_compact K) (hU : is_open U) (hKU : K ⊆ U) : ∃ (V : set G), is_open V ∧ 0 ∈ V ∧ K + V ⊆ U := sorry /-- A compact set is covered by finitely many left multiplicative translates of a set with non-empty interior. -/ theorem compact_covered_by_add_left_translates {G : Type w} [topological_space G] [add_group G] [topological_add_group G] {K : set G} {V : set G} (hK : is_compact K) (hV : set.nonempty (interior V)) : ∃ (t : finset G), K ⊆ set.Union fun (g : G) => set.Union fun (H : g ∈ t) => (fun (h : G) => g + h) ⁻¹' V := sorry /-- Every locally compact separable topological group is σ-compact. Note: this is not true if we drop the topological group hypothesis. -/ protected instance separable_locally_compact_group.sigma_compact_space {G : Type w} [topological_space G] [group G] [topological_group G] [topological_space.separable_space G] [locally_compact_space G] : sigma_compact_space G := sorry theorem nhds_add {G : Type w} [topological_space G] [add_comm_group G] [topological_add_group G] (x : G) (y : G) : nhds (x + y) = nhds x + nhds y := sorry theorem nhds_is_mul_hom {G : Type w} [topological_space G] [comm_group G] [topological_group G] : is_mul_hom fun (x : G) => nhds x := is_mul_hom.mk fun (_x _x_1 : G) => nhds_mul _x _x_1 protected instance additive.topological_add_group {G : Type u_1} [h : topological_space G] [group G] [topological_group G] : topological_add_group (additive G) := topological_add_group.mk continuous_inv protected instance multiplicative.topological_group {G : Type u_1} [h : topological_space G] [add_group G] [topological_add_group G] : topological_group (multiplicative G) := topological_group.mk continuous_neg end Mathlib
5de4ebaa304e474c70174347db3c2b3904d4b6a0
947b78d97130d56365ae2ec264df196ce769371a
/stage0/src/Init/Control/Alternative.lean
40aec814af5625986c05904ca326d366d461be3c
[ "Apache-2.0" ]
permissive
shyamalschandra/lean4
27044812be8698f0c79147615b1d5090b9f4b037
6e7a883b21eaf62831e8111b251dc9b18f40e604
refs/heads/master
1,671,417,126,371
1,601,859,995,000
1,601,860,020,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,005
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ prelude import Init.Core import Init.Control.Applicative universes u v class Alternative (f : Type u → Type v) extends Applicative f : Type (max (u+1) v) := (failure : ∀ {α : Type u}, f α) (orelse : ∀ {α : Type u}, f α → f α → f α) instance alternativeHasOrelse (f : Type u → Type v) (α : Type u) [Alternative f] : HasOrelse (f α) := ⟨Alternative.orelse⟩ section variables {f : Type u → Type v} [Alternative f] {α : Type u} export Alternative (failure) @[inline] def guard {f : Type → Type v} [Alternative f] (p : Prop) [Decidable p] : f Unit := if p then pure () else failure @[inline] def assert {f : Type → Type v} [Alternative f] (p : Prop) [Decidable p] : f (Inhabited p) := if h : p then pure ⟨h⟩ else failure @[inline] def optional (x : f α) : f (Option α) := some <$> x <|> pure none end
e4593da16c3c0a1fc6acd65e9a3e7cc2c2c52ed1
9dc8cecdf3c4634764a18254e94d43da07142918
/src/set_theory/cardinal/cofinality.lean
595e1b1fcf498436a0db4a1b54a98b8f097bad1e
[ "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
45,773
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Floris van Doorn, Violeta Hernández Palacios -/ import set_theory.cardinal.ordinal import set_theory.ordinal.fixed_point /-! # Cofinality This file contains the definition of cofinality of an ordinal number and regular cardinals ## Main Definitions * `ordinal.cof o` is the cofinality of the ordinal `o`. If `o` is the order type of the relation `<` on `α`, then `o.cof` is the smallest cardinality of a subset `s` of α that is *cofinal* in `α`, i.e. `∀ x : α, ∃ y ∈ s, ¬ y < x`. * `cardinal.is_limit c` means that `c` is a (weak) limit cardinal: `c ≠ 0 ∧ ∀ x < c, succ x < c`. * `cardinal.is_strong_limit c` means that `c` is a strong limit cardinal: `c ≠ 0 ∧ ∀ x < c, 2 ^ x < c`. * `cardinal.is_regular c` means that `c` is a regular cardinal: `ℵ₀ ≤ c ∧ c.ord.cof = c`. * `cardinal.is_inaccessible c` means that `c` is strongly inaccessible: `ℵ₀ < c ∧ is_regular c ∧ is_strong_limit c`. ## Main Statements * `ordinal.infinite_pigeonhole_card`: the infinite pigeonhole principle * `cardinal.lt_power_cof`: A consequence of König's theorem stating that `c < c ^ c.ord.cof` for `c ≥ ℵ₀` * `cardinal.univ_inaccessible`: The type of ordinals in `Type u` form an inaccessible cardinal (in `Type v` with `v > u`). This shows (externally) that in `Type u` there are at least `u` inaccessible cardinals. ## Implementation Notes * The cofinality is defined for ordinals. If `c` is a cardinal number, its cofinality is `c.ord.cof`. ## Tags cofinality, regular cardinals, limits cardinals, inaccessible cardinals, infinite pigeonhole principle -/ noncomputable theory open function cardinal set order open_locale classical cardinal ordinal universes u v w variables {α : Type*} {r : α → α → Prop} /-! ### Cofinality of orders -/ namespace order /-- Cofinality of a reflexive order `≼`. This is the smallest cardinality of a subset `S : set α` such that `∀ a, ∃ b ∈ S, a ≼ b`. -/ def cof (r : α → α → Prop) : cardinal := Inf {c | ∃ S : set α, (∀ a, ∃ b ∈ S, r a b) ∧ #S = c} /-- The set in the definition of `order.cof` is nonempty. -/ theorem cof_nonempty (r : α → α → Prop) [is_refl α r] : {c | ∃ S : set α, (∀ a, ∃ b ∈ S, r a b) ∧ #S = c}.nonempty := ⟨_, set.univ, λ a, ⟨a, ⟨⟩, refl _⟩, rfl⟩ lemma cof_le (r : α → α → Prop) {S : set α} (h : ∀ a, ∃ b ∈ S, r a b) : cof r ≤ #S := cInf_le' ⟨S, h, rfl⟩ lemma le_cof {r : α → α → Prop} [is_refl α r] (c : cardinal) : c ≤ cof r ↔ ∀ {S : set α}, (∀ a, ∃ b ∈ S, r a b) → c ≤ #S := begin rw [cof, le_cInf_iff'' (cof_nonempty r)], use λ H S h, H _ ⟨S, h, rfl⟩, rintro H d ⟨S, h, rfl⟩, exact H h end end order theorem rel_iso.cof_le_lift {α : Type u} {β : Type v} {r : α → α → Prop} {s} [is_refl β s] (f : r ≃r s) : cardinal.lift.{max u v} (order.cof r) ≤ cardinal.lift.{max u v} (order.cof s) := begin rw [order.cof, order.cof, lift_Inf, lift_Inf, le_cInf_iff'' (nonempty_image_iff.2 (order.cof_nonempty s))], rintros - ⟨-, ⟨u, H, rfl⟩, rfl⟩, apply cInf_le', refine ⟨_, ⟨f.symm '' u, λ a, _, rfl⟩, lift_mk_eq.{u v (max u v)}.2 ⟨((f.symm).to_equiv.image u).symm⟩⟩, rcases H (f a) with ⟨b, hb, hb'⟩, refine ⟨f.symm b, mem_image_of_mem _ hb, f.map_rel_iff.1 _⟩, rwa rel_iso.apply_symm_apply end theorem rel_iso.cof_eq_lift {α : Type u} {β : Type v} {r s} [is_refl α r] [is_refl β s] (f : r ≃r s) : cardinal.lift.{max u v} (order.cof r) = cardinal.lift.{max u v} (order.cof s) := (rel_iso.cof_le_lift f).antisymm (rel_iso.cof_le_lift f.symm) theorem rel_iso.cof_le {α β : Type u} {r : α → α → Prop} {s} [is_refl β s] (f : r ≃r s) : order.cof r ≤ order.cof s := lift_le.1 (rel_iso.cof_le_lift f) theorem rel_iso.cof_eq {α β : Type u} {r s} [is_refl α r] [is_refl β s] (f : r ≃r s) : order.cof r = order.cof s := lift_inj.1 (rel_iso.cof_eq_lift f) /-- Cofinality of a strict order `≺`. This is the smallest cardinality of a set `S : set α` such that `∀ a, ∃ b ∈ S, ¬ b ≺ a`. -/ def strict_order.cof (r : α → α → Prop) : cardinal := order.cof (swap r)ᶜ /-- The set in the definition of `order.strict_order.cof` is nonempty. -/ theorem strict_order.cof_nonempty (r : α → α → Prop) [is_irrefl α r] : {c | ∃ S : set α, unbounded r S ∧ #S = c}.nonempty := @order.cof_nonempty α _ (is_refl.swap rᶜ) /-! ### Cofinality of ordinals -/ namespace ordinal /-- Cofinality of an ordinal. This is the smallest cardinal of a subset `S` of the ordinal which is unbounded, in the sense `∀ a, ∃ b ∈ S, a ≤ b`. It is defined for all ordinals, but `cof 0 = 0` and `cof (succ o) = 1`, so it is only really interesting on limit ordinals (when it is an infinite cardinal). -/ def cof (o : ordinal.{u}) : cardinal.{u} := o.lift_on (λ a, strict_order.cof a.r) begin rintros ⟨α, r, wo₁⟩ ⟨β, s, wo₂⟩ ⟨⟨f, hf⟩⟩, haveI := wo₁, haveI := wo₂, apply @rel_iso.cof_eq _ _ _ _ _ _ , { split, exact λ a b, not_iff_not.2 hf }, { exact ⟨(is_well_order.is_irrefl r).1⟩ }, { exact ⟨(is_well_order.is_irrefl s).1⟩ } end lemma cof_type (r : α → α → Prop) [is_well_order α r] : (type r).cof = strict_order.cof r := rfl theorem le_cof_type [is_well_order α r] {c} : c ≤ cof (type r) ↔ ∀ S, unbounded r S → c ≤ #S := (le_cInf_iff'' (strict_order.cof_nonempty r)).trans ⟨λ H S h, H _ ⟨S, h, rfl⟩, by { rintros H d ⟨S, h, rfl⟩, exact H _ h }⟩ theorem cof_type_le [is_well_order α r] {S : set α} (h : unbounded r S) : cof (type r) ≤ #S := le_cof_type.1 le_rfl S h theorem lt_cof_type [is_well_order α r] {S : set α} : #S < cof (type r) → bounded r S := by simpa using not_imp_not.2 cof_type_le theorem cof_eq (r : α → α → Prop) [is_well_order α r] : ∃ S, unbounded r S ∧ #S = cof (type r) := Inf_mem (strict_order.cof_nonempty r) theorem ord_cof_eq (r : α → α → Prop) [is_well_order α r] : ∃ S, unbounded r S ∧ type (subrel r S) = (cof (type r)).ord := let ⟨S, hS, e⟩ := cof_eq r, ⟨s, _, e'⟩ := cardinal.ord_eq S, T : set α := {a | ∃ aS : a ∈ S, ∀ b : S, s b ⟨_, aS⟩ → r b a} in begin resetI, suffices, { refine ⟨T, this, le_antisymm _ (cardinal.ord_le.2 $ cof_type_le this)⟩, rw [← e, e'], refine (rel_embedding.of_monotone (λ a : T, (⟨a, let ⟨aS, _⟩ := a.2 in aS⟩ : S)) (λ a b h, _)) .ordinal_type_le, rcases a with ⟨a, aS, ha⟩, rcases b with ⟨b, bS, hb⟩, change s ⟨a, _⟩ ⟨b, _⟩, refine ((trichotomous_of s _ _).resolve_left (λ hn, _)).resolve_left _, { exact asymm h (ha _ hn) }, { intro e, injection e with e, subst b, exact irrefl _ h } }, { intro a, have : {b : S | ¬ r b a}.nonempty := let ⟨b, bS, ba⟩ := hS a in ⟨⟨b, bS⟩, ba⟩, let b := (is_well_founded.wf).min _ this, have ba : ¬r b a := (is_well_founded.wf).min_mem _ this, refine ⟨b, ⟨b.2, λ c, not_imp_not.1 $ λ h, _⟩, ba⟩, rw [show ∀b:S, (⟨b, b.2⟩:S) = b, by intro b; cases b; refl], exact (is_well_founded.wf).not_lt_min _ this (is_order_connected.neg_trans h ba) } end /-! ### Cofinality of suprema and least strict upper bounds -/ private theorem card_mem_cof {o} : ∃ {ι} (f : ι → ordinal), lsub.{u u} f = o ∧ #ι = o.card := ⟨_, _, lsub_typein o, mk_ordinal_out o⟩ /-- The set in the `lsub` characterization of `cof` is nonempty. -/ theorem cof_lsub_def_nonempty (o) : {a : cardinal | ∃ {ι} (f : ι → ordinal), lsub.{u u} f = o ∧ #ι = a}.nonempty := ⟨_, card_mem_cof⟩ theorem cof_eq_Inf_lsub (o : ordinal.{u}) : cof o = Inf {a : cardinal | ∃ {ι : Type u} (f : ι → ordinal), lsub.{u u} f = o ∧ #ι = a} := begin refine le_antisymm (le_cInf (cof_lsub_def_nonempty o) _) (cInf_le' _), { rintros a ⟨ι, f, hf, rfl⟩, rw ←type_lt o, refine (cof_type_le (λ a, _)).trans (@mk_le_of_injective _ _ (λ s : (typein ((<) : o.out.α → o.out.α → Prop))⁻¹' (set.range f), classical.some s.prop) (λ s t hst, let H := congr_arg f hst in by rwa [classical.some_spec s.prop, classical.some_spec t.prop, typein_inj, subtype.coe_inj] at H)), have := typein_lt_self a, simp_rw [←hf, lt_lsub_iff] at this, cases this with i hi, refine ⟨enum (<) (f i) _, _, _⟩, { rw [type_lt, ←hf], apply lt_lsub }, { rw [mem_preimage, typein_enum], exact mem_range_self i }, { rwa [←typein_le_typein, typein_enum] } }, { rcases cof_eq (<) with ⟨S, hS, hS'⟩, let f : S → ordinal := λ s, typein (<) s.val, refine ⟨S, f, le_antisymm (lsub_le (λ i, typein_lt_self i)) (le_of_forall_lt (λ a ha, _)), by rwa type_lt o at hS'⟩, rw ←type_lt o at ha, rcases hS (enum (<) a ha) with ⟨b, hb, hb'⟩, rw [←typein_le_typein, typein_enum] at hb', exact hb'.trans_lt (lt_lsub.{u u} f ⟨b, hb⟩) } end @[simp] theorem lift_cof (o) : (cof o).lift = cof o.lift := begin refine induction_on o _, introsI α r _, apply le_antisymm, { refine le_cof_type.2 (λ S H, _), have : (#(ulift.up ⁻¹' S)).lift ≤ #S, { rw [← cardinal.lift_umax, ← cardinal.lift_id' (#S)], exact mk_preimage_of_injective_lift ulift.up _ ulift.up_injective }, refine (cardinal.lift_le.2 $ cof_type_le _).trans this, exact λ a, let ⟨⟨b⟩, bs, br⟩ := H ⟨a⟩ in ⟨b, bs, br⟩ }, { rcases cof_eq r with ⟨S, H, e'⟩, have : #(ulift.down ⁻¹' S) ≤ (#S).lift := ⟨⟨λ ⟨⟨x⟩, h⟩, ⟨⟨x, h⟩⟩, λ ⟨⟨x⟩, h₁⟩ ⟨⟨y⟩, h₂⟩ e, by simp at e; congr; injections⟩⟩, rw e' at this, unfreezingI { refine (cof_type_le _).trans this }, exact λ ⟨a⟩, let ⟨b, bs, br⟩ := H a in ⟨⟨b⟩, bs, br⟩ } end theorem cof_le_card (o) : cof o ≤ card o := by { rw cof_eq_Inf_lsub, exact cInf_le' card_mem_cof } theorem cof_ord_le (c : cardinal) : c.ord.cof ≤ c := by simpa using cof_le_card c.ord theorem ord_cof_le (o : ordinal.{u}) : o.cof.ord ≤ o := (ord_le_ord.2 (cof_le_card o)).trans (ord_card_le o) theorem exists_lsub_cof (o : ordinal) : ∃ {ι} (f : ι → ordinal), lsub.{u u} f = o ∧ #ι = cof o := by { rw cof_eq_Inf_lsub, exact Inf_mem (cof_lsub_def_nonempty o) } theorem cof_lsub_le {ι} (f : ι → ordinal) : cof (lsub.{u u} f) ≤ #ι := by { rw cof_eq_Inf_lsub, exact cInf_le' ⟨ι, f, rfl, rfl⟩ } theorem cof_lsub_le_lift {ι} (f : ι → ordinal) : cof (lsub f) ≤ cardinal.lift.{v u} (#ι) := begin rw ←mk_ulift, convert cof_lsub_le (λ i : ulift ι, f i.down), exact lsub_eq_of_range_eq.{u (max u v) max u v} (set.ext (λ x, ⟨λ ⟨i, hi⟩, ⟨ulift.up i, hi⟩, λ ⟨i, hi⟩, ⟨_, hi⟩⟩)) end theorem le_cof_iff_lsub {o : ordinal} {a : cardinal} : a ≤ cof o ↔ ∀ {ι} (f : ι → ordinal), lsub.{u u} f = o → a ≤ #ι := begin rw cof_eq_Inf_lsub, exact (le_cInf_iff'' (cof_lsub_def_nonempty o)).trans ⟨λ H ι f hf, H _ ⟨ι, f, hf, rfl⟩, λ H b ⟨ι, f, hf, hb⟩, ( by { rw ←hb, exact H _ hf} )⟩ end theorem lsub_lt_ord_lift {ι} {f : ι → ordinal} {c : ordinal} (hι : cardinal.lift (#ι) < c.cof) (hf : ∀ i, f i < c) : lsub.{u v} f < c := lt_of_le_of_ne (lsub_le hf) (λ h, by { subst h, exact (cof_lsub_le_lift f).not_lt hι }) theorem lsub_lt_ord {ι} {f : ι → ordinal} {c : ordinal} (hι : #ι < c.cof) : (∀ i, f i < c) → lsub.{u u} f < c := lsub_lt_ord_lift (by rwa (#ι).lift_id) theorem cof_sup_le_lift {ι} {f : ι → ordinal} (H : ∀ i, f i < sup f) : cof (sup f) ≤ (#ι).lift := by { rw ←sup_eq_lsub_iff_lt_sup at H, rw H, exact cof_lsub_le_lift f } theorem cof_sup_le {ι} {f : ι → ordinal} (H : ∀ i, f i < sup.{u u} f) : cof (sup.{u u} f) ≤ #ι := by { rw ←(#ι).lift_id, exact cof_sup_le_lift H } theorem sup_lt_ord_lift {ι} {f : ι → ordinal} {c : ordinal} (hι : cardinal.lift (#ι) < c.cof) (hf : ∀ i, f i < c) : sup.{u v} f < c := (sup_le_lsub.{u v} f).trans_lt (lsub_lt_ord_lift hι hf) theorem sup_lt_ord {ι} {f : ι → ordinal} {c : ordinal} (hι : #ι < c.cof) : (∀ i, f i < c) → sup.{u u} f < c := sup_lt_ord_lift (by rwa (#ι).lift_id) theorem supr_lt_lift {ι} {f : ι → cardinal} {c : cardinal} (hι : cardinal.lift (#ι) < c.ord.cof) (hf : ∀ i, f i < c) : supr f < c := begin rw [←ord_lt_ord, supr_ord (cardinal.bdd_above_range _)], refine sup_lt_ord_lift hι (λ i, _), rw ord_lt_ord, apply hf end theorem supr_lt {ι} {f : ι → cardinal} {c : cardinal} (hι : #ι < c.ord.cof) : (∀ i, f i < c) → supr f < c := supr_lt_lift (by rwa (#ι).lift_id) theorem nfp_family_lt_ord_lift {ι} {f : ι → ordinal → ordinal} {c} (hc : ℵ₀ < cof c) (hc' : (#ι).lift < cof c) (hf : ∀ i (b < c), f i b < c) {a} (ha : a < c) : nfp_family.{u v} f a < c := begin refine sup_lt_ord_lift ((cardinal.lift_le.2 (mk_list_le_max ι)).trans_lt _) (λ l, _), { rw lift_max, apply max_lt _ hc', rwa cardinal.lift_aleph_0 }, { induction l with i l H, { exact ha }, { exact hf _ _ H } } end theorem nfp_family_lt_ord {ι} {f : ι → ordinal → ordinal} {c} (hc : ℵ₀ < cof c) (hc' : #ι < cof c) (hf : ∀ i (b < c), f i b < c) {a} : a < c → nfp_family.{u u} f a < c := nfp_family_lt_ord_lift hc (by rwa (#ι).lift_id) hf theorem nfp_bfamily_lt_ord_lift {o : ordinal} {f : Π a < o, ordinal → ordinal} {c} (hc : ℵ₀ < cof c) (hc' : o.card.lift < cof c) (hf : ∀ i hi (b < c), f i hi b < c) {a} : a < c → nfp_bfamily.{u v} o f a < c := nfp_family_lt_ord_lift hc (by rwa mk_ordinal_out) (λ i, hf _ _) theorem nfp_bfamily_lt_ord {o : ordinal} {f : Π a < o, ordinal → ordinal} {c} (hc : ℵ₀ < cof c) (hc' : o.card < cof c) (hf : ∀ i hi (b < c), f i hi b < c) {a} : a < c → nfp_bfamily.{u u} o f a < c := nfp_bfamily_lt_ord_lift hc (by rwa o.card.lift_id) hf theorem nfp_lt_ord {f : ordinal → ordinal} {c} (hc : ℵ₀ < cof c) (hf : ∀ i < c, f i < c) {a} : a < c → nfp f a < c := nfp_family_lt_ord_lift hc (by simpa using cardinal.one_lt_aleph_0.trans hc) (λ _, hf) theorem exists_blsub_cof (o : ordinal) : ∃ (f : Π a < (cof o).ord, ordinal), blsub.{u u} _ f = o := begin rcases exists_lsub_cof o with ⟨ι, f, hf, hι⟩, rcases cardinal.ord_eq ι with ⟨r, hr, hι'⟩, rw ←@blsub_eq_lsub' ι r hr at hf, rw [←hι, hι'], exact ⟨_, hf⟩ end theorem le_cof_iff_blsub {b : ordinal} {a : cardinal} : a ≤ cof b ↔ ∀ {o} (f : Π a < o, ordinal), blsub.{u u} o f = b → a ≤ o.card := le_cof_iff_lsub.trans ⟨λ H o f hf, by simpa using H _ hf, λ H ι f hf, begin rcases cardinal.ord_eq ι with ⟨r, hr, hι'⟩, rw ←@blsub_eq_lsub' ι r hr at hf, simpa using H _ hf end⟩ theorem cof_blsub_le_lift {o} (f : Π a < o, ordinal) : cof (blsub o f) ≤ cardinal.lift.{v u} (o.card) := by { convert cof_lsub_le_lift _, exact (mk_ordinal_out o).symm } theorem cof_blsub_le {o} (f : Π a < o, ordinal) : cof (blsub.{u u} o f) ≤ o.card := by { rw ←(o.card).lift_id, exact cof_blsub_le_lift f } theorem blsub_lt_ord_lift {o : ordinal} {f : Π a < o, ordinal} {c : ordinal} (ho : o.card.lift < c.cof) (hf : ∀ i hi, f i hi < c) : blsub.{u v} o f < c := lt_of_le_of_ne (blsub_le hf) (λ h, ho.not_le (by simpa [←supr_ord, hf, h] using cof_blsub_le_lift.{u} f)) theorem blsub_lt_ord {o : ordinal} {f : Π a < o, ordinal} {c : ordinal} (ho : o.card < c.cof) (hf : ∀ i hi, f i hi < c) : blsub.{u u} o f < c := blsub_lt_ord_lift (by rwa (o.card).lift_id) hf theorem cof_bsup_le_lift {o : ordinal} {f : Π a < o, ordinal} (H : ∀ i h, f i h < bsup o f) : cof (bsup o f) ≤ o.card.lift := by { rw ←bsup_eq_blsub_iff_lt_bsup at H, rw H, exact cof_blsub_le_lift f } theorem cof_bsup_le {o : ordinal} {f : Π a < o, ordinal} : (∀ i h, f i h < bsup.{u u} o f) → cof (bsup.{u u} o f) ≤ o.card := by { rw ←(o.card).lift_id, exact cof_bsup_le_lift } theorem bsup_lt_ord_lift {o : ordinal} {f : Π a < o, ordinal} {c : ordinal} (ho : o.card.lift < c.cof) (hf : ∀ i hi, f i hi < c) : bsup.{u v} o f < c := (bsup_le_blsub f).trans_lt (blsub_lt_ord_lift ho hf) theorem bsup_lt_ord {o : ordinal} {f : Π a < o, ordinal} {c : ordinal} (ho : o.card < c.cof) : (∀ i hi, f i hi < c) → bsup.{u u} o f < c := bsup_lt_ord_lift (by rwa (o.card).lift_id) /-! ### Basic results -/ @[simp] theorem cof_zero : cof 0 = 0 := (cof_le_card 0).antisymm (cardinal.zero_le _) @[simp] theorem cof_eq_zero {o} : cof o = 0 ↔ o = 0 := ⟨induction_on o $ λ α r _ z, by exactI let ⟨S, hl, e⟩ := cof_eq r in type_eq_zero_iff_is_empty.2 $ ⟨λ a, let ⟨b, h, _⟩ := hl a in (mk_eq_zero_iff.1 (e.trans z)).elim' ⟨_, h⟩⟩, λ e, by simp [e]⟩ theorem cof_ne_zero {o} : cof o ≠ 0 ↔ o ≠ 0 := cof_eq_zero.not @[simp] theorem cof_succ (o) : cof (succ o) = 1 := begin apply le_antisymm, { refine induction_on o (λ α r _, _), change cof (type _) ≤ _, rw [← (_ : #_ = 1)], apply cof_type_le, { refine λ a, ⟨sum.inr punit.star, set.mem_singleton _, _⟩, rcases a with a|⟨⟨⟨⟩⟩⟩; simp [empty_relation] }, { rw [cardinal.mk_fintype, set.card_singleton], simp } }, { rw [← cardinal.succ_zero, succ_le_iff], simpa [lt_iff_le_and_ne, cardinal.zero_le] using λ h, succ_ne_zero o (cof_eq_zero.1 (eq.symm h)) } end @[simp] theorem cof_eq_one_iff_is_succ {o} : cof.{u} o = 1 ↔ ∃ a, o = succ a := ⟨induction_on o $ λ α r _ z, begin resetI, rcases cof_eq r with ⟨S, hl, e⟩, rw z at e, cases mk_ne_zero_iff.1 (by rw e; exact one_ne_zero) with a, refine ⟨typein r a, eq.symm $ quotient.sound ⟨rel_iso.of_surjective (rel_embedding.of_monotone _ (λ x y, _)) (λ x, _)⟩⟩, { apply sum.rec; [exact subtype.val, exact λ _, a] }, { rcases x with x|⟨⟨⟨⟩⟩⟩; rcases y with y|⟨⟨⟨⟩⟩⟩; simp [subrel, order.preimage, empty_relation], exact x.2 }, { suffices : r x a ∨ ∃ (b : punit), ↑a = x, {simpa}, rcases trichotomous_of r x a with h|h|h, { exact or.inl h }, { exact or.inr ⟨punit.star, h.symm⟩ }, { rcases hl x with ⟨a', aS, hn⟩, rw (_ : ↑a = a') at h, {exact absurd h hn}, refine congr_arg subtype.val (_ : a = ⟨a', aS⟩), haveI := le_one_iff_subsingleton.1 (le_of_eq e), apply subsingleton.elim } } end, λ ⟨a, e⟩, by simp [e]⟩ /-- A fundamental sequence for `a` is an increasing sequence of length `o = cof a` that converges at `a`. We provide `o` explicitly in order to avoid type rewrites. -/ def is_fundamental_sequence (a o : ordinal.{u}) (f : Π b < o, ordinal.{u}) : Prop := o ≤ a.cof.ord ∧ (∀ {i j} (hi hj), i < j → f i hi < f j hj) ∧ blsub.{u u} o f = a namespace is_fundamental_sequence variables {a o : ordinal.{u}} {f : Π b < o, ordinal.{u}} protected theorem cof_eq (hf : is_fundamental_sequence a o f) : a.cof.ord = o := hf.1.antisymm' $ by { rw ←hf.2.2, exact (ord_le_ord.2 (cof_blsub_le f)).trans (ord_card_le o) } protected theorem strict_mono (hf : is_fundamental_sequence a o f) {i j} : ∀ hi hj, i < j → f i hi < f j hj := hf.2.1 theorem blsub_eq (hf : is_fundamental_sequence a o f) : blsub.{u u} o f = a := hf.2.2 theorem ord_cof (hf : is_fundamental_sequence a o f) : is_fundamental_sequence a a.cof.ord (λ i hi, f i (hi.trans_le (by rw hf.cof_eq))) := by { have H := hf.cof_eq, subst H, exact hf } theorem id_of_le_cof (h : o ≤ o.cof.ord) : is_fundamental_sequence o o (λ a _, a) := ⟨h, λ _ _ _ _, id, blsub_id o⟩ protected theorem zero {f : Π b < (0 : ordinal), ordinal} : is_fundamental_sequence 0 0 f := ⟨by rw [cof_zero, ord_zero], λ i j hi, (ordinal.not_lt_zero i hi).elim, blsub_zero f⟩ protected theorem succ : is_fundamental_sequence (succ o) 1 (λ _ _, o) := begin refine ⟨_, λ i j hi hj h, _, blsub_const ordinal.one_ne_zero o⟩, { rw [cof_succ, ord_one] }, { rw lt_one_iff_zero at hi hj, rw [hi, hj] at h, exact h.false.elim } end protected theorem monotone (hf : is_fundamental_sequence a o f) {i j : ordinal} (hi : i < o) (hj : j < o) (hij : i ≤ j) : f i hi ≤ f j hj := begin rcases lt_or_eq_of_le hij with hij | rfl, { exact (hf.2.1 hi hj hij).le }, { refl } end theorem trans {a o o' : ordinal.{u}} {f : Π b < o, ordinal.{u}} (hf : is_fundamental_sequence a o f) {g : Π b < o', ordinal.{u}} (hg : is_fundamental_sequence o o' g) : is_fundamental_sequence a o' (λ i hi, f (g i hi) (by { rw ←hg.2.2, apply lt_blsub })) := begin refine ⟨_, λ i j _ _ h, hf.2.1 _ _ (hg.2.1 _ _ h), _⟩, { rw hf.cof_eq, exact hg.1.trans (ord_cof_le o) }, { rw @blsub_comp.{u u u} o _ f (@is_fundamental_sequence.monotone _ _ f hf), exact hf.2.2 } end end is_fundamental_sequence /-- Every ordinal has a fundamental sequence. -/ theorem exists_fundamental_sequence (a : ordinal.{u}) : ∃ f, is_fundamental_sequence a a.cof.ord f := begin rsuffices ⟨o, f, hf⟩ : ∃ o f, is_fundamental_sequence a o f, { exact ⟨_, hf.ord_cof⟩ }, rcases exists_lsub_cof a with ⟨ι, f, hf, hι⟩, rcases ord_eq ι with ⟨r, wo, hr⟩, haveI := wo, let r' := subrel r {i | ∀ j, r j i → f j < f i}, let hrr' : r' ↪r r := subrel.rel_embedding _ _, haveI := hrr'.is_well_order, refine ⟨_, _, hrr'.ordinal_type_le.trans _, λ i j _ h _, (enum r' j h).prop _ _, le_antisymm (blsub_le (λ i hi, lsub_le_iff.1 hf.le _)) _⟩, { rw [←hι, hr] }, { change r (hrr'.1 _ ) (hrr'.1 _ ), rwa [hrr'.2, @enum_lt_enum _ r'] }, { rw [←hf, lsub_le_iff], intro i, rsuffices ⟨i', hi', hfg⟩ : ∃ i' hi', f i ≤ bfamily_of_family' r' (λ i, f i) i' hi', { exact hfg.trans_lt (lt_blsub _ _ _) }, by_cases h : ∀ j, r j i → f j < f i, { refine ⟨typein r' ⟨i, h⟩, typein_lt_type _ _, _⟩, rw bfamily_of_family'_typein, refl }, { push_neg at h, cases wo.wf.min_mem _ h with hji hij, refine ⟨typein r' ⟨_, λ k hkj, lt_of_lt_of_le _ hij⟩, typein_lt_type _ _, _⟩, { by_contra' H, exact (wo.wf.not_lt_min _ h ⟨is_trans.trans _ _ _ hkj hji, H⟩) hkj }, { rwa bfamily_of_family'_typein } } } end @[simp] theorem cof_cof (a : ordinal.{u}) : cof (cof a).ord = cof a := begin cases exists_fundamental_sequence a with f hf, cases exists_fundamental_sequence a.cof.ord with g hg, exact ord_injective ((hf.trans hg).cof_eq.symm) end protected theorem is_normal.is_fundamental_sequence {f : ordinal.{u} → ordinal.{u}} (hf : is_normal f) {a o} (ha : is_limit a) {g} (hg : is_fundamental_sequence a o g) : is_fundamental_sequence (f a) o (λ b hb, f (g b hb)) := begin refine ⟨_, λ i j _ _ h, hf.strict_mono (hg.2.1 _ _ h), _⟩, { rcases exists_lsub_cof (f a) with ⟨ι, f', hf', hι⟩, rw [←hg.cof_eq, ord_le_ord, ←hι], suffices : lsub.{u u} (λ i, (Inf {b : ordinal | f' i ≤ f b})) = a, { rw ←this, apply cof_lsub_le }, have H : ∀ i, ∃ b < a, f' i ≤ f b := λ i, begin have := lt_lsub.{u u} f' i, rwa [hf', ←is_normal.blsub_eq.{u u} hf ha, lt_blsub_iff] at this end, refine (lsub_le (λ i, _)).antisymm (le_of_forall_lt (λ b hb, _)), { rcases H i with ⟨b, hb, hb'⟩, exact lt_of_le_of_lt (cInf_le' hb') hb }, { have := hf.strict_mono hb, rw [←hf', lt_lsub_iff] at this, cases this with i hi, rcases H i with ⟨b, _, hb⟩, exact ((le_cInf_iff'' ⟨b, hb⟩).2 (λ c hc, hf.strict_mono.le_iff_le.1 (hi.trans hc))).trans_lt (lt_lsub _ i) } }, { rw @blsub_comp.{u u u} a _ (λ b _, f b) (λ i j hi hj h, hf.strict_mono.monotone h) g hg.2.2, exact is_normal.blsub_eq.{u u} hf ha } end theorem is_normal.cof_eq {f} (hf : is_normal f) {a} (ha : is_limit a) : cof (f a) = cof a := let ⟨g, hg⟩ := exists_fundamental_sequence a in ord_injective (hf.is_fundamental_sequence ha hg).cof_eq theorem is_normal.cof_le {f} (hf : is_normal f) (a) : cof a ≤ cof (f a) := begin rcases zero_or_succ_or_limit a with rfl | ⟨b, rfl⟩ | ha, { rw cof_zero, exact zero_le _ }, { rw [cof_succ, cardinal.one_le_iff_ne_zero, cof_ne_zero, ←ordinal.pos_iff_ne_zero], exact (ordinal.zero_le (f b)).trans_lt (hf.1 b) }, { rw hf.cof_eq ha } end @[simp] theorem cof_add (a b : ordinal) : b ≠ 0 → cof (a + b) = cof b := λ h, begin rcases zero_or_succ_or_limit b with rfl | ⟨c, rfl⟩ | hb, { contradiction }, { rw [add_succ, cof_succ, cof_succ] }, { exact (add_is_normal a).cof_eq hb } end theorem aleph_0_le_cof {o} : ℵ₀ ≤ cof o ↔ is_limit o := begin rcases zero_or_succ_or_limit o with rfl|⟨o,rfl⟩|l, { simp [not_zero_is_limit, cardinal.aleph_0_ne_zero] }, { simp [not_succ_is_limit, cardinal.one_lt_aleph_0] }, { simp [l], refine le_of_not_lt (λ h, _), cases cardinal.lt_aleph_0.1 h with n e, have := cof_cof o, rw [e, ord_nat] at this, cases n, { simp at e, simpa [e, not_zero_is_limit] using l }, { rw [nat_cast_succ, cof_succ] at this, rw [← this, cof_eq_one_iff_is_succ] at e, rcases e with ⟨a, rfl⟩, exact not_succ_is_limit _ l } } end @[simp] theorem aleph'_cof {o : ordinal} (ho : o.is_limit) : (aleph' o).ord.cof = o.cof := aleph'_is_normal.cof_eq ho @[simp] theorem aleph_cof {o : ordinal} (ho : o.is_limit) : (aleph o).ord.cof = o.cof := aleph_is_normal.cof_eq ho @[simp] theorem cof_omega : cof ω = ℵ₀ := (aleph_0_le_cof.2 omega_is_limit).antisymm' $ by { rw ←card_omega, apply cof_le_card } theorem cof_eq' (r : α → α → Prop) [is_well_order α r] (h : is_limit (type r)) : ∃ S : set α, (∀ a, ∃ b ∈ S, r a b) ∧ #S = cof (type r) := let ⟨S, H, e⟩ := cof_eq r in ⟨S, λ a, let a' := enum r _ (h.2 _ (typein_lt_type r a)) in let ⟨b, h, ab⟩ := H a' in ⟨b, h, (is_order_connected.conn a b a' $ (typein_lt_typein r).1 (by { rw typein_enum, exact lt_succ (typein _ _) })).resolve_right ab⟩, e⟩ @[simp] theorem cof_univ : cof univ.{u v} = cardinal.univ := le_antisymm (cof_le_card _) begin refine le_of_forall_lt (λ c h, _), rcases lt_univ'.1 h with ⟨c, rfl⟩, rcases @cof_eq ordinal.{u} (<) _ with ⟨S, H, Se⟩, rw [univ, ← lift_cof, ← cardinal.lift_lift, cardinal.lift_lt, ← Se], refine lt_of_not_ge (λ h, _), cases cardinal.lift_down h with a e, refine quotient.induction_on a (λ α e, _) e, cases quotient.exact e with f, have f := equiv.ulift.symm.trans f, let g := λ a, (f a).1, let o := succ (sup.{u u} g), rcases H o with ⟨b, h, l⟩, refine l (lt_succ_iff.2 _), rw ← show g (f.symm ⟨b, h⟩) = b, by dsimp [g]; simp, apply le_sup end /-! ### Infinite pigeonhole principle -/ /-- If the union of s is unbounded and s is smaller than the cofinality, then s has an unbounded member -/ theorem unbounded_of_unbounded_sUnion (r : α → α → Prop) [wo : is_well_order α r] {s : set (set α)} (h₁ : unbounded r $ ⋃₀ s) (h₂ : #s < strict_order.cof r) : ∃ x ∈ s, unbounded r x := begin by_contra' h, simp_rw not_unbounded_iff at h, let f : s → α := λ x : s, wo.wf.sup x (h x.1 x.2), refine h₂.not_le (le_trans (cInf_le' ⟨range f, λ x, _, rfl⟩) mk_range_le), rcases h₁ x with ⟨y, ⟨c, hc, hy⟩, hxy⟩, exact ⟨f ⟨c, hc⟩, mem_range_self _, λ hxz, hxy (trans (wo.wf.lt_sup _ hy) hxz)⟩ end /-- If the union of s is unbounded and s is smaller than the cofinality, then s has an unbounded member -/ theorem unbounded_of_unbounded_Union {α β : Type u} (r : α → α → Prop) [wo : is_well_order α r] (s : β → set α) (h₁ : unbounded r $ ⋃ x, s x) (h₂ : #β < strict_order.cof r) : ∃ x : β, unbounded r (s x) := begin rw ←sUnion_range at h₁, rcases unbounded_of_unbounded_sUnion r h₁ (mk_range_le.trans_lt h₂) with ⟨_, ⟨x, rfl⟩, u⟩, exact ⟨x, u⟩ end /-- The infinite pigeonhole principle -/ theorem infinite_pigeonhole {β α : Type u} (f : β → α) (h₁ : ℵ₀ ≤ #β) (h₂ : #α < (#β).ord.cof) : ∃ a : α, #(f ⁻¹' {a}) = #β := begin have : ∃ a, #β ≤ #(f ⁻¹' {a}), { by_contra' h, apply mk_univ.not_lt, rw [←preimage_univ, ←Union_of_singleton, preimage_Union], exact mk_Union_le_sum_mk.trans_lt ((sum_le_supr _).trans_lt $ mul_lt_of_lt h₁ (h₂.trans_le $ cof_ord_le _) (supr_lt h₂ h)) }, cases this with x h, refine ⟨x, h.antisymm' _⟩, rw le_mk_iff_exists_set, exact ⟨_, rfl⟩ end /-- Pigeonhole principle for a cardinality below the cardinality of the domain -/ theorem infinite_pigeonhole_card {β α : Type u} (f : β → α) (θ : cardinal) (hθ : θ ≤ #β) (h₁ : ℵ₀ ≤ θ) (h₂ : #α < θ.ord.cof) : ∃ a : α, θ ≤ #(f ⁻¹' {a}) := begin rcases le_mk_iff_exists_set.1 hθ with ⟨s, rfl⟩, cases infinite_pigeonhole (f ∘ subtype.val : s → α) h₁ h₂ with a ha, use a, rw [←ha, @preimage_comp _ _ _ subtype.val f], exact mk_preimage_of_injective _ _ subtype.val_injective end theorem infinite_pigeonhole_set {β α : Type u} {s : set β} (f : s → α) (θ : cardinal) (hθ : θ ≤ #s) (h₁ : ℵ₀ ≤ θ) (h₂ : #α < θ.ord.cof) : ∃ (a : α) (t : set β) (h : t ⊆ s), θ ≤ #t ∧ ∀ {{x}} (hx : x ∈ t), f ⟨x, h hx⟩ = a := begin cases infinite_pigeonhole_card f θ hθ h₁ h₂ with a ha, refine ⟨a, {x | ∃ h, f ⟨x, h⟩ = a}, _, _, _⟩, { rintro x ⟨hx, hx'⟩, exact hx }, { refine ha.trans (ge_of_eq $ quotient.sound ⟨equiv.trans _ (equiv.subtype_subtype_equiv_subtype_exists _ _).symm⟩), simp only [coe_eq_subtype, mem_singleton_iff, mem_preimage, mem_set_of_eq] }, rintro x ⟨hx, hx'⟩, exact hx' end end ordinal /-! ### Regular and inaccessible cardinals -/ namespace cardinal open ordinal local infixr (name := cardinal.pow) ^ := @pow cardinal.{u} cardinal cardinal.has_pow /-- A cardinal is a limit if it is not zero or a successor cardinal. Note that `ℵ₀` is a limit cardinal by this definition. -/ def is_limit (c : cardinal) : Prop := c ≠ 0 ∧ ∀ x < c, succ x < c theorem is_limit.ne_zero {c} (h : is_limit c) : c ≠ 0 := h.1 theorem is_limit.succ_lt {x c} (h : is_limit c) : x < c → succ x < c := h.2 x theorem is_limit.aleph_0_le {c} (h : is_limit c) : ℵ₀ ≤ c := begin by_contra' h', rcases lt_aleph_0.1 h' with ⟨_ | n, rfl⟩, { exact h.1.irrefl }, { simpa using h.2 n } end /-- A cardinal is a strong limit if it is not zero and it is closed under powersets. Note that `ℵ₀` is a strong limit by this definition. -/ def is_strong_limit (c : cardinal) : Prop := c ≠ 0 ∧ ∀ x < c, 2 ^ x < c theorem is_strong_limit.ne_zero {c} (h : is_strong_limit c) : c ≠ 0 := h.1 theorem is_strong_limit.two_power_lt {x c} (h : is_strong_limit c) : x < c → 2 ^ x < c := h.2 x theorem is_strong_limit_aleph_0 : is_strong_limit ℵ₀ := ⟨aleph_0_ne_zero, λ x hx, begin rcases lt_aleph_0.1 hx with ⟨n, rfl⟩, exact_mod_cast nat_lt_aleph_0 (pow 2 n) end⟩ theorem is_strong_limit.is_limit {c} (H : is_strong_limit c) : is_limit c := ⟨H.1, λ x h, (succ_le_of_lt $ cantor x).trans_lt (H.2 _ h)⟩ theorem is_limit_aleph_0 : is_limit ℵ₀ := is_strong_limit_aleph_0.is_limit theorem is_strong_limit_beth {o : ordinal} (H : ∀ a < o, succ a < o) : is_strong_limit (beth o) := begin rcases eq_or_ne o 0 with rfl | h, { rw beth_zero, exact is_strong_limit_aleph_0 }, { refine ⟨beth_ne_zero o, λ a ha, _⟩, rw beth_limit ⟨h, H⟩ at ha, rcases exists_lt_of_lt_csupr' ha with ⟨⟨i, hi⟩, ha⟩, have := power_le_power_left two_ne_zero' ha.le, rw ←beth_succ at this, exact this.trans_lt (beth_lt.2 (H i hi)) } end theorem mk_bounded_subset {α : Type*} (h : ∀ x < #α, 2 ^ x < #α) {r : α → α → Prop} [is_well_order α r] (hr : (#α).ord = type r) : #{s : set α // bounded r s} = #α := begin rcases eq_or_ne (#α) 0 with ha | ha, { rw ha, haveI := mk_eq_zero_iff.1 ha, rw mk_eq_zero_iff, split, rintro ⟨s, hs⟩, exact (not_unbounded_iff s).2 hs (unbounded_of_is_empty s) }, have h' : is_strong_limit (#α) := ⟨ha, h⟩, have ha := h'.is_limit.aleph_0_le, apply le_antisymm, { have : {s : set α | bounded r s} = ⋃ i, 𝒫 {j | r j i} := set_of_exists _, rw [←coe_set_of, this], convert mk_Union_le_sum_mk.trans ((sum_le_supr _).trans (mul_le_max_of_aleph_0_le_left ha)), apply (max_eq_left _).symm, apply csupr_le' (λ i, _), rw mk_powerset, apply (h'.two_power_lt _).le, rw [coe_set_of, card_typein, ←lt_ord, hr], apply typein_lt_type }, { refine @mk_le_of_injective α _ (λ x, subtype.mk {x} _) _, { apply bounded_singleton, rw ←hr, apply ord_is_limit ha }, { intros a b hab, simpa only [singleton_eq_singleton_iff] using hab } } end theorem mk_subset_mk_lt_cof {α : Type*} (h : ∀ x < #α, 2 ^ x < #α) : #{s : set α // #s < cof (#α).ord} = #α := begin rcases eq_or_ne (#α) 0 with ha | ha, { rw ha, simp [λ s, (cardinal.zero_le s).not_lt] }, have h' : is_strong_limit (#α) := ⟨ha, h⟩, rcases ord_eq α with ⟨r, wo, hr⟩, haveI := wo, apply le_antisymm, { nth_rewrite_rhs 0 ←mk_bounded_subset h hr, apply mk_le_mk_of_subset (λ s hs, _), rw hr at hs, exact lt_cof_type hs }, { refine @mk_le_of_injective α _ (λ x, subtype.mk {x} _) _, { rw mk_singleton, exact one_lt_aleph_0.trans_le (aleph_0_le_cof.2 (ord_is_limit h'.is_limit.aleph_0_le)) }, { intros a b hab, simpa only [singleton_eq_singleton_iff] using hab } } end /-- A cardinal is regular if it is infinite and it equals its own cofinality. -/ def is_regular (c : cardinal) : Prop := ℵ₀ ≤ c ∧ c ≤ c.ord.cof lemma is_regular.aleph_0_le {c : cardinal} (H : c.is_regular) : ℵ₀ ≤ c := H.1 lemma is_regular.cof_eq {c : cardinal} (H : c.is_regular) : c.ord.cof = c := (cof_ord_le c).antisymm H.2 lemma is_regular.pos {c : cardinal} (H : c.is_regular) : 0 < c := aleph_0_pos.trans_le H.1 lemma is_regular.ord_pos {c : cardinal} (H : c.is_regular) : 0 < c.ord := by { rw cardinal.lt_ord, exact H.pos } theorem is_regular_cof {o : ordinal} (h : o.is_limit) : is_regular o.cof := ⟨aleph_0_le_cof.2 h, (cof_cof o).ge⟩ theorem is_regular_aleph_0 : is_regular ℵ₀ := ⟨le_rfl, by simp⟩ theorem is_regular_succ {c : cardinal.{u}} (h : ℵ₀ ≤ c) : is_regular (succ c) := ⟨h.trans (le_succ c), succ_le_of_lt begin cases quotient.exists_rep (@succ cardinal _ _ c) with α αe, simp at αe, rcases ord_eq α with ⟨r, wo, re⟩, resetI, have := ord_is_limit (h.trans (le_succ _)), rw [← αe, re] at this ⊢, rcases cof_eq' r this with ⟨S, H, Se⟩, rw [← Se], apply lt_imp_lt_of_le_imp_le (λ h, mul_le_mul_right' h c), rw [mul_eq_self h, ← succ_le_iff, ← αe, ← sum_const'], refine le_trans _ (sum_le_sum (λ x, card (typein r x)) _ (λ i, _)), { simp only [← card_typein, ← mk_sigma], exact ⟨embedding.of_surjective (λ x, x.2.1) (λ a, let ⟨b, h, ab⟩ := H a in ⟨⟨⟨_, h⟩, _, ab⟩, rfl⟩)⟩ }, { rw [← lt_succ_iff, ← lt_ord, ← αe, re], apply typein_lt_type } end⟩ theorem is_regular_aleph_one : is_regular (aleph 1) := by { rw ←succ_aleph_0, exact is_regular_succ le_rfl } theorem is_regular_aleph'_succ {o : ordinal} (h : ω ≤ o) : is_regular (aleph' (succ o)) := by { rw aleph'_succ, exact is_regular_succ (aleph_0_le_aleph'.2 h) } theorem is_regular_aleph_succ (o : ordinal) : is_regular (aleph (succ o)) := by { rw aleph_succ, exact is_regular_succ (aleph_0_le_aleph o) } /-- A function whose codomain's cardinality is infinite but strictly smaller than its domain's has a fiber with cardinality strictly great than the codomain. -/ theorem infinite_pigeonhole_card_lt {β α : Type u} (f : β → α) (w : #α < #β) (w' : ℵ₀ ≤ #α) : ∃ a : α, #α < #(f ⁻¹' {a}) := begin simp_rw [← succ_le_iff], exact ordinal.infinite_pigeonhole_card f (succ (#α)) (succ_le_of_lt w) (w'.trans (lt_succ _).le) ((lt_succ _).trans_le (is_regular_succ w').2.ge), end /-- A function whose codomain's cardinality is infinite but strictly smaller than its domain's has an infinite fiber. -/ theorem exists_infinite_fiber {β α : Type*} (f : β → α) (w : #α < #β) (w' : _root_.infinite α) : ∃ a : α, _root_.infinite (f ⁻¹' {a}) := begin simp_rw [cardinal.infinite_iff] at ⊢ w', cases infinite_pigeonhole_card_lt f w w' with a ha, exact ⟨a, w'.trans ha.le⟩, end /-- If an infinite type `β` can be expressed as a union of finite sets, then the cardinality of the collection of those finite sets must be at least the cardinality of `β`. -/ lemma le_range_of_union_finset_eq_top {α β : Type*} [infinite β] (f : α → finset β) (w : (⋃ a, (f a : set β)) = ⊤) : #β ≤ #(range f) := begin have k : _root_.infinite (range f), { rw infinite_coe_iff, apply mt (union_finset_finite_of_range_finite f), rw w, exact infinite_univ, }, by_contradiction h, simp only [not_le] at h, let u : Π b, ∃ a, b ∈ f a := λ b, by simpa using (w.ge : _) (set.mem_univ b), let u' : β → range f := λ b, ⟨f (u b).some, by simp⟩, have v' : ∀ a, u' ⁻¹' {⟨f a, by simp⟩} ≤ f a, begin rintros a p m, simp at m, rw ←m, apply (λ b, (u b).some_spec), end, obtain ⟨⟨-, ⟨a, rfl⟩⟩, p⟩ := exists_infinite_fiber u' h k, exact (@infinite.of_injective _ _ p (inclusion (v' a)) (inclusion_injective _)).false, end theorem lsub_lt_ord_lift_of_is_regular {ι} {f : ι → ordinal} {c} (hc : is_regular c) (hι : cardinal.lift (#ι) < c) : (∀ i, f i < c.ord) → ordinal.lsub f < c.ord := lsub_lt_ord_lift (by rwa hc.cof_eq) theorem lsub_lt_ord_of_is_regular {ι} {f : ι → ordinal} {c} (hc : is_regular c) (hι : #ι < c) : (∀ i, f i < c.ord) → ordinal.lsub f < c.ord := lsub_lt_ord (by rwa hc.cof_eq) theorem sup_lt_ord_lift_of_is_regular {ι} {f : ι → ordinal} {c} (hc : is_regular c) (hι : cardinal.lift (#ι) < c) : (∀ i, f i < c.ord) → ordinal.sup f < c.ord := sup_lt_ord_lift (by rwa hc.cof_eq) theorem sup_lt_ord_of_is_regular {ι} {f : ι → ordinal} {c} (hc : is_regular c) (hι : #ι < c) : (∀ i, f i < c.ord) → ordinal.sup f < c.ord := sup_lt_ord (by rwa hc.cof_eq) theorem blsub_lt_ord_lift_of_is_regular {o : ordinal} {f : Π a < o, ordinal} {c} (hc : is_regular c) (ho : cardinal.lift o.card < c) : (∀ i hi, f i hi < c.ord) → ordinal.blsub o f < c.ord := blsub_lt_ord_lift (by rwa hc.cof_eq) theorem blsub_lt_ord_of_is_regular {o : ordinal} {f : Π a < o, ordinal} {c} (hc : is_regular c) (ho : o.card < c) : (∀ i hi, f i hi < c.ord) → ordinal.blsub o f < c.ord := blsub_lt_ord (by rwa hc.cof_eq) theorem bsup_lt_ord_lift_of_is_regular {o : ordinal} {f : Π a < o, ordinal} {c} (hc : is_regular c) (hι : cardinal.lift o.card < c) : (∀ i hi, f i hi < c.ord) → ordinal.bsup o f < c.ord := bsup_lt_ord_lift (by rwa hc.cof_eq) theorem bsup_lt_ord_of_is_regular {o : ordinal} {f : Π a < o, ordinal} {c} (hc : is_regular c) (hι : o.card < c) : (∀ i hi, f i hi < c.ord) → ordinal.bsup o f < c.ord := bsup_lt_ord (by rwa hc.cof_eq) theorem supr_lt_lift_of_is_regular {ι} {f : ι → cardinal} {c} (hc : is_regular c) (hι : cardinal.lift (#ι) < c) : (∀ i, f i < c) → supr f < c := supr_lt_lift (by rwa hc.cof_eq) theorem supr_lt_of_is_regular {ι} {f : ι → cardinal} {c} (hc : is_regular c) (hι : #ι < c) : (∀ i, f i < c) → supr f < c := supr_lt (by rwa hc.cof_eq) theorem sum_lt_lift_of_is_regular {ι : Type u} {f : ι → cardinal} {c : cardinal} (hc : is_regular c) (hι : cardinal.lift.{v u} (#ι) < c) (hf : ∀ i, f i < c) : sum f < c := (sum_le_supr_lift _).trans_lt $ mul_lt_of_lt hc.1 hι (supr_lt_lift_of_is_regular hc hι hf) theorem sum_lt_of_is_regular {ι : Type u} {f : ι → cardinal} {c : cardinal} (hc : is_regular c) (hι : #ι < c) : (∀ i, f i < c) → sum f < c := sum_lt_lift_of_is_regular.{u u} hc (by rwa lift_id) theorem nfp_family_lt_ord_lift_of_is_regular {ι} {f : ι → ordinal → ordinal} {c} (hc : is_regular c) (hι : (#ι).lift < c) (hc' : c ≠ ℵ₀) (hf : ∀ i (b < c.ord), f i b < c.ord) {a} (ha : a < c.ord) : nfp_family.{u v} f a < c.ord := by { apply nfp_family_lt_ord_lift _ _ hf ha; rwa hc.cof_eq, exact lt_of_le_of_ne hc.1 hc'.symm } theorem nfp_family_lt_ord_of_is_regular {ι} {f : ι → ordinal → ordinal} {c} (hc : is_regular c) (hι : #ι < c) (hc' : c ≠ ℵ₀) {a} (hf : ∀ i (b < c.ord), f i b < c.ord) : a < c.ord → nfp_family.{u u} f a < c.ord := nfp_family_lt_ord_lift_of_is_regular hc (by rwa lift_id) hc' hf theorem nfp_bfamily_lt_ord_lift_of_is_regular {o : ordinal} {f : Π a < o, ordinal → ordinal} {c} (hc : is_regular c) (ho : o.card.lift < c) (hc' : c ≠ ℵ₀) (hf : ∀ i hi (b < c.ord), f i hi b < c.ord) {a} : a < c.ord → nfp_bfamily.{u v} o f a < c.ord := nfp_family_lt_ord_lift_of_is_regular hc (by rwa mk_ordinal_out) hc' (λ i, hf _ _) theorem nfp_bfamily_lt_ord_of_is_regular {o : ordinal} {f : Π a < o, ordinal → ordinal} {c} (hc : is_regular c) (ho : o.card < c) (hc' : c ≠ ℵ₀) (hf : ∀ i hi (b < c.ord), f i hi b < c.ord) {a} : a < c.ord → nfp_bfamily.{u u} o f a < c.ord := nfp_bfamily_lt_ord_lift_of_is_regular hc (by rwa lift_id) hc' hf theorem nfp_lt_ord_of_is_regular {f : ordinal → ordinal} {c} (hc : is_regular c) (hc' : c ≠ ℵ₀) (hf : ∀ i < c.ord, f i < c.ord) {a} : (a < c.ord) → nfp f a < c.ord := nfp_lt_ord (by { rw hc.cof_eq, exact lt_of_le_of_ne hc.1 hc'.symm }) hf theorem deriv_family_lt_ord_lift {ι} {f : ι → ordinal → ordinal} {c} (hc : is_regular c) (hι : (#ι).lift < c) (hc' : c ≠ ℵ₀) (hf : ∀ i (b < c.ord), f i b < c.ord) {a} : a < c.ord → deriv_family.{u v} f a < c.ord := begin have hω : ℵ₀ < c.ord.cof, { rw hc.cof_eq, exact lt_of_le_of_ne hc.1 hc'.symm }, apply a.limit_rec_on, { rw deriv_family_zero, exact nfp_family_lt_ord_lift hω (by rwa hc.cof_eq) hf }, { intros b hb hb', rw deriv_family_succ, exact nfp_family_lt_ord_lift hω (by rwa hc.cof_eq) hf ((ord_is_limit hc.1).2 _ (hb ((lt_succ b).trans hb'))) }, { intros b hb H hb', rw deriv_family_limit f hb, exact bsup_lt_ord_of_is_regular hc (ord_lt_ord.1 ((ord_card_le b).trans_lt hb')) (λ o' ho', H o' ho' (ho'.trans hb')) } end theorem deriv_family_lt_ord {ι} {f : ι → ordinal → ordinal} {c} (hc : is_regular c) (hι : #ι < c) (hc' : c ≠ ℵ₀) (hf : ∀ i (b < c.ord), f i b < c.ord) {a} : a < c.ord → deriv_family.{u u} f a < c.ord := deriv_family_lt_ord_lift hc (by rwa lift_id) hc' hf theorem deriv_bfamily_lt_ord_lift {o : ordinal} {f : Π a < o, ordinal → ordinal} {c} (hc : is_regular c) (hι : o.card.lift < c) (hc' : c ≠ ℵ₀) (hf : ∀ i hi (b < c.ord), f i hi b < c.ord) {a} : a < c.ord → deriv_bfamily.{u v} o f a < c.ord := deriv_family_lt_ord_lift hc (by rwa mk_ordinal_out) hc' (λ i, hf _ _) theorem deriv_bfamily_lt_ord {o : ordinal} {f : Π a < o, ordinal → ordinal} {c} (hc : is_regular c) (hι : o.card < c) (hc' : c ≠ ℵ₀) (hf : ∀ i hi (b < c.ord), f i hi b < c.ord) {a} : a < c.ord → deriv_bfamily.{u u} o f a < c.ord := deriv_bfamily_lt_ord_lift hc (by rwa lift_id) hc' hf theorem deriv_lt_ord {f : ordinal.{u} → ordinal} {c} (hc : is_regular c) (hc' : c ≠ ℵ₀) (hf : ∀ i < c.ord, f i < c.ord) {a} : a < c.ord → deriv f a < c.ord := deriv_family_lt_ord_lift hc (by simpa using cardinal.one_lt_aleph_0.trans (lt_of_le_of_ne hc.1 hc'.symm)) hc' (λ _, hf) /-- A cardinal is inaccessible if it is an uncountable regular strong limit cardinal. -/ def is_inaccessible (c : cardinal) := ℵ₀ < c ∧ is_regular c ∧ is_strong_limit c theorem is_inaccessible.mk {c} (h₁ : ℵ₀ < c) (h₂ : c ≤ c.ord.cof) (h₃ : ∀ x < c, 2 ^ x < c) : is_inaccessible c := ⟨h₁, ⟨h₁.le, h₂⟩, (aleph_0_pos.trans h₁).ne', h₃⟩ /- Lean's foundations prove the existence of ℵ₀ many inaccessible cardinals -/ theorem univ_inaccessible : is_inaccessible (univ.{u v}) := is_inaccessible.mk (by simpa using lift_lt_univ' ℵ₀) (by simp) (λ c h, begin rcases lt_univ'.1 h with ⟨c, rfl⟩, rw ← lift_two_power.{u (max (u+1) v)}, apply lift_lt_univ' end) theorem lt_power_cof {c : cardinal.{u}} : ℵ₀ ≤ c → c < c ^ cof c.ord := quotient.induction_on c $ λ α h, begin rcases ord_eq α with ⟨r, wo, re⟩, resetI, have := ord_is_limit h, rw [mk_def, re] at this ⊢, rcases cof_eq' r this with ⟨S, H, Se⟩, have := sum_lt_prod (λ a:S, #{x // r x a}) (λ _, #α) (λ i, _), { simp only [cardinal.prod_const, cardinal.lift_id, ← Se, ← mk_sigma, power_def] at this ⊢, refine lt_of_le_of_lt _ this, refine ⟨embedding.of_surjective _ _⟩, { exact λ x, x.2.1 }, { exact λ a, let ⟨b, h, ab⟩ := H a in ⟨⟨⟨_, h⟩, _, ab⟩, rfl⟩ } }, { have := typein_lt_type r i, rwa [← re, lt_ord] at this } end theorem lt_cof_power {a b : cardinal} (ha : ℵ₀ ≤ a) (b1 : 1 < b) : a < cof (b ^ a).ord := begin have b0 : b ≠ 0 := (zero_lt_one.trans b1).ne', apply lt_imp_lt_of_le_imp_le (power_le_power_left $ power_ne_zero a b0), rw [←power_mul, mul_eq_self ha], exact lt_power_cof (ha.trans $ (cantor' _ b1).le), end end cardinal
2528ea577c19fd5f45f99ceec57192a6ff5d1db0
491068d2ad28831e7dade8d6dff871c3e49d9431
/tests/lean/run/rewrite10.lean
5fa5f42685e77a7efb338865728f10b54bc5a885
[ "Apache-2.0" ]
permissive
davidmueller13/lean
65a3ed141b4088cd0a268e4de80eb6778b21a0e9
c626e2e3c6f3771e07c32e82ee5b9e030de5b050
refs/heads/master
1,611,278,313,401
1,444,021,177,000
1,444,021,177,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
825
lean
import data.nat open nat section variables (a b c d e : nat) theorem T (H1 : a = b) (H2 : b = c + 1) (H3 : c = d) (H4 : e = 1 + d) : a = e := by rewrite [H1, H2, H3, add.comm, -H4] end example (x y : ℕ) : (x + y) * (x + y) = x * x + y * x + x * y + y * y := by rewrite [*mul.left_distrib, *mul.right_distrib, -add.assoc] namespace tst definition even (a : nat) := ∃b, a = 2*b theorem even_plus_even {a b : nat} (H1 : even a) (H2 : even b) : even (a + b) := exists.elim H1 (fun (w1 : nat) (Hw1 : a = 2*w1), exists.elim H2 (fun (w2 : nat) (Hw2 : b = 2*w2), exists.intro (w1 + w2) begin rewrite [Hw1, Hw2, mul.left_distrib] end)) theorem T2 (a b c : nat) (H1 : a = b) (H2 : b = c + 1) : a ≠ 0 := calc a = succ c : by rewrite [H1, H2, add_one] ... ≠ 0 : succ_ne_zero c end tst
3ef82a388c941ecbbb1b0f678320e484ecad1879
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/combinatorics/simple_graph/adj_matrix.lean
fa1cde99ecd1da7c15eb92b1e080e882b6cf21fe
[ "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
9,386
lean
/- Copyright (c) 2020 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson, Jalex Stark, Kyle Miller, Lu-Ming Zhang -/ import combinatorics.simple_graph.basic import combinatorics.simple_graph.connectivity import linear_algebra.matrix.trace import linear_algebra.matrix.symmetric /-! # Adjacency Matrices > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This module defines the adjacency matrix of a graph, and provides theorems connecting graph properties to computational properties of the matrix. ## Main definitions * `matrix.is_adj_matrix`: `A : matrix V V α` is qualified as an "adjacency matrix" if (1) every entry of `A` is `0` or `1`, (2) `A` is symmetric, (3) every diagonal entry of `A` is `0`. * `matrix.is_adj_matrix.to_graph`: for `A : matrix V V α` and `h : A.is_adj_matrix`, `h.to_graph` is the simple graph induced by `A`. * `matrix.compl`: for `A : matrix V V α`, `A.compl` is supposed to be the adjacency matrix of the complement graph of the graph induced by `A`. * `simple_graph.adj_matrix`: the adjacency matrix of a `simple_graph`. * `simple_graph.adj_matrix_pow_apply_eq_card_walk`: each entry of the `n`th power of a graph's adjacency matrix counts the number of length-`n` walks between the corresponding pair of vertices. -/ open_locale big_operators matrix open finset matrix simple_graph variables {V α β : Type*} namespace matrix /-- `A : matrix V V α` is qualified as an "adjacency matrix" if (1) every entry of `A` is `0` or `1`, (2) `A` is symmetric, (3) every diagonal entry of `A` is `0`. -/ structure is_adj_matrix [has_zero α] [has_one α] (A : matrix V V α) : Prop := (zero_or_one : ∀ i j, (A i j) = 0 ∨ (A i j) = 1 . obviously) (symm : A.is_symm . obviously) (apply_diag : ∀ i, A i i = 0 . obviously) namespace is_adj_matrix variables {A : matrix V V α} @[simp] lemma apply_diag_ne [mul_zero_one_class α] [nontrivial α] (h : is_adj_matrix A) (i : V) : ¬ A i i = 1 := by simp [h.apply_diag i] @[simp] lemma apply_ne_one_iff [mul_zero_one_class α] [nontrivial α] (h : is_adj_matrix A) (i j : V) : ¬ A i j = 1 ↔ A i j = 0 := by { obtain (h|h) := h.zero_or_one i j; simp [h] } @[simp] lemma apply_ne_zero_iff [mul_zero_one_class α] [nontrivial α] (h : is_adj_matrix A) (i j : V) : ¬ A i j = 0 ↔ A i j = 1 := by rw [←apply_ne_one_iff h, not_not] /-- For `A : matrix V V α` and `h : is_adj_matrix A`, `h.to_graph` is the simple graph whose adjacency matrix is `A`. -/ @[simps] def to_graph [mul_zero_one_class α] [nontrivial α] (h : is_adj_matrix A) : simple_graph V := { adj := λ i j, A i j = 1, symm := λ i j hij, by rwa h.symm.apply i j, loopless := λ i, by simp [h] } instance [mul_zero_one_class α] [nontrivial α] [decidable_eq α] (h : is_adj_matrix A) : decidable_rel h.to_graph.adj := by { simp only [to_graph], apply_instance } end is_adj_matrix /-- For `A : matrix V V α`, `A.compl` is supposed to be the adjacency matrix of the complement graph of the graph induced by `A.adj_matrix`. -/ def compl [has_zero α] [has_one α] [decidable_eq α] [decidable_eq V] (A : matrix V V α) : matrix V V α := λ i j, ite (i = j) 0 (ite (A i j = 0) 1 0) section compl variables [decidable_eq α] [decidable_eq V] (A : matrix V V α) @[simp] lemma compl_apply_diag [has_zero α] [has_one α] (i : V) : A.compl i i = 0 := by simp [compl] @[simp] lemma compl_apply [has_zero α] [has_one α] (i j : V) : A.compl i j = 0 ∨ A.compl i j = 1 := by { unfold compl, split_ifs; simp, } @[simp] lemma is_symm_compl [has_zero α] [has_one α] (h : A.is_symm) : A.compl.is_symm := by { ext, simp [compl, h.apply, eq_comm], } @[simp] lemma is_adj_matrix_compl [has_zero α] [has_one α] (h : A.is_symm) : is_adj_matrix A.compl := { symm := by simp [h] } namespace is_adj_matrix variable {A} @[simp] lemma compl [has_zero α] [has_one α] (h : is_adj_matrix A) : is_adj_matrix A.compl := is_adj_matrix_compl A h.symm lemma to_graph_compl_eq [mul_zero_one_class α] [nontrivial α] (h : is_adj_matrix A) : h.compl.to_graph = (h.to_graph)ᶜ := begin ext v w, cases h.zero_or_one v w with h h; by_cases hvw : v = w; simp [matrix.compl, h, hvw] end end is_adj_matrix end compl end matrix open matrix namespace simple_graph variables (G : simple_graph V) [decidable_rel G.adj] variables (α) /-- `adj_matrix G α` is the matrix `A` such that `A i j = (1 : α)` if `i` and `j` are adjacent in the simple graph `G`, and otherwise `A i j = 0`. -/ def adj_matrix [has_zero α] [has_one α] : matrix V V α := of $ λ i j, if (G.adj i j) then (1 : α) else 0 variable {α} -- TODO: set as an equation lemma for `adj_matrix`, see mathlib4#3024 @[simp] lemma adj_matrix_apply (v w : V) [has_zero α] [has_one α] : G.adj_matrix α v w = if (G.adj v w) then 1 else 0 := rfl @[simp] theorem transpose_adj_matrix [has_zero α] [has_one α] : (G.adj_matrix α)ᵀ = G.adj_matrix α := by { ext, simp [adj_comm] } @[simp] lemma is_symm_adj_matrix [has_zero α] [has_one α] : (G.adj_matrix α).is_symm := transpose_adj_matrix G variable (α) /-- The adjacency matrix of `G` is an adjacency matrix. -/ @[simp] lemma is_adj_matrix_adj_matrix [has_zero α] [has_one α] : (G.adj_matrix α).is_adj_matrix := { zero_or_one := λ i j, by by_cases G.adj i j; simp [h] } /-- The graph induced by the adjacency matrix of `G` is `G` itself. -/ lemma to_graph_adj_matrix_eq [mul_zero_one_class α] [nontrivial α] : (G.is_adj_matrix_adj_matrix α).to_graph = G := begin ext, simp only [is_adj_matrix.to_graph_adj, adj_matrix_apply, ite_eq_left_iff, zero_ne_one], apply not_not, end variables {α} [fintype V] @[simp] lemma adj_matrix_dot_product [non_assoc_semiring α] (v : V) (vec : V → α) : dot_product (G.adj_matrix α v) vec = ∑ u in G.neighbor_finset v, vec u := by simp [neighbor_finset_eq_filter, dot_product, sum_filter] @[simp] lemma dot_product_adj_matrix [non_assoc_semiring α] (v : V) (vec : V → α) : dot_product vec (G.adj_matrix α v) = ∑ u in G.neighbor_finset v, vec u := by simp [neighbor_finset_eq_filter, dot_product, sum_filter, finset.sum_apply] @[simp] lemma adj_matrix_mul_vec_apply [non_assoc_semiring α] (v : V) (vec : V → α) : ((G.adj_matrix α).mul_vec vec) v = ∑ u in G.neighbor_finset v, vec u := by rw [mul_vec, adj_matrix_dot_product] @[simp] lemma adj_matrix_vec_mul_apply [non_assoc_semiring α] (v : V) (vec : V → α) : ((G.adj_matrix α).vec_mul vec) v = ∑ u in G.neighbor_finset v, vec u := begin rw [← dot_product_adj_matrix, vec_mul], refine congr rfl _, ext, rw [← transpose_apply (adj_matrix α G) x v, transpose_adj_matrix], end @[simp] lemma adj_matrix_mul_apply [non_assoc_semiring α] (M : matrix V V α) (v w : V) : (G.adj_matrix α ⬝ M) v w = ∑ u in G.neighbor_finset v, M u w := by simp [mul_apply, neighbor_finset_eq_filter, sum_filter] @[simp] lemma mul_adj_matrix_apply [non_assoc_semiring α] (M : matrix V V α) (v w : V) : (M ⬝ G.adj_matrix α) v w = ∑ u in G.neighbor_finset w, M v u := by simp [mul_apply, neighbor_finset_eq_filter, sum_filter, adj_comm] variable (α) @[simp] theorem trace_adj_matrix [add_comm_monoid α] [has_one α] : matrix.trace (G.adj_matrix α) = 0 := by simp [matrix.trace] variable {α} theorem adj_matrix_mul_self_apply_self [non_assoc_semiring α] (i : V) : ((G.adj_matrix α) ⬝ (G.adj_matrix α)) i i = degree G i := by simp [degree] variable {G} @[simp] lemma adj_matrix_mul_vec_const_apply [semiring α] {a : α} {v : V} : (G.adj_matrix α).mul_vec (function.const _ a) v = G.degree v * a := by simp [degree] lemma adj_matrix_mul_vec_const_apply_of_regular [semiring α] {d : ℕ} {a : α} (hd : G.is_regular_of_degree d) {v : V} : (G.adj_matrix α).mul_vec (function.const _ a) v = (d * a) := by simp [hd v] theorem adj_matrix_pow_apply_eq_card_walk [decidable_eq V] [semiring α] (n : ℕ) (u v : V) : (G.adj_matrix α ^ n) u v = fintype.card {p : G.walk u v | p.length = n} := begin rw card_set_walk_length_eq, induction n with n ih generalizing u v, { obtain rfl | h := eq_or_ne u v; simp [finset_walk_length, *] }, { nth_rewrite 0 [nat.succ_eq_one_add], simp only [pow_add, pow_one, finset_walk_length, ih, mul_eq_mul, adj_matrix_mul_apply], rw finset.card_bUnion, { norm_cast, simp only [nat.cast_sum, card_map, neighbor_finset_def], apply finset.sum_to_finset_eq_subtype, }, /- Disjointness for card_bUnion -/ { rintros ⟨x, hx⟩ - ⟨y, hy⟩ - hxy, rw disjoint_iff_inf_le, intros p hp, simp only [inf_eq_inter, mem_inter, mem_map, function.embedding.coe_fn_mk, exists_prop] at hp; obtain ⟨⟨px, hpx, rfl⟩, ⟨py, hpy, hp⟩⟩ := hp, cases hp, simpa using hxy, } }, end end simple_graph namespace matrix.is_adj_matrix variables [mul_zero_one_class α] [nontrivial α] variables {A : matrix V V α} (h : is_adj_matrix A) /-- If `A` is qualified as an adjacency matrix, then the adjacency matrix of the graph induced by `A` is itself. -/ lemma adj_matrix_to_graph_eq [decidable_eq α] : h.to_graph.adj_matrix α = A := begin ext i j, obtain (h'|h') := h.zero_or_one i j; simp [h'], end end matrix.is_adj_matrix
e1a8665c79edb22cd051d16dc66fa2b3d7c81783
1b8f093752ba748c5ca0083afef2959aaa7dace5
/src/category_theory/path_category.lean
5d8dfd9ef2d16db7385d32cacc3a09a2f942b3e8
[]
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,002
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Stephen Morgan and Scott Morrison import category_theory.graphs.category import category_theory.universe_lifting -- FIXME why do we need this here? @[obviously] meta def obviously_4 := tactic.tidy { tactics := extended_tidy_tactics } open category_theory open category_theory.graphs universes u₁ u₂ variable {G : Type u₁} variable [graph G] variable {C : Type u₂} variable [small_category C] namespace category_theory.graphs def Path (C : Type u₁) := C instance PathCategory (C : Type u₁) [graph C] : small_category (Path C) := { hom := λ x y : C, path x y, id := λ x, path.nil x, comp := λ _ _ _ f g, concatenate_paths f g, comp_id' := begin tidy, induction f, -- PROJECT think about how to automate an inductive step. When can you be sure it's a good idea? obviously, end, assoc' := begin tidy, induction f, obviously, end } def path_to_morphism (H : graph_homomorphism G C) : Π {X Y : G}, path X Y → ((H.onVertices X) ⟶ (H.onVertices Y)) | ._ ._ (path.nil Z) := 𝟙 (H.onVertices Z) | ._ ._ (@path.cons ._ _ _ _ _ e p) := (H.onEdges e) ≫ (path_to_morphism p) @[simp] lemma path_to_morphism.comp (H : graph_homomorphism G C) {X Y Z : Path G} (f : X ⟶ Y) (g : Y ⟶ Z) : path_to_morphism H (f ≫ g) = path_to_morphism H f ≫ path_to_morphism H g := begin induction f, obviously, end end category_theory.graphs namespace category_theory.functor open category_theory.graphs -- PROJECT obtain this as the left adjoint to the forgetful functor. def from_GraphHomomorphism (H : graph_homomorphism G C) : (Path G) ⥤ C := { obj := λ X, (H.onVertices X), map' := λ _ _ f, (path_to_morphism H f) } end category_theory.functor
5e6f9462c44419b19e61554eecd4eab05a361653
82e44445c70db0f03e30d7be725775f122d72f3e
/src/algebra/floor.lean
dea119ef9776a42c90b855d28e7d4bcae4ddf632
[ "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
14,810
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Kevin Kappelmann -/ import tactic.linarith import tactic.abel import algebra.ordered_group import data.set.intervals.basic /-! # Floor and ceil ## Summary We define `floor`, `ceil`, `nat_floor`and `nat_ceil` functions on linear ordered rings. ## Main Definitions - `floor_ring`: Linear ordered ring with a floor function. - `floor x`: Greatest integer `z` such that `z ≤ x`. - `ceil x`: Least integer `z` such that `x ≤ z`. - `fract x`: Fractional part of `x`, defined as `x - floor x`. - `nat_floor x`: Greatest natural `n` such that `n ≤ x`. Defined as `0` if `x < 0`. - `nat_ceil x`: Least natural `n` such that `x ≤ n`. ## Notations - `⌊x⌋` is `floor x`. - `⌈x⌉` is `ceil x`. ## Tags rounding, floor, ceil -/ variables {α : Type*} open_locale classical /-! ### Floor rings -/ /-- A `floor_ring` is a linear ordered ring over `α` with a function `floor : α → ℤ` satisfying `∀ (z : ℤ) (x : α), z ≤ floor x ↔ (z : α) ≤ x)`. -/ class floor_ring (α) [linear_ordered_ring α] := (floor : α → ℤ) (le_floor : ∀ (z : ℤ) (x : α), z ≤ floor x ↔ (z : α) ≤ x) instance : floor_ring ℤ := { floor := id, le_floor := λ _ _, by rw int.cast_id; refl } variables [linear_ordered_ring α] [floor_ring α] /-- `floor x` is the greatest integer `z` such that `z ≤ x` -/ def floor : α → ℤ := floor_ring.floor notation `⌊` x `⌋` := floor x theorem le_floor : ∀ {z : ℤ} {x : α}, z ≤ ⌊x⌋ ↔ (z : α) ≤ x := floor_ring.le_floor theorem floor_lt {x : α} {z : ℤ} : ⌊x⌋ < z ↔ x < z := lt_iff_lt_of_le_iff_le le_floor theorem floor_le (x : α) : (⌊x⌋ : α) ≤ x := le_floor.1 (le_refl _) theorem floor_nonneg {x : α} : 0 ≤ ⌊x⌋ ↔ 0 ≤ x := by rw [le_floor]; refl theorem lt_succ_floor (x : α) : x < ⌊x⌋.succ := floor_lt.1 $ int.lt_succ_self _ theorem lt_floor_add_one (x : α) : x < ⌊x⌋ + 1 := by simpa only [int.succ, int.cast_add, int.cast_one] using lt_succ_floor x theorem sub_one_lt_floor (x : α) : x - 1 < ⌊x⌋ := sub_lt_iff_lt_add.2 (lt_floor_add_one x) @[simp] theorem floor_coe (z : ℤ) : ⌊(z:α)⌋ = z := eq_of_forall_le_iff $ λ a, by rw [le_floor, int.cast_le] @[simp] theorem floor_zero : ⌊(0:α)⌋ = 0 := floor_coe 0 @[simp] theorem floor_one : ⌊(1:α)⌋ = 1 := by rw [← int.cast_one, floor_coe] @[mono] theorem floor_mono {a b : α} (h : a ≤ b) : ⌊a⌋ ≤ ⌊b⌋ := le_floor.2 (le_trans (floor_le _) h) @[simp] theorem floor_add_int (x : α) (z : ℤ) : ⌊x + z⌋ = ⌊x⌋ + z := eq_of_forall_le_iff $ λ a, by rw [le_floor, ← sub_le_iff_le_add, ← sub_le_iff_le_add, le_floor, int.cast_sub] @[simp] theorem floor_int_add (z : ℤ) (x : α) : ⌊↑z + x⌋ = z + ⌊x⌋ := by simpa only [add_comm] using floor_add_int x z @[simp] theorem floor_add_nat (x : α) (n : ℕ) : ⌊x + n⌋ = ⌊x⌋ + n := floor_add_int x n @[simp] theorem floor_nat_add (n : ℕ) (x : α) : ⌊↑n + x⌋ = n + ⌊x⌋ := floor_int_add n x @[simp] theorem floor_sub_int (x : α) (z : ℤ) : ⌊x - z⌋ = ⌊x⌋ - z := eq.trans (by rw [int.cast_neg, sub_eq_add_neg]) (floor_add_int _ _) @[simp] theorem floor_sub_nat (x : α) (n : ℕ) : ⌊x - n⌋ = ⌊x⌋ - n := floor_sub_int x n lemma abs_sub_lt_one_of_floor_eq_floor {α : Type*} [linear_ordered_comm_ring α] [floor_ring α] {x y : α} (h : ⌊x⌋ = ⌊y⌋) : abs (x - y) < 1 := begin have : x < ⌊x⌋ + 1 := lt_floor_add_one x, have : y < ⌊y⌋ + 1 := lt_floor_add_one y, have : (⌊x⌋ : α) = ⌊y⌋ := int.cast_inj.2 h, have : (⌊x⌋: α) ≤ x := floor_le x, have : (⌊y⌋ : α) ≤ y := floor_le y, exact abs_sub_lt_iff.2 ⟨by linarith, by linarith⟩ end lemma floor_eq_iff {r : α} {z : ℤ} : ⌊r⌋ = z ↔ ↑z ≤ r ∧ r < (z + 1) := by rw [←le_floor, ←int.cast_one, ←int.cast_add, ←floor_lt, int.lt_add_one_iff, le_antisymm_iff, and.comm] lemma floor_ring_unique {α} [linear_ordered_ring α] (inst1 inst2 : floor_ring α) : @floor _ _ inst1 = @floor _ _ inst2 := begin ext v, suffices : (⌊v⌋ : α) ≤ v ∧ v < ⌊v⌋ + 1, by rwa [floor_eq_iff], exact ⟨floor_le v, lt_floor_add_one v⟩ end lemma floor_eq_on_Ico (n : ℤ) : ∀ x ∈ (set.Ico n (n+1) : set α), floor x = n := λ x ⟨h₀, h₁⟩, floor_eq_iff.mpr ⟨h₀, h₁⟩ lemma floor_eq_on_Ico' (n : ℤ) : ∀ x ∈ (set.Ico n (n+1) : set α), (floor x : α) = n := λ x hx, by exact_mod_cast floor_eq_on_Ico n x hx /-- The fractional part fract r of r is just r - ⌊r⌋ -/ def fract (r : α) : α := r - ⌊r⌋ -- Mathematical notation is usually {r}. Let's not even go there. @[simp] lemma floor_add_fract (r : α) : (⌊r⌋ : α) + fract r = r := by unfold fract; simp @[simp] lemma fract_add_floor (r : α) : fract r + ⌊r⌋ = r := sub_add_cancel _ _ theorem fract_nonneg (r : α) : 0 ≤ fract r := sub_nonneg.2 $ floor_le _ theorem fract_lt_one (r : α) : fract r < 1 := sub_lt.1 $ sub_one_lt_floor _ @[simp] lemma fract_zero : fract (0 : α) = 0 := by unfold fract; simp @[simp] lemma fract_coe (z : ℤ) : fract (z : α) = 0 := by unfold fract; rw floor_coe; exact sub_self _ @[simp] lemma fract_floor (r : α) : fract (⌊r⌋ : α) = 0 := fract_coe _ @[simp] lemma floor_fract (r : α) : ⌊fract r⌋ = 0 := by rw floor_eq_iff; exact ⟨fract_nonneg _, by rw [int.cast_zero, zero_add]; exact fract_lt_one r⟩ theorem fract_eq_iff {r s : α} : fract r = s ↔ 0 ≤ s ∧ s < 1 ∧ ∃ z : ℤ, r - s = z := ⟨λ h, by rw ←h; exact ⟨fract_nonneg _, fract_lt_one _, ⟨⌊r⌋, sub_sub_cancel _ _⟩⟩, begin intro h, show r - ⌊r⌋ = s, apply eq.symm, rw [eq_sub_iff_add_eq, add_comm, ←eq_sub_iff_add_eq], rcases h with ⟨hge, hlt, ⟨z, hz⟩⟩, rw [hz, int.cast_inj, floor_eq_iff, ←hz], clear hz, split; simpa [sub_eq_add_neg, add_assoc] end⟩ theorem fract_eq_fract {r s : α} : fract r = fract s ↔ ∃ z : ℤ, r - s = z := ⟨λ h, ⟨⌊r⌋ - ⌊s⌋, begin unfold fract at h, rw [int.cast_sub, sub_eq_sub_iff_sub_eq_sub.1 h], end⟩, λ h, begin rcases h with ⟨z, hz⟩, rw fract_eq_iff, split, exact fract_nonneg _, split, exact fract_lt_one _, use z + ⌊s⌋, rw [eq_add_of_sub_eq hz, int.cast_add], unfold fract, simp [sub_eq_add_neg, add_assoc] end⟩ @[simp] lemma fract_fract (r : α) : fract (fract r) = fract r := by rw fract_eq_fract; exact ⟨-⌊r⌋, by simp [sub_eq_add_neg, add_assoc, fract]⟩ theorem fract_add (r s : α) : ∃ z : ℤ, fract (r + s) - fract r - fract s = z := ⟨⌊r⌋ + ⌊s⌋ - ⌊r + s⌋, by unfold fract; simp [sub_eq_add_neg]; abel⟩ theorem fract_mul_nat (r : α) (b : ℕ) : ∃ z : ℤ, fract r * b - fract (r * b) = z := begin induction b with c hc, use 0, simp, rcases hc with ⟨z, hz⟩, rw [nat.succ_eq_add_one, nat.cast_add, mul_add, mul_add, nat.cast_one, mul_one, mul_one], rcases fract_add (r * c) r with ⟨y, hy⟩, use z - y, rw [int.cast_sub, ←hz, ←hy], abel end /-- `ceil x` is the smallest integer `z` such that `x ≤ z` -/ def ceil (x : α) : ℤ := -⌊-x⌋ notation `⌈` x `⌉` := ceil x theorem ceil_le {z : ℤ} {x : α} : ⌈x⌉ ≤ z ↔ x ≤ z := by rw [ceil, neg_le, le_floor, int.cast_neg, neg_le_neg_iff] theorem lt_ceil {x : α} {z : ℤ} : z < ⌈x⌉ ↔ (z:α) < x := lt_iff_lt_of_le_iff_le ceil_le theorem ceil_le_floor_add_one (x : α) : ⌈x⌉ ≤ ⌊x⌋ + 1 := by rw [ceil_le, int.cast_add, int.cast_one]; exact le_of_lt (lt_floor_add_one x) theorem le_ceil (x : α) : x ≤ ⌈x⌉ := ceil_le.1 (le_refl _) @[simp] theorem ceil_coe (z : ℤ) : ⌈(z:α)⌉ = z := by rw [ceil, ← int.cast_neg, floor_coe, neg_neg] theorem ceil_mono {a b : α} (h : a ≤ b) : ⌈a⌉ ≤ ⌈b⌉ := ceil_le.2 (le_trans h (le_ceil _)) @[simp] theorem ceil_add_int (x : α) (z : ℤ) : ⌈x + z⌉ = ⌈x⌉ + z := by rw [ceil, neg_add', floor_sub_int, neg_sub, sub_eq_neg_add]; refl theorem ceil_sub_int (x : α) (z : ℤ) : ⌈x - z⌉ = ⌈x⌉ - z := eq.trans (by rw [int.cast_neg, sub_eq_add_neg]) (ceil_add_int _ _) theorem ceil_lt_add_one (x : α) : (⌈x⌉ : α) < x + 1 := by rw [← lt_ceil, ← int.cast_one, ceil_add_int]; apply lt_add_one lemma ceil_pos {a : α} : 0 < ⌈a⌉ ↔ 0 < a := ⟨ λ h, have ⌊-a⌋ < 0, from neg_of_neg_pos h, pos_of_neg_neg $ lt_of_not_ge $ (not_iff_not_of_iff floor_nonneg).1 $ not_le_of_gt this, λ h, have -a < 0, from neg_neg_of_pos h, neg_pos_of_neg $ lt_of_not_ge $ (not_iff_not_of_iff floor_nonneg).2 $ not_le_of_gt this ⟩ @[simp] theorem ceil_zero : ⌈(0 : α)⌉ = 0 := by simp [ceil] lemma ceil_nonneg {q : α} (hq : 0 ≤ q) : 0 ≤ ⌈q⌉ := if h : q > 0 then le_of_lt $ ceil_pos.2 h else by rw [le_antisymm (le_of_not_lt h) hq, ceil_zero]; trivial lemma ceil_eq_iff {r : α} {z : ℤ} : ⌈r⌉ = z ↔ ↑z-1 < r ∧ r ≤ z := by rw [←ceil_le, ←int.cast_one, ←int.cast_sub, ←lt_ceil, int.sub_one_lt_iff, le_antisymm_iff, and.comm] lemma ceil_eq_on_Ioc (n : ℤ) : ∀ x ∈ (set.Ioc (n-1) n : set α), ceil x = n := λ x ⟨h₀, h₁⟩, ceil_eq_iff.mpr ⟨h₀, h₁⟩ lemma ceil_eq_on_Ioc' (n : ℤ) : ∀ x ∈ (set.Ioc (n-1) n : set α), (ceil x : α) = n := λ x hx, by exact_mod_cast ceil_eq_on_Ioc n x hx /-! ### `nat_floor` and `nat_ceil` -/ section nat variables {a : α} {n : ℕ} /-- `nat_floor x` is the greatest natural `n` that is less than `x`. It is equal to `⌊q⌋` when `q ≥ 0`, and is `0` otherwise. -/ def nat_floor (a : α) : ℕ := int.to_nat ⌊a⌋ lemma nat_floor_of_nonpos (ha : a ≤ 0) : nat_floor a = 0 := begin apply int.to_nat_of_nonpos, exact_mod_cast (floor_le a).trans ha, end lemma pos_of_nat_floor_pos (h : 0 < nat_floor a) : 0 < a := begin refine (le_or_lt a 0).resolve_left (λ ha, lt_irrefl 0 _), rwa nat_floor_of_nonpos ha at h, end lemma nat_floor_le (ha : 0 ≤ a) : ↑(nat_floor a) ≤ a := begin refine le_trans _ (floor_le _), norm_cast, exact (int.to_nat_of_nonneg (floor_nonneg.2 ha)).le, end lemma le_nat_floor_of_le (h : ↑n ≤ a) : n ≤ nat_floor a := begin have hn := int.le_to_nat n, norm_cast at hn, exact hn.trans (int.to_nat_le_to_nat (le_floor.2 h)), end theorem le_nat_floor_iff (ha : 0 ≤ a) : n ≤ nat_floor a ↔ ↑n ≤ a := ⟨λ h, (nat.cast_le.2 h).trans (nat_floor_le ha), le_nat_floor_of_le⟩ lemma lt_of_lt_nat_floor (h : n < nat_floor a) : ↑n < a := (nat.cast_lt.2 h).trans_le (nat_floor_le (pos_of_nat_floor_pos ((nat.zero_le n).trans_lt h)).le) theorem nat_floor_lt_iff (ha : 0 ≤ a) : nat_floor a < n ↔ a < ↑n := le_iff_le_iff_lt_iff_lt.1 (le_nat_floor_iff ha) theorem nat_floor_mono {a₁ a₂ : α} (h : a₁ ≤ a₂) : nat_floor a₁ ≤ nat_floor a₂ := begin obtain ha | ha := le_total a₁ 0, { rw nat_floor_of_nonpos ha, exact nat.zero_le _ }, exact le_nat_floor_of_le ((nat_floor_le ha).trans h), end @[simp] theorem nat_floor_coe (n : ℕ) : nat_floor (n : α) = n := begin rw nat_floor, convert int.to_nat_coe_nat n, exact floor_coe n, end @[simp] theorem nat_floor_zero : nat_floor (0 : α) = 0 := nat_floor_coe 0 theorem nat_floor_add_nat (ha : 0 ≤ a) (n : ℕ) : nat_floor (a + n) = nat_floor a + n := begin change int.to_nat ⌊a + (n : ℤ)⌋ = int.to_nat ⌊a⌋ + n, rw [floor_add_int, int.to_nat_add_nat (le_floor.2 ha)], end lemma lt_nat_floor_add_one (a : α) : a < nat_floor a + 1 := begin refine (lt_floor_add_one a).trans_le (add_le_add_right _ 1), norm_cast, exact int.le_to_nat _, end lemma nat_floor_eq_zero_iff : nat_floor a = 0 ↔ a < 1 := begin obtain ha | ha := le_total a 0, { exact iff_of_true (nat_floor_of_nonpos ha) (ha.trans_lt zero_lt_one) }, rw [←nat.cast_one, ←nat_floor_lt_iff ha, nat.lt_add_one_iff, nat.le_zero_iff], end /-- `nat_ceil x` is the least natural `n` that is greater than `x`. It is equal to `⌈q⌉` when `q ≥ 0`, and is `0` otherwise. -/ def nat_ceil (a : α) : ℕ := int.to_nat ⌈a⌉ theorem nat_ceil_le : nat_ceil a ≤ n ↔ a ≤ n := by rw [nat_ceil, int.to_nat_le, ceil_le]; refl theorem lt_nat_ceil : n < nat_ceil a ↔ (n : α) < a := not_iff_not.1 $ by rw [not_lt, not_lt, nat_ceil_le] theorem le_nat_ceil (a : α) : a ≤ nat_ceil a := nat_ceil_le.1 (le_refl _) theorem nat_ceil_mono {a₁ a₂ : α} (h : a₁ ≤ a₂) : nat_ceil a₁ ≤ nat_ceil a₂ := nat_ceil_le.2 (le_trans h (le_nat_ceil _)) @[simp] theorem nat_ceil_coe (n : ℕ) : nat_ceil (n : α) = n := show (⌈((n : ℤ) : α)⌉).to_nat = n, by rw [ceil_coe]; refl @[simp] theorem nat_ceil_zero : nat_ceil (0 : α) = 0 := nat_ceil_coe 0 theorem nat_ceil_add_nat {a : α} (a_nonneg : 0 ≤ a) (n : ℕ) : nat_ceil (a + n) = nat_ceil a + n := begin change int.to_nat (⌈a + (n:ℤ)⌉) = int.to_nat ⌈a⌉ + n, rw [ceil_add_int], have : 0 ≤ ⌈a⌉, by simpa using (ceil_mono a_nonneg), obtain ⟨_, ceil_a_eq⟩ : ∃ (n : ℕ), ⌈a⌉ = n, from int.eq_coe_of_zero_le this, rw ceil_a_eq, refl end theorem nat_ceil_lt_add_one {a : α} (a_nonneg : 0 ≤ a) : (nat_ceil a : α) < a + 1 := lt_nat_ceil.1 $ by rw ( show nat_ceil (a + 1) = nat_ceil a + 1, by exact_mod_cast (nat_ceil_add_nat a_nonneg 1)); apply nat.lt_succ_self lemma lt_of_nat_ceil_lt {x : α} {n : ℕ} (h : nat_ceil x < n) : x < n := lt_of_le_of_lt (le_nat_ceil x) (by exact_mod_cast h) lemma le_of_nat_ceil_le {x : α} {n : ℕ} (h : nat_ceil x ≤ n) : x ≤ n := le_trans (le_nat_ceil x) (by exact_mod_cast h) end nat namespace int @[simp] lemma preimage_Ioo {x y : α} : ((coe : ℤ → α) ⁻¹' (set.Ioo x y)) = set.Ioo (floor x) (ceil y) := by { ext, simp [floor_lt, lt_ceil] } @[simp] lemma preimage_Ico {x y : α} : ((coe : ℤ → α) ⁻¹' (set.Ico x y)) = set.Ico (ceil x) (ceil y) := by { ext, simp [ceil_le, lt_ceil] } @[simp] lemma preimage_Ioc {x y : α} : ((coe : ℤ → α) ⁻¹' (set.Ioc x y)) = set.Ioc (floor x) (floor y) := by { ext, simp [floor_lt, le_floor] } @[simp] lemma preimage_Icc {x y : α} : ((coe : ℤ → α) ⁻¹' (set.Icc x y)) = set.Icc (ceil x) (floor y) := by { ext, simp [ceil_le, le_floor] } @[simp] lemma preimage_Ioi {x : α} : ((coe : ℤ → α) ⁻¹' (set.Ioi x)) = set.Ioi (floor x) := by { ext, simp [floor_lt] } @[simp] lemma preimage_Ici {x : α} : ((coe : ℤ → α) ⁻¹' (set.Ici x)) = set.Ici (ceil x) := by { ext, simp [ceil_le] } @[simp] lemma preimage_Iio {x : α} : ((coe : ℤ → α) ⁻¹' (set.Iio x)) = set.Iio (ceil x) := by { ext, simp [lt_ceil] } @[simp] lemma preimage_Iic {x : α} : ((coe : ℤ → α) ⁻¹' (set.Iic x)) = set.Iic (floor x) := by { ext, simp [le_floor] } end int
c09ec52121a0fc63f751e9a17139832792406dab
a4673261e60b025e2c8c825dfa4ab9108246c32e
/tests/lean/run/newfrontend2.lean
4f9f2c43471e42d120b59771bce931dd13312090
[ "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
455
lean
def foo {α} (a : Option α) (b : α) : α := match a with | some a => a | none => b structure S := (x : Nat) #check if 0 == 1 then true else false def f (x : Nat) : Nat := if x < 5 then x+1 else x-1 def x := 1 #check foo x x #check match 1 with x => x + 1 #check match 1 : Int with x => x + 1 #check match 1 with | x => x + 1 #check match 1 : Int with | x => x + 1 def g (x : Nat × Nat) (y : Nat) := x.1 + x.2 + y #check (g ⟨·, 1⟩ ·)
f8e6672e9c4f71cdc9ef824f11025e33de25d537
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/tabulate.lean
06c7852355f628b7b4e9228ea4fdd3c5301c70ad
[ "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
334
lean
inductive Vector (α : Type u) : Nat → Type u | nil : Vector α 0 | cons : α → Vector α n → Vector α (n+1) deriving Repr infix:67 " :: " => Vector.cons def tabulate (f : Fin n → α) : Vector α n := match n with | 0 => Vector.nil | n+1 => f 0 :: tabulate (f ∘ Fin.succ) #eval tabulate fun i : Fin 5 => i
fe1caa11778036594aeb587a834767e9ba7ebf7d
ae1e94c332e17c7dc7051ce976d5a9eebe7ab8a5
/tests/lean/run/structInst2.lean
dfe72de7bd9bac25fc4b93efe38ba31dd60f58bc
[ "Apache-2.0" ]
permissive
dupuisf/lean4
d082d13b01243e1de29ae680eefb476961221eef
6a39c65bd28eb0e28c3870188f348c8914502718
refs/heads/master
1,676,948,755,391
1,610,665,114,000
1,610,665,114,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,518
lean
import Init.Control.Option universes u v def OptionT2 (m : Type u → Type v) (α : Type u) : Type v := m (Option α) namespace OptionT2 variables {m : Type u → Type v} [Monad m] {α β : Type u} @[inline] protected def bind (ma : OptionT2 m α) (f : α → OptionT2 m β) : OptionT2 m β := (do { let a? ← ma; (match a? with | some a => f a | none => pure none) } : m (Option β)) @[inline] protected def pure (a : α) : OptionT2 m α := (Pure.pure (some a) : m (Option α)) @[inline] protected def orelse (ma : OptionT2 m α) (mb : OptionT2 m α) : OptionT2 m α := (do { let a? ← ma; (match a? with | some a => pure (some a) | _ => mb) } : m (Option α)) @[inline] protected def fail : OptionT2 m α := (pure none : m (Option α)) end OptionT2 instance optMonad1 {m} [Monad m] : Monad (OptionT2 m) := { pure := OptionT2.pure, bind := OptionT2.bind } def optMonad2 {m} [Monad m] : Monad (OptionT m) := { pure := OptionT.pure, bind := OptionT.bind } def optAlt1 {m} [Monad m] : Alternative (OptionT m) := { failure := OptionT.fail, orElse := OptionT.orElse, toApplicative := Monad.toApplicative } def optAlt2 {m} [Monad m] : Alternative (OptionT m) := ⟨OptionT.fail, OptionT.orElse⟩ -- it works because it treats `toApplicative` as an instance implicit argument def optAlt3 {m} [Monad m] : Alternative (OptionT2 m) := { failure := OptionT2.fail, orElse := OptionT2.orelse, toApplicative := Monad.toApplicative }
7d0b56d8c5981af22066533934458c4c112e31e6
ebbdcbd7ddc89a9ef7c3b397b301d5f5272a918f
/qp/p0_stdlib/c5_dlist.lean
38e1153303637e20a5e7fe0a2564781188ca2b6a
[]
no_license
intoverflow/qvr
34b9ef23604738381ca20b7d622fd0399d88f2dd
0cfcd33fe4bf8d93851a00cec5bfd21e77105d74
refs/heads/master
1,616,591,570,371
1,492,575,772,000
1,492,575,772,000
80,061,627
0
0
null
null
null
null
UTF-8
Lean
false
false
13,379
lean
/- ----------------------------------------------------------------------- Dependent lists. ----------------------------------------------------------------------- -/ import .c1_fin namespace qp namespace stdaux universe variables ℓ₁ ℓ₂ /-! #brief A dependent list. -/ inductive dlist {A : Type ℓ₁} (B : A → Sort ℓ₂) : list A → Type (max ℓ₁ ℓ₂) | nil : dlist [] | cons : ∀ (a : A) (b : B a) (aa : list A) (bb : dlist aa) , dlist (a :: aa) -- notation `][` := dlist.nil _ -- notation h ` :Σ: ` t := dlist.cons _ h _ t /-! #brief Equality of dlists. -/ definition dlist.eq {A : Type ℓ₁} {B : A → Sort ℓ₂} : ∀ {a : A} {aa : list A} {b₁ b₂ : B a} {bb₁ bb₂ : dlist B aa} (ωb : b₁ = b₂) (ωbb : bb₁ = bb₂) , dlist.cons a b₁ aa bb₁ = dlist.cons a b₂ aa bb₂ | a aa b .(b) bb .(bb) (eq.refl .(b)) (eq.refl .(bb)) := rfl -- /-! #brief The head of a dlist. -- -/ -- definition dlist.head {A : Type ℓ₁} {B : A → Sort ℓ₂} -- : ∀ {a: A} {aa : list A} -- (bb : dlist B (a :: aa)) -- , B a -- | a aa (dlist.cons .a b .aa bb) := b /-! #brief Mapping across a dependent list. -/ definition dlist.map {A : Type ℓ₁} {B₁ B₂ : A → Sort ℓ₂} (f : ∀ {a : A}, B₁ a → B₂ a) : ∀ {aa : list A} , dlist B₁ aa → dlist B₂ aa | [] bb := dlist.nil B₂ | (a :: aa) (dlist.cons .(a) b .(aa) bb) := dlist.cons a (f b) aa (dlist.map bb) /-! #brief Mapping a map. -/ theorem dlist.map_map {A : Type ℓ₁} {B₁ B₂ B₃ : A → Sort ℓ₂} (g : ∀ {a : A}, B₂ a → B₃ a) (f : ∀ {a : A}, B₁ a → B₂ a) : ∀ {aa : list A} {bb : dlist B₁ aa} , dlist.map @g (dlist.map @f bb) = dlist.map (λ a b, g (f b)) bb | [] bb := rfl | (a :: aa) (dlist.cons .(a) b .(aa) bb) := begin apply dlist.eq, { trivial }, { apply dlist.map_map } end /-! #brief Getting an item out of a dependent list. -/ definition dlist.get {A : Type ℓ₁} {B : A → Sort ℓ₂} : ∀ {aa : list A} (bb : dlist B aa) (n : fin (list.length aa)) , B (list.get aa n) | [] bb n := fin.zero_elim n | (a :: aa) (dlist.cons .(a) b .(aa) bb) (fin.mk 0 ω) := b | (a :: aa) (dlist.cons .(a) b .(aa) bb) (fin.mk (nat.succ n) ω) := dlist.get bb { val := n, is_lt := nat.lt_of_succ_lt_succ ω } theorem dlist.get.simp {A : Type ℓ₁} {B : A → Sort ℓ₂} (a : A) (b : B a) (aa : list A) (bb : dlist B aa) (n : ℕ) (ω : nat.succ n < list.length (a :: aa)) : dlist.get (dlist.cons a b aa bb) { val := nat.succ n, is_lt := ω } == dlist.get bb { val := n, is_lt := nat.lt_of_succ_lt_succ ω } := heq.refl _ /-! #brief Congruence for dlist.get. -/ theorem dlist.congr_get {A : Type ℓ₁} {B : A → Sort ℓ₂} {aa : list A} {bb₁ bb₂ : dlist B aa} (ωbb : bb₁ = bb₂) (n : fin (list.length aa)) : dlist.get bb₁ n = dlist.get bb₂ n := by rw ωbb /-! #brief Getting an item out of a map. -/ theorem dlist.get_map {A : Type ℓ₁} {B₁ B₂ : A → Sort ℓ₂} (f : ∀ {a : A}, B₁ a → B₂ a) : ∀ {aa : list A} (bb : dlist B₁ aa) (n : fin (list.length aa)) , dlist.get (dlist.map @f bb) n = f (dlist.get bb n) | [] bb n := fin.zero_elim n | (a :: aa) (dlist.cons .(a) b .(aa) bb) (fin.mk 0 ω) := rfl | (a :: aa) (dlist.cons .(a) b .(aa) bb) (fin.mk (nat.succ n) ω) := begin dsimp [dlist.map], apply eq_of_heq, apply heq.trans (dlist.get.simp a (f b) aa (dlist.map @f bb) n ω), apply heq_of_eq, apply dlist.get_map end /-! #brief Dropping the bottom out of a finite function. -/ definition fin.drop {A : Type ℓ₁} {B : A → Sort ℓ₂} {a : A} {aa : list A} (f : ∀ (n : fin (list.length (a :: aa))), B (list.get (a :: aa) n)) : ∀ (n : fin (list.length aa)) , B (list.get aa n) | (fin.mk n ω) := f { val := nat.succ n, is_lt := nat.succ_lt_succ ω } /-! #brief Dropping on get. -/ theorem dlist.drop_get {A : Type ℓ₁} {B : A → Sort ℓ₂} : ∀ {a : A} {b : B a} {aa : list A} {bb : dlist B aa} {n : ℕ} {ω : n < list.length aa} , dlist.get (dlist.cons a b aa bb) (fin.mk (nat.succ n) (nat.succ_lt_succ ω)) == dlist.get bb (fin.mk n ω) | a b [] bb n ω := fin.zero_elim (fin.mk n ω) | a₁ b₁ (a₂ :: aa) (dlist.cons .(a₂) b₂ .(aa) bb) 0 ω := heq.refl _ | a₁ b₁ (a₂ :: aa) (dlist.cons .(a₂) b₂ .(aa) bb) (nat.succ n) ω := begin refine heq.trans (dlist.get.simp _ _ _ _ _ _) _, refine heq.trans (@dlist.drop_get _ _ _ _ n (nat.lt_of_succ_lt_succ ω)) _, apply heq.symm, apply dlist.get.simp end /-! #brief Inverse of dlist.get. -/ definition dlist.enum {A : Type ℓ₁} {B : A → Sort ℓ₂} : ∀ {aa : list A} (f : ∀ (n : fin (list.length aa)), B (list.get aa n)) , dlist B aa | [] f := dlist.nil B | (a :: aa) f := dlist.cons a (f fin.zero) aa (dlist.enum (fin.drop f)) /-! #brief When an enum is equal to a map. -/ theorem dlist.enum_eq_map {A : Type ℓ₁} {B₁ B₂ : A → Sort ℓ₂} (f : ∀ {a : A}, B₁ a → B₂ a) : ∀ {aa : list A} (bb : dlist B₁ aa) (h : ∀ (n : fin (list.length aa)), B₂ (list.get aa n)) (ωh : ∀ (n : fin (list.length aa)), h n = f (dlist.get bb n)) , dlist.enum h = @dlist.map A B₁ B₂ @f aa bb | [] bb h ωh := rfl | (a :: aa) (dlist.cons .(a) b .(aa) bb) h ωh := begin dsimp [dlist.enum, dlist.map], rw ωh, apply congr_arg, apply dlist.enum_eq_map, intro n, cases n with n ωn, dsimp [fin.drop], rw ωh, trivial end /-! #brief Getting an item out of an enumerated dlist. -/ theorem dlist.get_enum {A : Type ℓ₁} {B : A → Sort ℓ₂} : ∀ {aa : list A} (f : ∀ (n : fin (list.length aa)), B (list.get aa n)) (n : fin (list.length aa)) , dlist.get (dlist.enum f) n = f n | [] f n := fin.zero_elim n | (a :: aa) f (fin.mk 0 ω) := rfl | (a :: aa) f (fin.mk (nat.succ n) ω) := begin dsimp [dlist.enum, dlist.get], apply eq_of_heq, apply heq.trans (dlist.get.simp a (f fin.zero) aa _ n ω), apply heq_of_eq, apply eq.trans (dlist.get_enum (fin.drop f) _), trivial end /-! #brief Enumerating the dlist.get function. -/ theorem dlist.enum_get {A : Type ℓ₁} {B : A → Sort ℓ₂} : ∀ {aa : list A} {bb : dlist B aa} , dlist.enum (dlist.get bb) = bb | [] bb := begin cases bb, trivial end | (a :: aa) (dlist.cons .(a) b .(aa) bb) := begin apply dlist.eq, { trivial }, { refine eq.trans _ dlist.enum_get, apply congr_arg dlist.enum, apply funext, intro n, cases n with n ωn, unfold fin.drop, apply eq_of_heq, apply dlist.drop_get } end /-! #brief dlist.get is injective. -/ theorem dlist.get.inj {A : Type ℓ₁} {B : A → Sort ℓ₂} {aa : list A} {bb₁ bb₂ : dlist B aa} (ω : dlist.get bb₁ = dlist.get bb₂) : bb₁ = bb₂ := by calc bb₁ = dlist.enum (dlist.get bb₁) : eq.symm dlist.enum_get ... = dlist.enum (dlist.get bb₂) : by rw ω ... = bb₂ : dlist.enum_get /-! #brief Appending dlists. -/ definition dlist.append {A : Type ℓ₁} {B : A → Sort ℓ₂} : ∀ {aa₁ : list A} (bb₁ : dlist B aa₁) {aa₂ : list A} (bb₂ : dlist B aa₂) , dlist B (aa₁ ++ aa₂) | [] bb₁ aa₂ bb₂ := bb₂ | (a :: aa₁) (dlist.cons .(a) b .(aa₁) bb₁) aa₂ bb₂ := dlist.cons a b (aa₁ ++ aa₂) (dlist.append bb₁ bb₂) /-! #brief Splitting apart a dlist at an append (left part). -/ definition dlist.split_left {A : Type ℓ₁} {B : A → Sort ℓ₂} : ∀ (aa₁ : list A) {aa₂ : list A} (bb : dlist B (aa₁ ++ aa₂)) , dlist B aa₁ := λ aa₁ aa₂ bb , begin induction aa₁ with a aa₁ rec, { exact dlist.nil B }, { cases bb with a b aa₁ bb', apply dlist.cons _ b _, exact rec bb' } end /-! #brief Splitting apart a dlist at an append (right part). -/ definition dlist.split_right {A : Type ℓ₁} {B : A → Sort ℓ₂} : ∀ (aa₁ : list A) {aa₂ : list A} (bb : dlist B (aa₁ ++ aa₂)) , dlist B aa₂ := λ aa₁ aa₂ bb , begin induction aa₁ with a aa₁ rec, { exact bb }, { cases bb with a b aa₁ bb', exact rec bb'} end /-! #brief Appending the splits. -/ theorem dlist.append_split {A : Type ℓ₁} {B : A → Sort ℓ₂} : ∀ {aa₁ aa₂ : list A} {bb : dlist B (aa₁ ++ aa₂)} , dlist.append (dlist.split_left _ bb) (dlist.split_right _ bb) = bb := λ aa₁ aa₂ bb , begin induction aa₁ with a aa₁ rec, { trivial }, { cases bb with a b aa₁ bb', apply dlist.eq, { trivial }, { apply rec } } end /-! #brief Equality of appended dlists. -/ theorem dlist.append_eq {A : Type ℓ₁} {B : A → Sort ℓ₂} {aa₁ aa₂ : list A} {bb₁ bb₂ : dlist B (aa₁ ++ aa₂)} (ωleft : dlist.split_left _ bb₁ = dlist.split_left _ bb₂) (ωright : dlist.split_right _ bb₁ = dlist.split_right _ bb₂) : bb₁ = bb₂ := begin refine eq.trans (eq.symm dlist.append_split) _, refine eq.trans _ (dlist.append_split), rw [ωleft, ωright] end /-! #brief Splitting an append. -/ theorem dlist.split_left_append {A : Type ℓ₁} {B : A → Sort ℓ₂} : ∀ {aa₁ aa₂ : list A} {bb₁ : dlist B aa₁} {bb₂ : dlist B aa₂} , dlist.split_left aa₁ (dlist.append bb₁ bb₂) = bb₁ | aa₁ aa₂ bb₁ bb₂ := begin induction aa₁ with a aa₁ rec, { cases bb₁ with a b aa₁ bb₁, trivial }, { cases bb₁ with a b aa₁ bb₁, apply dlist.eq, { trivial }, { apply rec } } end /-! #brief Splitting an append. -/ theorem dlist.split_right_append {A : Type ℓ₁} {B : A → Sort ℓ₂} : ∀ {aa₁ aa₂ : list A} {bb₁ : dlist B aa₁} {bb₂ : dlist B aa₂} , dlist.split_right aa₁ (dlist.append bb₁ bb₂) = bb₂ | aa₁ aa₂ bb₁ bb₂ := begin induction aa₁ with a aa₁ rec, { cases bb₁ with a b aa₁ bb₁, trivial }, { cases bb₁ with a b aa₁ bb₁, apply rec } end /-! #brief Splitting a map. -/ theorem dlist.split_left_map {A : Type ℓ₁} {B₁ B₂ : A → Sort ℓ₂} (f : ∀ {a : A}, B₁ a → B₂ a) : ∀ {aa₁ aa₂ : list A} {bb : dlist B₁ (aa₁ ++ aa₂)} , dlist.split_left aa₁ (dlist.map @f bb) = dlist.map @f (dlist.split_left aa₁ bb) | aa₁ aa₂ bb := begin induction aa₁ with a aa₁ rec, { trivial }, { cases bb with a b aa₁ bb', apply dlist.eq, { trivial }, { apply rec } } end /-! #brief Splitting a map. -/ theorem dlist.split_right_map {A : Type ℓ₁} {B₁ B₂ : A → Sort ℓ₂} (f : ∀ {a : A}, B₁ a → B₂ a) : ∀ {aa₁ aa₂ : list A} {bb : dlist B₁ (aa₁ ++ aa₂)} , dlist.split_right aa₁ (dlist.map @f bb) = dlist.map @f (dlist.split_right aa₁ bb) | aa₁ aa₂ bb := begin induction aa₁ with a aa₁ rec, { trivial }, { cases bb with a b aa₁ bb', apply rec } end /-! #brief Getting out of an append. -/ theorem dlist.get_append {A : Type ℓ₁} {B : A → Sort ℓ₂} : ∀ {aa₁ aa₂ : list A} {bb₁ : dlist B aa₁} {bb₂ : dlist B aa₂} {n : ℕ} {ωn : n < list.length aa₁} , dlist.get (dlist.append bb₁ bb₂) (fin.mk n (list.length.grow_left ωn)) == dlist.get bb₁ (fin.mk n ωn) | aa₁ aa₂ bb₁ bb₂ n ωn := sorry /-! #brief Getting out of a split. -/ theorem dlist.get_split_left {A : Type ℓ₁} {B : A → Sort ℓ₂} : ∀ {aa₁ aa₂ : list A} {bb : dlist B (aa₁ ++ aa₂)} {n : ℕ} {ωn : n < list.length aa₁} , dlist.get (dlist.split_left aa₁ bb) (fin.mk n ωn) == dlist.get bb (fin.mk n (list.length.grow_left ωn)) := λ aa₁ aa₂ bb n ωn , sorry /-! #brief Getting out of a split. -/ theorem dlist.get_split_right {A : Type ℓ₁} {B : A → Sort ℓ₂} : ∀ {aa₁ aa₂ : list A} {bb : dlist B (aa₁ ++ aa₂)} {n : ℕ} {ωn : n < list.length aa₂} , dlist.get (dlist.split_right aa₁ bb) (fin.mk n ωn) == dlist.get bb (fin.mk (n + list.length aa₁) (list.length.grow_right ωn)) := λ aa₁ aa₂ bb n ωn , sorry /-! #brief Repeating an item as a dlist. -/ definition dlist.repeat {A : Type ℓ₁} {B : A → Sort ℓ₂} {a : A} (b : B a) : ∀ (N : ℕ) , dlist B (list.repeat a N) | 0 := dlist.nil B | (nat.succ n) := dlist.cons a b (list.repeat a n) (dlist.repeat n) /-! #brief Action of get on repeat. -/ theorem dlist.get_repeat {A : Type ℓ₁} {B : A → Sort ℓ₂} {a : A} {b : B a} : ∀ {N : ℕ} {n : fin N} , dlist.get (dlist.repeat b N) (fin.mk n^.val begin rw list.length_repeat, exact n^.is_lt end) == b | 0 n := fin.zero_elim n | (nat.succ N) (fin.mk 0 ω0) := heq.refl _ | (nat.succ N) (fin.mk (nat.succ n) ωn) := @dlist.get_repeat N (fin.mk n (nat.le_of_lt_succ ωn)) end stdaux end qp
7d8f8d1be97affd1db1e01845400a7fd4f7553b4
19cc34575500ee2e3d4586c15544632aa07a8e66
/src/topology/list.lean
966a130d2e1ba5212ec86609c5ee1ac0be8b87c4
[ "Apache-2.0" ]
permissive
LibertasSpZ/mathlib
b9fcd46625eb940611adb5e719a4b554138dade6
33f7870a49d7cc06d2f3036e22543e6ec5046e68
refs/heads/master
1,672,066,539,347
1,602,429,158,000
1,602,429,158,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,884
lean
/- Copyright (c) 2019 Reid Barton. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl Topology on lists and vectors. -/ import topology.constructions import topology.algebra.group open topological_space set filter open_locale topological_space filter variables {α : Type*} {β : Type*} [topological_space α] [topological_space β] instance : topological_space (list α) := topological_space.mk_of_nhds (traverse nhds) lemma nhds_list (as : list α) : 𝓝 as = traverse 𝓝 as := begin refine nhds_mk_of_nhds _ _ _ _, { assume l, induction l, case list.nil { exact le_refl _ }, case list.cons : a l ih { suffices : list.cons <$> pure a <*> pure l ≤ list.cons <$> 𝓝 a <*> traverse 𝓝 l, { simpa only [] with functor_norm using this }, exact filter.seq_mono (filter.map_mono $ pure_le_nhds a) ih } }, { assume l s hs, rcases (mem_traverse_sets_iff _ _).1 hs with ⟨u, hu, hus⟩, clear as hs, have : ∃v:list (set α), l.forall₂ (λa s, is_open s ∧ a ∈ s) v ∧ sequence v ⊆ s, { induction hu generalizing s, case list.forall₂.nil : hs this { existsi [], simpa only [list.forall₂_nil_left_iff, exists_eq_left] }, case list.forall₂.cons : a s as ss ht h ih t hts { rcases mem_nhds_sets_iff.1 ht with ⟨u, hut, hu⟩, rcases ih (subset.refl _) with ⟨v, hv, hvss⟩, exact ⟨u::v, list.forall₂.cons hu hv, subset.trans (set.seq_mono (set.image_subset _ hut) hvss) hts⟩ } }, rcases this with ⟨v, hv, hvs⟩, refine ⟨sequence v, mem_traverse_sets _ _ _, hvs, _⟩, { exact hv.imp (assume a s ⟨hs, ha⟩, mem_nhds_sets hs ha) }, { assume u hu, have hu := (list.mem_traverse _ _).1 hu, have : list.forall₂ (λa s, is_open s ∧ a ∈ s) u v, { refine list.forall₂.flip _, replace hv := hv.flip, simp only [list.forall₂_and_left, flip] at ⊢ hv, exact ⟨hv.1, hu.flip⟩ }, refine mem_sets_of_superset _ hvs, exact mem_traverse_sets _ _ (this.imp $ assume a s ⟨hs, ha⟩, mem_nhds_sets hs ha) } } end lemma nhds_nil : 𝓝 ([] : list α) = pure [] := by rw [nhds_list, list.traverse_nil _]; apply_instance lemma nhds_cons (a : α) (l : list α) : 𝓝 (a :: l) = list.cons <$> 𝓝 a <*> 𝓝 l := by rw [nhds_list, list.traverse_cons _, ← nhds_list]; apply_instance lemma list.tendsto_cons {a : α} {l : list α} : tendsto (λp:α×list α, list.cons p.1 p.2) (𝓝 a ×ᶠ 𝓝 l) (𝓝 (a :: l)) := by rw [nhds_cons, tendsto, map_prod]; exact le_refl _ lemma filter.tendsto.cons {α : Type*} {f : α → β} {g : α → list β} {a : _root_.filter α} {b : β} {l : list β} (hf : tendsto f a (𝓝 b)) (hg : tendsto g a (𝓝 l)) : tendsto (λa, list.cons (f a) (g a)) a (𝓝 (b :: l)) := list.tendsto_cons.comp (tendsto.prod_mk hf hg) namespace list lemma tendsto_cons_iff {β : Type*} {f : list α → β} {b : _root_.filter β} {a : α} {l : list α} : tendsto f (𝓝 (a :: l)) b ↔ tendsto (λp:α×list α, f (p.1 :: p.2)) (𝓝 a ×ᶠ 𝓝 l) b := have 𝓝 (a :: l) = (𝓝 a ×ᶠ 𝓝 l).map (λp:α×list α, (p.1 :: p.2)), begin simp only [nhds_cons, filter.prod_eq, (filter.map_def _ _).symm, (filter.seq_eq_filter_seq _ _).symm], simp [-filter.seq_eq_filter_seq, -filter.map_def, (∘)] with functor_norm, end, by rw [this, filter.tendsto_map'_iff] lemma continuous_cons : continuous (λ x : α × list α, (x.1 :: x.2 : list α)) := continuous_iff_continuous_at.mpr $ λ ⟨x, y⟩, continuous_at_fst.cons continuous_at_snd lemma tendsto_nhds {β : Type*} {f : list α → β} {r : list α → _root_.filter β} (h_nil : tendsto f (pure []) (r [])) (h_cons : ∀l a, tendsto f (𝓝 l) (r l) → tendsto (λp:α×list α, f (p.1 :: p.2)) (𝓝 a ×ᶠ 𝓝 l) (r (a::l))) : ∀l, tendsto f (𝓝 l) (r l) | [] := by rwa [nhds_nil] | (a::l) := by rw [tendsto_cons_iff]; exact h_cons l a (tendsto_nhds l) lemma continuous_at_length : ∀(l : list α), continuous_at list.length l := begin simp only [continuous_at, nhds_discrete], refine tendsto_nhds _ _, { exact tendsto_pure_pure _ _ }, { assume l a ih, dsimp only [list.length], refine tendsto.comp (tendsto_pure_pure (λx, x + 1) _) _, refine tendsto.comp ih tendsto_snd } end lemma tendsto_insert_nth' {a : α} : ∀{n : ℕ} {l : list α}, tendsto (λp:α×list α, insert_nth n p.1 p.2) (𝓝 a ×ᶠ 𝓝 l) (𝓝 (insert_nth n a l)) | 0 l := tendsto_cons | (n+1) [] := suffices tendsto (λa, []) (𝓝 a) (𝓝 ([] : list α)), by simpa [nhds_nil, tendsto, map_prod, (∘), insert_nth], tendsto_const_nhds | (n+1) (a'::l) := have 𝓝 a ×ᶠ 𝓝 (a' :: l) = (𝓝 a ×ᶠ (𝓝 a' ×ᶠ 𝓝 l)).map (λp:α×α×list α, (p.1, p.2.1 :: p.2.2)), begin simp only [nhds_cons, filter.prod_eq, (filter.map_def _ _).symm, (filter.seq_eq_filter_seq _ _).symm], simp [-filter.seq_eq_filter_seq, -filter.map_def, (∘)] with functor_norm end, begin rw [this, tendsto_map'_iff], exact (tendsto_fst.comp tendsto_snd).cons ((@tendsto_insert_nth' n l).comp $ tendsto_fst.prod_mk $ tendsto_snd.comp tendsto_snd) end lemma tendsto_insert_nth {β} {n : ℕ} {a : α} {l : list α} {f : β → α} {g : β → list α} {b : _root_.filter β} (hf : tendsto f b (𝓝 a)) (hg : tendsto g b (𝓝 l)) : tendsto (λb:β, insert_nth n (f b) (g b)) b (𝓝 (insert_nth n a l)) := tendsto_insert_nth'.comp (tendsto.prod_mk hf hg) lemma continuous_insert_nth {n : ℕ} : continuous (λp:α×list α, insert_nth n p.1 p.2) := continuous_iff_continuous_at.mpr $ assume ⟨a, l⟩, by rw [continuous_at, nhds_prod_eq]; exact tendsto_insert_nth' lemma tendsto_remove_nth : ∀{n : ℕ} {l : list α}, tendsto (λl, remove_nth l n) (𝓝 l) (𝓝 (remove_nth l n)) | _ [] := by rw [nhds_nil]; exact tendsto_pure_nhds _ _ | 0 (a::l) := by rw [tendsto_cons_iff]; exact tendsto_snd | (n+1) (a::l) := begin rw [tendsto_cons_iff], dsimp [remove_nth], exact tendsto_fst.cons ((@tendsto_remove_nth n l).comp tendsto_snd) end lemma continuous_remove_nth {n : ℕ} : continuous (λl : list α, remove_nth l n) := continuous_iff_continuous_at.mpr $ assume a, tendsto_remove_nth @[to_additive] lemma tendsto_prod [monoid α] [has_continuous_mul α] {l : list α} : tendsto list.prod (𝓝 l) (𝓝 l.prod) := begin induction l with x l ih, { simp [nhds_nil, mem_of_nhds, tendsto_pure_left] {contextual := tt} }, simp_rw [tendsto_cons_iff, prod_cons], have := continuous_iff_continuous_at.mp continuous_mul (x, l.prod), rw [continuous_at, nhds_prod_eq] at this, exact this.comp (tendsto_id.prod_map ih) end @[to_additive] lemma continuous_prod [monoid α] [has_continuous_mul α] : continuous (prod : list α → α) := continuous_iff_continuous_at.mpr $ λ l, tendsto_prod end list namespace vector open list instance (n : ℕ) : topological_space (vector α n) := by unfold vector; apply_instance lemma tendsto_cons {n : ℕ} {a : α} {l : vector α n}: tendsto (λp:α×vector α n, vector.cons p.1 p.2) (𝓝 a ×ᶠ 𝓝 l) (𝓝 (a :: l)) := by { simp [tendsto_subtype_rng, ←subtype.val_eq_coe, cons_val], exact tendsto_fst.cons (tendsto.comp continuous_at_subtype_coe tendsto_snd) } lemma tendsto_insert_nth {n : ℕ} {i : fin (n+1)} {a:α} : ∀{l:vector α n}, tendsto (λp:α×vector α n, insert_nth p.1 i p.2) (𝓝 a ×ᶠ 𝓝 l) (𝓝 (insert_nth a i l)) | ⟨l, hl⟩ := begin rw [insert_nth, tendsto_subtype_rng], simp [insert_nth_val], exact list.tendsto_insert_nth tendsto_fst (tendsto.comp continuous_at_subtype_coe tendsto_snd : _) end lemma continuous_insert_nth' {n : ℕ} {i : fin (n+1)} : continuous (λp:α×vector α n, insert_nth p.1 i p.2) := continuous_iff_continuous_at.mpr $ assume ⟨a, l⟩, by rw [continuous_at, nhds_prod_eq]; exact tendsto_insert_nth lemma continuous_insert_nth {n : ℕ} {i : fin (n+1)} {f : β → α} {g : β → vector α n} (hf : continuous f) (hg : continuous g) : continuous (λb, insert_nth (f b) i (g b)) := continuous_insert_nth'.comp (continuous.prod_mk hf hg) lemma continuous_at_remove_nth {n : ℕ} {i : fin (n+1)} : ∀{l:vector α (n+1)}, continuous_at (remove_nth i) l | ⟨l, hl⟩ := -- ∀{l:vector α (n+1)}, tendsto (remove_nth i) (𝓝 l) (𝓝 (remove_nth i l)) --| ⟨l, hl⟩ := begin rw [continuous_at, remove_nth, tendsto_subtype_rng], simp only [← subtype.val_eq_coe, vector.remove_nth_val], exact tendsto.comp list.tendsto_remove_nth continuous_at_subtype_coe, end lemma continuous_remove_nth {n : ℕ} {i : fin (n+1)} : continuous (remove_nth i : vector α (n+1) → vector α n) := continuous_iff_continuous_at.mpr $ assume ⟨a, l⟩, continuous_at_remove_nth end vector
b635d86af213dea04a5afda694cda675dbb11207
9dc8cecdf3c4634764a18254e94d43da07142918
/src/representation_theory/fdRep.lean
054983741e6a12891774139376c4b57d31c7dba1
[ "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
4,542
lean
/- Copyright (c) 2022 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import representation_theory.Rep import algebra.category.FinVect import representation_theory.basic /-! # `fdRep k G` is the category of finite dimensional `k`-linear representations of `G`. If `V : fdRep k G`, there is a coercion that allows you to treat `V` as a type, and this type comes equipped with `module k V` and `finite_dimensional k V` instances. Also `V.ρ` gives the homomorphism `G →* (V →ₗ[k] V)`. Conversely, given a homomorphism `ρ : G →* (V →ₗ[k] V)`, you can construct the bundled representation as `Rep.of ρ`. We verify that `fdRep k G` is a rigid monoidal category. ## TODO * `fdRep k G` has all finite (co)limits. * `fdRep k G` is abelian. * `fdRep k G ≌ FinVect (monoid_algebra k G)` (this will require generalising `FinVect` first). * Upgrade the right rigid structure to a rigid structure. -/ universes u open category_theory open category_theory.limits /-- The category of finite dimensional `k`-linear representations of a monoid `G`. -/ @[derive [large_category, concrete_category/-, has_limits, has_colimits-/]] abbreviation fdRep (k G : Type u) [field k] [monoid G] := Action (FinVect.{u} k) (Mon.of G) namespace fdRep variables {k G : Type u} [field k] [monoid G] instance : has_coe_to_sort (fdRep k G) (Type u) := concrete_category.has_coe_to_sort _ instance (V : fdRep k G) : add_comm_group V := by { change add_comm_group ((forget₂ (fdRep k G) (FinVect k)).obj V).obj, apply_instance, } instance (V : fdRep k G) : module k V := by { change module k ((forget₂ (fdRep k G) (FinVect k)).obj V).obj, apply_instance, } instance (V : fdRep k G) : finite_dimensional k V := by { change finite_dimensional k ((forget₂ (fdRep k G) (FinVect k)).obj V).obj, apply_instance, } /-- The monoid homomorphism corresponding to the action of `G` onto `V : fdRep k G`. -/ def ρ (V : fdRep k G) : G →* (V →ₗ[k] V) := V.ρ /-- The underlying `linear_equiv` of an isomorphism of representations. -/ def iso_to_linear_equiv {V W : fdRep k G} (i : V ≅ W) : V ≃ₗ[k] W := FinVect.iso_to_linear_equiv ((Action.forget (FinVect k) (Mon.of G)).map_iso i) lemma iso.conj_ρ {V W : fdRep k G} (i : V ≅ W) (g : G) : W.ρ g = (fdRep.iso_to_linear_equiv i).conj (V.ρ g) := begin rw [fdRep.iso_to_linear_equiv, ←FinVect.iso.conj_eq_conj, iso.conj_apply], rw [iso.eq_inv_comp ((Action.forget (FinVect k) (Mon.of G)).map_iso i)], exact (i.hom.comm g).symm, end -- This works well with the new design for representations: example (V : fdRep k G) : G →* (V →ₗ[k] V) := V.ρ /-- Lift an unbundled representation to `fdRep`. -/ @[simps ρ] def of {V : Type u} [add_comm_group V] [module k V] [finite_dimensional k V] (ρ : representation k G V) : fdRep k G := ⟨FinVect.of k V, ρ⟩ instance : has_forget₂ (fdRep k G) (Rep k G) := { forget₂ := (forget₂ (FinVect k) (Module k)).map_Action (Mon.of G), } -- Verify that the monoidal structure is available. example : monoidal_category (fdRep k G) := by apply_instance end fdRep namespace fdRep variables {k G : Type u} [field k] [group G] -- Verify that the rigid structure is available when the monoid is a group. noncomputable instance : right_rigid_category (fdRep k G) := by { change right_rigid_category (Action (FinVect k) (Group.of G)), apply_instance, } end fdRep namespace fdRep open representation variables {k G V W : Type u} [field k] [group G] variables [add_comm_group V] [module k V] [add_comm_group W] [module k W] variables [finite_dimensional k V] [finite_dimensional k W] variables (ρV : representation k G V) (ρW : representation k G W) /-- Auxiliary definition for `fdRep.dual_tensor_iso_lin_hom`. -/ noncomputable def dual_tensor_iso_lin_hom_aux : ((fdRep.of ρV.dual) ⊗ (fdRep.of ρW)).V ≅ (fdRep.of (lin_hom ρV ρW)).V := (dual_tensor_hom_equiv k V W).to_FinVect_iso /-- When `V` and `W` are finite dimensional representations of a group `G`, the isomorphism `dual_tensor_hom_equiv k V W` of vector spaces induces an isomorphism of representations. -/ noncomputable def dual_tensor_iso_lin_hom : (fdRep.of ρV.dual) ⊗ (fdRep.of ρW) ≅ fdRep.of (lin_hom ρV ρW) := begin apply Action.mk_iso (dual_tensor_iso_lin_hom_aux ρV ρW), convert (dual_tensor_hom_comm ρV ρW), end @[simp] lemma dual_tensor_iso_lin_hom_hom_hom : (dual_tensor_iso_lin_hom ρV ρW).hom.hom = dual_tensor_hom k V W := rfl end fdRep
f81ba6c40340f14bde3f420d0c354f6d9b9f24d9
2a70b774d16dbdf5a533432ee0ebab6838df0948
/_target/deps/mathlib/src/group_theory/perm/sign.lean
b5ea227919e2d0c953b07508a882a28efa4483ef
[ "Apache-2.0" ]
permissive
hjvromen/lewis
40b035973df7c77ebf927afab7878c76d05ff758
105b675f73630f028ad5d890897a51b3c1146fb0
refs/heads/master
1,677,944,636,343
1,676,555,301,000
1,676,555,301,000
327,553,599
0
0
null
null
null
null
UTF-8
Lean
false
false
39,140
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import data.fintype.basic import data.finset.sort import algebra.group.conj import algebra.big_operators.basic import group_theory.perm.basic /-! # Sign of a permutation The main definition of this file is `equiv.perm.sign`, associating a `units ℤ` sign with a permutation. This file also contains miscellaneous lemmas about `equiv.perm` and `equiv.swap`, building on top of those in `data/equiv/basic` and `data/equiv/perm`. -/ universes u v open equiv function fintype finset open_locale big_operators variables {α : Type u} {β : Type v} namespace equiv.perm /-- `mod_swap i j` contains permutations up to swapping `i` and `j`. We use this to partition permutations in `matrix.det_zero_of_row_eq`, such that each partition sums up to `0`. -/ def mod_swap [decidable_eq α] (i j : α) : setoid (perm α) := ⟨λ σ τ, σ = τ ∨ σ = swap i j * τ, λ σ, or.inl (refl σ), λ σ τ h, or.cases_on h (λ h, or.inl h.symm) (λ h, or.inr (by rw [h, swap_mul_self_mul])), λ σ τ υ hστ hτυ, by cases hστ; cases hτυ; try {rw [hστ, hτυ, swap_mul_self_mul]}; finish⟩ instance {α : Type*} [fintype α] [decidable_eq α] (i j : α) : decidable_rel (mod_swap i j).r := λ σ τ, or.decidable /-- If the permutation `f` fixes the subtype `{x // p x}`, then this returns the permutation on `{x // p x}` induced by `f`. -/ def subtype_perm (f : perm α) {p : α → Prop} (h : ∀ x, p x ↔ p (f x)) : perm {x // p x} := ⟨λ x, ⟨f x, (h _).1 x.2⟩, λ x, ⟨f⁻¹ x, (h (f⁻¹ x)).2 $ by simpa using x.2⟩, λ _, by simp only [perm.inv_apply_self, subtype.coe_eta, subtype.coe_mk], λ _, by simp only [perm.apply_inv_self, subtype.coe_eta, subtype.coe_mk]⟩ @[simp] lemma subtype_perm_one (p : α → Prop) (h : ∀ x, p x ↔ p ((1 : perm α) x)) : @subtype_perm α 1 p h = 1 := equiv.ext $ λ ⟨_, _⟩, rfl /-- The inclusion map of permutations on a subtype of `α` into permutations of `α`, fixing the other points. -/ def of_subtype {p : α → Prop} [decidable_pred p] : perm (subtype p) →* perm α := { to_fun := λ f, ⟨λ x, if h : p x then f ⟨x, h⟩ else x, λ x, if h : p x then f⁻¹ ⟨x, h⟩ else x, λ x, have h : ∀ h : p x, p (f ⟨x, h⟩), from λ h, (f ⟨x, h⟩).2, by { simp only [], split_ifs at *; simp only [perm.inv_apply_self, subtype.coe_eta, subtype.coe_mk, not_true, *] at * }, λ x, have h : ∀ h : p x, p (f⁻¹ ⟨x, h⟩), from λ h, (f⁻¹ ⟨x, h⟩).2, by { simp only [], split_ifs at *; simp only [perm.apply_inv_self, subtype.coe_eta, subtype.coe_mk, not_true, *] at *}⟩, map_one' := begin ext, dsimp, split_ifs; refl, end, map_mul' := λ f g, equiv.ext $ λ x, begin by_cases h : p x, { have h₁ : p (f (g ⟨x, h⟩)), from (f (g ⟨x, h⟩)).2, have h₂ : p (g ⟨x, h⟩), from (g ⟨x, h⟩).2, simp only [h, h₂, coe_fn_mk, perm.mul_apply, dif_pos, subtype.coe_eta] }, { simp only [h, coe_fn_mk, perm.mul_apply, dif_neg, not_false_iff] } end } /-- Two permutations `f` and `g` are `disjoint` if their supports are disjoint, i.e., every element is fixed either by `f`, or by `g`. -/ def disjoint (f g : perm α) := ∀ x, f x = x ∨ g x = x @[symm] lemma disjoint.symm {f g : perm α} : disjoint f g → disjoint g f := by simp only [disjoint, or.comm, imp_self] lemma disjoint_comm {f g : perm α} : disjoint f g ↔ disjoint g f := ⟨disjoint.symm, disjoint.symm⟩ lemma disjoint_mul_comm {f g : perm α} (h : disjoint f g) : f * g = g * f := equiv.ext $ λ x, (h x).elim (λ hf, (h (g x)).elim (λ hg, by simp [mul_apply, hf, hg]) (λ hg, by simp [mul_apply, hf, g.injective hg])) (λ hg, (h (f x)).elim (λ hf, by simp [mul_apply, f.injective hf, hg]) (λ hf, by simp [mul_apply, hf, hg])) @[simp] lemma disjoint_one_left (f : perm α) : disjoint 1 f := λ _, or.inl rfl @[simp] lemma disjoint_one_right (f : perm α) : disjoint f 1 := λ _, or.inr rfl lemma disjoint_mul_left {f g h : perm α} (H1 : disjoint f h) (H2 : disjoint g h) : disjoint (f * g) h := λ x, by cases H1 x; cases H2 x; simp * lemma disjoint_mul_right {f g h : perm α} (H1 : disjoint f g) (H2 : disjoint f h) : disjoint f (g * h) := by rw disjoint_comm; exact disjoint_mul_left H1.symm H2.symm lemma disjoint_prod_right {f : perm α} (l : list (perm α)) (h : ∀ g ∈ l, disjoint f g) : disjoint f l.prod := begin induction l with g l ih, { exact disjoint_one_right _ }, { rw list.prod_cons; exact disjoint_mul_right (h _ (list.mem_cons_self _ _)) (ih (λ g hg, h g (list.mem_cons_of_mem _ hg))) } end lemma disjoint_prod_perm {l₁ l₂ : list (perm α)} (hl : l₁.pairwise disjoint) (hp : l₁ ~ l₂) : l₁.prod = l₂.prod := hp.prod_eq' $ hl.imp $ λ f g, disjoint_mul_comm lemma of_subtype_subtype_perm {f : perm α} {p : α → Prop} [decidable_pred p] (h₁ : ∀ x, p x ↔ p (f x)) (h₂ : ∀ x, f x ≠ x → p x) : of_subtype (subtype_perm f h₁) = f := equiv.ext $ λ x, begin rw [of_subtype, subtype_perm], by_cases hx : p x, { simp only [hx, coe_fn_mk, dif_pos, monoid_hom.coe_mk, subtype.coe_mk]}, { haveI := classical.prop_decidable, simp only [hx, not_not.mp (mt (h₂ x) hx), coe_fn_mk, dif_neg, not_false_iff, monoid_hom.coe_mk] } end lemma of_subtype_apply_of_not_mem {p : α → Prop} [decidable_pred p] (f : perm (subtype p)) {x : α} (hx : ¬ p x) : of_subtype f x = x := dif_neg hx lemma mem_iff_of_subtype_apply_mem {p : α → Prop} [decidable_pred p] (f : perm (subtype p)) (x : α) : p x ↔ p ((of_subtype f : α → α) x) := if h : p x then by dsimp [of_subtype]; simpa [h] using (f ⟨x, h⟩).2 else by simp [h, of_subtype_apply_of_not_mem f h] @[simp] lemma subtype_perm_of_subtype {p : α → Prop} [decidable_pred p] (f : perm (subtype p)) : subtype_perm (of_subtype f) (mem_iff_of_subtype_apply_mem f) = f := equiv.ext $ λ ⟨x, hx⟩, by dsimp [subtype_perm, of_subtype]; simp [show p x, from hx] lemma pow_apply_eq_self_of_apply_eq_self {f : perm α} {x : α} (hfx : f x = x) : ∀ n : ℕ, (f ^ n) x = x | 0 := rfl | (n+1) := by rw [pow_succ', mul_apply, hfx, pow_apply_eq_self_of_apply_eq_self] lemma gpow_apply_eq_self_of_apply_eq_self {f : perm α} {x : α} (hfx : f x = x) : ∀ n : ℤ, (f ^ n) x = x | (n : ℕ) := pow_apply_eq_self_of_apply_eq_self hfx n | -[1+ n] := by rw [gpow_neg_succ_of_nat, inv_eq_iff_eq, pow_apply_eq_self_of_apply_eq_self hfx] lemma pow_apply_eq_of_apply_apply_eq_self {f : perm α} {x : α} (hffx : f (f x) = x) : ∀ n : ℕ, (f ^ n) x = x ∨ (f ^ n) x = f x | 0 := or.inl rfl | (n+1) := (pow_apply_eq_of_apply_apply_eq_self n).elim (λ h, or.inr (by rw [pow_succ, mul_apply, h])) (λ h, or.inl (by rw [pow_succ, mul_apply, h, hffx])) lemma gpow_apply_eq_of_apply_apply_eq_self {f : perm α} {x : α} (hffx : f (f x) = x) : ∀ i : ℤ, (f ^ i) x = x ∨ (f ^ i) x = f x | (n : ℕ) := pow_apply_eq_of_apply_apply_eq_self hffx n | -[1+ n] := by rw [gpow_neg_succ_of_nat, inv_eq_iff_eq, ← injective.eq_iff f.injective, ← mul_apply, ← pow_succ, eq_comm, inv_eq_iff_eq, ← mul_apply, ← pow_succ', @eq_comm _ x, or.comm]; exact pow_apply_eq_of_apply_apply_eq_self hffx _ variable [decidable_eq α] /-- The `finset` of nonfixed points of a permutation. -/ def support [fintype α] (f : perm α) := univ.filter (λ x, f x ≠ x) @[simp] lemma mem_support [fintype α] {f : perm α} {x : α} : x ∈ f.support ↔ f x ≠ x := by simp only [support, true_and, mem_filter, mem_univ] /-- `f.is_swap` indicates that the permutation `f` is a transposition of two elements. -/ def is_swap (f : perm α) := ∃ x y, x ≠ y ∧ f = swap x y lemma is_swap_of_subtype {p : α → Prop} [decidable_pred p] {f : perm (subtype p)} (h : is_swap f) : is_swap (of_subtype f) := let ⟨⟨x, hx⟩, ⟨y, hy⟩, hxy⟩ := h in ⟨x, y, by simp only [ne.def] at hxy; tauto, equiv.ext $ λ z, begin rw [hxy.2, of_subtype], simp only [swap_apply_def, coe_fn_mk, swap_inv, subtype.mk_eq_mk, monoid_hom.coe_mk], split_ifs; rw subtype.coe_mk <|> cc, end⟩ lemma ne_and_ne_of_swap_mul_apply_ne_self {f : perm α} {x y : α} (hy : (swap x (f x) * f) y ≠ y) : f y ≠ y ∧ y ≠ x := begin simp only [swap_apply_def, mul_apply, injective.eq_iff f.injective] at *, by_cases h : f y = x, { split; intro; simp only [*, if_true, eq_self_iff_true, not_true, ne.def] at *}, { split_ifs at hy; cc } end lemma support_swap_mul_eq [fintype α] {f : perm α} {x : α} (hffx : f (f x) ≠ x) : (swap x (f x) * f).support = f.support.erase x := have hfx : f x ≠ x, from λ hfx, by simpa [hfx] using hffx, finset.ext $ λ y, ⟨λ hy, have hy' : (swap x (f x) * f) y ≠ y, from mem_support.1 hy, mem_erase.2 ⟨λ hyx, by simp [hyx, mul_apply, *] at *, mem_support.2 $ λ hfy, by simp only [mul_apply, swap_apply_def, hfy] at hy'; split_ifs at hy'; simp only [*, eq_self_iff_true, not_true, ne.def, apply_eq_iff_eq] at *⟩, λ hy, by simp only [mem_erase, mem_support, swap_apply_def, mul_apply] at *; intro; split_ifs at *; simp only [*, eq_self_iff_true, not_true, ne.def] at *⟩ lemma card_support_swap_mul [fintype α] {f : perm α} {x : α} (hx : f x ≠ x) : (swap x (f x) * f).support.card < f.support.card := finset.card_lt_card ⟨λ z hz, mem_support.2 (ne_and_ne_of_swap_mul_apply_ne_self (mem_support.1 hz)).1, λ h, absurd (h (mem_support.2 hx)) (mt mem_support.1 (by simp))⟩ /-- Given a list `l : list α` and a permutation `f : perm α` such that the nonfixed points of `f` are in `l`, recursively factors `f` as a product of transpositions. -/ def swap_factors_aux : Π (l : list α) (f : perm α), (∀ {x}, f x ≠ x → x ∈ l) → {l : list (perm α) // l.prod = f ∧ ∀ g ∈ l, is_swap g} | [] := λ f h, ⟨[], equiv.ext $ λ x, by rw [list.prod_nil]; exact eq.symm (not_not.1 (mt h (list.not_mem_nil _))), by simp⟩ | (x :: l) := λ f h, if hfx : x = f x then swap_factors_aux l f (λ y hy, list.mem_of_ne_of_mem (λ h : y = x, by simpa [h, hfx.symm] using hy) (h hy)) else let m := swap_factors_aux l (swap x (f x) * f) (λ y hy, have f y ≠ y ∧ y ≠ x, from ne_and_ne_of_swap_mul_apply_ne_self hy, list.mem_of_ne_of_mem this.2 (h this.1)) in ⟨swap x (f x) :: m.1, by rw [list.prod_cons, m.2.1, ← mul_assoc, mul_def (swap x (f x)), swap_swap, ← one_def, one_mul], λ g hg, ((list.mem_cons_iff _ _ _).1 hg).elim (λ h, ⟨x, f x, hfx, h⟩) (m.2.2 _)⟩ /-- `swap_factors` represents a permutation as a product of a list of transpositions. The representation is non unique and depends on the linear order structure. For types without linear order `trunc_swap_factors` can be used -/ def swap_factors [fintype α] [linear_order α] (f : perm α) : {l : list (perm α) // l.prod = f ∧ ∀ g ∈ l, is_swap g} := swap_factors_aux ((@univ α _).sort (≤)) f (λ _ _, (mem_sort _).2 (mem_univ _)) /-- This computably represents the fact that any permutation can be represented as the product of a list of transpositions. -/ def trunc_swap_factors [fintype α] (f : perm α) : trunc {l : list (perm α) // l.prod = f ∧ ∀ g ∈ l, is_swap g} := quotient.rec_on_subsingleton (@univ α _).1 (λ l h, trunc.mk (swap_factors_aux l f h)) (show ∀ x, f x ≠ x → x ∈ (@univ α _).1, from λ _ _, mem_univ _) /-- An induction principle for permutations. If `P` holds for the identity permutation, and is preserved under composition with a non-trivial swap, then `P` holds for all permutations. -/ @[elab_as_eliminator] lemma swap_induction_on [fintype α] {P : perm α → Prop} (f : perm α) : P 1 → (∀ f x y, x ≠ y → P f → P (swap x y * f)) → P f := begin cases trunc.out (trunc_swap_factors f) with l hl, induction l with g l ih generalizing f, { simp only [hl.left.symm, list.prod_nil, forall_true_iff] {contextual := tt}}, { assume h1 hmul_swap, rcases hl.2 g (by simp) with ⟨x, y, hxy⟩, rw [← hl.1, list.prod_cons, hxy.2], exact hmul_swap _ _ _ hxy.1 (ih _ ⟨rfl, λ v hv, hl.2 _ (list.mem_cons_of_mem _ hv)⟩ h1 hmul_swap) } end /-- Like `swap_induction_on`, but with the composition on the right of `f`. An induction principle for permutations. If `P` holds for the identity permutation, and is preserved under composition with a non-trivial swap, then `P` holds for all permutations. -/ @[elab_as_eliminator] lemma swap_induction_on' [fintype α] {P : perm α → Prop} (f : perm α) : P 1 → (∀ f x y, x ≠ y → P f → P (f * swap x y)) → P f := λ h1 IH, inv_inv f ▸ swap_induction_on f⁻¹ h1 (λ f, IH f⁻¹) lemma is_conj_swap {w x y z : α} (hwx : w ≠ x) (hyz : y ≠ z) : is_conj (swap w x) (swap y z) := have h : ∀ {y z : α}, y ≠ z → w ≠ z → (swap w y * swap x z) * swap w x * (swap w y * swap x z)⁻¹ = swap y z := λ y z hyz hwz, by rw [mul_inv_rev, swap_inv, swap_inv, mul_assoc (swap w y), mul_assoc (swap w y), ← mul_assoc _ (swap x z), swap_mul_swap_mul_swap hwx hwz, ← mul_assoc, swap_mul_swap_mul_swap hwz.symm hyz.symm], if hwz : w = z then have hwy : w ≠ y, by cc, ⟨swap w z * swap x y, by rw [swap_comm y z, h hyz.symm hwy]⟩ else ⟨swap w y * swap x z, h hyz hwz⟩ /-- set of all pairs (⟨a, b⟩ : Σ a : fin n, fin n) such that b < a -/ def fin_pairs_lt (n : ℕ) : finset (Σ a : fin n, fin n) := (univ : finset (fin n)).sigma (λ a, (range a).attach_fin (λ m hm, lt_trans (mem_range.1 hm) a.2)) lemma mem_fin_pairs_lt {n : ℕ} {a : Σ a : fin n, fin n} : a ∈ fin_pairs_lt n ↔ a.2 < a.1 := by simp only [fin_pairs_lt, fin.lt_iff_coe_lt_coe, true_and, mem_attach_fin, mem_range, mem_univ, mem_sigma] /-- `sign_aux σ` is the sign of a permutation on `fin n`, defined as the parity of the number of pairs `(x₁, x₂)` such that `x₂ < x₁` but `σ x₁ ≤ σ x₂` -/ def sign_aux {n : ℕ} (a : perm (fin n)) : units ℤ := ∏ x in fin_pairs_lt n, if a x.1 ≤ a x.2 then -1 else 1 @[simp] lemma sign_aux_one (n : ℕ) : sign_aux (1 : perm (fin n)) = 1 := begin unfold sign_aux, conv { to_rhs, rw ← @finset.prod_const_one _ (units ℤ) (fin_pairs_lt n) }, exact finset.prod_congr rfl (λ a ha, if_neg (not_le_of_gt (mem_fin_pairs_lt.1 ha))) end /-- `sign_bij_aux f ⟨a, b⟩` returns the pair consisting of `f a` and `f b` in decreasing order. -/ def sign_bij_aux {n : ℕ} (f : perm (fin n)) (a : Σ a : fin n, fin n) : Σ a : fin n, fin n := if hxa : f a.2 < f a.1 then ⟨f a.1, f a.2⟩ else ⟨f a.2, f a.1⟩ lemma sign_bij_aux_inj {n : ℕ} {f : perm (fin n)} : ∀ a b : Σ a : fin n, fin n, a ∈ fin_pairs_lt n → b ∈ fin_pairs_lt n → sign_bij_aux f a = sign_bij_aux f b → a = b := λ ⟨a₁, a₂⟩ ⟨b₁, b₂⟩ ha hb h, begin unfold sign_bij_aux at h, rw mem_fin_pairs_lt at *, have : ¬b₁ < b₂ := not_lt_of_ge (le_of_lt hb), split_ifs at h; simp only [*, (equiv.injective f).eq_iff, eq_self_iff_true, and_self, heq_iff_eq] at *, end lemma sign_bij_aux_surj {n : ℕ} {f : perm (fin n)} : ∀ a ∈ fin_pairs_lt n, ∃ b ∈ fin_pairs_lt n, a = sign_bij_aux f b := λ ⟨a₁, a₂⟩ ha, if hxa : f⁻¹ a₂ < f⁻¹ a₁ then ⟨⟨f⁻¹ a₁, f⁻¹ a₂⟩, mem_fin_pairs_lt.2 hxa, by dsimp [sign_bij_aux]; rw [apply_inv_self, apply_inv_self, dif_pos (mem_fin_pairs_lt.1 ha)]⟩ else ⟨⟨f⁻¹ a₂, f⁻¹ a₁⟩, mem_fin_pairs_lt.2 $ lt_of_le_of_ne (le_of_not_gt hxa) $ λ h, by simpa [mem_fin_pairs_lt, (f⁻¹).injective h, lt_irrefl] using ha, by dsimp [sign_bij_aux]; rw [apply_inv_self, apply_inv_self, dif_neg (not_lt_of_ge (le_of_lt (mem_fin_pairs_lt.1 ha)))]⟩ lemma sign_bij_aux_mem {n : ℕ} {f : perm (fin n)}: ∀ a : Σ a : fin n, fin n, a ∈ fin_pairs_lt n → sign_bij_aux f a ∈ fin_pairs_lt n := λ ⟨a₁, a₂⟩ ha, begin unfold sign_bij_aux, split_ifs with h, { exact mem_fin_pairs_lt.2 h }, { exact mem_fin_pairs_lt.2 (lt_of_le_of_ne (le_of_not_gt h) (λ h, ne_of_lt (mem_fin_pairs_lt.1 ha) (f.injective h.symm))) } end @[simp] lemma sign_aux_inv {n : ℕ} (f : perm (fin n)) : sign_aux f⁻¹ = sign_aux f := prod_bij (λ a ha, sign_bij_aux f⁻¹ a) sign_bij_aux_mem (λ ⟨a, b⟩ hab, if h : f⁻¹ b < f⁻¹ a then by rw [sign_bij_aux, dif_pos h, if_neg (not_le_of_gt h), apply_inv_self, apply_inv_self, if_neg (not_le_of_gt $ mem_fin_pairs_lt.1 hab)] else by rw [sign_bij_aux, if_pos (le_of_not_gt h), dif_neg h, apply_inv_self, apply_inv_self, if_pos (le_of_lt $ mem_fin_pairs_lt.1 hab)]) sign_bij_aux_inj sign_bij_aux_surj lemma sign_aux_mul {n : ℕ} (f g : perm (fin n)) : sign_aux (f * g) = sign_aux f * sign_aux g := begin rw ← sign_aux_inv g, unfold sign_aux, rw ← prod_mul_distrib, refine prod_bij (λ a ha, sign_bij_aux g a) sign_bij_aux_mem _ sign_bij_aux_inj sign_bij_aux_surj, rintros ⟨a, b⟩ hab, rw [sign_bij_aux, mul_apply, mul_apply], rw mem_fin_pairs_lt at hab, by_cases h : g b < g a, { rw dif_pos h, simp only [not_le_of_gt hab, mul_one, perm.inv_apply_self, if_false] }, { rw [dif_neg h, inv_apply_self, inv_apply_self, if_pos (le_of_lt hab)], by_cases h₁ : f (g b) ≤ f (g a), { have : f (g b) ≠ f (g a), { rw [ne.def, injective.eq_iff f.injective, injective.eq_iff g.injective]; exact ne_of_lt hab }, rw [if_pos h₁, if_neg (not_le_of_gt (lt_of_le_of_ne h₁ this))], refl }, { rw [if_neg h₁, if_pos (le_of_lt (lt_of_not_ge h₁))], refl } } end private lemma sign_aux_swap_zero_one {n : ℕ} (hn : 2 ≤ n) : sign_aux (swap (⟨0, lt_of_lt_of_le dec_trivial hn⟩ : fin n) ⟨1, lt_of_lt_of_le dec_trivial hn⟩) = -1 := let zero : fin n := ⟨0, lt_of_lt_of_le dec_trivial hn⟩ in let one : fin n := ⟨1, lt_of_lt_of_le dec_trivial hn⟩ in have hzo : zero < one := dec_trivial, show _ = ∏ x : Σ a : fin n, fin n in {(⟨one, zero⟩ : Σ a : fin n, fin n)}, if (equiv.swap zero one) x.1 ≤ swap zero one x.2 then (-1 : units ℤ) else 1, begin refine eq.symm (prod_subset (λ ⟨x₁, x₂⟩, by simp [mem_fin_pairs_lt, hzo] {contextual := tt}) (λ a ha₁ ha₂, _)), rcases a with ⟨⟨a₁, ha₁⟩, ⟨a₂, ha₂⟩⟩, replace ha₁ : a₂ < a₁ := mem_fin_pairs_lt.1 ha₁, simp only [swap_apply_def], have : ¬ 1 ≤ a₂ → a₂ = 0, from λ h, nat.le_zero_iff.1 (nat.le_of_lt_succ (lt_of_not_ge h)), have : a₁ ≤ 1 → a₁ = 0 ∨ a₁ = 1, from nat.cases_on a₁ (λ _, or.inl rfl) (λ a₁, nat.cases_on a₁ (λ _, or.inr rfl) (λ _ h, absurd h dec_trivial)), split_ifs; simp only [*, not_le.symm, iff.intro fin.veq_of_eq fin.eq_of_veq, nat.le_zero_iff, eq_self_iff_true, not_true, fin.le_def, one, nat.zero_le, and_self, heq_iff_eq, mem_singleton, forall_prop_of_true, or_self, le_refl] at *, end lemma sign_aux_swap : ∀ {n : ℕ} {x y : fin n} (hxy : x ≠ y), sign_aux (swap x y) = -1 | 0 := dec_trivial | 1 := dec_trivial | (n+2) := λ x y hxy, have h2n : 2 ≤ n + 2 := dec_trivial, by rw [← is_conj_iff_eq, ← sign_aux_swap_zero_one h2n]; exact (monoid_hom.mk' sign_aux sign_aux_mul).map_is_conj (is_conj_swap hxy dec_trivial) /-- When the list `l : list α` contains all nonfixed points of the permutation `f : perm α`, `sign_aux2 l f` recursively calculates the sign of `f`. -/ def sign_aux2 : list α → perm α → units ℤ | [] f := 1 | (x::l) f := if x = f x then sign_aux2 l f else -sign_aux2 l (swap x (f x) * f) lemma sign_aux_eq_sign_aux2 {n : ℕ} : ∀ (l : list α) (f : perm α) (e : α ≃ fin n) (h : ∀ x, f x ≠ x → x ∈ l), sign_aux ((e.symm.trans f).trans e) = sign_aux2 l f | [] f e h := have f = 1, from equiv.ext $ λ y, not_not.1 (mt (h y) (list.not_mem_nil _)), by rw [this, one_def, equiv.trans_refl, equiv.symm_trans, ← one_def, sign_aux_one, sign_aux2] | (x::l) f e h := begin rw sign_aux2, by_cases hfx : x = f x, { rw if_pos hfx, exact sign_aux_eq_sign_aux2 l f _ (λ y (hy : f y ≠ y), list.mem_of_ne_of_mem (λ h : y = x, by simpa [h, hfx.symm] using hy) (h y hy) ) }, { have hy : ∀ y : α, (swap x (f x) * f) y ≠ y → y ∈ l, from λ y hy, have f y ≠ y ∧ y ≠ x, from ne_and_ne_of_swap_mul_apply_ne_self hy, list.mem_of_ne_of_mem this.2 (h _ this.1), have : (e.symm.trans (swap x (f x) * f)).trans e = (swap (e x) (e (f x))) * (e.symm.trans f).trans e, by ext; simp [← equiv.symm_trans_swap_trans, mul_def], have hefx : e x ≠ e (f x), from mt (injective.eq_iff e.injective).1 hfx, rw [if_neg hfx, ← sign_aux_eq_sign_aux2 _ _ e hy, this, sign_aux_mul, sign_aux_swap hefx], simp only [units.neg_neg, one_mul, units.neg_mul]} end /-- When the multiset `s : multiset α` contains all nonfixed points of the permutation `f : perm α`, `sign_aux2 f _` recursively calculates the sign of `f`. -/ def sign_aux3 [fintype α] (f : perm α) {s : multiset α} : (∀ x, x ∈ s) → units ℤ := quotient.hrec_on s (λ l h, sign_aux2 l f) (trunc.induction_on (equiv_fin α) (λ e l₁ l₂ h, function.hfunext (show (∀ x, x ∈ l₁) = ∀ x, x ∈ l₂, by simp only [h.mem_iff]) (λ h₁ h₂ _, by rw [← sign_aux_eq_sign_aux2 _ _ e (λ _ _, h₁ _), ← sign_aux_eq_sign_aux2 _ _ e (λ _ _, h₂ _)]))) lemma sign_aux3_mul_and_swap [fintype α] (f g : perm α) (s : multiset α) (hs : ∀ x, x ∈ s) : sign_aux3 (f * g) hs = sign_aux3 f hs * sign_aux3 g hs ∧ ∀ x y, x ≠ y → sign_aux3 (swap x y) hs = -1 := let ⟨l, hl⟩ := quotient.exists_rep s in let ⟨e, _⟩ := trunc.exists_rep (equiv_fin α) in begin clear _let_match _let_match, subst hl, show sign_aux2 l (f * g) = sign_aux2 l f * sign_aux2 l g ∧ ∀ x y, x ≠ y → sign_aux2 l (swap x y) = -1, have hfg : (e.symm.trans (f * g)).trans e = (e.symm.trans f).trans e * (e.symm.trans g).trans e, from equiv.ext (λ h, by simp [mul_apply]), split, { rw [← sign_aux_eq_sign_aux2 _ _ e (λ _ _, hs _), ← sign_aux_eq_sign_aux2 _ _ e (λ _ _, hs _), ← sign_aux_eq_sign_aux2 _ _ e (λ _ _, hs _), hfg, sign_aux_mul] }, { assume x y hxy, have hexy : e x ≠ e y, from mt (injective.eq_iff e.injective).1 hxy, rw [← sign_aux_eq_sign_aux2 _ _ e (λ _ _, hs _), equiv.symm_trans_swap_trans, sign_aux_swap hexy] } end /-- `sign` of a permutation returns the signature or parity of a permutation, `1` for even permutations, `-1` for odd permutations. It is the unique surjective group homomorphism from `perm α` to the group with two elements.-/ def sign [fintype α] : perm α →* units ℤ := monoid_hom.mk' (λ f, sign_aux3 f mem_univ) (λ f g, (sign_aux3_mul_and_swap f g _ mem_univ).1) section sign variable [fintype α] @[simp] lemma sign_mul (f g : perm α) : sign (f * g) = sign f * sign g := monoid_hom.map_mul sign f g @[simp] lemma sign_one : (sign (1 : perm α)) = 1 := monoid_hom.map_one sign @[simp] lemma sign_refl : sign (equiv.refl α) = 1 := monoid_hom.map_one sign @[simp] lemma sign_inv (f : perm α) : sign f⁻¹ = sign f := by rw [monoid_hom.map_inv sign f, int.units_inv_eq_self] lemma sign_swap {x y : α} (h : x ≠ y) : sign (swap x y) = -1 := (sign_aux3_mul_and_swap 1 1 _ mem_univ).2 x y h @[simp] lemma sign_swap' {x y : α} : (swap x y).sign = if x = y then 1 else -1 := if H : x = y then by simp [H, swap_self] else by simp [sign_swap H, H] lemma sign_eq_of_is_swap {f : perm α} (h : is_swap f) : sign f = -1 := let ⟨x, y, hxy⟩ := h in hxy.2.symm ▸ sign_swap hxy.1 lemma sign_aux3_symm_trans_trans [decidable_eq β] [fintype β] (f : perm α) (e : α ≃ β) {s : multiset α} {t : multiset β} (hs : ∀ x, x ∈ s) (ht : ∀ x, x ∈ t) : sign_aux3 ((e.symm.trans f).trans e) ht = sign_aux3 f hs := quotient.induction_on₂ t s (λ l₁ l₂ h₁ h₂, show sign_aux2 _ _ = sign_aux2 _ _, from let n := trunc.out (equiv_fin β) in by rw [← sign_aux_eq_sign_aux2 _ _ n (λ _ _, h₁ _), ← sign_aux_eq_sign_aux2 _ _ (e.trans n) (λ _ _, h₂ _)]; exact congr_arg sign_aux (equiv.ext (λ x, by simp only [equiv.coe_trans, apply_eq_iff_eq, symm_trans_apply]))) ht hs lemma sign_symm_trans_trans [decidable_eq β] [fintype β] (f : perm α) (e : α ≃ β) : sign ((e.symm.trans f).trans e) = sign f := sign_aux3_symm_trans_trans f e mem_univ mem_univ lemma sign_prod_list_swap {l : list (perm α)} (hl : ∀ g ∈ l, is_swap g) : sign l.prod = (-1) ^ l.length := have h₁ : l.map sign = list.repeat (-1) l.length := list.eq_repeat.2 ⟨by simp, λ u hu, let ⟨g, hg⟩ := list.mem_map.1 hu in hg.2 ▸ sign_eq_of_is_swap (hl _ hg.1)⟩, by rw [← list.prod_repeat, ← h₁, list.prod_hom _ (@sign α _ _)] lemma sign_surjective (hα : 1 < fintype.card α) : function.surjective (sign : perm α → units ℤ) := λ a, (int.units_eq_one_or a).elim (λ h, ⟨1, by simp [h]⟩) (λ h, let ⟨x⟩ := fintype.card_pos_iff.1 (lt_trans zero_lt_one hα) in let ⟨y, hxy⟩ := fintype.exists_ne_of_one_lt_card hα x in ⟨swap y x, by rw [sign_swap hxy, h]⟩ ) lemma eq_sign_of_surjective_hom {s : perm α →* units ℤ} (hs : surjective s) : s = sign := have ∀ {f}, is_swap f → s f = -1 := λ f ⟨x, y, hxy, hxy'⟩, hxy'.symm ▸ by_contradiction (λ h, have ∀ f, is_swap f → s f = 1 := λ f ⟨a, b, hab, hab'⟩, by rw [← is_conj_iff_eq, ← or.resolve_right (int.units_eq_one_or _) h, hab']; exact (monoid_hom.of s).map_is_conj (is_conj_swap hab hxy), let ⟨g, hg⟩ := hs (-1) in let ⟨l, hl⟩ := trunc.out (trunc_swap_factors g) in have ∀ a ∈ l.map s, a = (1 : units ℤ) := λ a ha, let ⟨g, hg⟩ := list.mem_map.1 ha in hg.2 ▸ this _ (hl.2 _ hg.1), have s l.prod = 1, by rw [← l.prod_hom s, list.eq_repeat'.2 this, list.prod_repeat, one_pow], by rw [hl.1, hg] at this; exact absurd this dec_trivial), monoid_hom.ext $ λ f, let ⟨l, hl₁, hl₂⟩ := trunc.out (trunc_swap_factors f) in have hsl : ∀ a ∈ l.map s, a = (-1 : units ℤ) := λ a ha, let ⟨g, hg⟩ := list.mem_map.1 ha in hg.2 ▸ this (hl₂ _ hg.1), by rw [← hl₁, ← l.prod_hom s, list.eq_repeat'.2 hsl, list.length_map, list.prod_repeat, sign_prod_list_swap hl₂] lemma sign_subtype_perm (f : perm α) {p : α → Prop} [decidable_pred p] (h₁ : ∀ x, p x ↔ p (f x)) (h₂ : ∀ x, f x ≠ x → p x) : sign (subtype_perm f h₁) = sign f := let l := trunc.out (trunc_swap_factors (subtype_perm f h₁)) in have hl' : ∀ g' ∈ l.1.map of_subtype, is_swap g' := λ g' hg', let ⟨g, hg⟩ := list.mem_map.1 hg' in hg.2 ▸ is_swap_of_subtype (l.2.2 _ hg.1), have hl'₂ : (l.1.map of_subtype).prod = f, by rw [l.1.prod_hom of_subtype, l.2.1, of_subtype_subtype_perm _ h₂], by conv {congr, rw ← l.2.1, skip, rw ← hl'₂}; rw [sign_prod_list_swap l.2.2, sign_prod_list_swap hl', list.length_map] @[simp] lemma sign_of_subtype {p : α → Prop} [decidable_pred p] (f : perm (subtype p)) : sign (of_subtype f) = sign f := have ∀ x, of_subtype f x ≠ x → p x, from λ x, not_imp_comm.1 (of_subtype_apply_of_not_mem f), by conv {to_rhs, rw [← subtype_perm_of_subtype f, sign_subtype_perm _ _ this]} lemma sign_eq_sign_of_equiv [decidable_eq β] [fintype β] (f : perm α) (g : perm β) (e : α ≃ β) (h : ∀ x, e (f x) = g (e x)) : sign f = sign g := have hg : g = (e.symm.trans f).trans e, from equiv.ext $ by simp [h], by rw [hg, sign_symm_trans_trans] lemma sign_bij [decidable_eq β] [fintype β] {f : perm α} {g : perm β} (i : Π x : α, f x ≠ x → β) (h : ∀ x hx hx', i (f x) hx' = g (i x hx)) (hi : ∀ x₁ x₂ hx₁ hx₂, i x₁ hx₁ = i x₂ hx₂ → x₁ = x₂) (hg : ∀ y, g y ≠ y → ∃ x hx, i x hx = y) : sign f = sign g := calc sign f = sign (@subtype_perm _ f (λ x, f x ≠ x) (by simp)) : eq.symm (sign_subtype_perm _ _ (λ _, id)) ... = sign (@subtype_perm _ g (λ x, g x ≠ x) (by simp)) : sign_eq_sign_of_equiv _ _ (equiv.of_bijective (λ x : {x // f x ≠ x}, (⟨i x.1 x.2, have f (f x) ≠ f x, from mt (λ h, f.injective h) x.2, by rw [← h _ x.2 this]; exact mt (hi _ _ this x.2) x.2⟩ : {y // g y ≠ y})) ⟨λ ⟨x, hx⟩ ⟨y, hy⟩ h, subtype.eq (hi _ _ _ _ (subtype.mk.inj h)), λ ⟨y, hy⟩, let ⟨x, hfx, hx⟩ := hg y hy in ⟨⟨x, hfx⟩, subtype.eq hx⟩⟩) (λ ⟨x, _⟩, subtype.eq (h x _ _)) ... = sign g : sign_subtype_perm _ _ (λ _, id) /-- A permutation is a cycle when any two nonfixed points of the permutation are related by repeated application of the permutation. -/ def is_cycle (f : perm β) := ∃ x, f x ≠ x ∧ ∀ y, f y ≠ y → ∃ i : ℤ, (f ^ i) x = y lemma is_cycle_swap {α : Type*} [decidable_eq α] {x y : α} (hxy : x ≠ y) : is_cycle (swap x y) := ⟨y, by rwa swap_apply_right, λ a (ha : ite (a = x) y (ite (a = y) x a) ≠ a), if hya : y = a then ⟨0, hya⟩ else ⟨1, by rw [gpow_one, swap_apply_def]; split_ifs at *; cc⟩⟩ lemma is_cycle_inv {f : perm β} (hf : is_cycle f) : is_cycle (f⁻¹) := let ⟨x, hx⟩ := hf in ⟨x, by simp only [inv_eq_iff_eq, *, forall_prop_of_true, ne.def] at *; cc, λ y hy, let ⟨i, hi⟩ := hx.2 y (by simp only [inv_eq_iff_eq, *, forall_prop_of_true, ne.def] at *; cc) in ⟨-i, by rwa [gpow_neg, inv_gpow, inv_inv]⟩⟩ lemma exists_gpow_eq_of_is_cycle {f : perm β} (hf : is_cycle f) {x y : β} (hx : f x ≠ x) (hy : f y ≠ y) : ∃ i : ℤ, (f ^ i) x = y := let ⟨g, hg⟩ := hf in let ⟨a, ha⟩ := hg.2 x hx in let ⟨b, hb⟩ := hg.2 y hy in ⟨b - a, by rw [← ha, ← mul_apply, ← gpow_add, sub_add_cancel, hb]⟩ lemma is_cycle_swap_mul_aux₁ {α : Type*} [decidable_eq α] : ∀ (n : ℕ) {b x : α} {f : perm α} (hb : (swap x (f x) * f) b ≠ b) (h : (f ^ n) (f x) = b), ∃ i : ℤ, ((swap x (f x) * f) ^ i) (f x) = b | 0 := λ b x f hb h, ⟨0, h⟩ | (n+1 : ℕ) := λ b x f hb h, if hfbx : f x = b then ⟨0, hfbx⟩ else have f b ≠ b ∧ b ≠ x, from ne_and_ne_of_swap_mul_apply_ne_self hb, have hb' : (swap x (f x) * f) (f⁻¹ b) ≠ f⁻¹ b, by rw [mul_apply, apply_inv_self, swap_apply_of_ne_of_ne this.2 (ne.symm hfbx), ne.def, ← injective.eq_iff f.injective, apply_inv_self]; exact this.1, let ⟨i, hi⟩ := is_cycle_swap_mul_aux₁ n hb' (f.injective $ by rw [apply_inv_self]; rwa [pow_succ, mul_apply] at h) in ⟨i + 1, by rw [add_comm, gpow_add, mul_apply, hi, gpow_one, mul_apply, apply_inv_self, swap_apply_of_ne_of_ne (ne_and_ne_of_swap_mul_apply_ne_self hb).2 (ne.symm hfbx)]⟩ lemma is_cycle_swap_mul_aux₂ {α : Type*} [decidable_eq α] : ∀ (n : ℤ) {b x : α} {f : perm α} (hb : (swap x (f x) * f) b ≠ b) (h : (f ^ n) (f x) = b), ∃ i : ℤ, ((swap x (f x) * f) ^ i) (f x) = b | (n : ℕ) := λ b x f, is_cycle_swap_mul_aux₁ n | -[1+ n] := λ b x f hb h, if hfbx : f⁻¹ x = b then ⟨-1, by rwa [gpow_neg, gpow_one, mul_inv_rev, mul_apply, swap_inv, swap_apply_right]⟩ else if hfbx' : f x = b then ⟨0, hfbx'⟩ else have f b ≠ b ∧ b ≠ x := ne_and_ne_of_swap_mul_apply_ne_self hb, have hb : (swap x (f⁻¹ x) * f⁻¹) (f⁻¹ b) ≠ f⁻¹ b, by rw [mul_apply, swap_apply_def]; split_ifs; simp only [inv_eq_iff_eq, perm.mul_apply, gpow_neg_succ_of_nat, ne.def, perm.apply_inv_self] at *; cc, let ⟨i, hi⟩ := is_cycle_swap_mul_aux₁ n hb (show (f⁻¹ ^ n) (f⁻¹ x) = f⁻¹ b, by rw [← gpow_coe_nat, ← h, ← mul_apply, ← mul_apply, ← mul_apply, gpow_neg_succ_of_nat, ← inv_pow, pow_succ', mul_assoc, mul_assoc, inv_mul_self, mul_one, gpow_coe_nat, ← pow_succ', ← pow_succ]) in have h : (swap x (f⁻¹ x) * f⁻¹) (f x) = f⁻¹ x, by rw [mul_apply, inv_apply_self, swap_apply_left], ⟨-i, by rw [← add_sub_cancel i 1, neg_sub, sub_eq_add_neg, gpow_add, gpow_one, gpow_neg, ← inv_gpow, mul_inv_rev, swap_inv, mul_swap_eq_swap_mul, inv_apply_self, swap_comm _ x, gpow_add, gpow_one, mul_apply, mul_apply (_ ^ i), h, hi, mul_apply, apply_inv_self, swap_apply_of_ne_of_ne this.2 (ne.symm hfbx')]⟩ lemma eq_swap_of_is_cycle_of_apply_apply_eq_self {α : Type*} [decidable_eq α] {f : perm α} (hf : is_cycle f) {x : α} (hfx : f x ≠ x) (hffx : f (f x) = x) : f = swap x (f x) := equiv.ext $ λ y, let ⟨z, hz⟩ := hf in let ⟨i, hi⟩ := hz.2 x hfx in if hyx : y = x then by simp [hyx] else if hfyx : y = f x then by simp [hfyx, hffx] else begin rw [swap_apply_of_ne_of_ne hyx hfyx], refine by_contradiction (λ hy, _), cases hz.2 y hy with j hj, rw [← sub_add_cancel j i, gpow_add, mul_apply, hi] at hj, cases gpow_apply_eq_of_apply_apply_eq_self hffx (j - i) with hji hji, { rw [← hj, hji] at hyx, cc }, { rw [← hj, hji] at hfyx, cc } end lemma is_cycle_swap_mul {α : Type*} [decidable_eq α] {f : perm α} (hf : is_cycle f) {x : α} (hx : f x ≠ x) (hffx : f (f x) ≠ x) : is_cycle (swap x (f x) * f) := ⟨f x, by simp only [swap_apply_def, mul_apply]; split_ifs; simp [injective.eq_iff f.injective] at *; cc, λ y hy, let ⟨i, hi⟩ := exists_gpow_eq_of_is_cycle hf hx (ne_and_ne_of_swap_mul_apply_ne_self hy).1 in have hi : (f ^ (i - 1)) (f x) = y, from calc (f ^ (i - 1)) (f x) = (f ^ (i - 1) * f ^ (1 : ℤ)) x : by rw [gpow_one, mul_apply] ... = y : by rwa [← gpow_add, sub_add_cancel], is_cycle_swap_mul_aux₂ (i - 1) hy hi⟩ @[simp] lemma support_swap {x y : α} (hxy : x ≠ y) : (swap x y).support = {x, y} := finset.ext $ λ a, by simp [swap_apply_def]; split_ifs; cc lemma card_support_swap {x y : α} (hxy : x ≠ y) : (swap x y).support.card = 2 := show (swap x y).support.card = finset.card ⟨x ::ₘ y ::ₘ 0, by simp [hxy]⟩, from congr_arg card $ by rw [support_swap hxy]; simp [*, finset.ext_iff]; cc lemma sign_cycle : ∀ {f : perm α} (hf : is_cycle f), sign f = -(-1) ^ f.support.card | f := λ hf, let ⟨x, hx⟩ := hf in calc sign f = sign (swap x (f x) * (swap x (f x) * f)) : by rw [← mul_assoc, mul_def, mul_def, swap_swap, trans_refl] ... = -(-1) ^ f.support.card : if h1 : f (f x) = x then have h : swap x (f x) * f = 1, begin rw eq_swap_of_is_cycle_of_apply_apply_eq_self hf hx.1 h1, simp only [perm.mul_def, perm.one_def, swap_apply_left, swap_swap] end, by rw [sign_mul, sign_swap hx.1.symm, h, sign_one, eq_swap_of_is_cycle_of_apply_apply_eq_self hf hx.1 h1, card_support_swap hx.1.symm]; refl else have h : card (support (swap x (f x) * f)) + 1 = card (support f), by rw [← insert_erase (mem_support.2 hx.1), support_swap_mul_eq h1, card_insert_of_not_mem (not_mem_erase _ _)], have wf : card (support (swap x (f x) * f)) < card (support f), from card_support_swap_mul hx.1, by rw [sign_mul, sign_swap hx.1.symm, sign_cycle (is_cycle_swap_mul hf hx.1 h1), ← h]; simp only [pow_add, mul_one, units.neg_neg, one_mul, units.mul_neg, eq_self_iff_true, pow_one, units.neg_mul_neg] using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf (λ f, f.support.card)⟩]} /-- If we apply `prod_extend_right a (σ a)` for all `a : α` in turn, we get `prod_congr_right σ`. -/ lemma prod_prod_extend_right {α : Type*} [decidable_eq α] (σ : α → perm β) {l : list α} (hl : l.nodup) (mem_l : ∀ a, a ∈ l) : (l.map (λ a, prod_extend_right a (σ a))).prod = prod_congr_right σ := begin ext ⟨a, b⟩ : 1, -- We'll use induction on the list of elements, -- but we have to keep track of whether we already passed `a` in the list. suffices : (a ∈ l ∧ (l.map (λ a, prod_extend_right a (σ a))).prod (a, b) = (a, σ a b)) ∨ (a ∉ l ∧ (l.map (λ a, prod_extend_right a (σ a))).prod (a, b) = (a, b)), { obtain ⟨_, prod_eq⟩ := or.resolve_right this (not_and.mpr (λ h _, h (mem_l a))), rw [prod_eq, prod_congr_right_apply] }, clear mem_l, induction l with a' l ih, { refine or.inr ⟨list.not_mem_nil _, _⟩, rw [list.map_nil, list.prod_nil, one_apply] }, rw [list.map_cons, list.prod_cons, mul_apply], rcases ih (list.nodup_cons.mp hl).2 with ⟨mem_l, prod_eq⟩ | ⟨not_mem_l, prod_eq⟩; rw prod_eq, { refine or.inl ⟨list.mem_cons_of_mem _ mem_l, _⟩, rw prod_extend_right_apply_ne _ (λ (h : a = a'), (list.nodup_cons.mp hl).1 (h ▸ mem_l)) }, by_cases ha' : a = a', { rw ← ha' at *, refine or.inl ⟨l.mem_cons_self a, _⟩, rw prod_extend_right_apply_eq }, { refine or.inr ⟨λ h, not_or ha' not_mem_l ((list.mem_cons_iff _ _ _).mp h), _⟩, rw prod_extend_right_apply_ne _ ha' }, end section congr variables [decidable_eq β] [fintype β] @[simp] lemma sign_prod_extend_right (a : α) (σ : perm β) : (prod_extend_right a σ).sign = σ.sign := sign_bij (λ (ab : α × β) _, ab.snd) (λ ⟨a', b⟩ hab hab', by simp [eq_of_prod_extend_right_ne hab]) (λ ⟨a₁, b₁⟩ ⟨a₂, b₂⟩ hab₁ hab₂ h, by simpa [eq_of_prod_extend_right_ne hab₁, eq_of_prod_extend_right_ne hab₂] using h) (λ y hy, ⟨(a, y), by simpa, by simp⟩) lemma sign_prod_congr_right (σ : α → perm β) : sign (prod_congr_right σ) = ∏ k, (σ k).sign := begin obtain ⟨l, hl, mem_l⟩ := fintype.exists_univ_list α, have l_to_finset : l.to_finset = finset.univ, { apply eq_top_iff.mpr, intros b _, exact list.mem_to_finset.mpr (mem_l b) }, rw [← prod_prod_extend_right σ hl mem_l, sign.map_list_prod, list.map_map, ← l_to_finset, list.prod_to_finset _ hl], simp_rw ← λ a, sign_prod_extend_right a (σ a) end lemma sign_prod_congr_left (σ : α → perm β) : sign (prod_congr_left σ) = ∏ k, (σ k).sign := begin refine (sign_eq_sign_of_equiv _ _ (prod_comm β α) _).trans (sign_prod_congr_right σ), rintro ⟨b, α⟩, refl end @[simp] lemma sign_perm_congr (e : α ≃ β) (p : perm α) : (e.perm_congr p).sign = p.sign := equiv.perm.sign_eq_sign_of_equiv _ _ e.symm (by simp) @[simp] lemma sign_sum_congr (σa : perm α) (σb : perm β) : (sum_congr σa σb).sign = σa.sign * σb.sign := begin suffices : (sum_congr σa (1 : perm β)).sign = σa.sign ∧ (sum_congr (1 : perm α) σb).sign = σb.sign, { rw [←this.1, ←this.2, ←sign_mul, sum_congr_mul, one_mul, mul_one], }, split, { apply σa.swap_induction_on _ (λ σa' a₁ a₂ ha ih, _), { simp }, { rw [←one_mul (1 : perm β), ←sum_congr_mul, sign_mul, sign_mul, ih, sum_congr_swap_one, sign_swap ha, sign_swap (sum.injective_inl.ne_iff.mpr ha)], }, }, { apply σb.swap_induction_on _ (λ σb' b₁ b₂ hb ih, _), { simp }, { rw [←one_mul (1 : perm α), ←sum_congr_mul, sign_mul, sign_mul, ih, sum_congr_one_swap, sign_swap hb, sign_swap (sum.injective_inr.ne_iff.mpr hb)], }, } end end congr end sign end equiv.perm
05fe4db43c469bc082b8b558d161138252163564
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/tactic/lean_core_docs.lean
f2a39e78830bb67283b8224556199337612f530a
[ "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
22,853
lean
/- Copyright (c) 2020 Kevin Buzzard. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Buzzard, Bryan Gin-ge Chen, Robert Y. Lewis, Scott Morrison -/ import tactic.doc_commands /-! # Core tactic documentation This file adds the majority of the interactive tactics from core Lean (i.e. pre-mathlib) to the API documentation. ## TODO * Make a PR to core changing core docstrings to the docstrings below, and also changing the docstrings of `cc`, `simp` and `conv` to the ones already in the API docs. * SMT tactics are currently not documented. * `rsimp` and `constructor_matching` are currently not documented. * `dsimp` deserves better documentation. -/ add_tactic_doc { name := "abstract", category := doc_category.tactic, decl_names := [`tactic.interactive.abstract], tags := ["core", "proof extraction"] } /-- Proves a goal of the form `s = t` when `s` and `t` are expressions built up out of a binary operation, and equality can be proved using associativity and commutativity of that operation. -/ add_tactic_doc { name := "ac_refl", category := doc_category.tactic, decl_names := [`tactic.interactive.ac_refl, `tactic.interactive.ac_reflexivity], tags := ["core", "lemma application", "finishing"] } add_tactic_doc { name := "all_goals", category := doc_category.tactic, decl_names := [`tactic.interactive.all_goals], tags := ["core", "goal management"] } add_tactic_doc { name := "any_goals", category := doc_category.tactic, decl_names := [`tactic.interactive.any_goals], tags := ["core", "goal management"] } add_tactic_doc { name := "apply", category := doc_category.tactic, decl_names := [`tactic.interactive.apply], tags := ["core", "basic", "lemma application"] } add_tactic_doc { name := "apply_auto_param", category := doc_category.tactic, decl_names := [`tactic.interactive.apply_auto_param], tags := ["core", "lemma application"] } add_tactic_doc { name := "apply_instance", category := doc_category.tactic, decl_names := [`tactic.interactive.apply_instance], tags := ["core", "type class"] } add_tactic_doc { name := "apply_opt_param", category := doc_category.tactic, decl_names := [`tactic.interactive.apply_opt_param], tags := ["core", "lemma application"] } add_tactic_doc { name := "apply_with", category := doc_category.tactic, decl_names := [`tactic.interactive.apply_with], tags := ["core", "lemma application"] } add_tactic_doc { name := "assume", category := doc_category.tactic, decl_names := [`tactic.interactive.assume], tags := ["core", "logic"] } add_tactic_doc { name := "assumption", category := doc_category.tactic, decl_names := [`tactic.interactive.assumption], tags := ["core", "basic", "finishing"] } add_tactic_doc { name := "assumption'", category := doc_category.tactic, decl_names := [`tactic.interactive.assumption'], tags := ["core", "goal management"] } add_tactic_doc { name := "async", category := doc_category.tactic, decl_names := [`tactic.interactive.async], tags := ["core", "goal management", "combinator", "proof extraction"] } /-- `by_cases p` splits the main goal into two cases, assuming `h : p` in the first branch, and `h : ¬ p` in the second branch. You can specify the name of the new hypothesis using the syntax `by_cases h : p`. This tactic requires that `p` is decidable. To ensure that all propositions are decidable via classical reasoning, use `open_locale classical` (or `local attribute [instance, priority 10] classical.prop_decidable` if you are not using mathlib). -/ add_tactic_doc { name := "by_cases", category := doc_category.tactic, decl_names := [`tactic.interactive.by_cases], tags := ["core", "basic", "logic", "case bashing"] } /-- If the target of the main goal is a proposition `p`, `by_contra h` reduces the goal to proving `false` using the additional hypothesis `h : ¬ p`. If `h` is omitted, a name is generated automatically. This tactic requires that `p` is decidable. To ensure that all propositions are decidable via classical reasoning, use `open_locale classical` (or `local attribute [instance, priority 10] classical.prop_decidable` if you are not using mathlib). -/ add_tactic_doc { name := "by_contra / by_contradiction", category := doc_category.tactic, decl_names := [`tactic.interactive.by_contra, `tactic.interactive.by_contradiction], tags := ["core", "logic"] } add_tactic_doc { name := "case", category := doc_category.tactic, decl_names := [`tactic.interactive.case], tags := ["core", "goal management"] } add_tactic_doc { name := "cases", category := doc_category.tactic, decl_names := [`tactic.interactive.cases], tags := ["core", "basic", "induction"] } /-- `cases_matching p` applies the `cases` tactic to a hypothesis `h : type` if `type` matches the pattern `p`. `cases_matching [p_1, ..., p_n]` applies the `cases` tactic to a hypothesis `h : type` if `type` matches one of the given patterns. `cases_matching* p` is a more efficient and compact version of `focus1 { repeat { cases_matching p } }`. It is more efficient because the pattern is compiled once. `casesm` is shorthand for `cases_matching`. Example: The following tactic destructs all conjunctions and disjunctions in the current context. ``` cases_matching* [_ ∨ _, _ ∧ _] ``` -/ add_tactic_doc { name := "cases_matching / casesm", category := doc_category.tactic, decl_names := [`tactic.interactive.cases_matching, `tactic.interactive.casesm], tags := ["core", "induction", "context management"] } /-- * `cases_type I` applies the `cases` tactic to a hypothesis `h : (I ...)` * `cases_type I_1 ... I_n` applies the `cases` tactic to a hypothesis `h : (I_1 ...)` or ... or `h : (I_n ...)` * `cases_type* I` is shorthand for `focus1 { repeat { cases_type I } }` * `cases_type! I` only applies `cases` if the number of resulting subgoals is <= 1. Example: The following tactic destructs all conjunctions and disjunctions in the current context. ``` cases_type* or and ``` -/ add_tactic_doc { name := "cases_type", category := doc_category.tactic, decl_names := [`tactic.interactive.cases_type], tags := ["core", "induction", "context management"] } add_tactic_doc { name := "change", category := doc_category.tactic, decl_names := [`tactic.interactive.change], tags := ["core", "basic", "renaming"] } add_tactic_doc { name := "clear", category := doc_category.tactic, decl_names := [`tactic.interactive.clear], tags := ["core", "context management"] } /-- Close goals of the form `n ≠ m` when `n` and `m` have type `nat`, `char`, `string`, `int` or `fin sz`, and they are literals. It also closes goals of the form `n < m`, `n > m`, `n ≤ m` and `n ≥ m` for `nat`. If the goal is of the form `n = m`, then it tries to close it using reflexivity. In mathlib, consider using `norm_num` instead for numeric types. -/ add_tactic_doc { name := "comp_val", category := doc_category.tactic, decl_names := [`tactic.interactive.comp_val], tags := ["core", "arithmetic"] } /-- The `congr` tactic attempts to identify both sides of an equality goal `A = B`, leaving as new goals the subterms of `A` and `B` which are not definitionally equal. Example: suppose the goal is `x * f y = g w * f z`. Then `congr` will produce two goals: `x = g w` and `y = z`. Note that `congr` can be over-aggressive at times; the `congr'` tactic in mathlib provides a more refined approach, by taking a parameter that limits the recursion depth. -/ add_tactic_doc { name := "congr", category := doc_category.tactic, decl_names := [`tactic.interactive.congr], tags := ["core", "congruence"] } add_tactic_doc { name := "constructor", category := doc_category.tactic, decl_names := [`tactic.interactive.constructor], tags := ["core", "logic"] } add_tactic_doc { name := "contradiction", category := doc_category.tactic, decl_names := [`tactic.interactive.contradiction], tags := ["core", "basic", "finishing"] } add_tactic_doc { name := "delta", category := doc_category.tactic, decl_names := [`tactic.interactive.delta], tags := ["core", "simplification"] } add_tactic_doc { name := "destruct", category := doc_category.tactic, decl_names := [`tactic.interactive.destruct], tags := ["core", "induction"] } add_tactic_doc { name := "done", category := doc_category.tactic, decl_names := [`tactic.interactive.done], tags := ["core", "goal management"] } add_tactic_doc { name := "dsimp", category := doc_category.tactic, decl_names := [`tactic.interactive.dsimp], tags := ["core", "simplification"] } add_tactic_doc { name := "dunfold", category := doc_category.tactic, decl_names := [`tactic.interactive.dunfold], tags := ["core", "simplification"] } add_tactic_doc { name := "eapply", category := doc_category.tactic, decl_names := [`tactic.interactive.eapply], tags := ["core", "lemma application"] } add_tactic_doc { name := "econstructor", category := doc_category.tactic, decl_names := [`tactic.interactive.econstructor], tags := ["core", "logic"] } /-- A variant of `rw` that uses the unifier more aggressively, unfolding semireducible definitions. -/ add_tactic_doc { name := "erewrite / erw", category := doc_category.tactic, decl_names := [`tactic.interactive.erewrite, `tactic.interactive.erw], tags := ["core", "rewriting"] } add_tactic_doc { name := "exact", category := doc_category.tactic, decl_names := [`tactic.interactive.exact], tags := ["core", "basic", "finishing"] } add_tactic_doc { name := "exacts", category := doc_category.tactic, decl_names := [`tactic.interactive.exacts], tags := ["core", "finishing"] } add_tactic_doc { name := "exfalso", category := doc_category.tactic, decl_names := [`tactic.interactive.exfalso], tags := ["core", "basic", "logic"] } /-- `existsi e` will instantiate an existential quantifier in the target with `e` and leave the instantiated body as the new target. More generally, it applies to any inductive type with one constructor and at least two arguments, applying the constructor with `e` as the first argument and leaving the remaining arguments as goals. `existsi [e₁, ..., eₙ]` iteratively does the same for each expression in the list. Note: in mathlib, the `use` tactic is an equivalent tactic which sometimes is smarter with unification. -/ add_tactic_doc { name := "existsi", category := doc_category.tactic, decl_names := [`tactic.interactive.existsi], tags := ["core", "logic"] } add_tactic_doc { name := "fail_if_success", category := doc_category.tactic, decl_names := [`tactic.interactive.fail_if_success], tags := ["core", "testing", "combinator"] } add_tactic_doc { name := "fapply", category := doc_category.tactic, decl_names := [`tactic.interactive.fapply], tags := ["core", "lemma application"] } add_tactic_doc { name := "focus", category := doc_category.tactic, decl_names := [`tactic.interactive.focus], tags := ["core", "goal management", "combinator"] } add_tactic_doc { name := "from", category := doc_category.tactic, decl_names := [`tactic.interactive.from], tags := ["core", "finishing"] } /-- Apply function extensionality and introduce new hypotheses. The tactic `funext` will keep applying new the `funext` lemma until the goal target is not reducible to ``` |- ((fun x, ...) = (fun x, ...)) ``` The variant `funext h₁ ... hₙ` applies `funext` `n` times, and uses the given identifiers to name the new hypotheses. Note also the mathlib tactic `ext`, which applies as many extensionality lemmas as possible. -/ add_tactic_doc { name := "funext", category := doc_category.tactic, decl_names := [`tactic.interactive.funext], tags := ["core", "logic"] } add_tactic_doc { name := "generalize", category := doc_category.tactic, decl_names := [`tactic.interactive.generalize], tags := ["core", "context management"] } add_tactic_doc { name := "guard_hyp", category := doc_category.tactic, decl_names := [`tactic.interactive.guard_hyp], tags := ["core", "testing", "context management"] } add_tactic_doc { name := "guard_target", category := doc_category.tactic, decl_names := [`tactic.interactive.guard_target], tags := ["core", "testing", "goal management"] } add_tactic_doc { name := "have", category := doc_category.tactic, decl_names := [`tactic.interactive.have], tags := ["core", "basic", "context management"] } add_tactic_doc { name := "induction", category := doc_category.tactic, decl_names := [`tactic.interactive.induction], tags := ["core", "basic", "induction"] } add_tactic_doc { name := "injection", category := doc_category.tactic, decl_names := [`tactic.interactive.injection], tags := ["core", "structures", "induction"] } add_tactic_doc { name := "injections", category := doc_category.tactic, decl_names := [`tactic.interactive.injections], tags := ["core", "structures", "induction"] } /-- If the current goal is a Pi/forall `∀ x : t, u` (resp. `let x := t in u`) then `intro` puts `x : t` (resp. `x := t`) in the local context. The new subgoal target is `u`. If the goal is an arrow `t → u`, then it puts `h : t` in the local context and the new goal target is `u`. If the goal is neither a Pi/forall nor begins with a let binder, the tactic `intro` applies the tactic `whnf` until an introduction can be applied or the goal is not head reducible. In the latter case, the tactic fails. The variant `intro z` uses the identifier `z` to name the new hypothesis. The variant `intros` will keep introducing new hypotheses until the goal target is not a Pi/forall or let binder. The variant `intros h₁ ... hₙ` introduces `n` new hypotheses using the given identifiers to name them. -/ add_tactic_doc { name := "intro / intros", category := doc_category.tactic, decl_names := [`tactic.interactive.intro, `tactic.interactive.intros], tags := ["core", "basic", "logic"] } add_tactic_doc { name := "introv", category := doc_category.tactic, decl_names := [`tactic.interactive.introv], tags := ["core", "logic"] } add_tactic_doc { name := "iterate", category := doc_category.tactic, decl_names := [`tactic.interactive.iterate], tags := ["core", "combinator"] } /-- `left` applies the first constructor when the type of the target is an inductive data type with two constructors. Similarly, `right` applies the second constructor. -/ add_tactic_doc { name := "left / right", category := doc_category.tactic, decl_names := [`tactic.interactive.left, `tactic.interactive.right], tags := ["core", "basic", "logic"] } /-- `let h : t := p` adds the hypothesis `h : t := p` to the current goal if `p` a term of type `t`. If `t` is omitted, it will be inferred. `let h : t` adds the hypothesis `h : t := ?M` to the current goal and opens a new subgoal `?M : t`. The new subgoal becomes the main goal. If `t` is omitted, it will be replaced by a fresh metavariable. If `h` is omitted, the name `this` is used. Note the related mathlib tactic `set a := t with h`, which adds the hypothesis `h : a = t` to the local context and replaces `t` with `a` everywhere it can. -/ add_tactic_doc { name := "let", category := doc_category.tactic, decl_names := [`tactic.interactive.let], tags := ["core", "basic", "logic", "context management"] } add_tactic_doc { name := "mapply", category := doc_category.tactic, decl_names := [`tactic.interactive.mapply], tags := ["core", "lemma application"] } add_tactic_doc { name := "match_target", category := doc_category.tactic, decl_names := [`tactic.interactive.match_target], tags := ["core", "testing", "goal management"] } add_tactic_doc { name := "refine", category := doc_category.tactic, decl_names := [`tactic.interactive.refine], tags := ["core", "basic", "lemma application"] } /-- This tactic applies to a goal whose target has the form `t ~ u` where `~` is a reflexive relation, that is, a relation which has a reflexivity lemma tagged with the attribute `[refl]`. The tactic checks whether `t` and `u` are definitionally equal and then solves the goal. -/ add_tactic_doc { name := "refl / reflexivity", category := doc_category.tactic, decl_names := [`tactic.interactive.refl, `tactic.interactive.reflexivity], tags := ["core", "basic", "finishing"] } add_tactic_doc { name := "rename", category := doc_category.tactic, decl_names := [`tactic.interactive.rename], tags := ["core", "renaming"] } add_tactic_doc { name := "repeat", category := doc_category.tactic, decl_names := [`tactic.interactive.repeat], tags := ["core", "combinator"] } add_tactic_doc { name := "revert", category := doc_category.tactic, decl_names := [`tactic.interactive.revert], tags := ["core", "context management", "goal management"] } /-- `rw e` applies an equation or iff `e` as a rewrite rule to the main goal. If `e` is preceded by left arrow (`←` or `<-`), the rewrite is applied in the reverse direction. If `e` is a defined constant, then the equational lemmas associated with `e` are used. This provides a convenient way to unfold `e`. `rw [e₁, ..., eₙ]` applies the given rules sequentially. `rw e at l` rewrites `e` at location(s) `l`, where `l` is either `*` or a list of hypotheses in the local context. In the latter case, a turnstile `⊢` or `|-` can also be used, to signify the target of the goal. `rewrite` is synonymous with `rw`. -/ add_tactic_doc { name := "rw / rewrite", category := doc_category.tactic, decl_names := [`tactic.interactive.rw, `tactic.interactive.rewrite], tags := ["core", "basic", "rewriting"] } add_tactic_doc { name := "rwa", category := doc_category.tactic, decl_names := [`tactic.interactive.rwa], tags := ["core", "rewriting"] } add_tactic_doc { name := "show", category := doc_category.tactic, decl_names := [`tactic.interactive.show], tags := ["core", "goal management", "renaming"] } add_tactic_doc { name := "simp_intros", category := doc_category.tactic, decl_names := [`tactic.interactive.simp_intros], tags := ["core", "simplification"] } add_tactic_doc { name := "skip", category := doc_category.tactic, decl_names := [`tactic.interactive.skip], tags := ["core", "combinator"] } add_tactic_doc { name := "solve1", category := doc_category.tactic, decl_names := [`tactic.interactive.solve1], tags := ["core", "combinator", "goal management"] } add_tactic_doc { name := "sorry / admit", category := doc_category.tactic, decl_names := [`tactic.interactive.sorry, `tactic.interactive.admit], inherit_description_from := `tactic.interactive.sorry, tags := ["core", "testing", "debugging"] } add_tactic_doc { name := "specialize", category := doc_category.tactic, decl_names := [`tactic.interactive.specialize], tags := ["core", "context management", "lemma application"] } add_tactic_doc { name := "split", category := doc_category.tactic, decl_names := [`tactic.interactive.split], tags := ["core", "basic", "logic"] } add_tactic_doc { name := "subst", category := doc_category.tactic, decl_names := [`tactic.interactive.subst], tags := ["core", "rewriting"] } add_tactic_doc { name := "subst_vars", category := doc_category.tactic, decl_names := [`tactic.interactive.subst_vars], tags := ["core", "rewriting"] } add_tactic_doc { name := "success_if_fail", category := doc_category.tactic, decl_names := [`tactic.interactive.success_if_fail], tags := ["core", "testing", "combinator"] } add_tactic_doc { name := "suffices", category := doc_category.tactic, decl_names := [`tactic.interactive.suffices], tags := ["core", "basic", "goal management"] } add_tactic_doc { name := "symmetry", category := doc_category.tactic, decl_names := [`tactic.interactive.symmetry], tags := ["core", "basic", "lemma application"] } add_tactic_doc { name := "trace", category := doc_category.tactic, decl_names := [`tactic.interactive.trace], tags := ["core", "debugging", "testing"] } add_tactic_doc { name := "trace_simp_set", category := doc_category.tactic, decl_names := [`tactic.interactive.trace_simp_set], tags := ["core", "debugging", "testing"] } add_tactic_doc { name := "trace_state", category := doc_category.tactic, decl_names := [`tactic.interactive.trace_state], tags := ["core", "debugging", "testing"] } add_tactic_doc { name := "transitivity", category := doc_category.tactic, decl_names := [`tactic.interactive.transitivity], tags := ["core", "lemma application"] } add_tactic_doc { name := "trivial", category := doc_category.tactic, decl_names := [`tactic.interactive.trivial], tags := ["core", "finishing"] } add_tactic_doc { name := "try", category := doc_category.tactic, decl_names := [`tactic.interactive.try], tags := ["core", "combinator"] } add_tactic_doc { name := "type_check", category := doc_category.tactic, decl_names := [`tactic.interactive.type_check], tags := ["core", "debugging", "testing"] } add_tactic_doc { name := "unfold", category := doc_category.tactic, decl_names := [`tactic.interactive.unfold], tags := ["core", "basic", "rewriting"] } add_tactic_doc { name := "unfold1", category := doc_category.tactic, decl_names := [`tactic.interactive.unfold1], tags := ["core", "rewriting"] } add_tactic_doc { name := "unfold_projs", category := doc_category.tactic, decl_names := [`tactic.interactive.unfold_projs], tags := ["core", "rewriting"] } add_tactic_doc { name := "with_cases", category := doc_category.tactic, decl_names := [`tactic.interactive.with_cases], tags := ["core", "combinator"] }