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
c9dd38fd9309698d5dcaeb22eed6493f31b375ff
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/group_theory/subsemigroup/center.lean
46cd73116a996a4f0e87523db2cda04b90d814ea
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
5,163
lean
/- Copyright (c) 2021 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser, Jireh Loreaux -/ import algebra.ring.defs import group_theory.subsemigroup.operations /-! # Centers of magmas and semigroups > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. ## Main definitions * `set.center`: the center of a magma * `subsemigroup.center`: the center of a semigroup * `set.add_center`: the center of an additive magma * `add_subsemigroup.center`: the center of an additive semigroup We provide `submonoid.center`, `add_submonoid.center`, `subgroup.center`, `add_subgroup.center`, `subsemiring.center`, and `subring.center` in other files. -/ variables {M : Type*} namespace set variables (M) /-- The center of a magma. -/ @[to_additive add_center /-" The center of an additive magma. "-/] def center [has_mul M] : set M := {z | ∀ m, m * z = z * m} @[to_additive mem_add_center] lemma mem_center_iff [has_mul M] {z : M} : z ∈ center M ↔ ∀ g, g * z = z * g := iff.rfl instance decidable_mem_center [has_mul M] [∀ a : M, decidable $ ∀ b : M, b * a = a * b] : decidable_pred (∈ center M) := λ _, decidable_of_iff' _ (mem_center_iff M) @[simp, to_additive zero_mem_add_center] lemma one_mem_center [mul_one_class M] : (1 : M) ∈ set.center M := by simp [mem_center_iff] @[simp] lemma zero_mem_center [mul_zero_class M] : (0 : M) ∈ set.center M := by simp [mem_center_iff] variables {M} @[simp, to_additive add_mem_add_center] lemma mul_mem_center [semigroup M] {a b : M} (ha : a ∈ set.center M) (hb : b ∈ set.center M) : a * b ∈ set.center M := λ g, by rw [mul_assoc, ←hb g, ← mul_assoc, ha g, mul_assoc] @[simp, to_additive neg_mem_add_center] lemma inv_mem_center [group M] {a : M} (ha : a ∈ set.center M) : a⁻¹ ∈ set.center M := λ g, by rw [← inv_inj, mul_inv_rev, inv_inv, ← ha, mul_inv_rev, inv_inv] @[simp] lemma add_mem_center [distrib M] {a b : M} (ha : a ∈ set.center M) (hb : b ∈ set.center M) : a + b ∈ set.center M := λ c, by rw [add_mul, mul_add, ha c, hb c] @[simp] lemma neg_mem_center [ring M] {a : M} (ha : a ∈ set.center M) : -a ∈ set.center M := λ c, by rw [←neg_mul_comm, ha (-c), neg_mul_comm] @[to_additive subset_add_center_add_units] lemma subset_center_units [monoid M] : (coe : Mˣ → M) ⁻¹' center M ⊆ set.center Mˣ := λ a ha b, units.ext $ ha _ lemma center_units_subset [group_with_zero M] : set.center Mˣ ⊆ (coe : Mˣ → M) ⁻¹' center M := λ a ha b, begin obtain rfl | hb := eq_or_ne b 0, { rw [zero_mul, mul_zero], }, { exact units.ext_iff.mp (ha (units.mk0 _ hb)) } end /-- In a group with zero, the center of the units is the preimage of the center. -/ lemma center_units_eq [group_with_zero M] : set.center Mˣ = (coe : Mˣ → M) ⁻¹' center M := subset.antisymm center_units_subset subset_center_units @[simp] lemma inv_mem_center₀ [group_with_zero M] {a : M} (ha : a ∈ set.center M) : a⁻¹ ∈ set.center M := begin obtain rfl | ha0 := eq_or_ne a 0, { rw inv_zero, exact zero_mem_center M }, rcases is_unit.mk0 _ ha0 with ⟨a, rfl⟩, rw ←units.coe_inv, exact center_units_subset (inv_mem_center (subset_center_units ha)), end @[simp, to_additive sub_mem_add_center] lemma div_mem_center [group M] {a b : M} (ha : a ∈ set.center M) (hb : b ∈ set.center M) : a / b ∈ set.center M := begin rw [div_eq_mul_inv], exact mul_mem_center ha (inv_mem_center hb), end @[simp] lemma div_mem_center₀ [group_with_zero M] {a b : M} (ha : a ∈ set.center M) (hb : b ∈ set.center M) : a / b ∈ set.center M := begin rw div_eq_mul_inv, exact mul_mem_center ha (inv_mem_center₀ hb), end variables (M) @[simp, to_additive add_center_eq_univ] lemma center_eq_univ [comm_semigroup M] : center M = set.univ := subset.antisymm (subset_univ _) $ λ x _ y, mul_comm y x end set namespace subsemigroup section variables (M) [semigroup M] /-- The center of a semigroup `M` is the set of elements that commute with everything in `M` -/ @[to_additive "The center of a semigroup `M` is the set of elements that commute with everything in `M`"] def center : subsemigroup M := { carrier := set.center M, mul_mem' := λ a b, set.mul_mem_center } @[to_additive] lemma coe_center : ↑(center M) = set.center M := rfl variables {M} @[to_additive] lemma mem_center_iff {z : M} : z ∈ center M ↔ ∀ g, g * z = z * g := iff.rfl @[to_additive] instance decidable_mem_center (a) [decidable $ ∀ b : M, b * a = a * b] : decidable (a ∈ center M) := decidable_of_iff' _ mem_center_iff /-- The center of a semigroup is commutative. -/ @[to_additive "The center of an additive semigroup is commutative."] instance : comm_semigroup (center M) := { mul_comm := λ a b, subtype.ext $ b.prop _, .. mul_mem_class.to_semigroup (center M) } end section variables (M) [comm_semigroup M] @[simp, to_additive] lemma center_eq_top : center M = ⊤ := set_like.coe_injective (set.center_eq_univ M) end end subsemigroup -- Guard against import creep assert_not_exists finset
a74b5328a2ab3ad8d0abe78951720cb3d95b724b
2eab05920d6eeb06665e1a6df77b3157354316ad
/src/topology/sheaves/stalks.lean
3c7c94709d1e61bfd1061ba8d87bad016be41da2
[ "Apache-2.0" ]
permissive
ayush1801/mathlib
78949b9f789f488148142221606bf15c02b960d2
ce164e28f262acbb3de6281b3b03660a9f744e3c
refs/heads/master
1,692,886,907,941
1,635,270,866,000
1,635,270,866,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
17,419
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Justus Springer -/ import topology.category.Top.open_nhds import topology.sheaves.presheaf import topology.sheaves.sheaf_condition.unique_gluing import category_theory.limits.types import category_theory.limits.preserves.filtered import tactic.elementwise /-! # Stalks For a presheaf `F` on a topological space `X`, valued in some category `C`, the *stalk* of `F` at the point `x : X` is defined as the colimit of the following functor (nhds x)ᵒᵖ ⥤ (opens X)ᵒᵖ ⥤ C where the functor on the left is the inclusion of categories and the functor on the right is `F`. For an open neighborhood `U` of `x`, we define the map `F.germ x : F.obj (op U) ⟶ F.stalk x` as the canonical morphism into this colimit. Taking stalks is functorial: For every point `x : X` we define a functor `stalk_functor C x`, sending presheaves on `X` to objects of `C`. Furthermore, for a map `f : X ⟶ Y` between topological spaces, we define `stalk_pushforward` as the induced map on the stalks `(f _* ℱ).stalk (f x) ⟶ ℱ.stalk x`. Some lemmas about stalks and germs only hold for certain classes of concrete categories. A basic property of forgetful functors of categories of algebraic structures (like `Mon`, `CommRing`,...) is that they preserve filtered colimits. Since stalks are filtered colimits, this ensures that the stalks of presheaves valued in these categories behave exactly as for `Type`-valued presheaves. For example, in `germ_exist` we prove that in such a category, every element of the stalk is the germ of a section. Furthermore, if we require the forgetful functor to reflect isomorphisms and preserve limits (as is the case for most algebraic structures), we have access to the unique gluing API and can prove further properties. Most notably, in `is_iso_iff_stalk_functor_map_iso`, we prove that in such a category, a morphism of sheaves is an isomorphism if and only if all of its stalk maps are isomorphisms. See also the definition of "algebraic structures" in the stacks project: https://stacks.math.columbia.edu/tag/007L -/ noncomputable theory universes v u v' u' open category_theory open Top open category_theory.limits open topological_space open opposite variables {C : Type u} [category.{v} C] variables [has_colimits.{v} C] variables {X Y Z : Top.{v}} namespace Top.presheaf variables (C) /-- Stalks are functorial with respect to morphisms of presheaves over a fixed `X`. -/ def stalk_functor (x : X) : X.presheaf C ⥤ C := ((whiskering_left _ _ C).obj (open_nhds.inclusion x).op) ⋙ colim variables {C} /-- The stalk of a presheaf `F` at a point `x` is calculated as the colimit of the functor nbhds x ⥤ opens F.X ⥤ C -/ def stalk (ℱ : X.presheaf C) (x : X) : C := (stalk_functor C x).obj ℱ -- -- colimit ((open_nhds.inclusion x).op ⋙ ℱ) @[simp] lemma stalk_functor_obj (ℱ : X.presheaf C) (x : X) : (stalk_functor C x).obj ℱ = ℱ.stalk x := rfl /-- The germ of a section of a presheaf over an open at a point of that open. -/ def germ (F : X.presheaf C) {U : opens X} (x : U) : F.obj (op U) ⟶ stalk F x := colimit.ι ((open_nhds.inclusion x.1).op ⋙ F) (op ⟨U, x.2⟩) @[simp, elementwise] lemma germ_res (F : X.presheaf C) {U V : opens X} (i : U ⟶ V) (x : U) : F.map i.op ≫ germ F x = germ F (i x : V) := let i' : (⟨U, x.2⟩ : open_nhds x.1) ⟶ ⟨V, (i x : V).2⟩ := i in colimit.w ((open_nhds.inclusion x.1).op ⋙ F) i'.op /-- A morphism from the stalk of `F` at `x` to some object `Y` is completely determined by its composition with the `germ` morphisms. -/ lemma stalk_hom_ext (F : X.presheaf C) {x} {Y : C} {f₁ f₂ : F.stalk x ⟶ Y} (ih : ∀ (U : opens X) (hxU : x ∈ U), F.germ ⟨x, hxU⟩ ≫ f₁ = F.germ ⟨x, hxU⟩ ≫ f₂) : f₁ = f₂ := colimit.hom_ext $ λ U, by { induction U using opposite.rec, cases U with U hxU, exact ih U hxU } @[simp, reassoc, elementwise] lemma stalk_functor_map_germ {F G : X.presheaf C} (U : opens X) (x : U) (f : F ⟶ G) : germ F x ≫ (stalk_functor C x.1).map f = f.app (op U) ≫ germ G x := colimit.ι_map (whisker_left ((open_nhds.inclusion x.1).op) f) (op ⟨U, x.2⟩) variables (C) /-- For a presheaf `F` on a space `X`, a continuous map `f : X ⟶ Y` induces a morphisms between the stalk of `f _ * F` at `f x` and the stalk of `F` at `x`. -/ def stalk_pushforward (f : X ⟶ Y) (F : X.presheaf C) (x : X) : (f _* F).stalk (f x) ⟶ F.stalk x := begin -- This is a hack; Lean doesn't like to elaborate the term written directly. transitivity, swap, exact colimit.pre _ (open_nhds.map f x).op, exact colim.map (whisker_right (nat_trans.op (open_nhds.inclusion_map_iso f x).inv) F), end @[simp, elementwise, reassoc] lemma stalk_pushforward_germ (f : X ⟶ Y) (F : X.presheaf C) (U : opens Y) (x : (opens.map f).obj U) : (f _* F).germ ⟨f x, x.2⟩ ≫ F.stalk_pushforward C f x = F.germ x := begin rw [stalk_pushforward, germ, colimit.ι_map_assoc, colimit.ι_pre, whisker_right_app], erw [category_theory.functor.map_id, category.id_comp], refl, end -- Here are two other potential solutions, suggested by @fpvandoorn at -- <https://github.com/leanprover-community/mathlib/pull/1018#discussion_r283978240> -- However, I can't get the subsequent two proofs to work with either one. -- def stalk_pushforward (f : X ⟶ Y) (ℱ : X.presheaf C) (x : X) : -- (f _* ℱ).stalk (f x) ⟶ ℱ.stalk x := -- colim.map ((functor.associator _ _ _).inv ≫ -- whisker_right (nat_trans.op (open_nhds.inclusion_map_iso f x).inv) ℱ) ≫ -- colimit.pre ((open_nhds.inclusion x).op ⋙ ℱ) (open_nhds.map f x).op -- def stalk_pushforward (f : X ⟶ Y) (ℱ : X.presheaf C) (x : X) : -- (f _* ℱ).stalk (f x) ⟶ ℱ.stalk x := -- (colim.map (whisker_right (nat_trans.op (open_nhds.inclusion_map_iso f x).inv) ℱ) : -- colim.obj ((open_nhds.inclusion (f x) ⋙ opens.map f).op ⋙ ℱ) ⟶ _) ≫ -- colimit.pre ((open_nhds.inclusion x).op ⋙ ℱ) (open_nhds.map f x).op namespace stalk_pushforward local attribute [tidy] tactic.op_induction' @[simp] lemma id (ℱ : X.presheaf C) (x : X) : ℱ.stalk_pushforward C (𝟙 X) x = (stalk_functor C x).map ((pushforward.id ℱ).hom) := begin dsimp [stalk_pushforward, stalk_functor], ext1, tactic.op_induction', cases j, cases j_val, rw [colimit.ι_map_assoc, colimit.ι_map, colimit.ι_pre, whisker_left_app, whisker_right_app, pushforward.id_hom_app, eq_to_hom_map, eq_to_hom_refl], dsimp, -- FIXME A simp lemma which unfortunately doesn't fire: erw [category_theory.functor.map_id], end -- This proof is sadly not at all robust: -- having to use `erw` at all is a bad sign. @[simp] lemma comp (ℱ : X.presheaf C) (f : X ⟶ Y) (g : Y ⟶ Z) (x : X) : ℱ.stalk_pushforward C (f ≫ g) x = ((f _* ℱ).stalk_pushforward C g (f x)) ≫ (ℱ.stalk_pushforward C f x) := begin dsimp [stalk_pushforward, stalk_functor], ext U, induction U using opposite.rec, cases U, cases U_val, simp only [colimit.ι_map_assoc, colimit.ι_pre_assoc, whisker_right_app, category.assoc], dsimp, -- FIXME: Some of these are simp lemmas, but don't fire successfully: erw [category_theory.functor.map_id, category.id_comp, category.id_comp, category.id_comp, colimit.ι_pre, colimit.ι_pre], refl, end end stalk_pushforward section concrete variables {C} variables [concrete_category.{v} C] local attribute [instance] concrete_category.has_coe_to_sort concrete_category.has_coe_to_fun @[ext] lemma germ_ext (F : X.presheaf C) {U V : opens X} {x : X} {hxU : x ∈ U} {hxV : x ∈ V} (W : opens X) (hxW : x ∈ W) (iWU : W ⟶ U) (iWV : W ⟶ V) {sU : F.obj (op U)} {sV : F.obj (op V)} (ih : F.map iWU.op sU = F.map iWV.op sV) : F.germ ⟨x, hxU⟩ sU = F.germ ⟨x, hxV⟩ sV := by erw [← F.germ_res iWU ⟨x, hxW⟩, ← F.germ_res iWV ⟨x, hxW⟩, comp_apply, comp_apply, ih] variables [preserves_filtered_colimits (forget C)] /-- For presheaves valued in a concrete category whose forgetful functor preserves filtered colimits, every element of the stalk is the germ of a section. -/ lemma germ_exist (F : X.presheaf C) (x : X) (t : stalk F x) : ∃ (U : opens X) (m : x ∈ U) (s : F.obj (op U)), F.germ ⟨x, m⟩ s = t := begin obtain ⟨U, s, e⟩ := types.jointly_surjective _ (is_colimit_of_preserves (forget C) (colimit.is_colimit _)) t, revert s e, rw [(show U = op (unop U), from rfl)], generalize : unop U = V, clear U, cases V with V m, intros s e, exact ⟨V, m, s, e⟩, end lemma germ_eq (F : X.presheaf C) {U V : opens X} (x : X) (mU : x ∈ U) (mV : x ∈ V) (s : F.obj (op U)) (t : F.obj (op V)) (h : germ F ⟨x, mU⟩ s = germ F ⟨x, mV⟩ t) : ∃ (W : opens X) (m : x ∈ W) (iU : W ⟶ U) (iV : W ⟶ V), F.map iU.op s = F.map iV.op t := begin obtain ⟨W, iU, iV, e⟩ := (types.filtered_colimit.is_colimit_eq_iff _ (is_colimit_of_preserves _ (colimit.is_colimit ((open_nhds.inclusion x).op ⋙ F)))).mp h, exact ⟨(unop W).1, (unop W).2, iU.unop, iV.unop, e⟩, end lemma stalk_functor_map_injective_of_app_injective {F G : presheaf C X} (f : F ⟶ G) (h : ∀ U : opens X, function.injective (f.app (op U))) (x : X) : function.injective ((stalk_functor C x).map f) := λ s t hst, begin rcases germ_exist F x s with ⟨U₁, hxU₁, s, rfl⟩, rcases germ_exist F x t with ⟨U₂, hxU₂, t, rfl⟩, simp only [stalk_functor_map_germ_apply _ ⟨x,_⟩] at hst, obtain ⟨W, hxW, iWU₁, iWU₂, heq⟩ := G.germ_eq x hxU₁ hxU₂ _ _ hst, rw [← comp_apply, ← comp_apply, ← f.naturality, ← f.naturality, comp_apply, comp_apply] at heq, replace heq := h W heq, convert congr_arg (F.germ ⟨x,hxW⟩) heq, exacts [(F.germ_res_apply iWU₁ ⟨x,hxW⟩ s).symm, (F.germ_res_apply iWU₂ ⟨x,hxW⟩ t).symm], end variables [has_limits C] [preserves_limits (forget C)] [reflects_isomorphisms (forget C)] /-- Let `F` be a sheaf valued in a concrete category, whose forgetful functor reflects isomorphisms, preserves limits and filtered colimits. Then two sections who agree on every stalk must be equal. -/ lemma section_ext (F : sheaf C X) (U : opens X) (s t : F.1.obj (op U)) (h : ∀ x : U, F.1.germ x s = F.1.germ x t) : s = t := begin -- We use `germ_eq` and the axiom of choice, to pick for every point `x` a neighbourhood -- `V x`, such that the restrictions of `s` and `t` to `V x` coincide. choose V m i₁ i₂ heq using λ x : U, F.1.germ_eq x.1 x.2 x.2 s t (h x), -- Since `F` is a sheaf, we can prove the equality locally, if we can show that these -- neighborhoods form a cover of `U`. apply F.eq_of_locally_eq' V U i₁, { intros x hxU, rw [opens.mem_coe, opens.mem_supr], exact ⟨⟨x, hxU⟩, m ⟨x, hxU⟩⟩ }, { intro x, rw [heq, subsingleton.elim (i₁ x) (i₂ x)] } end /- Note that the analogous statement for surjectivity is false: Surjectivity on stalks does not imply surjectivity of the components of a sheaf morphism. However it does imply that the morphism is an epi, but this fact is not yet formalized. -/ lemma app_injective_of_stalk_functor_map_injective {F : sheaf C X} {G : presheaf C X} (f : F.1 ⟶ G) (h : ∀ x : X, function.injective ((stalk_functor C x).map f)) (U : opens X) : function.injective (f.app (op U)) := λ s t hst, section_ext F _ _ _ $ λ x, h x.1 $ by rw [stalk_functor_map_germ_apply, stalk_functor_map_germ_apply, hst] lemma app_injective_iff_stalk_functor_map_injective {F : sheaf C X} {G : presheaf C X} (f : F.1 ⟶ G) : (∀ x : X, function.injective ((stalk_functor C x).map f)) ↔ (∀ U : opens X, function.injective (f.app (op U))) := ⟨app_injective_of_stalk_functor_map_injective f, stalk_functor_map_injective_of_app_injective f⟩ /-- For surjectivity, we are given an arbitrary section `t` and need to find a preimage for it. We claim that it suffices to find preimages *locally*. That is, for each `x : U` we construct a neighborhood `V ≤ U` and a section `s : F.obj (op V))` such that `f.app (op V) s` and `t` agree on `V`. -/ lemma app_surjective_of_injective_of_locally_surjective {F G : sheaf C X} (f : F ⟶ G) (hinj : ∀ x : X, function.injective ((stalk_functor C x).map f)) (U : opens X) (hsurj : ∀ (t) (x : U), ∃ (V : opens X) (m : x.1 ∈ V) (iVU : V ⟶ U) (s : F.1.obj (op V)), f.app (op V) s = G.1.map iVU.op t) : function.surjective (f.app (op U)) := begin intro t, -- We use the axiom of choice to pick around each point `x` an open neighborhood `V` and a -- preimage under `f` on `V`. choose V mV iVU sf heq using hsurj t, -- These neighborhoods clearly cover all of `U`. have V_cover : U ≤ supr V, { intros x hxU, rw [opens.mem_coe, opens.mem_supr], exact ⟨⟨x, hxU⟩, mV ⟨x, hxU⟩⟩ }, -- Since `F` is a sheaf, we can glue all the local preimages together to get a global preimage. obtain ⟨s, s_spec, -⟩ := F.exists_unique_gluing' V U iVU V_cover sf _, { use s, apply G.eq_of_locally_eq' V U iVU V_cover, intro x, rw [← comp_apply, ← f.naturality, comp_apply, s_spec, heq] }, { intros x y, -- What's left to show here is that the secions `sf` are compatible, i.e. they agree on -- the intersections `V x ⊓ V y`. We prove this by showing that all germs are equal. apply section_ext, intro z, -- Here, we need to use injectivity of the stalk maps. apply (hinj z), erw [stalk_functor_map_germ_apply, stalk_functor_map_germ_apply], simp_rw [← comp_apply, f.naturality, comp_apply, heq, ← comp_apply, ← G.1.map_comp], refl } end lemma app_surjective_of_stalk_functor_map_bijective {F G : sheaf C X} (f : F ⟶ G) (h : ∀ x : X, function.bijective ((stalk_functor C x).map f)) (U : opens X) : function.surjective (f.app (op U)) := begin refine app_surjective_of_injective_of_locally_surjective f (λ x, (h x).1) U (λ t x, _), -- Now we need to prove our initial claim: That we can find preimages of `t` locally. -- Since `f` is surjective on stalks, we can find a preimage `s₀` of the germ of `t` at `x` obtain ⟨s₀,hs₀⟩ := (h x).2 (G.1.germ x t), -- ... and this preimage must come from some section `s₁` defined on some open neighborhood `V₁` obtain ⟨V₁,hxV₁,s₁,hs₁⟩ := F.1.germ_exist x.1 s₀, subst hs₁, rename hs₀ hs₁, erw stalk_functor_map_germ_apply V₁ ⟨x.1,hxV₁⟩ f s₁ at hs₁, -- Now, the germ of `f.app (op V₁) s₁` equals the germ of `t`, hence they must coincide on -- some open neighborhood `V₂`. obtain ⟨V₂, hxV₂, iV₂V₁, iV₂U, heq⟩ := G.1.germ_eq x.1 hxV₁ x.2 _ _ hs₁, -- The restriction of `s₁` to that neighborhood is our desired local preimage. use [V₂, hxV₂, iV₂U, F.1.map iV₂V₁.op s₁], rw [← comp_apply, f.naturality, comp_apply, heq], end lemma app_bijective_of_stalk_functor_map_bijective {F G : sheaf C X} (f : F ⟶ G) (h : ∀ x : X, function.bijective ((stalk_functor C x).map f)) (U : opens X) : function.bijective (f.app (op U)) := ⟨app_injective_of_stalk_functor_map_injective f (λ x, (h x).1) U, app_surjective_of_stalk_functor_map_bijective f h U⟩ /-- Let `F` and `G` be sheaves valued in a concrete category, whose forgetful functor reflects isomorphisms, preserves limits and filtered colimits. Then if the stalk maps of a morphism `f : F ⟶ G` are all isomorphisms, `f` must be an isomorphism. -/ -- Making this an instance would cause a loop in typeclass resolution with `functor.map_is_iso` lemma is_iso_of_stalk_functor_map_iso {F G : sheaf C X} (f : F ⟶ G) [∀ x : X, is_iso ((stalk_functor C x).map f)] : is_iso f := begin -- Since the inclusion functor from sheaves to presheaves is fully faithful, it suffices to -- show that `f`, as a morphism between _presheaves_, is an isomorphism. suffices : is_iso ((sheaf.forget C X).map f), { exactI is_iso_of_fully_faithful (sheaf.forget C X) f }, -- We show that all components of `f` are isomorphisms. suffices : ∀ U : (opens X)ᵒᵖ, is_iso (f.app U), { exact @nat_iso.is_iso_of_is_iso_app _ _ _ _ F.1 G.1 f this, }, intro U, induction U using opposite.rec, -- Since the forgetful functor of `C` reflects isomorphisms, it suffices to see that the -- underlying map between types is an isomorphism, i.e. bijective. suffices : is_iso ((forget C).map (f.app (op U))), { exactI is_iso_of_reflects_iso (f.app (op U)) (forget C) }, rw is_iso_iff_bijective, apply app_bijective_of_stalk_functor_map_bijective, intro x, apply (is_iso_iff_bijective _).mp, exact functor.map_is_iso (forget C) ((stalk_functor C x).map f), end /-- Let `F` and `G` be sheaves valued in a concrete category, whose forgetful functor reflects isomorphisms, preserves limits and filtered colimits. Then a morphism `f : F ⟶ G` is an isomorphism if and only if all of its stalk maps are isomorphisms. -/ lemma is_iso_iff_stalk_functor_map_iso {F G : sheaf C X} (f : F ⟶ G) : is_iso f ↔ ∀ x : X, is_iso ((stalk_functor C x).map f) := begin split, { intros h x, resetI, exact @functor.map_is_iso _ _ _ _ _ _ (stalk_functor C x) f ((sheaf.forget C X).map_is_iso f) }, { intro h, exactI is_iso_of_stalk_functor_map_iso f } end end concrete end Top.presheaf
1a19884bd01547fe38b6907e5e0376c8c4dbe760
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/analysis/normed_space/extend.lean
df94fa21910bdf1b4db7a11eccfbca288951b321
[]
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,378
lean
/- Copyright (c) 2020 Ruben Van de Velde. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Ruben Van de Velde -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.analysis.complex.basic import Mathlib.analysis.normed_space.operator_norm import Mathlib.data.complex.is_R_or_C import Mathlib.PostPort universes u_1 u_2 namespace Mathlib /-! # Extending a continuous `ℝ`-linear map to a continuous `𝕜`-linear map In this file we provide a way to extend a continuous `ℝ`-linear map to a continuous `𝕜`-linear map in a way that bounds the norm by the norm of the original map, when `𝕜` is either `ℝ` (the extension is trivial) or `ℂ`. We formulate the extension uniformly, by assuming `is_R_or_C 𝕜`. We motivate the form of the extension as follows. Note that `fc : F →ₗ[𝕜] 𝕜` is determined fully by `Re fc`: for all `x : F`, `fc (I • x) = I * fc x`, so `Im (fc x) = -Re (fc (I • x))`. Therefore, given an `fr : F →ₗ[ℝ] ℝ`, we define `fc x = fr x - fr (I • x) * I`. -/ /-- Extend `fr : F →ₗ[ℝ] ℝ` to `F →ₗ[𝕜] 𝕜` in a way that will also be continuous and have its norm bounded by `∥fr∥` if `fr` is continuous. -/ def linear_map.extend_to_𝕜 {𝕜 : Type u_1} [is_R_or_C 𝕜] {F : Type u_2} [normed_group F] [normed_space 𝕜 F] (fr : linear_map ℝ (restrict_scalars ℝ 𝕜 F) ℝ) : linear_map 𝕜 F 𝕜 := let fc : F → 𝕜 := fun (x : F) => ↑(coe_fn fr x) - is_R_or_C.I * ↑(coe_fn fr (is_R_or_C.I • x)); linear_map.mk fc sorry sorry /-- The norm of the extension is bounded by `∥fr∥`. -/ theorem norm_bound {𝕜 : Type u_1} [is_R_or_C 𝕜] {F : Type u_2} [normed_group F] [normed_space 𝕜 F] (fr : continuous_linear_map ℝ (restrict_scalars ℝ 𝕜 F) ℝ) (x : F) : norm (coe_fn (linear_map.extend_to_𝕜 (continuous_linear_map.to_linear_map fr)) x) ≤ norm fr * norm x := sorry /-- Extend `fr : F →L[ℝ] ℝ` to `F →L[𝕜] 𝕜`. -/ def continuous_linear_map.extend_to_𝕜 {𝕜 : Type u_1} [is_R_or_C 𝕜] {F : Type u_2} [normed_group F] [normed_space 𝕜 F] (fr : continuous_linear_map ℝ (restrict_scalars ℝ 𝕜 F) ℝ) : continuous_linear_map 𝕜 F 𝕜 := linear_map.mk_continuous (linear_map.extend_to_𝕜 (continuous_linear_map.to_linear_map fr)) (norm fr) (norm_bound fr)
d39691321a3a57442803df647835e6d02dc5c991
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/number_theory/padics/padic_val.lean
d0817533ceafcd0ff7ce4eccd7a0103072133c92
[ "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,771
lean
/- Copyright (c) 2018 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis -/ import number_theory.divisors import ring_theory.int.basic import tactic.ring_exp /-! # p-adic Valuation This file defines the `p`-adic valuation on `ℕ`, `ℤ`, and `ℚ`. The `p`-adic valuation on `ℚ` is the difference of the multiplicities of `p` in the numerator and denominator of `q`. This function obeys the standard properties of a valuation, with the appropriate assumptions on `p`. The `p`-adic valuations on `ℕ` and `ℤ` agree with that on `ℚ`. The valuation induces a norm on `ℚ`. This norm is defined in padic_norm.lean. ## Notations This file uses the local notation `/.` for `rat.mk`. ## Implementation notes Much, but not all, of this file assumes that `p` is prime. This assumption is inferred automatically by taking `[fact p.prime]` as a type class argument. ## References * [F. Q. Gouvêa, *p-adic numbers*][gouvea1997] * [R. Y. Lewis, *A formal proof of Hensel's lemma over the p-adic integers*][lewis2019] * <https://en.wikipedia.org/wiki/P-adic_number> ## Tags p-adic, p adic, padic, norm, valuation -/ universe u open nat open_locale rat open multiplicity /-- For `p ≠ 1`, the `p`-adic valuation of a natural `n ≠ 0` is the largest natural number `k` such that `p^k` divides `z`. If `n = 0` or `p = 1`, then `padic_val_nat p q` defaults to `0`. -/ def padic_val_nat (p : ℕ) (n : ℕ) : ℕ := if h : p ≠ 1 ∧ 0 < n then (multiplicity p n).get (multiplicity.finite_nat_iff.2 h) else 0 namespace padic_val_nat open multiplicity variables {p : ℕ} /-- `padic_val_nat p 0` is `0` for any `p`. -/ @[simp] protected lemma zero : padic_val_nat p 0 = 0 := by simp [padic_val_nat] /-- `padic_val_nat p 1` is `0` for any `p`. -/ @[simp] protected lemma one : padic_val_nat p 1 = 0 := by { unfold padic_val_nat, split_ifs, simp } /-- If `p ≠ 0` and `p ≠ 1`, then `padic_val_rat p p` is `1`. -/ @[simp] lemma self (hp : 1 < p) : padic_val_nat p p = 1 := begin have neq_one : (¬ p = 1) ↔ true, { exact iff_of_true ((ne_of_lt hp).symm) trivial }, have eq_zero_false : p = 0 ↔ false, { exact iff_false_intro ((ne_of_lt (trans zero_lt_one hp)).symm) }, simp [padic_val_nat, neq_one, eq_zero_false] end lemma eq_zero_of_not_dvd {n : ℕ} (h : ¬ p ∣ n) : padic_val_nat p n = 0 := by { rw padic_val_nat, split_ifs; simp [multiplicity_eq_zero_of_not_dvd h] } end padic_val_nat /-- For `p ≠ 1`, the `p`-adic valuation of an integer `z ≠ 0` is the largest natural number `k` such that `p^k` divides `z`. If `x = 0` or `p = 1`, then `padic_val_int p q` defaults to `0`. -/ def padic_val_int (p : ℕ) (z : ℤ) : ℕ := padic_val_nat p z.nat_abs namespace padic_val_int open multiplicity variables {p : ℕ} lemma of_ne_one_ne_zero {z : ℤ} (hp : p ≠ 1) (hz : z ≠ 0) : padic_val_int p z = (multiplicity (p : ℤ) z).get (by {apply multiplicity.finite_int_iff.2, simp [hp, hz]}) := begin rw [padic_val_int, padic_val_nat, dif_pos (and.intro hp (int.nat_abs_pos_of_ne_zero hz))], simp only [multiplicity.int.nat_abs p z], refl end /-- `padic_val_int p 0` is `0` for any `p`. -/ @[simp] protected lemma zero : padic_val_int p 0 = 0 := by simp [padic_val_int] /-- `padic_val_int p 1` is `0` for any `p`. -/ @[simp] protected lemma one : padic_val_int p 1 = 0 := by simp [padic_val_int] /-- The `p`-adic value of a natural is its `p`-adic value as an integer. -/ @[simp] lemma of_nat {n : ℕ} : padic_val_int p n = padic_val_nat p n := by simp [padic_val_int] /-- If `p ≠ 0` and `p ≠ 1`, then `padic_val_int p p` is `1`. -/ lemma self (hp : 1 < p) : padic_val_int p p = 1 := by simp [padic_val_nat.self hp] lemma eq_zero_of_not_dvd {z : ℤ} (h : ¬ (p : ℤ) ∣ z) : padic_val_int p z = 0 := begin rw [padic_val_int, padic_val_nat], split_ifs; simp [multiplicity.int.nat_abs, multiplicity_eq_zero_of_not_dvd h], end end padic_val_int /-- `padic_val_rat` defines the valuation of a rational `q` to be the valuation of `q.num` minus the valuation of `q.denom`. If `q = 0` or `p = 1`, then `padic_val_rat p q` defaults to `0`. -/ def padic_val_rat (p : ℕ) (q : ℚ) : ℤ := padic_val_int p q.num - padic_val_nat p q.denom namespace padic_val_rat open multiplicity variables {p : ℕ} /-- `padic_val_rat p q` is symmetric in `q`. -/ @[simp] protected lemma neg (q : ℚ) : padic_val_rat p (-q) = padic_val_rat p q := by simp [padic_val_rat, padic_val_int] /-- `padic_val_rat p 0` is `0` for any `p`. -/ @[simp] protected lemma zero : padic_val_rat p 0 = 0 := by simp [padic_val_rat] /-- `padic_val_rat p 1` is `0` for any `p`. -/ @[simp] protected lemma one : padic_val_rat p 1 = 0 := by simp [padic_val_rat] /-- The `p`-adic value of an integer `z ≠ 0` is its `p`-adic_value as a rational. -/ @[simp] lemma of_int {z : ℤ} : padic_val_rat p z = padic_val_int p z := by simp [padic_val_rat] /-- The `p`-adic value of an integer `z ≠ 0` is the multiplicity of `p` in `z`. -/ lemma of_int_multiplicity {z : ℤ} (hp : p ≠ 1) (hz : z ≠ 0) : padic_val_rat p (z : ℚ) = (multiplicity (p : ℤ) z).get (finite_int_iff.2 ⟨hp, hz⟩) := by rw [of_int, padic_val_int.of_ne_one_ne_zero hp hz] lemma multiplicity_sub_multiplicity {q : ℚ} (hp : p ≠ 1) (hq : q ≠ 0) : padic_val_rat p q = (multiplicity (p : ℤ) q.num).get (finite_int_iff.2 ⟨hp, rat.num_ne_zero_of_ne_zero hq⟩) - (multiplicity p q.denom).get (by { rw [← finite_iff_dom, finite_nat_iff], exact ⟨hp, q.pos⟩ }) := begin rw [padic_val_rat, padic_val_int.of_ne_one_ne_zero hp, padic_val_nat, dif_pos], { refl }, { exact ⟨hp, q.pos⟩ }, { exact rat.num_ne_zero_of_ne_zero hq } end /-- The `p`-adic value of an integer `z ≠ 0` is its `p`-adic value as a rational. -/ @[simp] lemma of_nat {n : ℕ} : padic_val_rat p n = padic_val_nat p n := by simp [padic_val_rat] /-- If `p ≠ 0` and `p ≠ 1`, then `padic_val_rat p p` is `1`. -/ lemma self (hp : 1 < p) : padic_val_rat p p = 1 := by simp [hp] end padic_val_rat section padic_val_nat variables {p : ℕ} lemma zero_le_padic_val_rat_of_nat (n : ℕ) : 0 ≤ padic_val_rat p n := by simp /-- `padic_val_rat` coincides with `padic_val_nat`. -/ @[norm_cast] lemma padic_val_rat_of_nat (n : ℕ) : ↑(padic_val_nat p n) = padic_val_rat p n := by simp /-- A simplification of `padic_val_nat` when one input is prime, by analogy with `padic_val_rat_def`. -/ lemma padic_val_nat_def [hp : fact p.prime] {n : ℕ} (hn : 0 < n) : padic_val_nat p n = (multiplicity p n).get (multiplicity.finite_nat_iff.2 ⟨nat.prime.ne_one hp.1, hn⟩) := begin simp [padic_val_nat], split_ifs, { refl }, { exfalso, exact h ⟨hp.out.ne_one, hn⟩ } end lemma padic_val_nat_def' {n : ℕ} (hp : p ≠ 1) (hn : 0 < n) : ↑(padic_val_nat p n) = multiplicity p n := by simp [padic_val_nat, hp, hn] @[simp] lemma padic_val_nat_self [fact p.prime] : padic_val_nat p p = 1 := by simp [padic_val_nat_def (fact.out p.prime).pos] lemma one_le_padic_val_nat_of_dvd {n : ℕ} [hp : fact p.prime] (hn : 0 < n) (div : p ∣ n) : 1 ≤ padic_val_nat p n := begin rw padic_val_nat_def hn, let one_le_mul : _ ≤ multiplicity p n := multiplicity.le_multiplicity_of_pow_dvd (by { rw [pow_one], exact div }), simp only [nat.cast_one] at one_le_mul, rcases one_le_mul with ⟨_, q⟩, dsimp at q, solve_by_elim, exact hp end lemma dvd_iff_padic_val_nat_ne_zero {p n : ℕ} [fact p.prime] (hn0 : n ≠ 0) : (p ∣ n) ↔ padic_val_nat p n ≠ 0 := ⟨λ h, one_le_iff_ne_zero.mp (one_le_padic_val_nat_of_dvd hn0.bot_lt h), λ h, not_not.1 (mt padic_val_nat.eq_zero_of_not_dvd h)⟩ end padic_val_nat namespace padic_val_rat open multiplicity variables {p : ℕ} [hp : fact p.prime] include hp /-- The multiplicity of `p : ℕ` in `a : ℤ` is finite exactly when `a ≠ 0`. -/ lemma finite_int_prime_iff {a : ℤ} : finite (p : ℤ) a ↔ a ≠ 0 := by simp [finite_int_iff, ne.symm (ne_of_lt hp.1.one_lt)] /-- A rewrite lemma for `padic_val_rat p q` when `q` is expressed in terms of `rat.mk`. -/ protected lemma defn (p : ℕ) [hp : fact p.prime] {q : ℚ} {n d : ℤ} (hqz : q ≠ 0) (qdf : q = n /. d) : padic_val_rat p q = (multiplicity (p : ℤ) n).get (finite_int_iff.2 ⟨ne.symm $ ne_of_lt hp.1.one_lt, λ hn, by simp * at *⟩) - (multiplicity (p : ℤ) d).get (finite_int_iff.2 ⟨ne.symm $ ne_of_lt hp.1.one_lt, λ hd, by simp * at *⟩) := have hd : d ≠ 0, from rat.mk_denom_ne_zero_of_ne_zero hqz qdf, let ⟨c, hc1, hc2⟩ := rat.num_denom_mk hd qdf in begin rw [padic_val_rat.multiplicity_sub_multiplicity]; simp [hc1, hc2, multiplicity.mul' (nat.prime_iff_prime_int.1 hp.1), ne.symm (ne_of_lt hp.1.one_lt), hqz, pos_iff_ne_zero, int.coe_nat_multiplicity p q.denom] end /-- A rewrite lemma for `padic_val_rat p (q * r)` with conditions `q ≠ 0`, `r ≠ 0`. -/ protected lemma mul {q r : ℚ} (hq : q ≠ 0) (hr : r ≠ 0) : padic_val_rat p (q * r) = padic_val_rat p q + padic_val_rat p r := have q * r = (q.num * r.num) /. (q.denom * r.denom), by rw_mod_cast rat.mul_num_denom, have hq' : q.num /. q.denom ≠ 0, by rw rat.num_denom; exact hq, have hr' : r.num /. r.denom ≠ 0, by rw rat.num_denom; exact hr, have hp' : _root_.prime (p : ℤ), from nat.prime_iff_prime_int.1 hp.1, begin rw [padic_val_rat.defn p (mul_ne_zero hq hr) this], conv_rhs { rw [← @rat.num_denom q, padic_val_rat.defn p hq', ← @rat.num_denom r, padic_val_rat.defn p hr'] }, rw [multiplicity.mul' hp', multiplicity.mul' hp']; simp [add_comm, add_left_comm, sub_eq_add_neg] end /-- A rewrite lemma for `padic_val_rat p (q^k)` with condition `q ≠ 0`. -/ protected lemma pow {q : ℚ} (hq : q ≠ 0) {k : ℕ} : padic_val_rat p (q ^ k) = k * padic_val_rat p q := by induction k; simp [*, padic_val_rat.mul hq (pow_ne_zero _ hq), pow_succ, add_mul, add_comm] /-- A rewrite lemma for `padic_val_rat p (q⁻¹)` with condition `q ≠ 0`. -/ protected lemma inv (q : ℚ) : padic_val_rat p q⁻¹ = -padic_val_rat p q := begin by_cases hq : q = 0, { simp [hq] }, { rw [eq_neg_iff_add_eq_zero, ← padic_val_rat.mul (inv_ne_zero hq) hq, inv_mul_cancel hq, padic_val_rat.one], exact hp }, end /-- A rewrite lemma for `padic_val_rat p (q / r)` with conditions `q ≠ 0`, `r ≠ 0`. -/ protected lemma div {q r : ℚ} (hq : q ≠ 0) (hr : r ≠ 0) : padic_val_rat p (q / r) = padic_val_rat p q - padic_val_rat p r := begin rw [div_eq_mul_inv, padic_val_rat.mul hq (inv_ne_zero hr), padic_val_rat.inv r, sub_eq_add_neg], all_goals { exact hp } end /-- A condition for `padic_val_rat p (n₁ / d₁) ≤ padic_val_rat p (n₂ / d₂)`, in terms of divisibility by `p^n`. -/ lemma padic_val_rat_le_padic_val_rat_iff {n₁ n₂ d₁ d₂ : ℤ} (hn₁ : n₁ ≠ 0) (hn₂ : n₂ ≠ 0) (hd₁ : d₁ ≠ 0) (hd₂ : d₂ ≠ 0) : padic_val_rat p (n₁ /. d₁) ≤ padic_val_rat p (n₂ /. d₂) ↔ ∀ n : ℕ, ↑p ^ n ∣ n₁ * d₂ → ↑p ^ n ∣ n₂ * d₁ := have hf1 : finite (p : ℤ) (n₁ * d₂), from finite_int_prime_iff.2 (mul_ne_zero hn₁ hd₂), have hf2 : finite (p : ℤ) (n₂ * d₁), from finite_int_prime_iff.2 (mul_ne_zero hn₂ hd₁), by conv { to_lhs, rw [padic_val_rat.defn p (rat.mk_ne_zero_of_ne_zero hn₁ hd₁) rfl, padic_val_rat.defn p (rat.mk_ne_zero_of_ne_zero hn₂ hd₂) rfl, sub_le_iff_le_add', ← add_sub_assoc, le_sub_iff_add_le], norm_cast, rw [← multiplicity.mul' (nat.prime_iff_prime_int.1 hp.1) hf1, add_comm, ← multiplicity.mul' (nat.prime_iff_prime_int.1 hp.1) hf2, part_enat.get_le_get, multiplicity_le_multiplicity_iff] } /-- Sufficient conditions to show that the `p`-adic valuation of `q` is less than or equal to the `p`-adic valuation of `q + r`. -/ theorem le_padic_val_rat_add_of_le {q r : ℚ} (hqr : q + r ≠ 0) (h : padic_val_rat p q ≤ padic_val_rat p r) : padic_val_rat p q ≤ padic_val_rat p (q + r) := if hq : q = 0 then by simpa [hq] using h else if hr : r = 0 then by simp [hr] else have hqn : q.num ≠ 0, from rat.num_ne_zero_of_ne_zero hq, have hqd : (q.denom : ℤ) ≠ 0, by exact_mod_cast rat.denom_ne_zero _, have hrn : r.num ≠ 0, from rat.num_ne_zero_of_ne_zero hr, have hrd : (r.denom : ℤ) ≠ 0, by exact_mod_cast rat.denom_ne_zero _, have hqreq : q + r = (q.num * r.denom + q.denom * r.num) /. (q.denom * r.denom), from rat.add_num_denom _ _, have hqrd : q.num * r.denom + q.denom * r.num ≠ 0, from rat.mk_num_ne_zero_of_ne_zero hqr hqreq, begin conv_lhs { rw ← @rat.num_denom q }, rw [hqreq, padic_val_rat_le_padic_val_rat_iff hqn hqrd hqd (mul_ne_zero hqd hrd), ← multiplicity_le_multiplicity_iff, mul_left_comm, multiplicity.mul (nat.prime_iff_prime_int.1 hp.1), add_mul], rw [← @rat.num_denom q, ← @rat.num_denom r, padic_val_rat_le_padic_val_rat_iff hqn hrn hqd hrd, ← multiplicity_le_multiplicity_iff] at h, calc _ ≤ min (multiplicity ↑p (q.num * ↑r.denom * ↑q.denom)) (multiplicity ↑p (↑q.denom * r.num * ↑q.denom)) : (le_min (by rw [@multiplicity.mul _ _ _ _ (_ * _) _ (nat.prime_iff_prime_int.1 hp.1), add_comm]) (by rw [mul_assoc, @multiplicity.mul _ _ _ _ (q.denom : ℤ) (_ * _) (nat.prime_iff_prime_int.1 hp.1)]; exact add_le_add_left h _)) ... ≤ _ : min_le_multiplicity_add, all_goals { exact hp } end /-- The minimum of the valuations of `q` and `r` is at most the valuation of `q + r`. -/ theorem min_le_padic_val_rat_add {q r : ℚ} (hqr : q + r ≠ 0) : min (padic_val_rat p q) (padic_val_rat p r) ≤ padic_val_rat p (q + r) := (le_total (padic_val_rat p q) (padic_val_rat p r)).elim (λ h, by rw [min_eq_left h]; exact le_padic_val_rat_add_of_le hqr h) (λ h, by rw [min_eq_right h, add_comm]; exact le_padic_val_rat_add_of_le (by rwa add_comm) h) open_locale big_operators /-- A finite sum of rationals with positive `p`-adic valuation has positive `p`-adic valuation (if the sum is non-zero). -/ theorem sum_pos_of_pos {n : ℕ} {F : ℕ → ℚ} (hF : ∀ i, i < n → 0 < padic_val_rat p (F i)) (hn0 : ∑ i in finset.range n, F i ≠ 0) : 0 < padic_val_rat p (∑ i in finset.range n, F i) := begin induction n with d hd, { exact false.elim (hn0 rfl) }, { rw finset.sum_range_succ at hn0 ⊢, by_cases h : ∑ (x : ℕ) in finset.range d, F x = 0, { rw [h, zero_add], exact hF d (lt_add_one _) }, { refine lt_of_lt_of_le _ (min_le_padic_val_rat_add hn0), { refine lt_min (hd (λ i hi, _) h) (hF d (lt_add_one _)), exact hF _ (lt_trans hi (lt_add_one _)) } } } end end padic_val_rat namespace padic_val_nat variables {p a b : ℕ} [hp : fact p.prime] include hp /-- A rewrite lemma for `padic_val_nat p (a * b)` with conditions `a ≠ 0`, `b ≠ 0`. -/ protected lemma mul (ha : a ≠ 0) (hb : b ≠ 0) : padic_val_nat p (a * b) = padic_val_nat p a + padic_val_nat p b := begin apply int.coe_nat_inj, simp only [padic_val_rat_of_nat, nat.cast_mul], rw padic_val_rat.mul, norm_cast, exact cast_ne_zero.mpr ha, exact cast_ne_zero.mpr hb end protected lemma div_of_dvd (h : b ∣ a) : padic_val_nat p (a / b) = padic_val_nat p a - padic_val_nat p b := begin rcases eq_or_ne a 0 with rfl | ha, { simp }, obtain ⟨k, rfl⟩ := h, obtain ⟨hb, hk⟩ := mul_ne_zero_iff.mp ha, rw [mul_comm, k.mul_div_cancel hb.bot_lt, padic_val_nat.mul hk hb, nat.add_sub_cancel], exact hp end /-- Dividing out by a prime factor reduces the `padic_val_nat` by `1`. -/ protected lemma div (dvd : p ∣ b) : padic_val_nat p (b / p) = (padic_val_nat p b) - 1 := begin convert padic_val_nat.div_of_dvd dvd, rw padic_val_nat_self, exact hp end /-- A version of `padic_val_rat.pow` for `padic_val_nat`. -/ protected lemma pow (n : ℕ) (ha : a ≠ 0) : padic_val_nat p (a ^ n) = n * padic_val_nat p a := by simpa only [← @nat.cast_inj ℤ] with push_cast using padic_val_rat.pow (cast_ne_zero.mpr ha) @[simp] protected lemma prime_pow (n : ℕ) : padic_val_nat p (p ^ n) = n := by rwa [padic_val_nat.pow _ (fact.out p.prime).ne_zero, padic_val_nat_self, mul_one] protected lemma div_pow (dvd : p ^ a ∣ b) : padic_val_nat p (b / p ^ a) = (padic_val_nat p b) - a := begin convert padic_val_nat.div_of_dvd dvd, rw padic_val_nat.prime_pow, exact hp end end padic_val_nat section padic_val_nat variables {p : ℕ} lemma dvd_of_one_le_padic_val_nat {n : ℕ} (hp : 1 ≤ padic_val_nat p n) : p ∣ n := begin by_contra h, rw padic_val_nat.eq_zero_of_not_dvd h at hp, exact lt_irrefl 0 (lt_of_lt_of_le zero_lt_one hp) end lemma pow_padic_val_nat_dvd {n : ℕ} : p ^ padic_val_nat p n ∣ n := begin rcases n.eq_zero_or_pos with rfl | hn, { simp }, rcases eq_or_ne p 1 with rfl | hp, { simp }, rw [multiplicity.pow_dvd_iff_le_multiplicity, padic_val_nat_def']; assumption end lemma pow_succ_padic_val_nat_not_dvd {n : ℕ} [hp : fact p.prime] (hn : 0 < n) : ¬ p ^ (padic_val_nat p n + 1) ∣ n := begin rw multiplicity.pow_dvd_iff_le_multiplicity, rw padic_val_nat_def hn, { rw [nat.cast_add, part_enat.coe_get], simp only [nat.cast_one, not_le], exact part_enat.lt_add_one (ne_top_iff_finite.mpr (finite_nat_iff.mpr ⟨(fact.elim hp).ne_one, hn⟩)), }, { apply_instance } end lemma padic_val_nat_dvd_iff (n : ℕ) [hp : fact p.prime] (a : ℕ) : p ^ n ∣ a ↔ a = 0 ∨ n ≤ padic_val_nat p a := begin split, { rw [pow_dvd_iff_le_multiplicity, padic_val_nat], split_ifs, { rw part_enat.coe_le_iff, exact λ hn, or.inr (hn _) }, { simp only [true_and, not_lt, ne.def, not_false_iff, le_zero_iff, hp.out.ne_one] at h, exact λ hn, or.inl h } }, { rintro (rfl|h), { exact dvd_zero (p ^ n) }, { exact dvd_trans (pow_dvd_pow p h) pow_padic_val_nat_dvd } } end lemma padic_val_nat_primes {q : ℕ} [hp : fact p.prime] [hq : fact q.prime] (neq : p ≠ q) : padic_val_nat p q = 0 := @padic_val_nat.eq_zero_of_not_dvd p q $ (not_congr (iff.symm (prime_dvd_prime_iff_eq hp.1 hq.1))).mp neq protected lemma padic_val_nat.div' [hp : fact p.prime] : ∀ {m : ℕ} (cpm : coprime p m) {b : ℕ} (dvd : m ∣ b), padic_val_nat p (b / m) = padic_val_nat p b | 0 := λ cpm b dvd, by { rw zero_dvd_iff at dvd, rw [dvd, nat.zero_div] } | (n + 1) := λ cpm b dvd, begin rcases dvd with ⟨c, rfl⟩, rw [mul_div_right c (nat.succ_pos _)],by_cases hc : c = 0, { rw [hc, mul_zero] }, { rw padic_val_nat.mul, { suffices : ¬ p ∣ (n + 1), { rw [padic_val_nat.eq_zero_of_not_dvd this, zero_add] }, contrapose! cpm, exact hp.1.dvd_iff_not_coprime.mp cpm }, { exact nat.succ_ne_zero _ }, { exact hc } } end open_locale big_operators lemma range_pow_padic_val_nat_subset_divisors {n : ℕ} (hn : n ≠ 0) : (finset.range (padic_val_nat p n + 1)).image (pow p) ⊆ n.divisors := begin intros t ht, simp only [exists_prop, finset.mem_image, finset.mem_range] at ht, obtain ⟨k, hk, rfl⟩ := ht, rw nat.mem_divisors, exact ⟨(pow_dvd_pow p $ by linarith).trans pow_padic_val_nat_dvd, hn⟩ end lemma range_pow_padic_val_nat_subset_divisors' {n : ℕ} [hp : fact p.prime] : (finset.range (padic_val_nat p n)).image (λ t, p ^ (t + 1)) ⊆ n.divisors.erase 1 := begin rcases eq_or_ne n 0 with rfl | hn, { simp }, intros t ht, simp only [exists_prop, finset.mem_image, finset.mem_range] at ht, obtain ⟨k, hk, rfl⟩ := ht, rw [finset.mem_erase, nat.mem_divisors], refine ⟨_, (pow_dvd_pow p $ succ_le_iff.2 hk).trans pow_padic_val_nat_dvd, hn⟩, exact (nat.one_lt_pow _ _ k.succ_pos hp.out.one_lt).ne' end end padic_val_nat section padic_val_int variables {p : ℕ} [hp : fact p.prime] include hp lemma padic_val_int_dvd_iff (n : ℕ) (a : ℤ) : (p : ℤ) ^ n ∣ a ↔ a = 0 ∨ n ≤ padic_val_int p a := by rw [padic_val_int, ← int.nat_abs_eq_zero, ← padic_val_nat_dvd_iff, ← int.coe_nat_dvd_left, int.coe_nat_pow] lemma padic_val_int_dvd (a : ℤ) : (p : ℤ) ^ padic_val_int p a ∣ a := begin rw padic_val_int_dvd_iff, exact or.inr le_rfl end lemma padic_val_int_self : padic_val_int p p = 1 := padic_val_int.self hp.out.one_lt lemma padic_val_int.mul {a b : ℤ} (ha : a ≠ 0) (hb : b ≠ 0) : padic_val_int p (a * b) = padic_val_int p a + padic_val_int p b := begin simp_rw padic_val_int, rw [int.nat_abs_mul, padic_val_nat.mul]; rwa int.nat_abs_ne_zero end lemma padic_val_int_mul_eq_succ (a : ℤ) (ha : a ≠ 0) : padic_val_int p (a * p) = (padic_val_int p a) + 1 := begin rw padic_val_int.mul ha (int.coe_nat_ne_zero.mpr hp.out.ne_zero), simp only [eq_self_iff_true, padic_val_int.of_nat, padic_val_nat_self], exact hp end end padic_val_int
f41f701c9a0913692d86774997af3cd70eb5584d
e0f9ba56b7fedc16ef8697f6caeef5898b435143
/src/group_theory/congruence.lean
d9ce4305b40bcc82a1399b52d283a23bf14e92c5
[ "Apache-2.0" ]
permissive
anrddh/mathlib
6a374da53c7e3a35cb0298b0cd67824efef362b4
a4266a01d2dcb10de19369307c986d038c7bb6a6
refs/heads/master
1,656,710,827,909
1,589,560,456,000
1,589,560,456,000
264,271,800
0
0
Apache-2.0
1,589,568,062,000
1,589,568,061,000
null
UTF-8
Lean
false
false
42,254
lean
/- Copyright (c) 2019 Amelia Livingston. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Amelia Livingston -/ import data.setoid import algebra.pi_instances /-! # Congruence relations This file defines congruence relations: equivalence relations that preserve a binary operation, which in this case is multiplication or addition. The principal definition is a `structure` extending a `setoid` (an equivalence relation), and the inductive definition of the smallest congruence relation containing a binary relation is also given (see `con_gen`). The file also proves basic properties of the quotient of a type by a congruence relation, and the complete lattice of congruence relations on a type. We then establish an order-preserving bijection between the set of congruence relations containing a congruence relation `c` and the set of congruence relations on the quotient by `c`. The second half of the file concerns congruence relations on monoids, in which case the quotient by the congruence relation is also a monoid. There are results about the universal property of quotients of monoids, and the isomorphism theorems for monoids. ## Implementation notes The inductive definition of a congruence relation could be a nested inductive type, defined using the equivalence closure of a binary relation `eqv_gen`, but the recursor generated does not work. A nested inductive definition could conceivably shorten proofs, because they would allow invocation of the corresponding lemmas about `eqv_gen`. The lemmas `refl`, `symm` and `trans` are not tagged with `@[refl]`, `@[symm]`, and `@[trans]` respectively as these tags do not work on a structure coerced to a binary relation. There is a coercion from elements of a type to the element's equivalence class under a congruence relation. A congruence relation on a monoid `M` can be thought of as a submonoid of `M × M` for which membership is an equivalence relation, but whilst this fact is established in the file, it is not used, since this perspective adds more layers of definitional unfolding. ## Tags congruence, congruence relation, quotient, quotient by congruence relation, monoid, quotient monoid, isomorphism theorems -/ variables (M : Type*) {N : Type*} {P : Type*} set_option old_structure_cmd true open function setoid /-- A congruence relation on a type with an addition is an equivalence relation which preserves addition. -/ structure add_con [has_add M] extends setoid M := (add' : ∀ {w x y z}, r w x → r y z → r (w + y) (x + z)) /-- A congruence relation on a type with a multiplication is an equivalence relation which preserves multiplication. -/ @[to_additive add_con] structure con [has_mul M] extends setoid M := (mul' : ∀ {w x y z}, r w x → r y z → r (w * y) (x * z)) variables {M} /-- The inductively defined smallest additive congruence relation containing a given binary relation. -/ inductive add_con_gen.rel [has_add M] (r : M → M → Prop) : M → M → Prop | of : Π x y, r x y → add_con_gen.rel x y | refl : Π x, add_con_gen.rel x x | symm : Π x y, add_con_gen.rel x y → add_con_gen.rel y x | trans : Π x y z, add_con_gen.rel x y → add_con_gen.rel y z → add_con_gen.rel x z | add : Π w x y z, add_con_gen.rel w x → add_con_gen.rel y z → add_con_gen.rel (w + y) (x + z) /-- The inductively defined smallest multiplicative congruence relation containing a given binary relation. -/ @[to_additive add_con_gen.rel] inductive con_gen.rel [has_mul M] (r : M → M → Prop) : M → M → Prop | of : Π x y, r x y → con_gen.rel x y | refl : Π x, con_gen.rel x x | symm : Π x y, con_gen.rel x y → con_gen.rel y x | trans : Π x y z, con_gen.rel x y → con_gen.rel y z → con_gen.rel x z | mul : Π w x y z, con_gen.rel w x → con_gen.rel y z → con_gen.rel (w * y) (x * z) /-- The inductively defined smallest multiplicative congruence relation containing a given binary relation. -/ @[to_additive add_con_gen "The inductively defined smallest additive congruence relation containing a given binary relation."] def con_gen [has_mul M] (r : M → M → Prop) : con M := ⟨con_gen.rel r, ⟨con_gen.rel.refl, con_gen.rel.symm, con_gen.rel.trans⟩, con_gen.rel.mul⟩ namespace con section variables [has_mul M] [has_mul N] [has_mul P] (c : con M) @[to_additive] instance : inhabited (con M) := ⟨con_gen empty_relation⟩ /-- A coercion from a congruence relation to its underlying binary relation. -/ @[to_additive "A coercion from an additive congruence relation to its underlying binary relation."] instance : has_coe_to_fun (con M) := ⟨_, λ c, λ x y, c.r x y⟩ /-- Congruence relations are reflexive. -/ @[to_additive "Additive congruence relations are reflexive."] protected lemma refl (x) : c x x := c.2.1 x /-- Congruence relations are symmetric. -/ @[to_additive "Additive congruence relations are symmetric."] protected lemma symm : ∀ {x y}, c x y → c y x := λ _ _ h, c.2.2.1 h /-- Congruence relations are transitive. -/ @[to_additive "Additive congruence relations are transitive."] protected lemma trans : ∀ {x y z}, c x y → c y z → c x z := λ _ _ _ h, c.2.2.2 h /-- Multiplicative congruence relations preserve multiplication. -/ @[to_additive "Additive congruence relations preserve addition."] protected lemma mul : ∀ {w x y z}, c w x → c y z → c (w * y) (x * z) := λ _ _ _ _ h1 h2, c.3 h1 h2 /-- Given a type `M` with a multiplication, a congruence relation `c` on `M`, and elements of `M` `x, y`, `(x, y) ∈ M × M` iff `x` is related to `y` by `c`. -/ @[to_additive "Given a type `M` with an addition, `x, y ∈ M`, and an additive congruence relation `c` on `M`, `(x, y) ∈ M × M` iff `x` is related to `y` by `c`."] instance : has_mem (M × M) (con M) := ⟨λ x c, c x.1 x.2⟩ variables {c} /-- The map sending a congruence relation to its underlying binary relation is injective. -/ @[to_additive "The map sending an additive congruence relation to its underlying binary relation is injective."] lemma ext' {c d : con M} (H : c.r = d.r) : c = d := by cases c; cases d; simpa using H /-- Extensionality rule for congruence relations. -/ @[ext, to_additive "Extensionality rule for additive congruence relations."] lemma ext {c d : con M} (H : ∀ x y, c x y ↔ d x y) : c = d := ext' $ by ext; apply H attribute [ext] add_con.ext /-- The map sending a congruence relation to its underlying equivalence relation is injective. -/ @[to_additive "The map sending an additive congruence relation to its underlying equivalence relation is injective."] lemma to_setoid_inj {c d : con M} (H : c.to_setoid = d.to_setoid) : c = d := ext $ ext_iff.1 H /-- Iff version of extensionality rule for congruence relations. -/ @[to_additive "Iff version of extensionality rule for additive congruence relations."] lemma ext_iff {c d : con M} : (∀ x y, c x y ↔ d x y) ↔ c = d := ⟨ext, λ h _ _, h ▸ iff.rfl⟩ /-- Two congruence relations are equal iff their underlying binary relations are equal. -/ @[to_additive "Two additive congruence relations are equal iff their underlying binary relations are equal."] lemma ext'_iff {c d : con M} : c.r = d.r ↔ c = d := ⟨ext', λ h, h ▸ rfl⟩ /-- The kernel of a multiplication-preserving function as a congruence relation. -/ @[to_additive "The kernel of an addition-preserving function as an additive congruence relation."] def mul_ker (f : M → P) (h : ∀ x y, f (x * y) = f x * f y) : con M := { r := λ x y, f x = f y, iseqv := ⟨λ _, rfl, λ _ _, eq.symm, λ _ _ _, eq.trans⟩, mul' := λ _ _ _ _ h1 h2, by rw [h, h1, h2, h] } /-- Given types with multiplications `M, N`, the product of two congruence relations `c` on `M` and `d` on `N`: `(x₁, x₂), (y₁, y₂) ∈ M × N` are related by `c.prod d` iff `x₁` is related to `y₁` by `c` and `x₂` is related to `y₂` by `d`. -/ @[to_additive prod "Given types with additions `M, N`, the product of two congruence relations `c` on `M` and `d` on `N`: `(x₁, x₂), (y₁, y₂) ∈ M × N` are related by `c.prod d` iff `x₁` is related to `y₁` by `c` and `x₂` is related to `y₂` by `d`."] protected def prod (c : con M) (d : con N) : con (M × N) := { mul' := λ _ _ _ _ h1 h2, ⟨c.mul h1.1 h2.1, d.mul h1.2 h2.2⟩, ..c.to_setoid.prod d.to_setoid } /-- The product of an indexed collection of congruence relations. -/ @[to_additive "The product of an indexed collection of additive congruence relations."] def pi {ι : Type*} {f : ι → Type*} [Π i, has_mul (f i)] (C : Π i, con (f i)) : con (Π i, f i) := { mul' := λ _ _ _ _ h1 h2 i, (C i).mul (h1 i) (h2 i), ..@pi_setoid _ _ $ λ i, (C i).to_setoid } variables (c) @[simp, to_additive] lemma coe_eq : c.to_setoid.r = c := rfl -- Quotients /-- Defining the quotient by a congruence relation of a type with a multiplication. -/ @[to_additive "Defining the quotient by an additive congruence relation of a type with an addition."] protected def quotient := quotient $ c.to_setoid /-- Coercion from a type with a multiplication to its quotient by a congruence relation. See Note [use has_coe_t]. -/ @[to_additive "Coercion from a type with an addition to its quotient by an additive congruence relation", priority 0] instance : has_coe_t M c.quotient := ⟨@quotient.mk _ c.to_setoid⟩ /-- The quotient of a type with decidable equality by a congruence relation also has decidable equality. -/ @[to_additive "The quotient of a type with decidable equality by an additive congruence relation also has decidable equality."] instance [d : ∀ a b, decidable (c a b)] : decidable_eq c.quotient := @quotient.decidable_eq M c.to_setoid d /-- The function on the quotient by a congruence relation `c` induced by a function that is constant on `c`'s equivalence classes. -/ @[elab_as_eliminator, to_additive "The function on the quotient by a congruence relation `c` induced by a function that is constant on `c`'s equivalence classes."] protected def lift_on {β} {c : con M} (q : c.quotient) (f : M → β) (h : ∀ a b, c a b → f a = f b) : β := quotient.lift_on' q f h variables {c} /-- The inductive principle used to prove propositions about the elements of a quotient by a congruence relation. -/ @[elab_as_eliminator, to_additive "The inductive principle used to prove propositions about the elements of a quotient by an additive congruence relation."] protected lemma induction_on {C : c.quotient → Prop} (q : c.quotient) (H : ∀ x : M, C x) : C q := quotient.induction_on' q H /-- A version of `con.induction_on` for predicates which take two arguments. -/ @[elab_as_eliminator, to_additive "A version of `add_con.induction_on` for predicates which take two arguments."] protected lemma induction_on₂ {d : con N} {C : c.quotient → d.quotient → Prop} (p : c.quotient) (q : d.quotient) (H : ∀ (x : M) (y : N), C x y) : C p q := quotient.induction_on₂' p q H variables (c) /-- Two elements are related by a congruence relation `c` iff they are represented by the same element of the quotient by `c`. -/ @[simp, to_additive "Two elements are related by an additive congruence relation `c` iff they are represented by the same element of the quotient by `c`."] protected lemma eq {a b : M} : (a : c.quotient) = b ↔ c a b := quotient.eq' /-- The multiplication induced on the quotient by a congruence relation on a type with a multiplication. -/ @[to_additive "The addition induced on the quotient by an additive congruence relation on a type with a addition."] instance has_mul : has_mul c.quotient := ⟨λ x y, quotient.lift_on₂' x y (λ w z, ((w * z : M) : c.quotient)) $ λ _ _ _ _ h1 h2, c.eq.2 $ c.mul h1 h2⟩ /-- The kernel of the quotient map induced by a congruence relation `c` equals `c`. -/ @[simp, to_additive "The kernel of the quotient map induced by an additive congruence relation `c` equals `c`."] lemma mul_ker_mk_eq : mul_ker (coe : M → c.quotient) (λ x y, rfl) = c := ext $ λ x y, quotient.eq' variables {c} /-- The coercion to the quotient of a congruence relation commutes with multiplication (by definition). -/ @[simp, to_additive "The coercion to the quotient of an additive congruence relation commutes with addition (by definition)."] lemma coe_mul (x y : M) : (↑(x * y) : c.quotient) = ↑x * ↑y := rfl /-- Definition of the function on the quotient by a congruence relation `c` induced by a function that is constant on `c`'s equivalence classes. -/ @[simp, to_additive "Definition of the function on the quotient by an additive congruence relation `c` induced by a function that is constant on `c`'s equivalence classes."] protected lemma lift_on_beta {β} (c : con M) (f : M → β) (h : ∀ a b, c a b → f a = f b) (x : M) : con.lift_on (x : c.quotient) f h = f x := rfl /-- Makes an isomorphism of quotients by two congruence relations, given that the relations are equal. -/ @[to_additive "Makes an additive isomorphism of quotients by two additive congruence relations, given that the relations are equal."] protected def congr {c d : con M} (h : c = d) : c.quotient ≃* d.quotient := { map_mul' := λ x y, by rcases x; rcases y; refl, ..quotient.congr (equiv.refl M) $ by apply ext_iff.2 h } -- The complete lattice of congruence relations on a type /-- For congruence relations `c, d` on a type `M` with a multiplication, `c ≤ d` iff `∀ x y ∈ M`, `x` is related to `y` by `d` if `x` is related to `y` by `c`. -/ @[to_additive "For additive congruence relations `c, d` on a type `M` with an addition, `c ≤ d` iff `∀ x y ∈ M`, `x` is related to `y` by `d` if `x` is related to `y` by `c`."] instance : has_le (con M) := ⟨λ c d, c.to_setoid ≤ d.to_setoid⟩ /-- Definition of `≤` for congruence relations. -/ @[to_additive "Definition of `≤` for additive congruence relations."] theorem le_def {c d : con M} : c ≤ d ↔ ∀ {x y}, c x y → d x y := iff.rfl /-- The infimum of a set of congruence relations on a given type with a multiplication. -/ @[to_additive "The infimum of a set of additive congruence relations on a given type with an addition."] instance : has_Inf (con M) := ⟨λ S, ⟨λ x y, ∀ c : con M, c ∈ S → c x y, ⟨λ x c hc, c.refl x, λ _ _ h c hc, c.symm $ h c hc, λ _ _ _ h1 h2 c hc, c.trans (h1 c hc) $ h2 c hc⟩, λ _ _ _ _ h1 h2 c hc, c.mul (h1 c hc) $ h2 c hc⟩⟩ /-- The infimum of a set of congruence relations is the same as the infimum of the set's image under the map to the underlying equivalence relation. -/ @[to_additive "The infimum of a set of additive congruence relations is the same as the infimum of the set's image under the map to the underlying equivalence relation."] lemma Inf_to_setoid (S : set (con M)) : (Inf S).to_setoid = Inf (to_setoid '' S) := setoid.ext' $ λ x y, ⟨λ h r ⟨c, hS, hr⟩, by rw ←hr; exact h c hS, λ h c hS, h c.to_setoid ⟨c, hS, rfl⟩⟩ /-- The infimum of a set of congruence relations is the same as the infimum of the set's image under the map to the underlying binary relation. -/ @[to_additive "The infimum of a set of additive congruence relations is the same as the infimum of the set's image under the map to the underlying binary relation."] lemma Inf_def (S : set (con M)) : (Inf S).r = Inf (r '' S) := by { ext, simp only [Inf_image, infi_apply, infi_Prop_eq], refl } @[to_additive] instance : partial_order (con M) := { le := (≤), lt := λ c d, c ≤ d ∧ ¬d ≤ c, le_refl := λ c _ _, id, le_trans := λ c1 c2 c3 h1 h2 x y h, h2 $ h1 h, lt_iff_le_not_le := λ _ _, iff.rfl, le_antisymm := λ c d hc hd, ext $ λ x y, ⟨λ h, hc h, λ h, hd h⟩ } /-- The complete lattice of congruence relations on a given type with a multiplication. -/ @[to_additive "The complete lattice of additive congruence relations on a given type with an addition."] instance : complete_lattice (con M) := { inf := λ c d, ⟨(c.to_setoid ⊓ d.to_setoid).1, (c.to_setoid ⊓ d.to_setoid).2, λ _ _ _ _ h1 h2, ⟨c.mul h1.1 h2.1, d.mul h1.2 h2.2⟩⟩, inf_le_left := λ _ _ _ _ h, h.1, inf_le_right := λ _ _ _ _ h, h.2, le_inf := λ _ _ _ hb hc _ _ h, ⟨hb h, hc h⟩, top := { mul' := by tauto, ..setoid.complete_lattice.top}, le_top := λ _ _ _ h, trivial, bot := { mul' := λ _ _ _ _ h1 h2, h1 ▸ h2 ▸ rfl, ..setoid.complete_lattice.bot}, bot_le := λ c x y h, h ▸ c.refl x, .. complete_lattice_of_Inf (con M) $ assume s, ⟨λ r hr x y h, (h : ∀ r ∈ s, (r : con M) x y) r hr, λ r hr x y h r' hr', hr hr' h⟩ } /-- The infimum of two congruence relations equals the infimum of the underlying binary operations. -/ @[to_additive "The infimum of two additive congruence relations equals the infimum of the underlying binary operations."] lemma inf_def {c d : con M} : (c ⊓ d).r = c.r ⊓ d.r := rfl /-- Definition of the infimum of two congruence relations. -/ @[to_additive "Definition of the infimum of two additive congruence relations."] theorem inf_iff_and {c d : con M} {x y} : (c ⊓ d) x y ↔ c x y ∧ d x y := iff.rfl /-- The inductively defined smallest congruence relation containing a binary relation `r` equals the infimum of the set of congruence relations containing `r`. -/ @[to_additive add_con_gen_eq "The inductively defined smallest additive congruence relation containing a binary relation `r` equals the infimum of the set of additive congruence relations containing `r`."] theorem con_gen_eq (r : M → M → Prop) : con_gen r = Inf {s : con M | ∀ x y, r x y → s x y} := le_antisymm (λ x y H, con_gen.rel.rec_on H (λ _ _ h _ hs, hs _ _ h) (con.refl _) (λ _ _ _, con.symm _) (λ _ _ _ _ _, con.trans _) $ λ w x y z _ _ h1 h2 c hc, c.mul (h1 c hc) $ h2 c hc) (Inf_le (λ _ _, con_gen.rel.of _ _)) /-- The smallest congruence relation containing a binary relation `r` is contained in any congruence relation containing `r`. -/ @[to_additive add_con_gen_le "The smallest additive congruence relation containing a binary relation `r` is contained in any additive congruence relation containing `r`."] theorem con_gen_le {r : M → M → Prop} {c : con M} (h : ∀ x y, r x y → c.r x y) : con_gen r ≤ c := by rw con_gen_eq; exact Inf_le h /-- Given binary relations `r, s` with `r` contained in `s`, the smallest congruence relation containing `s` contains the smallest congruence relation containing `r`. -/ @[to_additive add_con_gen_mono "Given binary relations `r, s` with `r` contained in `s`, the smallest additive congruence relation containing `s` contains the smallest additive congruence relation containing `r`."] theorem con_gen_mono {r s : M → M → Prop} (h : ∀ x y, r x y → s x y) : con_gen r ≤ con_gen s := con_gen_le $ λ x y hr, con_gen.rel.of _ _ $ h x y hr /-- Congruence relations equal the smallest congruence relation in which they are contained. -/ @[simp, to_additive add_con_gen_of_add_con "Additive congruence relations equal the smallest additive congruence relation in which they are contained."] lemma con_gen_of_con (c : con M) : con_gen c = c := le_antisymm (by rw con_gen_eq; exact Inf_le (λ _ _, id)) con_gen.rel.of /-- The map sending a binary relation to the smallest congruence relation in which it is contained is idempotent. -/ @[simp, to_additive add_con_gen_idem "The map sending a binary relation to the smallest additive congruence relation in which it is contained is idempotent."] lemma con_gen_idem (r : M → M → Prop) : con_gen (con_gen r) = con_gen r := con_gen_of_con _ /-- The supremum of congruence relations `c, d` equals the smallest congruence relation containing the binary relation '`x` is related to `y` by `c` or `d`'. -/ @[to_additive sup_eq_add_con_gen "The supremum of additive congruence relations `c, d` equals the smallest additive congruence relation containing the binary relation '`x` is related to `y` by `c` or `d`'."] lemma sup_eq_con_gen (c d : con M) : c ⊔ d = con_gen (λ x y, c x y ∨ d x y) := begin rw con_gen_eq, apply congr_arg Inf, simp only [le_def, or_imp_distrib, ← forall_and_distrib] end /-- The supremum of two congruence relations equals the smallest congruence relation containing the supremum of the underlying binary operations. -/ @[to_additive "The supremum of two additive congruence relations equals the smallest additive congruence relation containing the supremum of the underlying binary operations."] lemma sup_def {c d : con M} : c ⊔ d = con_gen (c.r ⊔ d.r) := by rw sup_eq_con_gen; refl /-- The supremum of a set of congruence relations `S` equals the smallest congruence relation containing the binary relation 'there exists `c ∈ S` such that `x` is related to `y` by `c`'. -/ @[to_additive Sup_eq_add_con_gen "The supremum of a set of additive congruence relations S equals the smallest additive congruence relation containing the binary relation 'there exists `c ∈ S` such that `x` is related to `y` by `c`'."] lemma Sup_eq_con_gen (S : set (con M)) : Sup S = con_gen (λ x y, ∃ c : con M, c ∈ S ∧ c x y) := begin rw con_gen_eq, apply congr_arg Inf, ext, exact ⟨λ h _ _ ⟨r, hr⟩, h hr.1 hr.2, λ h r hS _ _ hr, h _ _ ⟨r, hS, hr⟩⟩, end /-- The supremum of a set of congruence relations is the same as the smallest congruence relation containing the supremum of the set's image under the map to the underlying binary relation. -/ @[to_additive "The supremum of a set of additive congruence relations is the same as the smallest additive congruence relation containing the supremum of the set's image under the map to the underlying binary relation."] lemma Sup_def {S : set (con M)} : Sup S = con_gen (Sup (r '' S)) := begin rw Sup_eq_con_gen, congr, ext x y, erw [Sup_image, supr_apply, supr_apply, supr_Prop_eq], simp only [Sup_image, supr_Prop_eq, supr_apply, supr_Prop_eq, exists_prop], refl, end variables (M) /-- There is a Galois insertion of congruence relations on a type with a multiplication `M` into binary relations on `M`. -/ @[to_additive "There is a Galois insertion of additive congruence relations on a type with an addition `M` into binary relations on `M`."] protected def gi : @galois_insertion (M → M → Prop) (con M) _ _ con_gen r := { choice := λ r h, con_gen r, gc := λ r c, ⟨λ H _ _ h, H $ con_gen.rel.of _ _ h, λ H, con_gen_of_con c ▸ con_gen_mono H⟩, le_l_u := λ x, (con_gen_of_con x).symm ▸ le_refl x, choice_eq := λ _ _, rfl } variables {M} (c) /-- Given a function `f`, the smallest congruence relation containing the binary relation on `f`'s image defined by '`x ≈ y` iff the elements of `f⁻¹(x)` are related to the elements of `f⁻¹(y)` by a congruence relation `c`.' -/ @[to_additive "Given a function `f`, the smallest additive congruence relation containing the binary relation on `f`'s image defined by '`x ≈ y` iff the elements of `f⁻¹(x)` are related to the elements of `f⁻¹(y)` by an additive congruence relation `c`.'"] def map_gen (f : M → N) : con N := con_gen $ λ x y, ∃ a b, f a = x ∧ f b = y ∧ c a b /-- Given a surjective multiplicative-preserving function `f` whose kernel is contained in a congruence relation `c`, the congruence relation on `f`'s codomain defined by '`x ≈ y` iff the elements of `f⁻¹(x)` are related to the elements of `f⁻¹(y)` by `c`.' -/ @[to_additive "Given a surjective addition-preserving function `f` whose kernel is contained in an additive congruence relation `c`, the additive congruence relation on `f`'s codomain defined by '`x ≈ y` iff the elements of `f⁻¹(x)` are related to the elements of `f⁻¹(y)` by `c`.'"] def map_of_surjective (f : M → N) (H : ∀ x y, f (x * y) = f x * f y) (h : mul_ker f H ≤ c) (hf : surjective f) : con N := { mul' := λ w x y z ⟨a, b, hw, hx, h1⟩ ⟨p, q, hy, hz, h2⟩, ⟨a * p, b * q, by rw [H, hw, hy], by rw [H, hx, hz], c.mul h1 h2⟩, ..c.to_setoid.map_of_surjective f h hf } /-- A specialization of 'the smallest congruence relation containing a congruence relation `c` equals `c`'. -/ @[to_additive "A specialization of 'the smallest additive congruence relation containing an additive congruence relation `c` equals `c`'."] lemma map_of_surjective_eq_map_gen {c : con M} {f : M → N} (H : ∀ x y, f (x * y) = f x * f y) (h : mul_ker f H ≤ c) (hf : surjective f) : c.map_gen f = c.map_of_surjective f H h hf := by rw ←con_gen_of_con (c.map_of_surjective f H h hf); refl /-- Given types with multiplications `M, N` and a congruence relation `c` on `N`, a multiplication-preserving map `f : M → N` induces a congruence relation on `f`'s domain defined by '`x ≈ y` iff `f(x)` is related to `f(y)` by `c`.' -/ @[to_additive "Given types with additions `M, N` and an additive congruence relation `c` on `N`, an addition-preserving map `f : M → N` induces an additive congruence relation on `f`'s domain defined by '`x ≈ y` iff `f(x)` is related to `f(y)` by `c`.' "] def comap (f : M → N) (H : ∀ x y, f (x * y) = f x * f y) (c : con N) : con M := { mul' := λ w x y z h1 h2, show c (f (w * y)) (f (x * z)), by rw [H, H]; exact c.mul h1 h2, ..c.to_setoid.comap f } section open quotient /-- Given a congruence relation `c` on a type `M` with a multiplication, the order-preserving bijection between the set of congruence relations containing `c` and the congruence relations on the quotient of `M` by `c`. -/ @[to_additive "Given an additive congruence relation `c` on a type `M` with an addition, the order-preserving bijection between the set of additive congruence relations containing `c` and the additive congruence relations on the quotient of `M` by `c`."] def correspondence : ((≤) : {d // c ≤ d} → {d // c ≤ d} → Prop) ≃o ((≤) : con c.quotient → con c.quotient → Prop) := { to_fun := λ d, d.1.map_of_surjective coe _ (by rw mul_ker_mk_eq; exact d.2) $ @exists_rep _ c.to_setoid, inv_fun := λ d, ⟨comap (coe : M → c.quotient) (λ x y, rfl) d, λ _ _ h, show d _ _, by rw c.eq.2 h; exact d.refl _ ⟩, left_inv := λ d, subtype.ext.2 $ ext $ λ _ _, ⟨λ h, let ⟨a, b, hx, hy, H⟩ := h in d.1.trans (d.1.symm $ d.2 $ c.eq.1 hx) $ d.1.trans H $ d.2 $ c.eq.1 hy, λ h, ⟨_, _, rfl, rfl, h⟩⟩, right_inv := λ d, let Hm : mul_ker (coe : M → c.quotient) (λ x y, rfl) ≤ comap (coe : M → c.quotient) (λ x y, rfl) d := λ x y h, show d _ _, by rw mul_ker_mk_eq at h; exact c.eq.2 h ▸ d.refl _ in ext $ λ x y, ⟨λ h, let ⟨a, b, hx, hy, H⟩ := h in hx ▸ hy ▸ H, con.induction_on₂ x y $ λ w z h, ⟨w, z, rfl, rfl, h⟩⟩, ord' := λ s t, ⟨λ h _ _ hs, let ⟨a, b, hx, hy, Hs⟩ := hs in ⟨a, b, hx, hy, h Hs⟩, λ h _ _ hs, let ⟨a, b, hx, hy, ht⟩ := h ⟨_, _, rfl, rfl, hs⟩ in t.1.trans (t.1.symm $ t.2 $ eq_rel.1 hx) $ t.1.trans ht $ t.2 $ eq_rel.1 hy⟩ } end end -- Monoids variables {M} [monoid M] [monoid N] [monoid P] (c : con M) /-- The quotient of a monoid by a congruence relation is a monoid. -/ @[to_additive add_monoid "The quotient of an `add_monoid` by an additive congruence relation is an `add_monoid`."] instance monoid : monoid c.quotient := { one := ((1 : M) : c.quotient), mul := (*), mul_assoc := λ x y z, quotient.induction_on₃' x y z $ λ _ _ _, congr_arg coe $ mul_assoc _ _ _, mul_one := λ x, quotient.induction_on' x $ λ _, congr_arg coe $ mul_one _, one_mul := λ x, quotient.induction_on' x $ λ _, congr_arg coe $ one_mul _ } /-- The quotient of a `comm_monoid` by a congruence relation is a `comm_monoid`. -/ @[to_additive add_comm_monoid "The quotient of an `add_comm_monoid` by an additive congruence relation is an `add_comm_monoid`."] instance comm_monoid {α : Type*} [comm_monoid α] (c : con α) : comm_monoid c.quotient := { mul_comm := λ x y, con.induction_on₂ x y $ λ w z, by rw [←coe_mul, ←coe_mul, mul_comm], ..c.monoid} variables {c} /-- The 1 of the quotient of a monoid by a congruence relation is the equivalence class of the monoid's 1. -/ @[simp, to_additive "The 0 of the quotient of an `add_monoid` by an additive congruence relation is the equivalence class of the `add_monoid`'s 0."] lemma coe_one : ((1 : M) : c.quotient) = 1 := rfl variables (M c) /-- The submonoid of `M × M` defined by a congruence relation on a monoid `M`. -/ @[to_additive add_submonoid "The `add_submonoid` of `M × M` defined by an additive congruence relation on an `add_monoid` `M`."] protected def submonoid : submonoid (M × M) := { carrier := { x | c x.1 x.2 }, one_mem' := c.iseqv.1 1, mul_mem' := λ _ _, c.mul } variables {M c} /-- The congruence relation on a monoid `M` from a submonoid of `M × M` for which membership is an equivalence relation. -/ @[to_additive of_add_submonoid "The additive congruence relation on an `add_monoid` `M` from an `add_submonoid` of `M × M` for which membership is an equivalence relation."] def of_submonoid (N : submonoid (M × M)) (H : equivalence (λ x y, (x, y) ∈ N)) : con M := { r := λ x y, (x, y) ∈ N, iseqv := H, mul' := λ _ _ _ _, N.mul_mem } /-- Coercion from a congruence relation `c` on a monoid `M` to the submonoid of `M × M` whose elements are `(x, y)` such that `x` is related to `y` by `c`. -/ @[to_additive to_add_submonoid "Coercion from a congruence relation `c` on an `add_monoid` `M` to the `add_submonoid` of `M × M` whose elements are `(x, y)` such that `x` is related to `y` by `c`."] instance to_submonoid : has_coe (con M) (submonoid (M × M)) := ⟨λ c, c.submonoid M⟩ @[to_additive] lemma mem_coe {c : con M} {x y} : (x, y) ∈ (↑c : submonoid (M × M)) ↔ (x, y) ∈ c := iff.rfl @[to_additive to_add_submonoid_inj] theorem to_submonoid_inj (c d : con M) (H : (c : submonoid (M × M)) = d) : c = d := ext $ λ x y, show (x, y) ∈ (c : submonoid (M × M)) ↔ (x, y) ∈ ↑d, by rw H @[to_additive] lemma le_iff {c d : con M} : c ≤ d ↔ (c : submonoid (M × M)) ≤ d := ⟨λ h x H, h H, λ h x y hc, h $ show (x, y) ∈ c, from hc⟩ /-- The kernel of a monoid homomorphism as a congruence relation. -/ @[to_additive "The kernel of an `add_monoid` homomorphism as an additive congruence relation."] def ker (f : M →* P) : con M := mul_ker f f.3 /-- The definition of the congruence relation defined by a monoid homomorphism's kernel. -/ @[to_additive "The definition of the additive congruence relation defined by an `add_monoid` homomorphism's kernel."] lemma ker_rel (f : M →* P) {x y} : ker f x y ↔ f x = f y := iff.rfl /-- There exists an element of the quotient of a monoid by a congruence relation (namely 1). -/ @[to_additive "There exists an element of the quotient of an `add_monoid` by a congruence relation (namely 0)."] instance quotient.inhabited : inhabited c.quotient := ⟨((1 : M) : c.quotient)⟩ variables (c) /-- The natural homomorphism from a monoid to its quotient by a congruence relation. -/ @[to_additive "The natural homomorphism from an `add_monoid` to its quotient by an additive congruence relation."] def mk' : M →* c.quotient := ⟨coe, rfl, λ _ _, rfl⟩ variables (x y : M) /-- The kernel of the natural homomorphism from a monoid to its quotient by a congruence relation `c` equals `c`. -/ @[simp, to_additive "The kernel of the natural homomorphism from an `add_monoid` to its quotient by an additive congruence relation `c` equals `c`."] lemma mk'_ker : ker c.mk' = c := ext $ λ _ _, c.eq variables {c} /-- The natural homomorphism from a monoid to its quotient by a congruence relation is surjective. -/ @[to_additive "The natural homomorphism from an `add_monoid` to its quotient by a congruence relation is surjective."] lemma mk'_surjective : surjective c.mk' := λ x, by rcases x; exact ⟨x, rfl⟩ @[simp, to_additive] lemma comp_mk'_apply (g : c.quotient →* P) {x} : g.comp c.mk' x = g x := rfl /-- The elements related to `x ∈ M`, `M` a monoid, by the kernel of a monoid homomorphism are those in the preimage of `f(x)` under `f`. -/ @[to_additive "The elements related to `x ∈ M`, `M` an `add_monoid`, by the kernel of an `add_monoid` homomorphism are those in the preimage of `f(x)` under `f`. "] lemma ker_apply_eq_preimage {f : M →* P} (x) : (ker f) x = f ⁻¹' {f x} := set.ext $ λ x, ⟨λ h, set.mem_preimage.2 $ set.mem_singleton_iff.2 h.symm, λ h, (set.mem_singleton_iff.1 $ set.mem_preimage.1 h).symm⟩ /-- Given a monoid homomorphism `f : N → M` and a congruence relation `c` on `M`, the congruence relation induced on `N` by `f` equals the kernel of `c`'s quotient homomorphism composed with `f`. -/ @[to_additive "Given an `add_monoid` homomorphism `f : N → M` and an additive congruence relation `c` on `M`, the additive congruence relation induced on `N` by `f` equals the kernel of `c`'s quotient homomorphism composed with `f`."] lemma comap_eq {f : N →* M} : comap f f.map_mul c = ker (c.mk'.comp f) := ext $ λ x y, show c _ _ ↔ c.mk' _ = c.mk' _, by rw ←c.eq; refl variables (c) (f : M →* P) /-- The homomorphism on the quotient of a monoid by a congruence relation `c` induced by a homomorphism constant on `c`'s equivalence classes. -/ @[to_additive "The homomorphism on the quotient of an `add_monoid` by an additive congruence relation `c` induced by a homomorphism constant on `c`'s equivalence classes."] def lift (H : c ≤ ker f) : c.quotient →* P := { to_fun := λ x, con.lift_on x f $ λ _ _ h, H h, map_one' := by rw ←f.map_one; refl, map_mul' := λ x y, con.induction_on₂ x y $ λ m n, f.map_mul m n ▸ rfl } variables {c f} /-- The diagram describing the universal property for quotients of monoids commutes. -/ @[simp, to_additive "The diagram describing the universal property for quotients of `add_monoid`s commutes."] lemma lift_mk' (H : c ≤ ker f) (x) : c.lift f H (c.mk' x) = f x := rfl /-- The diagram describing the universal property for quotients of monoids commutes. -/ @[simp, to_additive "The diagram describing the universal property for quotients of `add_monoid`s commutes."] lemma lift_coe (H : c ≤ ker f) (x : M) : c.lift f H x = f x := rfl /-- The diagram describing the universal property for quotients of monoids commutes. -/ @[simp, to_additive "The diagram describing the universal property for quotients of `add_monoid`s commutes."] theorem lift_comp_mk' (H : c ≤ ker f) : (c.lift f H).comp c.mk' = f := by ext; refl /-- Given a homomorphism `f` from the quotient of a monoid by a congruence relation, `f` equals the homomorphism on the quotient induced by `f` composed with the natural map from the monoid to the quotient. -/ @[simp, to_additive "Given a homomorphism `f` from the quotient of an `add_monoid` by an additive congruence relation, `f` equals the homomorphism on the quotient induced by `f` composed with the natural map from the `add_monoid` to the quotient."] lemma lift_apply_mk' (f : c.quotient →* P) : c.lift (f.comp c.mk') (λ x y h, show f ↑x = f ↑y, by rw c.eq.2 h) = f := by ext; rcases x; refl /-- Homomorphisms on the quotient of a monoid by a congruence relation are equal if they are equal on elements that are coercions from the monoid. -/ @[to_additive "Homomorphisms on the quotient of an `add_monoid` by an additive congruence relation are equal if they are equal on elements that are coercions from the `add_monoid`."] lemma lift_funext (f g : c.quotient →* P) (h : ∀ a : M, f a = g a) : f = g := begin rw [←lift_apply_mk' f, ←lift_apply_mk' g], congr' 1, exact monoid_hom.ext_iff.2 h, end /-- The uniqueness part of the universal property for quotients of monoids. -/ @[to_additive "The uniqueness part of the universal property for quotients of `add_monoid`s."] theorem lift_unique (H : c ≤ ker f) (g : c.quotient →* P) (Hg : g.comp c.mk' = f) : g = c.lift f H := lift_funext g (c.lift f H) $ λ x, by rw [lift_coe H, ←comp_mk'_apply, Hg] /-- Given a congruence relation `c` on a monoid and a homomorphism `f` constant on `c`'s equivalence classes, `f` has the same image as the homomorphism that `f` induces on the quotient. -/ @[to_additive "Given an additive congruence relation `c` on an `add_monoid` and a homomorphism `f` constant on `c`'s equivalence classes, `f` has the same image as the homomorphism that `f` induces on the quotient."] theorem lift_range (H : c ≤ ker f) : (c.lift f H).mrange = f.mrange := submonoid.ext $ λ x, ⟨λ ⟨y, hy⟩, by revert hy; rcases y; exact λ hy, ⟨y, hy.1, by rw [hy.2.symm, ←lift_coe H]; refl⟩, λ ⟨y, hy⟩, ⟨↑y, hy.1, by rw ←hy.2; refl⟩⟩ /-- Surjective monoid homomorphisms constant on a congruence relation `c`'s equivalence classes induce a surjective homomorphism on `c`'s quotient. -/ @[to_additive "Surjective `add_monoid` homomorphisms constant on an additive congruence relation `c`'s equivalence classes induce a surjective homomorphism on `c`'s quotient."] lemma lift_surjective_of_surjective (h : c ≤ ker f) (hf : surjective f) : surjective (c.lift f h) := λ y, exists.elim (hf y) $ λ w hw, ⟨w, (lift_mk' h w).symm ▸ hw⟩ variables (c f) /-- Given a monoid homomorphism `f` from `M` to `P`, the kernel of `f` is the unique congruence relation on `M` whose induced map from the quotient of `M` to `P` is injective. -/ @[to_additive "Given an `add_monoid` homomorphism `f` from `M` to `P`, the kernel of `f` is the unique additive congruence relation on `M` whose induced map from the quotient of `M` to `P` is injective."] lemma ker_eq_lift_of_injective (H : c ≤ ker f) (h : injective (c.lift f H)) : ker f = c := to_setoid_inj $ ker_eq_lift_of_injective f H h variables {c} /-- The homomorphism induced on the quotient of a monoid by the kernel of a monoid homomorphism. -/ @[to_additive "The homomorphism induced on the quotient of an `add_monoid` by the kernel of an `add_monoid` homomorphism."] def ker_lift : (ker f).quotient →* P := (ker f).lift f $ λ _ _, id variables {f} /-- The diagram described by the universal property for quotients of monoids, when the congruence relation is the kernel of the homomorphism, commutes. -/ @[simp, to_additive "The diagram described by the universal property for quotients of `add_monoid`s, when the additive congruence relation is the kernel of the homomorphism, commutes."] lemma ker_lift_mk (x : M) : ker_lift f x = f x := rfl /-- Given a monoid homomorphism `f`, the induced homomorphism on the quotient by `f`'s kernel has the same image as `f`. -/ @[simp, to_additive "Given an `add_monoid` homomorphism `f`, the induced homomorphism on the quotient by `f`'s kernel has the same image as `f`."] lemma ker_lift_range_eq : (ker_lift f).mrange = f.mrange := lift_range $ λ _ _, id /-- A monoid homomorphism `f` induces an injective homomorphism on the quotient by `f`'s kernel. -/ @[to_additive "An `add_monoid` homomorphism `f` induces an injective homomorphism on the quotient by `f`'s kernel."] lemma injective_ker_lift (f : M →* P) : injective (ker_lift f) := λ x y, quotient.induction_on₂' x y $ λ _ _, (ker f).eq.2 /-- Given congruence relations `c, d` on a monoid such that `d` contains `c`, `d`'s quotient map induces a homomorphism from the quotient by `c` to the quotient by `d`. -/ @[to_additive "Given additive congruence relations `c, d` on an `add_monoid` such that `d` contains `c`, `d`'s quotient map induces a homomorphism from the quotient by `c` to the quotient by `d`."] def map (c d : con M) (h : c ≤ d) : c.quotient →* d.quotient := c.lift d.mk' $ λ x y hc, show (ker d.mk') x y, from (mk'_ker d).symm ▸ h hc /-- Given congruence relations `c, d` on a monoid such that `d` contains `c`, the definition of the homomorphism from the quotient by `c` to the quotient by `d` induced by `d`'s quotient map. -/ @[to_additive "Given additive congruence relations `c, d` on an `add_monoid` such that `d` contains `c`, the definition of the homomorphism from the quotient by `c` to the quotient by `d` induced by `d`'s quotient map."] lemma map_apply {c d : con M} (h : c ≤ d) (x) : c.map d h x = c.lift d.mk' (λ x y hc, d.eq.2 $ h hc) x := rfl variables (c) /-- The first isomorphism theorem for monoids. -/ @[to_additive "The first isomorphism theorem for `add_monoid`s."] noncomputable def quotient_ker_equiv_range (f : M →* P) : (ker f).quotient ≃* f.mrange := { map_mul' := monoid_hom.map_mul _, ..@equiv.of_bijective _ _ ((@mul_equiv.to_monoid_hom (ker_lift f).mrange _ _ _ $ mul_equiv.submonoid_congr ker_lift_range_eq).comp (ker_lift f).range_restrict) $ bijective_comp (equiv.bijective _) ⟨λ x y h, injective_ker_lift f $ by rcases x; rcases y; injections, λ ⟨w, z, hzm, hz⟩, ⟨z, by rcases hz; rcases _x; refl⟩⟩ } /-- The first isomorphism theorem for monoids in the case of a surjective homomorphism. -/ @[to_additive "The first isomorphism theorem for `add_monoid`s in the case of a surjective homomorphism."] noncomputable def quotient_ker_equiv_of_surjective (f : M →* P) (hf : surjective f) : (ker f).quotient ≃* P := { map_mul' := monoid_hom.map_mul _, ..@equiv.of_bijective _ _ (ker_lift f) ⟨injective_ker_lift f, lift_surjective_of_surjective (le_refl _) hf⟩ } /-- The second isomorphism theorem for monoids. -/ @[to_additive "The second isomorphism theorem for `add_monoid`s."] noncomputable def comap_quotient_equiv (f : N →* M) : (comap f f.map_mul c).quotient ≃* (c.mk'.comp f).mrange := (con.congr comap_eq).trans $ quotient_ker_equiv_range $ c.mk'.comp f /-- The third isomorphism theorem for monoids. -/ @[to_additive "The third isomorphism theorem for `add_monoid`s."] def quotient_quotient_equiv_quotient (c d : con M) (h : c ≤ d) : (ker (c.map d h)).quotient ≃* d.quotient := { map_mul' := λ x y, con.induction_on₂ x y $ λ w z, con.induction_on₂ w z $ λ a b, show _ = d.mk' a * d.mk' b, by rw ←d.mk'.map_mul; refl, ..quotient_quotient_equiv_quotient _ _ h } end con
e56aea093a579b58bd09926737ab5a6048e915b1
f618aea02cb4104ad34ecf3b9713065cc0d06103
/src/data/int/basic.lean
0d9cf4d4c7a81e5937b1b8f6593c5fd6f5f2c4af
[ "Apache-2.0" ]
permissive
joehendrix/mathlib
84b6603f6be88a7e4d62f5b1b0cbb523bb82b9a5
c15eab34ad754f9ecd738525cb8b5a870e834ddc
refs/heads/master
1,589,606,591,630
1,555,946,393,000
1,555,946,393,000
182,813,854
0
0
null
1,555,946,309,000
1,555,946,308,000
null
UTF-8
Lean
false
false
49,555
lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad The integers, with addition, multiplication, and subtraction. -/ import data.nat.basic data.list.basic algebra.char_zero algebra.order_functions open nat namespace int instance : inhabited ℤ := ⟨int.zero⟩ @[simp] lemma default_eq_zero : default ℤ = 0 := rfl meta instance : has_to_format ℤ := ⟨λ z, int.rec_on z (λ k, ↑k) (λ k, "-("++↑k++"+1)")⟩ meta instance : has_reflect ℤ := by tactic.mk_has_reflect_instance attribute [simp] int.coe_nat_add int.coe_nat_mul int.coe_nat_zero int.coe_nat_one int.coe_nat_succ @[simp] theorem add_def {a b : ℤ} : int.add a b = a + b := rfl @[simp] theorem mul_def {a b : ℤ} : int.mul a b = a * b := rfl @[simp] theorem coe_nat_mul_neg_succ (m n : ℕ) : (m : ℤ) * -[1+ n] = -(m * succ n) := rfl @[simp] theorem neg_succ_mul_coe_nat (m n : ℕ) : -[1+ m] * n = -(succ m * n) := rfl @[simp] theorem neg_succ_mul_neg_succ (m n : ℕ) : -[1+ m] * -[1+ n] = succ m * succ n := rfl @[simp] theorem coe_nat_le {m n : ℕ} : (↑m : ℤ) ≤ ↑n ↔ m ≤ n := coe_nat_le_coe_nat_iff m n @[simp] theorem coe_nat_lt {m n : ℕ} : (↑m : ℤ) < ↑n ↔ m < n := coe_nat_lt_coe_nat_iff m n @[simp] theorem coe_nat_inj' {m n : ℕ} : (↑m : ℤ) = ↑n ↔ m = n := int.coe_nat_eq_coe_nat_iff m n @[simp] theorem coe_nat_pos {n : ℕ} : (0 : ℤ) < n ↔ 0 < n := by rw [← int.coe_nat_zero, coe_nat_lt] @[simp] theorem coe_nat_eq_zero {n : ℕ} : (n : ℤ) = 0 ↔ n = 0 := by rw [← int.coe_nat_zero, coe_nat_inj'] @[simp] theorem coe_nat_ne_zero {n : ℕ} : (n : ℤ) ≠ 0 ↔ n ≠ 0 := not_congr coe_nat_eq_zero lemma coe_nat_nonneg (n : ℕ) : 0 ≤ (n : ℤ) := coe_nat_le.2 (nat.zero_le _) lemma coe_nat_ne_zero_iff_pos {n : ℕ} : (n : ℤ) ≠ 0 ↔ 0 < n := ⟨λ h, nat.pos_of_ne_zero (coe_nat_ne_zero.1 h), λ h, (ne_of_lt (coe_nat_lt.2 h)).symm⟩ lemma coe_nat_succ_pos (n : ℕ) : 0 < (n.succ : ℤ) := int.coe_nat_pos.2 (succ_pos n) @[simp] theorem coe_nat_abs (n : ℕ) : abs (n : ℤ) = n := abs_of_nonneg (coe_nat_nonneg n) /- succ and pred -/ /-- Immediate successor of an integer: `succ n = n + 1` -/ def succ (a : ℤ) := a + 1 /-- Immediate predecessor of an integer: `pred n = n - 1` -/ def pred (a : ℤ) := a - 1 theorem nat_succ_eq_int_succ (n : ℕ) : (nat.succ n : ℤ) = int.succ n := rfl theorem pred_succ (a : ℤ) : pred (succ a) = a := add_sub_cancel _ _ theorem succ_pred (a : ℤ) : succ (pred a) = a := sub_add_cancel _ _ theorem neg_succ (a : ℤ) : -succ a = pred (-a) := neg_add _ _ theorem succ_neg_succ (a : ℤ) : succ (-succ a) = -a := by rw [neg_succ, succ_pred] theorem neg_pred (a : ℤ) : -pred a = succ (-a) := by rw [eq_neg_of_eq_neg (neg_succ (-a)).symm, neg_neg] theorem pred_neg_pred (a : ℤ) : pred (-pred a) = -a := by rw [neg_pred, pred_succ] theorem pred_nat_succ (n : ℕ) : pred (nat.succ n) = n := pred_succ n theorem neg_nat_succ (n : ℕ) : -(nat.succ n : ℤ) = pred (-n) := neg_succ n theorem succ_neg_nat_succ (n : ℕ) : succ (-nat.succ n) = -n := succ_neg_succ n theorem lt_succ_self (a : ℤ) : a < succ a := lt_add_of_pos_right _ zero_lt_one theorem pred_self_lt (a : ℤ) : pred a < a := sub_lt_self _ zero_lt_one theorem add_one_le_iff {a b : ℤ} : a + 1 ≤ b ↔ a < b := iff.rfl theorem lt_add_one_iff {a b : ℤ} : a < b + 1 ↔ a ≤ b := @add_le_add_iff_right _ _ a b 1 theorem sub_one_lt_iff {a b : ℤ} : a - 1 < b ↔ a ≤ b := sub_lt_iff_lt_add.trans lt_add_one_iff theorem le_sub_one_iff {a b : ℤ} : a ≤ b - 1 ↔ a < b := le_sub_iff_add_le @[elab_as_eliminator] protected lemma induction_on {p : ℤ → Prop} (i : ℤ) (hz : p 0) (hp : ∀i : ℕ, p i → p (i + 1)) (hn : ∀i : ℕ, p (-i) → p (-i - 1)) : p i := begin induction i, { induction i, { exact hz }, { exact hp _ i_ih } }, { have : ∀n:ℕ, p (- n), { intro n, induction n, { simp [hz] }, { have := hn _ n_ih, simpa } }, exact this (i + 1) } end protected def induction_on' {C : ℤ → Sort*} (z : ℤ) (b : ℤ) : C b → (∀ k ≥ b, C k → C (k + 1)) → (∀ k ≤ b, C k → C (k - 1)) → C z := λ H0 Hs Hp, begin rw ←sub_add_cancel z b, induction (z - b), { induction a with n ih, { rwa [of_nat_zero, zero_add] }, rw [of_nat_succ, add_assoc, add_comm 1 b, ←add_assoc], exact Hs _ (le_add_of_nonneg_left (of_nat_nonneg _)) ih }, { induction a with n ih, { rw [neg_succ_of_nat_eq, ←of_nat_eq_coe, of_nat_zero, zero_add, neg_add_eq_sub], exact Hp _ (le_refl _) H0 }, { rw [neg_succ_of_nat_coe', nat.succ_eq_add_one, ←neg_succ_of_nat_coe, sub_add_eq_add_sub], exact Hp _ (le_of_lt (add_lt_of_neg_of_le (neg_succ_lt_zero _) (le_refl _))) ih } } end /- nat abs -/ attribute [simp] nat_abs nat_abs_of_nat nat_abs_zero nat_abs_one theorem nat_abs_add_le (a b : ℤ) : nat_abs (a + b) ≤ nat_abs a + nat_abs b := begin have : ∀ (a b : ℕ), nat_abs (sub_nat_nat a (nat.succ b)) ≤ nat.succ (a + b), { refine (λ a b : ℕ, sub_nat_nat_elim a b.succ (λ m n i, n = b.succ → nat_abs i ≤ (m + b).succ) _ _ rfl); intros i n e, { subst e, rw [add_comm _ i, add_assoc], exact nat.le_add_right i (b.succ + b).succ }, { apply succ_le_succ, rw [← succ_inj e, ← add_assoc, add_comm], apply nat.le_add_right } }, cases a; cases b with b b; simp [nat_abs, nat.succ_add]; try {refl}; [skip, rw add_comm a b]; apply this end theorem nat_abs_neg_of_nat (n : ℕ) : nat_abs (neg_of_nat n) = n := by cases n; refl theorem nat_abs_mul (a b : ℤ) : nat_abs (a * b) = (nat_abs a) * (nat_abs b) := by cases a; cases b; simp only [(*), int.mul, nat_abs_neg_of_nat, eq_self_iff_true, int.nat_abs] @[simp] lemma nat_abs_mul_self' (a : ℤ) : (nat_abs a * nat_abs a : ℤ) = a * a := by rw [← int.coe_nat_mul, nat_abs_mul_self] theorem neg_succ_of_nat_eq' (m : ℕ) : -[1+ m] = -m - 1 := by simp [neg_succ_of_nat_eq] lemma nat_abs_ne_zero_of_ne_zero {z : ℤ} (hz : z ≠ 0) : z.nat_abs ≠ 0 := λ h, hz $ int.eq_zero_of_nat_abs_eq_zero h /- / -/ @[simp] theorem of_nat_div (m n : ℕ) : of_nat (m / n) = (of_nat m) / (of_nat n) := rfl @[simp] theorem coe_nat_div (m n : ℕ) : ((m / n : ℕ) : ℤ) = m / n := rfl theorem neg_succ_of_nat_div (m : ℕ) {b : ℤ} (H : b > 0) : -[1+m] / b = -(m / b + 1) := match b, eq_succ_of_zero_lt H with ._, ⟨n, rfl⟩ := rfl end @[simp] protected theorem div_neg : ∀ (a b : ℤ), a / -b = -(a / b) | (m : ℕ) 0 := show of_nat (m / 0) = -(m / 0 : ℕ), by rw nat.div_zero; refl | (m : ℕ) (n+1:ℕ) := rfl | 0 -[1+ n] := rfl | (m+1:ℕ) -[1+ n] := (neg_neg _).symm | -[1+ m] 0 := rfl | -[1+ m] (n+1:ℕ) := rfl | -[1+ m] -[1+ n] := rfl theorem div_of_neg_of_pos {a b : ℤ} (Ha : a < 0) (Hb : b > 0) : a / b = -((-a - 1) / b + 1) := match a, b, eq_neg_succ_of_lt_zero Ha, eq_succ_of_zero_lt Hb with | ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩ := by change (- -[1+ m] : ℤ) with (m+1 : ℤ); rw add_sub_cancel; refl end protected theorem div_nonneg {a b : ℤ} (Ha : a ≥ 0) (Hb : b ≥ 0) : a / b ≥ 0 := match a, b, eq_coe_of_zero_le Ha, eq_coe_of_zero_le Hb with | ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩ := coe_zero_le _ end protected theorem div_nonpos {a b : ℤ} (Ha : a ≥ 0) (Hb : b ≤ 0) : a / b ≤ 0 := nonpos_of_neg_nonneg $ by rw [← int.div_neg]; exact int.div_nonneg Ha (neg_nonneg_of_nonpos Hb) theorem div_neg' {a b : ℤ} (Ha : a < 0) (Hb : b > 0) : a / b < 0 := match a, b, eq_neg_succ_of_lt_zero Ha, eq_succ_of_zero_lt Hb with | ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩ := neg_succ_lt_zero _ end @[simp] protected theorem zero_div : ∀ (b : ℤ), 0 / b = 0 | 0 := rfl | (n+1:ℕ) := rfl | -[1+ n] := rfl @[simp] protected theorem div_zero : ∀ (a : ℤ), a / 0 = 0 | 0 := rfl | (n+1:ℕ) := rfl | -[1+ n] := rfl @[simp] protected theorem div_one : ∀ (a : ℤ), a / 1 = a | 0 := rfl | (n+1:ℕ) := congr_arg of_nat (nat.div_one _) | -[1+ n] := congr_arg neg_succ_of_nat (nat.div_one _) theorem div_eq_zero_of_lt {a b : ℤ} (H1 : 0 ≤ a) (H2 : a < b) : a / b = 0 := match a, b, eq_coe_of_zero_le H1, eq_succ_of_zero_lt (lt_of_le_of_lt H1 H2), H2 with | ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩, H2 := congr_arg of_nat $ nat.div_eq_of_lt $ lt_of_coe_nat_lt_coe_nat H2 end theorem div_eq_zero_of_lt_abs {a b : ℤ} (H1 : 0 ≤ a) (H2 : a < abs b) : a / b = 0 := match b, abs b, abs_eq_nat_abs b, H2 with | (n : ℕ), ._, rfl, H2 := div_eq_zero_of_lt H1 H2 | -[1+ n], ._, rfl, H2 := neg_inj $ by rw [← int.div_neg]; exact div_eq_zero_of_lt H1 H2 end protected theorem add_mul_div_right (a b : ℤ) {c : ℤ} (H : c ≠ 0) : (a + b * c) / c = a / c + b := have ∀ {k n : ℕ} {a : ℤ}, (a + n * k.succ) / k.succ = a / k.succ + n, from λ k n a, match a with | (m : ℕ) := congr_arg of_nat $ nat.add_mul_div_right _ _ k.succ_pos | -[1+ m] := show ((n * k.succ:ℕ) - m.succ : ℤ) / k.succ = n - (m / k.succ + 1 : ℕ), begin cases lt_or_ge m (n*k.succ) with h h, { rw [← int.coe_nat_sub h, ← int.coe_nat_sub ((nat.div_lt_iff_lt_mul _ _ k.succ_pos).2 h)], apply congr_arg of_nat, rw [mul_comm, nat.mul_sub_div], rwa mul_comm }, { change (↑(n * nat.succ k) - (m + 1) : ℤ) / ↑(nat.succ k) = ↑n - ((m / nat.succ k : ℕ) + 1), rw [← sub_sub, ← sub_sub, ← neg_sub (m:ℤ), ← neg_sub _ (n:ℤ), ← int.coe_nat_sub h, ← int.coe_nat_sub ((nat.le_div_iff_mul_le _ _ k.succ_pos).2 h), ← neg_succ_of_nat_coe', ← neg_succ_of_nat_coe'], { apply congr_arg neg_succ_of_nat, rw [mul_comm, nat.sub_mul_div], rwa mul_comm } } end end, have ∀ {a b c : ℤ}, c > 0 → (a + b * c) / c = a / c + b, from λ a b c H, match c, eq_succ_of_zero_lt H, b with | ._, ⟨k, rfl⟩, (n : ℕ) := this | ._, ⟨k, rfl⟩, -[1+ n] := show (a - n.succ * k.succ) / k.succ = (a / k.succ) - n.succ, from eq_sub_of_add_eq $ by rw [← this, sub_add_cancel] end, match lt_trichotomy c 0 with | or.inl hlt := neg_inj $ by rw [← int.div_neg, neg_add, ← int.div_neg, ← neg_mul_neg]; apply this (neg_pos_of_neg hlt) | or.inr (or.inl heq) := absurd heq H | or.inr (or.inr hgt) := this hgt end protected theorem add_mul_div_left (a : ℤ) {b : ℤ} (c : ℤ) (H : b ≠ 0) : (a + b * c) / b = a / b + c := by rw [mul_comm, int.add_mul_div_right _ _ H] @[simp] protected theorem mul_div_cancel (a : ℤ) {b : ℤ} (H : b ≠ 0) : a * b / b = a := by have := int.add_mul_div_right 0 a H; rwa [zero_add, int.zero_div, zero_add] at this @[simp] protected theorem mul_div_cancel_left {a : ℤ} (b : ℤ) (H : a ≠ 0) : a * b / a = b := by rw [mul_comm, int.mul_div_cancel _ H] @[simp] protected theorem div_self {a : ℤ} (H : a ≠ 0) : a / a = 1 := by have := int.mul_div_cancel 1 H; rwa one_mul at this /- mod -/ theorem of_nat_mod (m n : nat) : (m % n : ℤ) = of_nat (m % n) := rfl @[simp] theorem coe_nat_mod (m n : ℕ) : (↑(m % n) : ℤ) = ↑m % ↑n := rfl theorem neg_succ_of_nat_mod (m : ℕ) {b : ℤ} (bpos : b > 0) : -[1+m] % b = b - 1 - m % b := by rw [sub_sub, add_comm]; exact match b, eq_succ_of_zero_lt bpos with ._, ⟨n, rfl⟩ := rfl end @[simp] theorem mod_neg : ∀ (a b : ℤ), a % -b = a % b | (m : ℕ) n := @congr_arg ℕ ℤ _ _ (λ i, ↑(m % i)) (nat_abs_neg _) | -[1+ m] n := @congr_arg ℕ ℤ _ _ (λ i, sub_nat_nat i (nat.succ (m % i))) (nat_abs_neg _) @[simp] theorem mod_abs (a b : ℤ) : a % (abs b) = a % b := abs_by_cases (λ i, a % i = a % b) rfl (mod_neg _ _) @[simp] theorem zero_mod (b : ℤ) : 0 % b = 0 := congr_arg of_nat $ nat.zero_mod _ @[simp] theorem mod_zero : ∀ (a : ℤ), a % 0 = a | (m : ℕ) := congr_arg of_nat $ nat.mod_zero _ | -[1+ m] := congr_arg neg_succ_of_nat $ nat.mod_zero _ @[simp] theorem mod_one : ∀ (a : ℤ), a % 1 = 0 | (m : ℕ) := congr_arg of_nat $ nat.mod_one _ | -[1+ m] := show (1 - (m % 1).succ : ℤ) = 0, by rw nat.mod_one; refl theorem mod_eq_of_lt {a b : ℤ} (H1 : 0 ≤ a) (H2 : a < b) : a % b = a := match a, b, eq_coe_of_zero_le H1, eq_coe_of_zero_le (le_trans H1 (le_of_lt H2)), H2 with | ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩, H2 := congr_arg of_nat $ nat.mod_eq_of_lt (lt_of_coe_nat_lt_coe_nat H2) end theorem mod_nonneg : ∀ (a : ℤ) {b : ℤ}, b ≠ 0 → a % b ≥ 0 | (m : ℕ) n H := coe_zero_le _ | -[1+ m] n H := sub_nonneg_of_le $ coe_nat_le_coe_nat_of_le $ nat.mod_lt _ (nat_abs_pos_of_ne_zero H) theorem mod_lt_of_pos (a : ℤ) {b : ℤ} (H : b > 0) : a % b < b := match a, b, eq_succ_of_zero_lt H with | (m : ℕ), ._, ⟨n, rfl⟩ := coe_nat_lt_coe_nat_of_lt (nat.mod_lt _ (nat.succ_pos _)) | -[1+ m], ._, ⟨n, rfl⟩ := sub_lt_self _ (coe_nat_lt_coe_nat_of_lt $ nat.succ_pos _) end theorem mod_lt (a : ℤ) {b : ℤ} (H : b ≠ 0) : a % b < abs b := by rw [← mod_abs]; exact mod_lt_of_pos _ (abs_pos_of_ne_zero H) theorem mod_add_div_aux (m n : ℕ) : (n - (m % n + 1) - (n * (m / n) + n) : ℤ) = -[1+ m] := begin rw [← sub_sub, neg_succ_of_nat_coe, sub_sub (n:ℤ)], apply eq_neg_of_eq_neg, rw [neg_sub, sub_sub_self, add_right_comm], exact @congr_arg ℕ ℤ _ _ (λi, (i + 1 : ℤ)) (nat.mod_add_div _ _).symm end theorem mod_add_div : ∀ (a b : ℤ), a % b + b * (a / b) = a | (m : ℕ) 0 := congr_arg of_nat (nat.mod_add_div _ _) | (m : ℕ) (n+1:ℕ) := congr_arg of_nat (nat.mod_add_div _ _) | 0 -[1+ n] := rfl | (m+1:ℕ) -[1+ n] := show (_ + -(n+1) * -((m + 1) / (n + 1) : ℕ) : ℤ) = _, by rw [neg_mul_neg]; exact congr_arg of_nat (nat.mod_add_div _ _) | -[1+ m] 0 := by rw [mod_zero, int.div_zero]; refl | -[1+ m] (n+1:ℕ) := mod_add_div_aux m n.succ | -[1+ m] -[1+ n] := mod_add_div_aux m n.succ theorem mod_def (a b : ℤ) : a % b = a - b * (a / b) := eq_sub_of_add_eq (mod_add_div _ _) @[simp] theorem add_mul_mod_self {a b c : ℤ} : (a + b * c) % c = a % c := if cz : c = 0 then by rw [cz, mul_zero, add_zero] else by rw [mod_def, mod_def, int.add_mul_div_right _ _ cz, mul_add, mul_comm, add_sub_add_right_eq_sub] @[simp] theorem add_mul_mod_self_left (a b c : ℤ) : (a + b * c) % b = a % b := by rw [mul_comm, add_mul_mod_self] @[simp] theorem add_mod_self {a b : ℤ} : (a + b) % b = a % b := by have := add_mul_mod_self_left a b 1; rwa mul_one at this @[simp] theorem add_mod_self_left {a b : ℤ} : (a + b) % a = b % a := by rw [add_comm, add_mod_self] @[simp] theorem mod_add_mod (m n k : ℤ) : (m % n + k) % n = (m + k) % n := by have := (add_mul_mod_self_left (m % n + k) n (m / n)).symm; rwa [add_right_comm, mod_add_div] at this @[simp] theorem add_mod_mod (m n k : ℤ) : (m + n % k) % k = (m + n) % k := by rw [add_comm, mod_add_mod, add_comm] theorem add_mod_eq_add_mod_right {m n k : ℤ} (i : ℤ) (H : m % n = k % n) : (m + i) % n = (k + i) % n := by rw [← mod_add_mod, ← mod_add_mod k, H] theorem add_mod_eq_add_mod_left {m n k : ℤ} (i : ℤ) (H : m % n = k % n) : (i + m) % n = (i + k) % n := by rw [add_comm, add_mod_eq_add_mod_right _ H, add_comm] theorem mod_add_cancel_right {m n k : ℤ} (i) : (m + i) % n = (k + i) % n ↔ m % n = k % n := ⟨λ H, by have := add_mod_eq_add_mod_right (-i) H; rwa [add_neg_cancel_right, add_neg_cancel_right] at this, add_mod_eq_add_mod_right _⟩ theorem mod_add_cancel_left {m n k i : ℤ} : (i + m) % n = (i + k) % n ↔ m % n = k % n := by rw [add_comm, add_comm i, mod_add_cancel_right] theorem mod_sub_cancel_right {m n k : ℤ} (i) : (m - i) % n = (k - i) % n ↔ m % n = k % n := mod_add_cancel_right _ theorem mod_eq_mod_iff_mod_sub_eq_zero {m n k : ℤ} : m % n = k % n ↔ (m - k) % n = 0 := (mod_sub_cancel_right k).symm.trans $ by simp @[simp] theorem mul_mod_left (a b : ℤ) : (a * b) % b = 0 := by rw [← zero_add (a * b), add_mul_mod_self, zero_mod] @[simp] theorem mul_mod_right (a b : ℤ) : (a * b) % a = 0 := by rw [mul_comm, mul_mod_left] @[simp] theorem mod_self {a : ℤ} : a % a = 0 := by have := mul_mod_left 1 a; rwa one_mul at this @[simp] lemma mod_mod (a b : ℤ) : a % b % b = a % b := by conv {to_rhs, rw [← mod_add_div a b, add_mul_mod_self_left]} /- properties of / and % -/ @[simp] theorem mul_div_mul_of_pos {a : ℤ} (b c : ℤ) (H : a > 0) : a * b / (a * c) = b / c := suffices ∀ (m k : ℕ) (b : ℤ), (m.succ * b / (m.succ * k) : ℤ) = b / k, from match a, eq_succ_of_zero_lt H, c, eq_coe_or_neg c with | ._, ⟨m, rfl⟩, ._, ⟨k, or.inl rfl⟩ := this _ _ _ | ._, ⟨m, rfl⟩, ._, ⟨k, or.inr rfl⟩ := by rw [← neg_mul_eq_mul_neg, int.div_neg, int.div_neg]; apply congr_arg has_neg.neg; apply this end, λ m k b, match b, k with | (n : ℕ), k := congr_arg of_nat (nat.mul_div_mul _ _ m.succ_pos) | -[1+ n], 0 := by rw [int.coe_nat_zero, mul_zero, int.div_zero, int.div_zero] | -[1+ n], k+1 := congr_arg neg_succ_of_nat $ show (m.succ * n + m) / (m.succ * k.succ) = n / k.succ, begin apply nat.div_eq_of_lt_le, { refine le_trans _ (nat.le_add_right _ _), rw [← nat.mul_div_mul _ _ m.succ_pos], apply nat.div_mul_le_self }, { change m.succ * n.succ ≤ _, rw [mul_left_comm], apply nat.mul_le_mul_left, apply (nat.div_lt_iff_lt_mul _ _ k.succ_pos).1, apply nat.lt_succ_self } end end @[simp] theorem mul_div_mul_of_pos_left (a : ℤ) {b : ℤ} (c : ℤ) (H : b > 0) : a * b / (c * b) = a / c := by rw [mul_comm, mul_comm c, mul_div_mul_of_pos _ _ H] @[simp] theorem mul_mod_mul_of_pos {a : ℤ} (b c : ℤ) (H : a > 0) : a * b % (a * c) = a * (b % c) := by rw [mod_def, mod_def, mul_div_mul_of_pos _ _ H, mul_sub_left_distrib, mul_assoc] theorem lt_div_add_one_mul_self (a : ℤ) {b : ℤ} (H : b > 0) : a < (a / b + 1) * b := by rw [add_mul, one_mul, mul_comm]; apply lt_add_of_sub_left_lt; rw [← mod_def]; apply mod_lt_of_pos _ H theorem abs_div_le_abs : ∀ (a b : ℤ), abs (a / b) ≤ abs a := suffices ∀ (a : ℤ) (n : ℕ), abs (a / n) ≤ abs a, from λ a b, match b, eq_coe_or_neg b with | ._, ⟨n, or.inl rfl⟩ := this _ _ | ._, ⟨n, or.inr rfl⟩ := by rw [int.div_neg, abs_neg]; apply this end, λ a n, by rw [abs_eq_nat_abs, abs_eq_nat_abs]; exact coe_nat_le_coe_nat_of_le (match a, n with | (m : ℕ), n := nat.div_le_self _ _ | -[1+ m], 0 := nat.zero_le _ | -[1+ m], n+1 := nat.succ_le_succ (nat.div_le_self _ _) end) theorem div_le_self {a : ℤ} (b : ℤ) (Ha : a ≥ 0) : a / b ≤ a := by have := le_trans (le_abs_self _) (abs_div_le_abs a b); rwa [abs_of_nonneg Ha] at this theorem mul_div_cancel_of_mod_eq_zero {a b : ℤ} (H : a % b = 0) : b * (a / b) = a := by have := mod_add_div a b; rwa [H, zero_add] at this theorem div_mul_cancel_of_mod_eq_zero {a b : ℤ} (H : a % b = 0) : a / b * b = a := by rw [mul_comm, mul_div_cancel_of_mod_eq_zero H] lemma mod_two_eq_zero_or_one (n : ℤ) : n % 2 = 0 ∨ n % 2 = 1 := have h : n % 2 < 2 := abs_of_nonneg (show (2 : ℤ) ≥ 0, from dec_trivial) ▸ int.mod_lt _ dec_trivial, have h₁ : n % 2 ≥ 0 := int.mod_nonneg _ dec_trivial, match (n % 2), h, h₁ with | (0 : ℕ) := λ _ _, or.inl rfl | (1 : ℕ) := λ _ _, or.inr rfl | (k + 2 : ℕ) := λ h _, absurd h dec_trivial | -[1+ a] := λ _ h₁, absurd h₁ dec_trivial end /- dvd -/ theorem coe_nat_dvd {m n : ℕ} : (↑m : ℤ) ∣ ↑n ↔ m ∣ n := ⟨λ ⟨a, ae⟩, m.eq_zero_or_pos.elim (λm0, by simp [m0] at ae; simp [ae, m0]) (λm0l, by { cases eq_coe_of_zero_le (@nonneg_of_mul_nonneg_left ℤ _ m a (by simp [ae.symm]) (by simpa using m0l)) with k e, subst a, exact ⟨k, int.coe_nat_inj ae⟩ }), λ ⟨k, e⟩, dvd.intro k $ by rw [e, int.coe_nat_mul]⟩ theorem coe_nat_dvd_left {n : ℕ} {z : ℤ} : (↑n : ℤ) ∣ z ↔ n ∣ z.nat_abs := by rcases nat_abs_eq z with eq | eq; rw eq; simp [coe_nat_dvd] theorem coe_nat_dvd_right {n : ℕ} {z : ℤ} : z ∣ (↑n : ℤ) ↔ z.nat_abs ∣ n := by rcases nat_abs_eq z with eq | eq; rw eq; simp [coe_nat_dvd] theorem dvd_antisymm {a b : ℤ} (H1 : a ≥ 0) (H2 : b ≥ 0) : a ∣ b → b ∣ a → a = b := begin rw [← abs_of_nonneg H1, ← abs_of_nonneg H2, abs_eq_nat_abs, abs_eq_nat_abs], rw [coe_nat_dvd, coe_nat_dvd, coe_nat_inj'], apply nat.dvd_antisymm end theorem dvd_of_mod_eq_zero {a b : ℤ} (H : b % a = 0) : a ∣ b := ⟨b / a, (mul_div_cancel_of_mod_eq_zero H).symm⟩ theorem mod_eq_zero_of_dvd : ∀ {a b : ℤ}, a ∣ b → b % a = 0 | a ._ ⟨c, rfl⟩ := mul_mod_right _ _ theorem dvd_iff_mod_eq_zero (a b : ℤ) : a ∣ b ↔ b % a = 0 := ⟨mod_eq_zero_of_dvd, dvd_of_mod_eq_zero⟩ theorem nat_abs_dvd {a b : ℤ} : (a.nat_abs : ℤ) ∣ b ↔ a ∣ b := (nat_abs_eq a).elim (λ e, by rw ← e) (λ e, by rw [← neg_dvd_iff_dvd, ← e]) theorem dvd_nat_abs {a b : ℤ} : a ∣ b.nat_abs ↔ a ∣ b := (nat_abs_eq b).elim (λ e, by rw ← e) (λ e, by rw [← dvd_neg_iff_dvd, ← e]) instance decidable_dvd : @decidable_rel ℤ (∣) := assume a n, decidable_of_decidable_of_iff (by apply_instance) (dvd_iff_mod_eq_zero _ _).symm protected theorem div_mul_cancel {a b : ℤ} (H : b ∣ a) : a / b * b = a := div_mul_cancel_of_mod_eq_zero (mod_eq_zero_of_dvd H) protected theorem mul_div_cancel' {a b : ℤ} (H : a ∣ b) : a * (b / a) = b := by rw [mul_comm, int.div_mul_cancel H] protected theorem mul_div_assoc (a : ℤ) : ∀ {b c : ℤ}, c ∣ b → (a * b) / c = a * (b / c) | ._ c ⟨d, rfl⟩ := if cz : c = 0 then by simp [cz] else by rw [mul_left_comm, int.mul_div_cancel_left _ cz, int.mul_div_cancel_left _ cz] theorem div_dvd_div : ∀ {a b c : ℤ} (H1 : a ∣ b) (H2 : b ∣ c), b / a ∣ c / a | a ._ ._ ⟨b, rfl⟩ ⟨c, rfl⟩ := if az : a = 0 then by simp [az] else by rw [int.mul_div_cancel_left _ az, mul_assoc, int.mul_div_cancel_left _ az]; apply dvd_mul_right protected theorem eq_mul_of_div_eq_right {a b c : ℤ} (H1 : b ∣ a) (H2 : a / b = c) : a = b * c := by rw [← H2, int.mul_div_cancel' H1] protected theorem div_eq_of_eq_mul_right {a b c : ℤ} (H1 : b ≠ 0) (H2 : a = b * c) : a / b = c := by rw [H2, int.mul_div_cancel_left _ H1] protected theorem div_eq_iff_eq_mul_right {a b c : ℤ} (H : b ≠ 0) (H' : b ∣ a) : a / b = c ↔ a = b * c := ⟨int.eq_mul_of_div_eq_right H', int.div_eq_of_eq_mul_right H⟩ protected theorem div_eq_iff_eq_mul_left {a b c : ℤ} (H : b ≠ 0) (H' : b ∣ a) : a / b = c ↔ a = c * b := by rw mul_comm; exact int.div_eq_iff_eq_mul_right H H' protected theorem eq_mul_of_div_eq_left {a b c : ℤ} (H1 : b ∣ a) (H2 : a / b = c) : a = c * b := by rw [mul_comm, int.eq_mul_of_div_eq_right H1 H2] protected theorem div_eq_of_eq_mul_left {a b c : ℤ} (H1 : b ≠ 0) (H2 : a = c * b) : a / b = c := int.div_eq_of_eq_mul_right H1 (by rw [mul_comm, H2]) theorem neg_div_of_dvd : ∀ {a b : ℤ} (H : b ∣ a), -a / b = -(a / b) | ._ b ⟨c, rfl⟩ := if bz : b = 0 then by simp [bz] else by rw [neg_mul_eq_mul_neg, int.mul_div_cancel_left _ bz, int.mul_div_cancel_left _ bz] lemma add_div_of_dvd {a b c : ℤ} : c ∣ a → c ∣ b → (a + b) / c = a / c + b / c := begin intros h1 h2, by_cases h3 : c = 0, { rw [h3, zero_dvd_iff] at *, rw [h1, h2, h3], refl }, { apply eq_of_mul_eq_mul_right h3, rw add_mul, repeat {rw [int.div_mul_cancel]}; try {apply dvd_add}; assumption } end theorem div_sign : ∀ a b, a / sign b = a * sign b | a (n+1:ℕ) := by unfold sign; simp | a 0 := by simp [sign] | a -[1+ n] := by simp [sign] @[simp] theorem sign_mul : ∀ a b, sign (a * b) = sign a * sign b | a 0 := by simp | 0 b := by simp | (m+1:ℕ) (n+1:ℕ) := rfl | (m+1:ℕ) -[1+ n] := rfl | -[1+ m] (n+1:ℕ) := rfl | -[1+ m] -[1+ n] := rfl protected theorem sign_eq_div_abs (a : ℤ) : sign a = a / (abs a) := if az : a = 0 then by simp [az] else (int.div_eq_of_eq_mul_left (mt eq_zero_of_abs_eq_zero az) (sign_mul_abs _).symm).symm theorem mul_sign : ∀ (i : ℤ), i * sign i = nat_abs i | (n+1:ℕ) := mul_one _ | 0 := mul_zero _ | -[1+ n] := mul_neg_one _ theorem le_of_dvd {a b : ℤ} (bpos : b > 0) (H : a ∣ b) : a ≤ b := match a, b, eq_succ_of_zero_lt bpos, H with | (m : ℕ), ._, ⟨n, rfl⟩, H := coe_nat_le_coe_nat_of_le $ nat.le_of_dvd n.succ_pos $ coe_nat_dvd.1 H | -[1+ m], ._, ⟨n, rfl⟩, _ := le_trans (le_of_lt $ neg_succ_lt_zero _) (coe_zero_le _) end theorem eq_one_of_dvd_one {a : ℤ} (H : a ≥ 0) (H' : a ∣ 1) : a = 1 := match a, eq_coe_of_zero_le H, H' with | ._, ⟨n, rfl⟩, H' := congr_arg coe $ nat.eq_one_of_dvd_one $ coe_nat_dvd.1 H' end theorem eq_one_of_mul_eq_one_right {a b : ℤ} (H : a ≥ 0) (H' : a * b = 1) : a = 1 := eq_one_of_dvd_one H ⟨b, H'.symm⟩ theorem eq_one_of_mul_eq_one_left {a b : ℤ} (H : b ≥ 0) (H' : a * b = 1) : b = 1 := eq_one_of_mul_eq_one_right H (by rw [mul_comm, H']) lemma of_nat_dvd_of_dvd_nat_abs {a : ℕ} : ∀ {z : ℤ} (haz : a ∣ z.nat_abs), ↑a ∣ z | (int.of_nat _) haz := int.coe_nat_dvd.2 haz | -[1+k] haz := begin change ↑a ∣ -(k+1 : ℤ), apply dvd_neg_of_dvd, apply int.coe_nat_dvd.2, exact haz end lemma dvd_nat_abs_of_of_nat_dvd {a : ℕ} : ∀ {z : ℤ} (haz : ↑a ∣ z), a ∣ z.nat_abs | (int.of_nat _) haz := int.coe_nat_dvd.1 (int.dvd_nat_abs.2 haz) | -[1+k] haz := have haz' : (↑a:ℤ) ∣ (↑(k+1):ℤ), from dvd_of_dvd_neg haz, int.coe_nat_dvd.1 haz' lemma pow_dvd_of_le_of_pow_dvd {p m n : ℕ} {k : ℤ} (hmn : m ≤ n) (hdiv : ↑(p ^ n) ∣ k) : ↑(p ^ m) ∣ k := begin induction k, { apply int.coe_nat_dvd.2, apply pow_dvd_of_le_of_pow_dvd hmn, apply int.coe_nat_dvd.1 hdiv }, { change -[1+k] with -(↑(k+1) : ℤ), apply dvd_neg_of_dvd, apply int.coe_nat_dvd.2, apply pow_dvd_of_le_of_pow_dvd hmn, apply int.coe_nat_dvd.1, apply dvd_of_dvd_neg, exact hdiv } end lemma dvd_of_pow_dvd {p k : ℕ} {m : ℤ} (hk : 1 ≤ k) (hpk : ↑(p^k) ∣ m) : ↑p ∣ m := by rw ←nat.pow_one p; exact pow_dvd_of_le_of_pow_dvd hk hpk /- / and ordering -/ protected theorem div_mul_le (a : ℤ) {b : ℤ} (H : b ≠ 0) : a / b * b ≤ a := le_of_sub_nonneg $ by rw [mul_comm, ← mod_def]; apply mod_nonneg _ H protected theorem div_le_of_le_mul {a b c : ℤ} (H : c > 0) (H' : a ≤ b * c) : a / c ≤ b := le_of_mul_le_mul_right (le_trans (int.div_mul_le _ (ne_of_gt H)) H') H protected theorem mul_lt_of_lt_div {a b c : ℤ} (H : c > 0) (H3 : a < b / c) : a * c < b := lt_of_not_ge $ mt (int.div_le_of_le_mul H) (not_le_of_gt H3) protected theorem mul_le_of_le_div {a b c : ℤ} (H1 : c > 0) (H2 : a ≤ b / c) : a * c ≤ b := le_trans (mul_le_mul_of_nonneg_right H2 (le_of_lt H1)) (int.div_mul_le _ (ne_of_gt H1)) protected theorem le_div_of_mul_le {a b c : ℤ} (H1 : c > 0) (H2 : a * c ≤ b) : a ≤ b / c := le_of_lt_add_one $ lt_of_mul_lt_mul_right (lt_of_le_of_lt H2 (lt_div_add_one_mul_self _ H1)) (le_of_lt H1) protected theorem le_div_iff_mul_le {a b c : ℤ} (H : c > 0) : a ≤ b / c ↔ a * c ≤ b := ⟨int.mul_le_of_le_div H, int.le_div_of_mul_le H⟩ protected theorem div_le_div {a b c : ℤ} (H : c > 0) (H' : a ≤ b) : a / c ≤ b / c := int.le_div_of_mul_le H (le_trans (int.div_mul_le _ (ne_of_gt H)) H') protected theorem div_lt_of_lt_mul {a b c : ℤ} (H : c > 0) (H' : a < b * c) : a / c < b := lt_of_not_ge $ mt (int.mul_le_of_le_div H) (not_le_of_gt H') protected theorem lt_mul_of_div_lt {a b c : ℤ} (H1 : c > 0) (H2 : a / c < b) : a < b * c := lt_of_not_ge $ mt (int.le_div_of_mul_le H1) (not_le_of_gt H2) protected theorem div_lt_iff_lt_mul {a b c : ℤ} (H : c > 0) : a / c < b ↔ a < b * c := ⟨int.lt_mul_of_div_lt H, int.div_lt_of_lt_mul H⟩ protected theorem le_mul_of_div_le {a b c : ℤ} (H1 : b ≥ 0) (H2 : b ∣ a) (H3 : a / b ≤ c) : a ≤ c * b := by rw [← int.div_mul_cancel H2]; exact mul_le_mul_of_nonneg_right H3 H1 protected theorem lt_div_of_mul_lt {a b c : ℤ} (H1 : b ≥ 0) (H2 : b ∣ c) (H3 : a * b < c) : a < c / b := lt_of_not_ge $ mt (int.le_mul_of_div_le H1 H2) (not_le_of_gt H3) protected theorem lt_div_iff_mul_lt {a b : ℤ} (c : ℤ) (H : c > 0) (H' : c ∣ b) : a < b / c ↔ a * c < b := ⟨int.mul_lt_of_lt_div H, int.lt_div_of_mul_lt (le_of_lt H) H'⟩ theorem div_pos_of_pos_of_dvd {a b : ℤ} (H1 : a > 0) (H2 : b ≥ 0) (H3 : b ∣ a) : a / b > 0 := int.lt_div_of_mul_lt H2 H3 (by rwa zero_mul) theorem div_eq_div_of_mul_eq_mul {a b c d : ℤ} (H1 : b ∣ a) (H2 : d ∣ c) (H3 : b ≠ 0) (H4 : d ≠ 0) (H5 : a * d = b * c) : a / b = c / d := int.div_eq_of_eq_mul_right H3 $ by rw [← int.mul_div_assoc _ H2]; exact (int.div_eq_of_eq_mul_left H4 H5.symm).symm theorem eq_mul_div_of_mul_eq_mul_of_dvd_left {a b c d : ℤ} (hb : b ≠ 0) (hd : d ≠ 0) (hbc : b ∣ c) (h : b * a = c * d) : a = c / b * d := begin cases hbc with k hk, subst hk, rw int.mul_div_cancel_left, rw mul_assoc at h, apply _root_.eq_of_mul_eq_mul_left _ h, repeat {assumption} end theorem of_nat_add_neg_succ_of_nat_of_lt {m n : ℕ} (h : m < n.succ) : of_nat m + -[1+n] = -[1+ n - m] := begin change sub_nat_nat _ _ = _, have h' : n.succ - m = (n - m).succ, apply succ_sub, apply le_of_lt_succ h, simp [*, sub_nat_nat] end theorem of_nat_add_neg_succ_of_nat_of_ge {m n : ℕ} (h : m ≥ n.succ) : of_nat m + -[1+n] = of_nat (m - n.succ) := begin change sub_nat_nat _ _ = _, have h' : n.succ - m = 0, apply sub_eq_zero_of_le h, simp [*, sub_nat_nat] end @[simp] theorem neg_add_neg (m n : ℕ) : -[1+m] + -[1+n] = -[1+nat.succ(m+n)] := rfl /- to_nat -/ theorem to_nat_eq_max : ∀ (a : ℤ), (to_nat a : ℤ) = max a 0 | (n : ℕ) := (max_eq_left (coe_zero_le n)).symm | -[1+ n] := (max_eq_right (le_of_lt (neg_succ_lt_zero n))).symm @[simp] theorem to_nat_of_nonneg {a : ℤ} (h : 0 ≤ a) : (to_nat a : ℤ) = a := by rw [to_nat_eq_max, max_eq_left h] @[simp] theorem to_nat_coe_nat (n : ℕ) : to_nat ↑n = n := rfl theorem le_to_nat (a : ℤ) : a ≤ to_nat a := by rw [to_nat_eq_max]; apply le_max_left @[simp] theorem to_nat_le (a : ℤ) (n : ℕ) : to_nat a ≤ n ↔ a ≤ n := by rw [(coe_nat_le_coe_nat_iff _ _).symm, to_nat_eq_max, max_le_iff]; exact and_iff_left (coe_zero_le _) theorem to_nat_le_to_nat {a b : ℤ} (h : a ≤ b) : to_nat a ≤ to_nat b := by rw to_nat_le; exact le_trans h (le_to_nat b) def to_nat' : ℤ → option ℕ | (n : ℕ) := some n | -[1+ n] := none theorem mem_to_nat' : ∀ (a : ℤ) (n : ℕ), n ∈ to_nat' a ↔ a = n | (m : ℕ) n := option.some_inj.trans coe_nat_inj'.symm | -[1+ m] n := by split; intro h; cases h /- units -/ @[simp] theorem units_nat_abs (u : units ℤ) : nat_abs u = 1 := units.ext_iff.1 $ nat.units_eq_one ⟨nat_abs u, nat_abs ↑u⁻¹, by rw [← nat_abs_mul, units.mul_inv]; refl, by rw [← nat_abs_mul, units.inv_mul]; refl⟩ theorem units_eq_one_or (u : units ℤ) : u = 1 ∨ u = -1 := by simpa [units.ext_iff, units_nat_abs] using nat_abs_eq u lemma units_inv_eq_self (u : units ℤ) : u⁻¹ = u := (units_eq_one_or u).elim (λ h, h.symm ▸ rfl) (λ h, h.symm ▸ rfl) /- bitwise ops -/ @[simp] lemma bodd_zero : bodd 0 = ff := rfl @[simp] lemma bodd_one : bodd 1 = tt := rfl @[simp] lemma bodd_two : bodd 2 = ff := rfl @[simp] lemma bodd_sub_nat_nat (m n : ℕ) : bodd (sub_nat_nat m n) = bxor m.bodd n.bodd := by apply sub_nat_nat_elim m n (λ m n i, bodd i = bxor m.bodd n.bodd); intros i m; simp [bodd]; cases i.bodd; cases m.bodd; refl @[simp] lemma bodd_neg_of_nat (n : ℕ) : bodd (neg_of_nat n) = n.bodd := by cases n; simp; refl @[simp] lemma bodd_neg (n : ℤ) : bodd (-n) = bodd n := by cases n; unfold has_neg.neg; simp [int.coe_nat_eq, int.neg, bodd] @[simp] lemma bodd_add (m n : ℤ) : bodd (m + n) = bxor (bodd m) (bodd n) := by cases m with m m; cases n with n n; unfold has_add.add; simp [int.add, bodd]; cases m.bodd; cases n.bodd; refl @[simp] lemma bodd_mul (m n : ℤ) : bodd (m * n) = bodd m && bodd n := by cases m with m m; cases n with n n; unfold has_mul.mul; simp [int.mul, bodd]; cases m.bodd; cases n.bodd; refl theorem bodd_add_div2 : ∀ n, cond (bodd n) 1 0 + 2 * div2 n = n | (n : ℕ) := by rw [show (cond (bodd n) 1 0 : ℤ) = (cond (bodd n) 1 0 : ℕ), by cases bodd n; refl]; exact congr_arg of_nat n.bodd_add_div2 | -[1+ n] := begin refine eq.trans _ (congr_arg neg_succ_of_nat n.bodd_add_div2), dsimp [bodd], cases nat.bodd n; dsimp [cond, bnot, div2, int.mul], { change -[1+ 2 * nat.div2 n] = _, rw zero_add }, { rw [zero_add, add_comm], refl } end theorem div2_val : ∀ n, div2 n = n / 2 | (n : ℕ) := congr_arg of_nat n.div2_val | -[1+ n] := congr_arg neg_succ_of_nat n.div2_val lemma bit0_val (n : ℤ) : bit0 n = 2 * n := (two_mul _).symm lemma bit1_val (n : ℤ) : bit1 n = 2 * n + 1 := congr_arg (+(1:ℤ)) (bit0_val _) lemma bit_val (b n) : bit b n = 2 * n + cond b 1 0 := by { cases b, apply (bit0_val n).trans (add_zero _).symm, apply bit1_val } lemma bit_decomp (n : ℤ) : bit (bodd n) (div2 n) = n := (bit_val _ _).trans $ (add_comm _ _).trans $ bodd_add_div2 _ def {u} bit_cases_on {C : ℤ → Sort u} (n) (h : ∀ b n, C (bit b n)) : C n := by rw [← bit_decomp n]; apply h @[simp] lemma bit_zero : bit ff 0 = 0 := rfl @[simp] lemma bit_coe_nat (b) (n : ℕ) : bit b n = nat.bit b n := by rw [bit_val, nat.bit_val]; cases b; refl @[simp] lemma bit_neg_succ (b) (n : ℕ) : bit b -[1+ n] = -[1+ nat.bit (bnot b) n] := by rw [bit_val, nat.bit_val]; cases b; refl @[simp] lemma bodd_bit (b n) : bodd (bit b n) = b := by rw bit_val; simp; cases b; cases bodd n; refl @[simp] lemma div2_bit (b n) : div2 (bit b n) = n := begin rw [bit_val, div2_val, add_comm, int.add_mul_div_left, (_ : (_/2:ℤ) = 0), zero_add], cases b, all_goals {exact dec_trivial} end @[simp] lemma test_bit_zero (b) : ∀ n, test_bit (bit b n) 0 = b | (n : ℕ) := by rw [bit_coe_nat]; apply nat.test_bit_zero | -[1+ n] := by rw [bit_neg_succ]; dsimp [test_bit]; rw [nat.test_bit_zero]; clear test_bit_zero; cases b; refl @[simp] lemma test_bit_succ (m b) : ∀ n, test_bit (bit b n) (nat.succ m) = test_bit n m | (n : ℕ) := by rw [bit_coe_nat]; apply nat.test_bit_succ | -[1+ n] := by rw [bit_neg_succ]; dsimp [test_bit]; rw [nat.test_bit_succ] private meta def bitwise_tac : tactic unit := `[ funext m, funext n, cases m with m m; cases n with n n; try {refl}, all_goals { apply congr_arg of_nat <|> apply congr_arg neg_succ_of_nat, try {dsimp [nat.land, nat.ldiff, nat.lor]}, try {rw [ show nat.bitwise (λ a b, a && bnot b) n m = nat.bitwise (λ a b, b && bnot a) m n, from congr_fun (congr_fun (@nat.bitwise_swap (λ a b, b && bnot a) rfl) n) m]}, apply congr_arg (λ f, nat.bitwise f m n), funext a, funext b, cases a; cases b; refl }, all_goals {unfold nat.land nat.ldiff nat.lor} ] theorem bitwise_or : bitwise bor = lor := by bitwise_tac theorem bitwise_and : bitwise band = land := by bitwise_tac theorem bitwise_diff : bitwise (λ a b, a && bnot b) = ldiff := by bitwise_tac theorem bitwise_xor : bitwise bxor = lxor := by bitwise_tac @[simp] lemma bitwise_bit (f : bool → bool → bool) (a m b n) : bitwise f (bit a m) (bit b n) = bit (f a b) (bitwise f m n) := begin cases m with m m; cases n with n n; repeat { rw [← int.coe_nat_eq] <|> rw bit_coe_nat <|> rw bit_neg_succ }; unfold bitwise nat_bitwise bnot; [ induction h : f ff ff, induction h : f ff tt, induction h : f tt ff, induction h : f tt tt ], all_goals { unfold cond, rw nat.bitwise_bit, repeat { rw bit_coe_nat <|> rw bit_neg_succ <|> rw bnot_bnot } }, all_goals { unfold bnot {fail_if_unchanged := ff}; rw h; refl } end @[simp] lemma lor_bit (a m b n) : lor (bit a m) (bit b n) = bit (a || b) (lor m n) := by rw [← bitwise_or, bitwise_bit] @[simp] lemma land_bit (a m b n) : land (bit a m) (bit b n) = bit (a && b) (land m n) := by rw [← bitwise_and, bitwise_bit] @[simp] lemma ldiff_bit (a m b n) : ldiff (bit a m) (bit b n) = bit (a && bnot b) (ldiff m n) := by rw [← bitwise_diff, bitwise_bit] @[simp] lemma lxor_bit (a m b n) : lxor (bit a m) (bit b n) = bit (bxor a b) (lxor m n) := by rw [← bitwise_xor, bitwise_bit] @[simp] lemma lnot_bit (b) : ∀ n, lnot (bit b n) = bit (bnot b) (lnot n) | (n : ℕ) := by simp [lnot] | -[1+ n] := by simp [lnot] @[simp] lemma test_bit_bitwise (f : bool → bool → bool) (m n k) : test_bit (bitwise f m n) k = f (test_bit m k) (test_bit n k) := begin induction k with k IH generalizing m n; apply bit_cases_on m; intros a m'; apply bit_cases_on n; intros b n'; rw bitwise_bit, { simp [test_bit_zero] }, { simp [test_bit_succ, IH] } end @[simp] lemma test_bit_lor (m n k) : test_bit (lor m n) k = test_bit m k || test_bit n k := by rw [← bitwise_or, test_bit_bitwise] @[simp] lemma test_bit_land (m n k) : test_bit (land m n) k = test_bit m k && test_bit n k := by rw [← bitwise_and, test_bit_bitwise] @[simp] lemma test_bit_ldiff (m n k) : test_bit (ldiff m n) k = test_bit m k && bnot (test_bit n k) := by rw [← bitwise_diff, test_bit_bitwise] @[simp] lemma test_bit_lxor (m n k) : test_bit (lxor m n) k = bxor (test_bit m k) (test_bit n k) := by rw [← bitwise_xor, test_bit_bitwise] @[simp] lemma test_bit_lnot : ∀ n k, test_bit (lnot n) k = bnot (test_bit n k) | (n : ℕ) k := by simp [lnot, test_bit] | -[1+ n] k := by simp [lnot, test_bit] lemma shiftl_add : ∀ (m : ℤ) (n : ℕ) (k : ℤ), shiftl m (n + k) = shiftl (shiftl m n) k | (m : ℕ) n (k:ℕ) := congr_arg of_nat (nat.shiftl_add _ _ _) | -[1+ m] n (k:ℕ) := congr_arg neg_succ_of_nat (nat.shiftl'_add _ _ _ _) | (m : ℕ) n -[1+k] := sub_nat_nat_elim n k.succ (λ n k i, shiftl ↑m i = nat.shiftr (nat.shiftl m n) k) (λ i n, congr_arg coe $ by rw [← nat.shiftl_sub, nat.add_sub_cancel_left]; apply nat.le_add_right) (λ i n, congr_arg coe $ by rw [add_assoc, nat.shiftr_add, ← nat.shiftl_sub, nat.sub_self]; refl) | -[1+ m] n -[1+k] := sub_nat_nat_elim n k.succ (λ n k i, shiftl -[1+ m] i = -[1+ nat.shiftr (nat.shiftl' tt m n) k]) (λ i n, congr_arg neg_succ_of_nat $ by rw [← nat.shiftl'_sub, nat.add_sub_cancel_left]; apply nat.le_add_right) (λ i n, congr_arg neg_succ_of_nat $ by rw [add_assoc, nat.shiftr_add, ← nat.shiftl'_sub, nat.sub_self]; refl) lemma shiftl_sub (m : ℤ) (n : ℕ) (k : ℤ) : shiftl m (n - k) = shiftr (shiftl m n) k := shiftl_add _ _ _ @[simp] lemma shiftl_neg (m n : ℤ) : shiftl m (-n) = shiftr m n := rfl @[simp] lemma shiftr_neg (m n : ℤ) : shiftr m (-n) = shiftl m n := by rw [← shiftl_neg, neg_neg] @[simp] lemma shiftl_coe_nat (m n : ℕ) : shiftl m n = nat.shiftl m n := rfl @[simp] lemma shiftr_coe_nat (m n : ℕ) : shiftr m n = nat.shiftr m n := by cases n; refl @[simp] lemma shiftl_neg_succ (m n : ℕ) : shiftl -[1+ m] n = -[1+ nat.shiftl' tt m n] := rfl @[simp] lemma shiftr_neg_succ (m n : ℕ) : shiftr -[1+ m] n = -[1+ nat.shiftr m n] := by cases n; refl lemma shiftr_add : ∀ (m : ℤ) (n k : ℕ), shiftr m (n + k) = shiftr (shiftr m n) k | (m : ℕ) n k := by rw [shiftr_coe_nat, shiftr_coe_nat, ← int.coe_nat_add, shiftr_coe_nat, nat.shiftr_add] | -[1+ m] n k := by rw [shiftr_neg_succ, shiftr_neg_succ, ← int.coe_nat_add, shiftr_neg_succ, nat.shiftr_add] lemma shiftl_eq_mul_pow : ∀ (m : ℤ) (n : ℕ), shiftl m n = m * ↑(2 ^ n) | (m : ℕ) n := congr_arg coe (nat.shiftl_eq_mul_pow _ _) | -[1+ m] n := @congr_arg ℕ ℤ _ _ (λi, -i) (nat.shiftl'_tt_eq_mul_pow _ _) lemma shiftr_eq_div_pow : ∀ (m : ℤ) (n : ℕ), shiftr m n = m / ↑(2 ^ n) | (m : ℕ) n := by rw shiftr_coe_nat; exact congr_arg coe (nat.shiftr_eq_div_pow _ _) | -[1+ m] n := begin rw [shiftr_neg_succ, neg_succ_of_nat_div, nat.shiftr_eq_div_pow], refl, exact coe_nat_lt_coe_nat_of_lt (nat.pos_pow_of_pos _ dec_trivial) end lemma one_shiftl (n : ℕ) : shiftl 1 n = (2 ^ n : ℕ) := congr_arg coe (nat.one_shiftl _) @[simp] lemma zero_shiftl : ∀ n : ℤ, shiftl 0 n = 0 | (n : ℕ) := congr_arg coe (nat.zero_shiftl _) | -[1+ n] := congr_arg coe (nat.zero_shiftr _) @[simp] lemma zero_shiftr (n) : shiftr 0 n = 0 := zero_shiftl _ /- Least upper bound property for integers -/ theorem exists_least_of_bdd {P : ℤ → Prop} [HP : decidable_pred P] (Hbdd : ∃ b : ℤ, ∀ z : ℤ, P z → b ≤ z) (Hinh : ∃ z : ℤ, P z) : ∃ lb : ℤ, P lb ∧ (∀ z : ℤ, P z → lb ≤ z) := let ⟨b, Hb⟩ := Hbdd in have EX : ∃ n : ℕ, P (b + n), from let ⟨elt, Helt⟩ := Hinh in match elt, le.dest (Hb _ Helt), Helt with | ._, ⟨n, rfl⟩, Hn := ⟨n, Hn⟩ end, ⟨b + (nat.find EX : ℤ), nat.find_spec EX, λ z h, match z, le.dest (Hb _ h), h with | ._, ⟨n, rfl⟩, h := add_le_add_left (int.coe_nat_le.2 $ nat.find_min' _ h) _ end⟩ theorem exists_greatest_of_bdd {P : ℤ → Prop} [HP : decidable_pred P] (Hbdd : ∃ b : ℤ, ∀ z : ℤ, P z → z ≤ b) (Hinh : ∃ z : ℤ, P z) : ∃ ub : ℤ, P ub ∧ (∀ z : ℤ, P z → z ≤ ub) := have Hbdd' : ∃ (b : ℤ), ∀ (z : ℤ), P (-z) → b ≤ z, from let ⟨b, Hb⟩ := Hbdd in ⟨-b, λ z h, neg_le.1 (Hb _ h)⟩, have Hinh' : ∃ z : ℤ, P (-z), from let ⟨elt, Helt⟩ := Hinh in ⟨-elt, by rw [neg_neg]; exact Helt⟩, let ⟨lb, Plb, al⟩ := exists_least_of_bdd Hbdd' Hinh' in ⟨-lb, Plb, λ z h, le_neg.1 $ al _ $ by rwa neg_neg⟩ /- cast (injection into groups with one) -/ @[simp] theorem nat_cast_eq_coe_nat : ∀ n, @coe ℕ ℤ (@coe_to_lift _ _ (@coe_base _ _ nat.cast_coe)) n = @coe ℕ ℤ (@coe_to_lift _ _ (@coe_base _ _ int.has_coe)) n | 0 := rfl | (n+1) := congr_arg (+(1:ℤ)) (nat_cast_eq_coe_nat n) section cast variables {α : Type*} local attribute [instance, priority 0] nat.cast_coe section variables [has_neg α] [has_zero α] [has_one α] [has_add α] /-- Canonical homomorphism from the integers to any ring(-like) structure `α` -/ protected def cast : ℤ → α | (n : ℕ) := n | -[1+ n] := -(n+1) def cast_coe : has_coe ℤ α := ⟨int.cast⟩ local attribute [instance, priority 0] cast_coe @[simp] theorem cast_zero : ((0 : ℤ) : α) = 0 := rfl @[simp] theorem cast_of_nat (n : ℕ) : (of_nat n : α) = n := rfl @[simp] theorem cast_coe_nat (n : ℕ) : ((n : ℤ) : α) = n := rfl @[simp] theorem cast_coe_nat' (n : ℕ) : (@coe ℕ ℤ (@coe_to_lift _ _ (@coe_base _ _ nat.cast_coe)) n : α) = n := by simp @[simp] theorem cast_neg_succ_of_nat (n : ℕ) : (-[1+ n] : α) = -(n + 1) := rfl end local attribute [instance, priority 0] cast_coe @[simp] theorem cast_one [add_monoid α] [has_one α] [has_neg α] : ((1 : ℤ) : α) = 1 := nat.cast_one @[simp] theorem cast_sub_nat_nat [add_group α] [has_one α] (m n) : ((int.sub_nat_nat m n : ℤ) : α) = m - n := begin unfold sub_nat_nat, cases e : n - m, { simp [sub_nat_nat, e, nat.le_of_sub_eq_zero e] }, { rw [sub_nat_nat, cast_neg_succ_of_nat, ← nat.cast_succ, ← e, nat.cast_sub $ _root_.le_of_lt $ nat.lt_of_sub_eq_succ e, neg_sub] }, end @[simp] theorem cast_neg_of_nat [add_group α] [has_one α] : ∀ n, ((neg_of_nat n : ℤ) : α) = -n | 0 := neg_zero.symm | (n+1) := rfl @[simp] theorem cast_add [add_group α] [has_one α] : ∀ m n, ((m + n : ℤ) : α) = m + n | (m : ℕ) (n : ℕ) := nat.cast_add _ _ | (m : ℕ) -[1+ n] := cast_sub_nat_nat _ _ | -[1+ m] (n : ℕ) := (cast_sub_nat_nat _ _).trans $ sub_eq_of_eq_add $ show (n:α) = -(m+1) + n + (m+1), by rw [add_assoc, ← cast_succ, ← nat.cast_add, add_comm, nat.cast_add, cast_succ, neg_add_cancel_left] | -[1+ m] -[1+ n] := show -((m + n + 1 + 1 : ℕ) : α) = -(m + 1) + -(n + 1), by rw [← neg_add_rev, ← nat.cast_add_one, ← nat.cast_add_one, ← nat.cast_add]; apply congr_arg (λ x:ℕ, -(x:α)); simp @[simp] theorem cast_neg [add_group α] [has_one α] : ∀ n, ((-n : ℤ) : α) = -n | (n : ℕ) := cast_neg_of_nat _ | -[1+ n] := (neg_neg _).symm theorem cast_sub [add_group α] [has_one α] (m n) : ((m - n : ℤ) : α) = m - n := by simp @[simp] theorem cast_eq_zero [add_group α] [has_one α] [char_zero α] {n : ℤ} : (n : α) = 0 ↔ n = 0 := ⟨λ h, begin cases n, { exact congr_arg coe (nat.cast_eq_zero.1 h) }, { rw [cast_neg_succ_of_nat, neg_eq_zero, ← cast_succ, nat.cast_eq_zero] at h, contradiction } end, λ h, by rw [h, cast_zero]⟩ @[simp] theorem cast_inj [add_group α] [has_one α] [char_zero α] {m n : ℤ} : (m : α) = n ↔ m = n := by rw [← sub_eq_zero, ← cast_sub, cast_eq_zero, sub_eq_zero] theorem cast_injective [add_group α] [has_one α] [char_zero α] : function.injective (coe : ℤ → α) | m n := cast_inj.1 @[simp] theorem cast_ne_zero [add_group α] [has_one α] [char_zero α] {n : ℤ} : (n : α) ≠ 0 ↔ n ≠ 0 := not_congr cast_eq_zero @[simp] theorem cast_mul [ring α] : ∀ m n, ((m * n : ℤ) : α) = m * n | (m : ℕ) (n : ℕ) := nat.cast_mul _ _ | (m : ℕ) -[1+ n] := (cast_neg_of_nat _).trans $ show (-(m * (n + 1) : ℕ) : α) = m * -(n + 1), by rw [nat.cast_mul, nat.cast_add_one, neg_mul_eq_mul_neg] | -[1+ m] (n : ℕ) := (cast_neg_of_nat _).trans $ show (-((m + 1) * n : ℕ) : α) = -(m + 1) * n, by rw [nat.cast_mul, nat.cast_add_one, neg_mul_eq_neg_mul] | -[1+ m] -[1+ n] := show (((m + 1) * (n + 1) : ℕ) : α) = -(m + 1) * -(n + 1), by rw [nat.cast_mul, nat.cast_add_one, nat.cast_add_one, neg_mul_neg] instance cast.is_ring_hom [ring α] : is_ring_hom (int.cast : ℤ → α) := ⟨cast_one, cast_mul, cast_add⟩ theorem mul_cast_comm [ring α] (a : α) (n : ℤ) : a * n = n * a := by cases n; simp [nat.mul_cast_comm, left_distrib, right_distrib, *] @[simp] theorem cast_bit0 [ring α] (n : ℤ) : ((bit0 n : ℤ) : α) = bit0 n := cast_add _ _ @[simp] theorem cast_bit1 [ring α] (n : ℤ) : ((bit1 n : ℤ) : α) = bit1 n := by rw [bit1, cast_add, cast_one, cast_bit0]; refl lemma cast_two [ring α] : ((2 : ℤ) : α) = 2 := by simp theorem cast_nonneg [linear_ordered_ring α] : ∀ {n : ℤ}, (0 : α) ≤ n ↔ 0 ≤ n | (n : ℕ) := by simp | -[1+ n] := by simpa [not_le_of_gt (neg_succ_lt_zero n)] using show -(n:α) < 1, from lt_of_le_of_lt (by simp) zero_lt_one @[simp] theorem cast_le [linear_ordered_ring α] {m n : ℤ} : (m : α) ≤ n ↔ m ≤ n := by rw [← sub_nonneg, ← cast_sub, cast_nonneg, sub_nonneg] @[simp] theorem cast_lt [linear_ordered_ring α] {m n : ℤ} : (m : α) < n ↔ m < n := by simpa [-cast_le] using not_congr (@cast_le α _ n m) @[simp] theorem cast_nonpos [linear_ordered_ring α] {n : ℤ} : (n : α) ≤ 0 ↔ n ≤ 0 := by rw [← cast_zero, cast_le] @[simp] theorem cast_pos [linear_ordered_ring α] {n : ℤ} : (0 : α) < n ↔ 0 < n := by rw [← cast_zero, cast_lt] @[simp] theorem cast_lt_zero [linear_ordered_ring α] {n : ℤ} : (n : α) < 0 ↔ n < 0 := by rw [← cast_zero, cast_lt] theorem eq_cast [add_group α] [has_one α] (f : ℤ → α) (H1 : f 1 = 1) (Hadd : ∀ x y, f (x + y) = f x + f y) (n : ℤ) : f n = n := begin have H : ∀ (n : ℕ), f n = n := nat.eq_cast' (λ n, f n) H1 (λ x y, Hadd x y), cases n, {apply H}, apply eq_neg_of_add_eq_zero, rw [← nat.cast_zero, ← H 0, int.coe_nat_zero, ← show -[1+ n] + (↑n + 1) = 0, from neg_add_self (↑n+1), Hadd, show f (n+1) = n+1, from H (n+1)] end @[simp] theorem cast_id (n : ℤ) : ↑n = n := (eq_cast id rfl (λ _ _, rfl) n).symm @[simp] theorem cast_min [decidable_linear_ordered_comm_ring α] {a b : ℤ} : (↑(min a b) : α) = min a b := by by_cases a ≤ b; simp [h, min] @[simp] theorem cast_max [decidable_linear_ordered_comm_ring α] {a b : ℤ} : (↑(max a b) : α) = max a b := by by_cases a ≤ b; simp [h, max] @[simp] theorem cast_abs [decidable_linear_ordered_comm_ring α] {q : ℤ} : ((abs q : ℤ) : α) = abs q := by simp [abs] end cast section decidable def range (m n : ℤ) : list ℤ := (list.range (to_nat (n-m))).map $ λ r, m+r theorem mem_range_iff {m n r : ℤ} : r ∈ range m n ↔ m ≤ r ∧ r < n := ⟨λ H, let ⟨s, h1, h2⟩ := list.mem_map.1 H in h2 ▸ ⟨le_add_of_nonneg_right trivial, add_lt_of_lt_sub_left $ match n-m, h1 with | (k:ℕ), h1 := by rwa [list.mem_range, to_nat_coe_nat, ← coe_nat_lt] at h1 end⟩, λ ⟨h1, h2⟩, list.mem_map.2 ⟨to_nat (r-m), list.mem_range.2 $ by rw [← coe_nat_lt, to_nat_of_nonneg (sub_nonneg_of_le h1), to_nat_of_nonneg (sub_nonneg_of_le (le_of_lt (lt_of_le_of_lt h1 h2)))]; exact sub_lt_sub_right h2 _, show m + _ = _, by rw [to_nat_of_nonneg (sub_nonneg_of_le h1), add_sub_cancel'_right]⟩⟩ instance decidable_le_lt (P : int → Prop) [decidable_pred P] (m n : ℤ) : decidable (∀ r, m ≤ r → r < n → P r) := decidable_of_iff (∀ r ∈ range m n, P r) $ by simp only [mem_range_iff, and_imp] instance decidable_le_le (P : int → Prop) [decidable_pred P] (m n : ℤ) : decidable (∀ r, m ≤ r → r ≤ n → P r) := decidable_of_iff (∀ r ∈ range m (n+1), P r) $ by simp only [mem_range_iff, and_imp, lt_add_one_iff] instance decidable_lt_lt (P : int → Prop) [decidable_pred P] (m n : ℤ) : decidable (∀ r, m < r → r < n → P r) := int.decidable_le_lt P _ _ instance decidable_lt_le (P : int → Prop) [decidable_pred P] (m n : ℤ) : decidable (∀ r, m < r → r ≤ n → P r) := int.decidable_le_le P _ _ end decidable end int
fbbd273004c3d93e7bacfa7852fac2e870e2454a
b2e508d02500f1512e1618150413e6be69d9db10
/src/category_theory/full_subcategory.lean
27f42a4f9f9a6d12bad51be00da9a4590bd8b72d
[ "Apache-2.0" ]
permissive
callum-sutton/mathlib
c3788f90216e9cd43eeffcb9f8c9f959b3b01771
afd623825a3ac6bfbcc675a9b023edad3f069e89
refs/heads/master
1,591,371,888,053
1,560,990,690,000
1,560,990,690,000
192,476,045
0
0
Apache-2.0
1,568,941,843,000
1,560,837,965,000
Lean
UTF-8
Lean
false
false
2,393
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Scott Morrison, Reid Barton import category_theory.fully_faithful namespace category_theory universes v u₁ u₂ -- declare the `v`'s first; see `category_theory.category` for an explanation section induced /- Induced categories. Given a category D and a function F : C → D from a type C to the objects of D, there is an essentially unique way to give C a category structure such that F becomes a fully faithful functor, namely by taking Hom_C(X, Y) = Hom_D(FX, FY). We call this the category induced from D along F. As a special case, if C is a subtype of D, this produces the full subcategory of D on the objects belonging to C. In general the induced category is equivalent to the full subcategory of D on the image of F. -/ variables {C : Type u₁} {D : Type u₂} [𝒟 : category.{v} D] include 𝒟 variables (F : C → D) include F def induced_category : Type u₁ := C instance induced_category.category : category.{v} (induced_category F) := { hom := λ X Y, F X ⟶ F Y, id := λ X, 𝟙 (F X), comp := λ _ _ _ f g, f ≫ g } def induced_functor : induced_category F ⥤ D := { obj := F, map := λ x y f, f } @[simp] lemma induced_functor.obj {X} : (induced_functor F).obj X = F X := rfl @[simp] lemma induced_functor.hom {X Y} {f : X ⟶ Y} : (induced_functor F).map f = f := rfl instance induced_category.fully_faithful : fully_faithful (induced_functor F) := { preimage := λ x y f, f } end induced section full_subcategory /- A full subcategory is the special case of an induced category with F = subtype.val. -/ variables {C : Type u₂} [𝒞 : category.{v} C] include 𝒞 variables (Z : C → Prop) instance full_subcategory : category.{v} {X : C // Z X} := induced_category.category subtype.val def full_subcategory_inclusion : {X : C // Z X} ⥤ C := induced_functor subtype.val @[simp] lemma full_subcategory_inclusion.obj {X} : (full_subcategory_inclusion Z).obj X = X.val := rfl @[simp] lemma full_subcategory_inclusion.map {X Y} {f : X ⟶ Y} : (full_subcategory_inclusion Z).map f = f := rfl instance full_subcategory.fully_faithful : fully_faithful (full_subcategory_inclusion Z) := induced_category.fully_faithful subtype.val end full_subcategory end category_theory
5c8a48c81774793bbb359dc3cd7a7f0efb31f374
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/measure_theory/constructions/prod.lean
6bb0900ec5f03568fd8b7296a0a85ccf455dfde6
[ "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
55,699
lean
/- Copyright (c) 2020 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn -/ import measure_theory.measure.giry_monad import dynamics.ergodic.measure_preserving import measure_theory.integral.set_integral import measure_theory.measure.open_pos /-! # The product measure In this file we define and prove properties about the binary product measure. If `α` and `β` have σ-finite measures `μ` resp. `ν` then `α × β` can be equipped with a σ-finite measure `μ.prod ν` that satisfies `(μ.prod ν) s = ∫⁻ x, ν {y | (x, y) ∈ s} ∂μ`. We also have `(μ.prod ν) (s ×ˢ t) = μ s * ν t`, i.e. the measure of a rectangle is the product of the measures of the sides. We also prove Tonelli's theorem and Fubini's theorem. ## Main definition * `measure_theory.measure.prod`: The product of two measures. ## Main results * `measure_theory.measure.prod_apply` states `μ.prod ν s = ∫⁻ x, ν {y | (x, y) ∈ s} ∂μ` for measurable `s`. `measure_theory.measure.prod_apply_symm` is the reversed version. * `measure_theory.measure.prod_prod` states `μ.prod ν (s ×ˢ t) = μ s * ν t` for measurable sets `s` and `t`. * `measure_theory.lintegral_prod`: Tonelli's theorem. It states that for a measurable function `α × β → ℝ≥0∞` we have `∫⁻ z, f z ∂(μ.prod ν) = ∫⁻ x, ∫⁻ y, f (x, y) ∂ν ∂μ`. The version for functions `α → β → ℝ≥0∞` is reversed, and called `lintegral_lintegral`. Both versions have a variant with `_symm` appended, where the order of integration is reversed. The lemma `measurable.lintegral_prod_right'` states that the inner integral of the right-hand side is measurable. * `measure_theory.integrable_prod_iff` states that a binary function is integrable iff both * `y ↦ f (x, y)` is integrable for almost every `x`, and * the function `x ↦ ∫ ‖f (x, y)‖ dy` is integrable. * `measure_theory.integral_prod`: Fubini's theorem. It states that for a integrable function `α × β → E` (where `E` is a second countable Banach space) we have `∫ z, f z ∂(μ.prod ν) = ∫ x, ∫ y, f (x, y) ∂ν ∂μ`. This theorem has the same variants as Tonelli's theorem. The lemma `measure_theory.integrable.integral_prod_right` states that the inner integral of the right-hand side is integrable. ## Implementation Notes Many results are proven twice, once for functions in curried form (`α → β → γ`) and one for functions in uncurried form (`α × β → γ`). The former often has an assumption `measurable (uncurry f)`, which could be inconvenient to discharge, but for the latter it is more common that the function has to be given explicitly, since Lean cannot synthesize the function by itself. We name the lemmas about the uncurried form with a prime. Tonelli's theorem and Fubini's theorem have a different naming scheme, since the version for the uncurried version is reversed. ## Tags product measure, Fubini's theorem, Tonelli's theorem, Fubini-Tonelli theorem -/ noncomputable theory open_locale classical topological_space ennreal measure_theory open set function real ennreal open measure_theory measurable_space measure_theory.measure open topological_space (hiding generate_from) open filter (hiding prod_eq map) variables {α α' β β' γ E : Type*} /-- Rectangles formed by π-systems form a π-system. -/ lemma is_pi_system.prod {C : set (set α)} {D : set (set β)} (hC : is_pi_system C) (hD : is_pi_system D) : is_pi_system (image2 (×ˢ) C D) := begin rintro _ ⟨s₁, t₁, hs₁, ht₁, rfl⟩ _ ⟨s₂, t₂, hs₂, ht₂, rfl⟩ hst, rw [prod_inter_prod] at hst ⊢, rw [prod_nonempty_iff] at hst, exact mem_image2_of_mem (hC _ hs₁ _ hs₂ hst.1) (hD _ ht₁ _ ht₂ hst.2) end /-- Rectangles of countably spanning sets are countably spanning. -/ lemma is_countably_spanning.prod {C : set (set α)} {D : set (set β)} (hC : is_countably_spanning C) (hD : is_countably_spanning D) : is_countably_spanning (image2 (×ˢ) C D) := begin rcases ⟨hC, hD⟩ with ⟨⟨s, h1s, h2s⟩, t, h1t, h2t⟩, refine ⟨λ n, (s n.unpair.1) ×ˢ (t n.unpair.2), λ n, mem_image2_of_mem (h1s _) (h1t _), _⟩, rw [Union_unpair_prod, h2s, h2t, univ_prod_univ] end variables [measurable_space α] [measurable_space α'] [measurable_space β] [measurable_space β'] variables [measurable_space γ] variables {μ μ' : measure α} {ν ν' : measure β} {τ : measure γ} variables [normed_add_comm_group E] /-! ### Measurability Before we define the product measure, we can talk about the measurability of operations on binary functions. We show that if `f` is a binary measurable function, then the function that integrates along one of the variables (using either the Lebesgue or Bochner integral) is measurable. -/ /-- The product of generated σ-algebras is the one generated by rectangles, if both generating sets are countably spanning. -/ lemma generate_from_prod_eq {α β} {C : set (set α)} {D : set (set β)} (hC : is_countably_spanning C) (hD : is_countably_spanning D) : @prod.measurable_space _ _ (generate_from C) (generate_from D) = generate_from (image2 (×ˢ) C D) := begin apply le_antisymm, { refine sup_le _ _; rw [comap_generate_from]; apply generate_from_le; rintro _ ⟨s, hs, rfl⟩, { rcases hD with ⟨t, h1t, h2t⟩, rw [← prod_univ, ← h2t, prod_Union], apply measurable_set.Union, intro n, apply measurable_set_generate_from, exact ⟨s, t n, hs, h1t n, rfl⟩ }, { rcases hC with ⟨t, h1t, h2t⟩, rw [← univ_prod, ← h2t, Union_prod_const], apply measurable_set.Union, rintro n, apply measurable_set_generate_from, exact mem_image2_of_mem (h1t n) hs } }, { apply generate_from_le, rintro _ ⟨s, t, hs, ht, rfl⟩, rw [prod_eq], apply (measurable_fst _).inter (measurable_snd _), { exact measurable_set_generate_from hs }, { exact measurable_set_generate_from ht } } end /-- If `C` and `D` generate the σ-algebras on `α` resp. `β`, then rectangles formed by `C` and `D` generate the σ-algebra on `α × β`. -/ lemma generate_from_eq_prod {C : set (set α)} {D : set (set β)} (hC : generate_from C = ‹_›) (hD : generate_from D = ‹_›) (h2C : is_countably_spanning C) (h2D : is_countably_spanning D) : generate_from (image2 (×ˢ) C D) = prod.measurable_space := by rw [← hC, ← hD, generate_from_prod_eq h2C h2D] /-- The product σ-algebra is generated from boxes, i.e. `s ×ˢ t` for sets `s : set α` and `t : set β`. -/ lemma generate_from_prod : generate_from (image2 (×ˢ) {s : set α | measurable_set s} {t : set β | measurable_set t}) = prod.measurable_space := generate_from_eq_prod generate_from_measurable_set generate_from_measurable_set is_countably_spanning_measurable_set is_countably_spanning_measurable_set /-- Rectangles form a π-system. -/ lemma is_pi_system_prod : is_pi_system (image2 (×ˢ) {s : set α | measurable_set s} {t : set β | measurable_set t}) := is_pi_system_measurable_set.prod is_pi_system_measurable_set /-- If `ν` is a finite measure, and `s ⊆ α × β` is measurable, then `x ↦ ν { y | (x, y) ∈ s }` is a measurable function. `measurable_measure_prod_mk_left` is strictly more general. -/ lemma measurable_measure_prod_mk_left_finite [is_finite_measure ν] {s : set (α × β)} (hs : measurable_set s) : measurable (λ x, ν (prod.mk x ⁻¹' s)) := begin refine induction_on_inter generate_from_prod.symm is_pi_system_prod _ _ _ _ hs, { simp [measurable_zero, const_def] }, { rintro _ ⟨s, t, hs, ht, rfl⟩, simp only [mk_preimage_prod_right_eq_if, measure_if], exact measurable_const.indicator hs }, { intros t ht h2t, simp_rw [preimage_compl, measure_compl (measurable_prod_mk_left ht) (measure_ne_top ν _)], exact h2t.const_sub _ }, { intros f h1f h2f h3f, simp_rw [preimage_Union], have : ∀ b, ν (⋃ i, prod.mk b ⁻¹' f i) = ∑' i, ν (prod.mk b ⁻¹' f i) := λ b, measure_Union (λ i j hij, disjoint.preimage _ (h1f hij)) (λ i, measurable_prod_mk_left (h2f i)), simp_rw [this], apply measurable.ennreal_tsum h3f }, end /-- If `ν` is a σ-finite measure, and `s ⊆ α × β` is measurable, then `x ↦ ν { y | (x, y) ∈ s }` is a measurable function. -/ lemma measurable_measure_prod_mk_left [sigma_finite ν] {s : set (α × β)} (hs : measurable_set s) : measurable (λ x, ν (prod.mk x ⁻¹' s)) := begin have : ∀ x, measurable_set (prod.mk x ⁻¹' s) := λ x, measurable_prod_mk_left hs, simp only [← @supr_restrict_spanning_sets _ _ ν, this], apply measurable_supr, intro i, haveI := fact.mk (measure_spanning_sets_lt_top ν i), exact measurable_measure_prod_mk_left_finite hs end /-- If `μ` is a σ-finite measure, and `s ⊆ α × β` is measurable, then `y ↦ μ { x | (x, y) ∈ s }` is a measurable function. -/ lemma measurable_measure_prod_mk_right {μ : measure α} [sigma_finite μ] {s : set (α × β)} (hs : measurable_set s) : measurable (λ y, μ ((λ x, (x, y)) ⁻¹' s)) := measurable_measure_prod_mk_left (measurable_set_swap_iff.mpr hs) lemma measurable.map_prod_mk_left [sigma_finite ν] : measurable (λ x : α, map (prod.mk x) ν) := begin apply measurable_of_measurable_coe, intros s hs, simp_rw [map_apply measurable_prod_mk_left hs], exact measurable_measure_prod_mk_left hs end lemma measurable.map_prod_mk_right {μ : measure α} [sigma_finite μ] : measurable (λ y : β, map (λ x : α, (x, y)) μ) := begin apply measurable_of_measurable_coe, intros s hs, simp_rw [map_apply measurable_prod_mk_right hs], exact measurable_measure_prod_mk_right hs end /-- The Lebesgue integral is measurable. This shows that the integrand of (the right-hand-side of) Tonelli's theorem is measurable. -/ lemma measurable.lintegral_prod_right' [sigma_finite ν] : ∀ {f : α × β → ℝ≥0∞} (hf : measurable f), measurable (λ x, ∫⁻ y, f (x, y) ∂ν) := begin have m := @measurable_prod_mk_left, refine measurable.ennreal_induction _ _ _, { intros c s hs, simp only [← indicator_comp_right], suffices : measurable (λ x, c * ν (prod.mk x ⁻¹' s)), { simpa [lintegral_indicator _ (m hs)] }, exact (measurable_measure_prod_mk_left hs).const_mul _ }, { rintro f g - hf hg h2f h2g, simp_rw [pi.add_apply, lintegral_add_left (hf.comp m)], exact h2f.add h2g }, { intros f hf h2f h3f, have := measurable_supr h3f, have : ∀ x, monotone (λ n y, f n (x, y)) := λ x i j hij y, h2f hij (x, y), simpa [lintegral_supr (λ n, (hf n).comp m), this] } end /-- The Lebesgue integral is measurable. This shows that the integrand of (the right-hand-side of) Tonelli's theorem is measurable. This version has the argument `f` in curried form. -/ lemma measurable.lintegral_prod_right [sigma_finite ν] {f : α → β → ℝ≥0∞} (hf : measurable (uncurry f)) : measurable (λ x, ∫⁻ y, f x y ∂ν) := hf.lintegral_prod_right' /-- The Lebesgue integral is measurable. This shows that the integrand of (the right-hand-side of) the symmetric version of Tonelli's theorem is measurable. -/ lemma measurable.lintegral_prod_left' [sigma_finite μ] {f : α × β → ℝ≥0∞} (hf : measurable f) : measurable (λ y, ∫⁻ x, f (x, y) ∂μ) := (measurable_swap_iff.mpr hf).lintegral_prod_right' /-- The Lebesgue integral is measurable. This shows that the integrand of (the right-hand-side of) the symmetric version of Tonelli's theorem is measurable. This version has the argument `f` in curried form. -/ lemma measurable.lintegral_prod_left [sigma_finite μ] {f : α → β → ℝ≥0∞} (hf : measurable (uncurry f)) : measurable (λ y, ∫⁻ x, f x y ∂μ) := hf.lintegral_prod_left' lemma measurable_set_integrable [sigma_finite ν] ⦃f : α → β → E⦄ (hf : strongly_measurable (uncurry f)) : measurable_set {x | integrable (f x) ν} := begin simp_rw [integrable, hf.of_uncurry_left.ae_strongly_measurable, true_and], exact measurable_set_lt (measurable.lintegral_prod_right hf.ennnorm) measurable_const end section variables [normed_space ℝ E] [complete_space E] /-- The Bochner integral is measurable. This shows that the integrand of (the right-hand-side of) Fubini's theorem is measurable. This version has `f` in curried form. -/ lemma measure_theory.strongly_measurable.integral_prod_right [sigma_finite ν] ⦃f : α → β → E⦄ (hf : strongly_measurable (uncurry f)) : strongly_measurable (λ x, ∫ y, f x y ∂ν) := begin borelize E, haveI : separable_space (range (uncurry f) ∪ {0} : set E) := hf.separable_space_range_union_singleton, let s : ℕ → simple_func (α × β) E := simple_func.approx_on _ hf.measurable (range (uncurry f) ∪ {0}) 0 (by simp), let s' : ℕ → α → simple_func β E := λ n x, (s n).comp (prod.mk x) measurable_prod_mk_left, let f' : ℕ → α → E := λ n, {x | integrable (f x) ν}.indicator (λ x, (s' n x).integral ν), have hf' : ∀ n, strongly_measurable (f' n), { intro n, refine strongly_measurable.indicator _ (measurable_set_integrable hf), have : ∀ x, (s' n x).range.filter (λ x, x ≠ 0) ⊆ (s n).range, { intros x, refine finset.subset.trans (finset.filter_subset _ _) _, intro y, simp_rw [simple_func.mem_range], rintro ⟨z, rfl⟩, exact ⟨(x, z), rfl⟩ }, simp only [simple_func.integral_eq_sum_of_subset (this _)], refine finset.strongly_measurable_sum _ (λ x _, _), refine (measurable.ennreal_to_real _).strongly_measurable.smul_const _, simp only [simple_func.coe_comp, preimage_comp] {single_pass := tt}, apply measurable_measure_prod_mk_left, exact (s n).measurable_set_fiber x }, have h2f' : tendsto f' at_top (𝓝 (λ (x : α), ∫ (y : β), f x y ∂ν)), { rw [tendsto_pi_nhds], intro x, by_cases hfx : integrable (f x) ν, { have : ∀ n, integrable (s' n x) ν, { intro n, apply (hfx.norm.add hfx.norm).mono' (s' n x).ae_strongly_measurable, apply eventually_of_forall, intro y, simp_rw [s', simple_func.coe_comp], exact simple_func.norm_approx_on_zero_le _ _ (x, y) n }, simp only [f', hfx, simple_func.integral_eq_integral _ (this _), indicator_of_mem, mem_set_of_eq], refine tendsto_integral_of_dominated_convergence (λ y, ‖f x y‖ + ‖f x y‖) (λ n, (s' n x).ae_strongly_measurable) (hfx.norm.add hfx.norm) _ _, { exact λ n, eventually_of_forall (λ y, simple_func.norm_approx_on_zero_le _ _ (x, y) n) }, { refine eventually_of_forall (λ y, simple_func.tendsto_approx_on _ _ _), apply subset_closure, simp [-uncurry_apply_pair], } }, { simpa [f', hfx, integral_undef] using @tendsto_const_nhds _ _ _ (0 : E) _, } }, exact strongly_measurable_of_tendsto _ hf' h2f' end /-- The Bochner integral is measurable. This shows that the integrand of (the right-hand-side of) Fubini's theorem is measurable. -/ lemma measure_theory.strongly_measurable.integral_prod_right' [sigma_finite ν] ⦃f : α × β → E⦄ (hf : strongly_measurable f) : strongly_measurable (λ x, ∫ y, f (x, y) ∂ν) := by { rw [← uncurry_curry f] at hf, exact hf.integral_prod_right } /-- The Bochner integral is measurable. This shows that the integrand of (the right-hand-side of) the symmetric version of Fubini's theorem is measurable. This version has `f` in curried form. -/ lemma measure_theory.strongly_measurable.integral_prod_left [sigma_finite μ] ⦃f : α → β → E⦄ (hf : strongly_measurable (uncurry f)) : strongly_measurable (λ y, ∫ x, f x y ∂μ) := (hf.comp_measurable measurable_swap).integral_prod_right' /-- The Bochner integral is measurable. This shows that the integrand of (the right-hand-side of) the symmetric version of Fubini's theorem is measurable. -/ lemma measure_theory.strongly_measurable.integral_prod_left' [sigma_finite μ] ⦃f : α × β → E⦄ (hf : strongly_measurable f) : strongly_measurable (λ y, ∫ x, f (x, y) ∂μ) := (hf.comp_measurable measurable_swap).integral_prod_right' end /-! ### The product measure -/ namespace measure_theory namespace measure /-- The binary product of measures. They are defined for arbitrary measures, but we basically prove all properties under the assumption that at least one of them is σ-finite. -/ @[irreducible] protected def prod (μ : measure α) (ν : measure β) : measure (α × β) := bind μ $ λ x : α, map (prod.mk x) ν instance prod.measure_space {α β} [measure_space α] [measure_space β] : measure_space (α × β) := { volume := volume.prod volume } variables [sigma_finite ν] lemma volume_eq_prod (α β) [measure_space α] [measure_space β] : (volume : measure (α × β)) = (volume : measure α).prod (volume : measure β) := rfl lemma prod_apply {s : set (α × β)} (hs : measurable_set s) : μ.prod ν s = ∫⁻ x, ν (prod.mk x ⁻¹' s) ∂μ := by simp_rw [measure.prod, bind_apply hs measurable.map_prod_mk_left, map_apply measurable_prod_mk_left hs] /-- The product measure of the product of two sets is the product of their measures. Note that we do not need the sets to be measurable. -/ @[simp] lemma prod_prod (s : set α) (t : set β) : μ.prod ν (s ×ˢ t) = μ s * ν t := begin apply le_antisymm, { set ST := (to_measurable μ s) ×ˢ (to_measurable ν t), have hSTm : measurable_set ST := (measurable_set_to_measurable _ _).prod (measurable_set_to_measurable _ _), calc μ.prod ν (s ×ˢ t) ≤ μ.prod ν ST : measure_mono $ set.prod_mono (subset_to_measurable _ _) (subset_to_measurable _ _) ... = μ (to_measurable μ s) * ν (to_measurable ν t) : by simp_rw [prod_apply hSTm, mk_preimage_prod_right_eq_if, measure_if, lintegral_indicator _ (measurable_set_to_measurable _ _), lintegral_const, restrict_apply_univ, mul_comm] ... = μ s * ν t : by rw [measure_to_measurable, measure_to_measurable] }, { /- Formalization is based on https://mathoverflow.net/a/254134/136589 -/ set ST := to_measurable (μ.prod ν) (s ×ˢ t), have hSTm : measurable_set ST := measurable_set_to_measurable _ _, have hST : s ×ˢ t ⊆ ST := subset_to_measurable _ _, set f : α → ℝ≥0∞ := λ x, ν (prod.mk x ⁻¹' ST), have hfm : measurable f := measurable_measure_prod_mk_left hSTm, set s' : set α := {x | ν t ≤ f x}, have hss' : s ⊆ s' := λ x hx, measure_mono (λ y hy, hST $ mk_mem_prod hx hy), calc μ s * ν t ≤ μ s' * ν t : mul_le_mul_right' (measure_mono hss') _ ... = ∫⁻ x in s', ν t ∂μ : by rw [set_lintegral_const, mul_comm] ... ≤ ∫⁻ x in s', f x ∂μ : set_lintegral_mono measurable_const hfm (λ x, id) ... ≤ ∫⁻ x, f x ∂μ : lintegral_mono' restrict_le_self le_rfl ... = μ.prod ν ST : (prod_apply hSTm).symm ... = μ.prod ν (s ×ˢ t) : measure_to_measurable _ } end instance {X Y : Type*} [topological_space X] [topological_space Y] {m : measurable_space X} {μ : measure X} [is_open_pos_measure μ] {m' : measurable_space Y} {ν : measure Y} [is_open_pos_measure ν] [sigma_finite ν] : is_open_pos_measure (μ.prod ν) := begin constructor, rintros U U_open ⟨⟨x, y⟩, hxy⟩, rcases is_open_prod_iff.1 U_open x y hxy with ⟨u, v, u_open, v_open, xu, yv, huv⟩, refine ne_of_gt (lt_of_lt_of_le _ (measure_mono huv)), simp only [prod_prod, canonically_ordered_comm_semiring.mul_pos], split, { exact u_open.measure_pos μ ⟨x, xu⟩ }, { exact v_open.measure_pos ν ⟨y, yv⟩ } end instance {α β : Type*} {mα : measurable_space α} {mβ : measurable_space β} (μ : measure α) (ν : measure β) [is_finite_measure μ] [is_finite_measure ν] : is_finite_measure (μ.prod ν) := begin constructor, rw [← univ_prod_univ, prod_prod], exact mul_lt_top (measure_lt_top _ _).ne (measure_lt_top _ _).ne, end instance {α β : Type*} {mα : measurable_space α} {mβ : measurable_space β} (μ : measure α) (ν : measure β) [is_probability_measure μ] [is_probability_measure ν] : is_probability_measure (μ.prod ν) := ⟨by rw [← univ_prod_univ, prod_prod, measure_univ, measure_univ, mul_one]⟩ instance {α β : Type*} [topological_space α] [topological_space β] {mα : measurable_space α} {mβ : measurable_space β} (μ : measure α) (ν : measure β) [is_finite_measure_on_compacts μ] [is_finite_measure_on_compacts ν] [sigma_finite ν] : is_finite_measure_on_compacts (μ.prod ν) := begin refine ⟨λ K hK, _⟩, set L := (prod.fst '' K) ×ˢ (prod.snd '' K) with hL, have : K ⊆ L, { rintros ⟨x, y⟩ hxy, simp only [prod_mk_mem_set_prod_eq, mem_image, prod.exists, exists_and_distrib_right, exists_eq_right], exact ⟨⟨y, hxy⟩, ⟨x, hxy⟩⟩ }, apply lt_of_le_of_lt (measure_mono this), rw [hL, prod_prod], exact mul_lt_top ((is_compact.measure_lt_top ((hK.image continuous_fst))).ne) ((is_compact.measure_lt_top ((hK.image continuous_snd))).ne) end lemma ae_measure_lt_top {s : set (α × β)} (hs : measurable_set s) (h2s : (μ.prod ν) s ≠ ∞) : ∀ᵐ x ∂μ, ν (prod.mk x ⁻¹' s) < ∞ := by { simp_rw [prod_apply hs] at h2s, refine ae_lt_top (measurable_measure_prod_mk_left hs) h2s } lemma integrable_measure_prod_mk_left {s : set (α × β)} (hs : measurable_set s) (h2s : (μ.prod ν) s ≠ ∞) : integrable (λ x, (ν (prod.mk x ⁻¹' s)).to_real) μ := begin refine ⟨(measurable_measure_prod_mk_left hs).ennreal_to_real.ae_measurable.ae_strongly_measurable, _⟩, simp_rw [has_finite_integral, ennnorm_eq_of_real to_real_nonneg], convert h2s.lt_top using 1, simp_rw [prod_apply hs], apply lintegral_congr_ae, refine (ae_measure_lt_top hs h2s).mp _, apply eventually_of_forall, intros x hx, rw [lt_top_iff_ne_top] at hx, simp [of_real_to_real, hx], end /-- Note: the assumption `hs` cannot be dropped. For a counterexample, see Walter Rudin *Real and Complex Analysis*, example (c) in section 8.9. -/ lemma measure_prod_null {s : set (α × β)} (hs : measurable_set s) : μ.prod ν s = 0 ↔ (λ x, ν (prod.mk x ⁻¹' s)) =ᵐ[μ] 0 := by simp_rw [prod_apply hs, lintegral_eq_zero_iff (measurable_measure_prod_mk_left hs)] /-- Note: the converse is not true without assuming that `s` is measurable. For a counterexample, see Walter Rudin *Real and Complex Analysis*, example (c) in section 8.9. -/ lemma measure_ae_null_of_prod_null {s : set (α × β)} (h : μ.prod ν s = 0) : (λ x, ν (prod.mk x ⁻¹' s)) =ᵐ[μ] 0 := begin obtain ⟨t, hst, mt, ht⟩ := exists_measurable_superset_of_null h, simp_rw [measure_prod_null mt] at ht, rw [eventually_le_antisymm_iff], exact ⟨eventually_le.trans_eq (eventually_of_forall $ λ x, (measure_mono (preimage_mono hst) : _)) ht, eventually_of_forall $ λ x, zero_le _⟩ end lemma absolutely_continuous.prod [sigma_finite ν'] (h1 : μ ≪ μ') (h2 : ν ≪ ν') : μ.prod ν ≪ μ'.prod ν' := begin refine absolutely_continuous.mk (λ s hs h2s, _), simp_rw [measure_prod_null hs] at h2s ⊢, exact (h2s.filter_mono h1.ae_le).mono (λ _ h, h2 h) end /-- Note: the converse is not true. For a counterexample, see Walter Rudin *Real and Complex Analysis*, example (c) in section 8.9. -/ lemma ae_ae_of_ae_prod {p : α × β → Prop} (h : ∀ᵐ z ∂μ.prod ν, p z) : ∀ᵐ x ∂ μ, ∀ᵐ y ∂ ν, p (x, y) := measure_ae_null_of_prod_null h /-- `μ.prod ν` has finite spanning sets in rectangles of finite spanning sets. -/ noncomputable! def finite_spanning_sets_in.prod {ν : measure β} {C : set (set α)} {D : set (set β)} (hμ : μ.finite_spanning_sets_in C) (hν : ν.finite_spanning_sets_in D) : (μ.prod ν).finite_spanning_sets_in (image2 (×ˢ) C D) := begin haveI := hν.sigma_finite, refine ⟨λ n, hμ.set n.unpair.1 ×ˢ hν.set n.unpair.2, λ n, mem_image2_of_mem (hμ.set_mem _) (hν.set_mem _), λ n, _, _⟩, { rw [prod_prod], exact mul_lt_top (hμ.finite _).ne (hν.finite _).ne }, { simp_rw [Union_unpair_prod, hμ.spanning, hν.spanning, univ_prod_univ] } end lemma quasi_measure_preserving_fst : quasi_measure_preserving prod.fst (μ.prod ν) μ := begin refine ⟨measurable_fst, absolutely_continuous.mk (λ s hs h2s, _)⟩, rw [map_apply measurable_fst hs, ← prod_univ, prod_prod, h2s, zero_mul], end lemma quasi_measure_preserving_snd : quasi_measure_preserving prod.snd (μ.prod ν) ν := begin refine ⟨measurable_snd, absolutely_continuous.mk (λ s hs h2s, _)⟩, rw [map_apply measurable_snd hs, ← univ_prod, prod_prod, h2s, mul_zero] end variables [sigma_finite μ] instance prod.sigma_finite : sigma_finite (μ.prod ν) := (μ.to_finite_spanning_sets_in.prod ν.to_finite_spanning_sets_in).sigma_finite /-- A measure on a product space equals the product measure if they are equal on rectangles with as sides sets that generate the corresponding σ-algebras. -/ lemma prod_eq_generate_from {μ : measure α} {ν : measure β} {C : set (set α)} {D : set (set β)} (hC : generate_from C = ‹_›) (hD : generate_from D = ‹_›) (h2C : is_pi_system C) (h2D : is_pi_system D) (h3C : μ.finite_spanning_sets_in C) (h3D : ν.finite_spanning_sets_in D) {μν : measure (α × β)} (h₁ : ∀ (s ∈ C) (t ∈ D), μν (s ×ˢ t) = μ s * ν t) : μ.prod ν = μν := begin refine (h3C.prod h3D).ext (generate_from_eq_prod hC hD h3C.is_countably_spanning h3D.is_countably_spanning).symm (h2C.prod h2D) _, { rintro _ ⟨s, t, hs, ht, rfl⟩, haveI := h3D.sigma_finite, rw [h₁ s hs t ht, prod_prod] } end /-- A measure on a product space equals the product measure if they are equal on rectangles. -/ lemma prod_eq {μν : measure (α × β)} (h : ∀ s t, measurable_set s → measurable_set t → μν (s ×ˢ t) = μ s * ν t) : μ.prod ν = μν := prod_eq_generate_from generate_from_measurable_set generate_from_measurable_set is_pi_system_measurable_set is_pi_system_measurable_set μ.to_finite_spanning_sets_in ν.to_finite_spanning_sets_in (λ s hs t ht, h s t hs ht) lemma prod_swap : map prod.swap (μ.prod ν) = ν.prod μ := begin refine (prod_eq _).symm, intros s t hs ht, simp_rw [map_apply measurable_swap (hs.prod ht), preimage_swap_prod, prod_prod, mul_comm] end lemma measure_preserving_swap : measure_preserving prod.swap (μ.prod ν) (ν.prod μ) := ⟨measurable_swap, prod_swap⟩ lemma prod_apply_symm {s : set (α × β)} (hs : measurable_set s) : μ.prod ν s = ∫⁻ y, μ ((λ x, (x, y)) ⁻¹' s) ∂ν := by { rw [← prod_swap, map_apply measurable_swap hs], simp only [prod_apply (measurable_swap hs)], refl } lemma prod_assoc_prod [sigma_finite τ] : map measurable_equiv.prod_assoc ((μ.prod ν).prod τ) = μ.prod (ν.prod τ) := begin refine (prod_eq_generate_from generate_from_measurable_set generate_from_prod is_pi_system_measurable_set is_pi_system_prod μ.to_finite_spanning_sets_in (ν.to_finite_spanning_sets_in.prod τ.to_finite_spanning_sets_in) _).symm, rintro s hs _ ⟨t, u, ht, hu, rfl⟩, rw [mem_set_of_eq] at hs ht hu, simp_rw [map_apply (measurable_equiv.measurable _) (hs.prod (ht.prod hu)), measurable_equiv.prod_assoc, measurable_equiv.coe_mk, equiv.prod_assoc_preimage, prod_prod, mul_assoc] end /-! ### The product of specific measures -/ lemma prod_restrict (s : set α) (t : set β) : (μ.restrict s).prod (ν.restrict t) = (μ.prod ν).restrict (s ×ˢ t) := begin refine prod_eq (λ s' t' hs' ht', _), rw [restrict_apply (hs'.prod ht'), prod_inter_prod, prod_prod, restrict_apply hs', restrict_apply ht'] end lemma restrict_prod_eq_prod_univ (s : set α) : (μ.restrict s).prod ν = (μ.prod ν).restrict (s ×ˢ (univ : set β)) := begin have : ν = ν.restrict set.univ := measure.restrict_univ.symm, rwa [this, measure.prod_restrict, ← this], end lemma prod_dirac (y : β) : μ.prod (dirac y) = map (λ x, (x, y)) μ := begin refine prod_eq (λ s t hs ht, _), simp_rw [map_apply measurable_prod_mk_right (hs.prod ht), mk_preimage_prod_left_eq_if, measure_if, dirac_apply' _ ht, ← indicator_mul_right _ (λ x, μ s), pi.one_apply, mul_one] end lemma dirac_prod (x : α) : (dirac x).prod ν = map (prod.mk x) ν := begin refine prod_eq (λ s t hs ht, _), simp_rw [map_apply measurable_prod_mk_left (hs.prod ht), mk_preimage_prod_right_eq_if, measure_if, dirac_apply' _ hs, ← indicator_mul_left _ _ (λ x, ν t), pi.one_apply, one_mul] end lemma dirac_prod_dirac {x : α} {y : β} : (dirac x).prod (dirac y) = dirac (x, y) := by rw [prod_dirac, map_dirac measurable_prod_mk_right] lemma prod_sum {ι : Type*} [finite ι] (ν : ι → measure β) [∀ i, sigma_finite (ν i)] : μ.prod (sum ν) = sum (λ i, μ.prod (ν i)) := begin refine prod_eq (λ s t hs ht, _), simp_rw [sum_apply _ (hs.prod ht), sum_apply _ ht, prod_prod, ennreal.tsum_mul_left] end lemma sum_prod {ι : Type*} [finite ι] (μ : ι → measure α) [∀ i, sigma_finite (μ i)] : (sum μ).prod ν = sum (λ i, (μ i).prod ν) := begin refine prod_eq (λ s t hs ht, _), simp_rw [sum_apply _ (hs.prod ht), sum_apply _ hs, prod_prod, ennreal.tsum_mul_right] end lemma prod_add (ν' : measure β) [sigma_finite ν'] : μ.prod (ν + ν') = μ.prod ν + μ.prod ν' := by { refine prod_eq (λ s t hs ht, _), simp_rw [add_apply, prod_prod, left_distrib] } lemma add_prod (μ' : measure α) [sigma_finite μ'] : (μ + μ').prod ν = μ.prod ν + μ'.prod ν := by { refine prod_eq (λ s t hs ht, _), simp_rw [add_apply, prod_prod, right_distrib] } @[simp] lemma zero_prod (ν : measure β) : (0 : measure α).prod ν = 0 := by { rw measure.prod, exact bind_zero_left _ } @[simp] lemma prod_zero (μ : measure α) : μ.prod (0 : measure β) = 0 := by simp [measure.prod] lemma map_prod_map {δ} [measurable_space δ] {f : α → β} {g : γ → δ} {μa : measure α} {μc : measure γ} (hfa : sigma_finite (map f μa)) (hgc : sigma_finite (map g μc)) (hf : measurable f) (hg : measurable g) : (map f μa).prod (map g μc) = map (prod.map f g) (μa.prod μc) := begin haveI := hgc.of_map μc hg.ae_measurable, refine prod_eq (λ s t hs ht, _), rw [map_apply (hf.prod_map hg) (hs.prod ht), map_apply hf hs, map_apply hg ht], exact prod_prod (f ⁻¹' s) (g ⁻¹' t) end end measure open measure namespace measure_preserving variables {δ : Type*} [measurable_space δ] {μa : measure α} {μb : measure β} {μc : measure γ} {μd : measure δ} lemma skew_product [sigma_finite μb] [sigma_finite μd] {f : α → β} (hf : measure_preserving f μa μb) {g : α → γ → δ} (hgm : measurable (uncurry g)) (hg : ∀ᵐ x ∂μa, map (g x) μc = μd) : measure_preserving (λ p : α × γ, (f p.1, g p.1 p.2)) (μa.prod μc) (μb.prod μd) := begin classical, have : measurable (λ p : α × γ, (f p.1, g p.1 p.2)) := (hf.1.comp measurable_fst).prod_mk hgm, /- if `μa = 0`, then the lemma is trivial, otherwise we can use `hg` to deduce `sigma_finite μc`. -/ rcases eq_or_ne μa 0 with (rfl|ha), { rw [← hf.map_eq, zero_prod, measure.map_zero, zero_prod], exact ⟨this, by simp only [measure.map_zero]⟩ }, haveI : sigma_finite μc, { rcases (ae_ne_bot.2 ha).nonempty_of_mem hg with ⟨x, hx : map (g x) μc = μd⟩, exact sigma_finite.of_map _ hgm.of_uncurry_left.ae_measurable (by rwa hx) }, -- Thus we can apply `measure.prod_eq` to prove equality of measures. refine ⟨this, (prod_eq $ λ s t hs ht, _).symm⟩, rw [map_apply this (hs.prod ht)], refine (prod_apply (this $ hs.prod ht)).trans _, have : ∀ᵐ x ∂μa, μc ((λ y, (f x, g x y)) ⁻¹' s ×ˢ t) = indicator (f ⁻¹' s) (λ y, μd t) x, { refine hg.mono (λ x hx, _), unfreezingI { subst hx }, simp only [mk_preimage_prod_right_fn_eq_if, indicator_apply, mem_preimage], split_ifs, exacts [(map_apply hgm.of_uncurry_left ht).symm, measure_empty] }, simp only [preimage_preimage], rw [lintegral_congr_ae this, lintegral_indicator _ (hf.1 hs), set_lintegral_const, hf.measure_preimage hs, mul_comm] end /-- If `f : α → β` sends the measure `μa` to `μb` and `g : γ → δ` sends the measure `μc` to `μd`, then `prod.map f g` sends `μa.prod μc` to `μb.prod μd`. -/ protected lemma prod [sigma_finite μb] [sigma_finite μd] {f : α → β} {g : γ → δ} (hf : measure_preserving f μa μb) (hg : measure_preserving g μc μd) : measure_preserving (prod.map f g) (μa.prod μc) (μb.prod μd) := have measurable (uncurry $ λ _ : α, g), from (hg.1.comp measurable_snd), hf.skew_product this $ filter.eventually_of_forall $ λ _, hg.map_eq end measure_preserving namespace quasi_measure_preserving lemma prod_of_right {f : α × β → γ} {μ : measure α} {ν : measure β} {τ : measure γ} (hf : measurable f) [sigma_finite ν] (h2f : ∀ᵐ x ∂μ, quasi_measure_preserving (λ y, f (x, y)) ν τ) : quasi_measure_preserving f (μ.prod ν) τ := begin refine ⟨hf, _⟩, refine absolutely_continuous.mk (λ s hs h2s, _), simp_rw [map_apply hf hs, prod_apply (hf hs), preimage_preimage, lintegral_congr_ae (h2f.mono (λ x hx, hx.preimage_null h2s)), lintegral_zero], end lemma prod_of_left {α β γ} [measurable_space α] [measurable_space β] [measurable_space γ] {f : α × β → γ} {μ : measure α} {ν : measure β} {τ : measure γ} (hf : measurable f) [sigma_finite μ] [sigma_finite ν] (h2f : ∀ᵐ y ∂ν, quasi_measure_preserving (λ x, f (x, y)) μ τ) : quasi_measure_preserving f (μ.prod ν) τ := begin rw [← prod_swap], convert (quasi_measure_preserving.prod_of_right (hf.comp measurable_swap) h2f).comp ((measurable_swap.measure_preserving (ν.prod μ)).symm measurable_equiv.prod_comm) .quasi_measure_preserving, ext ⟨x, y⟩, refl, end end quasi_measure_preserving end measure_theory open measure_theory.measure section lemma ae_measurable.prod_swap [sigma_finite μ] [sigma_finite ν] {f : β × α → γ} (hf : ae_measurable f (ν.prod μ)) : ae_measurable (λ (z : α × β), f z.swap) (μ.prod ν) := by { rw ← prod_swap at hf, exact hf.comp_measurable measurable_swap } lemma measure_theory.ae_strongly_measurable.prod_swap {γ : Type*} [topological_space γ] [sigma_finite μ] [sigma_finite ν] {f : β × α → γ} (hf : ae_strongly_measurable f (ν.prod μ)) : ae_strongly_measurable (λ (z : α × β), f z.swap) (μ.prod ν) := by { rw ← prod_swap at hf, exact hf.comp_measurable measurable_swap } lemma ae_measurable.fst [sigma_finite ν] {f : α → γ} (hf : ae_measurable f μ) : ae_measurable (λ (z : α × β), f z.1) (μ.prod ν) := hf.comp_quasi_measure_preserving quasi_measure_preserving_fst lemma ae_measurable.snd [sigma_finite ν] {f : β → γ} (hf : ae_measurable f ν) : ae_measurable (λ (z : α × β), f z.2) (μ.prod ν) := hf.comp_quasi_measure_preserving quasi_measure_preserving_snd lemma measure_theory.ae_strongly_measurable.fst {γ} [topological_space γ] [sigma_finite ν] {f : α → γ} (hf : ae_strongly_measurable f μ) : ae_strongly_measurable (λ (z : α × β), f z.1) (μ.prod ν) := hf.comp_quasi_measure_preserving quasi_measure_preserving_fst lemma measure_theory.ae_strongly_measurable.snd {γ} [topological_space γ] [sigma_finite ν] {f : β → γ} (hf : ae_strongly_measurable f ν) : ae_strongly_measurable (λ (z : α × β), f z.2) (μ.prod ν) := hf.comp_quasi_measure_preserving quasi_measure_preserving_snd /-- The Bochner integral is a.e.-measurable. This shows that the integrand of (the right-hand-side of) Fubini's theorem is a.e.-measurable. -/ lemma measure_theory.ae_strongly_measurable.integral_prod_right' [sigma_finite ν] [normed_space ℝ E] [complete_space E] ⦃f : α × β → E⦄ (hf : ae_strongly_measurable f (μ.prod ν)) : ae_strongly_measurable (λ x, ∫ y, f (x, y) ∂ν) μ := ⟨λ x, ∫ y, hf.mk f (x, y) ∂ν, hf.strongly_measurable_mk.integral_prod_right', by { filter_upwards [ae_ae_of_ae_prod hf.ae_eq_mk] with _ hx using integral_congr_ae hx }⟩ lemma measure_theory.ae_strongly_measurable.prod_mk_left {γ : Type*} [sigma_finite ν] [topological_space γ] {f : α × β → γ} (hf : ae_strongly_measurable f (μ.prod ν)) : ∀ᵐ x ∂μ, ae_strongly_measurable (λ y, f (x, y)) ν := begin filter_upwards [ae_ae_of_ae_prod hf.ae_eq_mk] with x hx, exact ⟨λ y, hf.mk f (x, y), hf.strongly_measurable_mk.comp_measurable measurable_prod_mk_left, hx⟩ end end namespace measure_theory /-! ### The Lebesgue integral on a product -/ variables [sigma_finite ν] lemma lintegral_prod_swap [sigma_finite μ] (f : α × β → ℝ≥0∞) (hf : ae_measurable f (μ.prod ν)) : ∫⁻ z, f z.swap ∂(ν.prod μ) = ∫⁻ z, f z ∂(μ.prod ν) := by { rw ← prod_swap at hf, rw [← lintegral_map' hf measurable_swap.ae_measurable, prod_swap] } /-- **Tonelli's Theorem**: For `ℝ≥0∞`-valued measurable functions on `α × β`, the integral of `f` is equal to the iterated integral. -/ lemma lintegral_prod_of_measurable : ∀ (f : α × β → ℝ≥0∞) (hf : measurable f), ∫⁻ z, f z ∂(μ.prod ν) = ∫⁻ x, ∫⁻ y, f (x, y) ∂ν ∂μ := begin have m := @measurable_prod_mk_left, refine measurable.ennreal_induction _ _ _, { intros c s hs, simp only [← indicator_comp_right], simp [lintegral_indicator, m hs, hs, lintegral_const_mul, measurable_measure_prod_mk_left hs, prod_apply] }, { rintro f g - hf hg h2f h2g, simp [lintegral_add_left, measurable.lintegral_prod_right', hf.comp m, hf, h2f, h2g] }, { intros f hf h2f h3f, have kf : ∀ x n, measurable (λ y, f n (x, y)) := λ x n, (hf n).comp m, have k2f : ∀ x, monotone (λ n y, f n (x, y)) := λ x i j hij y, h2f hij (x, y), have lf : ∀ n, measurable (λ x, ∫⁻ y, f n (x, y) ∂ν) := λ n, (hf n).lintegral_prod_right', have l2f : monotone (λ n x, ∫⁻ y, f n (x, y) ∂ν) := λ i j hij x, lintegral_mono (k2f x hij), simp only [lintegral_supr hf h2f, lintegral_supr (kf _), k2f, lintegral_supr lf l2f, h3f] }, end /-- **Tonelli's Theorem**: For `ℝ≥0∞`-valued almost everywhere measurable functions on `α × β`, the integral of `f` is equal to the iterated integral. -/ lemma lintegral_prod (f : α × β → ℝ≥0∞) (hf : ae_measurable f (μ.prod ν)) : ∫⁻ z, f z ∂(μ.prod ν) = ∫⁻ x, ∫⁻ y, f (x, y) ∂ν ∂μ := begin have A : ∫⁻ z, f z ∂(μ.prod ν) = ∫⁻ z, hf.mk f z ∂(μ.prod ν) := lintegral_congr_ae hf.ae_eq_mk, have B : ∫⁻ x, ∫⁻ y, f (x, y) ∂ν ∂μ = ∫⁻ x, ∫⁻ y, hf.mk f (x, y) ∂ν ∂μ, { apply lintegral_congr_ae, filter_upwards [ae_ae_of_ae_prod hf.ae_eq_mk] with _ ha using lintegral_congr_ae ha, }, rw [A, B, lintegral_prod_of_measurable _ hf.measurable_mk], apply_instance end /-- The symmetric verion of Tonelli's Theorem: For `ℝ≥0∞`-valued almost everywhere measurable functions on `α × β`, the integral of `f` is equal to the iterated integral, in reverse order. -/ lemma lintegral_prod_symm [sigma_finite μ] (f : α × β → ℝ≥0∞) (hf : ae_measurable f (μ.prod ν)) : ∫⁻ z, f z ∂(μ.prod ν) = ∫⁻ y, ∫⁻ x, f (x, y) ∂μ ∂ν := by { simp_rw [← lintegral_prod_swap f hf], exact lintegral_prod _ hf.prod_swap } /-- The symmetric verion of Tonelli's Theorem: For `ℝ≥0∞`-valued measurable functions on `α × β`, the integral of `f` is equal to the iterated integral, in reverse order. -/ lemma lintegral_prod_symm' [sigma_finite μ] (f : α × β → ℝ≥0∞) (hf : measurable f) : ∫⁻ z, f z ∂(μ.prod ν) = ∫⁻ y, ∫⁻ x, f (x, y) ∂μ ∂ν := lintegral_prod_symm f hf.ae_measurable /-- The reversed version of **Tonelli's Theorem**. In this version `f` is in curried form, which makes it easier for the elaborator to figure out `f` automatically. -/ lemma lintegral_lintegral ⦃f : α → β → ℝ≥0∞⦄ (hf : ae_measurable (uncurry f) (μ.prod ν)) : ∫⁻ x, ∫⁻ y, f x y ∂ν ∂μ = ∫⁻ z, f z.1 z.2 ∂(μ.prod ν) := (lintegral_prod _ hf).symm /-- The reversed version of **Tonelli's Theorem** (symmetric version). In this version `f` is in curried form, which makes it easier for the elaborator to figure out `f` automatically. -/ lemma lintegral_lintegral_symm [sigma_finite μ] ⦃f : α → β → ℝ≥0∞⦄ (hf : ae_measurable (uncurry f) (μ.prod ν)) : ∫⁻ x, ∫⁻ y, f x y ∂ν ∂μ = ∫⁻ z, f z.2 z.1 ∂(ν.prod μ) := (lintegral_prod_symm _ hf.prod_swap).symm /-- Change the order of Lebesgue integration. -/ lemma lintegral_lintegral_swap [sigma_finite μ] ⦃f : α → β → ℝ≥0∞⦄ (hf : ae_measurable (uncurry f) (μ.prod ν)) : ∫⁻ x, ∫⁻ y, f x y ∂ν ∂μ = ∫⁻ y, ∫⁻ x, f x y ∂μ ∂ν := (lintegral_lintegral hf).trans (lintegral_prod_symm _ hf) lemma lintegral_prod_mul {f : α → ℝ≥0∞} {g : β → ℝ≥0∞} (hf : ae_measurable f μ) (hg : ae_measurable g ν) : ∫⁻ z, f z.1 * g z.2 ∂(μ.prod ν) = ∫⁻ x, f x ∂μ * ∫⁻ y, g y ∂ν := by simp [lintegral_prod _ (hf.fst.mul hg.snd), lintegral_lintegral_mul hf hg] /-! ### Integrability on a product -/ section lemma integrable.swap [sigma_finite μ] ⦃f : α × β → E⦄ (hf : integrable f (μ.prod ν)) : integrable (f ∘ prod.swap) (ν.prod μ) := ⟨hf.ae_strongly_measurable.prod_swap, (lintegral_prod_swap _ hf.ae_strongly_measurable.ennnorm : _).le.trans_lt hf.has_finite_integral⟩ lemma integrable_swap_iff [sigma_finite μ] ⦃f : α × β → E⦄ : integrable (f ∘ prod.swap) (ν.prod μ) ↔ integrable f (μ.prod ν) := ⟨λ hf, by { convert hf.swap, ext ⟨x, y⟩, refl }, λ hf, hf.swap⟩ lemma has_finite_integral_prod_iff ⦃f : α × β → E⦄ (h1f : strongly_measurable f) : has_finite_integral f (μ.prod ν) ↔ (∀ᵐ x ∂ μ, has_finite_integral (λ y, f (x, y)) ν) ∧ has_finite_integral (λ x, ∫ y, ‖f (x, y)‖ ∂ν) μ := begin simp only [has_finite_integral, lintegral_prod_of_measurable _ h1f.ennnorm], have : ∀ x, ∀ᵐ y ∂ν, 0 ≤ ‖f (x, y)‖ := λ x, eventually_of_forall (λ y, norm_nonneg _), simp_rw [integral_eq_lintegral_of_nonneg_ae (this _) (h1f.norm.comp_measurable measurable_prod_mk_left).ae_strongly_measurable, ennnorm_eq_of_real to_real_nonneg, of_real_norm_eq_coe_nnnorm], -- this fact is probably too specialized to be its own lemma have : ∀ {p q r : Prop} (h1 : r → p), (r ↔ p ∧ q) ↔ (p → (r ↔ q)) := λ p q r h1, by rw [← and.congr_right_iff, and_iff_right_of_imp h1], rw [this], { intro h2f, rw lintegral_congr_ae, refine h2f.mp _, apply eventually_of_forall, intros x hx, dsimp only, rw [of_real_to_real], rw [← lt_top_iff_ne_top], exact hx }, { intro h2f, refine ae_lt_top _ h2f.ne, exact h1f.ennnorm.lintegral_prod_right' }, end lemma has_finite_integral_prod_iff' ⦃f : α × β → E⦄ (h1f : ae_strongly_measurable f (μ.prod ν)) : has_finite_integral f (μ.prod ν) ↔ (∀ᵐ x ∂ μ, has_finite_integral (λ y, f (x, y)) ν) ∧ has_finite_integral (λ x, ∫ y, ‖f (x, y)‖ ∂ν) μ := begin rw [has_finite_integral_congr h1f.ae_eq_mk, has_finite_integral_prod_iff h1f.strongly_measurable_mk], apply and_congr, { apply eventually_congr, filter_upwards [ae_ae_of_ae_prod h1f.ae_eq_mk.symm], assume x hx, exact has_finite_integral_congr hx }, { apply has_finite_integral_congr, filter_upwards [ae_ae_of_ae_prod h1f.ae_eq_mk.symm] with _ hx using integral_congr_ae (eventually_eq.fun_comp hx _), }, { apply_instance, }, end /-- A binary function is integrable if the function `y ↦ f (x, y)` is integrable for almost every `x` and the function `x ↦ ∫ ‖f (x, y)‖ dy` is integrable. -/ lemma integrable_prod_iff ⦃f : α × β → E⦄ (h1f : ae_strongly_measurable f (μ.prod ν)) : integrable f (μ.prod ν) ↔ (∀ᵐ x ∂ μ, integrable (λ y, f (x, y)) ν) ∧ integrable (λ x, ∫ y, ‖f (x, y)‖ ∂ν) μ := by simp [integrable, h1f, has_finite_integral_prod_iff', h1f.norm.integral_prod_right', h1f.prod_mk_left] /-- A binary function is integrable if the function `x ↦ f (x, y)` is integrable for almost every `y` and the function `y ↦ ∫ ‖f (x, y)‖ dx` is integrable. -/ lemma integrable_prod_iff' [sigma_finite μ] ⦃f : α × β → E⦄ (h1f : ae_strongly_measurable f (μ.prod ν)) : integrable f (μ.prod ν) ↔ (∀ᵐ y ∂ ν, integrable (λ x, f (x, y)) μ) ∧ integrable (λ y, ∫ x, ‖f (x, y)‖ ∂μ) ν := by { convert integrable_prod_iff (h1f.prod_swap) using 1, rw [integrable_swap_iff] } lemma integrable.prod_left_ae [sigma_finite μ] ⦃f : α × β → E⦄ (hf : integrable f (μ.prod ν)) : ∀ᵐ y ∂ ν, integrable (λ x, f (x, y)) μ := ((integrable_prod_iff' hf.ae_strongly_measurable).mp hf).1 lemma integrable.prod_right_ae [sigma_finite μ] ⦃f : α × β → E⦄ (hf : integrable f (μ.prod ν)) : ∀ᵐ x ∂ μ, integrable (λ y, f (x, y)) ν := hf.swap.prod_left_ae lemma integrable.integral_norm_prod_left ⦃f : α × β → E⦄ (hf : integrable f (μ.prod ν)) : integrable (λ x, ∫ y, ‖f (x, y)‖ ∂ν) μ := ((integrable_prod_iff hf.ae_strongly_measurable).mp hf).2 lemma integrable.integral_norm_prod_right [sigma_finite μ] ⦃f : α × β → E⦄ (hf : integrable f (μ.prod ν)) : integrable (λ y, ∫ x, ‖f (x, y)‖ ∂μ) ν := hf.swap.integral_norm_prod_left lemma integrable_prod_mul {f : α → ℝ} {g : β → ℝ} (hf : integrable f μ) (hg : integrable g ν) : integrable (λ (z : α × β), f z.1 * g z.2) (μ.prod ν) := begin refine (integrable_prod_iff _).2 ⟨_, _⟩, { exact hf.1.fst.mul hg.1.snd }, { exact eventually_of_forall (λ x, hg.const_mul (f x)) }, { simpa only [norm_mul, integral_mul_left] using hf.norm.mul_const _ } end end variables [normed_space ℝ E] [complete_space E] lemma integrable.integral_prod_left ⦃f : α × β → E⦄ (hf : integrable f (μ.prod ν)) : integrable (λ x, ∫ y, f (x, y) ∂ν) μ := integrable.mono hf.integral_norm_prod_left hf.ae_strongly_measurable.integral_prod_right' $ eventually_of_forall $ λ x, (norm_integral_le_integral_norm _).trans_eq $ (norm_of_nonneg $ integral_nonneg_of_ae $ eventually_of_forall $ λ y, (norm_nonneg (f (x, y)) : _)).symm lemma integrable.integral_prod_right [sigma_finite μ] ⦃f : α × β → E⦄ (hf : integrable f (μ.prod ν)) : integrable (λ y, ∫ x, f (x, y) ∂μ) ν := hf.swap.integral_prod_left /-! ### The Bochner integral on a product -/ variables [sigma_finite μ] lemma integral_prod_swap (f : α × β → E) (hf : ae_strongly_measurable f (μ.prod ν)) : ∫ z, f z.swap ∂(ν.prod μ) = ∫ z, f z ∂(μ.prod ν) := begin rw ← prod_swap at hf, rw [← integral_map measurable_swap.ae_measurable hf, prod_swap] end variables {E' : Type*} [normed_add_comm_group E'] [complete_space E'] [normed_space ℝ E'] /-! Some rules about the sum/difference of double integrals. They follow from `integral_add`, but we separate them out as separate lemmas, because they involve quite some steps. -/ /-- Integrals commute with addition inside another integral. `F` can be any function. -/ lemma integral_fn_integral_add ⦃f g : α × β → E⦄ (F : E → E') (hf : integrable f (μ.prod ν)) (hg : integrable g (μ.prod ν)) : ∫ x, F (∫ y, f (x, y) + g (x, y) ∂ν) ∂μ = ∫ x, F (∫ y, f (x, y) ∂ν + ∫ y, g (x, y) ∂ν) ∂μ := begin refine integral_congr_ae _, filter_upwards [hf.prod_right_ae, hg.prod_right_ae] with _ h2f h2g, simp [integral_add h2f h2g], end /-- Integrals commute with subtraction inside another integral. `F` can be any measurable function. -/ lemma integral_fn_integral_sub ⦃f g : α × β → E⦄ (F : E → E') (hf : integrable f (μ.prod ν)) (hg : integrable g (μ.prod ν)) : ∫ x, F (∫ y, f (x, y) - g (x, y) ∂ν) ∂μ = ∫ x, F (∫ y, f (x, y) ∂ν - ∫ y, g (x, y) ∂ν) ∂μ := begin refine integral_congr_ae _, filter_upwards [hf.prod_right_ae, hg.prod_right_ae] with _ h2f h2g, simp [integral_sub h2f h2g], end /-- Integrals commute with subtraction inside a lower Lebesgue integral. `F` can be any function. -/ lemma lintegral_fn_integral_sub ⦃f g : α × β → E⦄ (F : E → ℝ≥0∞) (hf : integrable f (μ.prod ν)) (hg : integrable g (μ.prod ν)) : ∫⁻ x, F (∫ y, f (x, y) - g (x, y) ∂ν) ∂μ = ∫⁻ x, F (∫ y, f (x, y) ∂ν - ∫ y, g (x, y) ∂ν) ∂μ := begin refine lintegral_congr_ae _, filter_upwards [hf.prod_right_ae, hg.prod_right_ae] with _ h2f h2g, simp [integral_sub h2f h2g], end /-- Double integrals commute with addition. -/ lemma integral_integral_add ⦃f g : α × β → E⦄ (hf : integrable f (μ.prod ν)) (hg : integrable g (μ.prod ν)) : ∫ x, ∫ y, f (x, y) + g (x, y) ∂ν ∂μ = ∫ x, ∫ y, f (x, y) ∂ν ∂μ + ∫ x, ∫ y, g (x, y) ∂ν ∂μ := (integral_fn_integral_add id hf hg).trans $ integral_add hf.integral_prod_left hg.integral_prod_left /-- Double integrals commute with addition. This is the version with `(f + g) (x, y)` (instead of `f (x, y) + g (x, y)`) in the LHS. -/ lemma integral_integral_add' ⦃f g : α × β → E⦄ (hf : integrable f (μ.prod ν)) (hg : integrable g (μ.prod ν)) : ∫ x, ∫ y, (f + g) (x, y) ∂ν ∂μ = ∫ x, ∫ y, f (x, y) ∂ν ∂μ + ∫ x, ∫ y, g (x, y) ∂ν ∂μ := integral_integral_add hf hg /-- Double integrals commute with subtraction. -/ lemma integral_integral_sub ⦃f g : α × β → E⦄ (hf : integrable f (μ.prod ν)) (hg : integrable g (μ.prod ν)) : ∫ x, ∫ y, f (x, y) - g (x, y) ∂ν ∂μ = ∫ x, ∫ y, f (x, y) ∂ν ∂μ - ∫ x, ∫ y, g (x, y) ∂ν ∂μ := (integral_fn_integral_sub id hf hg).trans $ integral_sub hf.integral_prod_left hg.integral_prod_left /-- Double integrals commute with subtraction. This is the version with `(f - g) (x, y)` (instead of `f (x, y) - g (x, y)`) in the LHS. -/ lemma integral_integral_sub' ⦃f g : α × β → E⦄ (hf : integrable f (μ.prod ν)) (hg : integrable g (μ.prod ν)) : ∫ x, ∫ y, (f - g) (x, y) ∂ν ∂μ = ∫ x, ∫ y, f (x, y) ∂ν ∂μ - ∫ x, ∫ y, g (x, y) ∂ν ∂μ := integral_integral_sub hf hg /-- The map that sends an L¹-function `f : α × β → E` to `∫∫f` is continuous. -/ lemma continuous_integral_integral : continuous (λ (f : α × β →₁[μ.prod ν] E), ∫ x, ∫ y, f (x, y) ∂ν ∂μ) := begin rw [continuous_iff_continuous_at], intro g, refine tendsto_integral_of_L1 _ (L1.integrable_coe_fn g).integral_prod_left (eventually_of_forall $ λ h, (L1.integrable_coe_fn h).integral_prod_left) _, simp_rw [← lintegral_fn_integral_sub (λ x, (‖x‖₊ : ℝ≥0∞)) (L1.integrable_coe_fn _) (L1.integrable_coe_fn g)], refine tendsto_of_tendsto_of_tendsto_of_le_of_le tendsto_const_nhds _ (λ i, zero_le _) _, { exact λ i, ∫⁻ x, ∫⁻ y, ‖i (x, y) - g (x, y)‖₊ ∂ν ∂μ }, swap, { exact λ i, lintegral_mono (λ x, ennnorm_integral_le_lintegral_ennnorm _) }, show tendsto (λ (i : α × β →₁[μ.prod ν] E), ∫⁻ x, ∫⁻ (y : β), ‖i (x, y) - g (x, y)‖₊ ∂ν ∂μ) (𝓝 g) (𝓝 0), have : ∀ (i : α × β →₁[μ.prod ν] E), measurable (λ z, (‖i z - g z‖₊ : ℝ≥0∞)) := λ i, ((Lp.strongly_measurable i).sub (Lp.strongly_measurable g)).ennnorm, simp_rw [← lintegral_prod_of_measurable _ (this _), ← L1.of_real_norm_sub_eq_lintegral, ← of_real_zero], refine (continuous_of_real.tendsto 0).comp _, rw [← tendsto_iff_norm_tendsto_zero], exact tendsto_id end /-- **Fubini's Theorem**: For integrable functions on `α × β`, the Bochner integral of `f` is equal to the iterated Bochner integral. `integrable_prod_iff` can be useful to show that the function in question in integrable. `measure_theory.integrable.integral_prod_right` is useful to show that the inner integral of the right-hand side is integrable. -/ lemma integral_prod : ∀ (f : α × β → E) (hf : integrable f (μ.prod ν)), ∫ z, f z ∂(μ.prod ν) = ∫ x, ∫ y, f (x, y) ∂ν ∂μ := begin apply integrable.induction, { intros c s hs h2s, simp_rw [integral_indicator hs, ← indicator_comp_right, function.comp, integral_indicator (measurable_prod_mk_left hs), set_integral_const, integral_smul_const, integral_to_real (measurable_measure_prod_mk_left hs).ae_measurable (ae_measure_lt_top hs h2s.ne), prod_apply hs] }, { intros f g hfg i_f i_g hf hg, simp_rw [integral_add' i_f i_g, integral_integral_add' i_f i_g, hf, hg] }, { exact is_closed_eq continuous_integral continuous_integral_integral }, { intros f g hfg i_f hf, convert hf using 1, { exact integral_congr_ae hfg.symm }, { refine integral_congr_ae _, refine (ae_ae_of_ae_prod hfg).mp _, apply eventually_of_forall, intros x hfgx, exact integral_congr_ae (ae_eq_symm hfgx) } } end /-- Symmetric version of **Fubini's Theorem**: For integrable functions on `α × β`, the Bochner integral of `f` is equal to the iterated Bochner integral. This version has the integrals on the right-hand side in the other order. -/ lemma integral_prod_symm (f : α × β → E) (hf : integrable f (μ.prod ν)) : ∫ z, f z ∂(μ.prod ν) = ∫ y, ∫ x, f (x, y) ∂μ ∂ν := by { simp_rw [← integral_prod_swap f hf.ae_strongly_measurable], exact integral_prod _ hf.swap } /-- Reversed version of **Fubini's Theorem**. -/ lemma integral_integral {f : α → β → E} (hf : integrable (uncurry f) (μ.prod ν)) : ∫ x, ∫ y, f x y ∂ν ∂μ = ∫ z, f z.1 z.2 ∂(μ.prod ν) := (integral_prod _ hf).symm /-- Reversed version of **Fubini's Theorem** (symmetric version). -/ lemma integral_integral_symm {f : α → β → E} (hf : integrable (uncurry f) (μ.prod ν)) : ∫ x, ∫ y, f x y ∂ν ∂μ = ∫ z, f z.2 z.1 ∂(ν.prod μ) := (integral_prod_symm _ hf.swap).symm /-- Change the order of Bochner integration. -/ lemma integral_integral_swap ⦃f : α → β → E⦄ (hf : integrable (uncurry f) (μ.prod ν)) : ∫ x, ∫ y, f x y ∂ν ∂μ = ∫ y, ∫ x, f x y ∂μ ∂ν := (integral_integral hf).trans (integral_prod_symm _ hf) /-- **Fubini's Theorem** for set integrals. -/ lemma set_integral_prod (f : α × β → E) {s : set α} {t : set β} (hf : integrable_on f (s ×ˢ t) (μ.prod ν)) : ∫ z in s ×ˢ t, f z ∂(μ.prod ν) = ∫ x in s, ∫ y in t, f (x, y) ∂ν ∂μ := begin simp only [← measure.prod_restrict s t, integrable_on] at hf ⊢, exact integral_prod f hf end lemma integral_prod_mul (f : α → ℝ) (g : β → ℝ) : ∫ z, f z.1 * g z.2 ∂(μ.prod ν) = (∫ x, f x ∂μ) * (∫ y, g y ∂ν) := begin by_cases h : integrable (λ (z : α × β), f z.1 * g z.2) (μ.prod ν), { rw integral_prod _ h, simp_rw [integral_mul_left, integral_mul_right] }, have H : ¬(integrable f μ) ∨ ¬(integrable g ν), { contrapose! h, exact integrable_prod_mul h.1 h.2 }, cases H; simp [integral_undef h, integral_undef H], end lemma set_integral_prod_mul (f : α → ℝ) (g : β → ℝ) (s : set α) (t : set β) : ∫ z in s ×ˢ t, f z.1 * g z.2 ∂(μ.prod ν) = (∫ x in s, f x ∂μ) * (∫ y in t, g y ∂ν) := by simp only [← measure.prod_restrict s t, integrable_on, integral_prod_mul] end measure_theory
05f1e8a1398d89b45a9c32578990a76dd2090775
22e97a5d648fc451e25a06c668dc03ac7ed7bc25
/src/control/traversable/instances.lean
84aef494ab3ee0e81d424526a01933f5c7db68c7
[ "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
5,512
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Simon Hudon Instances of `traversable` for types from the core library -/ import data.list.forall2 import data.set.lattice import control.applicative universes u v section option open functor variables {F G : Type u → Type u} variables [applicative F] [applicative G] variables [is_lawful_applicative F] [is_lawful_applicative G] lemma option.id_traverse {α} (x : option α) : option.traverse id.mk x = x := by cases x; refl lemma option.comp_traverse {α β γ} (f : β → F γ) (g : α → G β) (x : option α) : option.traverse (comp.mk ∘ (<$>) f ∘ g) x = comp.mk (option.traverse f <$> option.traverse g x) := by cases x; simp! with functor_norm; refl lemma option.traverse_eq_map_id {α β} (f : α → β) (x : option α) : traverse (id.mk ∘ f) x = id.mk (f <$> x) := by cases x; refl variable (η : applicative_transformation F G) lemma option.naturality {α β} (f : α → F β) (x : option α) : η (option.traverse f x) = option.traverse (@η _ ∘ f) x := by cases x with x; simp! [*] with functor_norm end option instance : is_lawful_traversable option := { id_traverse := @option.id_traverse, comp_traverse := @option.comp_traverse, traverse_eq_map_id := @option.traverse_eq_map_id, naturality := @option.naturality } namespace list variables {F G : Type u → Type u} variables [applicative F] [applicative G] section variables [is_lawful_applicative F] [is_lawful_applicative G] open applicative functor open list (cons) protected lemma id_traverse {α} (xs : list α) : list.traverse id.mk xs = xs := by induction xs; simp! * with functor_norm; refl protected lemma comp_traverse {α β γ} (f : β → F γ) (g : α → G β) (x : list α) : list.traverse (comp.mk ∘ (<$>) f ∘ g) x = comp.mk (list.traverse f <$> list.traverse g x) := by induction x; simp! * with functor_norm; refl protected lemma traverse_eq_map_id {α β} (f : α → β) (x : list α) : list.traverse (id.mk ∘ f) x = id.mk (f <$> x) := by induction x; simp! * with functor_norm; refl variable (η : applicative_transformation F G) protected lemma naturality {α β} (f : α → F β) (x : list α) : η (list.traverse f x) = list.traverse (@η _ ∘ f) x := by induction x; simp! * with functor_norm open nat instance : is_lawful_traversable list := { id_traverse := @list.id_traverse, comp_traverse := @list.comp_traverse, traverse_eq_map_id := @list.traverse_eq_map_id, naturality := @list.naturality } end section traverse variables {α' β' : Type u} (f : α' → F β') @[simp] lemma traverse_nil : traverse f ([] : list α') = (pure [] : F (list β')) := rfl @[simp] lemma traverse_cons (a : α') (l : list α') : traverse f (a :: l) = (::) <$> f a <*> traverse f l := rfl variables [is_lawful_applicative F] @[simp] lemma traverse_append : ∀ (as bs : list α'), traverse f (as ++ bs) = (++) <$> traverse f as <*> traverse f bs | [] bs := have has_append.append ([] : list β') = id, by funext; refl, by simp [this] with functor_norm | (a :: as) bs := by simp [traverse_append as bs] with functor_norm; congr lemma mem_traverse {f : α' → set β'} : ∀(l : list α') (n : list β'), n ∈ traverse f l ↔ forall₂ (λb a, b ∈ f a) n l | [] [] := by simp | (a::as) [] := by simp; exact assume h, match h with end | [] (b::bs) := by simp | (a::as) (b::bs) := suffices (b :: bs : list β') ∈ traverse f (a :: as) ↔ b ∈ f a ∧ bs ∈ traverse f as, by simpa [mem_traverse as bs], iff.intro (assume ⟨_, ⟨b, hb, rfl⟩, _, hl, rfl⟩, ⟨hb, hl⟩) (assume ⟨hb, hl⟩, ⟨_, ⟨b, hb, rfl⟩, _, hl, rfl⟩) end traverse end list namespace sum section traverse variables {σ : Type u} variables {F G : Type u → Type u} variables [applicative F] [applicative G] open applicative functor open list (cons) variables [is_lawful_applicative F] [is_lawful_applicative G] protected lemma id_traverse {σ α} (x : σ ⊕ α) : sum.traverse id.mk x = x := by cases x; refl protected lemma comp_traverse {α β γ} (f : β → F γ) (g : α → G β) (x : σ ⊕ α) : sum.traverse (comp.mk ∘ (<$>) f ∘ g) x = comp.mk (sum.traverse f <$> sum.traverse g x) := by cases x; simp! [sum.traverse,map_id] with functor_norm; refl protected lemma traverse_eq_map_id {α β} (f : α → β) (x : σ ⊕ α) : sum.traverse (id.mk ∘ f) x = id.mk (f <$> x) := by induction x; simp! * with functor_norm; refl protected lemma map_traverse {α β γ} (g : α → G β) (f : β → γ) (x : σ ⊕ α) : (<$>) f <$> sum.traverse g x = sum.traverse ((<$>) f ∘ g) x := by cases x; simp [sum.traverse, id_map] with functor_norm; congr; refl protected lemma traverse_map {α β γ : Type u} (g : α → β) (f : β → G γ) (x : σ ⊕ α) : sum.traverse f (g <$> x) = sum.traverse (f ∘ g) x := by cases x; simp [sum.traverse, id_map] with functor_norm; refl variable (η : applicative_transformation F G) protected lemma naturality {α β} (f : α → F β) (x : σ ⊕ α) : η (sum.traverse f x) = sum.traverse (@η _ ∘ f) x := by cases x; simp! [sum.traverse] with functor_norm end traverse instance {σ : Type u} : is_lawful_traversable.{u} (sum σ) := { id_traverse := @sum.id_traverse σ, comp_traverse := @sum.comp_traverse σ, traverse_eq_map_id := @sum.traverse_eq_map_id σ, naturality := @sum.naturality σ } end sum
001b7f498d538d5cb2cfacc790b913daeb910b28
5ae26df177f810c5006841e9c73dc56e01b978d7
/src/algebra/field.lean
ea4a414d7e8703fe6020d041d278a0be44be3303
[ "Apache-2.0" ]
permissive
ChrisHughes24/mathlib
98322577c460bc6b1fe5c21f42ce33ad1c3e5558
a2a867e827c2a6702beb9efc2b9282bd801d5f9a
refs/heads/master
1,583,848,251,477
1,565,164,247,000
1,565,164,247,000
129,409,993
0
1
Apache-2.0
1,565,164,817,000
1,523,628,059,000
Lean
UTF-8
Lean
false
false
8,554
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import algebra.ring logic.basic open set universe u variables {α : Type u} -- Default priority sufficient as core version has custom-set lower priority (100) /-- Core version `division_ring_has_div` erratically requires two instances of `division_ring` -/ instance division_ring_has_div' [division_ring α] : has_div α := ⟨algebra.div⟩ instance division_ring.to_domain [s : division_ring α] : domain α := { eq_zero_or_eq_zero_of_mul_eq_zero := λ a b h, classical.by_contradiction $ λ hn, division_ring.mul_ne_zero (mt or.inl hn) (mt or.inr hn) h ..s } namespace units variables [division_ring α] {a b : α} /-- Embed an element of a division ring into the unit group. By combining this function with the operations on units, or the `/ₚ` operation, it is possible to write a division as a partial function with three arguments. -/ def mk0 (a : α) (ha : a ≠ 0) : units α := ⟨a, a⁻¹, mul_inv_cancel ha, inv_mul_cancel ha⟩ @[simp] theorem inv_eq_inv (u : units α) : (↑u⁻¹ : α) = u⁻¹ := (mul_left_inj u).1 $ by rw [units.mul_inv, mul_inv_cancel]; apply units.ne_zero @[simp] theorem mk0_val (ha : a ≠ 0) : (mk0 a ha : α) = a := rfl @[simp] theorem mk0_inv (ha : a ≠ 0) : ((mk0 a ha)⁻¹ : α) = a⁻¹ := rfl @[simp] lemma mk0_coe (u : units α) (h : (u : α) ≠ 0) : mk0 (u : α) h = u := units.ext rfl @[simp] lemma units.mk0_inj {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) : units.mk0 a ha = units.mk0 b hb ↔ a = b := ⟨λ h, by injection h, λ h, units.ext h⟩ end units section division_ring variables [s : division_ring α] {a b c : α} include s lemma div_eq_mul_inv : a / b = a * b⁻¹ := rfl attribute [simp] div_one zero_div div_self theorem divp_eq_div (a : α) (u : units α) : a /ₚ u = a / u := congr_arg _ $ units.inv_eq_inv _ @[simp] theorem divp_mk0 (a : α) {b : α} (hb : b ≠ 0) : a /ₚ units.mk0 b hb = a / b := divp_eq_div _ _ lemma inv_div (ha : a ≠ 0) (hb : b ≠ 0) : (a / b)⁻¹ = b / a := (mul_inv_eq (inv_ne_zero hb) ha).trans $ by rw division_ring.inv_inv hb; refl lemma inv_div_left (ha : a ≠ 0) (hb : b ≠ 0) : a⁻¹ / b = (b * a)⁻¹ := (mul_inv_eq ha hb).symm lemma neg_inv (h : a ≠ 0) : - a⁻¹ = (- a)⁻¹ := by rw [inv_eq_one_div, inv_eq_one_div, div_neg_eq_neg_div _ h] lemma division_ring.inv_comm_of_comm (h : a ≠ 0) (H : a * b = b * a) : a⁻¹ * b = b * a⁻¹ := begin have : a⁻¹ * (b * a) * a⁻¹ = a⁻¹ * (a * b) * a⁻¹ := congr_arg (λ x:α, a⁻¹ * x * a⁻¹) H.symm, rwa [mul_assoc, mul_assoc, mul_inv_cancel, mul_one, ← mul_assoc, inv_mul_cancel, one_mul] at this; exact h end lemma div_ne_zero (ha : a ≠ 0) (hb : b ≠ 0) : a / b ≠ 0 := division_ring.mul_ne_zero ha (inv_ne_zero hb) lemma div_ne_zero_iff (hb : b ≠ 0) : a / b ≠ 0 ↔ a ≠ 0 := ⟨mt (λ h, by rw [h, zero_div]), λ ha, div_ne_zero ha hb⟩ lemma div_eq_zero_iff (hb : b ≠ 0) : a / b = 0 ↔ a = 0 := by haveI := classical.prop_decidable; exact not_iff_not.1 (div_ne_zero_iff hb) lemma add_div (a b c : α) : (a + b) / c = a / c + b / c := (div_add_div_same _ _ _).symm lemma div_right_inj (hc : c ≠ 0) : a / c = b / c ↔ a = b := by rw [← divp_mk0 _ hc, ← divp_mk0 _ hc, divp_right_inj] lemma sub_div (a b c : α) : (a - b) / c = a / c - b / c := (div_sub_div_same _ _ _).symm lemma division_ring.inv_inj (ha : a ≠ 0) (hb : b ≠ 0) : a⁻¹ = b⁻¹ ↔ a = b := ⟨λ h, by rw [← division_ring.inv_inv ha, ← division_ring.inv_inv hb, h], congr_arg (λx,x⁻¹)⟩ lemma division_ring.inv_eq_iff (ha : a ≠ 0) (hb : b ≠ 0) : a⁻¹ = b ↔ b⁻¹ = a := by rw [← division_ring.inv_inj (inv_ne_zero ha) hb, eq_comm, division_ring.inv_inv ha] lemma div_neg (a : α) (hb : b ≠ 0) : a / -b = -(a / b) := by rw [← division_ring.neg_div_neg_eq _ (neg_ne_zero.2 hb), neg_neg, neg_div] lemma div_eq_iff_mul_eq (hb : b ≠ 0) : a / b = c ↔ c * b = a := ⟨λ h, by rw [← h, div_mul_cancel _ hb], λ h, by rw [← h, mul_div_cancel _ hb]⟩ end division_ring instance field.to_integral_domain [F : field α] : integral_domain α := { ..F, ..division_ring.to_domain } section variables [field α] {a b c d : α} lemma div_eq_inv_mul : a / b = b⁻¹ * a := mul_comm _ _ lemma inv_add_inv {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) : a⁻¹ + b⁻¹ = (a + b) / (a * b) := by rw [inv_eq_one_div, inv_eq_one_div, one_div_add_one_div ha hb] lemma inv_sub_inv {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) : a⁻¹ - b⁻¹ = (b - a) / (a * b) := by rw [inv_eq_one_div, inv_eq_one_div, div_sub_div _ _ ha hb, one_mul, mul_one] lemma mul_div_right_comm (a b c : α) : (a * b) / c = (a / c) * b := (div_mul_eq_mul_div _ _ _).symm lemma mul_comm_div (a b c : α) : (a / b) * c = a * (c / b) := by rw [← mul_div_assoc, mul_div_right_comm] lemma div_mul_comm (a b c : α) : (a / b) * c = (c / b) * a := by rw [div_mul_eq_mul_div, mul_comm, mul_div_right_comm] lemma mul_div_comm (a b c : α) : a * (b / c) = b * (a / c) := by rw [← mul_div_assoc, mul_comm, mul_div_assoc] lemma field.div_right_comm (a : α) (hb : b ≠ 0) (hc : c ≠ 0) : (a / b) / c = (a / c) / b := by rw [field.div_div_eq_div_mul _ hb hc, field.div_div_eq_div_mul _ hc hb, mul_comm] lemma field.div_div_div_cancel_right (a : α) (hb : b ≠ 0) (hc : c ≠ 0) : (a / c) / (b / c) = a / b := by rw [field.div_div_eq_mul_div _ hb hc, div_mul_cancel _ hc] lemma div_mul_div_cancel (a : α) (hc : c ≠ 0) : (a / c) * (c / b) = a / b := by rw [← mul_div_assoc, div_mul_cancel _ hc] lemma div_eq_div_iff (hb : b ≠ 0) (hd : d ≠ 0) : a / b = c / d ↔ a * d = c * b := (domain.mul_right_inj (mul_ne_zero' hb hd)).symm.trans $ by rw [← mul_assoc, div_mul_cancel _ hb, ← mul_assoc, mul_right_comm, div_mul_cancel _ hd] lemma field.div_div_cancel (ha : a ≠ 0) (hb : b ≠ 0) : a / (a / b) = b := by rw [div_eq_mul_inv, inv_div ha hb, mul_div_cancel' _ ha] end section variables [discrete_field α] {a b c : α} attribute [simp] inv_zero div_zero lemma div_right_comm (a b c : α) : (a / b) / c = (a / c) / b := if b0 : b = 0 then by simp only [b0, div_zero, zero_div] else if c0 : c = 0 then by simp only [c0, div_zero, zero_div] else field.div_right_comm _ b0 c0 lemma div_div_div_cancel_right (a b : α) (hc : c ≠ 0) : (a / c) / (b / c) = a / b := if b0 : b = 0 then by simp only [b0, div_zero, zero_div] else field.div_div_div_cancel_right _ b0 hc lemma div_div_cancel (ha : a ≠ 0) : a / (a / b) = b := if b0 : b = 0 then by simp only [b0, div_zero] else field.div_div_cancel ha b0 @[simp] lemma inv_eq_zero {a : α} : a⁻¹ = 0 ↔ a = 0 := classical.by_cases (assume : a = 0, by simp [*])(assume : a ≠ 0, by simp [*, inv_ne_zero]) lemma neg_inv' (a : α) : (-a)⁻¹ = - a⁻¹ := begin by_cases a = 0, { rw [h, neg_zero, inv_zero, neg_zero] }, { rw [neg_inv h] } end end @[reducible] def is_field_hom {α β} [division_ring α] [division_ring β] (f : α → β) := is_ring_hom f namespace is_field_hom open is_ring_hom section variables {β : Type*} [division_ring α] [division_ring β] variables (f : α → β) [is_field_hom f] {x y : α} lemma map_ne_zero : f x ≠ 0 ↔ x ≠ 0 := ⟨mt $ λ h, h.symm ▸ map_zero f, λ x0 h, one_ne_zero $ calc 1 = f (x * x⁻¹) : by rw [mul_inv_cancel x0, map_one f] ... = 0 : by rw [map_mul f, h, zero_mul]⟩ lemma map_eq_zero : f x = 0 ↔ x = 0 := by haveI := classical.dec; exact not_iff_not.1 (map_ne_zero f) lemma map_inv' (h : x ≠ 0) : f x⁻¹ = (f x)⁻¹ := (domain.mul_left_inj ((map_ne_zero f).2 h)).1 $ by rw [mul_inv_cancel ((map_ne_zero f).2 h), ← map_mul f, mul_inv_cancel h, map_one f] lemma map_div' (h : y ≠ 0) : f (x / y) = f x / f y := (map_mul f).trans $ congr_arg _ $ map_inv' f h lemma injective : function.injective f := (is_add_group_hom.injective_iff _).2 (λ a ha, classical.by_contradiction $ λ ha0, by simpa [ha, is_ring_hom.map_mul f, is_ring_hom.map_one f, zero_ne_one] using congr_arg f (mul_inv_cancel ha0)) end section variables {β : Type*} [discrete_field α] [discrete_field β] variables (f : α → β) [is_field_hom f] {x y : α} lemma map_inv : f x⁻¹ = (f x)⁻¹ := classical.by_cases (by rintro rfl; simp only [map_zero f, inv_zero]) (map_inv' f) lemma map_div : f (x / y) = f x / f y := (map_mul f).trans $ congr_arg _ $ map_inv f end end is_field_hom
d841714c7a2411e08502fb5dfbe06f2485b9ec21
82e44445c70db0f03e30d7be725775f122d72f3e
/src/group_theory/subgroup.lean
d3eed779de22e5b780c793d7e29c4160b0e71a26
[ "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
85,336
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 import algebra.group.conj import algebra.pointwise import order.atoms /-! # 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 variables {G : Type*} [group G] variables {A : Type*} [add_group A] 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 := ⟨subgroup.carrier, λ p q h, by cases p; cases q; congr'⟩ @[simp, to_additive] lemma mem_carrier {s : subgroup G} {x : G} : x ∈ s.carrier ↔ x ∈ s := 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 @[mono, to_additive] lemma to_submonoid_strict_mono : strict_mono (to_submonoid : subgroup G → submonoid G) := λ _ _, id @[mono, to_additive] lemma to_submonoid_mono : monotone (to_submonoid : subgroup G → submonoid G) := to_submonoid_strict_mono.monotone @[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' } /-- 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 attribute [ext] add_subgroup.ext /-- A subgroup contains the group's 1. -/ @[to_additive "An `add_subgroup` contains the group's 0."] theorem one_mem : (1 : G) ∈ H := H.one_mem' /-- A subgroup is closed under multiplication. -/ @[to_additive "An `add_subgroup` is closed under addition."] theorem mul_mem {x y : G} : x ∈ H → y ∈ H → x * y ∈ H := λ hx hy, H.mul_mem' hx hy /-- A subgroup is closed under inverse. -/ @[to_additive "An `add_subgroup` is closed under inverse."] theorem inv_mem {x : G} : x ∈ H → x⁻¹ ∈ H := λ hx, H.inv_mem' hx /-- A subgroup is closed under division. -/ @[to_additive "An `add_subgroup` is closed under subtraction."] theorem div_mem {x y : G} (hx : x ∈ H) (hy : y ∈ H) : x / y ∈ H := by simpa only [div_eq_mul_inv] using H.mul_mem' hx (H.inv_mem' hy) @[simp, to_additive] theorem inv_mem_iff {x : G} : x⁻¹ ∈ H ↔ x ∈ H := ⟨λ h, inv_inv x ▸ H.inv_mem h, H.inv_mem⟩ @[to_additive] lemma div_mem_comm_iff {a b : G} : a / b ∈ H ↔ b / a ∈ H := by rw [← H.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 (K : subgroup G) {P : G → Prop} : (∃ (x : G), x ∈ K ∧ P x⁻¹) ↔ ∃ x ∈ K, P x := by split; { rintros ⟨x, x_in, hx⟩, exact ⟨x⁻¹, inv_mem K 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 H.mul_mem hba (H.inv_mem h), λ hb, H.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 H.mul_mem (H.inv_mem h) hab, H.mul_mem 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`."] lemma list_prod_mem {l : list G} : (∀ x ∈ l, x ∈ K) → l.prod ∈ K := K.to_submonoid.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`."] lemma multiset_prod_mem {G} [comm_group G] (K : subgroup G) (g : multiset G) : (∀ a ∈ g, a ∈ K) → g.prod ∈ K := K.to_submonoid.multiset_prod_mem g /-- 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`."] 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 := K.to_submonoid.prod_mem h lemma pow_mem {x : G} (hx : x ∈ K) : ∀ n : ℕ, x ^ n ∈ K := K.to_submonoid.pow_mem hx lemma gpow_mem {x : G} (hx : x ∈ K) : ∀ n : ℤ, x ^ n ∈ K | (n : ℕ) := by { rw [gpow_coe_nat], exact pow_mem _ hx n } | -[1+ n] := by { rw [gpow_neg_succ_of_nat], exact K.inv_mem (K.pow_mem hx n.succ) } /-- 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 x hx hx, have inv_mem : ∀ x, x ∈ s → x⁻¹ ∈ s, from λ x hx, by simpa using hs 1 x one_mem hx, { carrier := s, one_mem' := one_mem, inv_mem' := inv_mem, mul_mem' := λ x y hx hy, by simpa using hs x y⁻¹ hx (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⟩⟩ @[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 attribute [norm_cast] add_subgroup.coe_add add_subgroup.coe_zero add_subgroup.coe_neg add_subgroup.coe_mk /-- 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) /-- 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) /-- 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) /-- 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) /-- 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] lemma coe_pow (x : H) (n : ℕ) : ((x ^ n : H) : G) = x ^ n := coe_subtype H ▸ monoid_hom.map_pow _ _ _ @[simp, norm_cast] lemma coe_gpow (x : H) (n : ℤ) : ((x ^ n : H) : G) = x ^ n := coe_subtype H ▸ monoid_hom.map_gpow _ _ _ /-- 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] } @[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 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] 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] instance fintype_bot : fintype (⊥ : subgroup G) := ⟨{1}, by {rintro ⟨x, ⟨hx⟩⟩, exact finset.mem_singleton_self _}⟩ @[simp] lemma _root_.add_subgroup.card_bot : fintype.card (⊥ : add_subgroup A) = 1 := fintype.card_eq_one_iff.2 ⟨⟨(0 : A), set.mem_singleton 0⟩, λ ⟨y, hy⟩, subtype.eq $ add_subgroup.mem_bot.1 hy⟩ -- `@[to_additive]` doesn't work, because it converts the `1 : ℕ` to `0`. @[simp] lemma card_bot : 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] 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, push_neg at h, simpa [nontrivial_iff_exists_ne_one] using h }, end /-- A subgroup is either the trivial subgroup or contains a nonzero element. -/ @[to_additive] 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 /-- 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_bInter_iff.1 hx i h), .. (⨅ S ∈ s, subgroup.to_submonoid S).copy (⋂ S ∈ s, ↑S) (by simp) }⟩ @[simp, to_additive] lemma coe_Inf (H : set (subgroup G)) : ((Inf H : subgroup G) : set G) = ⋂ s ∈ H, ↑s := rfl attribute [norm_cast] coe_Inf add_subgroup.coe_Inf @[simp, to_additive] lemma mem_Inf {S : set (subgroup G)} {x : G} : x ∈ Inf S ↔ ∀ p ∈ S, x ∈ p := set.mem_bInter_iff @[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, 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] attribute [norm_cast] coe_infi add_subgroup.coe_infi /-- 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 mem_supr_of_mem {ι : Type*} {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 @[to_additive] lemma subsingleton_iff : subsingleton G ↔ subsingleton (subgroup G) := ⟨ λ h, by exactI ⟨λ x y, subgroup.ext $ λ i, subsingleton.elim 1 i ▸ by simp [subgroup.one_mem]⟩, λ 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⟩⟩ @[to_additive] lemma nontrivial_iff : nontrivial G ↔ nontrivial (subgroup 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.mp ‹_›) a _⟩ @[to_additive] instance [nontrivial G] : nontrivial (subgroup G) := nontrivial_iff.mp ‹_› @[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 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`. -/ @[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, H1, Hmul, Hinv⟩ _).2 Hk h attribute [elab_as_eliminator] subgroup.closure_induction add_subgroup.closure_induction /-- An induction principle on elements of the subtype `subgroup.closure`. If `p` holds for `1` and all elements of `k`, and is preserved under multiplication and inverse, then `p` holds for all elements `x : closure k`. The difference with `subgroup.closure_induction` is that this acts on the subtype. -/ @[to_additive "An induction principle on elements of the subtype `add_subgroup.closure`. If `p` holds for `0` and all elements of `k`, and is preserved under addition and negation, then `p` holds for all elements `x : closure k`. The difference with `add_subgroup.closure_induction` is that this acts on the subtype."] lemma closure_induction' (k : set G) {p : closure k → Prop} (Hk : ∀ x (h : x ∈ k), p ⟨x, subset_closure h⟩) (H1 : p 1) (Hmul : ∀ x y, p x → p y → p (x * y)) (Hinv : ∀ x, p x → p x⁻¹) (x : closure k) : p x := subtype.rec_on x $ λ x hx, begin refine exists.elim _ (λ (hx : x ∈ closure k) (hc : p ⟨x, hx⟩), hc), exact closure_induction hx (λ x hx, ⟨subset_closure hx, Hk x hx⟩) ⟨one_mem _, H1⟩ (λ x y hx hy, exists.elim hx $ λ hx' hx, exists.elim hy $ λ hy' hy, ⟨mul_mem _ hx' hy', Hmul _ _ hx hy⟩) (λ x hx, exists.elim hx $ λ hx' hx, ⟨inv_mem _ hx', Hinv _ hx⟩), end attribute [elab_as_eliminator] subgroup.closure_induction' add_subgroup.closure_induction' 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 _} /-- The subgroup generated by an element of a group equals the set of integer number powers 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 ▸ gpow_mem _ (subset_closure $ mem_singleton x) n⟩, { intros y hy, rw [eq_of_mem_singleton hy], exact ⟨1, gpow_one x⟩ }, { exact ⟨0, gpow_zero x⟩ }, { rintros _ _ ⟨n, rfl⟩ ⟨m, rfl⟩, exact ⟨n + m, gpow_add x n m⟩ }, rintros _ ⟨n, rfl⟩, exact ⟨-n, gpow_neg x n⟩ end 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 [set.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, set.inv_inv, set.union_comm] }, { simp only [true_and, coe_to_submonoid, union_subset_iff, subset_closure, inv_subset_closure] } end /-- 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 := begin rw [← mem_to_submonoid, closure_to_submonoid k] at h, refine submonoid.closure_induction h (λ x hx, _) H1 (λ x y hx hy, Hmul x y hx hy), { rw [mem_union, mem_inv] at hx, cases hx with mem invmem, { exact Hk x mem }, { rw [← inv_inv x], exact Hk_inv _ invmem } }, 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, (K k).mul_mem (hki hi) (hkj hj)⟩ }, rintros _ ⟨i, hi⟩, exact ⟨i, inv_mem (K i) 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 _ @[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 _ _ _ @[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 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 comap_top (f : G →* N) : (⊤ : subgroup N).comap f = ⊤ := (gc_map_comap f).u_top @[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) /-- 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 /-- 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 : set G).prod (K : set N) := 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] /-- 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 } /-- 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 @[priority 100, to_additive] instance bot_normal : normal (⊥ : subgroup G) := ⟨by simp⟩ @[priority 100, to_additive] instance top_normal : normal (⊤ : subgroup G) := ⟨λ _ _, mem_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 a group `G` is the set of elements that commute with everything in `G`"] def center : subgroup G := { carrier := {z | ∀ g, g * z = z * g}, one_mem' := by simp, mul_mem' := λ a b (ha : ∀ g, g * a = a * g) (hb : ∀ g, g * b = b * g) g, by assoc_rw [ha, hb g], inv_mem' := λ a (ha : ∀ g, g * a = a * g) g, by rw [← inv_inj, mul_inv_rev, inv_inv, ← ha, mul_inv_rev, inv_inv] } variable {G} @[to_additive] lemma mem_center_iff {z : G} : z ∈ center G ↔ ∀ g, g * z = z * g := iff.rfl @[priority 100, to_additive] instance center_normal : (center G).normal := ⟨begin assume n hn g h, assoc_rw [hn (h * g), hn g], simp end⟩ variables {G} (H) /-- 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} [fintype S] {x : G} (h : ∀ n, n ∈ S → x * n * x⁻¹ ∈ S) : x ∈ subgroup.set_normalizer S := by haveI := classical.prop_decidable; 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 ∈ normalizer H ↔ ∀ n, n ∈ H ↔ g * n * g⁻¹ ∈ H := iff.rfl @[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⟩ 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⟩⟩ variable (H) /-- 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] 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)⟩⟩ 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_bUnion_iff 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.bUnion_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₁, is_conj_trans h₂ (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 subgroup.one_mem _ }, { exact subgroup.mul_mem _ ihx ihy }, { exact subgroup.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_refl _)))) @[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) end subgroup namespace add_subgroup open set lemma gsmul_mem (H : add_subgroup A) {x : A} (hx : x ∈ H) : ∀ n : ℤ, n • x ∈ H | (n : ℕ) := by { rw [gsmul_coe_nat], exact add_submonoid.nsmul_mem H.to_add_submonoid hx n } | -[1+ n] := begin rw gsmul_neg_succ_of_nat, apply H.neg_mem', exact add_submonoid.nsmul_mem H.to_add_submonoid hx n.succ end /-- 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 : A} : y ∈ closure ({x} : set A) ↔ ∃ n : ℤ, n • x = y := begin refine ⟨λ hy, closure_induction hy _ _ _ _, λ ⟨n, hn⟩, hn ▸ gsmul_mem _ (subset_closure $ mem_singleton x) n⟩, { intros y hy, rw [eq_of_mem_singleton hy], exact ⟨1, one_gsmul x⟩ }, { exact ⟨0, zero_gsmul x⟩ }, { rintros _ _ ⟨n, rfl⟩ ⟨m, rfl⟩, exact ⟨n + m, add_gsmul x n m⟩ }, { rintros _ ⟨n, rfl⟩, refine ⟨-n, neg_gsmul x n⟩ } end lemma closure_singleton_zero : closure ({0} : set A) = ⊥ := by simp [eq_bot_iff_forall, mem_closure_singleton] variable (H : add_subgroup A) @[simp] lemma coe_smul (x : H) (n : ℕ) : ((n • x : H) : A) = n • x := coe_subtype H ▸ add_monoid_hom.map_nsmul _ _ _ @[simp] lemma coe_gsmul (x : H) (n : ℤ) : ((n • x : H) : A) = n • x := coe_subtype H ▸ add_monoid_hom.map_gsmul _ _ _ attribute [to_additive add_subgroup.coe_smul] subgroup.coe_pow attribute [to_additive add_subgroup.coe_gsmul] subgroup.coe_gpow end add_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 := monoid_hom.mk' (λ g, ⟨f g, ⟨g, rfl⟩⟩) $ λ a b, by {ext, exact f.map_mul' _ _} @[simp, to_additive] lemma coe_range_restrict (f : G →* N) (g : G) : (f.range_restrict g : N) = f 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 _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 } /-- Restriction of a group hom to a subgroup of the domain. -/ @[to_additive "Restriction of an `add_group` hom to an `add_subgroup` of the domain."] def restrict (f : G →* N) (H : subgroup G) : H →* N := f.comp H.subtype @[simp, to_additive] lemma restrict_apply {H : subgroup G} (f : G →* N) (x : H) : f.restrict H x = f (x : G) := rfl /-- Restriction of a group hom to a subgroup of the codomain. -/ @[to_additive "Restriction of an `add_group` hom to an `add_subgroup` of the codomain."] def cod_restrict (f : G →* N) (S : subgroup N) (h : ∀ x, f x ∈ S) : G →* S := { to_fun := λ n, ⟨f n, h n⟩, map_one' := subtype.eq f.map_one, map_mul' := λ x y, subtype.eq (f.map_mul x y) } @[simp, to_additive] lemma cod_restrict_apply {G : Type*} [group G] {N : Type*} [group N] (f : G →* N) (S : subgroup N) (h : ∀ (x : G), f x ∈ S) {x : G} : f.cod_restrict S h x = ⟨f x, h x⟩ := rfl @[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`. -/ 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] 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] 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. -/ 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⟩ }⟩) lemma of_injective_apply {f : G →* N} (hf : function.injective f) {x : G} : ↑(of_injective hf x) = f x := rfl /-- 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 →* N) := (⊥ : subgroup N).comap f @[to_additive] lemma mem_ker (f : G →* N) {x : G} : x ∈ f.ker ↔ f x = 1 := iff.rfl @[to_additive] lemma coe_ker (f : G →* N) : (f.ker : set G) = (f : G → N) ⁻¹' {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 N] (f : G →* N) : 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 →* N).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 @[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 := begin dsimp only [ker], rw [←prod_map_comap_prod, bot_prod_bot], end /-- 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] 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) := le_antisymm (map_le_iff_le_comap.2 $ le_trans (closure_mono $ set.subset_preimage_image f s) (gclosure_preimage_le _ _)) ((closure_le _).2 $ set.image_subset _ subset_closure) -- 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 ker_le_comap (H : subgroup N) : f.ker ≤ comap f H := 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'⟩, have : y⁻¹ * x ∈ f.ker, { rw mem_ker, simp [hy'] }, convert mul_mem _ (mem_sup_left hy) (mem_sup_right this), simp, 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_injective {f : G →* N} (h : function.surjective f) : function.injective (comap f) := λ K L hKL, by { apply_fun map f at hKL, simpa [map_comap_eq_self_of_surjective h] using hKL } @[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_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] 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 (H K : subgroup N) (hf : function.surjective f): comap f H ⊔ comap f K = comap f (H ⊔ K) := begin have : map f (comap f H ⊔ comap f K) = map f (comap f (H ⊔ K)), { simp [subgroup.map_comap_eq, map_sup, f.range_top_of_surjective hf], }, refine map_injective_of_ker_le f _ _ this, { calc f.ker ≤ comap f H : ker_le_comap f _ ... ≤ comap f H ⊔ comap f K : le_sup_left, }, exact ker_le_comap _ _, end /-- 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 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 [monoid_hom.ker]; 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 gpowers (g : G) : subgroup G := subgroup.copy (gpowers_hom G g).range (set.range ((^) g : ℤ → G)) rfl @[simp] lemma mem_gpowers (g : G) : g ∈ gpowers g := ⟨1, gpow_one _⟩ lemma gpowers_eq_closure (g : G) : gpowers g = closure {g} := by { ext, exact mem_closure_singleton.symm } @[simp] lemma range_gpowers_hom (g : G) : (gpowers_hom G g).range = gpowers g := rfl lemma gpowers_subset {a : G} {K : subgroup G} (h : a ∈ K) : gpowers a ≤ K := λ x hx, match x, hx with _, ⟨i, rfl⟩ := K.gpow_mem h i end lemma mem_gpowers_iff {g h : G} : h ∈ gpowers g ↔ ∃ (k : ℤ), g ^ k = h := iff.rfl @[simp] lemma forall_gpowers {x : G} {p : gpowers x → Prop} : (∀ g, p g) ↔ ∀ m : ℤ, p ⟨x ^ m, m, rfl⟩ := set.forall_subtype_range_iff @[simp] lemma exists_gpowers {x : G} {p : gpowers x → Prop} : (∃ g, p g) ↔ ∃ m : ℤ, p ⟨x ^ m, m, rfl⟩ := set.exists_subtype_range_iff lemma forall_mem_gpowers {x : G} {p : G → Prop} : (∀ g ∈ gpowers x, p g) ↔ ∀ m : ℤ, p (x ^ m) := set.forall_range_iff lemma exists_mem_gpowers {x : G} {p : G → Prop} : (∃ g ∈ gpowers x, p g) ↔ ∃ m : ℤ, p (x ^ m) := set.exists_range_iff end subgroup namespace add_subgroup /-- The subgroup generated by an element. -/ def gmultiples (a : A) : add_subgroup A := add_subgroup.copy (gmultiples_hom A a).range (set.range ((• a) : ℤ → A)) rfl @[simp] lemma range_gmultiples_hom (a : A) : (gmultiples_hom A a).range = gmultiples a := rfl lemma gmultiples_subset {a : A} {B : add_subgroup A} (h : a ∈ B) : gmultiples a ≤ B := @subgroup.gpowers_subset (multiplicative A) _ _ (B.to_subgroup) h attribute [to_additive add_subgroup.gmultiples] subgroup.gpowers attribute [to_additive add_subgroup.mem_gmultiples] subgroup.mem_gpowers attribute [to_additive add_subgroup.gmultiples_eq_closure] subgroup.gpowers_eq_closure attribute [to_additive add_subgroup.range_gmultiples_hom] subgroup.range_gpowers_hom attribute [to_additive add_subgroup.gmultiples_subset] subgroup.gpowers_subset attribute [to_additive add_subgroup.mem_gmultiples_iff] subgroup.mem_gpowers_iff attribute [to_additive add_subgroup.forall_gmultiples] subgroup.forall_gpowers attribute [to_additive add_subgroup.forall_mem_gmultiples] subgroup.forall_mem_gpowers attribute [to_additive add_subgroup.exists_gmultiples] subgroup.exists_gpowers attribute [to_additive add_subgroup.exists_mem_gmultiples] subgroup.exists_mem_gpowers end add_subgroup lemma int.mem_gmultiples_iff {a b : ℤ} : b ∈ add_subgroup.gmultiples a ↔ a ∣ b := exists_congr (λ k, by rw [mul_comm, eq_comm, ← smul_eq_mul]) lemma of_mul_image_gpowers_eq_gmultiples_of_mul { x : G } : additive.of_mul '' ((subgroup.gpowers x) : set G) = add_subgroup.gmultiples (additive.of_mul x) := begin ext y, split, { rintro ⟨z, ⟨m, hm⟩, hz2⟩, use m, simp only, rwa [← of_mul_gpow, hm] }, { rintros ⟨n, hn⟩, refine ⟨x ^ n, ⟨n, rfl⟩, _⟩, rwa of_mul_gpow } end lemma of_add_image_gmultiples_eq_gpowers_of_add {x : A} : multiplicative.of_add '' ((add_subgroup.gmultiples x) : set A) = subgroup.gpowers (multiplicative.of_add x) := begin symmetry, rw equiv.eq_image_iff_symm_image_eq, exact of_mul_image_gpowers_eq_gmultiples_of_mul, end 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 } 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 _ ((le_sup_left : s ≤ s ⊔ t) hy) ((le_sup_right : t ≤ s ⊔ t) 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] 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_lattice (subgroup C) := ⟨λ H, H.normal_of_comm.eq_bot_or_eq_top⟩ open 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 C (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 C (inv_mem C (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 ⟨mul_mem A 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 A hyz (inv_mem A (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 A (mul_mem A (mem_inf.1 g.2).1 (mem_inf.1 n.2).1) (inv_mem A (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 B (mul_mem B (mem_inf.1 g.2).2 (mem_inf.1 n.2).2) (inv_mem B (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 end subgroup_normal 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_scalar α β] [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_scalar α β] [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_scalar α β] [mul_action G α] [mul_action G β] [is_scalar_tower G α β] (S : subgroup G) : is_scalar_tower S α β := S.to_submonoid.is_scalar_tower /-- 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 end subgroup end actions
4b07ea988e3386e9a65a5000422d75efedd3a4e9
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/linear_algebra/isomorphisms.lean
94799845bdfa5611e2fe5f4aa8007a0e6dcf6831
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
6,512
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, Kevin Buzzard, Yury Kudryashov -/ import linear_algebra.quotient /-! # Isomorphism theorems for modules. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. * The Noether's first, second, and third isomorphism theorems for modules are proved as `linear_map.quot_ker_equiv_range`, `linear_map.quotient_inf_equiv_sup_quotient` and `submodule.quotient_quotient_equiv_quotient`. -/ universes u v variables {R M M₂ M₃ : Type*} variables [ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [module R M] [module R M₂] [module R M₃] variables (f : M →ₗ[R] M₂) /-! The first and second isomorphism theorems for modules. -/ namespace linear_map open submodule section isomorphism_laws /-- The first isomorphism law for modules. The quotient of `M` by the kernel of `f` is linearly equivalent to the range of `f`. -/ noncomputable def quot_ker_equiv_range : (M ⧸ f.ker) ≃ₗ[R] f.range := (linear_equiv.of_injective (f.ker.liftq f $ le_rfl) $ ker_eq_bot.mp $ submodule.ker_liftq_eq_bot _ _ _ (le_refl f.ker)).trans (linear_equiv.of_eq _ _ $ submodule.range_liftq _ _ _) /-- The first isomorphism theorem for surjective linear maps. -/ noncomputable def quot_ker_equiv_of_surjective (f : M →ₗ[R] M₂) (hf : function.surjective f) : (M ⧸ f.ker) ≃ₗ[R] M₂ := f.quot_ker_equiv_range.trans (linear_equiv.of_top f.range (linear_map.range_eq_top.2 hf)) @[simp] lemma quot_ker_equiv_range_apply_mk (x : M) : (f.quot_ker_equiv_range (submodule.quotient.mk x) : M₂) = f x := rfl @[simp] lemma quot_ker_equiv_range_symm_apply_image (x : M) (h : f x ∈ f.range) : f.quot_ker_equiv_range.symm ⟨f x, h⟩ = f.ker.mkq x := f.quot_ker_equiv_range.symm_apply_apply (f.ker.mkq x) /-- Canonical linear map from the quotient `p/(p ∩ p')` to `(p+p')/p'`, mapping `x + (p ∩ p')` to `x + p'`, where `p` and `p'` are submodules of an ambient module. -/ def quotient_inf_to_sup_quotient (p p' : submodule R M) : p ⧸ (comap p.subtype (p ⊓ p')) →ₗ[R] _ ⧸ (comap (p ⊔ p').subtype p') := by exact (comap p.subtype (p ⊓ p')).liftq ((comap (p ⊔ p').subtype p').mkq.comp (of_le le_sup_left)) begin rw [ker_comp, of_le, comap_cod_restrict, ker_mkq, map_comap_subtype], exact comap_mono (inf_le_inf_right _ le_sup_left) end /-- Second Isomorphism Law : the canonical map from `p/(p ∩ p')` to `(p+p')/p'` as a linear isomorphism. -/ noncomputable def quotient_inf_equiv_sup_quotient (p p' : submodule R M) : (p ⧸ (comap p.subtype (p ⊓ p'))) ≃ₗ[R] _ ⧸ (comap (p ⊔ p').subtype p') := by exact linear_equiv.of_bijective (quotient_inf_to_sup_quotient p p') ⟨begin rw [← ker_eq_bot, quotient_inf_to_sup_quotient, ker_liftq_eq_bot], rw [ker_comp, ker_mkq], exact λ ⟨x, hx1⟩ hx2, ⟨hx1, hx2⟩ end, begin rw [← range_eq_top, quotient_inf_to_sup_quotient, range_liftq, eq_top_iff'], rintros ⟨x, hx⟩, rcases mem_sup.1 hx with ⟨y, hy, z, hz, rfl⟩, use [⟨y, hy⟩], apply (submodule.quotient.eq _).2, change y - (y + z) ∈ p', rwa [sub_add_eq_sub_sub, sub_self, zero_sub, neg_mem_iff] end⟩ @[simp] lemma coe_quotient_inf_to_sup_quotient (p p' : submodule R M) : ⇑(quotient_inf_to_sup_quotient p p') = quotient_inf_equiv_sup_quotient p p' := rfl @[simp] lemma quotient_inf_equiv_sup_quotient_apply_mk (p p' : submodule R M) (x : p) : quotient_inf_equiv_sup_quotient p p' (submodule.quotient.mk x) = submodule.quotient.mk (of_le (le_sup_left : p ≤ p ⊔ p') x) := rfl lemma quotient_inf_equiv_sup_quotient_symm_apply_left (p p' : submodule R M) (x : p ⊔ p') (hx : (x:M) ∈ p) : (quotient_inf_equiv_sup_quotient p p').symm (submodule.quotient.mk x) = submodule.quotient.mk ⟨x, hx⟩ := (linear_equiv.symm_apply_eq _).2 $ by simp [of_le_apply] @[simp] lemma quotient_inf_equiv_sup_quotient_symm_apply_eq_zero_iff {p p' : submodule R M} {x : p ⊔ p'} : (quotient_inf_equiv_sup_quotient p p').symm (submodule.quotient.mk x) = 0 ↔ (x:M) ∈ p' := (linear_equiv.symm_apply_eq _).trans $ by simp [of_le_apply] lemma quotient_inf_equiv_sup_quotient_symm_apply_right (p p' : submodule R M) {x : p ⊔ p'} (hx : (x:M) ∈ p') : (quotient_inf_equiv_sup_quotient p p').symm (submodule.quotient.mk x) = 0 := quotient_inf_equiv_sup_quotient_symm_apply_eq_zero_iff.2 hx end isomorphism_laws end linear_map /-! The third isomorphism theorem for modules. -/ namespace submodule variables (S T : submodule R M) (h : S ≤ T) /-- The map from the third isomorphism theorem for modules: `(M / S) / (T / S) → M / T`. -/ def quotient_quotient_equiv_quotient_aux (h : S ≤ T) : (M ⧸ S) ⧸ (T.map S.mkq) →ₗ[R] M ⧸ T := by exact liftq _ (mapq S T linear_map.id h) (by { rintro _ ⟨x, hx, rfl⟩, rw [linear_map.mem_ker, mkq_apply, mapq_apply], exact (quotient.mk_eq_zero _).mpr hx }) @[simp] lemma quotient_quotient_equiv_quotient_aux_mk (x : M ⧸ S) : quotient_quotient_equiv_quotient_aux S T h (quotient.mk x) = mapq S T linear_map.id h x := liftq_apply _ _ _ @[simp] lemma quotient_quotient_equiv_quotient_aux_mk_mk (x : M) : quotient_quotient_equiv_quotient_aux S T h (quotient.mk (quotient.mk x)) = quotient.mk x := by rw [quotient_quotient_equiv_quotient_aux_mk, mapq_apply, linear_map.id_apply] /-- **Noether's third isomorphism theorem** for modules: `(M / S) / (T / S) ≃ M / T`. -/ def quotient_quotient_equiv_quotient : ((M ⧸ S) ⧸ (T.map S.mkq)) ≃ₗ[R] M ⧸ T := { to_fun := quotient_quotient_equiv_quotient_aux S T h, inv_fun := mapq _ _ (mkq S) (le_comap_map _ _), left_inv := λ x, quotient.induction_on' x $ λ x, quotient.induction_on' x $ λ x, by simp, right_inv := λ x, quotient.induction_on' x $ λ x, by simp, .. quotient_quotient_equiv_quotient_aux S T h } /-- Corollary of the third isomorphism theorem: `[S : T] [M : S] = [M : T]` -/ lemma card_quotient_mul_card_quotient (S T : submodule R M) (hST : T ≤ S) [decidable_pred (λ x, x ∈ S.map T.mkq)] [fintype (M ⧸ S)] [fintype (M ⧸ T)] : fintype.card (S.map T.mkq) * fintype.card (M ⧸ S) = fintype.card (M ⧸ T) := by rw [submodule.card_eq_card_quotient_mul_card (map T.mkq S), fintype.card_eq.mpr ⟨(quotient_quotient_equiv_quotient T S hST).to_equiv⟩] end submodule
1b03a41b5d40fd030856368f1a60c488bc25b1d9
74caf7451c921a8d5ab9c6e2b828c9d0a35aae95
/library/init/meta/exceptional.lean
05ddd54f11782cef49ec200c1a9a170fd221f7ee
[ "Apache-2.0" ]
permissive
sakas--/lean
f37b6fad4fd4206f2891b89f0f8135f57921fc3f
570d9052820be1d6442a5cc58ece37397f8a9e4c
refs/heads/master
1,586,127,145,194
1,480,960,018,000
1,480,960,635,000
40,137,176
0
0
null
1,438,621,351,000
1,438,621,351,000
null
UTF-8
Lean
false
false
1,738
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.category.monad init.meta.format /- Remark: we use a function that produces a format object as the exception information. Motivation: the formatting object may be big, and we may create it on demand. -/ meta inductive exceptional (α : Type) | success : α → exceptional | exception : (options → format) → exceptional section open exceptional variables {α : Type} variables [has_to_string α] protected meta def exceptional.to_string : exceptional α → string | (success a) := to_string a | (exception .α e) := "Exception: " ++ to_string (e options.mk) meta instance : has_to_string (exceptional α) := has_to_string.mk exceptional.to_string end namespace exceptional variables {α β : Type} protected meta def to_bool : exceptional α → bool | (success _) := tt | (exception .α _) := ff protected meta def to_option : exceptional α → option α | (success a) := some a | (exception .α _) := none @[inline] protected meta def fmap (f : α → β) (e : exceptional α) : exceptional β := exceptional.cases_on e (λ a, success (f a)) (λ f, exception β f) @[inline] protected meta def bind (e₁ : exceptional α) (e₂ : α → exceptional β) : exceptional β := exceptional.cases_on e₁ (λ a, e₂ a) (λ f, exception β f) @[inline] protected meta def return (a : α) : exceptional α := success a @[inline] meta def fail (f : format) : exceptional α := exception α (λ u, f) end exceptional meta instance : monad exceptional := ⟨@exceptional.fmap, @exceptional.return, @exceptional.bind⟩
9869b5fca6d927ffdf722661c142603acf126786
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/uuu.lean
1ef3c6d4c698f1be6bbc7d3895bb1b3ce1a90960
[ "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,413
lean
prelude -- Porting Vladimir's file to Lean notation `assume` binders `,` r:(scoped f, f) := r notation `take` binders `,` r:(scoped f, f) := r inductive empty : Type inductive unit : Type := tt : unit definition tt := @unit.tt inductive nat : Type := | O : nat | S : nat → nat inductive paths {A : Type} (a : A) : A → Type := idpath : paths a a definition idpath := @paths.idpath inductive sum (A : Type) (B : Type) : Type := | inl : A -> sum A B | inr : B -> sum A B definition coprod := sum definition ii1fun {A : Type} (B : Type) (a : A) := sum.inl B a definition ii2fun (A : Type) {B : Type} (b : B) := sum.inr A b definition ii1 {A : Type} {B : Type} (a : A) := sum.inl B a definition ii2 {A : Type} {B : Type} (b : B) := sum.inl A b inductive total2 {T: Type} (P: T → Type) : Type := tpair : Π (t : T) (tp : P t), total2 P definition tpair := @total2.tpair definition pr1 {T : Type} {P : T → Type} (tp : total2 P) : T := total2.rec (λ a b, a) tp definition pr2 {T : Type} {P : T → Type} (tp : total2 P) : P (pr1 tp) := total2.rec (λ a b, b) tp inductive Phant (T : Type) : Type := phant : Phant T definition fromempty {X : Type} : empty → X := λe, empty.rec (λe, X) e definition tounit {X : Type} : X → unit := λx, tt definition termfun {X : Type} (x : X) : unit → X := λt, x definition idfun (T : Type) := λt : T, t definition funcomp {X : Type} {Y : Type} {Z : Type} (f : X → Y) (g : Y → Z) := λx, g (f x) infixl `∘`:60 := funcomp definition iteration {T : Type} (f : T → T) (n : nat) : T → T := nat.rec (idfun T) (λ m fm, funcomp fm f) n definition adjev {X : Type} {Y : Type} (x : X) (f : X → Y) := f x definition adjev2 {X : Type} {Y : Type} (phi : ((X → Y) → Y ) → Y ) : X → Y := λx, phi (λf, f x) definition dirprod (X : Type) (Y : Type) := total2 (λ x : X, Y) definition dirprodpair {X : Type} {Y : Type} := @tpair _ (λ x : X, Y) definition dirprodadj {X : Type} {Y : Type} {Z : Type} (f : dirprod X Y → Z ) : X → Y → Z := λx y, f (dirprodpair x y) definition dirprodf {X : Type} {Y : Type} {X' : Type} {Y' : Type} (f : X → Y) (f' : X' → Y') (xx' : dirprod X X') : dirprod Y Y' := dirprodpair (f (pr1 xx')) (f' (pr2 xx')) definition ddualand {X : Type} {Y : Type} {P : Type} (xp : (X → P) → P) (yp : (Y → P) → P) : (dirprod X Y → P) → P := λ X0, let int1 := λ (ypp : (Y → P) → P) (x : X), yp (λ y : Y, X0 (dirprodpair x y)) in xp (int1 yp) definition neg (X : Type) : Type := X → empty definition negf {X : Type} {Y : Type} (f : X → Y) : neg Y → neg X := λ (phi : Y → empty) (x : X), phi (f x) definition dneg (X : Type) : Type := (X → empty) → empty definition dnegf {X : Type} {Y : Type} (f : X → Y) : dneg X → dneg Y := negf (negf f) definition todneg (X : Type) : X → dneg X := adjev definition dnegnegtoneg {X : Type} : dneg (neg X) → neg X := adjev2 lemma dneganddnegl1 {X : Type} {Y : Type} (dnx : dneg X) (dny : dneg Y) : neg (X → neg Y) := take X2 : X → neg Y, have X3 : dneg X → neg Y, from take xx : dneg X, dnegnegtoneg (dnegf X2 xx), dny (X3 dnx) definition logeq (X : Type) (Y : Type) := dirprod (X → Y) (Y → X) infix `<->`:25 := logeq infix `↔`:25 := logeq definition logeqnegs {X : Type} {Y : Type} (l : X ↔ Y) : (neg X) ↔ (neg Y) := dirprodpair (negf (pr2 l)) (negf (pr1 l)) infix `=`:50 := paths definition pathscomp0 {X : Type} {a b c : X} (e1 : a = b) (e2 : b = c) : a = c := paths.rec e1 e2 definition pathscomp0rid {X : Type} {a b : X} (e1 : a = b) : pathscomp0 e1 (idpath b) = e1 := idpath _ definition pathsinv0 {X : Type} {a b : X} (e : a = b) : b = a := paths.rec (idpath _) e definition transport {A : Type} {a b : A} {P : A → Type} (H1 : a = b) (H2 : P a) : P b := paths.rec H2 H1 infixr `▸`:75 := transport infixr `⬝`:75 := pathscomp0 postfix `⁻¹`:100 := pathsinv0 definition idinv {X : Type} (x : X) : (idpath x)⁻¹ = idpath x := idpath (idpath x) definition idtrans {A : Type} (x : A) : (idpath x) ⬝ (idpath x) = (idpath x) := idpath (idpath x) definition pathsinv0l {X : Type} {a b : X} (e : a = b) : e⁻¹ ⬝ e = idpath b := paths.rec (idinv a⁻¹ ▸ idtrans a) e definition pathsinv0r {A : Type} {x y : A} (p : x = y) : p⁻¹ ⬝ p = idpath y := paths.rec (idinv x⁻¹ ▸ idtrans x) p definition pathsinv0inv0 {A : Type} {x y : A} (p : x = y) : (p⁻¹)⁻¹ = p := paths.rec (idpath (idpath x)) p definition pathsdirprod {X : Type} {Y : Type} {x1 x2 : X} {y1 y2 : Y} (ex : x1 = x2) (ey : y1 = y2 ) : dirprodpair x1 y1 = dirprodpair x2 y2 := ex ▸ ey ▸ idpath (dirprodpair x1 y1) definition maponpaths {T1 : Type} {T2 : Type} (f : T1 → T2) {t1 t2 : T1} (e : t1 = t2) : f t1 = f t2 := e ▸ idpath (f t1) definition ap {T1 : Type} {T2 : Type} := @maponpaths T1 T2 definition maponpathscomp0 {X : Type} {Y : Type} {x y z : X} (f : X → Y) (p : x = y) (q : y = z) : ap f (p ⬝ q) = (ap f p) ⬝ (ap f q) := paths.rec (idpath _) q definition maponpathsinv0 {X : Type} {Y : Type} (f : X → Y) {x1 x2 : X} (e : x1 = x2 ) : ap f (e⁻¹) = (ap f e)⁻¹ := paths.rec (idpath _) e lemma maponpathsidfun {X : Type} {x x' : X} (e : x = x') : ap (idfun X) e = e := paths.rec (idpath _) e lemma maponpathscomp {X : Type} {Y : Type} {Z : Type} {x x' : X} (f : X → Y) (g : Y → Z) (e : x = x') : ap g (ap f e) = ap (f ∘ g) e := paths.rec (idpath _) e
0119c6ae44f69950bb0ea5d86167a5e670d4dce5
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/finsupp/big_operators.lean
f91e7b90d5c8bf960308ea77725856d40e8cc3fe
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
4,909
lean
/- Copyright (c) 2022 Yakov Pechersky. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yakov Pechersky -/ import data.finsupp.defs import data.finset.pairwise /-! # Sums of collections of finsupp, and their support This file provides results about the `finsupp.support` of sums of collections of `finsupp`, including sums of `list`, `multiset`, and `finset`. The support of the sum is a subset of the union of the supports: * `list.support_sum_subset` * `multiset.support_sum_subset` * `finset.support_sum_subset` The support of the sum of pairwise disjoint finsupps is equal to the union of the supports * `list.support_sum_eq` * `multiset.support_sum_eq` * `finset.support_sum_eq` Member in the support of the indexed union over a collection iff it is a member of the support of a member of the collection: * `list.mem_foldr_sup_support_iff` * `multiset.mem_sup_map_support_iff` * `finset.mem_sup_support_iff` -/ variables {ι M : Type*} [decidable_eq ι] lemma list.support_sum_subset [add_monoid M] (l : list (ι →₀ M)) : l.sum.support ⊆ l.foldr ((⊔) ∘ finsupp.support) ∅ := begin induction l with hd tl IH, { simp }, { simp only [list.sum_cons, finset.union_comm], refine finsupp.support_add.trans (finset.union_subset_union _ IH), refl } end lemma multiset.support_sum_subset [add_comm_monoid M] (s : multiset (ι →₀ M)) : s.sum.support ⊆ (s.map (finsupp.support)).sup := begin induction s using quot.induction_on, simpa using list.support_sum_subset _ end lemma finset.support_sum_subset [add_comm_monoid M] (s : finset (ι →₀ M)) : (s.sum id).support ⊆ finset.sup s finsupp.support := by { classical, convert multiset.support_sum_subset s.1; simp } lemma list.mem_foldr_sup_support_iff [has_zero M] {l : list (ι →₀ M)} {x : ι} : x ∈ l.foldr ((⊔) ∘ finsupp.support) ∅ ↔ ∃ (f : ι →₀ M) (hf : f ∈ l), x ∈ f.support := begin simp only [finset.sup_eq_union, list.foldr_map, finsupp.mem_support_iff, exists_prop], induction l with hd tl IH, { simp }, { simp only [IH, list.foldr_cons, finset.mem_union, finsupp.mem_support_iff, list.mem_cons_iff], split, { rintro (h|h), { exact ⟨hd, or.inl rfl, h⟩ }, { exact h.imp (λ f hf, hf.imp_left or.inr) } }, { rintro ⟨f, rfl|hf, h⟩, { exact or.inl h }, { exact or.inr ⟨f, hf, h⟩ } } } end lemma multiset.mem_sup_map_support_iff [has_zero M] {s : multiset (ι →₀ M)} {x : ι} : x ∈ (s.map (finsupp.support)).sup ↔ ∃ (f : ι →₀ M) (hf : f ∈ s), x ∈ f.support := quot.induction_on s $ λ _, by simpa using list.mem_foldr_sup_support_iff lemma finset.mem_sup_support_iff [has_zero M] {s : finset (ι →₀ M)} {x : ι} : x ∈ s.sup finsupp.support ↔ ∃ (f : ι →₀ M) (hf : f ∈ s), x ∈ f.support := multiset.mem_sup_map_support_iff lemma list.support_sum_eq [add_monoid M] (l : list (ι →₀ M)) (hl : l.pairwise (disjoint on finsupp.support)) : l.sum.support = l.foldr ((⊔) ∘ finsupp.support) ∅ := begin induction l with hd tl IH, { simp }, { simp only [list.pairwise_cons] at hl, simp only [list.sum_cons, list.foldr_cons, function.comp_app], rw [finsupp.support_add_eq, IH hl.right, finset.sup_eq_union], suffices : disjoint hd.support (tl.foldr ((⊔) ∘ finsupp.support) ∅), { exact finset.disjoint_of_subset_right (list.support_sum_subset _) this }, { rw [←list.foldr_map, ←finset.bot_eq_empty, list.foldr_sup_eq_sup_to_finset], rw finset.disjoint_sup_right, intros f hf, simp only [list.mem_to_finset, list.mem_map] at hf, obtain ⟨f, hf, rfl⟩ := hf, exact hl.left _ hf } } end lemma multiset.support_sum_eq [add_comm_monoid M] (s : multiset (ι →₀ M)) (hs : s.pairwise (disjoint on finsupp.support)) : s.sum.support = (s.map finsupp.support).sup := begin induction s using quot.induction_on, obtain ⟨l, hl, hd⟩ := hs, convert list.support_sum_eq _ _, { simp }, { simp }, { simp only [multiset.quot_mk_to_coe'', multiset.coe_map, multiset.coe_eq_coe] at hl, exact hl.symm.pairwise hd (λ _ _ h, disjoint.symm h) } end lemma finset.support_sum_eq [add_comm_monoid M] (s : finset (ι →₀ M)) (hs : (s : set (ι →₀ M)).pairwise_disjoint finsupp.support) : (s.sum id).support = finset.sup s finsupp.support := begin classical, convert multiset.support_sum_eq s.1 _, { exact (finset.sum_val _).symm }, { obtain ⟨l, hl, hn⟩ : ∃ (l : list (ι →₀ M)), l.to_finset = s ∧ l.nodup, { refine ⟨s.to_list, _, finset.nodup_to_list _⟩, simp }, subst hl, rwa [list.to_finset_val, list.dedup_eq_self.mpr hn, multiset.pairwise_coe_iff_pairwise, ←list.pairwise_disjoint_iff_coe_to_finset_pairwise_disjoint hn], intros x y hxy, exact symmetric_disjoint hxy } end
d778be897f11816093114720ed20c4c597a8f0aa
94e33a31faa76775069b071adea97e86e218a8ee
/src/linear_algebra/matrix/basis.lean
d1ad9ce1df57ce9fb20cf73acadfdee14d760119
[ "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
9,523
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.reindex import linear_algebra.matrix.to_lin /-! # Bases and matrices This file defines the map `basis.to_matrix` that sends a family of vectors to the matrix of their coordinates with respect to some basis. ## Main definitions * `basis.to_matrix e v` is the matrix whose `i, j`th entry is `e.repr (v j) i` * `basis.to_matrix_equiv` is `basis.to_matrix` bundled as a linear equiv ## Main results * `linear_map.to_matrix_id_eq_basis_to_matrix`: `linear_map.to_matrix b c id` is equal to `basis.to_matrix b c` * `basis.to_matrix_mul_to_matrix`: multiplying `basis.to_matrix` with another `basis.to_matrix` gives a `basis.to_matrix` ## Tags matrix, basis -/ noncomputable theory open linear_map matrix set submodule open_locale big_operators open_locale matrix section basis_to_matrix variables {ι ι' κ κ' : Type*} variables {R M : Type*} [comm_semiring R] [add_comm_monoid M] [module R M] variables {R₂ M₂ : Type*} [comm_ring R₂] [add_comm_group M₂] [module R₂ M₂] open function matrix /-- From a basis `e : ι → M` and a family of vectors `v : ι' → M`, make the matrix whose columns are the vectors `v i` written in the basis `e`. -/ def basis.to_matrix (e : basis ι R M) (v : ι' → M) : matrix ι ι' R := λ i j, e.repr (v j) i variables (e : basis ι R M) (v : ι' → M) (i : ι) (j : ι') namespace basis lemma to_matrix_apply : e.to_matrix v i j = e.repr (v j) i := rfl lemma to_matrix_transpose_apply : (e.to_matrix v)ᵀ j = e.repr (v j) := funext $ (λ _, rfl) lemma to_matrix_eq_to_matrix_constr [fintype ι] [decidable_eq ι] (v : ι → M) : e.to_matrix v = linear_map.to_matrix e e (e.constr ℕ v) := by { ext, rw [basis.to_matrix_apply, linear_map.to_matrix_apply, basis.constr_basis] } -- TODO (maybe) Adjust the definition of `basis.to_matrix` to eliminate the transpose. lemma coe_pi_basis_fun.to_matrix_eq_transpose [fintype ι] : ((pi.basis_fun R ι).to_matrix : matrix ι ι R → matrix ι ι R) = matrix.transpose := by { ext M i j, refl, } @[simp] lemma to_matrix_self [decidable_eq ι] : e.to_matrix e = 1 := begin rw basis.to_matrix, ext i j, simp [basis.equiv_fun, matrix.one_apply, finsupp.single, eq_comm] end lemma to_matrix_update [decidable_eq ι'] (x : M) : e.to_matrix (function.update v j x) = matrix.update_column (e.to_matrix v) j (e.repr x) := begin ext i' k, rw [basis.to_matrix, matrix.update_column_apply, e.to_matrix_apply], split_ifs, { rw [h, update_same j x v] }, { rw update_noteq h }, end /-- The basis constructed by `units_smul` has vectors given by a diagonal matrix. -/ @[simp] lemma to_matrix_units_smul [decidable_eq ι] (e : basis ι R₂ M₂) (w : ι → R₂ˣ) : e.to_matrix (e.units_smul w) = diagonal (coe ∘ w) := begin ext i j, by_cases h : i = j, { simp [h, to_matrix_apply, units_smul_apply, units.smul_def] }, { simp [h, to_matrix_apply, units_smul_apply, units.smul_def, ne.symm h] } end /-- The basis constructed by `is_unit_smul` has vectors given by a diagonal matrix. -/ @[simp] lemma to_matrix_is_unit_smul [decidable_eq ι] (e : basis ι R₂ M₂) {w : ι → R₂} (hw : ∀ i, is_unit (w i)) : e.to_matrix (e.is_unit_smul hw) = diagonal w := e.to_matrix_units_smul _ @[simp] lemma sum_to_matrix_smul_self [fintype ι] : ∑ (i : ι), e.to_matrix v i j • e i = v j := by simp_rw [e.to_matrix_apply, e.sum_repr] lemma to_matrix_map_vec_mul {S : Type*} [ring S] [algebra R S] [fintype ι] (b : basis ι R S) (v : ι' → S) : ((b.to_matrix v).map $ algebra_map R S).vec_mul b = v := begin ext i, simp_rw [vec_mul, dot_product, matrix.map_apply, ← algebra.commutes, ← algebra.smul_def, sum_to_matrix_smul_self], end @[simp] lemma to_lin_to_matrix [fintype ι] [fintype ι'] [decidable_eq ι'] (v : basis ι' R M) : matrix.to_lin v e (e.to_matrix v) = id := v.ext (λ i, by rw [to_lin_self, id_apply, e.sum_to_matrix_smul_self]) /-- From a basis `e : ι → M`, build a linear equivalence between families of vectors `v : ι → M`, and matrices, making the matrix whose columns are the vectors `v i` written in the basis `e`. -/ def to_matrix_equiv [fintype ι] (e : basis ι R M) : (ι → M) ≃ₗ[R] matrix ι ι R := { to_fun := e.to_matrix, map_add' := λ v w, begin ext i j, change _ = _ + _, rw [e.to_matrix_apply, pi.add_apply, linear_equiv.map_add], refl end, map_smul' := begin intros c v, ext i j, rw [e.to_matrix_apply, pi.smul_apply, linear_equiv.map_smul], refl end, inv_fun := λ m j, ∑ i, (m i j) • e i, left_inv := begin intro v, ext j, exact e.sum_to_matrix_smul_self v j end, right_inv := begin intros m, ext k l, simp only [e.to_matrix_apply, ← e.equiv_fun_apply, ← e.equiv_fun_symm_apply, linear_equiv.apply_symm_apply], end } end basis section mul_linear_map_to_matrix variables {N : Type*} [add_comm_monoid N] [module R N] variables (b : basis ι R M) (b' : basis ι' R M) (c : basis κ R N) (c' : basis κ' R N) variables (f : M →ₗ[R] N) open linear_map section fintype variables [fintype ι'] [fintype κ] [fintype κ'] @[simp] lemma basis_to_matrix_mul_linear_map_to_matrix [decidable_eq ι'] : c.to_matrix c' ⬝ linear_map.to_matrix b' c' f = linear_map.to_matrix b' c f := (matrix.to_lin b' c).injective (by haveI := classical.dec_eq κ'; rw [to_lin_to_matrix, to_lin_mul b' c' c, to_lin_to_matrix, c.to_lin_to_matrix, id_comp]) variable [fintype ι] @[simp] lemma linear_map_to_matrix_mul_basis_to_matrix [decidable_eq ι] [decidable_eq ι'] : linear_map.to_matrix b' c' f ⬝ b'.to_matrix b = linear_map.to_matrix b c' f := (matrix.to_lin b c').injective (by rw [to_lin_to_matrix, to_lin_mul b b' c', to_lin_to_matrix, b'.to_lin_to_matrix, comp_id]) lemma basis_to_matrix_mul_linear_map_to_matrix_mul_basis_to_matrix [decidable_eq ι] [decidable_eq ι'] : c.to_matrix c' ⬝ linear_map.to_matrix b' c' f ⬝ b'.to_matrix b = linear_map.to_matrix b c f := by rw [basis_to_matrix_mul_linear_map_to_matrix, linear_map_to_matrix_mul_basis_to_matrix] lemma basis_to_matrix_mul [decidable_eq κ] (b₁ : basis ι R M) (b₂ : basis ι' R M) (b₃ : basis κ R N) (A : matrix ι' κ R) : b₁.to_matrix b₂ ⬝ A = linear_map.to_matrix b₃ b₁ (to_lin b₃ b₂ A) := begin have := basis_to_matrix_mul_linear_map_to_matrix b₃ b₁ b₂ (matrix.to_lin b₃ b₂ A), rwa [linear_map.to_matrix_to_lin] at this end lemma mul_basis_to_matrix [decidable_eq ι] [decidable_eq ι'] (b₁ : basis ι R M) (b₂ : basis ι' R M) (b₃ : basis κ R N) (A : matrix κ ι R) : A ⬝ b₁.to_matrix b₂ = linear_map.to_matrix b₂ b₃ (to_lin b₁ b₃ A) := begin have := linear_map_to_matrix_mul_basis_to_matrix b₂ b₁ b₃ (matrix.to_lin b₁ b₃ A), rwa [linear_map.to_matrix_to_lin] at this end lemma basis_to_matrix_basis_fun_mul (b : basis ι R (ι → R)) (A : matrix ι ι R) : b.to_matrix (pi.basis_fun R ι) ⬝ A = of (λ i j, b.repr (Aᵀ j) i) := begin classical, simp only [basis_to_matrix_mul _ _ (pi.basis_fun R ι), matrix.to_lin_eq_to_lin'], ext i j, rw [linear_map.to_matrix_apply, matrix.to_lin'_apply, pi.basis_fun_apply, matrix.mul_vec_std_basis_apply, matrix.of_apply] end /-- A generalization of `linear_map.to_matrix_id`. -/ @[simp] lemma linear_map.to_matrix_id_eq_basis_to_matrix [decidable_eq ι] : linear_map.to_matrix b b' id = b'.to_matrix b := by { haveI := classical.dec_eq ι', rw [←@basis_to_matrix_mul_linear_map_to_matrix _ _ ι, to_matrix_id, matrix.mul_one] } /-- See also `basis.to_matrix_reindex` which gives the `simp` normal form of this result. -/ lemma basis.to_matrix_reindex' [decidable_eq ι] [decidable_eq ι'] (b : basis ι R M) (v : ι' → M) (e : ι ≃ ι') : (b.reindex e).to_matrix v = matrix.reindex_alg_equiv _ e (b.to_matrix (v ∘ e)) := by { ext, simp only [basis.to_matrix_apply, basis.reindex_repr, matrix.reindex_alg_equiv_apply, matrix.reindex_apply, matrix.minor_apply, function.comp_app, e.apply_symm_apply] } end fintype /-- A generalization of `basis.to_matrix_self`, in the opposite direction. -/ @[simp] lemma basis.to_matrix_mul_to_matrix {ι'' : Type*} [fintype ι'] (b'' : ι'' → M) : b.to_matrix b' ⬝ b'.to_matrix b'' = b.to_matrix b'' := begin have := classical.dec_eq ι, have := classical.dec_eq ι', haveI := classical.dec_eq ι'', ext i j, simp only [matrix.mul_apply, basis.to_matrix_apply, basis.sum_repr_mul_repr], end /-- `b.to_matrix b'` and `b'.to_matrix b` are inverses. -/ lemma basis.to_matrix_mul_to_matrix_flip [decidable_eq ι] [fintype ι'] : b.to_matrix b' ⬝ b'.to_matrix b = 1 := by rw [basis.to_matrix_mul_to_matrix, basis.to_matrix_self] @[simp] lemma basis.to_matrix_reindex (b : basis ι R M) (v : ι' → M) (e : ι ≃ ι') : (b.reindex e).to_matrix v = (b.to_matrix v).minor e.symm id := by { ext, simp only [basis.to_matrix_apply, basis.reindex_repr, matrix.minor_apply, id.def] } @[simp] lemma basis.to_matrix_map (b : basis ι R M) (f : M ≃ₗ[R] N) (v : ι → N) : (b.map f).to_matrix v = b.to_matrix (f.symm ∘ v) := by { ext, simp only [basis.to_matrix_apply, basis.map, linear_equiv.trans_apply] } end mul_linear_map_to_matrix end basis_to_matrix
59cfd3a525aefd90163f77626bb212d515c96270
b2e508d02500f1512e1618150413e6be69d9db10
/src/category_theory/limits/opposites.lean
c20a70128dea19f6e8605f33aab34afecc6daff4
[ "Apache-2.0" ]
permissive
callum-sutton/mathlib
c3788f90216e9cd43eeffcb9f8c9f959b3b01771
afd623825a3ac6bfbcc675a9b023edad3f069e89
refs/heads/master
1,591,371,888,053
1,560,990,690,000
1,560,990,690,000
192,476,045
0
0
Apache-2.0
1,568,941,843,000
1,560,837,965,000
Lean
UTF-8
Lean
false
false
3,444
lean
-- Copyright (c) 2019 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Scott Morrison, Floris van Doorn import category_theory.limits.limits category_theory.discrete_category universes v u open category_theory open category_theory.functor open opposite namespace category_theory.limits variables {C : Type u} [𝒞 : category.{v+1} C] include 𝒞 variables {J : Type v} [small_category J] variable (F : J ⥤ Cᵒᵖ) instance [has_colimit.{v} F.left_op] : has_limit.{v} F := { cone := cone_of_cocone_left_op (colimit.cocone F.left_op), is_limit := { lift := λ s, (colimit.desc F.left_op (cocone_left_op_of_cone s)).op, fac' := λ s j, begin rw [cone_of_cocone_left_op_π_app, colimit.cocone_ι, ←op_comp, colimit.ι_desc, cocone_left_op_of_cone_ι_app, has_hom.hom.op_unop], refl, end, uniq' := λ s m w, begin -- It's a pity we can't do this automatically. -- Usually something like this would work by limit.hom_ext, -- but the opposites get in the way of this firing. have u := (colimit.is_colimit F.left_op).uniq (cocone_left_op_of_cone s) (m.unop), convert congr_arg (λ f : _ ⟶ _, f.op) (u _), clear u, intro j, rw [cocone_left_op_of_cone_ι_app, colimit.cocone_ι], convert congr_arg (λ f : _ ⟶ _, f.unop) (w (unop j)), clear w, rw [cone_of_cocone_left_op_π_app, colimit.cocone_ι, has_hom.hom.unop_op], refl, end } } instance [has_colimits_of_shape.{v} Jᵒᵖ C] : has_limits_of_shape.{v} J Cᵒᵖ := { has_limit := λ F, by apply_instance } instance [has_colimits.{v} C] : has_limits.{v} Cᵒᵖ := { has_limits_of_shape := λ J 𝒥, by { resetI, apply_instance } } instance [has_limit.{v} F.left_op] : has_colimit.{v} F := { cocone := cocone_of_cone_left_op (limit.cone F.left_op), is_colimit := { desc := λ s, (limit.lift F.left_op (cone_left_op_of_cocone s)).op, fac' := λ s j, begin rw [cocone_of_cone_left_op_ι_app, limit.cone_π, ←op_comp, limit.lift_π, cone_left_op_of_cocone_π_app, has_hom.hom.op_unop], refl, end, uniq' := λ s m w, begin have u := (limit.is_limit F.left_op).uniq (cone_left_op_of_cocone s) (m.unop), convert congr_arg (λ f : _ ⟶ _, f.op) (u _), clear u, intro j, rw [cone_left_op_of_cocone_π_app, limit.cone_π], convert congr_arg (λ f : _ ⟶ _, f.unop) (w (unop j)), clear w, rw [cocone_of_cone_left_op_ι_app, limit.cone_π, has_hom.hom.unop_op], refl, end } } instance [has_limits_of_shape.{v} Jᵒᵖ C] : has_colimits_of_shape.{v} J Cᵒᵖ := { has_colimit := λ F, by apply_instance } instance [has_limits.{v} C] : has_colimits.{v} Cᵒᵖ := { has_colimits_of_shape := λ J 𝒥, by { resetI, apply_instance } } variables (X : Type v) instance has_coproducts_opposite [has_limits_of_shape (discrete X) C] : has_colimits_of_shape (discrete X) Cᵒᵖ := begin haveI : has_limits_of_shape (discrete X)ᵒᵖ C := has_limits_of_shape_of_equivalence(discrete.opposite X).symm, apply_instance end instance has_products_opposite [has_colimits_of_shape (discrete X) C] : has_limits_of_shape (discrete X) Cᵒᵖ := begin haveI : has_colimits_of_shape (discrete X)ᵒᵖ C := has_colimits_of_shape_of_equivalence(discrete.opposite X).symm, apply_instance end end category_theory.limits
9915be1c3c97c34c7f7a396f67ffc464bcf77e23
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/topology/metric_space/metrizable_uniformity.lean
594f03f5112239f38b12db0371c5e9945b75c74b
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
14,515
lean
/- Copyright (c) 2022 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import topology.metric_space.metrizable /-! # Metrizable uniform spaces > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file we prove that a uniform space with countably generated uniformity filter is pseudometrizable: there exists a `pseudo_metric_space` structure that generates the same uniformity. The proof follows [Sergey Melikhov, Metrizable uniform spaces][melikhov2011]. ## Main definitions * `pseudo_metric_space.of_prenndist`: given a function `d : X → X → ℝ≥0` such that `d x x = 0` and `d x y = d y x` for all `x y : X`, constructs the maximal pseudo metric space structure such that `nndist x y ≤ d x y` for all `x y : X`. * `uniform_space.pseudo_metric_space`: given a uniform space `X` with countably generated `𝓤 X`, constructs a `pseudo_metric_space X` instance that is compatible with the uniform space structure. * `uniform_space.metric_space`: given a T₀ uniform space `X` with countably generated `𝓤 X`, constructs a `metric_space X` instance that is compatible with the uniform space structure. ## Main statements * `uniform_space.metrizable_uniformity`: if `X` is a uniform space with countably generated `𝓤 X`, then there exists a `pseudo_metric_space` structure that is compatible with this `uniform_space` structure. Use `uniform_space.pseudo_metric_space` or `uniform_space.metric_space` instead. * `uniform_space.pseudo_metrizable_space`: a uniform space with countably generated `𝓤 X` is pseudo metrizable. * `uniform_space.metrizable_space`: a T₀ uniform space with countably generated `𝓤 X` is metrizable. This is not an instance to avoid loops. ## Tags metrizable space, uniform space -/ open set function metric list filter open_locale nnreal filter uniformity variables {X : Type*} namespace pseudo_metric_space /-- The maximal pseudo metric space structure on `X` such that `dist x y ≤ d x y` for all `x y`, where `d : X → X → ℝ≥0` is a function such that `d x x = 0` and `d x y = d y x` for all `x`, `y`. -/ noncomputable def of_prenndist (d : X → X → ℝ≥0) (dist_self : ∀ x, d x x = 0) (dist_comm : ∀ x y, d x y = d y x) : pseudo_metric_space X := { dist := λ x y, ↑(⨅ l : list X, ((x :: l).zip_with d (l ++ [y])).sum : ℝ≥0), dist_self := λ x, (nnreal.coe_eq_zero _).2 $ nonpos_iff_eq_zero.1 $ (cinfi_le (order_bot.bdd_below _) []).trans_eq $ by simp [dist_self], dist_comm := λ x y, nnreal.coe_eq.2 $ begin refine reverse_surjective.infi_congr _ (λ l, _), rw [← sum_reverse, zip_with_distrib_reverse, reverse_append, reverse_reverse, reverse_singleton, singleton_append, reverse_cons, reverse_reverse, zip_with_comm_of_comm _ dist_comm], simp only [length, length_append] end, dist_triangle := λ x y z, begin rw [← nnreal.coe_add, nnreal.coe_le_coe], refine nnreal.le_infi_add_infi (λ lxy lyz, _), calc (⨅ l, (zip_with d (x :: l) (l ++ [z])).sum) ≤ (zip_with d (x :: (lxy ++ y :: lyz)) ((lxy ++ y :: lyz) ++ [z])).sum : cinfi_le (order_bot.bdd_below _) (lxy ++ y :: lyz) ... = (zip_with d (x :: lxy) (lxy ++ [y])).sum + (zip_with d (y :: lyz) (lyz ++ [z])).sum : _, rw [← sum_append, ← zip_with_append, cons_append, ← @singleton_append _ y, append_assoc, append_assoc, append_assoc], rw [length_cons, length_append, length_singleton] end } lemma dist_of_prenndist (d : X → X → ℝ≥0) (dist_self : ∀ x, d x x = 0) (dist_comm : ∀ x y, d x y = d y x) (x y : X) : @dist X (@pseudo_metric_space.to_has_dist X (pseudo_metric_space.of_prenndist d dist_self dist_comm)) x y = ↑(⨅ l : list X, ((x :: l).zip_with d (l ++ [y])).sum : ℝ≥0) := rfl lemma dist_of_prenndist_le (d : X → X → ℝ≥0) (dist_self : ∀ x, d x x = 0) (dist_comm : ∀ x y, d x y = d y x) (x y : X) : @dist X (@pseudo_metric_space.to_has_dist X (pseudo_metric_space.of_prenndist d dist_self dist_comm)) x y ≤ d x y := nnreal.coe_le_coe.2 $ (cinfi_le (order_bot.bdd_below _) []).trans_eq $ by simp /-- Consider a function `d : X → X → ℝ≥0` such that `d x x = 0` and `d x y = d y x` for all `x`, `y`. Let `dist` be the largest pseudometric distance such that `dist x y ≤ d x y`, see `pseudo_metric_space.of_prenndist`. Suppose that `d` satisfies the following triangle-like inequality: `d x₁ x₄ ≤ 2 * max (d x₁ x₂, d x₂ x₃, d x₃ x₄)`. Then `d x y ≤ 2 * dist x y` for all `x`, `y`. -/ lemma le_two_mul_dist_of_prenndist (d : X → X → ℝ≥0) (dist_self : ∀ x, d x x = 0) (dist_comm : ∀ x y, d x y = d y x) (hd : ∀ x₁ x₂ x₃ x₄, d x₁ x₄ ≤ 2 * max (d x₁ x₂) (max (d x₂ x₃) (d x₃ x₄))) (x y : X) : ↑(d x y) ≤ 2 * @dist X (@pseudo_metric_space.to_has_dist X (pseudo_metric_space.of_prenndist d dist_self dist_comm)) x y := begin /- We need to show that `d x y` is at most twice the sum `L` of `d xᵢ xᵢ₊₁` over a path `x₀=x, ..., xₙ=y`. We prove it by induction on the length `n` of the sequence. Find an edge that splits the path into two parts of almost equal length: both `d x₀ x₁ + ... + d xₖ₋₁ xₖ` and `d xₖ₊₁ xₖ₊₂ + ... + d xₙ₋₁ xₙ` are less than or equal to `L / 2`. Then `d x₀ xₖ ≤ L`, `d xₖ xₖ₊₁ ≤ L`, and `d xₖ₊₁ xₙ ≤ L`, thus `d x₀ xₙ ≤ 2 * L`. -/ rw [dist_of_prenndist, ← nnreal.coe_two, ← nnreal.coe_mul, nnreal.mul_infi, nnreal.coe_le_coe], refine le_cinfi (λ l, _), have hd₀_trans : transitive (λ x y, d x y = 0), { intros a b c hab hbc, rw ← nonpos_iff_eq_zero, simpa only [*, max_eq_right, mul_zero] using hd a b c c }, haveI : is_trans X (λ x y, d x y = 0) := ⟨hd₀_trans⟩, induction hn : length l using nat.strong_induction_on with n ihn generalizing x y l, simp only at ihn, subst n, set L := zip_with d (x :: l) (l ++ [y]), have hL_len : length L = length l + 1, by simp, cases eq_or_ne (d x y) 0 with hd₀ hd₀, { simp only [hd₀, zero_le] }, rsuffices ⟨z, z', hxz, hzz', hz'y⟩ : ∃ z z' : X, d x z ≤ L.sum ∧ d z z' ≤ L.sum ∧ d z' y ≤ L.sum, { exact (hd x z z' y).trans (mul_le_mul_left' (max_le hxz (max_le hzz' hz'y)) _) }, set s : set ℕ := {m : ℕ | 2 * (take m L).sum ≤ L.sum}, have hs₀ : 0 ∈ s, by simp [s], have hsne : s.nonempty, from ⟨0, hs₀⟩, obtain ⟨M, hMl, hMs⟩ : ∃ M ≤ length l, is_greatest s M, { have hs_ub : length l ∈ upper_bounds s, { intros m hm, rw [← not_lt, nat.lt_iff_add_one_le, ← hL_len], intro hLm, rw [mem_set_of_eq, take_all_of_le hLm, two_mul, add_le_iff_nonpos_left, nonpos_iff_eq_zero, sum_eq_zero_iff, ← all₂_iff_forall, all₂_zip_with, ← chain_append_singleton_iff_forall₂] at hm; [skip, by simp], exact hd₀ (hm.rel (mem_append.2 $ or.inr $ mem_singleton_self _)) }, have hs_bdd : bdd_above s, from ⟨length l, hs_ub⟩, exact ⟨Sup s, cSup_le hsne hs_ub, ⟨nat.Sup_mem hsne hs_bdd, λ k, le_cSup hs_bdd⟩⟩ }, have hM_lt : M < length L, by rwa [hL_len, nat.lt_succ_iff], have hM_ltx : M < length (x :: l), from lt_length_left_of_zip_with hM_lt, have hM_lty : M < length (l ++ [y]), from lt_length_right_of_zip_with hM_lt, refine ⟨(x :: l).nth_le M hM_ltx, (l ++ [y]).nth_le M hM_lty, _, _, _⟩, { cases M, { simp [dist_self] }, rw nat.succ_le_iff at hMl, have hMl' : length (take M l) = M, from (length_take _ _).trans (min_eq_left hMl.le), simp only [nth_le], refine (ihn _ hMl _ _ _ hMl').trans _, convert hMs.1.out, rw [zip_with_distrib_take, take, take_succ, nth_append hMl, nth_le_nth hMl, ← option.coe_def, option.to_list_some, take_append_of_le_length hMl.le], refl }, { refine single_le_sum (λ x hx, zero_le x) _ (mem_iff_nth_le.2 ⟨M, hM_lt, _⟩), apply nth_le_zip_with }, { rcases hMl.eq_or_lt with rfl|hMl, { simp only [nth_le_append_right le_rfl, sub_self, nth_le_singleton, dist_self, zero_le] }, rw [nth_le_append _ hMl], have hlen : length (drop (M + 1) l) = length l - (M + 1), from length_drop _ _, have hlen_lt : length l - (M + 1) < length l, from nat.sub_lt_of_pos_le _ _ M.succ_pos hMl, refine (ihn _ hlen_lt _ y _ hlen).trans _, rw [cons_nth_le_drop_succ], have hMs' : L.sum ≤ 2 * (L.take (M + 1)).sum, from not_lt.1 (λ h, (hMs.2 h.le).not_lt M.lt_succ_self), rw [← sum_take_add_sum_drop L (M + 1), two_mul, add_le_add_iff_left, ← add_le_add_iff_right, sum_take_add_sum_drop, ← two_mul] at hMs', convert hMs', rwa [zip_with_distrib_drop, drop, drop_append_of_le_length] } end end pseudo_metric_space /-- If `X` is a uniform space with countably generated uniformity filter, there exists a `pseudo_metric_space` structure compatible with the `uniform_space` structure. Use `uniform_space.pseudo_metric_space` or `uniform_space.metric_space` instead. -/ protected lemma uniform_space.metrizable_uniformity (X : Type*) [uniform_space X] [is_countably_generated (𝓤 X)] : ∃ I : pseudo_metric_space X, I.to_uniform_space = ‹_› := begin /- Choose a fast decreasing antitone basis `U : ℕ → set (X × X)` of the uniformity filter `𝓤 X`. Define `d x y : ℝ≥0` to be `(1 / 2) ^ n`, where `n` is the minimal index of `U n` that separates `x` and `y`: `(x, y) ∉ U n`, or `0` if `x` is not separated from `y`. This function satisfies the assumptions of `pseudo_metric_space.of_prenndist` and `pseudo_metric_space.le_two_mul_dist_of_prenndist`, hence the distance given by the former pseudo metric space structure is Lipschitz equivalent to the `d`. Thus the uniformities generated by `d` and `dist` are equal. Since the former uniformity is equal to `𝓤 X`, the latter is equal to `𝓤 X` as well. -/ classical, obtain ⟨U, hU_symm, hU_comp, hB⟩ : ∃ U : ℕ → set (X × X), (∀ n, symmetric_rel (U n)) ∧ (∀ ⦃m n⦄, m < n → U n ○ (U n ○ U n) ⊆ U m) ∧ (𝓤 X).has_antitone_basis U, { rcases uniform_space.has_seq_basis X with ⟨V, hB, hV_symm⟩, rcases hB.subbasis_with_rel (λ m, hB.tendsto_small_sets.eventually (eventually_uniformity_iterate_comp_subset (hB.mem m) 2)) with ⟨φ, hφ_mono, hφ_comp, hφB⟩, exact ⟨V ∘ φ, λ n, hV_symm _, hφ_comp, hφB⟩ }, letI := uniform_space.separation_setoid X, set d : X → X → ℝ≥0 := λ x y, if h : ∃ n, (x, y) ∉ U n then (1 / 2) ^ nat.find h else 0, have hd₀ : ∀ {x y}, d x y = 0 ↔ x ≈ y, { intros x y, dsimp only [d], refine iff.trans _ hB.to_has_basis.mem_separation_rel.symm, simp only [true_implies_iff], split_ifs with h, { rw [← not_forall] at h, simp [h, pow_eq_zero_iff'] }, { simpa only [not_exists, not_not, eq_self_iff_true, true_iff] using h } }, have hd_symm : ∀ x y, d x y = d y x, { intros x y, dsimp only [d], simp only [@symmetric_rel.mk_mem_comm _ _ (hU_symm _) x y] }, have hr : (1 / 2 : ℝ≥0) ∈ Ioo (0 : ℝ≥0) 1, from ⟨half_pos one_pos, nnreal.half_lt_self one_ne_zero⟩, letI I := pseudo_metric_space.of_prenndist d (λ x, hd₀.2 (setoid.refl _)) hd_symm, have hdist_le : ∀ x y, dist x y ≤ d x y, from pseudo_metric_space.dist_of_prenndist_le _ _ _, have hle_d : ∀ {x y : X} {n : ℕ}, (1 / 2) ^ n ≤ d x y ↔ (x, y) ∉ U n, { intros x y n, simp only [d], split_ifs with h, { rw [(strict_anti_pow hr.1 hr.2).le_iff_le, nat.find_le_iff], exact ⟨λ ⟨m, hmn, hm⟩ hn, hm (hB.antitone hmn hn), λ h, ⟨n, le_rfl, h⟩⟩ }, { push_neg at h, simp only [h, not_true, (pow_pos hr.1 _).not_le] } }, have hd_le : ∀ x y, ↑(d x y) ≤ 2 * dist x y, { refine pseudo_metric_space.le_two_mul_dist_of_prenndist _ _ _ (λ x₁ x₂ x₃ x₄, _), by_cases H : ∃ n, (x₁, x₄) ∉ U n, { refine (dif_pos H).trans_le _, rw [← nnreal.div_le_iff' two_ne_zero, ← mul_one_div (_ ^ _), ← pow_succ'], simp only [le_max_iff, hle_d, ← not_and_distrib], rintro ⟨h₁₂, h₂₃, h₃₄⟩, refine nat.find_spec H (hU_comp (lt_add_one $ nat.find H) _), exact ⟨x₂, h₁₂, x₃, h₂₃, h₃₄⟩ }, { exact (dif_neg H).trans_le (zero_le _) } }, refine ⟨I, uniform_space_eq $ (uniformity_basis_dist_pow hr.1 hr.2).ext hB.to_has_basis _ _⟩, { refine λ n hn, ⟨n, hn, λ x hx, (hdist_le _ _).trans_lt _⟩, rwa [← nnreal.coe_pow, nnreal.coe_lt_coe, ← not_le, hle_d, not_not, prod.mk.eta] }, { refine λ n hn, ⟨n + 1, trivial, λ x hx, _⟩, rw [mem_set_of_eq] at hx, contrapose! hx, refine le_trans _ ((div_le_iff' (zero_lt_two' ℝ)).2 (hd_le x.1 x.2)), rwa [← nnreal.coe_two, ← nnreal.coe_div, ← nnreal.coe_pow, nnreal.coe_le_coe, pow_succ', mul_one_div, nnreal.div_le_iff two_ne_zero, div_mul_cancel _ (two_ne_zero' ℝ≥0), hle_d, prod.mk.eta] } end /-- A `pseudo_metric_space` instance compatible with a given `uniform_space` structure. -/ protected noncomputable def uniform_space.pseudo_metric_space (X : Type*) [uniform_space X] [is_countably_generated (𝓤 X)] : pseudo_metric_space X := (uniform_space.metrizable_uniformity X).some.replace_uniformity $ congr_arg _ (uniform_space.metrizable_uniformity X).some_spec.symm /-- A `metric_space` instance compatible with a given `uniform_space` structure. -/ protected noncomputable def uniform_space.metric_space (X : Type*) [uniform_space X] [is_countably_generated (𝓤 X)] [t0_space X] : metric_space X := @metric_space.of_t0_pseudo_metric_space X (uniform_space.pseudo_metric_space X) _ /-- A uniform space with countably generated `𝓤 X` is pseudo metrizable. -/ @[priority 100] instance uniform_space.pseudo_metrizable_space [uniform_space X] [is_countably_generated (𝓤 X)] : topological_space.pseudo_metrizable_space X := by { letI := uniform_space.pseudo_metric_space X, apply_instance } /-- A T₀ uniform space with countably generated `𝓤 X` is metrizable. This is not an instance to avoid loops. -/ lemma uniform_space.metrizable_space [uniform_space X] [is_countably_generated (𝓤 X)] [t0_space X] : topological_space.metrizable_space X := by { letI := uniform_space.metric_space X, apply_instance }
c54db695d52c161488dd8f3758f142146e0ea435
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/algebra/big_operators/finprod.lean
4eb018173f5452c53a270222fa44ff7038eb3aa7
[ "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
39,653
lean
/- Copyright (c) 2020 Kexing Ying and Kevin Buzzard. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kexing Ying, Kevin Buzzard, Yury Kudryashov -/ import algebra.big_operators.order import algebra.indicator_function import data.set.pairwise /-! # Finite products and sums over types and sets We define products and sums over types and subsets of types, with no finiteness hypotheses. All infinite products and sums are defined to be junk values (i.e. one or zero). This approach is sometimes easier to use than `finset.sum`, when issues arise with `finset` and `fintype` being data. ## Main definitions We use the following variables: * `α`, `β` - types with no structure; * `s`, `t` - sets * `M`, `N` - additive or multiplicative commutative monoids * `f`, `g` - functions Definitions in this file: * `finsum f : M` : the sum of `f x` as `x` ranges over the support of `f`, if it's finite. Zero otherwise. * `finprod f : M` : the product of `f x` as `x` ranges over the multiplicative support of `f`, if it's finite. One otherwise. ## Notation * `∑ᶠ i, f i` and `∑ᶠ i : α, f i` for `finsum f` * `∏ᶠ i, f i` and `∏ᶠ i : α, f i` for `finprod f` This notation works for functions `f : p → M`, where `p : Prop`, so the following works: * `∑ᶠ i ∈ s, f i`, where `f : α → M`, `s : set α` : sum over the set `s`; * `∑ᶠ n < 5, f n`, where `f : ℕ → M` : same as `f 0 + f 1 + f 2 + f 3 + f 4`; * `∏ᶠ (n >= -2) (hn : n < 3), f n`, where `f : ℤ → M` : same as `f (-2) * f (-1) * f 0 * f 1 * f 2`. ## Implementation notes `finsum` and `finprod` is "yet another way of doing finite sums and products in Lean". However experiments in the wild (e.g. with matroids) indicate that it is a helpful approach in settings where the user is not interested in computability and wants to do reasoning without running into typeclass diamonds caused by the constructive finiteness used in definitions such as `finset` and `fintype`. By sticking solely to `set.finite` we avoid these problems. We are aware that there are other solutions but for beginner mathematicians this approach is easier in practice. Another application is the construction of a partition of unity from a collection of “bump” function. In this case the finite set depends on the point and it's convenient to have a definition that does not mention the set explicitly. The first arguments in all definitions and lemmas is the codomain of the function of the big operator. This is necessary for the heuristic in `@[to_additive]`. See the documentation of `to_additive.attr` for more information. We did not add `is_finite (X : Type) : Prop`, because it is simply `nonempty (fintype X)`. ## Tags finsum, finprod, finite sum, finite product -/ open function set /-! ### Definition and relation to `finset.sum` and `finset.prod` -/ section sort variables {M N : Type*} {α β ι : Sort*} [comm_monoid M] [comm_monoid N] open_locale big_operators section /- Note: we use classical logic only for these definitions, to ensure that we do not write lemmas with `classical.dec` in their statement. -/ open_locale classical /-- Sum of `f x` as `x` ranges over the elements of the support of `f`, if it's finite. Zero otherwise. -/ @[irreducible] noncomputable def finsum {M α} [add_comm_monoid M] (f : α → M) : M := if h : finite (support (f ∘ plift.down)) then ∑ i in h.to_finset, f i.down else 0 /-- Product of `f x` as `x` ranges over the elements of the multiplicative support of `f`, if it's finite. One otherwise. -/ @[irreducible, to_additive] noncomputable def finprod (f : α → M) : M := if h : finite (mul_support (f ∘ plift.down)) then ∏ i in h.to_finset, f i.down else 1 end localized "notation `∑ᶠ` binders `, ` r:(scoped:67 f, finsum f) := r" in big_operators localized "notation `∏ᶠ` binders `, ` r:(scoped:67 f, finprod f) := r" in big_operators @[to_additive] lemma finprod_eq_prod_plift_of_mul_support_to_finset_subset {f : α → M} (hf : finite (mul_support (f ∘ plift.down))) {s : finset (plift α)} (hs : hf.to_finset ⊆ s) : ∏ᶠ i, f i = ∏ i in s, f i.down := begin rw [finprod, dif_pos], refine finset.prod_subset hs (λ x hx hxf, _), rwa [hf.mem_to_finset, nmem_mul_support] at hxf end @[to_additive] lemma finprod_eq_prod_plift_of_mul_support_subset {f : α → M} {s : finset (plift α)} (hs : mul_support (f ∘ plift.down) ⊆ s) : ∏ᶠ i, f i = ∏ i in s, f i.down := finprod_eq_prod_plift_of_mul_support_to_finset_subset (s.finite_to_set.subset hs) $ λ x hx, by { rw finite.mem_to_finset at hx, exact hs hx } @[simp, to_additive] lemma finprod_one : ∏ᶠ i : α, (1 : M) = 1 := begin have : mul_support (λ x : plift α, (λ _, 1 : α → M) x.down) ⊆ (∅ : finset (plift α)), from λ x h, h rfl, rw [finprod_eq_prod_plift_of_mul_support_subset this, finset.prod_empty] end @[to_additive] lemma finprod_of_is_empty [is_empty α] (f : α → M) : ∏ᶠ i, f i = 1 := by { rw ← finprod_one, congr } @[simp, to_additive] lemma finprod_false (f : false → M) : ∏ᶠ i, f i = 1 := finprod_of_is_empty _ @[to_additive] lemma finprod_eq_single (f : α → M) (a : α) (ha : ∀ x ≠ a, f x = 1) : ∏ᶠ x, f x = f a := begin have : mul_support (f ∘ plift.down) ⊆ ({plift.up a} : finset (plift α)), { intro x, contrapose, simpa [plift.eq_up_iff_down_eq] using ha x.down }, rw [finprod_eq_prod_plift_of_mul_support_subset this, finset.prod_singleton], end @[to_additive] lemma finprod_unique [unique α] (f : α → M) : ∏ᶠ i, f i = f (default α) := finprod_eq_single f (default α) $ λ x hx, (hx $ unique.eq_default _).elim @[simp, to_additive] lemma finprod_true (f : true → M) : ∏ᶠ i, f i = f trivial := @finprod_unique M true _ ⟨⟨trivial⟩, λ _, rfl⟩ f @[to_additive] lemma finprod_eq_dif {p : Prop} [decidable p] (f : p → M) : ∏ᶠ i, f i = if h : p then f h else 1 := begin split_ifs, { haveI : unique p := ⟨⟨h⟩, λ _, rfl⟩, exact finprod_unique f }, { haveI : is_empty p := ⟨h⟩, exact finprod_of_is_empty f } end @[to_additive] lemma finprod_eq_if {p : Prop} [decidable p] {x : M} : ∏ᶠ i : p, x = if p then x else 1 := finprod_eq_dif (λ _, x) @[to_additive] lemma finprod_congr {f g : α → M} (h : ∀ x, f x = g x) : finprod f = finprod g := congr_arg _ $ funext h @[congr, to_additive] lemma finprod_congr_Prop {p q : Prop} {f : p → M} {g : q → M} (hpq : p = q) (hfg : ∀ h : q, f (hpq.mpr h) = g h) : finprod f = finprod g := by { subst q, exact finprod_congr hfg } attribute [congr] finsum_congr_Prop /-- To prove a property of a finite product, it suffices to prove that the property is multiplicative and holds on multipliers. -/ @[to_additive] lemma finprod_induction {f : α → M} (p : M → Prop) (hp₀ : p 1) (hp₁ : ∀ x y, p x → p y → p (x * y)) (hp₂ : ∀ i, p (f i)) : p (∏ᶠ i, f i) := begin rw finprod, split_ifs, exacts [finset.prod_induction _ _ hp₁ hp₀ (λ i hi, hp₂ _), hp₀] end /-- To prove a property of a finite sum, it suffices to prove that the property is additive and holds on summands. -/ add_decl_doc finsum_induction lemma finprod_nonneg {R : Type*} [ordered_comm_semiring R] {f : α → R} (hf : ∀ x, 0 ≤ f x) : 0 ≤ ∏ᶠ x, f x := finprod_induction (λ x, 0 ≤ x) zero_le_one (λ x y, mul_nonneg) hf @[to_additive finsum_nonneg] lemma one_le_finprod' {M : Type*} [ordered_comm_monoid M] {f : α → M} (hf : ∀ i, 1 ≤ f i) : 1 ≤ ∏ᶠ i, f i := finprod_induction _ le_rfl (λ _ _, one_le_mul) hf @[to_additive] lemma monoid_hom.map_finprod_plift (f : M →* N) (g : α → M) (h : finite (mul_support $ g ∘ plift.down)) : f (∏ᶠ x, g x) = ∏ᶠ x, f (g x) := begin rw [finprod_eq_prod_plift_of_mul_support_subset h.coe_to_finset.ge, finprod_eq_prod_plift_of_mul_support_subset, f.map_prod], rw [h.coe_to_finset], exact mul_support_comp_subset f.map_one (g ∘ plift.down) end @[to_additive] lemma monoid_hom.map_finprod_Prop {p : Prop} (f : M →* N) (g : p → M) : f (∏ᶠ x, g x) = ∏ᶠ x, f (g x) := f.map_finprod_plift g (finite.of_fintype _) @[to_additive] lemma monoid_hom.map_finprod_of_preimage_one (f : M →* N) (hf : ∀ x, f x = 1 → x = 1) (g : α → M) : f (∏ᶠ i, g i) = ∏ᶠ i, f (g i) := begin by_cases hg : (mul_support $ g ∘ plift.down).finite, { exact f.map_finprod_plift g hg }, rw [finprod, dif_neg, f.map_one, finprod, dif_neg], exacts [infinite.mono (λ x hx, mt (hf (g x.down)) hx) hg, hg] end @[to_additive] lemma monoid_hom.map_finprod_of_injective (g : M →* N) (hg : injective g) (f : α → M) : g (∏ᶠ i, f i) = ∏ᶠ i, g (f i) := g.map_finprod_of_preimage_one (λ x, (hg.eq_iff' g.map_one).mp) f @[to_additive] lemma mul_equiv.map_finprod (g : M ≃* N) (f : α → M) : g (∏ᶠ i, f i) = ∏ᶠ i, g (f i) := g.to_monoid_hom.map_finprod_of_injective g.injective f lemma finsum_smul {R M : Type*} [ring R] [add_comm_group M] [module R M] [no_zero_smul_divisors R M] (f : ι → R) (x : M) : (∑ᶠ i, f i) • x = (∑ᶠ i, (f i) • x) := begin rcases eq_or_ne x 0 with rfl|hx, { simp }, exact ((smul_add_hom R M).flip x).map_finsum_of_injective (smul_left_injective R hx) _ end lemma smul_finsum {R M : Type*} [ring R] [add_comm_group M] [module R M] [no_zero_smul_divisors R M] (c : R) (f : ι → M) : c • (∑ᶠ i, f i) = (∑ᶠ i, c • f i) := begin rcases eq_or_ne c 0 with rfl|hc, { simp }, exact (smul_add_hom R M c).map_finsum_of_injective (smul_right_injective M hc) _ end @[to_additive] lemma finprod_inv_distrib {G : Type*} [comm_group G] (f : α → G) : ∏ᶠ x, (f x)⁻¹ = (∏ᶠ x, f x)⁻¹ := ((mul_equiv.inv G).map_finprod f).symm end sort section type variables {α β ι M N : Type*} [comm_monoid M] [comm_monoid N] open_locale big_operators @[to_additive] lemma finprod_eq_mul_indicator_apply (s : set α) (f : α → M) (a : α) : ∏ᶠ (h : a ∈ s), f a = mul_indicator s f a := by convert finprod_eq_if @[simp, to_additive] lemma finprod_mem_mul_support (f : α → M) (a : α) : ∏ᶠ (h : f a ≠ 1), f a = f a := by rw [← mem_mul_support, finprod_eq_mul_indicator_apply, mul_indicator_mul_support] @[to_additive] lemma finprod_mem_def (s : set α) (f : α → M) : ∏ᶠ a ∈ s, f a = ∏ᶠ a, mul_indicator s f a := finprod_congr $ finprod_eq_mul_indicator_apply s f @[to_additive] lemma finprod_eq_prod_of_mul_support_subset (f : α → M) {s : finset α} (h : mul_support f ⊆ s) : ∏ᶠ i, f i = ∏ i in s, f i := begin have A : mul_support (f ∘ plift.down) = equiv.plift.symm '' mul_support f, { rw mul_support_comp_eq_preimage, exact (equiv.plift.symm.image_eq_preimage _).symm }, have : mul_support (f ∘ plift.down) ⊆ s.map equiv.plift.symm.to_embedding, { rw [A, finset.coe_map], exact image_subset _ h }, rw [finprod_eq_prod_plift_of_mul_support_subset this], simp end @[to_additive] lemma finprod_eq_prod_of_mul_support_to_finset_subset (f : α → M) (hf : finite (mul_support f)) {s : finset α} (h : hf.to_finset ⊆ s) : ∏ᶠ i, f i = ∏ i in s, f i := finprod_eq_prod_of_mul_support_subset _ $ λ x hx, h $ hf.mem_to_finset.2 hx @[to_additive] lemma finprod_def (f : α → M) [decidable (mul_support f).finite] : ∏ᶠ i : α, f i = if h : (mul_support f).finite then ∏ i in h.to_finset, f i else 1 := begin split_ifs, { exact finprod_eq_prod_of_mul_support_to_finset_subset _ h (finset.subset.refl _) }, { rw [finprod, dif_neg], rw [mul_support_comp_eq_preimage], exact mt (λ hf, hf.of_preimage equiv.plift.surjective) h} end @[to_additive] lemma finprod_of_infinite_mul_support {f : α → M} (hf : (mul_support f).infinite) : ∏ᶠ i, f i = 1 := by { classical, rw [finprod_def, dif_neg hf] } @[to_additive] lemma finprod_eq_prod (f : α → M) (hf : (mul_support f).finite) : ∏ᶠ i : α, f i = ∏ i in hf.to_finset, f i := by { classical, rw [finprod_def, dif_pos hf] } @[to_additive] lemma finprod_eq_prod_of_fintype [fintype α] (f : α → M) : ∏ᶠ i : α, f i = ∏ i, f i := finprod_eq_prod_of_mul_support_to_finset_subset _ (finite.of_fintype _) $ finset.subset_univ _ @[to_additive] lemma finprod_cond_eq_prod_of_cond_iff (f : α → M) {p : α → Prop} {t : finset α} (h : ∀ {x}, f x ≠ 1 → (p x ↔ x ∈ t)) : ∏ᶠ i (hi : p i), f i = ∏ i in t, f i := begin set s := {x | p x}, have : mul_support (s.mul_indicator f) ⊆ t, { rw [set.mul_support_mul_indicator], intros x hx, exact (h hx.2).1 hx.1 }, erw [finprod_mem_def, finprod_eq_prod_of_mul_support_subset _ this], refine finset.prod_congr rfl (λ x hx, mul_indicator_apply_eq_self.2 $ λ hxs, _), contrapose! hxs, exact (h hxs).2 hx end @[to_additive] lemma finprod_mem_eq_prod_of_inter_mul_support_eq (f : α → M) {s : set α} {t : finset α} (h : s ∩ mul_support f = t ∩ mul_support f) : ∏ᶠ i ∈ s, f i = ∏ i in t, f i := finprod_cond_eq_prod_of_cond_iff _ $ by simpa [set.ext_iff] using h @[to_additive] lemma finprod_mem_eq_prod_of_subset (f : α → M) {s : set α} {t : finset α} (h₁ : s ∩ mul_support f ⊆ t) (h₂ : ↑t ⊆ s) : ∏ᶠ i ∈ s, f i = ∏ i in t, f i := finprod_cond_eq_prod_of_cond_iff _ $ λ x hx, ⟨λ h, h₁ ⟨h, hx⟩, λ h, h₂ h⟩ @[to_additive] lemma finprod_mem_eq_prod (f : α → M) {s : set α} (hf : (s ∩ mul_support f).finite) : ∏ᶠ i ∈ s, f i = ∏ i in hf.to_finset, f i := finprod_mem_eq_prod_of_inter_mul_support_eq _ $ by simp [inter_assoc] @[to_additive] lemma finprod_mem_eq_prod_filter (f : α → M) (s : set α) [decidable_pred (∈ s)] (hf : (mul_support f).finite) : ∏ᶠ i ∈ s, f i = ∏ i in finset.filter (∈ s) hf.to_finset, f i := finprod_mem_eq_prod_of_inter_mul_support_eq _ $ by simp [inter_comm, inter_left_comm] @[to_additive] lemma finprod_mem_eq_to_finset_prod (f : α → M) (s : set α) [fintype s] : ∏ᶠ i ∈ s, f i = ∏ i in s.to_finset, f i := finprod_mem_eq_prod_of_inter_mul_support_eq _ $ by rw [coe_to_finset] @[to_additive] lemma finprod_mem_eq_finite_to_finset_prod (f : α → M) {s : set α} (hs : s.finite) : ∏ᶠ i ∈ s, f i = ∏ i in hs.to_finset, f i := finprod_mem_eq_prod_of_inter_mul_support_eq _ $ by rw [hs.coe_to_finset] @[to_additive] lemma finprod_mem_finset_eq_prod (f : α → M) (s : finset α) : ∏ᶠ i ∈ s, f i = ∏ i in s, f i := finprod_mem_eq_prod_of_inter_mul_support_eq _ rfl @[to_additive] lemma finprod_mem_coe_finset (f : α → M) (s : finset α) : ∏ᶠ i ∈ (s : set α), f i = ∏ i in s, f i := finprod_mem_eq_prod_of_inter_mul_support_eq _ rfl @[to_additive] lemma finprod_mem_eq_one_of_infinite {f : α → M} {s : set α} (hs : (s ∩ mul_support f).infinite) : ∏ᶠ i ∈ s, f i = 1 := begin rw finprod_mem_def, apply finprod_of_infinite_mul_support, rwa [← mul_support_mul_indicator] at hs end @[to_additive] lemma finprod_mem_inter_mul_support (f : α → M) (s : set α) : ∏ᶠ i ∈ (s ∩ mul_support f), f i = ∏ᶠ i ∈ s, f i := by rw [finprod_mem_def, finprod_mem_def, mul_indicator_inter_mul_support] @[to_additive] lemma finprod_mem_inter_mul_support_eq (f : α → M) (s t : set α) (h : s ∩ mul_support f = t ∩ mul_support f) : ∏ᶠ i ∈ s, f i = ∏ᶠ i ∈ t, f i := by rw [← finprod_mem_inter_mul_support, h, finprod_mem_inter_mul_support] @[to_additive] lemma finprod_mem_inter_mul_support_eq' (f : α → M) (s t : set α) (h : ∀ x ∈ mul_support f, x ∈ s ↔ x ∈ t) : ∏ᶠ i ∈ s, f i = ∏ᶠ i ∈ t, f i := begin apply finprod_mem_inter_mul_support_eq, ext x, exact and_congr_left (h x) end @[to_additive] lemma finprod_mem_univ (f : α → M) : ∏ᶠ i ∈ @set.univ α, f i = ∏ᶠ i : α, f i := finprod_congr $ λ i, finprod_true _ variables {f g : α → M} {a b : α} {s t : set α} @[to_additive] lemma finprod_mem_congr (h₀ : s = t) (h₁ : ∀ x ∈ t, f x = g x) : ∏ᶠ i ∈ s, f i = ∏ᶠ i ∈ t, g i := h₀.symm ▸ (finprod_congr $ λ i, finprod_congr_Prop rfl (h₁ i)) /-! ### Distributivity w.r.t. addition, subtraction, and (scalar) multiplication -/ /-- If the multiplicative supports of `f` and `g` are finite, then the product of `f i * g i` equals the product of `f i` multiplied by the product over `g i`. -/ @[to_additive] lemma finprod_mul_distrib (hf : (mul_support f).finite) (hg : (mul_support g).finite) : ∏ᶠ i, (f i * g i) = (∏ᶠ i, f i) * ∏ᶠ i, g i := begin classical, rw [finprod_eq_prod_of_mul_support_to_finset_subset _ hf (finset.subset_union_left _ _), finprod_eq_prod_of_mul_support_to_finset_subset _ hg (finset.subset_union_right _ _), ← finset.prod_mul_distrib], refine finprod_eq_prod_of_mul_support_subset _ _, simp [mul_support_mul] end /-- A more general version of `finprod_mem_mul_distrib` that requires `s ∩ mul_support f` and `s ∩ mul_support g` instead of `s` to be finite. -/ @[to_additive] lemma finprod_mem_mul_distrib' (hf : (s ∩ mul_support f).finite) (hg : (s ∩ mul_support g).finite) : ∏ᶠ i ∈ s, (f i * g i) = (∏ᶠ i ∈ s, f i) * ∏ᶠ i ∈ s, g i := begin rw [← mul_support_mul_indicator] at hf hg, simp only [finprod_mem_def, mul_indicator_mul, finprod_mul_distrib hf hg] end /-- The product of constant one over any set equals one. -/ @[to_additive] lemma finprod_mem_one (s : set α) : ∏ᶠ i ∈ s, (1 : M) = 1 := by simp /-- If a function `f` equals one on a set `s`, then the product of `f i` over `i ∈ s` equals one. -/ @[to_additive] lemma finprod_mem_of_eq_on_one (hf : eq_on f 1 s) : ∏ᶠ i ∈ s, f i = 1 := by { rw ← finprod_mem_one s, exact finprod_mem_congr rfl hf } /-- If the product of `f i` over `i ∈ s` is not equal to one, then there is some `x ∈ s` such that `f x ≠ 1`. -/ @[to_additive] lemma exists_ne_one_of_finprod_mem_ne_one (h : ∏ᶠ i ∈ s, f i ≠ 1) : ∃ x ∈ s, f x ≠ 1 := begin by_contra h', push_neg at h', exact h (finprod_mem_of_eq_on_one h') end /-- Given a finite set `s`, the product of `f i * g i` over `i ∈ s` equals the product of `f i` over `i ∈ s` times the product of `g i` over `i ∈ s`. -/ @[to_additive] lemma finprod_mem_mul_distrib (hs : s.finite) : ∏ᶠ i ∈ s, (f i * g i) = (∏ᶠ i ∈ s, f i) * ∏ᶠ i ∈ s, g i := finprod_mem_mul_distrib' (hs.inter_of_left _) (hs.inter_of_left _) @[to_additive] lemma monoid_hom.map_finprod {f : α → M} (g : M →* N) (hf : (mul_support f).finite) : g (∏ᶠ i, f i) = ∏ᶠ i, g (f i) := g.map_finprod_plift f $ hf.preimage $ equiv.plift.injective.inj_on _ /-- A more general version of `monoid_hom.map_finprod_mem` that requires `s ∩ mul_support f` and instead of `s` to be finite. -/ @[to_additive] lemma monoid_hom.map_finprod_mem' {f : α → M} (g : M →* N) (h₀ : (s ∩ mul_support f).finite) : g (∏ᶠ j ∈ s, f j) = ∏ᶠ i ∈ s, (g (f i)) := begin rw [g.map_finprod], { simp only [g.map_finprod_Prop] }, { simpa only [finprod_eq_mul_indicator_apply, mul_support_mul_indicator] } end /-- Given a monoid homomorphism `g : M →* N`, and a function `f : α → M`, the value of `g` at the product of `f i` over `i ∈ s` equals the product of `(g ∘ f) i` over `s`. -/ @[to_additive] lemma monoid_hom.map_finprod_mem (f : α → M) (g : M →* N) (hs : s.finite) : g (∏ᶠ j ∈ s, f j) = ∏ᶠ i ∈ s, g (f i) := g.map_finprod_mem' (hs.inter_of_left _) /-! ### `∏ᶠ x ∈ s, f x` and set operations -/ /-- The product of any function over an empty set is one. -/ @[to_additive] lemma finprod_mem_empty : ∏ᶠ i ∈ (∅ : set α), f i = 1 := by simp /-- A set `s` is not empty if the product of some function over `s` is not equal to one. -/ @[to_additive] lemma nonempty_of_finprod_mem_ne_one (h : ∏ᶠ i ∈ s, f i ≠ 1) : s.nonempty := ne_empty_iff_nonempty.1 $ λ h', h $ h'.symm ▸ finprod_mem_empty /-- Given finite sets `s` and `t`, the product of `f i` over `i ∈ s ∪ t` times the product of `f i` over `i ∈ s ∩ t` equals the product of `f i` over `i ∈ s` times the product of `f i` over `i ∈ t`. -/ @[to_additive] lemma finprod_mem_union_inter (hs : s.finite) (ht : t.finite) : (∏ᶠ i ∈ s ∪ t, f i) * ∏ᶠ i ∈ s ∩ t, f i = (∏ᶠ i ∈ s, f i) * ∏ᶠ i ∈ t, f i := begin lift s to finset α using hs, lift t to finset α using ht, classical, rw [← finset.coe_union, ← finset.coe_inter], simp only [finprod_mem_coe_finset, finset.prod_union_inter] end /-- A more general version of `finprod_mem_union_inter` that requires `s ∩ mul_support f` and `t ∩ mul_support f` instead of `s` and `t` to be finite. -/ @[to_additive] lemma finprod_mem_union_inter' (hs : (s ∩ mul_support f).finite) (ht : (t ∩ mul_support f).finite) : (∏ᶠ i ∈ s ∪ t, f i) * ∏ᶠ i ∈ s ∩ t, f i = (∏ᶠ i ∈ s, f i) * ∏ᶠ i ∈ t, f i := begin rw [← finprod_mem_inter_mul_support f s, ← finprod_mem_inter_mul_support f t, ← finprod_mem_union_inter hs ht, ← union_inter_distrib_right, finprod_mem_inter_mul_support, ← finprod_mem_inter_mul_support f (s ∩ t)], congr' 2, rw [inter_left_comm, inter_assoc, inter_assoc, inter_self, inter_left_comm] end /-- A more general version of `finprod_mem_union` that requires `s ∩ mul_support f` and `t ∩ mul_support f` instead of `s` and `t` to be finite. -/ @[to_additive] lemma finprod_mem_union' (hst : disjoint s t) (hs : (s ∩ mul_support f).finite) (ht : (t ∩ mul_support f).finite) : ∏ᶠ i ∈ s ∪ t, f i = (∏ᶠ i ∈ s, f i) * ∏ᶠ i ∈ t, f i := by rw [← finprod_mem_union_inter' hs ht, disjoint_iff_inter_eq_empty.1 hst, finprod_mem_empty, mul_one] /-- Given two finite disjoint sets `s` and `t`, the product of `f i` over `i ∈ s ∪ t` equals the product of `f i` over `i ∈ s` times the product of `f i` over `i ∈ t`. -/ @[to_additive] lemma finprod_mem_union (hst : disjoint s t) (hs : s.finite) (ht : t.finite) : ∏ᶠ i ∈ s ∪ t, f i = (∏ᶠ i ∈ s, f i) * ∏ᶠ i ∈ t, f i := finprod_mem_union' hst (hs.inter_of_left _) (ht.inter_of_left _) /-- A more general version of `finprod_mem_union'` that requires `s ∩ mul_support f` and `t ∩ mul_support f` instead of `s` and `t` to be disjoint -/ @[to_additive] lemma finprod_mem_union'' (hst : disjoint (s ∩ mul_support f) (t ∩ mul_support f)) (hs : (s ∩ mul_support f).finite) (ht : (t ∩ mul_support f).finite) : ∏ᶠ i ∈ s ∪ t, f i = (∏ᶠ i ∈ s, f i) * ∏ᶠ i ∈ t, f i := by rw [← finprod_mem_inter_mul_support f s, ← finprod_mem_inter_mul_support f t, ← finprod_mem_union hst hs ht, ← union_inter_distrib_right, finprod_mem_inter_mul_support] /-- The product of `f i` over `i ∈ {a}` equals `f a`. -/ @[to_additive] lemma finprod_mem_singleton : ∏ᶠ i ∈ ({a} : set α), f i = f a := by rw [← finset.coe_singleton, finprod_mem_coe_finset, finset.prod_singleton] @[simp, to_additive] lemma finprod_cond_eq_left : ∏ᶠ i = a, f i = f a := finprod_mem_singleton @[simp, to_additive] lemma finprod_cond_eq_right : ∏ᶠ i (hi : a = i), f i = f a := by simp [@eq_comm _ a] /-- A more general version of `finprod_mem_insert` that requires `s ∩ mul_support f` instead of `s` to be finite. -/ @[to_additive] lemma finprod_mem_insert' (f : α → M) (h : a ∉ s) (hs : (s ∩ mul_support f).finite) : ∏ᶠ i ∈ insert a s, f i = f a * ∏ᶠ i ∈ s, f i := begin rw [insert_eq, finprod_mem_union' _ _ hs, finprod_mem_singleton], { rwa disjoint_singleton_left }, { exact (finite_singleton a).inter_of_left _ } end /-- Given a finite set `s` and an element `a ∉ s`, the product of `f i` over `i ∈ insert a s` equals `f a` times the product of `f i` over `i ∈ s`. -/ @[to_additive] lemma finprod_mem_insert (f : α → M) (h : a ∉ s) (hs : s.finite) : ∏ᶠ i ∈ insert a s, f i = f a * ∏ᶠ i ∈ s, f i := finprod_mem_insert' f h $ hs.inter_of_left _ /-- If `f a = 1` for all `a ∉ s`, then the product of `f i` over `i ∈ insert a s` equals the product of `f i` over `i ∈ s`. -/ @[to_additive] lemma finprod_mem_insert_of_eq_one_if_not_mem (h : a ∉ s → f a = 1) : ∏ᶠ i ∈ (insert a s), f i = ∏ᶠ i ∈ s, f i := begin refine finprod_mem_inter_mul_support_eq' _ _ _ (λ x hx, ⟨_, or.inr⟩), rintro (rfl|hxs), exacts [not_imp_comm.1 h hx, hxs] end /-- If `f a = 1`, then the product of `f i` over `i ∈ insert a s` equals the product of `f i` over `i ∈ s`. -/ @[to_additive] lemma finprod_mem_insert_one (h : f a = 1) : ∏ᶠ i ∈ (insert a s), f i = ∏ᶠ i ∈ s, f i := finprod_mem_insert_of_eq_one_if_not_mem (λ _, h) /-- If the multiplicative support of `f` is finite, then for every `x` in the domain of `f`, `f x` divides `finprod f`. -/ lemma finprod_mem_dvd {f : α → N} (a : α) (hf : finite (mul_support f)) : f a ∣ finprod f := begin by_cases ha : a ∈ mul_support f, { rw finprod_eq_prod_of_mul_support_to_finset_subset f hf (set.subset.refl _), exact finset.dvd_prod_of_mem f ((finite.mem_to_finset hf).mpr ha) }, { rw nmem_mul_support.mp ha, exact one_dvd (finprod f) } end /-- The product of `f i` over `i ∈ {a, b}`, `a ≠ b`, is equal to `f a * f b`. -/ @[to_additive] lemma finprod_mem_pair (h : a ≠ b) : ∏ᶠ i ∈ ({a, b} : set α), f i = f a * f b := by { rw [finprod_mem_insert, finprod_mem_singleton], exacts [h, finite_singleton b] } /-- The product of `f y` over `y ∈ g '' s` equals the product of `f (g i)` over `s` provided that `g` is injective on `s ∩ mul_support (f ∘ g)`. -/ @[to_additive] lemma finprod_mem_image' {s : set β} {g : β → α} (hg : set.inj_on g (s ∩ mul_support (f ∘ g))) : ∏ᶠ i ∈ (g '' s), f i = ∏ᶠ j ∈ s, f (g j) := begin classical, by_cases hs : finite (s ∩ mul_support (f ∘ g)), { have hg : ∀ (x ∈ hs.to_finset) (y ∈ hs.to_finset), g x = g y → x = y, by simpa only [hs.mem_to_finset], rw [finprod_mem_eq_prod _ hs, ← finset.prod_image hg], refine finprod_mem_eq_prod_of_inter_mul_support_eq f _, rw [finset.coe_image, hs.coe_to_finset, ← image_inter_mul_support_eq, inter_assoc, inter_self] }, { rw [finprod_mem_eq_one_of_infinite hs, finprod_mem_eq_one_of_infinite], rwa [image_inter_mul_support_eq, infinite_image_iff hg] } end /-- The product of `f y` over `y ∈ g '' s` equals the product of `f (g i)` over `s` provided that `g` is injective on `s`. -/ @[to_additive] lemma finprod_mem_image {β} {s : set β} {g : β → α} (hg : set.inj_on g s) : ∏ᶠ i ∈ (g '' s), f i = ∏ᶠ j ∈ s, f (g j) := finprod_mem_image' $ hg.mono $ inter_subset_left _ _ /-- The product of `f y` over `y ∈ set.range g` equals the product of `f (g i)` over all `i` provided that `g` is injective on `mul_support (f ∘ g)`. -/ @[to_additive] lemma finprod_mem_range' {g : β → α} (hg : set.inj_on g (mul_support (f ∘ g))) : ∏ᶠ i ∈ range g, f i = ∏ᶠ j, f (g j) := begin rw [← image_univ, finprod_mem_image', finprod_mem_univ], rwa univ_inter end /-- The product of `f y` over `y ∈ set.range g` equals the product of `f (g i)` over all `i` provided that `g` is injective. -/ @[to_additive] lemma finprod_mem_range {g : β → α} (hg : injective g) : ∏ᶠ i ∈ range g, f i = ∏ᶠ j, f (g j) := finprod_mem_range' (hg.inj_on _) /-- The product of `f i` over `s : set α` is equal to the product of `g j` over `t : set β` if there exists a function `e : α → β` such that `e` is bijective from `s` to `t` and for all `x` in `s` we have `f x = g (e x)`. See also `finset.prod_bij`. -/ @[to_additive] lemma finprod_mem_eq_of_bij_on {s : set α} {t : set β} {f : α → M} {g : β → M} (e : α → β) (he₀ : set.bij_on e s t) (he₁ : ∀ x ∈ s, f x = g (e x)) : ∏ᶠ i ∈ s, f i = ∏ᶠ j ∈ t, g j := begin rw [← set.bij_on.image_eq he₀, finprod_mem_image he₀.2.1], exact finprod_mem_congr rfl he₁ end /-- The product of `f i` is equal to the product of `g j` if there exists a bijective function `e : α → β` such that for all `x` we have `f x = g (e x)`. See `finprod_comp`, `fintype.prod_bijective` and `finset.prod_bij` -/ @[to_additive] lemma finprod_eq_of_bijective {f : α → M} {g : β → M} (e : α → β) (he₀ : function.bijective e) (he₁ : ∀ x, f x = g (e x)) : ∏ᶠ i, f i = ∏ᶠ j, g j := begin rw [← finprod_mem_univ f, ← finprod_mem_univ g], exact finprod_mem_eq_of_bij_on _ (bijective_iff_bij_on_univ.mp he₀) (λ x _, he₁ x), end /-- Given a bijective function `e` the product of `g i` is equal to the product of `g (e i)`. See also `finprod_eq_of_bijective`, `fintype.prod_bijective` and `finset.prod_bij` -/ @[to_additive] lemma finprod_comp {g : β → M} (e : α → β) (he₀ : function.bijective e) : ∏ᶠ i, g (e i) = ∏ᶠ j, g j := finprod_eq_of_bijective e he₀ (λ x, rfl) @[to_additive] lemma finprod_set_coe_eq_finprod_mem (s : set α) : ∏ᶠ j : s, f j = ∏ᶠ i ∈ s, f i := begin rw [← finprod_mem_range, subtype.range_coe], exact subtype.coe_injective end @[to_additive] lemma finprod_subtype_eq_finprod_cond (p : α → Prop) : ∏ᶠ j : subtype p, f j = ∏ᶠ i (hi : p i), f i := finprod_set_coe_eq_finprod_mem {i | p i} @[to_additive] lemma finprod_mem_inter_mul_diff' (t : set α) (h : (s ∩ mul_support f).finite) : (∏ᶠ i ∈ s ∩ t, f i) * ∏ᶠ i ∈ s \ t, f i = ∏ᶠ i ∈ s, f i := begin rw [← finprod_mem_union', inter_union_diff], exacts [λ x hx, hx.2.2 hx.1.2, h.subset (λ x hx, ⟨hx.1.1, hx.2⟩), h.subset (λ x hx, ⟨hx.1.1, hx.2⟩)], end @[to_additive] lemma finprod_mem_inter_mul_diff (t : set α) (h : s.finite) : (∏ᶠ i ∈ s ∩ t, f i) * ∏ᶠ i ∈ s \ t, f i = ∏ᶠ i ∈ s, f i := finprod_mem_inter_mul_diff' _ $ h.inter_of_left _ /-- A more general version of `finprod_mem_mul_diff` that requires `t ∩ mul_support f` instead of `t` to be finite. -/ @[to_additive] lemma finprod_mem_mul_diff' (hst : s ⊆ t) (ht : (t ∩ mul_support f).finite) : (∏ᶠ i ∈ s, f i) * ∏ᶠ i ∈ t \ s, f i = ∏ᶠ i ∈ t, f i := by rw [← finprod_mem_inter_mul_diff' _ ht, inter_eq_self_of_subset_right hst] /-- Given a finite set `t` and a subset `s` of `t`, the product of `f i` over `i ∈ s` times the product of `f i` over `t \ s` equals the product of `f i` over `i ∈ t`. -/ @[to_additive] lemma finprod_mem_mul_diff (hst : s ⊆ t) (ht : t.finite) : (∏ᶠ i ∈ s, f i) * ∏ᶠ i ∈ t \ s, f i = ∏ᶠ i ∈ t, f i := finprod_mem_mul_diff' hst (ht.inter_of_left _) /-- Given a family of pairwise disjoint finite sets `t i` indexed by a finite type, the product of `f a` over the union `⋃ i, t i` is equal to the product over all indexes `i` of the products of `f a` over `a ∈ t i`. -/ @[to_additive] lemma finprod_mem_Union [fintype ι] {t : ι → set α} (h : pairwise (disjoint on t)) (ht : ∀ i, (t i).finite) : ∏ᶠ a ∈ (⋃ i : ι, t i), f a = ∏ᶠ i, (∏ᶠ a ∈ t i, f a) := begin lift t to ι → finset α using ht, classical, rw [← bUnion_univ, ← finset.coe_univ, ← finset.coe_bUnion, finprod_mem_coe_finset, finset.prod_bUnion], { simp only [finprod_mem_coe_finset, finprod_eq_prod_of_fintype] }, { exact λ x _ y _ hxy, finset.disjoint_iff_disjoint_coe.2 (h x y hxy) } end /-- Given a family of sets `t : ι → set α`, a finite set `I` in the index type such that all sets `t i`, `i ∈ I`, are finite, if all `t i`, `i ∈ I`, are pairwise disjoint, then the product of `f a` over `a ∈ ⋃ i ∈ I, t i` is equal to the product over `i ∈ I` of the products of `f a` over `a ∈ t i`. -/ @[to_additive] lemma finprod_mem_bUnion {I : set ι} {t : ι → set α} (h : I.pairwise (disjoint on t)) (hI : I.finite) (ht : ∀ i ∈ I, (t i).finite) : ∏ᶠ a ∈ ⋃ x ∈ I, t x, f a = ∏ᶠ i ∈ I, ∏ᶠ j ∈ t i, f j := begin haveI := hI.fintype, rw [bUnion_eq_Union, finprod_mem_Union, ← finprod_set_coe_eq_finprod_mem], exacts [λ x y hxy, h x x.2 y y.2 (subtype.coe_injective.ne hxy), λ b, ht b b.2] end /-- If `t` is a finite set of pairwise disjoint finite sets, then the product of `f a` over `a ∈ ⋃₀ t` is the product over `s ∈ t` of the products of `f a` over `a ∈ s`. -/ @[to_additive] lemma finprod_mem_sUnion {t : set (set α)} (h : t.pairwise disjoint) (ht₀ : t.finite) (ht₁ : ∀ x ∈ t, set.finite x): ∏ᶠ a ∈ ⋃₀ t, f a = ∏ᶠ s ∈ t, ∏ᶠ a ∈ s, f a := by rw [set.sUnion_eq_bUnion, finprod_mem_bUnion h ht₀ ht₁] /-- If `s : set α` and `t : set β` are finite sets, then the product over `s` commutes with the product over `t`. -/ @[to_additive] lemma finprod_mem_comm {s : set α} {t : set β} (f : α → β → M) (hs : s.finite) (ht : t.finite) : ∏ᶠ i ∈ s, ∏ᶠ j ∈ t, f i j = ∏ᶠ j ∈ t, ∏ᶠ i ∈ s, f i j := begin lift s to finset α using hs, lift t to finset β using ht, simp only [finprod_mem_coe_finset], exact finset.prod_comm end /-- To prove a property of a finite product, it suffices to prove that the property is multiplicative and holds on multipliers. -/ @[to_additive] lemma finprod_mem_induction (p : M → Prop) (hp₀ : p 1) (hp₁ : ∀ x y, p x → p y → p (x * y)) (hp₂ : ∀ x ∈ s, p $ f x) : p (∏ᶠ i ∈ s, f i) := finprod_induction _ hp₀ hp₁ $ λ x, finprod_induction _ hp₀ hp₁ $ hp₂ x lemma finprod_cond_nonneg {R : Type*} [ordered_comm_semiring R] {p : α → Prop} {f : α → R} (hf : ∀ x, p x → 0 ≤ f x) : 0 ≤ ∏ᶠ x (h : p x), f x := finprod_nonneg $ λ x, finprod_nonneg $ hf x @[to_additive] lemma single_le_finprod {M : Type*} [ordered_comm_monoid M] (i : α) {f : α → M} (hf : finite (mul_support f)) (h : ∀ j, 1 ≤ f j) : f i ≤ ∏ᶠ j, f j := by classical; calc f i ≤ ∏ j in insert i hf.to_finset, f j : finset.single_le_prod' (λ j hj, h j) (finset.mem_insert_self _ _) ... = ∏ᶠ j, f j : (finprod_eq_prod_of_mul_support_to_finset_subset _ hf (finset.subset_insert _ _)).symm lemma finprod_eq_zero {M₀ : Type*} [comm_monoid_with_zero M₀] (f : α → M₀) (x : α) (hx : f x = 0) (hf : finite (mul_support f)) : ∏ᶠ x, f x = 0 := begin nontriviality, rw [finprod_eq_prod f hf], refine finset.prod_eq_zero (hf.mem_to_finset.2 _) hx, simp [hx] end @[to_additive] lemma finprod_prod_comm (s : finset β) (f : α → β → M) (h : ∀ b ∈ s, (mul_support (λ a, f a b)).finite) : ∏ᶠ a : α, ∏ b in s, f a b = ∏ b in s, ∏ᶠ a : α, f a b := begin have hU : mul_support (λ a, ∏ b in s, f a b) ⊆ (s.finite_to_set.bUnion (λ b hb, h b (finset.mem_coe.1 hb))).to_finset, { rw finite.coe_to_finset, intros x hx, simp only [exists_prop, mem_Union, ne.def, mem_mul_support, finset.mem_coe], contrapose! hx, rw [mem_mul_support, not_not, finset.prod_congr rfl hx, finset.prod_const_one] }, rw [finprod_eq_prod_of_mul_support_subset _ hU, finset.prod_comm], refine finset.prod_congr rfl (λ b hb, (finprod_eq_prod_of_mul_support_subset _ _).symm), intros a ha, simp only [finite.coe_to_finset, mem_Union], exact ⟨b, hb, ha⟩ end @[to_additive] lemma prod_finprod_comm (s : finset α) (f : α → β → M) (h : ∀ a ∈ s, (mul_support (f a)).finite) : ∏ a in s, ∏ᶠ b : β, f a b = ∏ᶠ b : β, ∏ a in s, f a b := (finprod_prod_comm s (λ b a, f a b) h).symm lemma mul_finsum {R : Type*} [semiring R] (f : α → R) (r : R) (h : (function.support f).finite) : r * ∑ᶠ a : α, f a = ∑ᶠ a : α, r * f a := (add_monoid_hom.mul_left r).map_finsum h lemma finsum_mul {R : Type*} [semiring R] (f : α → R) (r : R) (h : (function.support f).finite) : (∑ᶠ a : α, f a) * r = ∑ᶠ a : α, f a * r := (add_monoid_hom.mul_right r).map_finsum h @[to_additive] lemma finset.mul_support_of_fiberwise_prod_subset_image [decidable_eq β] (s : finset α) (f : α → M) (g : α → β) : mul_support (λ b, (s.filter (λ a, g a = b)).prod f) ⊆ s.image g := begin simp only [finset.coe_image, set.mem_image, finset.mem_coe, function.support_subset_iff], intros b h, suffices : (s.filter (λ (a : α), g a = b)).nonempty, { simpa only [s.fiber_nonempty_iff_mem_image g b, finset.mem_image, exists_prop], }, exact finset.nonempty_of_prod_ne_one h, end /-- Note that `b ∈ (s.filter (λ ab, prod.fst ab = a)).image prod.snd` iff `(a, b) ∈ s` so we can simplify the right hand side of this lemma. However the form stated here is more useful for iterating this lemma, e.g., if we have `f : α × β × γ → M`. -/ @[to_additive] lemma finprod_mem_finset_product' [decidable_eq α] [decidable_eq β] (s : finset (α × β)) (f : α × β → M) : ∏ᶠ ab (h : ab ∈ s), f ab = ∏ᶠ a b (h : b ∈ (s.filter (λ ab, prod.fst ab = a)).image prod.snd), f (a, b) := begin have : ∀ a, ∏ (i : β) in (s.filter (λ ab, prod.fst ab = a)).image prod.snd, f (a, i) = (finset.filter (λ ab, prod.fst ab = a) s).prod f, { intros a, apply finset.prod_bij (λ b _, (a, b)); finish, }, rw finprod_mem_finset_eq_prod, simp_rw [finprod_mem_finset_eq_prod, this], rw [finprod_eq_prod_of_mul_support_subset _ (s.mul_support_of_fiberwise_prod_subset_image f prod.fst), ← finset.prod_fiberwise_of_maps_to _ f], finish, end /-- See also `finprod_mem_finset_product'`. -/ @[to_additive] lemma finprod_mem_finset_product (s : finset (α × β)) (f : α × β → M) : ∏ᶠ ab (h : ab ∈ s), f ab = ∏ᶠ a b (h : (a, b) ∈ s), f (a, b) := by { classical, rw finprod_mem_finset_product', simp, } @[to_additive] lemma finprod_mem_finset_product₃ {γ : Type*} (s : finset (α × β × γ)) (f : α × β × γ → M) : ∏ᶠ abc (h : abc ∈ s), f abc = ∏ᶠ a b c (h : (a, b, c) ∈ s), f (a, b, c) := by { classical, rw finprod_mem_finset_product', simp_rw finprod_mem_finset_product', simp, } @[to_additive] lemma finprod_curry (f : α × β → M) (hf : (mul_support f).finite) : ∏ᶠ ab, f ab = ∏ᶠ a b, f (a, b) := begin have h₁ : ∀ a, ∏ᶠ (h : a ∈ hf.to_finset), f a = f a, { simp, }, have h₂ : ∏ᶠ a, f a = ∏ᶠ a (h : a ∈ hf.to_finset), f a, { simp, }, simp_rw [h₂, finprod_mem_finset_product, h₁], end @[to_additive] lemma finprod_curry₃ {γ : Type*} (f : α × β × γ → M) (h : (mul_support f).finite) : ∏ᶠ abc, f abc = ∏ᶠ a b c, f (a, b, c) := by { rw finprod_curry f h, congr, ext a, rw finprod_curry, simp [h], } @[to_additive] lemma finprod_dmem {s : set α} [decidable_pred (∈ s)] (f : (Π (a : α), a ∈ s → M)) : ∏ᶠ (a : α) (h : a ∈ s), f a h = ∏ᶠ (a : α) (h : a ∈ s), if h' : a ∈ s then f a h' else 1 := finprod_congr (λ a, finprod_congr (λ ha, (dif_pos ha).symm)) @[to_additive] lemma finprod_emb_domain' {f : α → β} (hf : function.injective f) [decidable_pred (∈ set.range f)] (g : α → M) : ∏ᶠ (b : β), (if h : b ∈ set.range f then g (classical.some h) else 1) = ∏ᶠ (a : α), g a := begin simp_rw [← finprod_eq_dif], rw [finprod_dmem, finprod_mem_range hf, finprod_congr (λ a, _)], rw [dif_pos (set.mem_range_self a), hf (classical.some_spec (set.mem_range_self a))] end @[to_additive] lemma finprod_emb_domain (f : α ↪ β) [decidable_pred (∈ set.range f)] (g : α → M) : ∏ᶠ (b : β), (if h : b ∈ set.range f then g (classical.some h) else 1) = ∏ᶠ (a : α), g a := finprod_emb_domain' f.injective g end type
f1609a07aff7236a77fd6da16e34316441b8e89b
4b846d8dabdc64e7ea03552bad8f7fa74763fc67
/tests/lean/run/ematch_partial_apps.lean
20ba2cb7eaf2546eb02b5e202179639c06a27cae
[ "Apache-2.0" ]
permissive
pacchiano/lean
9324b33f3ac3b5c5647285160f9f6ea8d0d767dc
fdadada3a970377a6df8afcd629a6f2eab6e84e8
refs/heads/master
1,611,357,380,399
1,489,870,101,000
1,489,870,101,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,049
lean
open tactic meta def check_expr (p : pexpr) (t : expr) : tactic unit := do e ← to_expr p, guard (expr.alpha_eqv t e) meta def check_target (p : pexpr) : tactic unit := do t ← target, check_expr p t set_option trace.smt.ematch true example (a : list nat) (f : nat → nat) : a = [1, 2] → a^.for f = [f 1, f 2] := begin [smt] intros, ematch_using [list.for], ematch_using [flip], ematch_using [list.map], ematch_using [list.map], ematch_using [list.map] end example (a : list nat) (f : nat → nat) : a = [1, 2] → a^.for f = [f 1, f 2] := begin [smt] intros, repeat {ematch_using [list.for, flip, list.map], try { close }}, end attribute [ematch] list.map flip list.for example (a : list nat) (f : nat → nat) : a = [1, 2] → a^.for f = [f 1, f 2] := begin [smt] intros, eblast end constant f : nat → nat → nat constant g : nat → nat → nat axiom fgx : ∀ x y, (: f x :) = (λ y, y) ∧ (: g y :) = λ x, 0 attribute [ematch] fgx example (a b c : nat) : f a b = b ∧ g b c = 0 := begin [smt] ematch end
65a9015a0cb2359c3178e5ba1d5eefdea54627f5
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/category_theory/functor_category.lean
ca237ee531ee789f2d7b0f43ceb266b8df0ab5ad
[]
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
6,179
lean
/- Copyright (c) 2017 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Tim Baumann, Stephen Morgan, Scott Morrison, Floris van Doorn -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.category_theory.natural_transformation import Mathlib.PostPort universes u₁ u₂ v₁ v₂ v₃ u₃ namespace Mathlib namespace category_theory /-- `functor.category C D` gives the category structure on functors and natural transformations between categories `C` and `D`. Notice that if `C` and `D` are both small categories at the same universe level, this is another small category at that level. However if `C` and `D` are both large categories at the same universe level, this is a small category at the next higher level. -/ protected instance functor.category (C : Type u₁) [category C] (D : Type u₂) [category D] : category (C ⥤ D) := category.mk namespace nat_trans @[simp] theorem vcomp_eq_comp {C : Type u₁} [category C] {D : Type u₂} [category D] {F : C ⥤ D} {G : C ⥤ D} {H : C ⥤ D} (α : F ⟶ G) (β : G ⟶ H) : vcomp α β = α ≫ β := rfl theorem vcomp_app' {C : Type u₁} [category C] {D : Type u₂} [category D] {F : C ⥤ D} {G : C ⥤ D} {H : C ⥤ D} (α : F ⟶ G) (β : G ⟶ H) (X : C) : app (α ≫ β) X = app α X ≫ app β X := rfl theorem congr_app {C : Type u₁} [category C] {D : Type u₂} [category D] {F : C ⥤ D} {G : C ⥤ D} {α : F ⟶ G} {β : F ⟶ G} (h : α = β) (X : C) : app α X = app β X := eq.mpr (id (Eq._oldrec (Eq.refl (app α X = app β X)) h)) (Eq.refl (app β X)) @[simp] theorem id_app {C : Type u₁} [category C] {D : Type u₂} [category D] (F : C ⥤ D) (X : C) : app 𝟙 X = 𝟙 := rfl @[simp] theorem comp_app {C : Type u₁} [category C] {D : Type u₂} [category D] {F : C ⥤ D} {G : C ⥤ D} {H : C ⥤ D} (α : F ⟶ G) (β : G ⟶ H) (X : C) : app (α ≫ β) X = app α X ≫ app β X := rfl theorem app_naturality {C : Type u₁} [category C] {D : Type u₂} [category D] {E : Type u₃} [category E] {F : C ⥤ D ⥤ E} {G : C ⥤ D ⥤ E} (T : F ⟶ G) (X : C) {Y : D} {Z : D} (f : Y ⟶ Z) : functor.map (functor.obj F X) f ≫ app (app T X) Z = app (app T X) Y ≫ functor.map (functor.obj G X) f := naturality (app T X) f theorem naturality_app {C : Type u₁} [category C] {D : Type u₂} [category D] {E : Type u₃} [category E] {F : C ⥤ D ⥤ E} {G : C ⥤ D ⥤ E} (T : F ⟶ G) (Z : D) {X : C} {Y : C} (f : X ⟶ Y) : app (functor.map F f) Z ≫ app (app T Y) Z = app (app T X) Z ≫ app (functor.map G f) Z := congr_fun (congr_arg app (naturality T f)) Z /-- A natural transformation is a monomorphism if each component is. -/ theorem mono_app_of_mono {C : Type u₁} [category C] {D : Type u₂} [category D] {F : C ⥤ D} {G : C ⥤ D} (α : F ⟶ G) [∀ (X : C), mono (app α X)] : mono α := sorry /-- A natural transformation is an epimorphism if each component is. -/ theorem epi_app_of_epi {C : Type u₁} [category C] {D : Type u₂} [category D] {F : C ⥤ D} {G : C ⥤ D} (α : F ⟶ G) [∀ (X : C), epi (app α X)] : epi α := sorry /-- `hcomp α β` is the horizontal composition of natural transformations. -/ def hcomp {C : Type u₁} [category C] {D : Type u₂} [category D] {E : Type u₃} [category E] {F : C ⥤ D} {G : C ⥤ D} {H : D ⥤ E} {I : D ⥤ E} (α : F ⟶ G) (β : H ⟶ I) : F ⋙ H ⟶ G ⋙ I := mk fun (X : C) => app β (functor.obj F X) ≫ functor.map I (app α X) infixl:80 " ◫ " => Mathlib.category_theory.nat_trans.hcomp @[simp] theorem hcomp_app {C : Type u₁} [category C] {D : Type u₂} [category D] {E : Type u₃} [category E] {F : C ⥤ D} {G : C ⥤ D} {H : D ⥤ E} {I : D ⥤ E} (α : F ⟶ G) (β : H ⟶ I) (X : C) : app (α ◫ β) X = app β (functor.obj F X) ≫ functor.map I (app α X) := rfl @[simp] theorem hcomp_id_app {C : Type u₁} [category C] {D : Type u₂} [category D] {E : Type u₃} [category E] {F : C ⥤ D} {G : C ⥤ D} {H : D ⥤ E} (α : F ⟶ G) (X : C) : app (α ◫ 𝟙) X = functor.map H (app α X) := sorry theorem id_hcomp_app {C : Type u₁} [category C] {D : Type u₂} [category D] {E : Type u₃} [category E] {F : C ⥤ D} {G : C ⥤ D} {H : E ⥤ C} (α : F ⟶ G) (X : E) : app (𝟙 ◫ α) X = app α (functor.obj H X) := sorry -- Note that we don't yet prove a `hcomp_assoc` lemma here: even stating it is painful, because we -- need to use associativity of functor composition. (It's true without the explicit associator, -- because functor composition is definitionally associative, but relying on the definitional equality -- causes bad problems with elaboration later.) theorem exchange {C : Type u₁} [category C] {D : Type u₂} [category D] {E : Type u₃} [category E] {F : C ⥤ D} {G : C ⥤ D} {H : C ⥤ D} {I : D ⥤ E} {J : D ⥤ E} {K : D ⥤ E} (α : F ⟶ G) (β : G ⟶ H) (γ : I ⟶ J) (δ : J ⟶ K) : (α ≫ β) ◫ (γ ≫ δ) = α ◫ γ ≫ β ◫ δ := sorry end nat_trans namespace functor /-- Flip the arguments of a bifunctor. See also `currying.lean`. -/ protected def flip {C : Type u₁} [category C] {D : Type u₂} [category D] {E : Type u₃} [category E] (F : C ⥤ D ⥤ E) : D ⥤ C ⥤ E := mk (fun (k : D) => mk (fun (j : C) => obj (obj F j) k) fun (j j' : C) (f : j ⟶ j') => nat_trans.app (map F f) k) fun (c c' : D) (f : c ⟶ c') => nat_trans.mk fun (j : C) => map (obj F j) f @[simp] theorem flip_obj_obj {C : Type u₁} [category C] {D : Type u₂} [category D] {E : Type u₃} [category E] (F : C ⥤ D ⥤ E) (c : C) (d : D) : obj (obj (functor.flip F) d) c = obj (obj F c) d := rfl @[simp] theorem flip_obj_map {C : Type u₁} [category C] {D : Type u₂} [category D] {E : Type u₃} [category E] (F : C ⥤ D ⥤ E) {c : C} {c' : C} (f : c ⟶ c') (d : D) : map (obj (functor.flip F) d) f = nat_trans.app (map F f) d := rfl @[simp] theorem flip_map_app {C : Type u₁} [category C] {D : Type u₂} [category D] {E : Type u₃} [category E] (F : C ⥤ D ⥤ E) {d : D} {d' : D} (f : d ⟶ d') (c : C) : nat_trans.app (map (functor.flip F) f) c = map (obj F c) f := rfl
227c535ef6f7a8fb2fab6397084a457ba6f201be
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/stage0/src/Init/Data/Stack/Basic.lean
69c6b5e9f1eba1864ffee07e094d8774c53edd47
[ "Apache-2.0" ]
permissive
mhuisi/lean4
28d35a4febc2e251c7f05492e13f3b05d6f9b7af
dda44bc47f3e5d024508060dac2bcb59fd12e4c0
refs/heads/master
1,621,225,489,283
1,585,142,689,000
1,585,142,689,000
250,590,438
0
2
Apache-2.0
1,602,443,220,000
1,585,327,814,000
C
UTF-8
Lean
false
false
910
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Daniel Selsam Simple stack API implemented using an array. -/ prelude import Init.Data.Array import Init.Data.Int universes u v w structure Stack (α : Type u) := (vals : Array α := #[]) namespace Stack variable {α : Type u} def empty : Stack α := {} def isEmpty (s : Stack α) : Bool := s.vals.isEmpty def push (v : α) (s : Stack α) : Stack α := { vals := s.vals.push v .. s } def peek? (s : Stack α) : Option α := if s.vals.isEmpty then none else s.vals.get? (s.vals.size-1) def peek! [Inhabited α] (s : Stack α) : α := s.vals.back def pop [Inhabited α] (s : Stack α) : Stack α := { vals := s.vals.pop .. s } def modify [Inhabited α] (s : Stack α) (f : α → α) : Stack α := { vals := s.vals.modify (s.vals.size-1) f .. s } end Stack
d9ae88dd933f694fa48f17354067f6aa797756f6
d642a6b1261b2cbe691e53561ac777b924751b63
/src/set_theory/zfc.lean
e57042dd81d63f3357aab58533b54568549e44e6
[ "Apache-2.0" ]
permissive
cipher1024/mathlib
fee56b9954e969721715e45fea8bcb95f9dc03fe
d077887141000fefa5a264e30fa57520e9f03522
refs/heads/master
1,651,806,490,504
1,573,508,694,000
1,573,508,694,000
107,216,176
0
0
Apache-2.0
1,647,363,136,000
1,508,213,014,000
Lean
UTF-8
Lean
false
false
30,024
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro A model of ZFC in Lean. -/ import data.set.basic universes u v /-- The type of `n`-ary functions `α → α → ... → α`. -/ def arity (α : Type u) : nat → Type u | 0 := α | (n+1) := α → arity n /-- The type of pre-sets in universe `u`. A pre-set is a family of pre-sets indexed by a type in `Type u`. The ZFC universe is defined as a quotient of this to ensure extensionality. -/ inductive pSet : Type (u+1) | mk (α : Type u) (A : α → pSet) : pSet namespace pSet /-- The underlying type of a pre-set -/ def type : pSet → Type u | ⟨α, A⟩ := α /-- The underlying pre-set family of a pre-set -/ def func : Π (x : pSet), x.type → pSet | ⟨α, A⟩ := A theorem mk_type_func : Π (x : pSet), mk x.type x.func = x | ⟨α, A⟩ := rfl /-- Two pre-sets are extensionally equivalent if every element of the first family is extensionally equivalent to some element of the second family and vice-versa. -/ def equiv (x y : pSet) : Prop := pSet.rec (λα z m ⟨β, B⟩, (∀a, ∃b, m a (B b)) ∧ (∀b, ∃a, m a (B b))) x y theorem equiv.refl (x) : equiv x x := pSet.rec_on x $ λα A IH, ⟨λa, ⟨a, IH a⟩, λa, ⟨a, IH a⟩⟩ theorem equiv.euc {x} : Π {y z}, equiv x y → equiv z y → equiv x z := pSet.rec_on x $ λα A IH y, pSet.cases_on y $ λβ B ⟨γ, Γ⟩ ⟨αβ, βα⟩ ⟨γβ, βγ⟩, ⟨λa, let ⟨b, ab⟩ := αβ a, ⟨c, bc⟩ := βγ b in ⟨c, IH a ab bc⟩, λc, let ⟨b, cb⟩ := γβ c, ⟨a, ba⟩ := βα b in ⟨a, IH a ba cb⟩⟩ theorem equiv.symm {x y} : equiv x y → equiv y x := equiv.euc (equiv.refl y) theorem equiv.trans {x y z} (h1 : equiv x y) (h2 : equiv y z) : equiv x z := equiv.euc h1 (equiv.symm h2) instance setoid : setoid pSet := ⟨pSet.equiv, equiv.refl, λx y, equiv.symm, λx y z, equiv.trans⟩ protected def subset : pSet → pSet → Prop | ⟨α, A⟩ ⟨β, B⟩ := ∀a, ∃b, equiv (A a) (B b) instance : has_subset pSet := ⟨pSet.subset⟩ theorem equiv.ext : Π (x y : pSet), equiv x y ↔ (x ⊆ y ∧ y ⊆ x) | ⟨α, A⟩ ⟨β, B⟩ := ⟨λ⟨αβ, βα⟩, ⟨αβ, λb, let ⟨a, h⟩ := βα b in ⟨a, equiv.symm h⟩⟩, λ⟨αβ, βα⟩, ⟨αβ, λb, let ⟨a, h⟩ := βα b in ⟨a, equiv.symm h⟩⟩⟩ theorem subset.congr_left : Π {x y z : pSet}, equiv x y → (x ⊆ z ↔ y ⊆ z) | ⟨α, A⟩ ⟨β, B⟩ ⟨γ, Γ⟩ ⟨αβ, βα⟩ := ⟨λαγ b, let ⟨a, ba⟩ := βα b, ⟨c, ac⟩ := αγ a in ⟨c, equiv.trans (equiv.symm ba) ac⟩, λβγ a, let ⟨b, ab⟩ := αβ a, ⟨c, bc⟩ := βγ b in ⟨c, equiv.trans ab bc⟩⟩ theorem subset.congr_right : Π {x y z : pSet}, equiv x y → (z ⊆ x ↔ z ⊆ y) | ⟨α, A⟩ ⟨β, B⟩ ⟨γ, Γ⟩ ⟨αβ, βα⟩ := ⟨λγα c, let ⟨a, ca⟩ := γα c, ⟨b, ab⟩ := αβ a in ⟨b, equiv.trans ca ab⟩, λγβ c, let ⟨b, cb⟩ := γβ c, ⟨a, ab⟩ := βα b in ⟨a, equiv.trans cb (equiv.symm ab)⟩⟩ /-- `x ∈ y` as pre-sets if `x` is extensionally equivalent to a member of the family `y`. -/ def mem : pSet → pSet → Prop | x ⟨β, B⟩ := ∃b, equiv x (B b) instance : has_mem pSet.{u} pSet.{u} := ⟨mem⟩ theorem mem.mk {α: Type u} (A : α → pSet) (a : α) : A a ∈ mk α A := show mem (A a) ⟨α, A⟩, from ⟨a, equiv.refl (A a)⟩ theorem mem.ext : Π {x y : pSet.{u}}, (∀w:pSet.{u}, w ∈ x ↔ w ∈ y) → equiv x y | ⟨α, A⟩ ⟨β, B⟩ h := ⟨λa, (h (A a)).1 (mem.mk A a), λb, let ⟨a, ha⟩ := (h (B b)).2 (mem.mk B b) in ⟨a, equiv.symm ha⟩⟩ theorem mem.congr_right : Π {x y : pSet.{u}}, equiv x y → (∀{w:pSet.{u}}, w ∈ x ↔ w ∈ y) | ⟨α, A⟩ ⟨β, B⟩ ⟨αβ, βα⟩ w := ⟨λ⟨a, ha⟩, let ⟨b, hb⟩ := αβ a in ⟨b, equiv.trans ha hb⟩, λ⟨b, hb⟩, let ⟨a, ha⟩ := βα b in ⟨a, equiv.euc hb ha⟩⟩ theorem equiv_iff_mem {x y : pSet.{u}} : equiv x y ↔ (∀{w:pSet.{u}}, w ∈ x ↔ w ∈ y) := ⟨mem.congr_right, match x, y with | ⟨α, A⟩, ⟨β, B⟩, h := ⟨λ a, h.1 (mem.mk A a), λ b, let ⟨a, h⟩ := h.2 (mem.mk B b) in ⟨a, h.symm⟩⟩ end⟩ theorem mem.congr_left : Π {x y : pSet.{u}}, equiv x y → (∀{w : pSet.{u}}, x ∈ w ↔ y ∈ w) | x y h ⟨α, A⟩ := ⟨λ⟨a, ha⟩, ⟨a, equiv.trans (equiv.symm h) ha⟩, λ⟨a, ha⟩, ⟨a, equiv.trans h ha⟩⟩ /-- Convert a pre-set to a `set` of pre-sets. -/ def to_set (u : pSet.{u}) : set pSet.{u} := {x | x ∈ u} /-- Two pre-sets are equivalent iff they have the same members. -/ theorem equiv.eq {x y : pSet} : equiv x y ↔ to_set x = to_set y := equiv_iff_mem.trans (set.ext_iff _ _).symm instance : has_coe pSet (set pSet) := ⟨to_set⟩ /-- The empty pre-set -/ protected def empty : pSet := ⟨ulift empty, λe, match e with end⟩ instance : has_emptyc pSet := ⟨pSet.empty⟩ theorem mem_empty (x : pSet.{u}) : x ∉ (∅:pSet.{u}) := λe, match e with end /-- Insert an element into a pre-set -/ protected def insert : pSet → pSet → pSet | u ⟨α, A⟩ := ⟨option α, λo, option.rec u A o⟩ instance : has_insert pSet pSet := ⟨pSet.insert⟩ /-- The n-th von Neumann ordinal -/ def of_nat : ℕ → pSet | 0 := ∅ | (n+1) := pSet.insert (of_nat n) (of_nat n) /-- The von Neumann ordinal ω -/ def omega : pSet := ⟨ulift ℕ, λn, of_nat n.down⟩ /-- The separation operation `{x ∈ a | p x}` -/ protected def sep (p : set pSet) : pSet → pSet | ⟨α, A⟩ := ⟨{a // p (A a)}, λx, A x.1⟩ instance : has_sep pSet pSet := ⟨pSet.sep⟩ /-- The powerset operator -/ def powerset : pSet → pSet | ⟨α, A⟩ := ⟨set α, λp, ⟨{a // p a}, λx, A x.1⟩⟩ theorem mem_powerset : Π {x y : pSet}, y ∈ powerset x ↔ y ⊆ x | ⟨α, A⟩ ⟨β, B⟩ := ⟨λ⟨p, e⟩, (subset.congr_left e).2 $ λ⟨a, pa⟩, ⟨a, equiv.refl (A a)⟩, λβα, ⟨{a | ∃b, equiv (B b) (A a)}, λb, let ⟨a, ba⟩ := βα b in ⟨⟨a, b, ba⟩, ba⟩, λ⟨a, b, ba⟩, ⟨b, ba⟩⟩⟩ /-- The set union operator -/ def Union : pSet → pSet | ⟨α, A⟩ := ⟨Σx, (A x).type, λ⟨x, y⟩, (A x).func y⟩ theorem mem_Union : Π {x y : pSet.{u}}, y ∈ Union x ↔ ∃ z:pSet.{u}, ∃_:z ∈ x, y ∈ z | ⟨α, A⟩ y := ⟨λ⟨⟨a, c⟩, (e : equiv y ((A a).func c))⟩, have func (A a) c ∈ mk (A a).type (A a).func, from mem.mk (A a).func c, ⟨_, mem.mk _ _, (mem.congr_left e).2 (by rwa mk_type_func at this)⟩, λ⟨⟨β, B⟩, ⟨a, (e:equiv (mk β B) (A a))⟩, ⟨b, yb⟩⟩, by rw ←(mk_type_func (A a)) at e; exact let ⟨βt, tβ⟩ := e, ⟨c, bc⟩ := βt b in ⟨⟨a, c⟩, equiv.trans yb bc⟩⟩ /-- The image of a function -/ def image (f : pSet.{u} → pSet.{u}) : pSet.{u} → pSet | ⟨α, A⟩ := ⟨α, λa, f (A a)⟩ theorem mem_image {f : pSet.{u} → pSet.{u}} (H : ∀{x y}, equiv x y → equiv (f x) (f y)) : Π {x y : pSet.{u}}, y ∈ image f x ↔ ∃z ∈ x, equiv y (f z) | ⟨α, A⟩ y := ⟨λ⟨a, ya⟩, ⟨A a, mem.mk A a, ya⟩, λ⟨z, ⟨a, za⟩, yz⟩, ⟨a, equiv.trans yz (H za)⟩⟩ /-- Universe lift operation -/ protected def lift : pSet.{u} → pSet.{max u v} | ⟨α, A⟩ := ⟨ulift α, λ⟨x⟩, lift (A x)⟩ /-- Embedding of one universe in another -/ def embed : pSet.{max (u+1) v} := ⟨ulift.{v u+1} pSet, λ⟨x⟩, pSet.lift.{u (max (u+1) v)} x⟩ theorem lift_mem_embed : Π (x : pSet.{u}), pSet.lift.{u (max (u+1) v)} x ∈ embed.{u v} := λx, ⟨⟨x⟩, equiv.refl _⟩ /-- Function equivalence is defined so that `f ~ g` iff `∀ x y, x ~ y → f x ~ g y`. This extends to equivalence of n-ary functions. -/ def arity.equiv : Π {n}, arity pSet.{u} n → arity pSet.{u} n → Prop | 0 a b := equiv a b | (n+1) a b := ∀ x y, equiv x y → arity.equiv (a x) (b y) /-- `resp n` is the collection of n-ary functions on `pSet` that respect equivalence, i.e. when the inputs are equivalent the output is as well. -/ def resp (n) := { x : arity pSet.{u} n // arity.equiv x x } def resp.f {n} (f : resp (n+1)) (x : pSet) : resp n := ⟨f.1 x, f.2 _ _ $ equiv.refl x⟩ def resp.equiv {n} (a b : resp n) : Prop := arity.equiv a.1 b.1 theorem resp.refl {n} (a : resp n) : resp.equiv a a := a.2 theorem resp.euc : Π {n} {a b c : resp n}, resp.equiv a b → resp.equiv c b → resp.equiv a c | 0 a b c hab hcb := equiv.euc hab hcb | (n+1) a b c hab hcb := by delta resp.equiv; simp [arity.equiv]; exact λx y h, @resp.euc n (a.f x) (b.f y) (c.f y) (hab _ _ h) (hcb _ _ $ equiv.refl y) instance resp.setoid {n} : setoid (resp n) := ⟨resp.equiv, resp.refl, λx y h, resp.euc (resp.refl y) h, λx y z h1 h2, resp.euc h1 $ resp.euc (resp.refl z) h2⟩ end pSet /-- The ZFC universe of sets consists of the type of pre-sets, quotiented by extensional equivalence. -/ def Set : Type (u+1) := quotient pSet.setoid.{u} namespace pSet namespace resp def eval_aux : Π {n}, { f : resp n → arity Set.{u} n // ∀ (a b : resp n), resp.equiv a b → f a = f b } | 0 := ⟨λa, ⟦a.1⟧, λa b h, quotient.sound h⟩ | (n+1) := let F : resp (n + 1) → arity Set (n + 1) := λa, @quotient.lift _ _ pSet.setoid (λx, eval_aux.1 (a.f x)) (λb c h, eval_aux.2 _ _ (a.2 _ _ h)) in ⟨F, λb c h, funext $ @quotient.ind _ _ (λq, F b q = F c q) $ λz, eval_aux.2 (resp.f b z) (resp.f c z) (h _ _ (equiv.refl z))⟩ /-- An equivalence-respecting function yields an n-ary Set function. -/ def eval (n) : resp n → arity Set.{u} n := eval_aux.1 @[simp] theorem eval_val {n f x} : (@eval (n+1) f : Set → arity Set n) ⟦x⟧ = eval n (resp.f f x) := rfl end resp /-- A set function is "definable" if it is the image of some n-ary pre-set function. This isn't exactly definability, but is useful as a sufficient condition for functions that have a computable image. -/ @[class] inductive definable (n) : arity Set.{u} n → Type (u+1) | mk (f) : definable (resp.eval _ f) attribute [instance] definable.mk def definable.eq_mk {n} (f) : Π {s : arity Set.{u} n} (H : resp.eval _ f = s), definable n s | ._ rfl := ⟨f⟩ def definable.resp {n} : Π (s : arity Set.{u} n) [definable n s], resp n | ._ ⟨f⟩ := f theorem definable.eq {n} : Π (s : arity Set.{u} n) [H : definable n s], (@definable.resp n s H).eval _ = s | ._ ⟨f⟩ := rfl end pSet namespace classical open pSet noncomputable def all_definable : Π {n} (F : arity Set.{u} n), definable n F | 0 F := let p := @quotient.exists_rep pSet _ F in definable.eq_mk ⟨some p, equiv.refl _⟩ (some_spec p) | (n+1) (F : arity Set.{u} (n + 1)) := begin have I := λx, (all_definable (F x)), refine definable.eq_mk ⟨λx:pSet, (@definable.resp _ _ (I ⟦x⟧)).1, _⟩ _, { dsimp [arity.equiv], introsI x y h, rw @quotient.sound pSet _ _ _ h, exact (definable.resp (F ⟦y⟧)).2 }, exact funext (λq, quotient.induction_on q $ λx, by simp [resp.f]; exact @definable.eq _ (F ⟦x⟧) (I ⟦x⟧)) end end classical namespace Set open pSet def mk : pSet → Set := quotient.mk @[simp] theorem mk_eq (x : pSet) : @eq Set ⟦x⟧ (mk x) := rfl def mem : Set → Set → Prop := quotient.lift₂ pSet.mem (λx y x' y' hx hy, propext (iff.trans (mem.congr_left hx) (mem.congr_right hy))) instance : has_mem Set Set := ⟨mem⟩ /-- Convert a ZFC set into a `set` of sets -/ def to_set (u : Set.{u}) : set Set.{u} := {x | x ∈ u} protected def subset (x y : Set.{u}) := ∀ ⦃z⦄, z ∈ x → z ∈ y instance has_subset : has_subset Set := ⟨Set.subset⟩ theorem subset_iff : Π (x y : pSet), mk x ⊆ mk y ↔ x ⊆ y | ⟨α, A⟩ ⟨β, B⟩ := ⟨λh a, @h ⟦A a⟧ (mem.mk A a), λh z, quotient.induction_on z (λz ⟨a, za⟩, let ⟨b, ab⟩ := h a in ⟨b, equiv.trans za ab⟩)⟩ theorem ext {x y : Set.{u}} : (∀z:Set.{u}, z ∈ x ↔ z ∈ y) → x = y := quotient.induction_on₂ x y (λu v h, quotient.sound (mem.ext (λw, h ⟦w⟧))) theorem ext_iff {x y : Set.{u}} : (∀z:Set.{u}, z ∈ x ↔ z ∈ y) ↔ x = y := ⟨ext, λh, by simp [h]⟩ /-- The empty set -/ def empty : Set := mk ∅ instance : has_emptyc Set := ⟨empty⟩ instance : inhabited Set := ⟨∅⟩ @[simp] theorem mem_empty (x) : x ∉ (∅:Set.{u}) := quotient.induction_on x pSet.mem_empty theorem eq_empty (x : Set.{u}) : x = ∅ ↔ ∀y:Set.{u}, y ∉ x := ⟨λh, by rw h; exact mem_empty, λh, ext (λy, ⟨λyx, absurd yx (h y), λy0, absurd y0 (mem_empty _)⟩)⟩ /-- `insert x y` is the set `{x} ∪ y` -/ protected def insert : Set → Set → Set := resp.eval 2 ⟨pSet.insert, λu v uv ⟨α, A⟩ ⟨β, B⟩ ⟨αβ, βα⟩, ⟨λo, match o with | some a := let ⟨b, hb⟩ := αβ a in ⟨some b, hb⟩ | none := ⟨none, uv⟩ end, λo, match o with | some b := let ⟨a, ha⟩ := βα b in ⟨some a, ha⟩ | none := ⟨none, uv⟩ end⟩⟩ instance : has_insert Set Set := ⟨Set.insert⟩ @[simp] theorem mem_insert {x y z : Set.{u}} : x ∈ insert y z ↔ x = y ∨ x ∈ z := quotient.induction_on₃ x y z (λx y ⟨α, A⟩, show x ∈ pSet.mk (option α) (λo, option.rec y A o) ↔ mk x = mk y ∨ x ∈ pSet.mk α A, from ⟨λm, match m with | ⟨some a, ha⟩ := or.inr ⟨a, ha⟩ | ⟨none, h⟩ := or.inl (quotient.sound h) end, λm, match m with | or.inr ⟨a, ha⟩ := ⟨some a, ha⟩ | or.inl h := ⟨none, quotient.exact h⟩ end⟩) @[simp] theorem mem_singleton {x y : Set.{u}} : x ∈ @singleton Set.{u} Set.{u} _ _ y ↔ x = y := iff.trans mem_insert ⟨λo, or.rec (λh, h) (λn, absurd n (mem_empty _)) o, or.inl⟩ @[simp] theorem mem_singleton' {x y : Set.{u}} : x ∈ @insert Set.{u} Set.{u} _ y ∅ ↔ x = y := mem_singleton @[simp] theorem mem_pair {x y z : Set.{u}} : x ∈ ({y, z} : Set) ↔ x = y ∨ x = z := iff.trans mem_insert $ iff.trans or.comm $ let m := @mem_singleton x y in ⟨or.imp_left m.1, or.imp_left m.2⟩ /-- `omega` is the first infinite von Neumann ordinal -/ def omega : Set := mk omega @[simp] theorem omega_zero : ∅ ∈ omega := show pSet.mem ∅ pSet.omega, from ⟨⟨0⟩, equiv.refl _⟩ @[simp] theorem omega_succ {n} : n ∈ omega.{u} → insert n n ∈ omega.{u} := quotient.induction_on n (λx ⟨⟨n⟩, h⟩, ⟨⟨n+1⟩, have Set.insert ⟦x⟧ ⟦x⟧ = Set.insert ⟦of_nat n⟧ ⟦of_nat n⟧, by rw (@quotient.sound pSet _ _ _ h), quotient.exact this⟩) /-- `{x ∈ a | p x}` is the set of elements in `a` satisfying `p` -/ protected def sep (p : Set → Prop) : Set → Set := resp.eval 1 ⟨pSet.sep (λy, p ⟦y⟧), λ⟨α, A⟩ ⟨β, B⟩ ⟨αβ, βα⟩, ⟨λ⟨a, pa⟩, let ⟨b, hb⟩ := αβ a in ⟨⟨b, by rwa ←(@quotient.sound pSet _ _ _ hb)⟩, hb⟩, λ⟨b, pb⟩, let ⟨a, ha⟩ := βα b in ⟨⟨a, by rwa (@quotient.sound pSet _ _ _ ha)⟩, ha⟩⟩⟩ instance : has_sep Set Set := ⟨Set.sep⟩ @[simp] theorem mem_sep {p : Set.{u} → Prop} {x y : Set.{u}} : y ∈ {y ∈ x | p y} ↔ y ∈ x ∧ p y := quotient.induction_on₂ x y (λ⟨α, A⟩ y, ⟨λ⟨⟨a, pa⟩, h⟩, ⟨⟨a, h⟩, by rw (@quotient.sound pSet _ _ _ h); exact pa⟩, λ⟨⟨a, h⟩, pa⟩, ⟨⟨a, by rw ←(@quotient.sound pSet _ _ _ h); exact pa⟩, h⟩⟩) /-- The powerset operation, the collection of subsets of a set -/ def powerset : Set → Set := resp.eval 1 ⟨powerset, λ⟨α, A⟩ ⟨β, B⟩ ⟨αβ, βα⟩, ⟨λp, ⟨{b | ∃a, p a ∧ equiv (A a) (B b)}, λ⟨a, pa⟩, let ⟨b, ab⟩ := αβ a in ⟨⟨b, a, pa, ab⟩, ab⟩, λ⟨b, a, pa, ab⟩, ⟨⟨a, pa⟩, ab⟩⟩, λq, ⟨{a | ∃b, q b ∧ equiv (A a) (B b)}, λ⟨a, b, qb, ab⟩, ⟨⟨b, qb⟩, ab⟩, λ⟨b, qb⟩, let ⟨a, ab⟩ := βα b in ⟨⟨a, b, qb, ab⟩, ab⟩⟩⟩⟩ @[simp] theorem mem_powerset {x y : Set} : y ∈ powerset x ↔ y ⊆ x := quotient.induction_on₂ x y (λ⟨α, A⟩ ⟨β, B⟩, show (⟨β, B⟩ : pSet) ∈ (pSet.powerset ⟨α, A⟩) ↔ _, by simp [mem_powerset, subset_iff]) theorem Union_lem {α β : Type u} (A : α → pSet) (B : β → pSet) (αβ : ∀a, ∃b, equiv (A a) (B b)) : ∀a, ∃b, (equiv ((Union ⟨α, A⟩).func a) ((Union ⟨β, B⟩).func b)) | ⟨a, c⟩ := let ⟨b, hb⟩ := αβ a in begin induction ea : A a with γ Γ, induction eb : B b with δ Δ, rw [ea, eb] at hb, cases hb with γδ δγ, exact let c : type (A a) := c, ⟨d, hd⟩ := γδ (by rwa ea at c) in have equiv ((A a).func c) ((B b).func (eq.rec d (eq.symm eb))), from match A a, B b, ea, eb, c, d, hd with ._, ._, rfl, rfl, x, y, hd := hd end, ⟨⟨b, eq.rec d (eq.symm eb)⟩, this⟩ end /-- The union operator, the collection of elements of elements of a set -/ def Union : Set → Set := resp.eval 1 ⟨pSet.Union, λ⟨α, A⟩ ⟨β, B⟩ ⟨αβ, βα⟩, ⟨Union_lem A B αβ, λa, exists.elim (Union_lem B A (λb, exists.elim (βα b) (λc hc, ⟨c, equiv.symm hc⟩)) a) (λb hb, ⟨b, equiv.symm hb⟩)⟩⟩ notation `⋃` := Union @[simp] theorem mem_Union {x y : Set.{u}} : y ∈ Union x ↔ ∃ z ∈ x, y ∈ z := quotient.induction_on₂ x y (λx y, iff.trans mem_Union ⟨λ⟨z, h⟩, ⟨⟦z⟧, h⟩, λ⟨z, h⟩, quotient.induction_on z (λz h, ⟨z, h⟩) h⟩) @[simp] theorem Union_singleton {x : Set.{u}} : Union {x} = x := ext $ λy, by simp; exact ⟨λ⟨z, zx, yz⟩, by subst z; exact yz, λyx, ⟨x, by simp, yx⟩⟩ theorem singleton_inj {x y : Set.{u}} (H : ({x} : Set) = {y}) : x = y := let this := congr_arg Union H in by rwa [Union_singleton, Union_singleton] at this /-- The binary union operation -/ protected def union (x y : Set.{u}) : Set.{u} := ⋃ {x, y} /-- The binary intersection operation -/ protected def inter (x y : Set.{u}) : Set.{u} := {z ∈ x | z ∈ y} /-- The set difference operation -/ protected def diff (x y : Set.{u}) : Set.{u} := {z ∈ x | z ∉ y} instance : has_union Set := ⟨Set.union⟩ instance : has_inter Set := ⟨Set.inter⟩ instance : has_sdiff Set := ⟨Set.diff⟩ @[simp] theorem mem_union {x y z : Set.{u}} : z ∈ x ∪ y ↔ z ∈ x ∨ z ∈ y := iff.trans mem_Union ⟨λ⟨w, wxy, zw⟩, match mem_pair.1 wxy with | or.inl wx := or.inl (by rwa ←wx) | or.inr wy := or.inr (by rwa ←wy) end, λzxy, match zxy with | or.inl zx := ⟨x, mem_pair.2 (or.inl rfl), zx⟩ | or.inr zy := ⟨y, mem_pair.2 (or.inr rfl), zy⟩ end⟩ @[simp] theorem mem_inter {x y z : Set.{u}} : z ∈ x ∩ y ↔ z ∈ x ∧ z ∈ y := @@mem_sep (λz:Set.{u}, z ∈ y) @[simp] theorem mem_diff {x y z : Set.{u}} : z ∈ x \ y ↔ z ∈ x ∧ z ∉ y := @@mem_sep (λz:Set.{u}, z ∉ y) theorem induction_on {p : Set → Prop} (x) (h : ∀x, (∀y ∈ x, p y) → p x) : p x := quotient.induction_on x $ λu, pSet.rec_on u $ λα A IH, h _ $ λy, show @has_mem.mem _ _ Set.has_mem y ⟦⟨α, A⟩⟧ → p y, from quotient.induction_on y (λv ⟨a, ha⟩, by rw (@quotient.sound pSet _ _ _ ha); exact IH a) theorem regularity (x : Set.{u}) (h : x ≠ ∅) : ∃ y ∈ x, x ∩ y = ∅ := classical.by_contradiction $ λne, h $ (eq_empty x).2 $ λy, induction_on y $ λz (IH : ∀w:Set.{u}, w ∈ z → w ∉ x), show z ∉ x, from λzx, ne ⟨z, zx, (eq_empty _).2 (λw wxz, let ⟨wx, wz⟩ := mem_inter.1 wxz in IH w wz wx)⟩ /-- The image of a (definable) set function -/ def image (f : Set → Set) [H : definable 1 f] : Set → Set := let r := @definable.resp 1 f _ in resp.eval 1 ⟨image r.1, λx y e, mem.ext $ λz, iff.trans (mem_image r.2) $ iff.trans (by exact ⟨λ⟨w, h1, h2⟩, ⟨w, (mem.congr_right e).1 h1, h2⟩, λ⟨w, h1, h2⟩, ⟨w, (mem.congr_right e).2 h1, h2⟩⟩) $ iff.symm (mem_image r.2)⟩ theorem image.mk : Π (f : Set.{u} → Set.{u}) [H : definable 1 f] (x) {y} (h : y ∈ x), f y ∈ @image f H x | ._ ⟨F⟩ x y := quotient.induction_on₂ x y $ λ⟨α, A⟩ y ⟨a, ya⟩, ⟨a, F.2 _ _ ya⟩ @[simp] theorem mem_image : Π {f : Set.{u} → Set.{u}} [H : definable 1 f] {x y : Set.{u}}, y ∈ @image f H x ↔ ∃z ∈ x, f z = y | ._ ⟨F⟩ x y := quotient.induction_on₂ x y $ λ⟨α, A⟩ y, ⟨λ⟨a, ya⟩, ⟨⟦A a⟧, mem.mk A a, eq.symm $ quotient.sound ya⟩, λ⟨z, hz, e⟩, e ▸ image.mk _ _ hz⟩ /-- Kuratowski ordered pair -/ def pair (x y : Set.{u}) : Set.{u} := {{x}, {x, y}} /-- A subset of pairs `{(a, b) ∈ x × y | p a b}` -/ def pair_sep (p : Set.{u} → Set.{u} → Prop) (x y : Set.{u}) : Set.{u} := {z ∈ powerset (powerset (x ∪ y)) | ∃a ∈ x, ∃b ∈ y, z = pair a b ∧ p a b} @[simp] theorem mem_pair_sep {p} {x y z : Set.{u}} : z ∈ pair_sep p x y ↔ ∃a ∈ x, ∃b ∈ y, z = pair a b ∧ p a b := by refine iff.trans mem_sep ⟨and.right, λe, ⟨_, e⟩⟩; exact let ⟨a, ax, b, bY, ze, pab⟩ := e in by rw ze; exact mem_powerset.2 (λu uz, mem_powerset.2 $ (mem_pair.1 uz).elim (λua, by rw ua; exact λv vu, by rw mem_singleton.1 vu; exact mem_union.2 (or.inl ax)) (λuab, by rw uab; exact λv vu, (mem_pair.1 vu).elim (λva, by rw va; exact mem_union.2 (or.inl ax)) (λvb, by rw vb; exact mem_union.2 (or.inr bY)))) theorem pair_inj {x y x' y' : Set.{u}} (H : pair x y = pair x' y') : x = x' ∧ y = y' := begin have ae := ext_iff.2 H, simp [pair] at ae, have : x = x', { cases (ae {x}).1 (by simp) with h h, { exact singleton_inj h }, { have m : x' ∈ ({x} : Set), { rw h, simp }, simp at m, simp [*] } }, subst x', have he : y = x → y = y', { intro yx, subst y, cases (ae {x, y'}).2 (by simp) with xy'x xy'xx, { have y'x : y' ∈ ({x} : Set) := by rw ← xy'x; simp, simp at y'x, simp [*] }, { have yxx := (ext_iff.2 xy'xx y').1 (by simp), simp at yxx, subst y' } }, have xyxy' := (ae {x, y}).1 (by simp), cases xyxy' with xyx xyy', { have yx := (ext_iff.2 xyx y).1 (by simp), simp at yx, simp [he yx] }, { have yxy' := (ext_iff.2 xyy' y).1 (by simp), simp at yxy', cases yxy' with yx yy', { simp [he yx] }, { simp [yy'] } } end /-- The cartesian product, `{(a, b) | a ∈ x, b ∈ y}` -/ def prod : Set.{u} → Set.{u} → Set.{u} := pair_sep (λa b, true) @[simp] theorem mem_prod {x y z : Set.{u}} : z ∈ prod x y ↔ ∃a ∈ x, ∃b ∈ y, z = pair a b := by simp [prod] @[simp] theorem pair_mem_prod {x y a b : Set.{u}} : pair a b ∈ prod x y ↔ a ∈ x ∧ b ∈ y := ⟨λh, let ⟨a', a'x, b', b'y, e⟩ := mem_prod.1 h in match a', b', pair_inj e, a'x, b'y with ._, ._, ⟨rfl, rfl⟩, ax, bY := ⟨ax, bY⟩ end, λ⟨ax, bY⟩, by simp; exact ⟨a, ax, b, bY, rfl⟩⟩ /-- `is_func x y f` is the assertion `f : x → y` where `f` is a ZFC function (a set of ordered pairs) -/ def is_func (x y f : Set.{u}) : Prop := f ⊆ prod x y ∧ ∀z:Set.{u}, z ∈ x → ∃! w, pair z w ∈ f /-- `funs x y` is `y ^ x`, the set of all set functions `x → y` -/ def funs (x y : Set.{u}) : Set.{u} := {f ∈ powerset (prod x y) | is_func x y f} @[simp] theorem mem_funs {x y f : Set.{u}} : f ∈ funs x y ↔ is_func x y f := by simp [funs]; exact and_iff_right_of_imp and.left -- TODO(Mario): Prove this computably noncomputable instance map_definable_aux (f : Set → Set) [H : definable 1 f] : definable 1 (λy, pair y (f y)) := @classical.all_definable 1 _ /-- Graph of a function: `map f x` is the ZFC function which maps `a ∈ x` to `f a` -/ noncomputable def map (f : Set → Set) [H : definable 1 f] : Set → Set := image (λy, pair y (f y)) @[simp] theorem mem_map {f : Set → Set} [H : definable 1 f] {x y : Set} : y ∈ map f x ↔ ∃z ∈ x, pair z (f z) = y := mem_image theorem map_unique {f : Set.{u} → Set.{u}} [H : definable 1 f] {x z : Set.{u}} (zx : z ∈ x) : ∃! w, pair z w ∈ map f x := ⟨f z, image.mk _ _ zx, λy yx, let ⟨w, wx, we⟩ := mem_image.1 yx, ⟨wz, fy⟩ := pair_inj we in by rw[←fy, wz]⟩ @[simp] theorem map_is_func {f : Set → Set} [H : definable 1 f] {x y : Set} : is_func x y (map f x) ↔ ∀z ∈ x, f z ∈ y := ⟨λ⟨ss, h⟩ z zx, let ⟨t, t1, t2⟩ := h z zx in by rw (t2 (f z) (image.mk _ _ zx)); exact (pair_mem_prod.1 (ss t1)).right, λh, ⟨λy yx, let ⟨z, zx, ze⟩ := mem_image.1 yx in by rw ←ze; exact pair_mem_prod.2 ⟨zx, h z zx⟩, λz, map_unique⟩⟩ end Set def Class := set Set namespace Class instance : has_subset Class := ⟨set.subset⟩ instance : has_sep Set Class := ⟨set.sep⟩ instance : has_emptyc Class := ⟨λ a, false⟩ instance : has_insert Set Class := ⟨set.insert⟩ instance : has_union Class := ⟨set.union⟩ instance : has_inter Class := ⟨set.inter⟩ instance : has_neg Class := ⟨set.compl⟩ instance : has_sdiff Class := ⟨set.diff⟩ /-- Coerce a set into a class -/ def of_Set (x : Set.{u}) : Class.{u} := {y | y ∈ x} instance : has_coe Set Class := ⟨of_Set⟩ /-- The universal class -/ def univ : Class := set.univ /-- Assert that `A` is a set satisfying `p` -/ def to_Set (p : Set.{u} → Prop) (A : Class.{u}) : Prop := ∃x, ↑x = A ∧ p x /-- `A ∈ B` if `A` is a set which is a member of `B` -/ protected def mem (A B : Class.{u}) : Prop := to_Set.{u} B A instance : has_mem Class Class := ⟨Class.mem⟩ theorem mem_univ {A : Class.{u}} : A ∈ univ.{u} ↔ ∃ x : Set.{u}, ↑x = A := exists_congr $ λx, and_true _ /-- Convert a conglomerate (a collection of classes) into a class -/ def Cong_to_Class (x : set Class.{u}) : Class.{u} := {y | ↑y ∈ x} /-- Convert a class into a conglomerate (a collection of classes) -/ def Class_to_Cong (x : Class.{u}) : set Class.{u} := {y | y ∈ x} /-- The power class of a class is the class of all subclasses that are sets -/ def powerset (x : Class) : Class := Cong_to_Class (set.powerset x) /-- The union of a class is the class of all members of sets in the class -/ def Union (x : Class) : Class := set.sUnion (Class_to_Cong x) notation `⋃` := Union theorem of_Set.inj {x y : Set.{u}} (h : (x : Class.{u}) = y) : x = y := Set.ext $ λz, by change (x : Class.{u}) z ↔ (y : Class.{u}) z; simp [*] @[simp] theorem to_Set_of_Set (p : Set.{u} → Prop) (x : Set.{u}) : to_Set p x ↔ p x := ⟨λ⟨y, yx, py⟩, by rwa of_Set.inj yx at py, λpx, ⟨x, rfl, px⟩⟩ @[simp] theorem mem_hom_left (x : Set.{u}) (A : Class.{u}) : (x : Class.{u}) ∈ A ↔ A x := to_Set_of_Set _ _ @[simp] theorem mem_hom_right (x y : Set.{u}) : (y : Class.{u}) x ↔ x ∈ y := iff.refl _ @[simp] theorem subset_hom (x y : Set.{u}) : (x : Class.{u}) ⊆ y ↔ x ⊆ y := iff.refl _ @[simp] theorem sep_hom (p : Set.{u} → Prop) (x : Set.{u}) : (↑{y ∈ x | p y} : Class.{u}) = {y ∈ x | p y} := set.ext $ λy, Set.mem_sep @[simp] theorem empty_hom : ↑(∅ : Set.{u}) = (∅ : Class.{u}) := set.ext $ λy, show _ ↔ false, by simp; exact Set.mem_empty y @[simp] theorem insert_hom (x y : Set.{u}) : (@insert Set.{u} Class.{u} _ x y) = ↑(insert x y) := set.ext $ λz, iff.symm Set.mem_insert @[simp] theorem union_hom (x y : Set.{u}) : (x : Class.{u}) ∪ y = (x ∪ y : Set.{u}) := set.ext $ λz, iff.symm Set.mem_union @[simp] theorem inter_hom (x y : Set.{u}) : (x : Class.{u}) ∩ y = (x ∩ y : Set.{u}) := set.ext $ λz, iff.symm Set.mem_inter @[simp] theorem diff_hom (x y : Set.{u}) : (x : Class.{u}) \ y = (x \ y : Set.{u}) := set.ext $ λz, iff.symm Set.mem_diff @[simp] theorem powerset_hom (x : Set.{u}) : powerset.{u} x = Set.powerset x := set.ext $ λz, iff.symm Set.mem_powerset @[simp] theorem Union_hom (x : Set.{u}) : Union.{u} x = Set.Union x := set.ext $ λz, by refine iff.trans _ (iff.symm Set.mem_Union); exact ⟨λ⟨._, ⟨a, rfl, ax⟩, za⟩, ⟨a, ax, za⟩, λ⟨a, ax, za⟩, ⟨_, ⟨a, rfl, ax⟩, za⟩⟩ /-- The definite description operator, which is {x} if `{a | p a} = {x}` and ∅ otherwise -/ def iota (p : Set → Prop) : Class := Union {x | ∀y, p y ↔ y = x} theorem iota_val (p : Set → Prop) (x : Set) (H : ∀y, p y ↔ y = x) : iota p = ↑x := set.ext $ λy, ⟨λ⟨._, ⟨x', rfl, h⟩, yx'⟩, by rwa ←((H x').1 $ (h x').2 rfl), λyx, ⟨_, ⟨x, rfl, H⟩, yx⟩⟩ /-- Unlike the other set constructors, the `iota` definite descriptor is a set for any set input, but not constructively so, so there is no associated `(Set → Prop) → Set` function. -/ theorem iota_ex (p) : iota.{u} p ∈ univ.{u} := mem_univ.2 $ or.elim (classical.em $ ∃x, ∀y, p y ↔ y = x) (λ⟨x, h⟩, ⟨x, eq.symm $ iota_val p x h⟩) (λhn, ⟨∅, by simp; exact set.ext (λz, ⟨false.rec _, λ⟨._, ⟨x, rfl, H⟩, zA⟩, hn ⟨x, H⟩⟩)⟩) /-- Function value -/ def fval (F A : Class.{u}) : Class.{u} := iota (λy, to_Set (λx, F (Set.pair x y)) A) infixl `′`:100 := fval theorem fval_ex (F A : Class.{u}) : F ′ A ∈ univ.{u} := iota_ex _ end Class namespace Set @[simp] theorem map_fval {f : Set.{u} → Set.{u}} [H : pSet.definable 1 f] {x y : Set.{u}} (h : y ∈ x) : (Set.map f x ′ y : Class.{u}) = f y := Class.iota_val _ _ (λz, by simp; exact ⟨λ⟨w, wz, pr⟩, let ⟨wy, fw⟩ := Set.pair_inj pr in by rw[←fw, wy], λe, by cases e; exact ⟨_, h, rfl⟩⟩) variables (x : Set.{u}) (h : ∅ ∉ x) /-- A choice function on the set of nonempty sets `x` -/ noncomputable def choice : Set := @map (λy, classical.epsilon (λz, z ∈ y)) (classical.all_definable _) x include h theorem choice_mem_aux (y : Set.{u}) (yx : y ∈ x) : classical.epsilon (λz:Set.{u}, z ∈ y) ∈ y := @classical.epsilon_spec _ (λz:Set.{u}, z ∈ y) $ classical.by_contradiction $ λn, h $ by rwa ←((eq_empty y).2 $ λz zx, n ⟨z, zx⟩) theorem choice_is_func : is_func x (Union x) (choice x) := (@map_is_func _ (classical.all_definable _) _ _).2 $ λy yx, by simp; exact ⟨y, yx, choice_mem_aux x h y yx⟩ theorem choice_mem (y : Set.{u}) (yx : y ∈ x) : (choice x ′ y : Class.{u}) ∈ (y : Class.{u}) := by delta choice; rw map_fval yx; simp [choice_mem_aux x h y yx] end Set
7a8b987528410a21cba04616d501eacf8bf86cce
fe25de614feb5587799621c41487aaee0d083b08
/stage0/src/Lean/Data/Options.lean
b1954d9f016ade2f387f0dc2f74522a856485148
[ "Apache-2.0" ]
permissive
pollend/lean4
e8469c2f5fb8779b773618c3267883cf21fb9fac
c913886938c4b3b83238a3f99673c6c5a9cec270
refs/heads/master
1,687,973,251,481
1,628,039,739,000
1,628,039,739,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,161
lean
/- Copyright (c) 2018 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich and Leonardo de Moura -/ import Lean.ImportingFlag import Lean.Data.KVMap namespace Lean def Options := KVMap def Options.empty : Options := {} instance : Inhabited Options where default := {} instance : ToString Options := inferInstanceAs (ToString KVMap) instance : ForIn m Options (Name × DataValue) := inferInstanceAs (ForIn _ KVMap _) structure OptionDecl where defValue : DataValue group : String := "" descr : String := "" deriving Inhabited def OptionDecls := NameMap OptionDecl instance : Inhabited OptionDecls := ⟨({} : NameMap OptionDecl)⟩ private def initOptionDeclsRef : IO (IO.Ref OptionDecls) := IO.mkRef (mkNameMap OptionDecl) @[builtinInit initOptionDeclsRef] private constant optionDeclsRef : IO.Ref OptionDecls @[export lean_register_option] def registerOption (name : Name) (decl : OptionDecl) : IO Unit := do unless (← initializing) do throw (IO.userError "failed to register option, options can only be registered during initialization") let decls ← optionDeclsRef.get if decls.contains name then throw $ IO.userError s!"invalid option declaration '{name}', option already exists" optionDeclsRef.set $ decls.insert name decl def getOptionDecls : IO OptionDecls := optionDeclsRef.get @[export lean_get_option_decls_array] def getOptionDeclsArray : IO (Array (Name × OptionDecl)) := do let decls ← getOptionDecls pure $ decls.fold (fun (r : Array (Name × OptionDecl)) k v => r.push (k, v)) #[] def getOptionDecl (name : Name) : IO OptionDecl := do let decls ← getOptionDecls let (some decl) ← pure (decls.find? name) | throw $ IO.userError s!"unknown option '{name}'" pure decl def getOptionDefaulValue (name : Name) : IO DataValue := do let decl ← getOptionDecl name pure decl.defValue def getOptionDescr (name : Name) : IO String := do let decl ← getOptionDecl name pure decl.descr def setOptionFromString (opts : Options) (entry : String) : IO Options := do let ps := (entry.splitOn "=").map String.trim let [key, val] ← pure ps | throw $ IO.userError "invalid configuration option entry, it must be of the form '<key> = <value>'" let key := Name.mkSimple key let defValue ← getOptionDefaulValue key match defValue with | DataValue.ofString v => pure $ opts.setString key val | DataValue.ofBool v => if key == `true then pure $ opts.setBool key true else if key == `false then pure $ opts.setBool key false else throw $ IO.userError s!"invalid Bool option value '{val}'" | DataValue.ofName v => pure $ opts.setName key val.toName | DataValue.ofNat v => match val.toNat? with | none => throw (IO.userError s!"invalid Nat option value '{val}'") | some v => pure $ opts.setNat key v | DataValue.ofInt v => match val.toInt? with | none => throw (IO.userError s!"invalid Int option value '{val}'") | some v => pure $ opts.setInt key v class MonadOptions (m : Type → Type) where getOptions : m Options export MonadOptions (getOptions) instance (m n) [MonadLift m n] [MonadOptions m] : MonadOptions n where getOptions := liftM (getOptions : m _) variable {m} [Monad m] [MonadOptions m] def getBoolOption (k : Name) (defValue := false) : m Bool := do let opts ← getOptions pure $ opts.getBool k defValue def getNatOption (k : Name) (defValue := 0) : m Nat := do let opts ← getOptions pure $ opts.getNat k defValue /-- A strongly-typed reference to an option. -/ protected structure Option (α : Type) where name : Name defValue : α deriving Inhabited namespace Option protected structure Decl (α : Type) where defValue : α group : String := "" descr : String := "" protected def get? [KVMap.Value α] (opts : Options) (opt : Lean.Option α) : Option α := opts.get? opt.name protected def get [KVMap.Value α] (opts : Options) (opt : Lean.Option α) : α := opts.get opt.name opt.defValue protected def set [KVMap.Value α] (opts : Options) (opt : Lean.Option α) (val : α) : Options := opts.set opt.name val /-- Similar to `set`, but update `opts` only if it doesn't already contains an setting for `opt.name` -/ protected def setIfNotSet [KVMap.Value α] (opts : Options) (opt : Lean.Option α) (val : α) : Options := if opts.contains opt.name then opts else opt.set opts val protected def register [KVMap.Value α] (name : Name) (decl : Lean.Option.Decl α) : IO (Lean.Option α) := do registerOption name { defValue := KVMap.Value.toDataValue decl.defValue, group := decl.group, descr := decl.descr } return { name := name, defValue := decl.defValue } macro "register_builtin_option" name:ident " : " type:term " := " decl:term : command => `(builtin_initialize $name : Lean.Option $type ← Lean.Option.register $(quote name.getId) $decl) macro "register_option" name:ident " : " type:term " := " decl:term : command => `(initialize $name : Lean.Option $type ← Lean.Option.register $(quote name.getId) $decl) end Option end Lean
a3dee3e3ddaf2813867b2607824fe5974483dc8b
271e26e338b0c14544a889c31c30b39c989f2e0f
/src/Init/Lean/Compiler/IR/CompilerM.lean
038665f49f05018fd5a223a54ebf43996cd040b4
[ "Apache-2.0" ]
permissive
dgorokho/lean4
805f99b0b60c545b64ac34ab8237a8504f89d7d4
e949a052bad59b1c7b54a82d24d516a656487d8a
refs/heads/master
1,607,061,363,851
1,578,006,086,000
1,578,006,086,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,908
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Control.Reader import Init.Lean.Environment import Init.Lean.Compiler.IR.Basic import Init.Lean.Compiler.IR.Format namespace Lean namespace IR inductive LogEntry | step (cls : Name) (decls : Array Decl) | message (msg : Format) namespace LogEntry protected def fmt : LogEntry → Format | step cls decls => Format.bracket "[" (format cls) "]" ++ decls.foldl (fun fmt decl => fmt ++ Format.line ++ format decl) Format.nil | message msg => msg instance : HasFormat LogEntry := ⟨LogEntry.fmt⟩ end LogEntry abbrev Log := Array LogEntry def Log.format (log : Log) : Format := log.foldl (fun fmt entry => fmt ++ Format.line ++ format entry) Format.nil @[export lean_ir_log_to_string] def Log.toString (log : Log) : String := log.format.pretty structure CompilerState := (env : Environment) (log : Log := #[]) abbrev CompilerM := ReaderT Options (EStateM String CompilerState) def log (entry : LogEntry) : CompilerM Unit := modify $ fun s => { log := s.log.push entry, .. s } def tracePrefixOptionName := `trace.compiler.ir private def isLogEnabledFor (opts : Options) (optName : Name) : Bool := match opts.find optName with | some (DataValue.ofBool v) => v | other => opts.getBool tracePrefixOptionName private def logDeclsAux (optName : Name) (cls : Name) (decls : Array Decl) : CompilerM Unit := do opts ← read; when (isLogEnabledFor opts optName) $ log (LogEntry.step cls decls) @[inline] def logDecls (cls : Name) (decl : Array Decl) : CompilerM Unit := logDeclsAux (tracePrefixOptionName ++ cls) cls decl private def logMessageIfAux {α : Type} [HasFormat α] (optName : Name) (a : α) : CompilerM Unit := do opts ← read; when (isLogEnabledFor opts optName) $ log (LogEntry.message (format a)) @[inline] def logMessageIf {α : Type} [HasFormat α] (cls : Name) (a : α) : CompilerM Unit := logMessageIfAux (tracePrefixOptionName ++ cls) a @[inline] def logMessage {α : Type} [HasFormat α] (cls : Name) (a : α) : CompilerM Unit := logMessageIfAux tracePrefixOptionName a @[inline] def modifyEnv (f : Environment → Environment) : CompilerM Unit := modify $ fun s => { env := f s.env, .. s } abbrev DeclMap := SMap Name Decl /- Create an array of decls to be saved on .olean file. `decls` may contain duplicate entries, but we assume the one that occurs last is the most recent one. -/ private def mkEntryArray (decls : List Decl) : Array Decl := /- Remove duplicates by adding decls into a map -/ let map : HashMap Name Decl := {}; let map := decls.foldl (fun (map : HashMap Name Decl) decl => map.insert decl.name decl) map; map.fold (fun a k v => a.push v) #[] def mkDeclMapExtension : IO (SimplePersistentEnvExtension Decl DeclMap) := registerSimplePersistentEnvExtension { name := `IRDecls, addImportedFn := fun as => let m : DeclMap := mkStateFromImportedEntries (fun s (d : Decl) => s.insert d.name d) {} as; m.switch, addEntryFn := fun s d => s.insert d.name d, toArrayFn := mkEntryArray } @[init mkDeclMapExtension] constant declMapExt : SimplePersistentEnvExtension Decl DeclMap := arbitrary _ @[export lean_ir_find_env_decl] def findEnvDecl (env : Environment) (n : Name) : Option Decl := (declMapExt.getState env).find? n def findDecl (n : Name) : CompilerM (Option Decl) := do s ← get; pure $ findEnvDecl s.env n def containsDecl (n : Name) : CompilerM Bool := do s ← get; pure $ (declMapExt.getState s.env).contains n def getDecl (n : Name) : CompilerM Decl := do (some decl) ← findDecl n | throw ("unknown declaration '" ++ toString n ++ "'"); pure decl @[export lean_ir_add_decl] def addDeclAux (env : Environment) (decl : Decl) : Environment := declMapExt.addEntry env decl def getDecls (env : Environment) : List Decl := declMapExt.getEntries env def getEnv : CompilerM Environment := do s ← get; pure s.env def addDecl (decl : Decl) : CompilerM Unit := modifyEnv (fun env => declMapExt.addEntry env decl) def addDecls (decls : Array Decl) : CompilerM Unit := decls.forM addDecl def findEnvDecl' (env : Environment) (n : Name) (decls : Array Decl) : Option Decl := match decls.find? (fun decl => if decl.name == n then some decl else none) with | some decl => some decl | none => (declMapExt.getState env).find? n def findDecl' (n : Name) (decls : Array Decl) : CompilerM (Option Decl) := do s ← get; pure $ findEnvDecl' s.env n decls def containsDecl' (n : Name) (decls : Array Decl) : CompilerM Bool := if decls.any (fun decl => decl.name == n) then pure true else do s ← get; pure $ (declMapExt.getState s.env).contains n def getDecl' (n : Name) (decls : Array Decl) : CompilerM Decl := do (some decl) ← findDecl' n decls | throw ("unknown declaration '" ++ toString n ++ "'"); pure decl end IR end Lean
6016fcd8cd9a13667b3f9ee62180056e535668c6
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebraic_geometry/pullbacks.lean
5173a80bbca4d892bfe57b2304ccd27ff38cabe1
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
29,373
lean
/- Copyright (c) 2022 Andrew Yang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Andrew Yang -/ import algebraic_geometry.gluing import category_theory.limits.opposites import algebraic_geometry.AffineScheme import category_theory.limits.shapes.diagonal /-! # Fibred products of schemes > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file we construct the fibred product of schemes via gluing. We roughly follow [har77] Theorem 3.3. In particular, the main construction is to show that for an open cover `{ Uᵢ }` of `X`, if there exist fibred products `Uᵢ ×[Z] Y` for each `i`, then there exists a fibred product `X ×[Z] Y`. Then, for constructing the fibred product for arbitrary schemes `X, Y, Z`, we can use the construction to reduce to the case where `X, Y, Z` are all affine, where fibred products are constructed via tensor products. -/ universes v u noncomputable theory open category_theory category_theory.limits algebraic_geometry namespace algebraic_geometry.Scheme namespace pullback variables {C : Type u} [category.{v} C] variables {X Y Z : Scheme.{u}} (𝒰 : open_cover.{u} X) (f : X ⟶ Z) (g : Y ⟶ Z) variables [∀ i, has_pullback (𝒰.map i ≫ f) g] /-- The intersection of `Uᵢ ×[Z] Y` and `Uⱼ ×[Z] Y` is given by (Uᵢ ×[Z] Y) ×[X] Uⱼ -/ def V (i j : 𝒰.J) : Scheme := pullback ((pullback.fst : pullback ((𝒰.map i) ≫ f) g ⟶ _) ≫ (𝒰.map i)) (𝒰.map j) /-- The canonical transition map `(Uᵢ ×[Z] Y) ×[X] Uⱼ ⟶ (Uⱼ ×[Z] Y) ×[X] Uᵢ` given by the fact that pullbacks are associative and symmetric. -/ def t (i j : 𝒰.J) : V 𝒰 f g i j ⟶ V 𝒰 f g j i := begin haveI : has_pullback (pullback.snd ≫ 𝒰.map i ≫ f) g := has_pullback_assoc_symm (𝒰.map j) (𝒰.map i) (𝒰.map i ≫ f) g, haveI : has_pullback (pullback.snd ≫ 𝒰.map j ≫ f) g := has_pullback_assoc_symm (𝒰.map i) (𝒰.map j) (𝒰.map j ≫ f) g, refine (pullback_symmetry _ _).hom ≫ _, refine (pullback_assoc _ _ _ _).inv ≫ _, change pullback _ _ ⟶ pullback _ _, refine _ ≫ (pullback_symmetry _ _).hom, refine _ ≫ (pullback_assoc _ _ _ _).hom, refine pullback.map _ _ _ _ (pullback_symmetry _ _).hom (𝟙 _) (𝟙 _) _ _, rw [pullback_symmetry_hom_comp_snd_assoc, pullback.condition_assoc, category.comp_id], rw [category.comp_id, category.id_comp] end @[simp, reassoc] lemma t_fst_fst (i j : 𝒰.J) : t 𝒰 f g i j ≫ pullback.fst ≫ pullback.fst = pullback.snd := begin delta t, simp only [category.assoc, id.def, pullback_symmetry_hom_comp_fst_assoc, pullback_assoc_hom_snd_fst, pullback.lift_fst_assoc, pullback_symmetry_hom_comp_snd, pullback_assoc_inv_fst_fst, pullback_symmetry_hom_comp_fst], end @[simp, reassoc] lemma t_fst_snd (i j : 𝒰.J) : t 𝒰 f g i j ≫ pullback.fst ≫ pullback.snd = pullback.fst ≫ pullback.snd := begin delta t, simp only [pullback_symmetry_hom_comp_snd_assoc, category.comp_id, category.assoc, id.def, pullback_symmetry_hom_comp_fst_assoc, pullback_assoc_hom_snd_snd, pullback.lift_snd, pullback_assoc_inv_snd], end @[simp, reassoc] lemma t_snd (i j : 𝒰.J) : t 𝒰 f g i j ≫ pullback.snd = pullback.fst ≫ pullback.fst := begin delta t, simp only [pullback_symmetry_hom_comp_snd_assoc, category.assoc, id.def, pullback_symmetry_hom_comp_snd, pullback_assoc_hom_fst, pullback.lift_fst_assoc, pullback_symmetry_hom_comp_fst, pullback_assoc_inv_fst_snd], end lemma t_id (i : 𝒰.J) : t 𝒰 f g i i = 𝟙 _ := begin apply pullback.hom_ext; rw category.id_comp, apply pullback.hom_ext, { rw ← cancel_mono (𝒰.map i), simp only [pullback.condition, category.assoc, t_fst_fst] }, { simp only [category.assoc, t_fst_snd]}, { rw ← cancel_mono (𝒰.map i),simp only [pullback.condition, t_snd, category.assoc] } end /-- The inclusion map of `V i j = (Uᵢ ×[Z] Y) ×[X] Uⱼ ⟶ Uᵢ ×[Z] Y`-/ abbreviation fV (i j : 𝒰.J) : V 𝒰 f g i j ⟶ pullback ((𝒰.map i) ≫ f) g := pullback.fst /-- The map `((Xᵢ ×[Z] Y) ×[X] Xⱼ) ×[Xᵢ ×[Z] Y] ((Xᵢ ×[Z] Y) ×[X] Xₖ)` ⟶ `((Xⱼ ×[Z] Y) ×[X] Xₖ) ×[Xⱼ ×[Z] Y] ((Xⱼ ×[Z] Y) ×[X] Xᵢ)` needed for gluing -/ def t' (i j k : 𝒰.J) : pullback (fV 𝒰 f g i j) (fV 𝒰 f g i k) ⟶ pullback (fV 𝒰 f g j k) (fV 𝒰 f g j i) := begin refine (pullback_right_pullback_fst_iso _ _ _).hom ≫ _, refine _ ≫ (pullback_symmetry _ _).hom, refine _ ≫ (pullback_right_pullback_fst_iso _ _ _).inv, refine pullback.map _ _ _ _ (t 𝒰 f g i j) (𝟙 _) (𝟙 _) _ _, { simp only [←pullback.condition, category.comp_id, t_fst_fst_assoc] }, { simp only [category.comp_id, category.id_comp]} end section end @[simp, reassoc] lemma t'_fst_fst_fst (i j k : 𝒰.J) : t' 𝒰 f g i j k ≫ pullback.fst ≫ pullback.fst ≫ pullback.fst = pullback.fst ≫ pullback.snd := begin delta t', simp only [category.assoc, pullback_symmetry_hom_comp_fst_assoc, pullback_right_pullback_fst_iso_inv_snd_fst_assoc, pullback.lift_fst_assoc, t_fst_fst, pullback_right_pullback_fst_iso_hom_fst_assoc], end @[simp, reassoc] lemma t'_fst_fst_snd (i j k : 𝒰.J) : t' 𝒰 f g i j k ≫ pullback.fst ≫ pullback.fst ≫ pullback.snd = pullback.fst ≫ pullback.fst ≫ pullback.snd := begin delta t', simp only [category.assoc, pullback_symmetry_hom_comp_fst_assoc, pullback_right_pullback_fst_iso_inv_snd_fst_assoc, pullback.lift_fst_assoc, t_fst_snd, pullback_right_pullback_fst_iso_hom_fst_assoc], end @[simp, reassoc] lemma t'_fst_snd (i j k : 𝒰.J) : t' 𝒰 f g i j k ≫ pullback.fst ≫ pullback.snd = pullback.snd ≫ pullback.snd := begin delta t', simp only [category.comp_id, category.assoc, pullback_symmetry_hom_comp_fst_assoc, pullback_right_pullback_fst_iso_inv_snd_snd, pullback.lift_snd, pullback_right_pullback_fst_iso_hom_snd], end @[simp, reassoc] lemma t'_snd_fst_fst (i j k : 𝒰.J) : t' 𝒰 f g i j k ≫ pullback.snd ≫ pullback.fst ≫ pullback.fst = pullback.fst ≫ pullback.snd := begin delta t', simp only [category.assoc, pullback_symmetry_hom_comp_snd_assoc, pullback_right_pullback_fst_iso_inv_fst_assoc, pullback.lift_fst_assoc, t_fst_fst, pullback_right_pullback_fst_iso_hom_fst_assoc], end @[simp, reassoc] lemma t'_snd_fst_snd (i j k : 𝒰.J) : t' 𝒰 f g i j k ≫ pullback.snd ≫ pullback.fst ≫ pullback.snd = pullback.fst ≫ pullback.fst ≫ pullback.snd := begin delta t', simp only [category.assoc, pullback_symmetry_hom_comp_snd_assoc, pullback_right_pullback_fst_iso_inv_fst_assoc, pullback.lift_fst_assoc, t_fst_snd, pullback_right_pullback_fst_iso_hom_fst_assoc], end @[simp, reassoc] lemma t'_snd_snd (i j k : 𝒰.J) : t' 𝒰 f g i j k ≫ pullback.snd ≫ pullback.snd = pullback.fst ≫ pullback.fst ≫ pullback.fst := begin delta t', simp only [category.assoc, pullback_symmetry_hom_comp_snd_assoc, pullback_right_pullback_fst_iso_inv_fst_assoc, pullback.lift_fst_assoc, t_snd, pullback_right_pullback_fst_iso_hom_fst_assoc], end lemma cocycle_fst_fst_fst (i j k : 𝒰.J) : t' 𝒰 f g i j k ≫ t' 𝒰 f g j k i ≫ t' 𝒰 f g k i j ≫ pullback.fst ≫ pullback.fst ≫ pullback.fst = pullback.fst ≫ pullback.fst ≫ pullback.fst := by simp only [t'_fst_fst_fst, t'_fst_snd, t'_snd_snd] lemma cocycle_fst_fst_snd (i j k : 𝒰.J) : t' 𝒰 f g i j k ≫ t' 𝒰 f g j k i ≫ t' 𝒰 f g k i j ≫ pullback.fst ≫ pullback.fst ≫ pullback.snd = pullback.fst ≫ pullback.fst ≫ pullback.snd := by simp only [t'_fst_fst_snd] lemma cocycle_fst_snd (i j k : 𝒰.J) : t' 𝒰 f g i j k ≫ t' 𝒰 f g j k i ≫ t' 𝒰 f g k i j ≫ pullback.fst ≫ pullback.snd = pullback.fst ≫ pullback.snd := by simp only [t'_fst_snd, t'_snd_snd, t'_fst_fst_fst] lemma cocycle_snd_fst_fst (i j k : 𝒰.J) : t' 𝒰 f g i j k ≫ t' 𝒰 f g j k i ≫ t' 𝒰 f g k i j ≫ pullback.snd ≫ pullback.fst ≫ pullback.fst = pullback.snd ≫ pullback.fst ≫ pullback.fst := begin rw ← cancel_mono (𝒰.map i), simp only [pullback.condition_assoc, t'_snd_fst_fst, t'_fst_snd, t'_snd_snd] end lemma cocycle_snd_fst_snd (i j k : 𝒰.J) : t' 𝒰 f g i j k ≫ t' 𝒰 f g j k i ≫ t' 𝒰 f g k i j ≫ pullback.snd ≫ pullback.fst ≫ pullback.snd = pullback.snd ≫ pullback.fst ≫ pullback.snd := by simp only [pullback.condition_assoc, t'_snd_fst_snd] lemma cocycle_snd_snd (i j k : 𝒰.J) : t' 𝒰 f g i j k ≫ t' 𝒰 f g j k i ≫ t' 𝒰 f g k i j ≫ pullback.snd ≫ pullback.snd = pullback.snd ≫ pullback.snd := by simp only [t'_snd_snd, t'_fst_fst_fst, t'_fst_snd] -- `by tidy` should solve it, but it times out. lemma cocycle (i j k : 𝒰.J) : t' 𝒰 f g i j k ≫ t' 𝒰 f g j k i ≫ t' 𝒰 f g k i j = 𝟙 _ := begin apply pullback.hom_ext; rw category.id_comp, { apply pullback.hom_ext, { apply pullback.hom_ext, { simp_rw category.assoc, exact cocycle_fst_fst_fst 𝒰 f g i j k }, { simp_rw category.assoc, exact cocycle_fst_fst_snd 𝒰 f g i j k } }, { simp_rw category.assoc, exact cocycle_fst_snd 𝒰 f g i j k } }, { apply pullback.hom_ext, { apply pullback.hom_ext, { simp_rw category.assoc, exact cocycle_snd_fst_fst 𝒰 f g i j k }, { simp_rw category.assoc, exact cocycle_snd_fst_snd 𝒰 f g i j k } }, { simp_rw category.assoc, exact cocycle_snd_snd 𝒰 f g i j k } } end /-- Given `Uᵢ ×[Z] Y`, this is the glued fibered product `X ×[Z] Y`. -/ @[simps] def gluing : Scheme.glue_data.{u} := { J := 𝒰.J, U := λ i, pullback ((𝒰.map i) ≫ f) g, V := λ ⟨i, j⟩, V 𝒰 f g i j, -- `p⁻¹(Uᵢ ∩ Uⱼ)` where `p : Uᵢ ×[Z] Y ⟶ Uᵢ ⟶ X`. f := λ i j, pullback.fst, f_id := λ i, infer_instance, f_open := infer_instance, t := λ i j, t 𝒰 f g i j, t_id := λ i, t_id 𝒰 f g i, t' := λ i j k, t' 𝒰 f g i j k, t_fac := λ i j k, begin apply pullback.hom_ext, apply pullback.hom_ext, all_goals { simp only [t'_snd_fst_fst, t'_snd_fst_snd, t'_snd_snd, t_fst_fst, t_fst_snd, t_snd, category.assoc] } end, cocycle := λ i j k, cocycle 𝒰 f g i j k } /-- The first projection from the glued scheme into `X`. -/ def p1 : (gluing 𝒰 f g).glued ⟶ X := begin fapply multicoequalizer.desc, exact λ i, pullback.fst ≫ 𝒰.map i, rintro ⟨i, j⟩, change pullback.fst ≫ _ ≫ 𝒰.map i = (_ ≫ _) ≫ _ ≫ 𝒰.map j, rw pullback.condition, rw ← category.assoc, congr' 1, rw category.assoc, exact (t_fst_fst _ _ _ _ _).symm end /-- The second projection from the glued scheme into `Y`. -/ def p2 : (gluing 𝒰 f g).glued ⟶ Y := begin fapply multicoequalizer.desc, exact λ i, pullback.snd, rintro ⟨i, j⟩, change pullback.fst ≫ _ = (_ ≫ _) ≫ _, rw category.assoc, exact (t_fst_snd _ _ _ _ _).symm end lemma p_comm : p1 𝒰 f g ≫ f = p2 𝒰 f g ≫ g := begin apply multicoequalizer.hom_ext, intro i, erw [multicoequalizer.π_desc_assoc, multicoequalizer.π_desc_assoc], rw [category.assoc, pullback.condition] end variable (s : pullback_cone f g) /-- (Implementation) The canonical map `(s.X ×[X] Uᵢ) ×[s.X] (s.X ×[X] Uⱼ) ⟶ (Uᵢ ×[Z] Y) ×[X] Uⱼ` This is used in `glued_lift`. -/ def glued_lift_pullback_map (i j : 𝒰.J) : pullback ((𝒰.pullback_cover s.fst).map i) ((𝒰.pullback_cover s.fst).map j) ⟶ (gluing 𝒰 f g).V ⟨i, j⟩ := begin change pullback pullback.fst pullback.fst ⟶ pullback _ _, refine (pullback_right_pullback_fst_iso _ _ _).hom ≫ _, refine pullback.map _ _ _ _ _ (𝟙 _) (𝟙 _) _ _, { exact (pullback_symmetry _ _).hom ≫ pullback.map _ _ _ _ (𝟙 _) s.snd f (category.id_comp _).symm s.condition }, { simpa using pullback.condition }, { simp only [category.comp_id, category.id_comp] } end @[reassoc] lemma glued_lift_pullback_map_fst (i j : 𝒰.J) : glued_lift_pullback_map 𝒰 f g s i j ≫ pullback.fst = pullback.fst ≫ (pullback_symmetry _ _).hom ≫ pullback.map _ _ _ _ (𝟙 _) s.snd f (category.id_comp _).symm s.condition := begin delta glued_lift_pullback_map, simp only [category.assoc, id.def, pullback.lift_fst, pullback_right_pullback_fst_iso_hom_fst_assoc], end @[reassoc] lemma glued_lift_pullback_map_snd (i j : 𝒰.J) : glued_lift_pullback_map 𝒰 f g s i j ≫ pullback.snd = pullback.snd ≫ pullback.snd := begin delta glued_lift_pullback_map, simp only [category.assoc, category.comp_id, id.def, pullback.lift_snd, pullback_right_pullback_fst_iso_hom_snd], end /-- The lifted map `s.X ⟶ (gluing 𝒰 f g).glued` in order to show that `(gluing 𝒰 f g).glued` is indeed the pullback. Given a pullback cone `s`, we have the maps `s.fst ⁻¹' Uᵢ ⟶ Uᵢ` and `s.fst ⁻¹' Uᵢ ⟶ s.X ⟶ Y` that we may lift to a map `s.fst ⁻¹' Uᵢ ⟶ Uᵢ ×[Z] Y`. to glue these into a map `s.X ⟶ Uᵢ ×[Z] Y`, we need to show that the maps agree on `(s.fst ⁻¹' Uᵢ) ×[s.X] (s.fst ⁻¹' Uⱼ) ⟶ Uᵢ ×[Z] Y`. This is achieved by showing that both of these maps factors through `glued_lift_pullback_map`. -/ def glued_lift : s.X ⟶ (gluing 𝒰 f g).glued := begin fapply (𝒰.pullback_cover s.fst).glue_morphisms, { exact λ i, (pullback_symmetry _ _).hom ≫ pullback.map _ _ _ _ (𝟙 _) s.snd f (category.id_comp _).symm s.condition ≫ (gluing 𝒰 f g).ι i }, intros i j, rw ← glued_lift_pullback_map_fst_assoc, have : _ = pullback.fst ≫ _ := (gluing 𝒰 f g).glue_condition i j, rw [← this, gluing_to_glue_data_t, gluing_to_glue_data_f], simp_rw ← category.assoc, congr' 1, apply pullback.hom_ext; simp_rw category.assoc, { rw [t_fst_fst, glued_lift_pullback_map_snd], congr' 1, rw [← iso.inv_comp_eq, pullback_symmetry_inv_comp_snd], erw pullback.lift_fst, rw category.comp_id }, { rw [t_fst_snd, glued_lift_pullback_map_fst_assoc], erw [pullback.lift_snd, pullback.lift_snd], rw [pullback_symmetry_hom_comp_snd_assoc, pullback_symmetry_hom_comp_snd_assoc], exact pullback.condition_assoc _ } end lemma glued_lift_p1 : glued_lift 𝒰 f g s ≫ p1 𝒰 f g = s.fst := begin rw ← cancel_epi (𝒰.pullback_cover s.fst).from_glued, apply multicoequalizer.hom_ext, intro b, erw [multicoequalizer.π_desc_assoc, multicoequalizer.π_desc_assoc], delta glued_lift, simp_rw ← category.assoc, rw (𝒰.pullback_cover s.fst).ι_glue_morphisms, simp_rw category.assoc, erw [multicoequalizer.π_desc, pullback.lift_fst_assoc, pullback.condition, category.comp_id], rw pullback_symmetry_hom_comp_fst_assoc, end lemma glued_lift_p2 : glued_lift 𝒰 f g s ≫ p2 𝒰 f g = s.snd := begin rw ← cancel_epi (𝒰.pullback_cover s.fst).from_glued, apply multicoequalizer.hom_ext, intro b, erw [multicoequalizer.π_desc_assoc, multicoequalizer.π_desc_assoc], delta glued_lift, simp_rw ← category.assoc, rw (𝒰.pullback_cover s.fst).ι_glue_morphisms, simp_rw category.assoc, erw [multicoequalizer.π_desc, pullback.lift_snd], rw pullback_symmetry_hom_comp_snd_assoc, refl end /-- (Implementation) The canonical map `(W ×[X] Uᵢ) ×[W] (Uⱼ ×[Z] Y) ⟶ (Uⱼ ×[Z] Y) ×[X] Uᵢ = V j i` where `W` is the glued fibred product. This is used in `lift_comp_ι`. -/ def pullback_fst_ι_to_V (i j : 𝒰.J) : pullback (pullback.fst : pullback (p1 𝒰 f g) (𝒰.map i) ⟶ _) ((gluing 𝒰 f g).ι j) ⟶ V 𝒰 f g j i := (pullback_symmetry _ _ ≪≫ (pullback_right_pullback_fst_iso (p1 𝒰 f g) (𝒰.map i) _)).hom ≫ (pullback.congr_hom (multicoequalizer.π_desc _ _ _ _ _) rfl).hom @[simp, reassoc] lemma pullback_fst_ι_to_V_fst (i j : 𝒰.J) : pullback_fst_ι_to_V 𝒰 f g i j ≫ pullback.fst = pullback.snd := begin delta pullback_fst_ι_to_V, simp only [iso.trans_hom, pullback.congr_hom_hom, category.assoc, pullback.lift_fst, category.comp_id, pullback_right_pullback_fst_iso_hom_fst, pullback_symmetry_hom_comp_fst], end @[simp, reassoc] lemma pullback_fst_ι_to_V_snd (i j : 𝒰.J) : pullback_fst_ι_to_V 𝒰 f g i j ≫ pullback.snd = pullback.fst ≫ pullback.snd := begin delta pullback_fst_ι_to_V, simp only [iso.trans_hom, pullback.congr_hom_hom, category.assoc, pullback.lift_snd, category.comp_id, pullback_right_pullback_fst_iso_hom_snd, pullback_symmetry_hom_comp_snd_assoc] end /-- We show that the map `W ×[X] Uᵢ ⟶ Uᵢ ×[Z] Y ⟶ W` is the first projection, where the first map is given by the lift of `W ×[X] Uᵢ ⟶ Uᵢ` and `W ×[X] Uᵢ ⟶ W ⟶ Y`. It suffices to show that the two map agrees when restricted onto `Uⱼ ×[Z] Y`. In this case, both maps factor through `V j i` via `pullback_fst_ι_to_V` -/ lemma lift_comp_ι (i : 𝒰.J) : pullback.lift pullback.snd (pullback.fst ≫ p2 𝒰 f g) (by rw [← pullback.condition_assoc, category.assoc, p_comm]) ≫ (gluing 𝒰 f g).ι i = (pullback.fst : pullback (p1 𝒰 f g) (𝒰.map i) ⟶ _) := begin apply ((gluing 𝒰 f g).open_cover.pullback_cover pullback.fst).hom_ext, intro j, dsimp only [open_cover.pullback_cover], transitivity pullback_fst_ι_to_V 𝒰 f g i j ≫ fV 𝒰 f g j i ≫ (gluing 𝒰 f g).ι _, { rw ← (show _ = fV 𝒰 f g j i ≫ _, from (gluing 𝒰 f g).glue_condition j i), simp_rw ← category.assoc, congr' 1, rw [gluing_to_glue_data_f, gluing_to_glue_data_t], apply pullback.hom_ext; simp_rw category.assoc, { rw [t_fst_fst, pullback.lift_fst, pullback_fst_ι_to_V_snd] }, { rw [t_fst_snd, pullback.lift_snd, pullback_fst_ι_to_V_fst_assoc, pullback.condition_assoc], erw multicoequalizer.π_desc } }, { rw [pullback.condition, ← category.assoc], congr' 1, apply pullback.hom_ext, { simp only [pullback_fst_ι_to_V_fst] }, { simp only [pullback_fst_ι_to_V_fst] } } end /-- The canonical isomorphism between `W ×[X] Uᵢ` and `Uᵢ ×[X] Y`. That is, the preimage of `Uᵢ` in `W` along `p1` is indeed `Uᵢ ×[X] Y`. -/ def pullback_p1_iso (i : 𝒰.J) : pullback (p1 𝒰 f g) (𝒰.map i) ≅ pullback (𝒰.map i ≫ f) g := begin fsplit, exact pullback.lift pullback.snd (pullback.fst ≫ p2 𝒰 f g) (by rw [← pullback.condition_assoc, category.assoc, p_comm]), refine pullback.lift ((gluing 𝒰 f g).ι i) pullback.fst (by erw multicoequalizer.π_desc), { apply pullback.hom_ext, { simpa using lift_comp_ι 𝒰 f g i }, { simp only [category.assoc, pullback.lift_snd, pullback.lift_fst, category.id_comp] } }, { apply pullback.hom_ext, { simp only [category.assoc, pullback.lift_fst, pullback.lift_snd, category.id_comp] }, { simp only [category.assoc, pullback.lift_snd, pullback.lift_fst_assoc, category.id_comp], erw multicoequalizer.π_desc } }, end @[simp, reassoc] lemma pullback_p1_iso_hom_fst (i : 𝒰.J) : (pullback_p1_iso 𝒰 f g i).hom ≫ pullback.fst = pullback.snd := by { delta pullback_p1_iso, simp only [pullback.lift_fst] } @[simp, reassoc] lemma pullback_p1_iso_hom_snd (i : 𝒰.J) : (pullback_p1_iso 𝒰 f g i).hom ≫ pullback.snd = pullback.fst ≫ p2 𝒰 f g := by { delta pullback_p1_iso, simp only [pullback.lift_snd] } @[simp, reassoc] lemma pullback_p1_iso_inv_fst (i : 𝒰.J) : (pullback_p1_iso 𝒰 f g i).inv ≫ pullback.fst = (gluing 𝒰 f g).ι i := by { delta pullback_p1_iso, simp only [pullback.lift_fst] } @[simp, reassoc] lemma pullback_p1_iso_inv_snd (i : 𝒰.J) : (pullback_p1_iso 𝒰 f g i).inv ≫ pullback.snd = pullback.fst := by { delta pullback_p1_iso, simp only [pullback.lift_snd] } @[simp, reassoc] lemma pullback_p1_iso_hom_ι (i : 𝒰.J) : (pullback_p1_iso 𝒰 f g i).hom ≫ (gluing 𝒰 f g).ι i = pullback.fst := by rw [← pullback_p1_iso_inv_fst, iso.hom_inv_id_assoc] /-- The glued scheme (`(gluing 𝒰 f g).glued`) is indeed the pullback of `f` and `g`. -/ def glued_is_limit : is_limit (pullback_cone.mk _ _ (p_comm 𝒰 f g)) := begin apply pullback_cone.is_limit_aux', intro s, refine ⟨glued_lift 𝒰 f g s, glued_lift_p1 𝒰 f g s, glued_lift_p2 𝒰 f g s, _⟩, intros m h₁ h₂, change m ≫ p1 𝒰 f g = _ at h₁, change m ≫ p2 𝒰 f g = _ at h₂, apply (𝒰.pullback_cover s.fst).hom_ext, intro i, rw open_cover.pullback_cover_map, have := pullback_right_pullback_fst_iso (p1 𝒰 f g) (𝒰.map i) m ≪≫ pullback.congr_hom h₁ rfl, erw (𝒰.pullback_cover s.fst).ι_glue_morphisms, rw [← cancel_epi (pullback_right_pullback_fst_iso (p1 𝒰 f g) (𝒰.map i) m ≪≫ pullback.congr_hom h₁ rfl).hom, iso.trans_hom, category.assoc, pullback.congr_hom_hom, pullback.lift_fst_assoc, category.comp_id, pullback_right_pullback_fst_iso_hom_fst_assoc, pullback.condition], transitivity pullback.snd ≫ (pullback_p1_iso 𝒰 f g _).hom ≫ (gluing 𝒰 f g).ι _, { congr' 1, rw ← pullback_p1_iso_hom_ι }, simp_rw ← category.assoc, congr' 1, apply pullback.hom_ext, { simp only [category.comp_id, pullback_right_pullback_fst_iso_hom_snd, category.assoc, pullback_p1_iso_hom_fst, pullback.lift_snd, pullback.lift_fst, pullback_symmetry_hom_comp_fst] }, { simp only [category.comp_id, pullback_right_pullback_fst_iso_hom_fst_assoc, pullback_p1_iso_hom_snd, category.assoc, pullback.lift_fst_assoc, pullback_symmetry_hom_comp_snd_assoc, pullback.lift_snd], rw [← pullback.condition_assoc, h₂] } end lemma has_pullback_of_cover : has_pullback f g := ⟨⟨⟨_, glued_is_limit 𝒰 f g⟩⟩⟩ instance affine_has_pullback {A B C : CommRing} (f : Spec.obj (opposite.op A) ⟶ Spec.obj (opposite.op C)) (g : Spec.obj (opposite.op B) ⟶ Spec.obj (opposite.op C)) : has_pullback f g := begin rw [← Spec.image_preimage f, ← Spec.image_preimage g], exact ⟨⟨⟨_,is_limit_of_has_pullback_of_preserves_limit Spec (Spec.preimage f) (Spec.preimage g)⟩⟩⟩ end lemma affine_affine_has_pullback {B C : CommRing} {X : Scheme} (f : X ⟶ Spec.obj (opposite.op C)) (g : Spec.obj (opposite.op B) ⟶ Spec.obj (opposite.op C)) : has_pullback f g := has_pullback_of_cover X.affine_cover f g instance base_affine_has_pullback {C : CommRing} {X Y : Scheme} (f : X ⟶ Spec.obj (opposite.op C)) (g : Y ⟶ Spec.obj (opposite.op C)) : has_pullback f g := @@has_pullback_symmetry _ _ _ (@@has_pullback_of_cover Y.affine_cover g f (λ i, @@has_pullback_symmetry _ _ _ $ affine_affine_has_pullback _ _)) instance left_affine_comp_pullback_has_pullback {X Y Z : Scheme} (f : X ⟶ Z) (g : Y ⟶ Z) (i : Z.affine_cover.J) : has_pullback ((Z.affine_cover.pullback_cover f).map i ≫ f) g := begin let Xᵢ := pullback f (Z.affine_cover.map i), let Yᵢ := pullback g (Z.affine_cover.map i), let W := pullback (pullback.snd : Yᵢ ⟶ _) (pullback.snd : Xᵢ ⟶ _), have := big_square_is_pullback (pullback.fst : W ⟶ _) (pullback.fst : Yᵢ ⟶ _) (pullback.snd : Xᵢ ⟶ _) (Z.affine_cover.map i) pullback.snd pullback.snd g pullback.condition.symm pullback.condition.symm (pullback_cone.flip_is_limit $ pullback_is_pullback _ _) (pullback_cone.flip_is_limit $ pullback_is_pullback _ _), have : has_pullback (pullback.snd ≫ Z.affine_cover.map i : Xᵢ ⟶ _) g := ⟨⟨⟨_,this⟩⟩⟩, rw ← pullback.condition at this, exact this, end instance {X Y Z : Scheme} (f : X ⟶ Z) (g : Y ⟶ Z) : has_pullback f g := has_pullback_of_cover (Z.affine_cover.pullback_cover f) f g instance : has_pullbacks Scheme := has_pullbacks_of_has_limit_cospan _ instance {X Y Z : Scheme} (f : X ⟶ Z) (g : Y ⟶ Z) [is_affine X] [is_affine Y] [is_affine Z] : is_affine (pullback f g) := is_affine_of_iso (pullback.map f g (Spec.map (Γ.map f.op).op) (Spec.map (Γ.map g.op).op) (Γ_Spec.adjunction.unit.app X) (Γ_Spec.adjunction.unit.app Y) (Γ_Spec.adjunction.unit.app Z) (Γ_Spec.adjunction.unit.naturality f) (Γ_Spec.adjunction.unit.naturality g) ≫ (preserves_pullback.iso Spec _ _).inv) /-- Given an open cover `{ Xᵢ }` of `X`, then `X ×[Z] Y` is covered by `Xᵢ ×[Z] Y`. -/ @[simps J obj map] def open_cover_of_left (𝒰 : open_cover X) (f : X ⟶ Z) (g : Y ⟶ Z) : open_cover (pullback f g) := begin fapply ((gluing 𝒰 f g).open_cover.pushforward_iso (limit.iso_limit_cone ⟨_, glued_is_limit 𝒰 f g⟩).inv).copy 𝒰.J (λ i, pullback (𝒰.map i ≫ f) g) (λ i, pullback.map _ _ _ _ (𝒰.map i) (𝟙 _) (𝟙 _) (category.comp_id _) (by simp)) (equiv.refl 𝒰.J) (λ _, iso.refl _), rintro (i : 𝒰.J), change pullback.map _ _ _ _ _ _ _ _ _ = 𝟙 _ ≫ (gluing 𝒰 f g).ι i ≫ _, refine eq.trans _ (category.id_comp _).symm, apply pullback.hom_ext, all_goals { dsimp, simp only [limit.iso_limit_cone_inv_π, pullback_cone.mk_π_app_left, category.comp_id, pullback_cone.mk_π_app_right, category.assoc, pullback.lift_fst, pullback.lift_snd], symmetry, exact multicoequalizer.π_desc _ _ _ _ _ }, end /-- Given an open cover `{ Yᵢ }` of `Y`, then `X ×[Z] Y` is covered by `X ×[Z] Yᵢ`. -/ @[simps J obj map] def open_cover_of_right (𝒰 : open_cover Y) (f : X ⟶ Z) (g : Y ⟶ Z) : open_cover (pullback f g) := begin fapply ((open_cover_of_left 𝒰 g f).pushforward_iso (pullback_symmetry _ _).hom).copy 𝒰.J (λ i, pullback f (𝒰.map i ≫ g)) (λ i, pullback.map _ _ _ _ (𝟙 _) (𝒰.map i) (𝟙 _) (by simp) (category.comp_id _)) (equiv.refl _) (λ i, pullback_symmetry _ _), intro i, dsimp [open_cover.bind], apply pullback.hom_ext; simp, end /-- Given an open cover `{ Xᵢ }` of `X` and an open cover `{ Yⱼ }` of `Y`, then `X ×[Z] Y` is covered by `Xᵢ ×[Z] Yⱼ`. -/ @[simps J obj map] def open_cover_of_left_right (𝒰X : X.open_cover) (𝒰Y : Y.open_cover) (f : X ⟶ Z) (g : Y ⟶ Z) : (pullback f g).open_cover := begin fapply ((open_cover_of_left 𝒰X f g).bind (λ x, open_cover_of_right 𝒰Y (𝒰X.map x ≫ f) g)).copy (𝒰X.J × 𝒰Y.J) (λ ij, pullback (𝒰X.map ij.1 ≫ f) (𝒰Y.map ij.2 ≫ g)) (λ ij, pullback.map _ _ _ _ (𝒰X.map ij.1) (𝒰Y.map ij.2) (𝟙 _) (category.comp_id _) (category.comp_id _)) (equiv.sigma_equiv_prod _ _).symm (λ _, iso.refl _), rintro ⟨i, j⟩, apply pullback.hom_ext; simpa, end /-- (Implementation). Use `open_cover_of_base` instead. -/ def open_cover_of_base' (𝒰 : open_cover Z) (f : X ⟶ Z) (g : Y ⟶ Z) : open_cover (pullback f g) := begin apply (open_cover_of_left (𝒰.pullback_cover f) f g).bind, intro i, let Xᵢ := pullback f (𝒰.map i), let Yᵢ := pullback g (𝒰.map i), let W := pullback (pullback.snd : Yᵢ ⟶ _) (pullback.snd : Xᵢ ⟶ _), have := big_square_is_pullback (pullback.fst : W ⟶ _) (pullback.fst : Yᵢ ⟶ _) (pullback.snd : Xᵢ ⟶ _) (𝒰.map i) pullback.snd pullback.snd g pullback.condition.symm pullback.condition.symm (pullback_cone.flip_is_limit $ pullback_is_pullback _ _) (pullback_cone.flip_is_limit $ pullback_is_pullback _ _), refine open_cover_of_is_iso ((pullback_symmetry _ _).hom ≫ (limit.iso_limit_cone ⟨_, this⟩).inv ≫ pullback.map _ _ _ _ (𝟙 _) (𝟙 _) (𝟙 _) _ _), { simpa only [category.comp_id, category.id_comp, ← pullback.condition] }, { simp only [category.comp_id, category.id_comp] }, apply_instance end /-- Given an open cover `{ Zᵢ }` of `Z`, then `X ×[Z] Y` is covered by `Xᵢ ×[Zᵢ] Yᵢ`, where `Xᵢ = X ×[Z] Zᵢ` and `Yᵢ = Y ×[Z] Zᵢ` is the preimage of `Zᵢ` in `X` and `Y`. -/ @[simps J obj map] def open_cover_of_base (𝒰 : open_cover Z) (f : X ⟶ Z) (g : Y ⟶ Z) : open_cover (pullback f g) := begin apply (open_cover_of_base' 𝒰 f g).copy 𝒰.J (λ i, pullback (pullback.snd : pullback f (𝒰.map i) ⟶ _) (pullback.snd : pullback g (𝒰.map i) ⟶ _)) (λ i, pullback.map _ _ _ _ pullback.fst pullback.fst (𝒰.map i) pullback.condition.symm pullback.condition.symm) ((equiv.prod_punit 𝒰.J).symm.trans (equiv.sigma_equiv_prod 𝒰.J punit).symm) (λ _, iso.refl _), intro i, change _ = _ ≫ _ ≫ _, refine eq.trans _ (category.id_comp _).symm, apply pullback.hom_ext; simp only [category.comp_id, open_cover_of_left_map, open_cover.pullback_cover_map, pullback_cone.mk_π_app_left, open_cover_of_is_iso_map, limit.iso_limit_cone_inv_π_assoc, category.assoc, pullback.lift_fst_assoc, pullback_symmetry_hom_comp_snd_assoc, pullback.lift_fst, limit.iso_limit_cone_inv_π, pullback_cone.mk_π_app_right, pullback_symmetry_hom_comp_fst_assoc, pullback.lift_snd], end end pullback end algebraic_geometry.Scheme namespace algebraic_geometry instance {X Y S X' Y' S' : Scheme} (f : X ⟶ S) (g : Y ⟶ S) (f' : X' ⟶ S') (g' : Y' ⟶ S') (i₁ : X ⟶ X') (i₂ : Y ⟶ Y') (i₃ : S ⟶ S') (e₁ : f ≫ i₃ = i₁ ≫ f') (e₂ : g ≫ i₃ = i₂ ≫ g') [is_open_immersion i₁] [is_open_immersion i₂] [mono i₃] : is_open_immersion (pullback.map f g f' g' i₁ i₂ i₃ e₁ e₂) := begin rw pullback_map_eq_pullback_fst_fst_iso_inv, apply_instance end end algebraic_geometry
d6e9aa6293c0c82cd1f87b61d3866e612ec953fe
99b5e6372af1f404777312358869f95be7de84a3
/src/hott/types/nat/order.lean
6998bd9db4879bdc690d4b0065ae6994bc980a9f
[ "Apache-2.0" ]
permissive
forked-from-1kasper/hott3
8fa064ab5e8c9d6752a783d74ab226ddc5b5232a
2db24de7a361a7793b0eae4ca5c3fd4d4a0fc691
refs/heads/master
1,584,867,131,028
1,530,766,841,000
1,530,766,841,000
139,797,034
0
0
Apache-2.0
1,530,766,961,000
1,530,766,961,000
null
UTF-8
Lean
false
false
28,148
lean
/- Copyright (c) 2014 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Leonardo de Moura, Jeremy Avigad The order relation on the natural numbers. -/ import .basic ...algebra.ordered_ring universes u v w hott_theory namespace hott open hott.algebra nat sum namespace nat /- lt and le -/ inductive le (a : ℕ) : ℕ → Type | nat_refl : le a | step : Π {b}, le b → le (succ b) @[hott, instance, priority nat.prio] def nat_has_le : has_le nat := has_le.mk nat.le @[hott, refl] protected def le_refl : Π a : nat, a ≤ a := le.nat_refl @[hott, reducible] protected def lt (n m : ℕ) := succ n ≤ m @[hott, instance, priority nat.prio] def nat_has_lt : has_lt nat := has_lt.mk nat.lt @[hott] protected def le_of_eq {n m : ℕ} (p : n = m) : n ≤ m := by rwr p; apply le_refl @[hott] def le_succ (n : ℕ) : n ≤ succ n := le.step (nat.le_refl _) @[hott] def pred_le (n : ℕ) : pred n ≤ n := by cases n; repeat { constructor } @[hott, hsimp] def le_succ_iff_unit (n : ℕ) : n ≤ succ n ↔ unit := iff_unit_intro (le_succ n) @[hott, hsimp] def pred_le_iff_unit (n : ℕ) : pred n ≤ n ↔ unit := iff_unit_intro (pred_le n) @[hott] protected def le_trans {n m k : ℕ} (H1 : n ≤ m) (H2 : m ≤ k) : n ≤ k := begin hinduction H2 with k H2 IH, exact H1, exact le.step IH end @[hott] def le_succ_of_le {n m : ℕ} (H : n ≤ m) : n ≤ succ m := nat.le_trans H (le_succ _) @[hott] def le_of_succ_le {n m : ℕ} (H : succ n ≤ m) : n ≤ m := nat.le_trans (le_succ _) H @[hott] protected def le_of_lt {n m : ℕ} (H : n < m) : n ≤ m := le_of_succ_le H @[hott] def succ_le_succ {n m : ℕ} (H : n ≤ m) : succ n ≤ succ m := begin hinduction H with k H2 IH, reflexivity, exact le.step IH end @[hott] def pred_le_pred {n m : ℕ} (H : n ≤ m) : pred n ≤ pred m := begin hinduction H with k H2 IH, reflexivity, exact nat.le_trans IH (pred_le k) end @[hott] def le_of_succ_le_succ {n m : ℕ} : succ n ≤ succ m → n ≤ m := pred_le_pred @[hott] theorem le_succ_of_pred_le {n m : ℕ} : pred n ≤ m → n ≤ succ m := nat.cases_on n le.step (λa, succ_le_succ) @[hott] def not_succ_le_zero (n : ℕ) : ¬succ n ≤ 0 := by intro H; cases H @[hott] theorem succ_le_zero_iff_empty (n : ℕ) : succ n ≤ 0 ↔ empty := iff_empty_intro (not_succ_le_zero _) @[hott] def not_succ_le_self {n : ℕ} : ¬succ n ≤ n := begin hinduction n with n IH, apply not_succ_le_zero, intro H, apply IH, exact le_of_succ_le_succ H, end @[hott, hsimp] theorem succ_le_self_iff_empty (n : ℕ) : succ n ≤ n ↔ empty := iff_empty_intro not_succ_le_self @[hott] def zero_le (n : ℕ) : 0 ≤ n := begin hinduction n with n IH, reflexivity, exact le.step IH end @[hott, hsimp] theorem zero_le_iff_unit (n : ℕ) : 0 ≤ n ↔ unit := iff_unit_intro (zero_le n) @[hott] theorem lt.step {n m : ℕ} : n < m → n < succ m := le.step @[hott] def zero_lt_succ (n : ℕ) : 0 < succ n := succ_le_succ (zero_le _) @[hott, hsimp] theorem zero_lt_succ_iff_unit (n : ℕ) : 0 < succ n ↔ unit := iff_unit_intro (zero_lt_succ n) @[hott] protected theorem lt_trans {n m k : ℕ} (H1 : n < m) : m < k → n < k := nat.le_trans (le.step H1) @[hott] protected def lt_of_le_of_lt {n m k : ℕ} (H1 : n ≤ m) : m < k → n < k := nat.le_trans (succ_le_succ H1) @[hott] protected def lt_of_lt_of_le {n m k : ℕ} : n < m → m ≤ k → n < k := nat.le_trans @[hott] protected def lt_irrefl (n : ℕ) : ¬n < n := not_succ_le_self @[hott] theorem lt_self_iff_empty (n : ℕ) : n < n ↔ empty := iff_empty_intro (λ H, absurd H (nat.lt_irrefl n)) @[hott] theorem self_lt_succ (n : ℕ) : n < succ n := nat.le_refl _ @[hott, hsimp] theorem self_lt_succ_iff_unit (n : ℕ) : n < succ n ↔ unit := iff_unit_intro (self_lt_succ n) @[hott] theorem lt.base (n : ℕ) : n < succ n := nat.le_refl _ @[hott] theorem le_lt_antisymm {n m : ℕ} (H1 : n ≤ m) (H2 : m < n) : empty := nat.lt_irrefl _ (nat.lt_of_le_of_lt H1 H2) @[hott] protected def le_antisymm {n m : ℕ} (H1 : n ≤ m) (H2 : m ≤ n) : n = m := begin hinduction H1 with m H1 IH, reflexivity, exact absurd (nat.lt_of_le_of_lt H1 H2) (nat.lt_irrefl _) end @[hott] theorem lt_le_antisymm {n m : ℕ} (H1 : n < m) (H2 : m ≤ n) : empty := le_lt_antisymm H2 H1 @[hott] protected theorem nat.lt_asymm {n m : ℕ} (H1 : n < m) : ¬ m < n := le_lt_antisymm (nat.le_of_lt H1) @[hott] theorem not_lt_zero (a : ℕ) : ¬ a < 0 := not_succ_le_zero _ @[hott, hsimp] theorem lt_zero_iff_empty (a : ℕ) : a < 0 ↔ empty := iff_empty_intro (not_lt_zero a) @[hott] protected def eq_sum_lt_of_le {a b : ℕ} (H : a ≤ b) : a = b ⊎ a < b := le.cases_on H (inl rfl) (λn h, inr (succ_le_succ h)) @[hott] protected def le_of_eq_sum_lt {a b : ℕ} (H : a = b ⊎ a < b) : a ≤ b := begin hinduction H with H H, exact nat.le_of_eq H, exact nat.le_of_lt H end @[hott] theorem succ_lt_succ {a b : ℕ} : a < b → succ a < succ b := succ_le_succ @[hott] def lt_of_succ_lt {a b : ℕ} : succ a < b → a < b := le_of_succ_le @[hott] theorem lt_of_succ_lt_succ {a b : ℕ} : succ a < succ b → a < b := le_of_succ_le_succ @[hott, instance, priority nat.prio] def decidable_le : Π a b : nat, decidable (a ≤ b) := λa, nat.rec (λm, (decidable.inl (zero_le _))) (λn IH m, nat.cases_on m (decidable.inr (not_succ_le_zero n)) (λm, decidable.rec (λH, decidable.inl (succ_le_succ H)) (λH, decidable.inr (λa, H (le_of_succ_le_succ a))) (IH m))) a @[hott, instance, priority nat.prio] def decidable_lt : Π a b : nat, decidable (a < b) := λ a b, decidable_le (succ a) b @[hott] protected def lt_sum_ge (a b : ℕ) : a < b ⊎ a ≥ b := nat.rec (inr (zero_le _)) (λn H, sum.rec (λh, inl (le_succ_of_le h)) (λh, sum.rec_on (nat.eq_sum_lt_of_le h) (λe, inl (nat.le_of_eq (ap succ e⁻¹))) inr) H) b @[hott] protected def lt_ge_by_cases {a b : ℕ} {P : Type _} (H1 : a < b → P) (H2 : a ≥ b → P) : P := hott.decidable.by_cases H1 (λh, H2 (sum.rec_on (nat.lt_sum_ge a b) (λa, absurd a h) (λa, a))) @[hott] protected def lt_by_cases {a b : ℕ} {P : Type _} (H1 : a < b → P) (H2 : a = b → P) (H3 : b < a → P) : P := nat.lt_ge_by_cases H1 (λh₁, nat.lt_ge_by_cases H3 (λh₂, H2 (nat.le_antisymm h₂ h₁))) @[hott] protected theorem lt_trichotomy (a b : ℕ) : a < b ⊎ a = b ⊎ b < a := nat.lt_by_cases (λH, inl H) (λH, inr (inl H)) (λH, inr (inr H)) @[hott] protected theorem eq_sum_lt_of_not_lt {a b : ℕ} (hnlt : ¬ a < b) : a = b ⊎ b < a := sum.rec_on (nat.lt_trichotomy a b) (λ hlt, absurd hlt hnlt) (λ h, h) @[hott] def lt_succ_of_le {a b : ℕ} : a ≤ b → a < succ b := succ_le_succ @[hott] def lt_of_succ_le {a b : ℕ} (h : succ a ≤ b) : a < b := h @[hott] def succ_le_of_lt {a b : ℕ} (h : a < b) : succ a ≤ b := h @[hott, hsimp] theorem succ_sub_succ_eq_sub (a b : ℕ) : succ a - succ b = a - b := nat.rec (by simp) (λ b, ap pred) b @[hott] theorem sub_eq_succ_sub_succ (a b : ℕ) : a - b = succ a - succ b := (succ_sub_succ_eq_sub _ _)⁻¹ @[hott, hsimp] theorem zero_sub_eq_zero (a : ℕ) : 0 - a = 0 := nat.rec rfl (λ a, ap pred) a @[hott] theorem zero_eq_zero_sub (a : ℕ) : 0 = 0 - a := (zero_sub_eq_zero _)⁻¹ @[hott] theorem sub_le (a b : ℕ) : a - b ≤ a := nat.rec_on b (nat.le_refl _) (λ b₁, nat.le_trans (pred_le _)) @[hott, hsimp] theorem sub_le_iff_unit (a b : ℕ) : a - b ≤ a ↔ unit := iff_unit_intro (sub_le a b) @[hott] theorem sub_lt {a b : ℕ} (H1 : 0 < a) (H2 : 0 < b) : a - b < a := nat.cases_on a (λh, absurd h (nat.lt_irrefl _)) (λa h, succ_le_succ (nat.cases_on b (λh, absurd h (nat.lt_irrefl _)) (λb c, nat.le_trans (nat.le_of_eq (succ_sub_succ_eq_sub a b)) (sub_le a b)) H2)) H1 @[hott] theorem sub_lt_succ (a b : ℕ) : a - b < succ a := lt_succ_of_le (sub_le _ _) @[hott, hsimp] theorem sub_lt_succ_iff_unit (a b : ℕ) : a - b < succ a ↔ unit := iff_unit_intro (sub_lt_succ _ _) @[hott] protected def le_of_lt_sum_eq {m n : ℕ} (H : m < n ⊎ m = n) : m ≤ n := nat.le_of_eq_sum_lt (sum.swap H) @[hott] protected def lt_sum_eq_of_le {m n : ℕ} (H : m ≤ n) : m < n ⊎ m = n := sum.swap (nat.eq_sum_lt_of_le H) @[hott] protected def le_iff_lt_sum_eq (m n : ℕ) : m ≤ n ↔ m < n ⊎ m = n := iff.intro nat.lt_sum_eq_of_le nat.le_of_lt_sum_eq @[hott] protected def lt_of_le_prod_ne {m n : ℕ} (H1 : m ≤ n) : m ≠ n → m < n := sum.resolve_left (nat.eq_sum_lt_of_le H1) @[hott] protected theorem lt_iff_le_prod_ne (m n : ℕ) : m < n ↔ m ≤ n × m ≠ n := iff.intro (λH, ⟨nat.le_of_lt H, λH1, nat.lt_irrefl n (nat.le_trans (nat.le_of_eq (ap succ H1⁻¹)) H)⟩) (λv, prod.rec nat.lt_of_le_prod_ne v) @[hott] def le_add_right (n k : ℕ) : n ≤ n + k := begin hinduction k with k IH, reflexivity, exact le_succ_of_le IH end @[hott] theorem le_add_left (n m : ℕ): n ≤ m + n := by rwr add.comm; apply le_add_right @[hott] def le.intro {n m k : ℕ} (h : n + k = m) : n ≤ m := by rwr ←h; apply le_add_right @[hott] def le.elim {n m : ℕ} (H : n ≤ m) : Σ k, n + k = m := begin hinduction H with m H IH, exact ⟨0, idp⟩, hinduction IH with k H2, exact ⟨succ k, ap succ H2⟩ end @[hott] protected def le_total {m n : ℕ} : m ≤ n ⊎ n ≤ m := sum.imp_left nat.le_of_lt (nat.lt_sum_ge _ _) /- addition -/ @[hott] protected def add_le_add_left {n m : ℕ} (H : n ≤ m) (k : ℕ) : k + n ≤ k + m := begin hinduction le.elim H with p l Hl, fapply le.intro, exact l, rwr ←Hl, apply nat.add_assoc end @[hott] protected theorem add_le_add_right {n m : ℕ} (H : n ≤ m) (k : ℕ) : n + k ≤ m + k := by rwr [nat.add_comm n k, nat.add_comm m k]; apply nat.add_le_add_left H @[hott] protected def le_of_add_le_add_left {k n m : ℕ} (H : k + n ≤ k + m) : n ≤ m := begin hinduction le.elim H with p l Hl, exact le.intro (nat.add_left_cancel ((nat.add_assoc _ _ _)⁻¹ᵖ ⬝ Hl)) end @[hott] protected def lt_of_add_lt_add_left {k n m : ℕ} (H : k + n < k + m) : n < m := let H' := nat.le_of_lt H in nat.lt_of_le_prod_ne (nat.le_of_add_le_add_left H') (assume Heq, nat.lt_irrefl _ (Heq ▸ H)) @[hott] protected def add_lt_add_left {n m : ℕ} (H : n < m) (k : ℕ) : k + n < k + m := by apply lt_of_succ_le; rwr [←add_succ]; exact nat.add_le_add_left (succ_le_of_lt H) k @[hott] protected def add_lt_add_right {n m : ℕ} (H : n < m) (k : ℕ) : n + k < m + k := by rwr [nat.add_comm n k, nat.add_comm m k]; apply nat.add_lt_add_left H @[hott] protected def lt_add_of_pos_right {n k : ℕ} (H : k > 0) : n < n + k := nat.add_lt_add_left H n /- multiplication -/ @[hott] def mul_le_mul_left {n m : ℕ} (k : ℕ) (H : n ≤ m) : k * n ≤ k * m := begin hinduction le.elim H with p l Hl, have : k * n + k * l = k * m, by rwr [←nat.left_distrib, Hl], exact le.intro this end @[hott] def mul_le_mul_right {n m : ℕ} (k : ℕ) (H : n ≤ m) : n * k ≤ m * k := by rwr [mul.comm n k, mul.comm m k]; exact mul_le_mul_left _ H @[hott] protected theorem mul_le_mul {n m k l : ℕ} (H1 : n ≤ k) (H2 : m ≤ l) : n * m ≤ k * l := nat.le_trans (nat.mul_le_mul_right _ H1) (nat.mul_le_mul_left _ H2) @[hott] protected def mul_lt_mul_of_pos_left {n m k : ℕ} (H : n < m) (Hk : k > 0) : k * n < k * m := begin apply nat.lt_of_lt_of_le (nat.lt_add_of_pos_right Hk), rwr ←mul_succ, exact nat.mul_le_mul_left k (succ_le_of_lt H) end @[hott] protected def mul_lt_mul_of_pos_right {n m k : ℕ} (H : n < m) (Hk : k > 0) : n * k < m * k := by rwr [mul.comm n k, mul.comm m k]; exact nat.mul_lt_mul_of_pos_left H Hk /- nat is an instance of a linearly ordered semiring and a lattice -/ @[hott, instance] protected def decidable_linear_ordered_semiring : hott.algebra.decidable_linear_ordered_semiring ℕ := { add_left_cancel := @nat.add_left_cancel, add_right_cancel := @nat.add_right_cancel, lt := nat.lt, le := nat.le, le_refl := nat.le_refl, le_trans := @nat.le_trans, le_antisymm := @nat.le_antisymm, le_total := @nat.le_total, le_iff_lt_sum_eq := @nat.le_iff_lt_sum_eq, le_of_lt := @nat.le_of_lt, lt_irrefl := @nat.lt_irrefl, lt_of_lt_of_le := @nat.lt_of_lt_of_le, lt_of_le_of_lt := @nat.lt_of_le_of_lt, lt_of_add_lt_add_left := @nat.lt_of_add_lt_add_left, add_lt_add_left := @nat.add_lt_add_left, add_le_add_left := @nat.add_le_add_left, le_of_add_le_add_left := @nat.le_of_add_le_add_left, zero_lt_one := zero_lt_succ 0, mul_le_mul_of_nonneg_left := (λa b c H1 H2, nat.mul_le_mul_left c H1), mul_le_mul_of_nonneg_right := (λa b c H1 H2, nat.mul_le_mul_right c H1), mul_lt_mul_of_pos_left := @nat.mul_lt_mul_of_pos_left, mul_lt_mul_of_pos_right := @nat.mul_lt_mul_of_pos_right, decidable_lt := nat.decidable_lt, ..nat.comm_semiring } /- Extra instances to short-circuit type class resolution -/ @[hott] instance : algebra.add_comm_monoid nat := by apply_instance @[hott] instance : algebra.add_monoid nat := by apply_instance @[hott] instance : algebra.monoid nat := by apply_instance @[hott] instance : algebra.comm_monoid nat := by apply_instance @[hott] instance : algebra.comm_semigroup nat := by apply_instance @[hott] instance : algebra.semigroup nat := by apply_instance @[hott] instance : algebra.add_comm_semigroup nat := by apply_instance @[hott] instance : algebra.add_semigroup nat := by apply_instance @[hott] instance : algebra.distrib nat := by apply_instance @[hott] instance : algebra.semiring nat := by apply_instance @[hott] instance : algebra.ordered_semiring nat := by apply_instance @[hott, instance, priority nat.prio] def nat_has_dvd : has_dvd nat := has_dvd.mk has_dvd.dvd @[hott] theorem add_pos_left {a : ℕ} (H : 0 < a) (b : ℕ) : 0 < a + b := @hott.algebra.add_pos_of_pos_of_nonneg _ _ a b H (zero_le _) @[hott] theorem add_pos_right {a : ℕ} (H : 0 < a) (b : ℕ) : 0 < b + a := by rwr add.comm; apply add_pos_left H b @[hott] theorem add_eq_zero_iff_eq_zero_prod_eq_zero {a b : ℕ} : a + b = 0 ↔ a = 0 × b = 0 := @add_eq_zero_iff_eq_zero_prod_eq_zero_of_nonneg_of_nonneg _ _ a b (zero_le _) (zero_le _) @[hott] theorem le_add_of_le_left {a b c : ℕ} (H : b ≤ c) : b ≤ a + c := @hott.algebra.le_add_of_nonneg_of_le _ _ a b c (zero_le _) H @[hott] theorem le_add_of_le_right {a b c : ℕ} (H : b ≤ c) : b ≤ c + a := @hott.algebra.le_add_of_le_of_nonneg _ _ a b c H (zero_le _) @[hott] theorem lt_add_of_lt_left {b c : ℕ} (H : b < c) (a : ℕ) : b < a + c := @hott.algebra.lt_add_of_nonneg_of_lt _ _ a b c (zero_le _) H @[hott] theorem lt_add_of_lt_right {b c : ℕ} (H : b < c) (a : ℕ) : b < c + a := @hott.algebra.lt_add_of_lt_of_nonneg _ _ a b c H (zero_le _) @[hott] theorem lt_of_mul_lt_mul_left {a b c : ℕ} (H : c * a < c * b) : a < b := @hott.algebra.lt_of_mul_lt_mul_left _ _ a b c H (zero_le _) @[hott] theorem lt_of_mul_lt_mul_right {a b c : ℕ} (H : a * c < b * c) : a < b := @hott.algebra.lt_of_mul_lt_mul_right _ _ a b c H (zero_le _) @[hott] theorem pos_of_mul_pos_left {a b : ℕ} (H : 0 < a * b) : 0 < b := @hott.algebra.pos_of_mul_pos_left _ _ a b H (zero_le _) @[hott] theorem pos_of_mul_pos_right {a b : ℕ} (H : 0 < a * b) : 0 < a := @hott.algebra.pos_of_mul_pos_right _ _ a b H (zero_le _) @[hott] theorem zero_le_one : (0:nat) ≤ 1 := dec_star /- properties specific to nat -/ @[hott] theorem lt_intro {n m k : ℕ} (H : succ n + k = m) : n < m := lt_of_succ_le (le.intro H) @[hott] theorem lt_elim {n m : ℕ} (H : n < m) : Σk, succ n + k = m := le.elim (succ_le_of_lt H) @[hott] theorem lt_add_succ (n m : ℕ) : n < n + succ m := lt_intro (succ_add_eq_succ_add _ _) @[hott] theorem eq_zero_of_le_zero {n : ℕ} (H : n ≤ 0) : n = 0 := begin hinduction le.elim H with p k Hk, exact eq_zero_of_add_eq_zero_right Hk end /- succ and pred -/ @[hott] def le_of_lt_succ {m n : nat} : m < succ n → m ≤ n := le_of_succ_le_succ @[hott] theorem lt_iff_succ_le (m n : nat) : m < n ↔ succ m ≤ n := iff.rfl @[hott] theorem lt_succ_iff_le (m n : nat) : m < succ n ↔ m ≤ n := iff.intro le_of_lt_succ lt_succ_of_le @[hott] theorem self_le_succ (n : ℕ) : n ≤ succ n := le.intro (add_one _) @[hott] theorem succ_le_sum_eq_of_le {n m : ℕ} : n ≤ m → succ n ≤ m ⊎ n = m := lt_sum_eq_of_le @[hott] theorem pred_le_of_le_succ {n m : ℕ} : n ≤ succ m → pred n ≤ m := pred_le_pred @[hott] theorem succ_le_of_le_pred {n m : ℕ} : succ n ≤ m → n ≤ pred m := pred_le_pred @[hott] theorem pred_le_pred_of_le {n m : ℕ} : n ≤ m → pred n ≤ pred m := pred_le_pred @[hott] theorem pre_lt_of_lt {n m : ℕ} : n < m → pred n < m := lt_of_le_of_lt (pred_le _) @[hott] theorem lt_of_pred_lt_pred {n m : ℕ} (H : pred n < pred m) : n < m := lt_of_not_ge (λthis, not_lt_of_ge (pred_le_pred_of_le this) H) @[hott] theorem le_sum_eq_succ_of_le_succ {n m : ℕ} (H : n ≤ succ m) : n ≤ m ⊎ n = succ m := sum.imp_left le_of_succ_le_succ (succ_le_sum_eq_of_le H) @[hott] theorem le_pred_self (n : ℕ) : pred n ≤ n := pred_le n @[hott] theorem succ_pos (n : ℕ) : 0 < succ n := zero_lt_succ _ @[hott] theorem succ_pred_of_pos {n : ℕ} (H : n > 0) : succ (pred n) = n := (sum.resolve_left (eq_zero_sum_eq_succ_pred n) (ne.symm (ne_of_lt H)))⁻¹ @[hott] theorem exists_eq_succ_of_lt {n : ℕ} : Π {m : ℕ}, n < m → Σk, m = succ k | 0 H := absurd H (not_lt_zero _) | (succ k) H := sigma.mk k rfl @[hott] theorem lt_succ_self (n : ℕ) : n < succ n := lt.base n @[hott] lemma lt_succ_of_lt {i j : nat} : i < j → i < succ j := λPlt, hott.algebra.lt.trans Plt (self_lt_succ j) @[hott] lemma one_le_succ (n : ℕ) : 1 ≤ succ n := nat.succ_le_succ (zero_le _) @[hott] lemma two_le_succ_succ (n : ℕ) : 2 ≤ succ (succ n) := nat.succ_le_succ (one_le_succ _) /- other forms of induction -/ @[hott] protected def strong_rec_on {P : nat → Type _} (n : ℕ) (H : Πn, (Πm, m < n → P m) → P n) : P n := begin have : Π⦃m⦄, m < n → P m, { hinduction n with n IH; intros m Hm, cases Hm, hinduction (lt_sum_eq_of_le (le_of_lt_succ Hm)) with p H' H', exact IH H', hinduction H', exact H m IH }, exact H n this end @[hott] protected theorem case_strong_rec_on {P : nat → Type _} (a : nat) (H0 : P 0) (Hind : Π(n : nat), (Πm, m ≤ n → P m) → P (succ n)) : P a := nat.strong_rec_on a (λn, show (Π m, m < n → P m) → P n, from nat.cases_on n (λthis, show P 0, from H0) (λn this, show P (succ n), from Hind n (λm, assume H1 : m ≤ n, this _ (lt_succ_of_le H1)))) /- pos -/ @[hott] theorem by_cases_zero_pos {P : ℕ → Type _} (y : ℕ) (H0 : P 0) (H1 : Π {y : nat}, y > 0 → P y) : P y := nat.cases_on y H0 (λy, H1 (succ_pos _)) @[hott] theorem eq_zero_sum_pos (n : ℕ) : n = 0 ⊎ n > 0 := begin hinduction n with n IH, exact inl idp, exact inr (zero_lt_succ n) end @[hott] theorem pos_of_ne_zero {n : ℕ} (H : n ≠ 0) : n > 0 := sum.elim (eq_zero_sum_pos _) (λH2 : n = 0, empty.elim (H H2)) (λH2 : n > 0, H2) @[hott] theorem ne_zero_of_pos {n : ℕ} (H : n > 0) : n ≠ 0 := ne.symm (ne_of_lt H) @[hott] theorem exists_eq_succ_of_pos {n : ℕ} (H : n > 0) : Σl, n = succ l := exists_eq_succ_of_lt H -- @[hott] theorem pos_of_dvd_of_pos {m n : ℕ} (H1 : m ∣ n) (H2 : n > 0) : m > 0 := -- pos_of_ne_zero -- (λthis, -- have n = 0, by apply eq_zero_of_zero_dvd; rwra ←this, -- ne_of_lt H2 (by subst n)) /- multiplication -/ @[hott] theorem mul_lt_mul_of_le_of_lt {n m k l : ℕ} (Hk : k > 0) (H1 : n ≤ k) (H2 : m < l) : n * m < k * l := lt_of_le_of_lt (mul_le_mul_right m H1) (mul_lt_mul_of_pos_left H2 Hk) @[hott] theorem mul_lt_mul_of_lt_of_le {n m k l : ℕ} (Hl : l > 0) (H1 : n < k) (H2 : m ≤ l) : n * m < k * l := lt_of_le_of_lt (mul_le_mul_left n H2) (mul_lt_mul_of_pos_right H1 Hl) @[hott] theorem mul_lt_mul_of_le_of_le {n m k l : ℕ} (H1 : n < k) (H2 : m < l) : n * m < k * l := have H3 : n * m ≤ k * m, from mul_le_mul_right m (le_of_lt H1), have H4 : k * m < k * l, from mul_lt_mul_of_pos_left H2 (lt_of_le_of_lt (zero_le _) H1), lt_of_le_of_lt H3 H4 @[hott] theorem eq_of_mul_eq_mul_left {m k n : ℕ} (Hn : n > 0) (H : n * m = n * k) : m = k := have n * m ≤ n * k, by rwr H, have H2 : m ≤ k, from le_of_mul_le_mul_left this Hn, have n * k ≤ n * m, by rwr H, have k ≤ m, from le_of_mul_le_mul_left this Hn, le.antisymm H2 this @[hott] theorem eq_of_mul_eq_mul_right {n m k : ℕ} (Hm : m > 0) (H : n * m = k * m) : n = k := by apply eq_of_mul_eq_mul_left Hm; rwra [mul.comm m n, mul.comm m k] @[hott] theorem eq_zero_sum_eq_of_mul_eq_mul_left {n m k : ℕ} (H : n * m = n * k) : n = 0 ⊎ m = k := (eq_zero_sum_pos _).functor_right _ (assume Hn : n > 0, eq_of_mul_eq_mul_left Hn H) @[hott] theorem eq_zero_sum_eq_of_mul_eq_mul_right {n m k : ℕ} (H : n * m = k * m) : m = 0 ⊎ n = k := by apply eq_zero_sum_eq_of_mul_eq_mul_left; rwra [mul.comm m n, mul.comm m k] @[hott] theorem eq_one_of_mul_eq_one_right {n m : ℕ} (H : n * m = 1) : n = 1 := have H2 : n * m > 0, by rwr H; apply succ_pos, sum.elim (le_sum_gt n 1) (λH3, have n > 0, from pos_of_mul_pos_right H2, show n = 1, from le.antisymm H3 (succ_le_of_lt this)) (λH3, have m > 0, from pos_of_mul_pos_left H2, have n * m ≥ 2 * 1, from nat.mul_le_mul (succ_le_of_lt H3) (succ_le_of_lt this), have 1 ≥ 2, by rwra [H, hott.algebra.mul_one] at this, absurd (lt_succ_self _) (not_lt_of_ge this)) @[hott] theorem eq_one_of_mul_eq_one_left {n m : ℕ} (H : n * m = 1) : m = 1 := by apply eq_one_of_mul_eq_one_right; rwra [mul.comm] @[hott] theorem eq_one_of_mul_eq_self_left {n m : ℕ} (Hpos : n > 0) (H : m * n = n) : m = 1 := eq_of_mul_eq_mul_right Hpos (H ⬝ (one_mul _)⁻¹ᵖ) @[hott] theorem eq_one_of_mul_eq_self_right {n m : ℕ} (Hpos : m > 0) (H : m * n = m) : n = 1 := by apply eq_one_of_mul_eq_self_left Hpos; rwra [mul.comm] -- @[hott] theorem eq_one_of_dvd_one {n : ℕ} (H : n ∣ 1) : n = 1 := -- dvd.elim H -- (λm, suppose 1 = n * m, -- eq_one_of_mul_eq_one_right this⁻¹) /- min and max -/ open decidable local notation `min` := hott.algebra.min local notation `max` := hott.algebra.max @[hott, hsimp] theorem min_zero (a : ℕ) : min a 0 = 0 := by rwr [hott.algebra.min_eq_right (zero_le _)] @[hott, hsimp] theorem zero_min (a : ℕ) : min 0 a = 0 := by rwr [min_eq_left (zero_le _)] @[hott, hsimp] theorem max_zero (a : ℕ) : max a 0 = a := by rwr [max_eq_left (zero_le _)] @[hott, hsimp] theorem zero_max (a : ℕ) : max 0 a = a := by rwr [max_eq_right (zero_le _)] @[hott, hsimp] theorem min_succ_succ (a b : ℕ) : min (succ a) (succ b) = succ (min a b) := sum.elim (lt_sum_ge a b) (λthis, by rwr [min_eq_left_of_lt this, min_eq_left_of_lt (succ_lt_succ this)]) (λthis, by rwr [min_eq_right this, min_eq_right (succ_le_succ this)]) @[hott, hsimp] theorem max_succ_succ (a b : ℕ) : max (succ a) (succ b) = succ (max a b) := sum.elim (lt_sum_ge a b) (λthis, by rwr [max_eq_right_of_lt this, max_eq_right_of_lt (succ_lt_succ this)]) (λthis, by rwr [max_eq_left this, max_eq_left (succ_le_succ this)]) /- In algebra.ordered_group, these next four are only proved for additive groups, not additive semigroups. -/ @[hott] protected theorem min_add_add_left (a b c : ℕ) : min (a + b) (a + c) = a + min b c := sum.elim (le_sum_gt b c) (λH, have a + b ≤ a + c, from add_le_add_left H _, by rwr [min_eq_left H, min_eq_left this]) (λthis, have H : c ≤ b, from le_of_lt this, have a + c ≤ a + b, from add_le_add_left H _, by rwr [min_eq_right H, min_eq_right this]) @[hott] protected theorem min_add_add_right (a b c : ℕ) : min (a + c) (b + c) = min a b + c := by rwr [nat.add_comm a c, nat.add_comm b c, nat.add_comm (min _ _) c]; apply nat.min_add_add_left @[hott] protected theorem max_add_add_left (a b c : ℕ) : max (a + b) (a + c) = a + max b c := sum.elim (le_sum_gt b c) (λH, /- b ≤ c -/ have a + b ≤ a + c, from add_le_add_left H _, by rwr [max_eq_right H, max_eq_right this]) (λthis, have H : c ≤ b, from le_of_lt this, have a + c ≤ a + b, from add_le_add_left H _, by rwr [max_eq_left H, max_eq_left this]) @[hott] protected theorem max_add_add_right (a b c : ℕ) : max (a + c) (b + c) = max a b + c := by rwr [nat.add_comm a c, nat.add_comm b c, nat.add_comm (max _ _) c]; apply nat.max_add_add_left /- least and greatest -/ section least_prod_greatest variable (P : ℕ → Type _) variable [decP : Π n, decidable (P n)] include decP -- returns the least i < n satisfying P, sum n if there is none @[hott] def least : ℕ → ℕ | 0 := 0 | (succ n) := if' P (least n) then least n else succ n @[hott] theorem least_of_bound {n : ℕ} (H : P n) : P (least P n) := begin induction n with m ih, dsimp [least], apply H, dsimp [least], cases decidable.em (P (least P m)) with Hlp Hlp, rwr [if_pos Hlp], apply Hlp, rwr [if_neg Hlp], apply H end @[hott] theorem least_le (n : ℕ) : least P n ≤ n:= begin induction n with m ih, reflexivity, dsimp [least], cases decidable.em (P (least P m)) with Psm Pnsm, rwr [if_pos Psm], apply le.trans ih (le_succ _), rwr [if_neg Pnsm] end @[hott] theorem least_of_lt {i n : ℕ} (ltin : i < n) (H : P i) : P (least P n) := begin induction n with m ih, exact absurd ltin (not_lt_zero _), dsimp [least], cases decidable.em (P (least P m)) with Psm Pnsm, rwr [if_pos Psm], apply Psm, rwr [if_neg Pnsm], cases (lt_sum_eq_of_le (le_of_lt_succ ltin)) with Hlt Heq, exact absurd (ih Hlt) Pnsm, rwr Heq at H, exact absurd (least_of_bound P H) Pnsm end @[hott] theorem ge_least_of_lt {i n : ℕ} (ltin : i < n) (Hi : P i) : i ≥ least P n := begin induction n with m ih, exact absurd ltin (not_lt_zero _), dsimp [least], cases decidable.em (P (least P m)) with Psm Pnsm, rwr [if_pos Psm], cases (lt_sum_eq_of_le (le_of_lt_succ ltin)) with Hlt Heq, apply ih Hlt, rwr Heq, apply least_le, rwr [if_neg Pnsm], cases (lt_sum_eq_of_le (le_of_lt_succ ltin)) with Hlt Heq, apply absurd (least_of_lt P Hlt Hi) Pnsm, rwr Heq at Hi, apply absurd (least_of_bound P Hi) Pnsm end @[hott] theorem least_lt {n i : ℕ} (ltin : i < n) (Hi : P i) : least P n < n := lt_of_le_of_lt (ge_least_of_lt P ltin Hi) ltin -- returns the largest i < n satisfying P, sum n if there is none. @[hott] def greatest : ℕ → ℕ | 0 := 0 | (succ n) := if' P n then n else greatest n @[hott] theorem greatest_of_lt {i n : ℕ} (ltin : i < n) (Hi : P i) : P (greatest P n) := begin induction n with m ih, {exact absurd ltin (not_lt_zero _)}, {cases (decidable.em (P m)) with Psm Pnsm, {dsimp [greatest], rwr [if_pos Psm]; exact Psm}, {dsimp [greatest], rwr [if_neg Pnsm], have neim : i ≠ m, from assume H : i = m, absurd (H ▸ Hi) Pnsm, have ltim : i < m, from lt_of_le_of_ne (le_of_lt_succ ltin) neim, apply ih ltim}} end @[hott] theorem le_greatest_of_lt {i n : ℕ} (ltin : i < n) (Hi : P i) : i ≤ greatest P n := begin induction n with m ih, {exact absurd ltin (not_lt_zero _)}, {cases (decidable.em (P m)) with Psm Pnsm, {dsimp [greatest], rwr [if_pos Psm], apply le_of_lt_succ ltin}, {dsimp [greatest], rwr [if_neg Pnsm], have neim : i ≠ m, from assume H : i = m, absurd (H ▸ Hi) Pnsm, have ltim : i < m, from lt_of_le_of_ne (le_of_lt_succ ltin) neim, apply ih ltim}} end end least_prod_greatest end nat end hott
5c6e595752db80f51a094caf130260287e88a0ae
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/08_Building_Theories_and_Proofs.org.25.lean
8c307da17594a96271e2c2ae411198534a246ce1
[]
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
497
lean
import standard import standard open nat section variables x y : ℕ definition double := x + x check double y check double (2 * x) theorem t1 : double x = 2 * x := calc double x = x + x : rfl ... = 1 * x + x : one_mul ... = 1 * x + 1 * x : one_mul ... = (1 + 1) * x : mul.right_distrib ... = 2 * x : rfl check t1 y check t1 (2 * x) theorem t2 : double (2 * x) = 4 * x := calc double (2 * x) = 2 * (2 * x) : t1 ... = 2 * 2 * x : mul.assoc ... = 4 * x : rfl end
105a232867ea691609eddc8c1e113859129c662e
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/simplifier1.hlean
6abc46c1d4c0cd62a3c5a7456bf7e577e70a9cf9
[ "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
798
hlean
open nat -- deeper congruence universe l constants (T : Type.{l}) (x1 x2 x3 x4 x5 x6 : T) (f : T → T → T) constants (f_comm : ∀ x y, f x y = f y x) (f_l : ∀ x y z, f (f x y) z = f x (f y z)) (f_r : ∀ x y z, f x (f y z) = f y (f x z)) namespace tst attribute f_comm [simp] attribute f_l [simp] attribute f_r [simp] end tst #simplify eq tst 0 (f (f x2 x4) (f x5 (f x3 (f x1 x6)))) open is_trunc constants g : Π (x y : nat), x ≠ y → Type₁ constants a b c : nat constants H₁ : a ≠ b constants H₂ : a = c namespace tst attribute H₂ [simp] end tst definition ne_is_prop [instance] (a b : nat) : is_prop (a ≠ b) := sorry -- TODO(Daniel): simplifier seems to have applied unnecessary step (see: (eq.nrec ... (eq.refl ..))) #simplify eq tst 0 (g a b H₁)
8a2903f587331df9fa0fb3f6ee322adb09b0f61b
f10d66a159ce037d07005bd6021cee6bbd6d5ff0
/poly_over_UFD.lean
cc799bcf9231d0e9ba4cff9352a11daaa0de436a
[]
no_license
johoelzl/mason-stother
0c78bca183eb729d7f0f93e87ce073bc8cd8808d
573ecfaada288176462c03c87b80ad05bdab4644
refs/heads/master
1,631,751,973,492
1,528,923,934,000
1,528,923,934,000
109,133,224
0
1
null
null
null
null
UTF-8
Lean
false
false
1,378
lean
import .Sup_fin data.finsupp order.lattice data.nat.cast .euclidean_domain unique_factorization_domain import .to_finsupp poly .to_multiset poly_over_integral_domain --import data.multiset universes u v w local notation a`~ᵤ`b := associated a b noncomputable theory open classical set function finsupp lattice local attribute [instance] prop_decidable local attribute [instance] finsupp.to_comm_semiring local attribute [instance] finsupp.to_semiring local infix ^ := monoid.pow namespace polynomial open associated variables {α : Type u} {a a' a₁ a₂ : α} --{n m : ℕ} --do we want n and m? instance {α : Type u} [unique_factorization_domain α]: unique_factorization_domain (polynomial α) := { fac := sorry, unique := sorry, .. polynomial.integral_domain} lemma degree_gcd_le_left [unique_factorization_domain α] {a b : polynomial α} (h : a ≠ 0): degree (gcd a b) ≤ degree a := begin have h1 : gcd a b ∣ a, from gcd_left, apply nat.le_trans (degree_dvd h1 h), exact nat.le_refl _, end lemma associated_neg [unique_factorization_domain α] (a : polynomial α) : (a ~ᵤ (-a)) := begin have h_u: is_unit (-1 : polynomial α), { have : ((-1 : polynomial α) * -1 = 1), { simp, }, exact is_unit_of_mul_eq_one_left this, }, rcases h_u with ⟨u, hu⟩, exact ⟨u, by {rw ←hu, simp}⟩, end end polynomial
a1b2e6f5d8282eb3cbaa066fe9545cc249aeb888
9dc8cecdf3c4634764a18254e94d43da07142918
/src/linear_algebra/lagrange.lean
72cbe39d45cb514135fc7123a70be8cb9d3c01c8
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
24,227
lean
/- Copyright (c) 2020 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Wrenna Robson -/ import algebra.big_operators.basic import linear_algebra.vandermonde import logic.lemmas import ring_theory.polynomial.basic /-! # Lagrange interpolation ## Main definitions * In everything that follows, `s : finset ι` is a finite set of indexes, with `v : ι → F` an indexing of the field over some type. We call the image of v on s the interpolation nodes, though strictly unique nodes are only defined when v is injective on s. * `lagrange.basis_divisor x y`, with `x y : F`. These are the normalised irreducible factors of the Lagrange basis polynomials. They evaluate to `1` at `x` and `0` at `y` when `x` and `y` are distinct. * `lagrange.basis v i` with `i : ι`: the Lagrange basis polynomial that evaluates to `1` at `v i` and `0` at `v j` for `i ≠ j`. * `lagrange.interpolate v r` where `r : ι → F` is a function from the fintype to the field: the Lagrange interpolant that evaluates to `r i` at `x i` for all `i : ι`. The `r i` are the _values_ associated with the _nodes_`x i`. * `lagrange.interpolate_at v f`, where `v : ι ↪ F` and `ι` is a fintype, and `f : F → F` is a function from the field to itself: this is the Lagrange interpolant that evaluates to `f (x i)` at `x i`, and so approximates the function `f`. This is just a special case of the general interpolation, where the values are given by a known function `f`. -/ open_locale polynomial big_operators section polynomial_determination namespace polynomial variables {R : Type*} [comm_ring R] [is_domain R] {f g : R[X]} section finset open function fintype variables (s : finset R) theorem eq_zero_of_degree_lt_of_eval_finset_eq_zero (degree_f_lt : f.degree < s.card) (eval_f : ∀ x ∈ s, f.eval x = 0) : f = 0 := begin rw ← mem_degree_lt at degree_f_lt, simp_rw eval_eq_sum_degree_lt_equiv degree_f_lt at eval_f, rw ← degree_lt_equiv_eq_zero_iff_eq_zero degree_f_lt, exact matrix.eq_zero_of_forall_index_sum_mul_pow_eq_zero (injective.comp (embedding.subtype _).inj' (equiv_fin_of_card_eq (card_coe _)).symm.injective) (λ _, eval_f _ (finset.coe_mem _)) end theorem eq_of_degree_sub_lt_of_eval_finset_eq (degree_fg_lt : (f - g).degree < s.card) (eval_fg : ∀ x ∈ s, f.eval x = g.eval x) : f = g := begin rw ← sub_eq_zero, refine eq_zero_of_degree_lt_of_eval_finset_eq_zero _ degree_fg_lt _, simp_rw [eval_sub, sub_eq_zero], exact eval_fg end theorem eq_of_degrees_lt_of_eval_finset_eq (degree_f_lt : f.degree < s.card) (degree_g_lt : g.degree < s.card) (eval_fg : ∀ x ∈ s, f.eval x = g.eval x) : f = g := begin rw ← mem_degree_lt at degree_f_lt degree_g_lt, refine eq_of_degree_sub_lt_of_eval_finset_eq _ _ eval_fg, rw ← mem_degree_lt, exact submodule.sub_mem _ degree_f_lt degree_g_lt end end finset section indexed open finset variables {ι : Type*} {v : ι → R} (s : finset ι) theorem eq_zero_of_degree_lt_of_eval_index_eq_zero (hvs : set.inj_on v s) (degree_f_lt : f.degree < s.card) (eval_f : ∀ i ∈ s, f.eval (v i) = 0) : f = 0 := begin classical, rw ← card_image_of_inj_on hvs at degree_f_lt, refine eq_zero_of_degree_lt_of_eval_finset_eq_zero _ degree_f_lt _, intros x hx, rcases mem_image.mp hx with ⟨_, hj, rfl⟩, exact eval_f _ hj end theorem eq_of_degree_sub_lt_of_eval_index_eq (hvs : set.inj_on v s) (degree_fg_lt : (f - g).degree < s.card) (eval_fg : ∀ i ∈ s, f.eval (v i) = g.eval (v i)) : f = g := begin rw ← sub_eq_zero, refine eq_zero_of_degree_lt_of_eval_index_eq_zero _ hvs degree_fg_lt _, simp_rw [eval_sub, sub_eq_zero], exact eval_fg end theorem eq_of_degrees_lt_of_eval_index_eq (hvs : set.inj_on v s) (degree_f_lt : f.degree < s.card) (degree_g_lt : g.degree < s.card) (eval_fg : ∀ i ∈ s, f.eval (v i) = g.eval (v i)) : f = g := begin refine eq_of_degree_sub_lt_of_eval_index_eq _ hvs _ eval_fg, rw ← mem_degree_lt at degree_f_lt degree_g_lt ⊢, exact submodule.sub_mem _ degree_f_lt degree_g_lt end end indexed end polynomial end polynomial_determination noncomputable theory namespace lagrange open polynomial variables {F : Type*} [field F] section basis_divisor variables {x y : F} /-- `basis_divisor x y` is the unique linear or constant polynomial such that when evaluated at `x` it gives `1` and `y` it gives `0` (where when `x = y` it is identically `0`). Such polynomials are the building blocks for the Lagrange interpolants. -/ def basis_divisor (x y : F) : F[X] := C ((x - y)⁻¹) * (X - C (y)) lemma basis_divisor_self : basis_divisor x x = 0 := by simp only [basis_divisor, sub_self, inv_zero, map_zero, zero_mul] lemma basis_divisor_inj (hxy : basis_divisor x y = 0) : x = y := begin simp_rw [basis_divisor, mul_eq_zero, X_sub_C_ne_zero, or_false, C_eq_zero, inv_eq_zero, sub_eq_zero] at hxy, exact hxy end @[simp] lemma basis_divisor_eq_zero_iff : basis_divisor x y = 0 ↔ x = y := ⟨basis_divisor_inj, λ H, H ▸ basis_divisor_self⟩ lemma basis_divisor_ne_zero_iff : basis_divisor x y ≠ 0 ↔ x ≠ y := by rw [ne.def, basis_divisor_eq_zero_iff] lemma degree_basis_divisor_of_ne (hxy : x ≠ y) : (basis_divisor x y).degree = 1 := begin rw [basis_divisor, degree_mul, degree_X_sub_C, degree_C, zero_add], exact inv_ne_zero (sub_ne_zero_of_ne hxy) end @[simp] lemma degree_basis_divisor_self : (basis_divisor x x).degree = ⊥ := by rw [basis_divisor_self, degree_zero] lemma nat_degree_basis_divisor_self : (basis_divisor x x).nat_degree = 0 := by rw [basis_divisor_self, nat_degree_zero] lemma nat_degree_basis_divisor_of_ne (hxy : x ≠ y) : (basis_divisor x y).nat_degree = 1 := nat_degree_eq_of_degree_eq_some (degree_basis_divisor_of_ne hxy) @[simp] lemma eval_basis_divisor_right : eval y (basis_divisor x y) = 0 := by simp only [basis_divisor, eval_mul, eval_C, eval_sub, eval_X, sub_self, mul_zero] lemma eval_basis_divisor_left_of_ne (hxy : x ≠ y) : eval x (basis_divisor x y) = 1 := begin simp only [basis_divisor, eval_mul, eval_C, eval_sub, eval_X], exact inv_mul_cancel (sub_ne_zero_of_ne hxy) end end basis_divisor section basis open finset variables {ι : Type*} [decidable_eq ι] {s : finset ι} {v : ι → F} {i j : ι} /-- Lagrange basis polynomials indexed by `s : finset ι`, defined at nodes `v i` for a map `v : ι → F`. For `i, j ∈ s`, `basis s v i` evaluates to 0 at `v j` for `i ≠ j`. When `v` is injective on `s`, `basis s v i` evaluates to 1 at `v i`. -/ protected def basis (s : finset ι) (v : ι → F) (i : ι) : F[X] := ∏ j in s.erase i, basis_divisor (v i) (v j) @[simp] theorem basis_empty : lagrange.basis ∅ v i = 1 := rfl @[simp] theorem basis_singleton (i : ι) : lagrange.basis {i} v i = 1 := by rw [lagrange.basis, erase_singleton, prod_empty] @[simp] theorem basis_pair_left (hij : i ≠ j) : lagrange.basis {i, j} v i = basis_divisor (v i) (v j) := by simp only [lagrange.basis, hij, erase_insert_eq_erase, erase_eq_of_not_mem, mem_singleton, not_false_iff, prod_singleton] @[simp] theorem basis_pair_right (hij : i ≠ j) : lagrange.basis {i, j} v j = basis_divisor (v j) (v i) := by { rw pair_comm, exact basis_pair_left hij.symm } lemma basis_ne_zero (hvs : set.inj_on v s) (hi : i ∈ s) : lagrange.basis s v i ≠ 0 := begin simp_rw [lagrange.basis, prod_ne_zero_iff, ne.def, mem_erase], rintros j ⟨hij, hj⟩, rw [basis_divisor_eq_zero_iff, hvs.eq_iff hi hj], exact hij.symm end @[simp] theorem eval_basis_self (hvs : set.inj_on v s) (hi : i ∈ s) : (lagrange.basis s v i).eval (v i) = 1 := begin rw [lagrange.basis, eval_prod], refine prod_eq_one (λ j H, _), rw eval_basis_divisor_left_of_ne, rcases mem_erase.mp H with ⟨hij, hj⟩, exact mt (hvs hi hj) hij.symm end @[simp] theorem eval_basis_of_ne (hij : i ≠ j) (hj : j ∈ s) : (lagrange.basis s v i).eval (v j) = 0 := begin simp_rw [lagrange.basis, eval_prod, prod_eq_zero_iff], exact ⟨j, ⟨mem_erase.mpr ⟨hij.symm, hj⟩, eval_basis_divisor_right⟩⟩ end @[simp] theorem nat_degree_basis (hvs : set.inj_on v s) (hi : i ∈ s) : (lagrange.basis s v i).nat_degree = s.card - 1 := begin have H : ∀ j, j ∈ s.erase i → basis_divisor (v i) (v j) ≠ 0, { simp_rw [ne.def, mem_erase, basis_divisor_eq_zero_iff], exact λ j ⟨hij₁, hj⟩ hij₂, hij₁ (hvs hj hi hij₂.symm) }, rw [← card_erase_of_mem hi, card_eq_sum_ones], convert nat_degree_prod _ _ H using 1, refine sum_congr rfl (λ j hj, (nat_degree_basis_divisor_of_ne _).symm), rw [ne.def, ← basis_divisor_eq_zero_iff], exact H _ hj end theorem degree_basis (hvs : set.inj_on v s) (hi : i ∈ s) : (lagrange.basis s v i).degree = ↑(s.card - 1) := by rw [degree_eq_nat_degree (basis_ne_zero hvs hi), nat_degree_basis hvs hi] lemma sum_basis (hvs : set.inj_on v s) (hs : s.nonempty) : ∑ j in s, (lagrange.basis s v j) = 1 := begin refine eq_of_degrees_lt_of_eval_index_eq s hvs (lt_of_le_of_lt (degree_sum_le _ _) _) _ _, { rw finset.sup_lt_iff (with_bot.bot_lt_coe s.card), intros i hi, rw [degree_basis hvs hi, with_bot.coe_lt_coe], exact nat.pred_lt (card_ne_zero_of_mem hi) }, { rw [degree_one, ← with_bot.coe_zero, with_bot.coe_lt_coe], exact nonempty.card_pos hs }, { intros i hi, rw [eval_finset_sum, eval_one, ← add_sum_erase _ _ hi, eval_basis_self hvs hi, add_right_eq_self], refine sum_eq_zero (λ j hj, _), rcases mem_erase.mp hj with ⟨hij, hj⟩, rw eval_basis_of_ne hij hi } end lemma basis_divisor_add_symm {x y : F} (hxy : x ≠ y) : basis_divisor x y + basis_divisor y x = 1 := begin classical, rw [←sum_basis (set.inj_on_of_injective function.injective_id _) ⟨x, mem_insert_self _ {y}⟩, sum_insert (not_mem_singleton.mpr hxy), sum_singleton, basis_pair_left hxy, basis_pair_right hxy, id, id] end end basis section interpolate open finset variables {ι : Type*} [decidable_eq ι] {s t : finset ι} {i j : ι} {v : ι → F} (r r' : ι → F) /-- Lagrange interpolation: given a finset `s : finset ι`, a nodal map `v : ι → F` injective on `s` and a value function `r : ι → F`, `interpolate s v r` is the unique polynomial of degree `< s.card` that takes value `r i` on `v i` for all `i` in `s`. -/ @[simps] def interpolate (s : finset ι) (v : ι → F) : (ι → F) →ₗ[F] F[X] := { to_fun := λ r, ∑ i in s, C (r i) * (lagrange.basis s v i), map_add' := λ f g, by simp_rw [← finset.sum_add_distrib, ← add_mul, ← C_add, pi.add_apply], map_smul' := λ c f, by simp_rw [finset.smul_sum, C_mul', smul_smul, pi.smul_apply, ring_hom.id_apply, smul_eq_mul] } @[simp] theorem interpolate_empty : interpolate ∅ v r = 0 := by rw [interpolate_apply, sum_empty] @[simp] theorem interpolate_singleton : interpolate {i} v r = C (r i) := by rw [interpolate_apply, sum_singleton, basis_singleton, mul_one] theorem interpolate_one (hvs : set.inj_on v s) (hs : s.nonempty) : interpolate s v 1 = 1 := by { simp_rw [interpolate_apply, pi.one_apply, map_one, one_mul], exact sum_basis hvs hs } theorem eval_interpolate_at_node (hvs : set.inj_on v s) (hi : i ∈ s) : eval (v i) (interpolate s v r) = r i := begin rw [interpolate_apply, eval_finset_sum, ← add_sum_erase _ _ hi], simp_rw [eval_mul, eval_C, eval_basis_self hvs hi, mul_one, add_right_eq_self], refine sum_eq_zero (λ j H, _), rw [eval_basis_of_ne (mem_erase.mp H).1 hi, mul_zero] end theorem degree_interpolate_le (hvs : set.inj_on v s) : (interpolate s v r).degree ≤ ↑(s.card - 1) := begin refine (degree_sum_le _ _).trans _, rw finset.sup_le_iff, intros i hi, rw [degree_mul, degree_basis hvs hi], by_cases hr : r i = 0, { simpa only [hr, map_zero, degree_zero, with_bot.bot_add] using bot_le }, { rw [degree_C hr, zero_add, with_bot.coe_le_coe] } end theorem degree_interpolate_lt (hvs : set.inj_on v s) : (interpolate s v r).degree < s.card := begin rcases eq_empty_or_nonempty s with rfl | h, { rw [interpolate_empty, degree_zero, card_empty], exact with_bot.bot_lt_coe _ }, { refine lt_of_le_of_lt (degree_interpolate_le _ hvs) _, rw with_bot.coe_lt_coe, exact nat.sub_lt (nonempty.card_pos h) zero_lt_one } end theorem degree_interpolate_erase_lt (hvs : set.inj_on v s) (hi : i ∈ s) : (interpolate (s.erase i) v r).degree < ↑(s.card - 1) := begin rw ← finset.card_erase_of_mem hi, exact degree_interpolate_lt _ (set.inj_on.mono (coe_subset.mpr (erase_subset _ _)) hvs), end theorem values_eq_on_of_interpolate_eq (hvs : set.inj_on v s) (hrr' : interpolate s v r = interpolate s v r') : ∀ i ∈ s, r i = r' i := λ _ hi, by rw [← eval_interpolate_at_node r hvs hi, hrr', eval_interpolate_at_node r' hvs hi] theorem interpolate_eq_of_values_eq_on (hrr' : ∀ i ∈ s, r i = r' i) : interpolate s v r = interpolate s v r' := sum_congr rfl (λ i hi, (by rw hrr' _ hi)) theorem interpolate_eq_iff_values_eq_on (hvs : set.inj_on v s) : interpolate s v r = interpolate s v r' ↔ ∀ i ∈ s, r i = r' i := ⟨values_eq_on_of_interpolate_eq _ _ hvs, interpolate_eq_of_values_eq_on _ _⟩ theorem eq_interpolate {f : F[X]} (hvs : set.inj_on v s) (degree_f_lt : f.degree < s.card) : f = interpolate s v (λ i, f.eval (v i)) := eq_of_degrees_lt_of_eval_index_eq _ hvs degree_f_lt (degree_interpolate_lt _ hvs) $ λ i hi, (eval_interpolate_at_node _ hvs hi).symm theorem eq_interpolate_of_eval_eq {f : F[X]} (hvs : set.inj_on v s) (degree_f_lt : f.degree < s.card) (eval_f : ∀ i ∈ s, f.eval (v i) = r i) : f = interpolate s v r := by { rw eq_interpolate hvs degree_f_lt, exact interpolate_eq_of_values_eq_on _ _ eval_f } /-- This is the characteristic property of the interpolation: the interpolation is the unique polynomial of `degree < fintype.card ι` which takes the value of the `r i` on the `v i`. -/ theorem eq_interpolate_iff {f : F[X]} (hvs : set.inj_on v s) : (f.degree < s.card ∧ ∀ i ∈ s, eval (v i) f = r i) ↔ f = interpolate s v r := begin split; intro h, { exact eq_interpolate_of_eval_eq _ hvs h.1 h.2 }, { rw h, exact ⟨degree_interpolate_lt _ hvs, λ _ hi, eval_interpolate_at_node _ hvs hi⟩ } end /-- Lagrange interpolation induces isomorphism between functions from `s` and polynomials of degree less than `fintype.card ι`.-/ def fun_equiv_degree_lt (hvs : set.inj_on v s) : degree_lt F s.card ≃ₗ[F] (s → F) := { to_fun := λ f i, f.1.eval (v i), map_add' := λ f g, funext $ λ v, eval_add, map_smul' := λ c f, funext $ by simp, inv_fun := λ r, ⟨interpolate s v (λ x, if hx : x ∈ s then r ⟨x, hx⟩ else 0), mem_degree_lt.2 $ degree_interpolate_lt _ hvs⟩, left_inv := begin rintros ⟨f, hf⟩, simp only [subtype.mk_eq_mk, subtype.coe_mk, dite_eq_ite], rw mem_degree_lt at hf, nth_rewrite_rhs 0 eq_interpolate hvs hf, exact interpolate_eq_of_values_eq_on _ _ (λ _ hi, if_pos hi) end, right_inv := begin intro f, ext ⟨i, hi⟩, simp only [subtype.coe_mk, eval_interpolate_at_node _ hvs hi], exact dif_pos hi, end } theorem interpolate_eq_sum_interpolate_insert_sdiff (hvt : set.inj_on v t) (hs : s.nonempty) (hst : s ⊆ t) : interpolate t v r = ∑ i in s, (interpolate (insert i (t \ s)) v r) * lagrange.basis s v i := begin symmetry, refine eq_interpolate_of_eval_eq _ hvt (lt_of_le_of_lt (degree_sum_le _ _) _) (λ i hi, _), { simp_rw [(finset.sup_lt_iff (with_bot.bot_lt_coe t.card)), degree_mul], intros i hi, have hs : 1 ≤ s.card := nonempty.card_pos ⟨_, hi⟩, have hst' : s.card ≤ t.card := card_le_of_subset hst, have H : t.card = (1 + (t.card - s.card)) + (s.card - 1), { rw [add_assoc, tsub_add_tsub_cancel hst' hs, ← add_tsub_assoc_of_le (hs.trans hst'), nat.succ_add_sub_one, zero_add] }, rw [degree_basis (set.inj_on.mono hst hvt) hi, H, with_bot.coe_add, with_bot.add_lt_add_iff_right (@with_bot.coe_ne_bot _ (s.card - 1))], convert degree_interpolate_lt _ (hvt.mono (coe_subset.mpr (insert_subset.mpr ⟨hst hi, sdiff_subset _ _⟩))), rw [card_insert_of_not_mem (not_mem_sdiff_of_mem_right hi), card_sdiff hst, add_comm] }, { simp_rw [eval_finset_sum, eval_mul], by_cases hi' : i ∈ s, { rw [← add_sum_erase _ _ hi', eval_basis_self (hvt.mono hst) hi', eval_interpolate_at_node _ (hvt.mono (coe_subset.mpr (insert_subset.mpr ⟨hi, sdiff_subset _ _⟩))) (mem_insert_self _ _), mul_one, add_right_eq_self], refine sum_eq_zero (λ j hj, _), rcases mem_erase.mp hj with ⟨hij, hj⟩, rw [eval_basis_of_ne hij hi', mul_zero] }, { have H : ∑ j in s, eval (v i) (lagrange.basis s v j) = 1, { rw [← eval_finset_sum, sum_basis (hvt.mono hst) hs, eval_one] }, rw [← mul_one (r i), ← H, mul_sum], refine sum_congr rfl (λ j hj, _), congr, exact eval_interpolate_at_node _ (hvt.mono (insert_subset.mpr ⟨hst hj, sdiff_subset _ _⟩)) (mem_insert.mpr (or.inr (mem_sdiff.mpr ⟨hi, hi'⟩))) } } end theorem interpolate_eq_add_interpolate_erase (hvs : set.inj_on v s) (hi : i ∈ s) (hj : j ∈ s) (hij : i ≠ j) : interpolate s v r = interpolate (s.erase j) v r * basis_divisor (v i) (v j) + interpolate (s.erase i) v r * basis_divisor (v j) (v i) := begin rw [interpolate_eq_sum_interpolate_insert_sdiff _ hvs ⟨i, (mem_insert_self i {j})⟩ _, sum_insert (not_mem_singleton.mpr hij), sum_singleton, basis_pair_left hij, basis_pair_right hij, sdiff_insert_insert_of_mem_of_not_mem hi (not_mem_singleton.mpr hij), sdiff_singleton_eq_erase, pair_comm, sdiff_insert_insert_of_mem_of_not_mem hj (not_mem_singleton.mpr hij.symm), sdiff_singleton_eq_erase], { exact insert_subset.mpr ⟨hi, singleton_subset_iff.mpr hj⟩ }, end end interpolate section nodal open finset polynomial variables {ι : Type*} {s : finset ι} {v : ι → F} {i : ι} (r : ι → F) {x : F} /-- `nodal s v` is the unique monic polynomial whose roots are the nodes defined by `v` and `s`. That is, the roots of `nodal s v` are exactly the image of `v` on `s`, with appropriate multiplicity. We can use `nodal` to define the barycentric forms of the evaluated interpolant. -/ def nodal (s : finset ι) (v : ι → F) : F[X] := ∏ i in s, (X - C (v i)) lemma nodal_eq (s : finset ι) (v : ι → F) : nodal s v = ∏ i in s, (X - C (v i)) := rfl @[simp] lemma nodal_empty : nodal ∅ v = 1 := rfl lemma degree_nodal : (nodal s v).degree = s.card := by simp_rw [nodal, degree_prod, degree_X_sub_C, sum_const, nat.smul_one_eq_coe] lemma eval_nodal {x : F} : (nodal s v).eval x = ∏ i in s, (x - v i) := by simp_rw [nodal, eval_prod, eval_sub, eval_X, eval_C] lemma eval_nodal_at_node (hi : i ∈ s) : eval (v i) (nodal s v) = 0 := by { rw [eval_nodal, prod_eq_zero_iff], exact ⟨i, hi, sub_eq_zero_of_eq rfl⟩ } lemma eval_nodal_not_at_node (hx : ∀ i ∈ s, x ≠ v i) : eval x (nodal s v) ≠ 0 := by { simp_rw [nodal, eval_prod, prod_ne_zero_iff, eval_sub, eval_X, eval_C, sub_ne_zero], exact hx } lemma nodal_eq_mul_nodal_erase [decidable_eq ι] (hi : i ∈ s) : nodal s v = (X - C (v i)) * nodal (s.erase i) v := by simp_rw [nodal, mul_prod_erase _ _ hi] lemma X_sub_C_dvd_nodal (v : ι → F) (hi : i ∈ s) : (X - C (v i)) ∣ nodal s v := ⟨_, by { classical, exact nodal_eq_mul_nodal_erase hi }⟩ variable [decidable_eq ι] lemma nodal_erase_eq_nodal_div (hi : i ∈ s) : nodal (s.erase i) v = nodal s v / (X - C (v i)) := begin rw [nodal_eq_mul_nodal_erase hi, euclidean_domain.mul_div_cancel_left], exact X_sub_C_ne_zero _ end lemma nodal_insert_eq_nodal (hi : i ∉ s) : nodal (insert i s) v = (X - C (v i)) * (nodal s v) := by simp_rw [nodal, prod_insert hi] lemma derivative_nodal : (nodal s v).derivative = ∑ i in s, nodal (s.erase i) v := begin refine finset.induction_on s _ (λ _ _ hit IH, _), { rw [nodal_empty, derivative_one, sum_empty] }, { rw [nodal_insert_eq_nodal hit, derivative_mul, IH, derivative_sub, derivative_X, derivative_C, sub_zero, one_mul, sum_insert hit, mul_sum, erase_insert hit, add_right_inj], refine sum_congr rfl (λ j hjt, _), rw [nodal_erase_eq_nodal_div (mem_insert_of_mem hjt), nodal_insert_eq_nodal hit, euclidean_domain.mul_div_assoc _ (X_sub_C_dvd_nodal v hjt), nodal_erase_eq_nodal_div hjt] } end lemma eval_nodal_derivative_eval_node_eq (hi : i ∈ s) : eval (v i) (nodal s v).derivative = eval (v i) (nodal (s.erase i) v) := begin rw [derivative_nodal, eval_finset_sum, ← add_sum_erase _ _ hi, add_right_eq_self], refine sum_eq_zero (λ j hj, _), simp_rw [nodal, eval_prod, eval_sub, eval_X, eval_C, prod_eq_zero_iff, mem_erase], exact ⟨i, ⟨(mem_erase.mp hj).1.symm, hi⟩, sub_eq_zero_of_eq rfl⟩ end /-- This defines the nodal weight for a given set of node indexes and node mapping function `v`. -/ def nodal_weight (s : finset ι) (v : ι → F) (i : ι) := ∏ j in s.erase i, (v i - v j)⁻¹ lemma nodal_weight_eq_eval_nodal_erase_inv : nodal_weight s v i = (eval (v i) (nodal (s.erase i) v))⁻¹ := by rw [eval_nodal, nodal_weight, prod_inv_distrib] lemma nodal_weight_eq_eval_nodal_derative (hi : i ∈ s) : nodal_weight s v i = (eval (v i) (nodal s v).derivative)⁻¹ := by rw [eval_nodal_derivative_eval_node_eq hi, nodal_weight_eq_eval_nodal_erase_inv] lemma nodal_weight_ne_zero (hvs : set.inj_on v s) (hi : i ∈ s) : nodal_weight s v i ≠ 0 := begin rw [nodal_weight, prod_ne_zero_iff], intros j hj, rcases mem_erase.mp hj with ⟨hij, hj⟩, refine inv_ne_zero (sub_ne_zero_of_ne (mt (hvs.eq_iff hi hj).mp hij.symm)), end lemma basis_eq_prod_sub_inv_mul_nodal_div (hi : i ∈ s) : lagrange.basis s v i = C (nodal_weight s v i) * ( nodal s v / (X - C (v i)) ) := by simp_rw [lagrange.basis, basis_divisor, nodal_weight, prod_mul_distrib, map_prod, ← nodal_erase_eq_nodal_div hi, nodal] lemma eval_basis_not_at_node (hi : i ∈ s) (hxi : x ≠ v i) : eval x (lagrange.basis s v i) = (eval x (nodal s v)) * (nodal_weight s v i * (x - v i)⁻¹) := by rw [mul_comm, basis_eq_prod_sub_inv_mul_nodal_div hi, eval_mul, eval_C, ← nodal_erase_eq_nodal_div hi, eval_nodal, eval_nodal, mul_assoc, ← mul_prod_erase _ _ hi, ← mul_assoc (x - v i)⁻¹, inv_mul_cancel (sub_ne_zero_of_ne hxi), one_mul] lemma interpolate_eq_nodal_weight_mul_nodal_div_X_sub_C : interpolate s v r = ∑ i in s, C (nodal_weight s v i) * (nodal s v / (X - C (v i))) * C (r i) := sum_congr rfl (λ j hj, by rw [mul_comm, basis_eq_prod_sub_inv_mul_nodal_div hj]) /-- This is the first barycentric form of the Lagrange interpolant. -/ lemma eval_interpolate_not_at_node (hx : ∀ i ∈ s, x ≠ v i) : eval x (interpolate s v r) = eval x (nodal s v) * ∑ i in s, nodal_weight s v i * (x - v i)⁻¹ * r i := begin simp_rw [interpolate_apply, mul_sum, eval_finset_sum, eval_mul, eval_C], refine sum_congr rfl (λ i hi, _), rw [← mul_assoc, mul_comm, eval_basis_not_at_node hi (hx _ hi)] end lemma sum_nodal_weight_mul_inv_sub_ne_zero (hvs : set.inj_on v s) (hx : ∀ i ∈ s, x ≠ v i) (hs : s.nonempty) : ∑ i in s, nodal_weight s v i * (x - v i)⁻¹ ≠ 0 := @right_ne_zero_of_mul_eq_one _ _ _ (eval x (nodal s v)) _ $ by simpa only [pi.one_apply, interpolate_one hvs hs, eval_one, mul_one] using (eval_interpolate_not_at_node 1 hx).symm /-- This is the second barycentric form of the Lagrange interpolant. -/ lemma eval_interpolate_not_at_node' (hvs : set.inj_on v s) (hs : s.nonempty) (hx : ∀ i ∈ s, x ≠ v i) : eval x (interpolate s v r) = (∑ i in s, nodal_weight s v i * (x - v i)⁻¹ * r i) / ∑ i in s, nodal_weight s v i * (x - v i)⁻¹ := begin rw [← div_one (eval x (interpolate s v r)), ← @eval_one _ _ x, ← interpolate_one hvs hs, eval_interpolate_not_at_node r hx, eval_interpolate_not_at_node 1 hx], simp only [mul_div_mul_left _ _ (eval_nodal_not_at_node hx), pi.one_apply, mul_one] end end nodal end lagrange
5aa6f13dcd4d026e056696036a621b6f9d3cc1ba
8d65764a9e5f0923a67fc435eb1a5a1d02fd80e3
/src/topology/algebra/floor_ring.lean
6a65354b5c4798456d9bb7a80562ccdaba0230ee
[ "Apache-2.0" ]
permissive
troyjlee/mathlib
e18d4b8026e32062ab9e89bc3b003a5d1cfec3f5
45e7eb8447555247246e3fe91c87066506c14875
refs/heads/master
1,689,248,035,046
1,629,470,528,000
1,629,470,528,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
9,290
lean
/- Copyright (c) 2020 Anatole Dedecker. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anatole Dedecker Basic topological facts (limits and continuity) about `floor`, `ceil` and `fract` in a `floor_ring`. -/ import topology.algebra.ordered.basic import algebra.floor open set function filter open_locale topological_space variables {α : Type*} [linear_ordered_ring α] [floor_ring α] lemma tendsto_floor_at_top : tendsto (floor : α → ℤ) at_top at_top := begin refine monotone.tendsto_at_top_at_top (λ a b hab, floor_mono hab) (λ b, _), use (b : α) + ((1 : ℤ) : α), rw [floor_add_int, floor_coe], exact (lt_add_one _).le end lemma tendsto_floor_at_bot : tendsto (floor : α → ℤ) at_bot at_bot := begin refine monotone.tendsto_at_bot_at_bot (λ a b hab, floor_mono hab) (λ b, ⟨b, _⟩), rw floor_coe end lemma tendsto_ceil_at_top : tendsto (ceil : α → ℤ) at_top at_top := tendsto_neg_at_bot_at_top.comp (tendsto_floor_at_bot.comp tendsto_neg_at_top_at_bot) lemma tendsto_ceil_at_bot : tendsto (ceil : α → ℤ) at_bot at_bot := tendsto_neg_at_top_at_bot.comp (tendsto_floor_at_top.comp tendsto_neg_at_bot_at_top) variables [topological_space α] lemma continuous_on_floor (n : ℤ) : continuous_on (λ x, floor x : α → α) (Ico n (n+1) : set α) := (continuous_on_congr $ floor_eq_on_Ico' n).mpr continuous_on_const lemma continuous_on_ceil (n : ℤ) : continuous_on (λ x, ceil x : α → α) (Ioc (n-1) n : set α) := (continuous_on_congr $ ceil_eq_on_Ioc' n).mpr continuous_on_const lemma tendsto_floor_right' [order_closed_topology α] (n : ℤ) : tendsto (λ x, floor x : α → α) (𝓝[Ici n] n) (𝓝 n) := begin rw ← nhds_within_Ico_eq_nhds_within_Ici (lt_add_one (n : α)), simpa only [floor_coe] using (continuous_on_floor n _ (left_mem_Ico.mpr $ lt_add_one (_ : α))).tendsto end lemma tendsto_ceil_left' [order_closed_topology α] (n : ℤ) : tendsto (λ x, ceil x : α → α) (𝓝[Iic n] n) (𝓝 n) := begin rw ← nhds_within_Ioc_eq_nhds_within_Iic (sub_one_lt (n : α)), simpa only [ceil_coe] using (continuous_on_ceil _ _ (right_mem_Ioc.mpr $ sub_one_lt (_ : α))).tendsto end lemma tendsto_floor_right [order_closed_topology α] (n : ℤ) : tendsto (λ x, floor x : α → α) (𝓝[Ici n] n) (𝓝[Ici n] n) := tendsto_nhds_within_of_tendsto_nhds_of_eventually_within _ (tendsto_floor_right' _) begin refine (eventually_nhds_with_of_forall $ λ x (hx : (n : α) ≤ x), _), change _ ≤ _, norm_cast, convert ← floor_mono hx, rw floor_eq_iff, exact ⟨le_refl _, lt_add_one _⟩ end lemma tendsto_ceil_left [order_closed_topology α] (n : ℤ) : tendsto (λ x, ceil x : α → α) (𝓝[Iic n] n) (𝓝[Iic n] n) := tendsto_nhds_within_of_tendsto_nhds_of_eventually_within _ (tendsto_ceil_left' _) begin refine (eventually_nhds_with_of_forall $ λ x (hx : x ≤ (n : α)), _), change _ ≤ _, norm_cast, convert ← ceil_mono hx, rw ceil_eq_iff, exact ⟨sub_one_lt _, le_refl _⟩ end lemma tendsto_floor_left [order_closed_topology α] (n : ℤ) : tendsto (λ x, floor x : α → α) (𝓝[Iio n] n) (𝓝[Iic (n-1)] (n-1)) := begin rw ← nhds_within_Ico_eq_nhds_within_Iio (sub_one_lt (n : α)), convert (tendsto_nhds_within_congr $ (λ x hx, (floor_eq_on_Ico' (n-1) x hx).symm)) (tendsto_nhds_within_of_tendsto_nhds_of_eventually_within _ tendsto_const_nhds (eventually_of_forall (λ _, mem_Iic.mpr $ le_refl _))); norm_cast <|> apply_instance, ring end lemma tendsto_ceil_right [order_closed_topology α] (n : ℤ) : tendsto (λ x, ceil x : α → α) (𝓝[Ioi n] n) (𝓝[Ici (n+1)] (n+1)) := begin rw ← nhds_within_Ioc_eq_nhds_within_Ioi (lt_add_one (n : α)), convert (tendsto_nhds_within_congr $ (λ x hx, (ceil_eq_on_Ioc' (n+1) x hx).symm)) (tendsto_nhds_within_of_tendsto_nhds_of_eventually_within _ tendsto_const_nhds (eventually_of_forall (λ _, mem_Ici.mpr $ le_refl _))); norm_cast <|> apply_instance, ring end lemma tendsto_floor_left' [order_closed_topology α] (n : ℤ) : tendsto (λ x, floor x : α → α) (𝓝[Iio n] n) (𝓝 (n-1)) := begin rw ← nhds_within_univ, exact tendsto_nhds_within_mono_right (subset_univ _) (tendsto_floor_left n), end lemma tendsto_ceil_right' [order_closed_topology α] (n : ℤ) : tendsto (λ x, ceil x : α → α) (𝓝[Ioi n] n) (𝓝 (n+1)) := begin rw ← nhds_within_univ, exact tendsto_nhds_within_mono_right (subset_univ _) (tendsto_ceil_right n), end lemma continuous_on_fract [topological_add_group α] (n : ℤ) : continuous_on (fract : α → α) (Ico n (n+1) : set α) := continuous_on_id.sub (continuous_on_floor n) lemma tendsto_fract_left' [order_closed_topology α] [topological_add_group α] (n : ℤ) : tendsto (fract : α → α) (𝓝[Iio n] n) (𝓝 1) := begin convert (tendsto_nhds_within_of_tendsto_nhds tendsto_id).sub (tendsto_floor_left' n); [{norm_cast, ring}, apply_instance, apply_instance] end lemma tendsto_fract_left [order_closed_topology α] [topological_add_group α] (n : ℤ) : tendsto (fract : α → α) (𝓝[Iio n] n) (𝓝[Iio 1] 1) := tendsto_nhds_within_of_tendsto_nhds_of_eventually_within _ (tendsto_fract_left' _) (eventually_of_forall fract_lt_one) lemma tendsto_fract_right' [order_closed_topology α] [topological_add_group α] (n : ℤ) : tendsto (fract : α → α) (𝓝[Ici n] n) (𝓝 0) := begin convert (tendsto_nhds_within_of_tendsto_nhds tendsto_id).sub (tendsto_floor_right' n); [exact (sub_self _).symm, apply_instance, apply_instance] end lemma tendsto_fract_right [order_closed_topology α] [topological_add_group α] (n : ℤ) : tendsto (fract : α → α) (𝓝[Ici n] n) (𝓝[Ici 0] 0) := tendsto_nhds_within_of_tendsto_nhds_of_eventually_within _ (tendsto_fract_right' _) (eventually_of_forall fract_nonneg) local notation `I` := (Icc 0 1 : set α) lemma continuous_on.comp_fract' {β γ : Type*} [order_topology α] [topological_add_group α] [topological_space β] [topological_space γ] {f : β → α → γ} (h : continuous_on (uncurry f) $ (univ : set β).prod I) (hf : ∀ s, f s 0 = f s 1) : continuous (λ st : β × α, f st.1 $ fract st.2) := begin change continuous ((uncurry f) ∘ (prod.map id (fract))), rw continuous_iff_continuous_at, rintro ⟨s, t⟩, by_cases ht : t = floor t, { rw ht, rw ← continuous_within_at_univ, have : (univ : set (β × α)) ⊆ (set.prod univ (Iio $ floor t)) ∪ (set.prod univ (Ici $ floor t)), { rintros p -, rw ← prod_union, exact ⟨true.intro, lt_or_le _ _⟩ }, refine continuous_within_at.mono _ this, refine continuous_within_at.union _ _, { simp only [continuous_within_at, fract_coe, nhds_within_prod_eq, nhds_within_univ, id.def, comp_app, prod.map_mk], have : (uncurry f) (s, 0) = (uncurry f) (s, (1 : α)), by simp [uncurry, hf], rw this, refine (h _ ⟨true.intro, by exact_mod_cast right_mem_Icc.mpr zero_le_one⟩).tendsto.comp _, rw [nhds_within_prod_eq, nhds_within_univ], rw nhds_within_Icc_eq_nhds_within_Iic (@zero_lt_one α _ _), exact tendsto_id.prod_map (tendsto_nhds_within_mono_right Iio_subset_Iic_self $ tendsto_fract_left _) }, { simp only [continuous_within_at, fract_coe, nhds_within_prod_eq, nhds_within_univ, id.def, comp_app, prod.map_mk], refine (h _ ⟨true.intro, by exact_mod_cast left_mem_Icc.mpr zero_le_one⟩).tendsto.comp _, rw [nhds_within_prod_eq, nhds_within_univ, nhds_within_Icc_eq_nhds_within_Ici (@zero_lt_one α _ _)], exact tendsto_id.prod_map (tendsto_fract_right _) } }, { have : t ∈ Ioo (floor t : α) ((floor t : α) + 1), from ⟨lt_of_le_of_ne (floor_le t) (ne.symm ht), lt_floor_add_one _⟩, apply (h ((prod.map _ fract) _) ⟨trivial, ⟨fract_nonneg _, (fract_lt_one _).le⟩⟩).tendsto.comp, simp only [nhds_prod_eq, nhds_within_prod_eq, nhds_within_univ, id.def, prod.map_mk], exact continuous_at_id.tendsto.prod_map (tendsto_nhds_within_of_tendsto_nhds_of_eventually_within _ (((continuous_on_fract _ _ (Ioo_subset_Ico_self this)).mono Ioo_subset_Ico_self).continuous_at (Ioo_mem_nhds this.1 this.2)) (eventually_of_forall (λ x, ⟨fract_nonneg _, (fract_lt_one _).le⟩)) ) } end lemma continuous_on.comp_fract {β : Type*} [order_topology α] [topological_add_group α] [topological_space β] {f : α → β} (h : continuous_on f I) (hf : f 0 = f 1) : continuous (f ∘ fract) := begin let f' : unit → α → β := λ x y, f y, have : continuous_on (uncurry f') ((univ : set unit).prod I), { rintros ⟨s, t⟩ ⟨-, ht : t ∈ I⟩, simp only [continuous_within_at, uncurry, nhds_within_prod_eq, nhds_within_univ, f'], rw tendsto_prod_iff, intros W hW, specialize h t ht hW, rw mem_map_iff_exists_image at h, rcases h with ⟨V, hV, hVW⟩, rw image_subset_iff at hVW, use [univ, univ_mem, V, hV], intros x y hx hy, exact hVW hy }, have key : continuous (λ s, ⟨unit.star, s⟩ : α → unit × α) := by continuity, exact (this.comp_fract' (λ s, hf)).comp key end
158644acdbf47802cde22e3e6b0232aa9f471efc
a162e54d0534f0863de20e911278e6c41ba96e28
/src/imo2005_q3.lean
95aa81d7e187a420dd08850a0bd15809e8e289a3
[ "Apache-2.0" ]
permissive
manuelcandales/imo-lean
0ef79d470b58064d16a94adfb83711ae3265a19a
fa54938100fc84c98fe04e1d19e20a424dd006e7
refs/heads/master
1,680,228,525,536
1,617,602,898,000
1,617,602,898,000
353,518,197
0
0
null
null
null
null
UTF-8
Lean
false
false
3,460
lean
/- Copyright (c) 2021 Manuel Candales. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Manuel Candales -/ import data.real.basic /-! # IMO 2005 Q3 Let x, y and z be positive real numbers such that xyz ≥ 1. Prove that: (x^5 - x^2)/(x^5 + y^2 + z^2) + (y^5 - y^2)/(y^5 + z^2 + x^2) + (z^5 - z^2)/(z^5 + x^2 + y^2) ≥ 0 # Solution The solution by Iurie Boreico from Moldova is presented, which won a special prize during the exam. The key insignt is that (x^5-x^2)/(x^5+y^2+z^2) ≥ (x^2-y*z)/(x^2+y^2+z^2), which is proven by factoring (x^5-x^2)/(x^5+y^2+z^2) - (x^5-x^2)/(x^3*(x^2+y^2+z^2)) into a non-negative expression and then making use of xyz ≥ 1 to show (x^5-x^2)/(x^3*(x^2+y^2+z^2)) ≥ (x^2-y*z)/(x^2+y^2+z^2). -/ lemma key_insight (x y z : ℝ) (hx : x > 0) (hy : y > 0) (hz : z > 0) (h : x*y*z ≥ 1) : (x^5-x^2)/(x^5+y^2+z^2) ≥ (x^2-y*z)/(x^2+y^2+z^2) := begin have h₁ : x^5+y^2+z^2 > 0, linarith [pow_pos hx 5, pow_pos hy 2, pow_pos hz 2], have h₂ : x^3 > 0, exact pow_pos hx 3, have h₃ : x^2+y^2+z^2 > 0, linarith [pow_pos hx 2, pow_pos hy 2, pow_pos hz 2], have h₄ : x^3*(x^2+y^2+z^2) > 0, exact mul_pos h₂ h₃, have key : (x^5-x^2)/(x^5+y^2+z^2) - (x^5-x^2)/(x^3*(x^2+y^2+z^2)) = ((x^3 - 1)^2*x^2*(y^2 + z^2))/((x^5+y^2+z^2)*(x^3*(x^2+y^2+z^2))), calc (x^5-x^2)/(x^5+y^2+z^2) - (x^5-x^2)/(x^3*(x^2+y^2+z^2)) = ((x^5-x^2)*(x^3*(x^2+y^2+z^2))-(x^5+y^2+z^2)*(x^5-x^2))/((x^5+y^2+z^2)*(x^3*(x^2+y^2+z^2))): by exact div_sub_div _ _ (ne_of_gt h₁) (ne_of_gt h₄) -- a/b - c/d = (a*d-b*c)/(b*d) ... = ((x^3 - 1)^2*x^2*(y^2 + z^2))/((x^5+y^2+z^2)*(x^3*(x^2+y^2+z^2))) : by ring, have h₅ : ((x^3 - 1)^2*x^2*(y^2 + z^2))/((x^5+y^2+z^2)*(x^3*(x^2+y^2+z^2))) ≥ 0, { refine div_nonneg _ _, refine mul_nonneg (mul_nonneg (pow_two_nonneg _) (pow_two_nonneg _)) _, exact add_nonneg (pow_two_nonneg _) (pow_two_nonneg _), exact le_of_lt (mul_pos h₁ h₄) }, calc (x^5-x^2)/(x^5+y^2+z^2) ≥ (x^5-x^2)/(x^3*(x^2+y^2+z^2)) : by linarith [key, h₅] ... ≥ (x^5-x^2*(x*y*z))/(x^3*(x^2+y^2+z^2)) : by { refine (div_le_div_right h₄).mpr _, simp, exact (le_mul_iff_one_le_right (pow_pos hx 2)).mpr h } ... = (x^2-y*z)/(x^2+y^2+z^2) : by { field_simp [ne_of_gt h₂, ne_of_gt h₃], ring }, end theorem imo2005_q3 (x y z : ℝ) (hx : x > 0) (hy : y > 0) (hz : z > 0) (h : x*y*z ≥ 1) : (x^5-x^2)/(x^5+y^2+z^2) + (y^5-y^2)/(y^5+z^2+x^2) + (z^5-z^2)/(z^5+x^2+y^2) ≥ 0 := begin calc (x^5-x^2)/(x^5+y^2+z^2) + (y^5-y^2)/(y^5+z^2+x^2) + (z^5-z^2)/(z^5+x^2+y^2) ≥ (x^2-y*z)/(x^2+y^2+z^2) + (y^2-z*x)/(y^2+z^2+x^2) + (z^2-x*y)/(z^2+x^2+y^2) : by { linarith [key_insight x y z hx hy hz h, key_insight y z x hy hz hx (by linarith [h]), key_insight z x y hz hx hy (by linarith [h])] } ... = (x^2 + y^2 + z^2 - y*z - z*x - x*y) / (x^2+y^2+z^2) : by { have h₁ : y^2+z^2+x^2 = x^2+y^2+z^2, linarith, have h₂ : z^2+x^2+y^2 = x^2+y^2+z^2, linarith, rw [h₁, h₂], ring } ... = 1/2*( (x-y)^2 + (y-z)^2 + (z-x)^2 ) / (x^2+y^2+z^2) : by ring ... ≥ 0 : by { exact div_nonneg (by linarith [pow_two_nonneg (x-y), pow_two_nonneg (y-z), pow_two_nonneg (z-x)]) (by linarith [pow_two_nonneg x, pow_two_nonneg y, pow_two_nonneg z]) }, end
d8b59e3e9a79a39533b8b556068a68773ec352e6
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/erased.lean
a051082018a8e2eb2f8ba0db7f06611e3a38c455
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
623
lean
import Lean /-- `erased α` is the same as `α`, except that the elements of `erased α` are erased in the VM in the same way as types and proofs. This can be used to track data without storing it literally. -/ def Erased (α : Sort u) : Sort max 1 u := Σ's : α → Prop, ∃ a, (fun b => a = b) = s namespace Erased /-- Erase a value. -/ @[inline] def mk {α} (a : α) : Erased α := ⟨fun b => a = b, a, rfl⟩ open Lean.Compiler set_option pp.explicit true set_option pp.funBinderTypes true set_option pp.letVarTypes true set_option trace.Compiler.result true #eval Lean.Compiler.compile #[``Erased.mk]
269990a3289be33ce0e13d3439e3c461c084dafa
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/refl_beta.lean
aafb895b826ddc6aaad5ff96fe57531b740a920f
[ "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
288
lean
import data.stream open nat namespace stream variable A : Type set_option pp.beta false theorem mem_of_mem_odd₂ (a : A) (s : stream A) : a ∈ odd s → a ∈ s := assume ainos, obtain n (h : a = nth n (odd s)), from ainos, exists.intro (2*n+1) (by rewrite [h, nth_odd]) end stream
0a6a71f2148d7f4ea0baf56def55e590ec4e5c5c
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/category_theory/limits/shapes/equalizers.lean
f72c575d0371d0e0d208d20b0c751eb88ff83578
[ "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
46,003
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Markus Himmel -/ import category_theory.epi_mono import category_theory.limits.has_limits /-! # Equalizers and coequalizers > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines (co)equalizers as special cases of (co)limits. An equalizer is the categorical generalization of the subobject {a ∈ A | f(a) = g(a)} known from abelian groups or modules. It is a limit cone over the diagram formed by `f` and `g`. A coequalizer is the dual concept. ## Main definitions * `walking_parallel_pair` is the indexing category used for (co)equalizer_diagrams * `parallel_pair` is a functor from `walking_parallel_pair` to our category `C`. * a `fork` is a cone over a parallel pair. * there is really only one interesting morphism in a fork: the arrow from the vertex of the fork to the domain of f and g. It is called `fork.ι`. * an `equalizer` is now just a `limit (parallel_pair f g)` Each of these has a dual. ## Main statements * `equalizer.ι_mono` states that every equalizer map is a monomorphism * `is_iso_limit_cone_parallel_pair_of_self` states that the identity on the domain of `f` is an equalizer of `f` and `f`. ## Implementation notes As with the other special shapes in the limits library, all the definitions here are given as `abbreviation`s of the general statements for limits, so all the `simp` lemmas and theorems about general limits can be used. ## References * [F. Borceux, *Handbook of Categorical Algebra 1*][borceux-vol1] -/ noncomputable theory open category_theory opposite namespace category_theory.limits local attribute [tidy] tactic.case_bash universes v v₂ u u₂ /-- The type of objects for the diagram indexing a (co)equalizer. -/ @[derive decidable_eq, derive inhabited] inductive walking_parallel_pair : Type | zero | one open walking_parallel_pair /-- The type family of morphisms for the diagram indexing a (co)equalizer. -/ @[derive decidable_eq] inductive walking_parallel_pair_hom : walking_parallel_pair → walking_parallel_pair → Type | left : walking_parallel_pair_hom zero one | right : walking_parallel_pair_hom zero one | id : Π X : walking_parallel_pair, walking_parallel_pair_hom X X /-- Satisfying the inhabited linter -/ instance : inhabited (walking_parallel_pair_hom zero one) := { default := walking_parallel_pair_hom.left } open walking_parallel_pair_hom /-- Composition of morphisms in the indexing diagram for (co)equalizers. -/ def walking_parallel_pair_hom.comp : Π (X Y Z : walking_parallel_pair) (f : walking_parallel_pair_hom X Y) (g : walking_parallel_pair_hom Y Z), walking_parallel_pair_hom X Z | _ _ _ (id _) h := h | _ _ _ left (id one) := left | _ _ _ right (id one) := right . instance walking_parallel_pair_hom_category : small_category walking_parallel_pair := { hom := walking_parallel_pair_hom, id := walking_parallel_pair_hom.id, comp := walking_parallel_pair_hom.comp } @[simp] lemma walking_parallel_pair_hom_id (X : walking_parallel_pair) : walking_parallel_pair_hom.id X = 𝟙 X := rfl /-- The functor `walking_parallel_pair ⥤ walking_parallel_pairᵒᵖ` sending left to left and right to right. -/ def walking_parallel_pair_op : walking_parallel_pair ⥤ walking_parallel_pairᵒᵖ := { obj := (λ x, op $ by { cases x, exacts [one, zero] }), map := λ i j f, by { cases f; apply quiver.hom.op, exacts [left, right, walking_parallel_pair_hom.id _] }, map_comp' := by { rintros (_|_) (_|_) (_|_) (_|_|_) (_|_|_); refl } } @[simp] lemma walking_parallel_pair_op_zero : walking_parallel_pair_op.obj zero = op one := rfl @[simp] lemma walking_parallel_pair_op_one : walking_parallel_pair_op.obj one = op zero := rfl @[simp] lemma walking_parallel_pair_op_left : walking_parallel_pair_op.map left = @quiver.hom.op _ _ zero one left := rfl @[simp] lemma walking_parallel_pair_op_right : walking_parallel_pair_op.map right = @quiver.hom.op _ _ zero one right := rfl /-- The equivalence `walking_parallel_pair ⥤ walking_parallel_pairᵒᵖ` sending left to left and right to right. -/ @[simps functor inverse] def walking_parallel_pair_op_equiv : walking_parallel_pair ≌ walking_parallel_pairᵒᵖ := { functor := walking_parallel_pair_op, inverse := walking_parallel_pair_op.left_op, unit_iso := nat_iso.of_components (λ j, eq_to_iso (by { cases j; refl })) (by { rintros (_|_) (_|_) (_|_|_); refl }), counit_iso := nat_iso.of_components (λ j, eq_to_iso (by { induction j using opposite.rec, cases j; refl })) (λ i j f, by { induction i using opposite.rec, induction j using opposite.rec, let g := f.unop, have : f = g.op := rfl, clear_value g, subst this, rcases i with (_|_); rcases j with (_|_); rcases g with (_|_|_); refl }) } @[simp] lemma walking_parallel_pair_op_equiv_unit_iso_zero : walking_parallel_pair_op_equiv.unit_iso.app zero = iso.refl zero := rfl @[simp] lemma walking_parallel_pair_op_equiv_unit_iso_one : walking_parallel_pair_op_equiv.unit_iso.app one = iso.refl one := rfl @[simp] lemma walking_parallel_pair_op_equiv_counit_iso_zero : walking_parallel_pair_op_equiv.counit_iso.app (op zero) = iso.refl (op zero) := rfl @[simp] lemma walking_parallel_pair_op_equiv_counit_iso_one : walking_parallel_pair_op_equiv.counit_iso.app (op one) = iso.refl (op one) := rfl variables {C : Type u} [category.{v} C] variables {X Y : C} /-- `parallel_pair f g` is the diagram in `C` consisting of the two morphisms `f` and `g` with common domain and codomain. -/ def parallel_pair (f g : X ⟶ Y) : walking_parallel_pair ⥤ C := { obj := λ x, match x with | zero := X | one := Y end, map := λ x y h, match x, y, h with | _, _, (id _) := 𝟙 _ | _, _, left := f | _, _, right := g end, -- `tidy` can cope with this, but it's too slow: map_comp' := begin rintros (⟨⟩|⟨⟩) (⟨⟩|⟨⟩) (⟨⟩|⟨⟩) ⟨⟩⟨⟩; { unfold_aux, simp; refl }, end, }. @[simp] lemma parallel_pair_obj_zero (f g : X ⟶ Y) : (parallel_pair f g).obj zero = X := rfl @[simp] lemma parallel_pair_obj_one (f g : X ⟶ Y) : (parallel_pair f g).obj one = Y := rfl @[simp] lemma parallel_pair_map_left (f g : X ⟶ Y) : (parallel_pair f g).map left = f := rfl @[simp] lemma parallel_pair_map_right (f g : X ⟶ Y) : (parallel_pair f g).map right = g := rfl @[simp] lemma parallel_pair_functor_obj {F : walking_parallel_pair ⥤ C} (j : walking_parallel_pair) : (parallel_pair (F.map left) (F.map right)).obj j = F.obj j := begin cases j; refl end /-- Every functor indexing a (co)equalizer is naturally isomorphic (actually, equal) to a `parallel_pair` -/ @[simps] def diagram_iso_parallel_pair (F : walking_parallel_pair ⥤ C) : F ≅ parallel_pair (F.map left) (F.map right) := nat_iso.of_components (λ j, eq_to_iso $ by cases j; tidy) $ by tidy /-- Construct a morphism between parallel pairs. -/ def parallel_pair_hom {X' Y' : C} (f g : X ⟶ Y) (f' g' : X' ⟶ Y') (p : X ⟶ X') (q : Y ⟶ Y') (wf : f ≫ q = p ≫ f') (wg : g ≫ q = p ≫ g') : parallel_pair f g ⟶ parallel_pair f' g' := { app := λ j, match j with | zero := p | one := q end, naturality' := begin rintros (⟨⟩|⟨⟩) (⟨⟩|⟨⟩) ⟨⟩; { unfold_aux, simp [wf, wg], }, end } @[simp] lemma parallel_pair_hom_app_zero {X' Y' : C} (f g : X ⟶ Y) (f' g' : X' ⟶ Y') (p : X ⟶ X') (q : Y ⟶ Y') (wf : f ≫ q = p ≫ f') (wg : g ≫ q = p ≫ g') : (parallel_pair_hom f g f' g' p q wf wg).app zero = p := rfl @[simp] lemma parallel_pair_hom_app_one {X' Y' : C} (f g : X ⟶ Y) (f' g' : X' ⟶ Y') (p : X ⟶ X') (q : Y ⟶ Y') (wf : f ≫ q = p ≫ f') (wg : g ≫ q = p ≫ g') : (parallel_pair_hom f g f' g' p q wf wg).app one = q := rfl /-- Construct a natural isomorphism between functors out of the walking parallel pair from its components. -/ @[simps] def parallel_pair.ext {F G : walking_parallel_pair ⥤ C} (zero : F.obj zero ≅ G.obj zero) (one : F.obj one ≅ G.obj one) (left : F.map left ≫ one.hom = zero.hom ≫ G.map left) (right : F.map right ≫ one.hom = zero.hom ≫ G.map right) : F ≅ G := nat_iso.of_components (by { rintro ⟨j⟩, exacts [zero, one] }) (by { rintro ⟨j₁⟩ ⟨j₂⟩ ⟨f⟩; simp [left, right], }) /-- Construct a natural isomorphism between `parallel_pair f g` and `parallel_pair f' g'` given equalities `f = f'` and `g = g'`. -/ @[simps] def parallel_pair.eq_of_hom_eq {f g f' g' : X ⟶ Y} (hf : f = f') (hg : g = g') : parallel_pair f g ≅ parallel_pair f' g' := parallel_pair.ext (iso.refl _) (iso.refl _) (by simp [hf]) (by simp [hg]) /-- A fork on `f` and `g` is just a `cone (parallel_pair f g)`. -/ abbreviation fork (f g : X ⟶ Y) := cone (parallel_pair f g) /-- A cofork on `f` and `g` is just a `cocone (parallel_pair f g)`. -/ abbreviation cofork (f g : X ⟶ Y) := cocone (parallel_pair f g) variables {f g : X ⟶ Y} /-- A fork `t` on the parallel pair `f g : X ⟶ Y` consists of two morphisms `t.π.app zero : t.X ⟶ X` and `t.π.app one : t.X ⟶ Y`. Of these, only the first one is interesting, and we give it the shorter name `fork.ι t`. -/ def fork.ι (t : fork f g) := t.π.app zero @[simp] lemma fork.app_zero_eq_ι (t : fork f g) : t.π.app zero = t.ι := rfl /-- A cofork `t` on the parallel_pair `f g : X ⟶ Y` consists of two morphisms `t.ι.app zero : X ⟶ t.X` and `t.ι.app one : Y ⟶ t.X`. Of these, only the second one is interesting, and we give it the shorter name `cofork.π t`. -/ def cofork.π (t : cofork f g) := t.ι.app one @[simp] lemma cofork.app_one_eq_π (t : cofork f g) : t.ι.app one = t.π := rfl @[simp] lemma fork.app_one_eq_ι_comp_left (s : fork f g) : s.π.app one = s.ι ≫ f := by rw [←s.app_zero_eq_ι, ←s.w left, parallel_pair_map_left] @[reassoc] lemma fork.app_one_eq_ι_comp_right (s : fork f g) : s.π.app one = s.ι ≫ g := by rw [←s.app_zero_eq_ι, ←s.w right, parallel_pair_map_right] @[simp] lemma cofork.app_zero_eq_comp_π_left (s : cofork f g) : s.ι.app zero = f ≫ s.π := by rw [←s.app_one_eq_π, ←s.w left, parallel_pair_map_left] @[reassoc] lemma cofork.app_zero_eq_comp_π_right (s : cofork f g) : s.ι.app zero = g ≫ s.π := by rw [←s.app_one_eq_π, ←s.w right, parallel_pair_map_right] /-- A fork on `f g : X ⟶ Y` is determined by the morphism `ι : P ⟶ X` satisfying `ι ≫ f = ι ≫ g`. -/ @[simps] def fork.of_ι {P : C} (ι : P ⟶ X) (w : ι ≫ f = ι ≫ g) : fork f g := { X := P, π := { app := λ X, begin cases X, exact ι, exact ι ≫ f, end, naturality' := λ X Y f, begin cases X; cases Y; cases f; dsimp; simp, { dsimp, simp, }, -- See note [dsimp, simp]. { exact w }, { dsimp, simp, }, end } } /-- A cofork on `f g : X ⟶ Y` is determined by the morphism `π : Y ⟶ P` satisfying `f ≫ π = g ≫ π`. -/ @[simps] def cofork.of_π {P : C} (π : Y ⟶ P) (w : f ≫ π = g ≫ π) : cofork f g := { X := P, ι := { app := λ X, walking_parallel_pair.cases_on X (f ≫ π) π, naturality' := λ i j f, by { cases f; dsimp; simp [w] } } } -- See note [dsimp, simp] @[simp] lemma fork.ι_of_ι {P : C} (ι : P ⟶ X) (w : ι ≫ f = ι ≫ g) : (fork.of_ι ι w).ι = ι := rfl @[simp] lemma cofork.π_of_π {P : C} (π : Y ⟶ P) (w : f ≫ π = g ≫ π) : (cofork.of_π π w).π = π := rfl @[simp, reassoc] lemma fork.condition (t : fork f g) : t.ι ≫ f = t.ι ≫ g := by rw [←t.app_one_eq_ι_comp_left, ←t.app_one_eq_ι_comp_right] @[simp, reassoc] lemma cofork.condition (t : cofork f g) : f ≫ t.π = g ≫ t.π := by rw [←t.app_zero_eq_comp_π_left, ←t.app_zero_eq_comp_π_right] /-- To check whether two maps are equalized by both maps of a fork, it suffices to check it for the first map -/ lemma fork.equalizer_ext (s : fork f g) {W : C} {k l : W ⟶ s.X} (h : k ≫ s.ι = l ≫ s.ι) : ∀ (j : walking_parallel_pair), k ≫ s.π.app j = l ≫ s.π.app j | zero := h | one := by rw [s.app_one_eq_ι_comp_left, reassoc_of h] /-- To check whether two maps are coequalized by both maps of a cofork, it suffices to check it for the second map -/ lemma cofork.coequalizer_ext (s : cofork f g) {W : C} {k l : s.X ⟶ W} (h : cofork.π s ≫ k = cofork.π s ≫ l) : ∀ (j : walking_parallel_pair), s.ι.app j ≫ k = s.ι.app j ≫ l | zero := by simp only [s.app_zero_eq_comp_π_left, category.assoc, h] | one := h lemma fork.is_limit.hom_ext {s : fork f g} (hs : is_limit s) {W : C} {k l : W ⟶ s.X} (h : k ≫ fork.ι s = l ≫ fork.ι s) : k = l := hs.hom_ext $ fork.equalizer_ext _ h lemma cofork.is_colimit.hom_ext {s : cofork f g} (hs : is_colimit s) {W : C} {k l : s.X ⟶ W} (h : cofork.π s ≫ k = cofork.π s ≫ l) : k = l := hs.hom_ext $ cofork.coequalizer_ext _ h @[simp, reassoc] lemma fork.is_limit.lift_ι {s t : fork f g} (hs : is_limit s) : hs.lift t ≫ s.ι = t.ι := hs.fac _ _ @[simp, reassoc] lemma cofork.is_colimit.π_desc {s t : cofork f g} (hs : is_colimit s) : s.π ≫ hs.desc t = t.π := hs.fac _ _ /-- If `s` is a limit fork over `f` and `g`, then a morphism `k : W ⟶ X` satisfying `k ≫ f = k ≫ g` induces a morphism `l : W ⟶ s.X` such that `l ≫ fork.ι s = k`. -/ def fork.is_limit.lift' {s : fork f g} (hs : is_limit s) {W : C} (k : W ⟶ X) (h : k ≫ f = k ≫ g) : {l : W ⟶ s.X // l ≫ fork.ι s = k} := ⟨hs.lift $ fork.of_ι _ h, hs.fac _ _⟩ /-- If `s` is a colimit cofork over `f` and `g`, then a morphism `k : Y ⟶ W` satisfying `f ≫ k = g ≫ k` induces a morphism `l : s.X ⟶ W` such that `cofork.π s ≫ l = k`. -/ def cofork.is_colimit.desc' {s : cofork f g} (hs : is_colimit s) {W : C} (k : Y ⟶ W) (h : f ≫ k = g ≫ k) : {l : s.X ⟶ W // cofork.π s ≫ l = k} := ⟨hs.desc $ cofork.of_π _ h, hs.fac _ _⟩ lemma fork.is_limit.exists_unique {s : fork f g} (hs : is_limit s) {W : C} (k : W ⟶ X) (h : k ≫ f = k ≫ g) : ∃! (l : W ⟶ s.X), l ≫ fork.ι s = k := ⟨hs.lift $ fork.of_ι _ h, hs.fac _ _, λ m hm, fork.is_limit.hom_ext hs $ hm.symm ▸ (hs.fac (fork.of_ι _ h) walking_parallel_pair.zero).symm⟩ lemma cofork.is_colimit.exists_unique {s : cofork f g} (hs : is_colimit s) {W : C} (k : Y ⟶ W) (h : f ≫ k = g ≫ k) : ∃! (d : s.X ⟶ W), cofork.π s ≫ d = k := ⟨hs.desc $ cofork.of_π _ h, hs.fac _ _, λ m hm, cofork.is_colimit.hom_ext hs $ hm.symm ▸ (hs.fac (cofork.of_π _ h) walking_parallel_pair.one).symm⟩ /-- This is a slightly more convenient method to verify that a fork is a limit cone. It only asks for a proof of facts that carry any mathematical content -/ @[simps lift] def fork.is_limit.mk (t : fork f g) (lift : Π (s : fork f g), s.X ⟶ t.X) (fac : ∀ (s : fork f g), lift s ≫ fork.ι t = fork.ι s) (uniq : ∀ (s : fork f g) (m : s.X ⟶ t.X) (w : m ≫ t.ι = s.ι), m = lift s) : is_limit t := { lift := lift, fac' := λ s j, walking_parallel_pair.cases_on j (fac s) $ by erw [←s.w left, ←t.w left, ←category.assoc, fac]; refl, uniq' := λ s m j, by tidy } /-- This is another convenient method to verify that a fork is a limit cone. It only asks for a proof of facts that carry any mathematical content, and allows access to the same `s` for all parts. -/ def fork.is_limit.mk' {X Y : C} {f g : X ⟶ Y} (t : fork f g) (create : Π (s : fork f g), {l // l ≫ t.ι = s.ι ∧ ∀ {m}, m ≫ t.ι = s.ι → m = l}) : is_limit t := fork.is_limit.mk t (λ s, (create s).1) (λ s, (create s).2.1) (λ s m w, (create s).2.2 w) /-- This is a slightly more convenient method to verify that a cofork is a colimit cocone. It only asks for a proof of facts that carry any mathematical content -/ def cofork.is_colimit.mk (t : cofork f g) (desc : Π (s : cofork f g), t.X ⟶ s.X) (fac : ∀ (s : cofork f g), cofork.π t ≫ desc s = cofork.π s) (uniq : ∀ (s : cofork f g) (m : t.X ⟶ s.X) (w : t.π ≫ m = s.π), m = desc s) : is_colimit t := { desc := desc, fac' := λ s j, walking_parallel_pair.cases_on j (by erw [←s.w left, ←t.w left, category.assoc, fac]; refl) (fac s), uniq' := by tidy } /-- This is another convenient method to verify that a fork is a limit cone. It only asks for a proof of facts that carry any mathematical content, and allows access to the same `s` for all parts. -/ def cofork.is_colimit.mk' {X Y : C} {f g : X ⟶ Y} (t : cofork f g) (create : Π (s : cofork f g), {l : t.X ⟶ s.X // t.π ≫ l = s.π ∧ ∀ {m}, t.π ≫ m = s.π → m = l}) : is_colimit t := cofork.is_colimit.mk t (λ s, (create s).1) (λ s, (create s).2.1) (λ s m w, (create s).2.2 w) /-- Noncomputably make a limit cone from the existence of unique factorizations. -/ def fork.is_limit.of_exists_unique {t : fork f g} (hs : ∀ (s : fork f g), ∃! l : s.X ⟶ t.X, l ≫ fork.ι t = fork.ι s) : is_limit t := by { choose d hd hd' using hs, exact fork.is_limit.mk _ d hd (λ s m hm, hd' _ _ hm) } /-- Noncomputably make a colimit cocone from the existence of unique factorizations. -/ def cofork.is_colimit.of_exists_unique {t : cofork f g} (hs : ∀ (s : cofork f g), ∃! d : t.X ⟶ s.X, cofork.π t ≫ d = cofork.π s) : is_colimit t := by { choose d hd hd' using hs, exact cofork.is_colimit.mk _ d hd (λ s m hm, hd' _ _ hm) } /-- Given a limit cone for the pair `f g : X ⟶ Y`, for any `Z`, morphisms from `Z` to its point are in bijection with morphisms `h : Z ⟶ X` such that `h ≫ f = h ≫ g`. Further, this bijection is natural in `Z`: see `fork.is_limit.hom_iso_natural`. This is a special case of `is_limit.hom_iso'`, often useful to construct adjunctions. -/ @[simps] def fork.is_limit.hom_iso {X Y : C} {f g : X ⟶ Y} {t : fork f g} (ht : is_limit t) (Z : C) : (Z ⟶ t.X) ≃ {h : Z ⟶ X // h ≫ f = h ≫ g} := { to_fun := λ k, ⟨k ≫ t.ι, by simp only [category.assoc, t.condition]⟩, inv_fun := λ h, (fork.is_limit.lift' ht _ h.prop).1, left_inv := λ k, fork.is_limit.hom_ext ht (fork.is_limit.lift' _ _ _).prop, right_inv := λ h, subtype.ext (fork.is_limit.lift' ht _ _).prop } /-- The bijection of `fork.is_limit.hom_iso` is natural in `Z`. -/ lemma fork.is_limit.hom_iso_natural {X Y : C} {f g : X ⟶ Y} {t : fork f g} (ht : is_limit t) {Z Z' : C} (q : Z' ⟶ Z) (k : Z ⟶ t.X) : (fork.is_limit.hom_iso ht _ (q ≫ k) : Z' ⟶ X) = q ≫ (fork.is_limit.hom_iso ht _ k : Z ⟶ X) := category.assoc _ _ _ /-- Given a colimit cocone for the pair `f g : X ⟶ Y`, for any `Z`, morphisms from the cocone point to `Z` are in bijection with morphisms `h : Y ⟶ Z` such that `f ≫ h = g ≫ h`. Further, this bijection is natural in `Z`: see `cofork.is_colimit.hom_iso_natural`. This is a special case of `is_colimit.hom_iso'`, often useful to construct adjunctions. -/ @[simps] def cofork.is_colimit.hom_iso {X Y : C} {f g : X ⟶ Y} {t : cofork f g} (ht : is_colimit t) (Z : C) : (t.X ⟶ Z) ≃ {h : Y ⟶ Z // f ≫ h = g ≫ h} := { to_fun := λ k, ⟨t.π ≫ k, by simp only [←category.assoc, t.condition]⟩, inv_fun := λ h, (cofork.is_colimit.desc' ht _ h.prop).1, left_inv := λ k, cofork.is_colimit.hom_ext ht (cofork.is_colimit.desc' _ _ _).prop, right_inv := λ h, subtype.ext (cofork.is_colimit.desc' ht _ _).prop } /-- The bijection of `cofork.is_colimit.hom_iso` is natural in `Z`. -/ lemma cofork.is_colimit.hom_iso_natural {X Y : C} {f g : X ⟶ Y} {t : cofork f g} {Z Z' : C} (q : Z ⟶ Z') (ht : is_colimit t) (k : t.X ⟶ Z) : (cofork.is_colimit.hom_iso ht _ (k ≫ q) : Y ⟶ Z') = (cofork.is_colimit.hom_iso ht _ k : Y ⟶ Z) ≫ q := (category.assoc _ _ _).symm /-- This is a helper construction that can be useful when verifying that a category has all equalizers. Given `F : walking_parallel_pair ⥤ C`, which is really the same as `parallel_pair (F.map left) (F.map right)`, and a fork on `F.map left` and `F.map right`, we get a cone on `F`. If you're thinking about using this, have a look at `has_equalizers_of_has_limit_parallel_pair`, which you may find to be an easier way of achieving your goal. -/ def cone.of_fork {F : walking_parallel_pair ⥤ C} (t : fork (F.map left) (F.map right)) : cone F := { X := t.X, π := { app := λ X, t.π.app X ≫ eq_to_hom (by tidy), naturality' := λ j j' g, by { cases j; cases j'; cases g; dsimp; simp } } } /-- This is a helper construction that can be useful when verifying that a category has all coequalizers. Given `F : walking_parallel_pair ⥤ C`, which is really the same as `parallel_pair (F.map left) (F.map right)`, and a cofork on `F.map left` and `F.map right`, we get a cocone on `F`. If you're thinking about using this, have a look at `has_coequalizers_of_has_colimit_parallel_pair`, which you may find to be an easier way of achieving your goal. -/ def cocone.of_cofork {F : walking_parallel_pair ⥤ C} (t : cofork (F.map left) (F.map right)) : cocone F := { X := t.X, ι := { app := λ X, eq_to_hom (by tidy) ≫ t.ι.app X, naturality' := λ j j' g, by { cases j; cases j'; cases g; dsimp; simp } } } @[simp] lemma cone.of_fork_π {F : walking_parallel_pair ⥤ C} (t : fork (F.map left) (F.map right)) (j) : (cone.of_fork t).π.app j = t.π.app j ≫ eq_to_hom (by tidy) := rfl @[simp] lemma cocone.of_cofork_ι {F : walking_parallel_pair ⥤ C} (t : cofork (F.map left) (F.map right)) (j) : (cocone.of_cofork t).ι.app j = eq_to_hom (by tidy) ≫ t.ι.app j := rfl /-- Given `F : walking_parallel_pair ⥤ C`, which is really the same as `parallel_pair (F.map left) (F.map right)` and a cone on `F`, we get a fork on `F.map left` and `F.map right`. -/ def fork.of_cone {F : walking_parallel_pair ⥤ C} (t : cone F) : fork (F.map left) (F.map right) := { X := t.X, π := { app := λ X, t.π.app X ≫ eq_to_hom (by tidy) } } /-- Given `F : walking_parallel_pair ⥤ C`, which is really the same as `parallel_pair (F.map left) (F.map right)` and a cocone on `F`, we get a cofork on `F.map left` and `F.map right`. -/ def cofork.of_cocone {F : walking_parallel_pair ⥤ C} (t : cocone F) : cofork (F.map left) (F.map right) := { X := t.X, ι := { app := λ X, eq_to_hom (by tidy) ≫ t.ι.app X } } @[simp] lemma fork.of_cone_π {F : walking_parallel_pair ⥤ C} (t : cone F) (j) : (fork.of_cone t).π.app j = t.π.app j ≫ eq_to_hom (by tidy) := rfl @[simp] lemma cofork.of_cocone_ι {F : walking_parallel_pair ⥤ C} (t : cocone F) (j) : (cofork.of_cocone t).ι.app j = eq_to_hom (by tidy) ≫ t.ι.app j := rfl @[simp] lemma fork.ι_postcompose {f' g' : X ⟶ Y} {α : parallel_pair f g ⟶ parallel_pair f' g'} {c : fork f g} : fork.ι ((cones.postcompose α).obj c) = c.ι ≫ α.app _ := rfl @[simp] lemma cofork.π_precompose {f' g' : X ⟶ Y} {α : parallel_pair f g ⟶ parallel_pair f' g'} {c : cofork f' g'} : cofork.π ((cocones.precompose α).obj c) = α.app _ ≫ c.π := rfl /-- Helper function for constructing morphisms between equalizer forks. -/ @[simps] def fork.mk_hom {s t : fork f g} (k : s.X ⟶ t.X) (w : k ≫ t.ι = s.ι) : s ⟶ t := { hom := k, w' := begin rintro ⟨_|_⟩, { exact w }, { simp only [fork.app_one_eq_ι_comp_left, reassoc_of w] }, end } /-- To construct an isomorphism between forks, it suffices to give an isomorphism between the cone points and check that it commutes with the `ι` morphisms. -/ @[simps] def fork.ext {s t : fork f g} (i : s.X ≅ t.X) (w : i.hom ≫ t.ι = s.ι) : s ≅ t := { hom := fork.mk_hom i.hom w, inv := fork.mk_hom i.inv (by rw [← w, iso.inv_hom_id_assoc]) } /-- Every fork is isomorphic to one of the form `fork.of_ι _ _`. -/ def fork.iso_fork_of_ι (c : fork f g) : c ≅ fork.of_ι c.ι c.condition := fork.ext (by simp only [fork.of_ι_X, functor.const_obj_obj]) (by simp) /-- Helper function for constructing morphisms between coequalizer coforks. -/ @[simps] def cofork.mk_hom {s t : cofork f g} (k : s.X ⟶ t.X) (w : s.π ≫ k = t.π) : s ⟶ t := { hom := k, w' := begin rintro ⟨_|_⟩, { simp [cofork.app_zero_eq_comp_π_left, w] }, { exact w } end } @[simp, reassoc] lemma fork.hom_comp_ι {s t : fork f g} (f : s ⟶ t) : f.hom ≫ t.ι = s.ι := by tidy @[simp, reassoc] lemma fork.π_comp_hom {s t : cofork f g} (f : s ⟶ t) : s.π ≫ f.hom = t.π := by tidy /-- To construct an isomorphism between coforks, it suffices to give an isomorphism between the cocone points and check that it commutes with the `π` morphisms. -/ @[simps] def cofork.ext {s t : cofork f g} (i : s.X ≅ t.X) (w : s.π ≫ i.hom = t.π) : s ≅ t := { hom := cofork.mk_hom i.hom w, inv := cofork.mk_hom i.inv (by rw [iso.comp_inv_eq, w]) } /-- Every cofork is isomorphic to one of the form `cofork.of_π _ _`. -/ def cofork.iso_cofork_of_π (c : cofork f g) : c ≅ cofork.of_π c.π c.condition := cofork.ext (by simp only [cofork.of_π_X, functor.const_obj_obj]) (by dsimp; simp) variables (f g) section /-- `has_equalizer f g` represents a particular choice of limiting cone for the parallel pair of morphisms `f` and `g`. -/ abbreviation has_equalizer := has_limit (parallel_pair f g) variables [has_equalizer f g] /-- If an equalizer of `f` and `g` exists, we can access an arbitrary choice of such by saying `equalizer f g`. -/ abbreviation equalizer : C := limit (parallel_pair f g) /-- If an equalizer of `f` and `g` exists, we can access the inclusion `equalizer f g ⟶ X` by saying `equalizer.ι f g`. -/ abbreviation equalizer.ι : equalizer f g ⟶ X := limit.π (parallel_pair f g) zero /-- An equalizer cone for a parallel pair `f` and `g`. -/ abbreviation equalizer.fork : fork f g := limit.cone (parallel_pair f g) @[simp] lemma equalizer.fork_ι : (equalizer.fork f g).ι = equalizer.ι f g := rfl @[simp] lemma equalizer.fork_π_app_zero : (equalizer.fork f g).π.app zero = equalizer.ι f g := rfl @[reassoc] lemma equalizer.condition : equalizer.ι f g ≫ f = equalizer.ι f g ≫ g := fork.condition $ limit.cone $ parallel_pair f g /-- The equalizer built from `equalizer.ι f g` is limiting. -/ def equalizer_is_equalizer : is_limit (fork.of_ι (equalizer.ι f g) (equalizer.condition f g)) := is_limit.of_iso_limit (limit.is_limit _) (fork.ext (iso.refl _) (by tidy)) variables {f g} /-- A morphism `k : W ⟶ X` satisfying `k ≫ f = k ≫ g` factors through the equalizer of `f` and `g` via `equalizer.lift : W ⟶ equalizer f g`. -/ abbreviation equalizer.lift {W : C} (k : W ⟶ X) (h : k ≫ f = k ≫ g) : W ⟶ equalizer f g := limit.lift (parallel_pair f g) (fork.of_ι k h) @[simp, reassoc] lemma equalizer.lift_ι {W : C} (k : W ⟶ X) (h : k ≫ f = k ≫ g) : equalizer.lift k h ≫ equalizer.ι f g = k := limit.lift_π _ _ /-- A morphism `k : W ⟶ X` satisfying `k ≫ f = k ≫ g` induces a morphism `l : W ⟶ equalizer f g` satisfying `l ≫ equalizer.ι f g = k`. -/ def equalizer.lift' {W : C} (k : W ⟶ X) (h : k ≫ f = k ≫ g) : {l : W ⟶ equalizer f g // l ≫ equalizer.ι f g = k} := ⟨equalizer.lift k h, equalizer.lift_ι _ _⟩ /-- Two maps into an equalizer are equal if they are are equal when composed with the equalizer map. -/ @[ext] lemma equalizer.hom_ext {W : C} {k l : W ⟶ equalizer f g} (h : k ≫ equalizer.ι f g = l ≫ equalizer.ι f g) : k = l := fork.is_limit.hom_ext (limit.is_limit _) h lemma equalizer.exists_unique {W : C} (k : W ⟶ X) (h : k ≫ f = k ≫ g) : ∃! (l : W ⟶ equalizer f g), l ≫ equalizer.ι f g = k := fork.is_limit.exists_unique (limit.is_limit _) _ h /-- An equalizer morphism is a monomorphism -/ instance equalizer.ι_mono : mono (equalizer.ι f g) := { right_cancellation := λ Z h k w, equalizer.hom_ext w } end section variables {f g} /-- The equalizer morphism in any limit cone is a monomorphism. -/ lemma mono_of_is_limit_fork {c : fork f g} (i : is_limit c) : mono (fork.ι c) := { right_cancellation := λ Z h k w, fork.is_limit.hom_ext i w } end section variables {f g} /-- The identity determines a cone on the equalizer diagram of `f` and `g` if `f = g`. -/ def id_fork (h : f = g) : fork f g := fork.of_ι (𝟙 X) $ h ▸ rfl /-- The identity on `X` is an equalizer of `(f, g)`, if `f = g`. -/ def is_limit_id_fork (h : f = g) : is_limit (id_fork h) := fork.is_limit.mk _ (λ s, fork.ι s) (λ s, category.comp_id _) (λ s m h, by { convert h, exact (category.comp_id _).symm }) /-- Every equalizer of `(f, g)`, where `f = g`, is an isomorphism. -/ lemma is_iso_limit_cone_parallel_pair_of_eq (h₀ : f = g) {c : fork f g} (h : is_limit c) : is_iso c.ι := is_iso.of_iso $ is_limit.cone_point_unique_up_to_iso h $ is_limit_id_fork h₀ /-- The equalizer of `(f, g)`, where `f = g`, is an isomorphism. -/ lemma equalizer.ι_of_eq [has_equalizer f g] (h : f = g) : is_iso (equalizer.ι f g) := is_iso_limit_cone_parallel_pair_of_eq h $ limit.is_limit _ /-- Every equalizer of `(f, f)` is an isomorphism. -/ lemma is_iso_limit_cone_parallel_pair_of_self {c : fork f f} (h : is_limit c) : is_iso c.ι := is_iso_limit_cone_parallel_pair_of_eq rfl h /-- An equalizer that is an epimorphism is an isomorphism. -/ lemma is_iso_limit_cone_parallel_pair_of_epi {c : fork f g} (h : is_limit c) [epi (c.ι)] : is_iso c.ι := is_iso_limit_cone_parallel_pair_of_eq ((cancel_epi _).1 (fork.condition c)) h /-- Two morphisms are equal if there is a fork whose inclusion is epi. -/ lemma eq_of_epi_fork_ι (t : fork f g) [epi (fork.ι t)] : f = g := (cancel_epi (fork.ι t)).1 $ fork.condition t /-- If the equalizer of two morphisms is an epimorphism, then the two morphisms are equal. -/ lemma eq_of_epi_equalizer [has_equalizer f g] [epi (equalizer.ι f g)] : f = g := (cancel_epi (equalizer.ι f g)).1 $ equalizer.condition _ _ end instance has_equalizer_of_self : has_equalizer f f := has_limit.mk { cone := id_fork rfl, is_limit := is_limit_id_fork rfl } /-- The equalizer inclusion for `(f, f)` is an isomorphism. -/ instance equalizer.ι_of_self : is_iso (equalizer.ι f f) := equalizer.ι_of_eq rfl /-- The equalizer of a morphism with itself is isomorphic to the source. -/ def equalizer.iso_source_of_self : equalizer f f ≅ X := as_iso (equalizer.ι f f) @[simp] lemma equalizer.iso_source_of_self_hom : (equalizer.iso_source_of_self f).hom = equalizer.ι f f := rfl @[simp] lemma equalizer.iso_source_of_self_inv : (equalizer.iso_source_of_self f).inv = equalizer.lift (𝟙 X) (by simp) := by { ext, simp [equalizer.iso_source_of_self], } section /-- `has_coequalizer f g` represents a particular choice of colimiting cocone for the parallel pair of morphisms `f` and `g`. -/ abbreviation has_coequalizer := has_colimit (parallel_pair f g) variables [has_coequalizer f g] /-- If a coequalizer of `f` and `g` exists, we can access an arbitrary choice of such by saying `coequalizer f g`. -/ abbreviation coequalizer : C := colimit (parallel_pair f g) /-- If a coequalizer of `f` and `g` exists, we can access the corresponding projection by saying `coequalizer.π f g`. -/ abbreviation coequalizer.π : Y ⟶ coequalizer f g := colimit.ι (parallel_pair f g) one /-- An arbitrary choice of coequalizer cocone for a parallel pair `f` and `g`. -/ abbreviation coequalizer.cofork : cofork f g := colimit.cocone (parallel_pair f g) @[simp] lemma coequalizer.cofork_π : (coequalizer.cofork f g).π = coequalizer.π f g := rfl @[simp] lemma coequalizer.cofork_ι_app_one : (coequalizer.cofork f g).ι.app one = coequalizer.π f g := rfl @[reassoc] lemma coequalizer.condition : f ≫ coequalizer.π f g = g ≫ coequalizer.π f g := cofork.condition $ colimit.cocone $ parallel_pair f g /-- The cofork built from `coequalizer.π f g` is colimiting. -/ def coequalizer_is_coequalizer : is_colimit (cofork.of_π (coequalizer.π f g) (coequalizer.condition f g)) := is_colimit.of_iso_colimit (colimit.is_colimit _) (cofork.ext (iso.refl _) (by tidy)) variables {f g} /-- Any morphism `k : Y ⟶ W` satisfying `f ≫ k = g ≫ k` factors through the coequalizer of `f` and `g` via `coequalizer.desc : coequalizer f g ⟶ W`. -/ abbreviation coequalizer.desc {W : C} (k : Y ⟶ W) (h : f ≫ k = g ≫ k) : coequalizer f g ⟶ W := colimit.desc (parallel_pair f g) (cofork.of_π k h) @[simp, reassoc] lemma coequalizer.π_desc {W : C} (k : Y ⟶ W) (h : f ≫ k = g ≫ k) : coequalizer.π f g ≫ coequalizer.desc k h = k := colimit.ι_desc _ _ lemma coequalizer.π_colim_map_desc {X' Y' Z : C} (f' g' : X' ⟶ Y') [has_coequalizer f' g'] (p : X ⟶ X') (q : Y ⟶ Y') (wf : f ≫ q = p ≫ f') (wg : g ≫ q = p ≫ g') (h : Y' ⟶ Z) (wh : f' ≫ h = g' ≫ h) : coequalizer.π f g ≫ colim_map (parallel_pair_hom f g f' g' p q wf wg) ≫ coequalizer.desc h wh = q ≫ h := by rw [ι_colim_map_assoc, parallel_pair_hom_app_one, coequalizer.π_desc] /-- Any morphism `k : Y ⟶ W` satisfying `f ≫ k = g ≫ k` induces a morphism `l : coequalizer f g ⟶ W` satisfying `coequalizer.π ≫ g = l`. -/ def coequalizer.desc' {W : C} (k : Y ⟶ W) (h : f ≫ k = g ≫ k) : {l : coequalizer f g ⟶ W // coequalizer.π f g ≫ l = k} := ⟨coequalizer.desc k h, coequalizer.π_desc _ _⟩ /-- Two maps from a coequalizer are equal if they are equal when composed with the coequalizer map -/ @[ext] lemma coequalizer.hom_ext {W : C} {k l : coequalizer f g ⟶ W} (h : coequalizer.π f g ≫ k = coequalizer.π f g ≫ l) : k = l := cofork.is_colimit.hom_ext (colimit.is_colimit _) h lemma coequalizer.exists_unique {W : C} (k : Y ⟶ W) (h : f ≫ k = g ≫ k) : ∃! (d : coequalizer f g ⟶ W), coequalizer.π f g ≫ d = k := cofork.is_colimit.exists_unique (colimit.is_colimit _) _ h /-- A coequalizer morphism is an epimorphism -/ instance coequalizer.π_epi : epi (coequalizer.π f g) := { left_cancellation := λ Z h k w, coequalizer.hom_ext w } end section variables {f g} /-- The coequalizer morphism in any colimit cocone is an epimorphism. -/ lemma epi_of_is_colimit_cofork {c : cofork f g} (i : is_colimit c) : epi c.π := { left_cancellation := λ Z h k w, cofork.is_colimit.hom_ext i w } end section variables {f g} /-- The identity determines a cocone on the coequalizer diagram of `f` and `g`, if `f = g`. -/ def id_cofork (h : f = g) : cofork f g := cofork.of_π (𝟙 Y) $ h ▸ rfl /-- The identity on `Y` is a coequalizer of `(f, g)`, where `f = g`. -/ def is_colimit_id_cofork (h : f = g) : is_colimit (id_cofork h) := cofork.is_colimit.mk _ (λ s, cofork.π s) (λ s, category.id_comp _) (λ s m h, by { convert h, exact (category.id_comp _).symm }) /-- Every coequalizer of `(f, g)`, where `f = g`, is an isomorphism. -/ lemma is_iso_colimit_cocone_parallel_pair_of_eq (h₀ : f = g) {c : cofork f g} (h : is_colimit c) : is_iso c.π := is_iso.of_iso $ is_colimit.cocone_point_unique_up_to_iso (is_colimit_id_cofork h₀) h /-- The coequalizer of `(f, g)`, where `f = g`, is an isomorphism. -/ lemma coequalizer.π_of_eq [has_coequalizer f g] (h : f = g) : is_iso (coequalizer.π f g) := is_iso_colimit_cocone_parallel_pair_of_eq h $ colimit.is_colimit _ /-- Every coequalizer of `(f, f)` is an isomorphism. -/ lemma is_iso_colimit_cocone_parallel_pair_of_self {c : cofork f f} (h : is_colimit c) : is_iso c.π := is_iso_colimit_cocone_parallel_pair_of_eq rfl h /-- A coequalizer that is a monomorphism is an isomorphism. -/ lemma is_iso_limit_cocone_parallel_pair_of_epi {c : cofork f g} (h : is_colimit c) [mono c.π] : is_iso c.π := is_iso_colimit_cocone_parallel_pair_of_eq ((cancel_mono _).1 (cofork.condition c)) h /-- Two morphisms are equal if there is a cofork whose projection is mono. -/ lemma eq_of_mono_cofork_π (t : cofork f g) [mono (cofork.π t)] : f = g := (cancel_mono (cofork.π t)).1 $ cofork.condition t /-- If the coequalizer of two morphisms is a monomorphism, then the two morphisms are equal. -/ lemma eq_of_mono_coequalizer [has_coequalizer f g] [mono (coequalizer.π f g)] : f = g := (cancel_mono (coequalizer.π f g)).1 $ coequalizer.condition _ _ end instance has_coequalizer_of_self : has_coequalizer f f := has_colimit.mk { cocone := id_cofork rfl, is_colimit := is_colimit_id_cofork rfl } /-- The coequalizer projection for `(f, f)` is an isomorphism. -/ instance coequalizer.π_of_self : is_iso (coequalizer.π f f) := coequalizer.π_of_eq rfl /-- The coequalizer of a morphism with itself is isomorphic to the target. -/ def coequalizer.iso_target_of_self : coequalizer f f ≅ Y := (as_iso (coequalizer.π f f)).symm @[simp] lemma coequalizer.iso_target_of_self_hom : (coequalizer.iso_target_of_self f).hom = coequalizer.desc (𝟙 Y) (by simp) := by { ext, simp [coequalizer.iso_target_of_self], } @[simp] lemma coequalizer.iso_target_of_self_inv : (coequalizer.iso_target_of_self f).inv = coequalizer.π f f := rfl section comparison variables {D : Type u₂} [category.{v₂} D] (G : C ⥤ D) /-- The comparison morphism for the equalizer of `f,g`. This is an isomorphism iff `G` preserves the equalizer of `f,g`; see `category_theory/limits/preserves/shapes/equalizers.lean` -/ def equalizer_comparison [has_equalizer f g] [has_equalizer (G.map f) (G.map g)] : G.obj (equalizer f g) ⟶ equalizer (G.map f) (G.map g) := equalizer.lift (G.map (equalizer.ι _ _)) (by simp only [←G.map_comp, equalizer.condition]) @[simp, reassoc] lemma equalizer_comparison_comp_π [has_equalizer f g] [has_equalizer (G.map f) (G.map g)] : equalizer_comparison f g G ≫ equalizer.ι (G.map f) (G.map g) = G.map (equalizer.ι f g) := equalizer.lift_ι _ _ @[simp, reassoc] lemma map_lift_equalizer_comparison [has_equalizer f g] [has_equalizer (G.map f) (G.map g)] {Z : C} {h : Z ⟶ X} (w : h ≫ f = h ≫ g) : G.map (equalizer.lift h w) ≫ equalizer_comparison f g G = equalizer.lift (G.map h) (by simp only [←G.map_comp, w]) := by { ext, simp [← G.map_comp] } /-- The comparison morphism for the coequalizer of `f,g`. -/ def coequalizer_comparison [has_coequalizer f g] [has_coequalizer (G.map f) (G.map g)] : coequalizer (G.map f) (G.map g) ⟶ G.obj (coequalizer f g) := coequalizer.desc (G.map (coequalizer.π _ _)) (by simp only [←G.map_comp, coequalizer.condition]) @[simp, reassoc] lemma ι_comp_coequalizer_comparison [has_coequalizer f g] [has_coequalizer (G.map f) (G.map g)] : coequalizer.π _ _ ≫ coequalizer_comparison f g G = G.map (coequalizer.π _ _) := coequalizer.π_desc _ _ @[simp, reassoc] lemma coequalizer_comparison_map_desc [has_coequalizer f g] [has_coequalizer (G.map f) (G.map g)] {Z : C} {h : Y ⟶ Z} (w : f ≫ h = g ≫ h) : coequalizer_comparison f g G ≫ G.map (coequalizer.desc h w) = coequalizer.desc (G.map h) (by simp only [←G.map_comp, w]) := by { ext, simp [← G.map_comp] } end comparison variables (C) /-- `has_equalizers` represents a choice of equalizer for every pair of morphisms -/ abbreviation has_equalizers := has_limits_of_shape walking_parallel_pair C /-- `has_coequalizers` represents a choice of coequalizer for every pair of morphisms -/ abbreviation has_coequalizers := has_colimits_of_shape walking_parallel_pair C /-- If `C` has all limits of diagrams `parallel_pair f g`, then it has all equalizers -/ lemma has_equalizers_of_has_limit_parallel_pair [Π {X Y : C} {f g : X ⟶ Y}, has_limit (parallel_pair f g)] : has_equalizers C := { has_limit := λ F, has_limit_of_iso (diagram_iso_parallel_pair F).symm } /-- If `C` has all colimits of diagrams `parallel_pair f g`, then it has all coequalizers -/ lemma has_coequalizers_of_has_colimit_parallel_pair [Π {X Y : C} {f g : X ⟶ Y}, has_colimit (parallel_pair f g)] : has_coequalizers C := { has_colimit := λ F, has_colimit_of_iso (diagram_iso_parallel_pair F) } section -- In this section we show that a split mono `f` equalizes `(retraction f ≫ f)` and `(𝟙 Y)`. variables {C} [is_split_mono f] /-- A split mono `f` equalizes `(retraction f ≫ f)` and `(𝟙 Y)`. Here we build the cone, and show in `is_split_mono_equalizes` that it is a limit cone. -/ @[simps {rhs_md := semireducible}] def cone_of_is_split_mono : fork (𝟙 Y) (retraction f ≫ f) := fork.of_ι f (by simp) @[simp] lemma cone_of_is_split_mono_ι : (cone_of_is_split_mono f).ι = f := rfl /-- A split mono `f` equalizes `(retraction f ≫ f)` and `(𝟙 Y)`. -/ def is_split_mono_equalizes {X Y : C} (f : X ⟶ Y) [is_split_mono f] : is_limit (cone_of_is_split_mono f) := fork.is_limit.mk' _ $ λ s, ⟨s.ι ≫ retraction f, by { dsimp, rw [category.assoc, ←s.condition], apply category.comp_id }, λ m hm, by simp [←hm]⟩ end /-- We show that the converse to `is_split_mono_equalizes` is true: Whenever `f` equalizes `(r ≫ f)` and `(𝟙 Y)`, then `r` is a retraction of `f`. -/ def split_mono_of_equalizer {X Y : C} {f : X ⟶ Y} {r : Y ⟶ X} (hr : f ≫ r ≫ f = f) (h : is_limit (fork.of_ι f (hr.trans (category.comp_id _).symm : f ≫ r ≫ f = f ≫ 𝟙 Y))) : split_mono f := { retraction := r, id' := fork.is_limit.hom_ext h ((category.assoc _ _ _).trans $ hr.trans (category.id_comp _).symm) } variables {C f g} /-- The fork obtained by postcomposing an equalizer fork with a monomorphism is an equalizer. -/ def is_equalizer_comp_mono {c : fork f g} (i : is_limit c) {Z : C} (h : Y ⟶ Z) [hm : mono h] : is_limit (fork.of_ι c.ι (by simp [reassoc_of c.condition]) : fork (f ≫ h) (g ≫ h)) := fork.is_limit.mk' _ $ λ s, let s' : fork f g := fork.of_ι s.ι (by apply hm.right_cancellation; simp [s.condition]) in let l := fork.is_limit.lift' i s'.ι s'.condition in ⟨l.1, l.2, λ m hm, by apply fork.is_limit.hom_ext i; rw fork.ι_of_ι at hm; rw hm; exact l.2.symm⟩ variables (C f g) @[instance] lemma has_equalizer_comp_mono [has_equalizer f g] {Z : C} (h : Y ⟶ Z) [mono h] : has_equalizer (f ≫ h) (g ≫ h) := ⟨⟨{ cone := _, is_limit := is_equalizer_comp_mono (limit.is_limit _) h }⟩⟩ /-- An equalizer of an idempotent morphism and the identity is split mono. -/ @[simps] def split_mono_of_idempotent_of_is_limit_fork {X : C} {f : X ⟶ X} (hf : f ≫ f = f) {c : fork (𝟙 X) f} (i : is_limit c) : split_mono c.ι := { retraction := i.lift (fork.of_ι f (by simp [hf])), id' := begin letI := mono_of_is_limit_fork i, rw [←cancel_mono_id c.ι, category.assoc, fork.is_limit.lift_ι, fork.ι_of_ι, ←c.condition], exact category.comp_id c.ι end } /-- The equalizer of an idempotent morphism and the identity is split mono. -/ def split_mono_of_idempotent_equalizer {X : C} {f : X ⟶ X} (hf : f ≫ f = f) [has_equalizer (𝟙 X) f] : split_mono (equalizer.ι (𝟙 X) f) := split_mono_of_idempotent_of_is_limit_fork _ hf (limit.is_limit _) section -- In this section we show that a split epi `f` coequalizes `(f ≫ section_ f)` and `(𝟙 X)`. variables {C} [is_split_epi f] /-- A split epi `f` coequalizes `(f ≫ section_ f)` and `(𝟙 X)`. Here we build the cocone, and show in `is_split_epi_coequalizes` that it is a colimit cocone. -/ @[simps {rhs_md := semireducible}] def cocone_of_is_split_epi : cofork (𝟙 X) (f ≫ section_ f) := cofork.of_π f (by simp) @[simp] lemma cocone_of_is_split_epi_π : (cocone_of_is_split_epi f).π = f := rfl /-- A split epi `f` coequalizes `(f ≫ section_ f)` and `(𝟙 X)`. -/ def is_split_epi_coequalizes {X Y : C} (f : X ⟶ Y) [is_split_epi f] : is_colimit (cocone_of_is_split_epi f) := cofork.is_colimit.mk' _ $ λ s, ⟨section_ f ≫ s.π, by { dsimp, rw [← category.assoc, ← s.condition, category.id_comp] }, λ m hm, by simp [← hm]⟩ end /-- We show that the converse to `is_split_epi_equalizes` is true: Whenever `f` coequalizes `(f ≫ s)` and `(𝟙 X)`, then `s` is a section of `f`. -/ def split_epi_of_coequalizer {X Y : C} {f : X ⟶ Y} {s : Y ⟶ X} (hs : f ≫ s ≫ f = f) (h : is_colimit (cofork.of_π f ((category.assoc _ _ _).trans $ hs.trans (category.id_comp f).symm : (f ≫ s) ≫ f = 𝟙 X ≫ f))) : split_epi f := { section_ := s, id' := cofork.is_colimit.hom_ext h (hs.trans (category.comp_id _).symm) } variables {C f g} /-- The cofork obtained by precomposing a coequalizer cofork with an epimorphism is a coequalizer. -/ def is_coequalizer_epi_comp {c : cofork f g} (i : is_colimit c) {W : C} (h : W ⟶ X) [hm : epi h] : is_colimit (cofork.of_π c.π (by simp) : cofork (h ≫ f) (h ≫ g)) := cofork.is_colimit.mk' _ $ λ s, let s' : cofork f g := cofork.of_π s.π (by apply hm.left_cancellation; simp_rw [←category.assoc, s.condition]) in let l := cofork.is_colimit.desc' i s'.π s'.condition in ⟨l.1, l.2, λ m hm,by apply cofork.is_colimit.hom_ext i; rw cofork.π_of_π at hm; rw hm; exact l.2.symm⟩ lemma has_coequalizer_epi_comp [has_coequalizer f g] {W : C} (h : W ⟶ X) [hm : epi h] : has_coequalizer (h ≫ f) (h ≫ g) := ⟨⟨{ cocone := _, is_colimit := is_coequalizer_epi_comp (colimit.is_colimit _) h }⟩⟩ variables (C f g) /-- A coequalizer of an idempotent morphism and the identity is split epi. -/ @[simps] def split_epi_of_idempotent_of_is_colimit_cofork {X : C} {f : X ⟶ X} (hf : f ≫ f = f) {c : cofork (𝟙 X) f} (i : is_colimit c) : split_epi c.π := { section_ := i.desc (cofork.of_π f (by simp [hf])), id' := begin letI := epi_of_is_colimit_cofork i, rw [← cancel_epi_id c.π, ← category.assoc, cofork.is_colimit.π_desc, cofork.π_of_π, ← c.condition], exact category.id_comp _, end } /-- The coequalizer of an idempotent morphism and the identity is split epi. -/ def split_epi_of_idempotent_coequalizer {X : C} {f : X ⟶ X} (hf : f ≫ f = f) [has_coequalizer (𝟙 X) f] : split_epi (coequalizer.π (𝟙 X) f) := split_epi_of_idempotent_of_is_colimit_cofork _ hf (colimit.is_colimit _) end category_theory.limits
831e3b45fdad65ec5e09036f51e2258b68f9886a
ac89c256db07448984849346288e0eeffe8b20d0
/stage0/src/Lean/Elab/Command.lean
56862a3ded4ea8726dfcccb76741be6579a9f1bf
[ "Apache-2.0" ]
permissive
chepinzhang/lean4
002cc667f35417a418f0ebc9cb4a44559bb0ccac
24fe2875c68549b5481f07c57eab4ad4a0ae5305
refs/heads/master
1,688,942,838,326
1,628,801,942,000
1,628,801,995,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
18,072
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.Parser.Command import Lean.ResolveName import Lean.Meta.Reduce import Lean.Elab.Log import Lean.Elab.Term import Lean.Elab.Binders import Lean.Elab.SyntheticMVars import Lean.Elab.DeclModifiers import Lean.Elab.InfoTree import Lean.Elab.SetOption namespace Lean.Elab.Command structure Scope where header : String opts : Options := {} currNamespace : Name := Name.anonymous openDecls : List OpenDecl := [] levelNames : List Name := [] /-- section variables as `bracketedBinder`s -/ varDecls : Array Syntax := #[] /-- Globally unique internal identifiers for the `varDecls` -/ varUIds : Array Name := #[] deriving Inhabited structure State where env : Environment messages : MessageLog := {} scopes : List Scope := [{ header := "" }] nextMacroScope : Nat := firstFrontendMacroScope + 1 maxRecDepth : Nat nextInstIdx : Nat := 1 -- for generating anonymous instance names ngen : NameGenerator := {} infoState : InfoState := {} traceState : TraceState := {} deriving Inhabited structure Context where fileName : String fileMap : FileMap currRecDepth : Nat := 0 cmdPos : String.Pos := 0 macroStack : MacroStack := [] currMacroScope : MacroScope := firstFrontendMacroScope ref : Syntax := Syntax.missing abbrev CommandElabCoreM (ε) := ReaderT Context $ StateRefT State $ EIO ε abbrev CommandElabM := CommandElabCoreM Exception abbrev CommandElab := Syntax → CommandElabM Unit abbrev Linter := Syntax → CommandElabM Unit -- Make the compiler generate specialized `pure`/`bind` so we do not have to optimize through the -- whole monad stack at every use site. May eventually be covered by `deriving`. instance : Monad CommandElabM := { inferInstanceAs (Monad CommandElabM) with } def mkState (env : Environment) (messages : MessageLog := {}) (opts : Options := {}) : State := { env := env messages := messages scopes := [{ header := "", opts := opts }] maxRecDepth := maxRecDepth.get opts } /- Linters should be loadable as plugins, so store in a global IO ref instead of an attribute managed by the environment (which only contains `import`ed objects). -/ builtin_initialize lintersRef : IO.Ref (Array Linter) ← IO.mkRef #[] def addLinter (l : Linter) : IO Unit := do let ls ← lintersRef.get lintersRef.set (ls.push l) instance : MonadInfoTree CommandElabM where getInfoState := return (← get).infoState modifyInfoState f := modify fun s => { s with infoState := f s.infoState } instance : MonadEnv CommandElabM where getEnv := do pure (← get).env modifyEnv f := modify fun s => { s with env := f s.env } instance : MonadOptions CommandElabM where getOptions := do pure (← get).scopes.head!.opts protected def getRef : CommandElabM Syntax := return (← read).ref instance : AddMessageContext CommandElabM where addMessageContext := addMessageContextPartial instance : MonadRef CommandElabM where getRef := Command.getRef withRef ref x := withReader (fun ctx => { ctx with ref := ref }) x instance : MonadTrace CommandElabM where getTraceState := return (← get).traceState modifyTraceState f := modify fun s => { s with traceState := f s.traceState } instance : AddErrorMessageContext CommandElabM where add ref msg := do let ctx ← read let ref := getBetterRef ref ctx.macroStack let msg ← addMessageContext msg let msg ← addMacroStack msg ctx.macroStack return (ref, msg) def mkMessageAux (ctx : Context) (ref : Syntax) (msgData : MessageData) (severity : MessageSeverity) : Message := mkMessageCore ctx.fileName ctx.fileMap msgData severity (ref.getPos?.getD ctx.cmdPos) private def mkCoreContext (ctx : Context) (s : State) (heartbeats : Nat) : Core.Context := let scope := s.scopes.head! { options := scope.opts currRecDepth := ctx.currRecDepth maxRecDepth := s.maxRecDepth ref := ctx.ref currNamespace := scope.currNamespace openDecls := scope.openDecls initHeartbeats := heartbeats } def liftCoreM {α} (x : CoreM α) : CommandElabM α := do let s ← get let ctx ← read let heartbeats ← IO.getNumHeartbeats (ε := Exception) let Eα := Except Exception α let x : CoreM Eα := try let a ← x; pure <| Except.ok a catch ex => pure <| Except.error ex let x : EIO Exception (Eα × Core.State) := (ReaderT.run x (mkCoreContext ctx s heartbeats)).run { env := s.env, ngen := s.ngen, traceState := s.traceState } let (ea, coreS) ← liftM x modify fun s => { s with env := coreS.env, ngen := coreS.ngen, traceState := coreS.traceState } match ea with | Except.ok a => pure a | Except.error e => throw e private def ioErrorToMessage (ctx : Context) (ref : Syntax) (err : IO.Error) : Message := let ref := getBetterRef ref ctx.macroStack mkMessageAux ctx ref (toString err) MessageSeverity.error @[inline] def liftEIO {α} (x : EIO Exception α) : CommandElabM α := liftM x @[inline] def liftIO {α} (x : IO α) : CommandElabM α := do let ctx ← read IO.toEIO (fun (ex : IO.Error) => Exception.error ctx.ref ex.toString) x instance : MonadLiftT IO CommandElabM where monadLift := liftIO def getScope : CommandElabM Scope := do pure (← get).scopes.head! instance : MonadResolveName CommandElabM where getCurrNamespace := return (← getScope).currNamespace getOpenDecls := return (← getScope).openDecls instance : MonadLog CommandElabM where getRef := getRef getFileMap := return (← read).fileMap getFileName := return (← read).fileName logMessage msg := do let currNamespace ← getCurrNamespace let openDecls ← getOpenDecls let msg := { msg with data := MessageData.withNamingContext { currNamespace := currNamespace, openDecls := openDecls } msg.data } modify fun s => { s with messages := s.messages.add msg } def runLinters (stx : Syntax) : CommandElabM Unit := do let linters ← lintersRef.get unless linters.isEmpty do for linter in linters do let savedState ← get try linter stx catch ex => logException ex finally modify fun s => { savedState with messages := s.messages } protected def getCurrMacroScope : CommandElabM Nat := do pure (← read).currMacroScope protected def getMainModule : CommandElabM Name := do pure (← getEnv).mainModule protected def withFreshMacroScope {α} (x : CommandElabM α) : CommandElabM α := do let fresh ← modifyGet (fun st => (st.nextMacroScope, { st with nextMacroScope := st.nextMacroScope + 1 })) withReader (fun ctx => { ctx with currMacroScope := fresh }) x instance : MonadQuotation CommandElabM where getCurrMacroScope := Command.getCurrMacroScope getMainModule := Command.getMainModule withFreshMacroScope := Command.withFreshMacroScope unsafe def mkCommandElabAttributeUnsafe : IO (KeyedDeclsAttribute CommandElab) := mkElabAttribute CommandElab `Lean.Elab.Command.commandElabAttribute `builtinCommandElab `commandElab `Lean.Parser.Command `Lean.Elab.Command.CommandElab "command" @[implementedBy mkCommandElabAttributeUnsafe] constant mkCommandElabAttribute : IO (KeyedDeclsAttribute CommandElab) builtin_initialize commandElabAttribute : KeyedDeclsAttribute CommandElab ← mkCommandElabAttribute private def addTraceAsMessagesCore (ctx : Context) (log : MessageLog) (traceState : TraceState) : MessageLog := traceState.traces.foldl (init := log) fun (log : MessageLog) traceElem => let ref := replaceRef traceElem.ref ctx.ref; let pos := ref.getPos?.getD 0; log.add (mkMessageCore ctx.fileName ctx.fileMap traceElem.msg MessageSeverity.information pos) private def addTraceAsMessages : CommandElabM Unit := do let ctx ← read modify fun s => { s with messages := addTraceAsMessagesCore ctx s.messages s.traceState traceState.traces := {} } private def mkInfoTree (elaborator : Name) (stx : Syntax) (trees : Std.PersistentArray InfoTree) : CommandElabM InfoTree := do let ctx ← read let s ← get let scope := s.scopes.head! let tree := InfoTree.node (Info.ofCommandInfo { elaborator, stx }) trees return InfoTree.context { env := s.env, fileMap := ctx.fileMap, mctx := {}, currNamespace := scope.currNamespace, openDecls := scope.openDecls, options := scope.opts } tree private def elabCommandUsing (s : State) (stx : Syntax) : List (KeyedDeclsAttribute.AttributeEntry CommandElab) → CommandElabM Unit | [] => throwError "unexpected syntax{indentD stx}" | (elabFn::elabFns) => catchInternalId unsupportedSyntaxExceptionId (withInfoTreeContext (mkInfoTree := mkInfoTree elabFn.decl stx) <| elabFn.value stx) (fun _ => do set s; elabCommandUsing s stx elabFns) /- Elaborate `x` with `stx` on the macro stack -/ def withMacroExpansion {α} (beforeStx afterStx : Syntax) (x : CommandElabM α) : CommandElabM α := withReader (fun ctx => { ctx with macroStack := { before := beforeStx, after := afterStx } :: ctx.macroStack }) x instance : MonadMacroAdapter CommandElabM where getCurrMacroScope := getCurrMacroScope getNextMacroScope := return (← get).nextMacroScope setNextMacroScope next := modify fun s => { s with nextMacroScope := next } instance : MonadRecDepth CommandElabM where withRecDepth d x := withReader (fun ctx => { ctx with currRecDepth := d }) x getRecDepth := return (← read).currRecDepth getMaxRecDepth := return (← get).maxRecDepth register_builtin_option showPartialSyntaxErrors : Bool := { defValue := false descr := "show elaboration errors from partial syntax trees (i.e. after parser recovery)" } def withLogging (x : CommandElabM Unit) : CommandElabM Unit := do try x catch ex => match ex with | Exception.error _ _ => logException ex | Exception.internal id _ => if isAbortExceptionId id then pure () else let idName ← liftIO <| id.getName; logError m!"internal exception {idName}" builtin_initialize registerTraceClass `Elab.command partial def elabCommand (stx : Syntax) : CommandElabM Unit := do withLogging <| withRef stx <| withIncRecDepth <| withFreshMacroScope do match stx with | Syntax.node k args => if k == nullKind then -- list of commands => elaborate in order -- The parser will only ever return a single command at a time, but syntax quotations can return multiple ones args.forM elabCommand else do trace `Elab.command fun _ => stx; let s ← get match (← liftMacroM <| expandMacroImpl? s.env stx) with | some (decl, stxNew) => withInfoTreeContext (mkInfoTree := mkInfoTree decl stx) do withMacroExpansion stx stxNew do elabCommand stxNew | _ => match commandElabAttribute.getEntries s.env k with | [] => throwError "elaboration function for '{k}' has not been implemented" | elabFns => elabCommandUsing s stx elabFns | _ => throwError "unexpected command" /-- `elabCommand` wrapper that should be used for the initial invocation, not for recursive calls after macro expansion etc. -/ def elabCommandTopLevel (stx : Syntax) : CommandElabM Unit := withRef stx do let initMsgs ← modifyGet fun st => (st.messages, { st with messages := {} }) let initInfoTrees ← getResetInfoTrees withLogging do runLinters stx -- We should *not* factor out `elabCommand`'s `withLogging` to here since it would make its error -- recovery more coarse. In particular, If `c` in `set_option ... in $c` fails, the remaining -- `end` command of the `in` macro would be skipped and the option would be leaked to the outside! elabCommand stx -- note the order: first process current messages & info trees, then add back old messages & trees, -- then convert new traces to messages let mut msgs ← (← get).messages -- `stx.hasMissing` should imply `initMsgs.hasErrors`, but the latter should be cheaper to check in general if !showPartialSyntaxErrors.get (← getOptions) && initMsgs.hasErrors && stx.hasMissing then -- discard elaboration errors, except for a few important and unlikely misleading ones, on parse error msgs := ⟨msgs.msgs.filter fun msg => msg.data.hasTag `Elab.synthPlaceholder || msg.data.hasTag `Tactic.unsolvedGoals⟩ for tree in (← getInfoTrees) do trace[Elab.info] (← tree.format) modify fun st => { st with messages := initMsgs ++ msgs infoState := { st.infoState with trees := initInfoTrees ++ st.infoState.trees } } addTraceAsMessages /-- Adapt a syntax transformation to a regular, command-producing elaborator. -/ def adaptExpander (exp : Syntax → CommandElabM Syntax) : CommandElab := fun stx => do let stx' ← exp stx withMacroExpansion stx stx' <| elabCommand stx' private def getVarDecls (s : State) : Array Syntax := s.scopes.head!.varDecls instance {α} : Inhabited (CommandElabM α) where default := throw arbitrary private def mkMetaContext : Meta.Context := { config := { foApprox := true, ctxApprox := true, quasiPatternApprox := true } } def getBracketedBinderIds : Syntax → Array Name | `(bracketedBinder|($ids* $[: $ty?]? $(annot?)?)) => ids.map Syntax.getId | `(bracketedBinder|{$ids* $[: $ty?]?}) => ids.map Syntax.getId | `(bracketedBinder|[$id : $ty]) => #[id.getId] | `(bracketedBinder|[$ty]) => #[Name.anonymous] | _ => #[] private def mkTermContext (ctx : Context) (s : State) (declName? : Option Name) : Term.Context := do let scope := s.scopes.head! let mut sectionVars := {} for id in scope.varDecls.concatMap getBracketedBinderIds, uid in scope.varUIds do sectionVars := sectionVars.insert id uid { macroStack := ctx.macroStack fileName := ctx.fileName fileMap := ctx.fileMap currMacroScope := ctx.currMacroScope declName? := declName? sectionVars := sectionVars } private def mkTermState (scope : Scope) (s : State) : Term.State := { messages := {} levelNames := scope.levelNames infoState.enabled := s.infoState.enabled } def liftTermElabM {α} (declName? : Option Name) (x : TermElabM α) : CommandElabM α := do let ctx ← read let s ← get let heartbeats ← IO.getNumHeartbeats (ε := Exception) -- dbg_trace "heartbeats: {heartbeats}" let scope := s.scopes.head! -- We execute `x` with an empty message log. Thus, `x` cannot modify/view messages produced by previous commands. -- This is useful for implementing `runTermElabM` where we use `Term.resetMessageLog` let x : TermElabM _ := withSaveInfoContext x let x : MetaM _ := (observing x).run (mkTermContext ctx s declName?) (mkTermState scope s) let x : CoreM _ := x.run mkMetaContext {} let x : EIO _ _ := x.run (mkCoreContext ctx s heartbeats) { env := s.env, ngen := s.ngen, nextMacroScope := s.nextMacroScope } let (((ea, termS), metaS), coreS) ← liftEIO x modify fun s => { s with env := coreS.env messages := addTraceAsMessagesCore ctx (s.messages ++ termS.messages) coreS.traceState nextMacroScope := coreS.nextMacroScope ngen := coreS.ngen infoState.trees := s.infoState.trees.append termS.infoState.trees } match ea with | Except.ok a => pure a | Except.error ex => throw ex @[inline] def runTermElabM {α} (declName? : Option Name) (elabFn : Array Expr → TermElabM α) : CommandElabM α := do let scope ← getScope liftTermElabM declName? <| Term.withAutoBoundImplicit <| Term.elabBinders scope.varDecls fun xs => do -- We need to synthesize postponed terms because this is a checkpoint for the auto-bound implicit feature -- If we don't use this checkpoint here, then auto-bound implicits in the postponed terms will not be handled correctly. Term.synthesizeSyntheticMVarsNoPostponing let mut sectionFVars := {} for uid in scope.varUIds, x in xs do sectionFVars := sectionFVars.insert uid x withReader ({ · with sectionFVars := sectionFVars }) do -- We don't want to store messages produced when elaborating `(getVarDecls s)` because they have already been saved when we elaborated the `variable`(s) command. -- So, we use `Term.resetMessageLog`. Term.resetMessageLog let xs ← Term.addAutoBoundImplicits xs Term.withoutAutoBoundImplicit <| elabFn xs @[inline] def catchExceptions (x : CommandElabM Unit) : CommandElabCoreM Empty Unit := fun ctx ref => EIO.catchExceptions (withLogging x ctx ref) (fun _ => pure ()) private def liftAttrM {α} (x : AttrM α) : CommandElabM α := do liftCoreM x def getScopes : CommandElabM (List Scope) := do pure (← get).scopes def modifyScope (f : Scope → Scope) : CommandElabM Unit := modify fun s => { s with scopes := match s.scopes with | h::t => f h :: t | [] => unreachable! } def getLevelNames : CommandElabM (List Name) := return (← getScope).levelNames def addUnivLevel (idStx : Syntax) : CommandElabM Unit := withRef idStx do let id := idStx.getId let levelNames ← getLevelNames if levelNames.elem id then throwAlreadyDeclaredUniverseLevel id else modifyScope fun scope => { scope with levelNames := id :: scope.levelNames } def expandDeclId (declId : Syntax) (modifiers : Modifiers) : CommandElabM ExpandDeclIdResult := do let currNamespace ← getCurrNamespace let currLevelNames ← getLevelNames Lean.Elab.expandDeclId currNamespace currLevelNames declId modifiers end Elab.Command export Elab.Command (Linter addLinter) end Lean
75004af22ca0771dab5eb240c5501c525366fdad
4727251e0cd73359b15b664c3170e5d754078599
/src/data/polynomial/mirror.lean
80ef0a75e54834a232c24402bd213a66f1871095
[ "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
7,043
lean
/- Copyright (c) 2020 Thomas Browning. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Thomas Browning -/ import data.polynomial.ring_division /-! # "Mirror" of a univariate polynomial In this file we define `polynomial.mirror`, a variant of `polynomial.reverse`. The difference between `reverse` and `mirror` is that `reverse` will decrease the degree if the polynomial is divisible by `X`. ## Main definitions - `polynomial.mirror` ## Main results - `polynomial.mirror_mul_of_domain`: `mirror` preserves multiplication. - `polynomial.irreducible_of_mirror`: an irreducibility criterion involving `mirror` -/ namespace polynomial open_locale polynomial variables {R : Type*} [semiring R] (p : R[X]) section mirror /-- mirror of a polynomial: reverses the coefficients while preserving `polynomial.nat_degree` -/ noncomputable def mirror := p.reverse * X ^ p.nat_trailing_degree @[simp] lemma mirror_zero : (0 : R[X]).mirror = 0 := by simp [mirror] lemma mirror_monomial (n : ℕ) (a : R) : (monomial n a).mirror = (monomial n a) := begin classical, by_cases ha : a = 0, { rw [ha, monomial_zero_right, mirror_zero] }, { rw [mirror, reverse, nat_degree_monomial n a, if_neg ha, nat_trailing_degree_monomial ha, ←C_mul_X_pow_eq_monomial, reflect_C_mul_X_pow, rev_at_le (le_refl n), tsub_self, pow_zero, mul_one] }, end lemma mirror_C (a : R) : (C a).mirror = C a := mirror_monomial 0 a lemma mirror_X : X.mirror = (X : R[X]) := mirror_monomial 1 (1 : R) lemma mirror_nat_degree : p.mirror.nat_degree = p.nat_degree := begin by_cases hp : p = 0, { rw [hp, mirror_zero] }, nontriviality R, rw [mirror, nat_degree_mul', reverse_nat_degree, nat_degree_X_pow, tsub_add_cancel_of_le p.nat_trailing_degree_le_nat_degree], rwa [leading_coeff_X_pow, mul_one, reverse_leading_coeff, ne, trailing_coeff_eq_zero] end lemma mirror_nat_trailing_degree : p.mirror.nat_trailing_degree = p.nat_trailing_degree := begin by_cases hp : p = 0, { rw [hp, mirror_zero] }, { rw [mirror, nat_trailing_degree_mul_X_pow ((mt reverse_eq_zero.mp) hp), reverse_nat_trailing_degree, zero_add] }, end lemma coeff_mirror (n : ℕ) : p.mirror.coeff n = p.coeff (rev_at (p.nat_degree + p.nat_trailing_degree) n) := begin by_cases h2 : p.nat_degree < n, { rw [coeff_eq_zero_of_nat_degree_lt (by rwa mirror_nat_degree)], by_cases h1 : n ≤ p.nat_degree + p.nat_trailing_degree, { rw [rev_at_le h1, coeff_eq_zero_of_lt_nat_trailing_degree], exact (tsub_lt_iff_left h1).mpr (nat.add_lt_add_right h2 _) }, { rw [←rev_at_fun_eq, rev_at_fun, if_neg h1, coeff_eq_zero_of_nat_degree_lt h2] } }, rw not_lt at h2, rw [rev_at_le (h2.trans (nat.le_add_right _ _))], by_cases h3 : p.nat_trailing_degree ≤ n, { rw [←tsub_add_eq_add_tsub h2, ←tsub_tsub_assoc h2 h3, mirror, coeff_mul_X_pow', if_pos h3, coeff_reverse, rev_at_le (tsub_le_self.trans h2)] }, rw not_le at h3, rw coeff_eq_zero_of_nat_degree_lt (lt_tsub_iff_right.mpr (nat.add_lt_add_left h3 _)), exact coeff_eq_zero_of_lt_nat_trailing_degree (by rwa mirror_nat_trailing_degree), end --TODO: Extract `finset.sum_range_rev_at` lemma. lemma mirror_eval_one : p.mirror.eval 1 = p.eval 1 := begin simp_rw [eval_eq_sum_range, one_pow, mul_one, mirror_nat_degree], refine finset.sum_bij_ne_zero _ _ _ _ _, { exact λ n hn hp, rev_at (p.nat_degree + p.nat_trailing_degree) n }, { intros n hn hp, rw finset.mem_range_succ_iff at *, rw rev_at_le (hn.trans (nat.le_add_right _ _)), rw [tsub_le_iff_tsub_le, add_comm, add_tsub_cancel_right, ←mirror_nat_trailing_degree], exact nat_trailing_degree_le_of_ne_zero hp }, { exact λ n₁ n₂ hn₁ hp₁ hn₂ hp₂ h, by rw [←@rev_at_invol _ n₁, h, rev_at_invol] }, { intros n hn hp, use rev_at (p.nat_degree + p.nat_trailing_degree) n, refine ⟨_, _, rev_at_invol.symm⟩, { rw finset.mem_range_succ_iff at *, rw rev_at_le (hn.trans (nat.le_add_right _ _)), rw [tsub_le_iff_tsub_le, add_comm, add_tsub_cancel_right], exact nat_trailing_degree_le_of_ne_zero hp }, { change p.mirror.coeff _ ≠ 0, rwa [coeff_mirror, rev_at_invol] } }, { exact λ n hn hp, p.coeff_mirror n }, end lemma mirror_mirror : p.mirror.mirror = p := polynomial.ext (λ n, by rw [coeff_mirror, coeff_mirror, mirror_nat_degree, mirror_nat_trailing_degree, rev_at_invol]) lemma mirror_eq_zero : p.mirror = 0 ↔ p = 0 := ⟨λ h, by rw [←p.mirror_mirror, h, mirror_zero], λ h, by rw [h, mirror_zero]⟩ lemma mirror_trailing_coeff : p.mirror.trailing_coeff = p.leading_coeff := by rw [leading_coeff, trailing_coeff, mirror_nat_trailing_degree, coeff_mirror, rev_at_le (nat.le_add_left _ _), add_tsub_cancel_right] lemma mirror_leading_coeff : p.mirror.leading_coeff = p.trailing_coeff := by rw [←p.mirror_mirror, mirror_trailing_coeff, p.mirror_mirror] lemma mirror_mul_of_domain {R : Type*} [ring R] [is_domain R] (p q : R[X]) : (p * q).mirror = p.mirror * q.mirror := begin by_cases hp : p = 0, { rw [hp, zero_mul, mirror_zero, zero_mul] }, by_cases hq : q = 0, { rw [hq, mul_zero, mirror_zero, mul_zero] }, rw [mirror, mirror, mirror, reverse_mul_of_domain, nat_trailing_degree_mul hp hq, pow_add], rw [mul_assoc, ←mul_assoc q.reverse], conv_lhs { congr, skip, congr, rw [←X_pow_mul] }, repeat { rw [mul_assoc], }, end lemma mirror_smul {R : Type*} [ring R] [is_domain R] (p : R[X]) (a : R) : (a • p).mirror = a • p.mirror := by rw [←C_mul', ←C_mul', mirror_mul_of_domain, mirror_C] lemma mirror_neg {R : Type*} [ring R] (p : R[X]) : (-p).mirror = -(p.mirror) := by rw [mirror, mirror, reverse_neg, nat_trailing_degree_neg, neg_mul_eq_neg_mul] lemma irreducible_of_mirror {R : Type*} [comm_ring R] [is_domain R] {f : R[X]} (h1 : ¬ is_unit f) (h2 : ∀ k, f * f.mirror = k * k.mirror → k = f ∨ k = -f ∨ k = f.mirror ∨ k = -f.mirror) (h3 : ∀ g, g ∣ f → g ∣ f.mirror → is_unit g) : irreducible f := begin split, { exact h1 }, { intros g h fgh, let k := g * h.mirror, have key : f * f.mirror = k * k.mirror, { rw [fgh, mirror_mul_of_domain, mirror_mul_of_domain, mirror_mirror, mul_assoc, mul_comm h, mul_comm g.mirror, mul_assoc, ←mul_assoc] }, have g_dvd_f : g ∣ f, { rw fgh, exact dvd_mul_right g h }, have h_dvd_f : h ∣ f, { rw fgh, exact dvd_mul_left h g }, have g_dvd_k : g ∣ k, { exact dvd_mul_right g h.mirror }, have h_dvd_k_rev : h ∣ k.mirror, { rw [mirror_mul_of_domain, mirror_mirror], exact dvd_mul_left h g.mirror }, have hk := h2 k key, rcases hk with hk | hk | hk | hk, { exact or.inr (h3 h h_dvd_f (by rwa ← hk)) }, { exact or.inr (h3 h h_dvd_f (by rwa [eq_neg_iff_eq_neg.mp hk, mirror_neg, dvd_neg])) }, { exact or.inl (h3 g g_dvd_f (by rwa ← hk)) }, { exact or.inl (h3 g g_dvd_f (by rwa [eq_neg_iff_eq_neg.mp hk, dvd_neg])) } }, end end mirror end polynomial
e6b7465876683511af14023e6d21e7f10acb1ec4
e61a235b8468b03aee0120bf26ec615c045005d2
/stage0/src/Init/Lean/Elab/App.lean
e8598022d4b882b65b97ae2dd304bfd1cbdb3314
[ "Apache-2.0" ]
permissive
SCKelemen/lean4
140dc63a80539f7c61c8e43e1c174d8500ec3230
e10507e6615ddbef73d67b0b6c7f1e4cecdd82bc
refs/heads/master
1,660,973,595,917
1,590,278,033,000
1,590,278,033,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
29,221
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Lean.Util.FindMVar import Init.Lean.Elab.Term import Init.Lean.Elab.Binders namespace Lean namespace Elab namespace Term /-- 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 Arg.inhabited : Inhabited Arg := ⟨Arg.stx (arbitrary _)⟩ instance Arg.hasToString : HasToString Arg := ⟨fun arg => match arg with | Arg.stx val => toString val | Arg.expr val => toString val⟩ /-- Named arguments created using the notation `(x := val)` -/ structure NamedArg := (name : Name) (val : Arg) instance NamedArg.hasToString : HasToString NamedArg := ⟨fun s => "(" ++ toString s.name ++ " := " ++ toString s.val ++ ")"⟩ instance NamedArg.inhabited : Inhabited NamedArg := ⟨{ name := arbitrary _, val := arbitrary _ }⟩ /-- Add a new named argument to `namedArgs`, and throw an error if it already contains a named argument with the same name. -/ def addNamedArg (ref : Syntax) (namedArgs : Array NamedArg) (namedArg : NamedArg) : TermElabM (Array NamedArg) := do when (namedArgs.any $ fun namedArg' => namedArg.name == namedArg'.name) $ throwError ref ("argument '" ++ toString namedArg.name ++ "' was already set"); pure $ namedArgs.push namedArg def synthesizeAppInstMVars (ref : Syntax) (instMVars : Array MVarId) : TermElabM Unit := instMVars.forM $ fun mvarId => unlessM (synthesizeInstMVarCore ref mvarId) $ registerSyntheticMVar ref mvarId SyntheticMVarKind.typeClass private def ensureArgType (ref : Syntax) (f : Expr) (arg : Expr) (expectedType : Expr) : TermElabM Expr := do argType ← inferType ref arg; ensureHasTypeAux ref expectedType argType arg f private def elabArg (ref : Syntax) (f : Expr) (arg : Arg) (expectedType : Expr) : TermElabM Expr := match arg with | Arg.expr val => ensureArgType ref f val expectedType | Arg.stx val => do val ← elabTerm val expectedType; ensureArgType ref f val expectedType private def mkArrow (d b : Expr) : TermElabM Expr := do n ← mkFreshAnonymousName; pure $ Lean.mkForall n BinderInfo.default d b /- Relevant definitions: ``` class CoeFun (α : Sort u) (γ : α → outParam (Sort v)) abbrev coeFun {α : Sort u} {γ : α → Sort v} (a : α) [CoeFun α γ] : γ a ``` -/ private def tryCoeFun (ref : Syntax) (α : Expr) (a : Expr) : TermElabM Expr := do v ← mkFreshLevelMVar ref; type ← mkArrow α (mkSort v); γ ← mkFreshExprMVar ref type; u ← getLevel ref α; let coeFunInstType := mkAppN (Lean.mkConst `CoeFun [u, v]) #[α, γ]; mvar ← mkFreshExprMVar ref coeFunInstType MetavarKind.synthetic; let mvarId := mvar.mvarId!; synthesized ← catch (withoutMacroStackAtErr $ synthesizeInstMVarCore ref mvarId) (fun ex => match ex with | Exception.ex (Elab.Exception.error errMsg) => throwError ref ("function expected" ++ Format.line ++ errMsg.data) | _ => throwError ref "function expected"); if synthesized then pure $ mkAppN (Lean.mkConst `coeFun [u, v]) #[α, γ, a, mvar] else throwError ref "function expected" /-- Auxiliary structure used to elaborate function application arguments. -/ structure ElabAppArgsCtx := (ref : Syntax) (args : Array Arg) (expectedType? : Option Expr) (explicit : Bool) -- if true, all arguments are treated as explicit (argIdx : Nat := 0) -- position of next explicit argument to be processed (namedArgs : Array NamedArg) -- remaining named arguments to be processed (instMVars : Array MVarId := #[]) -- metavariables for the instance implicit arguments that have already been processed (typeMVars : Array MVarId := #[]) -- metavariables for implicit arguments of the form `{α : Sort u}` that have already been processed (foundExplicit : Bool := false) -- true if an explicit argument has already been processed /- Auxiliary function for retrieving the resulting type of a function application. See `propagateExpectedType`. -/ private partial def getForallBody : Nat → Array NamedArg → Expr → Option Expr | i, namedArgs, type@(Expr.forallE n d b c) => match namedArgs.findIdx? (fun namedArg => namedArg.name == n) with | some idx => getForallBody i (namedArgs.eraseIdx idx) 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 | i, namedArgs, type => if i == 0 && namedArgs.isEmpty then some type else none private def hasTypeMVar (ctx : ElabAppArgsCtx) (type : Expr) : Bool := (type.findMVar? (fun mvarId => ctx.typeMVars.contains mvarId)).isSome private def hasOnlyTypeMVar (ctx : ElabAppArgsCtx) (type : Expr) : Bool := (type.findMVar? (fun mvarId => !ctx.typeMVars.contains mvarId)).isNone /- 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 HasAdd.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 (ctx : ElabAppArgsCtx) (eType : Expr) : TermElabM Unit := unless (ctx.explicit || ctx.foundExplicit || ctx.typeMVars.isEmpty) $ do match ctx.expectedType? with | none => pure () | some expectedType => let numRemainingArgs := ctx.args.size - ctx.argIdx; match getForallBody numRemainingArgs ctx.namedArgs eType with | none => pure () | some eTypeBody => unless eTypeBody.hasLooseBVars $ when (hasTypeMVar ctx eTypeBody && hasOnlyTypeMVar ctx eTypeBody) $ do _ ← isDefEq ctx.ref expectedType eTypeBody; pure () private def nextArgIsHole (ctx : ElabAppArgsCtx) : Bool := if h : ctx.argIdx < ctx.args.size then match ctx.args.get ⟨ctx.argIdx, h⟩ with | Arg.stx (Syntax.node `Lean.Parser.Term.hole _) => true | _ => false else false /- Elaborate function application arguments. -/ private partial def elabAppArgsAux : ElabAppArgsCtx → Expr → Expr → TermElabM Expr | ctx, e, eType => do let finalize : Unit → TermElabM Expr := fun _ => do { -- all user explicit arguments have been consumed trace `Elab.app.finalize ctx.ref $ fun _ => e; match ctx.expectedType? with | none => pure () | some expectedType => do { -- Try to propagate expected type. Ignore if types are not definitionally equal, caller must handle it. _ ← isDefEq ctx.ref expectedType eType; pure () }; synthesizeAppInstMVars ctx.ref ctx.instMVars; pure e }; eType ← whnfForall ctx.ref eType; match eType with | Expr.forallE n d b c => match ctx.namedArgs.findIdx? (fun namedArg => namedArg.name == n) with | some idx => do let arg := ctx.namedArgs.get! idx; let namedArgs := ctx.namedArgs.eraseIdx idx; argElab ← elabArg ctx.ref e arg.val d; propagateExpectedType ctx eType; elabAppArgsAux { ctx with foundExplicit := true, namedArgs := namedArgs } (mkApp e argElab) (b.instantiate1 argElab) | none => let processExplictArg : Unit → TermElabM Expr := fun _ => do { propagateExpectedType ctx eType; let ctx := { ctx with foundExplicit := true }; if h : ctx.argIdx < ctx.args.size then do argElab ← elabArg ctx.ref e (ctx.args.get ⟨ctx.argIdx, h⟩) d; elabAppArgsAux { ctx with argIdx := ctx.argIdx + 1 } (mkApp e argElab) (b.instantiate1 argElab) else match ctx.explicit, d.getOptParamDefault?, d.getAutoParamTactic? with | false, some defVal, _ => elabAppArgsAux ctx (mkApp e defVal) (b.instantiate1 defVal) | false, _, some (Expr.const tacticDecl _ _) => do env ← getEnv; match evalSyntaxConstant env tacticDecl with | Except.error err => throwError ctx.ref err | Except.ok tacticSyntax => do tacticBlock ← `(begin $(tacticSyntax.getArgs)* end); -- tacticBlock does not have any position information -- use ctx.ref.getHeadInfo if available let tacticBlock := match ctx.ref.getHeadInfo with | some info => tacticBlock.replaceInfo info | _ => tacticBlock; let d := d.getArg! 0; -- `autoParam type := by tactic` ==> `type` argElab ← elabArg ctx.ref e (Arg.stx tacticBlock) d; elabAppArgsAux ctx (mkApp e argElab) (b.instantiate1 argElab) | false, _, some _ => throwError ctx.ref "invalid autoParam, argument must be a constant" | _, _, _ => if ctx.namedArgs.isEmpty then finalize () else throwError ctx.ref ("explicit parameter '" ++ n ++ "' is missing, unused named arguments " ++ toString (ctx.namedArgs.map $ fun narg => narg.name)) }; match c.binderInfo with | BinderInfo.implicit => if ctx.explicit then processExplictArg () else do a ← mkFreshExprMVar ctx.ref d; typeMVars ← condM (isTypeFormer ctx.ref a) (pure $ ctx.typeMVars.push a.mvarId!) (pure ctx.typeMVars); elabAppArgsAux { ctx with typeMVars := typeMVars } (mkApp e a) (b.instantiate1 a) | BinderInfo.instImplicit => if ctx.explicit && nextArgIsHole ctx then do /- Recall that if '@' has been used, and the argument is '_', then we still use type class resolution -/ a ← mkFreshExprMVar ctx.ref d MetavarKind.synthetic; elabAppArgsAux { ctx with argIdx := ctx.argIdx + 1, instMVars := ctx.instMVars.push a.mvarId! } (mkApp e a) (b.instantiate1 a) else if ctx.explicit then processExplictArg () else do a ← mkFreshExprMVar ctx.ref d MetavarKind.synthetic; elabAppArgsAux { ctx with instMVars := ctx.instMVars.push a.mvarId! } (mkApp e a) (b.instantiate1 a) | _ => processExplictArg () | _ => if ctx.namedArgs.isEmpty && ctx.argIdx == ctx.args.size then finalize () else do e ← tryCoeFun ctx.ref eType e; eType ← inferType ctx.ref e; elabAppArgsAux ctx e eType private def elabAppArgs (ref : Syntax) (f : Expr) (namedArgs : Array NamedArg) (args : Array Arg) (expectedType? : Option Expr) (explicit : Bool) : TermElabM Expr := do fType ← inferType ref f; fType ← instantiateMVars ref fType; trace `Elab.app.args ref $ fun _ => "explicit: " ++ toString explicit ++ ", " ++ f ++ " : " ++ fType; unless (namedArgs.isEmpty && args.isEmpty) $ tryPostponeIfMVar fType; elabAppArgsAux {ref := ref, args := args, expectedType? := expectedType?, explicit := explicit, namedArgs := namedArgs } f 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 (baseName : Name) (constName : Name) | localRec (baseName : Name) (fullName : Name) (fvar : Expr) | getOp (fullName : Name) (idx : Syntax) private def throwLValError {α} (ref : Syntax) (e : Expr) (eType : Expr) (msg : MessageData) : TermElabM α := throwError ref $ msg ++ indentExpr e ++ Format.line ++ "has type" ++ indentExpr eType private def resolveLValAux (ref : Syntax) (e : Expr) (eType : Expr) (lval : LVal) : TermElabM LValResolution := match eType.getAppFn, lval with | Expr.const structName _ _, LVal.fieldIdx idx => do when (idx == 0) $ throwError ref "invalid projection, index must be greater than 0"; env ← getEnv; unless (isStructureLike env structName) $ throwLValError ref 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 ref e eType ("invalid projection, structure has only " ++ toString fieldNames.size ++ " field(s)") | Expr.const structName _ _, LVal.fieldName fieldName => do env ← getEnv; let searchEnv (fullName : Name) : TermElabM LValResolution := do { match env.find? fullName with | some _ => pure $ LValResolution.const structName fullName | none => let fullNamePrv := mkPrivateName env fullName; match env.find? fullNamePrv with | some _ => pure $ LValResolution.const structName fullNamePrv | none => throwLValError ref e eType $ "invalid field notation, '" ++ fieldName ++ "' is not a valid \"field\" because environment does not contain '" ++ fullName ++ "'" }; -- search local context first, then environment let searchCtx : Unit → TermElabM LValResolution := fun _ => do { let fullName := structName ++ fieldName; currNamespace ← getCurrNamespace; let localName := fullName.replacePrefix currNamespace Name.anonymous; 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 fullName | none => searchEnv fullName }; if isStructure env structName then match findField? env structName fieldName with | some baseStructName => pure $ LValResolution.projFn baseStructName structName fieldName | none => searchCtx () else searchCtx () | Expr.const structName _ _, LVal.getOp idx => do env ← getEnv; let fullName := mkNameStr structName "getOp"; match env.find? fullName with | some _ => pure $ LValResolution.getOp fullName idx | none => throwLValError ref e eType $ "invalid [..] notation because environment does not contain '" ++ fullName ++ "'" | _, LVal.getOp idx => throwLValError ref e eType "invalid [..] notation, type is not of the form (C ...) where C is a constant" | _, _ => throwLValError ref e eType "invalid field notation, type is not of the form (C ...) where C is a constant" private partial def resolveLValLoop (ref : Syntax) (e : Expr) (lval : LVal) : Expr → Array Message → TermElabM LValResolution | eType, previousExceptions => do eType ← whnfCore ref eType; tryPostponeIfMVar eType; catch (resolveLValAux ref e eType lval) (fun ex => match ex with | Exception.postpone => throw ex | Exception.ex Elab.Exception.unsupportedSyntax => throw ex | Exception.ex (Elab.Exception.error errMsg) => do eType? ← unfoldDefinition? ref eType; match eType? with | some eType => resolveLValLoop eType (previousExceptions.push errMsg) | none => do previousExceptions.forM $ fun ex => logMessage errMsg; throw (Exception.ex (Elab.Exception.error errMsg))) private def resolveLVal (ref : Syntax) (e : Expr) (lval : LVal) : TermElabM LValResolution := do eType ← inferType ref e; resolveLValLoop ref e lval eType #[] private partial def mkBaseProjections (ref : Syntax) (baseStructName : Name) (structName : Name) (e : Expr) : TermElabM Expr := do env ← getEnv; match getPathToBaseStructure? env baseStructName structName with | none => throwError ref "failed to access field in parent structure" | some path => path.foldlM (fun e projFunName => do projFn ← mkConst ref projFunName; elabAppArgs ref projFn #[{ name := `self, val := Arg.expr e }] #[] none false) 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 (ref : Syntax) (baseName : Name) (fullName : Name) (e : Expr) (args : Array Arg) : Nat → Array NamedArg → Expr → TermElabM (Array Arg) | i, namedArgs, Expr.forallE n d b c => if !c.binderInfo.isExplicit then addLValArg i namedArgs b else /- If there is named argument with name `n`, then we should skip. -/ match namedArgs.findIdx? (fun namedArg => namedArg.name == n) with | some idx => do let namedArgs := namedArgs.eraseIdx idx; addLValArg i namedArgs b | none => do if d.consumeMData.isAppOf baseName then pure $ args.insertAt i (Arg.expr e) else if i < args.size then addLValArg (i+1) namedArgs b else throwError ref $ "invalid field notation, insufficient number of arguments for '" ++ fullName ++ "'" | _, _, fType => throwError ref $ "invalid field notation, function '" ++ fullName ++ "' does not have explicit argument with type (" ++ baseName ++ " ...)" private def elabAppLValsAux (ref : Syntax) (namedArgs : Array NamedArg) (args : Array Arg) (expectedType? : Option Expr) (explicit : Bool) : Expr → List LVal → TermElabM Expr | f, [] => elabAppArgs ref f namedArgs args expectedType? explicit | f, lval::lvals => do lvalRes ← resolveLVal ref f lval; match lvalRes with | LValResolution.projIdx structName idx => let f := mkProj structName idx f; elabAppLValsAux f lvals | LValResolution.projFn baseStructName structName fieldName => do f ← mkBaseProjections ref baseStructName structName f; projFn ← mkConst ref (baseStructName ++ fieldName); if lvals.isEmpty then do namedArgs ← addNamedArg ref namedArgs { name := `self, val := Arg.expr f }; elabAppArgs ref projFn namedArgs args expectedType? explicit else do f ← elabAppArgs ref projFn #[{ name := `self, val := Arg.expr f }] #[] none false; elabAppLValsAux f lvals | LValResolution.const baseName constName => do projFn ← mkConst ref constName; if lvals.isEmpty then do projFnType ← inferType ref projFn; args ← addLValArg ref baseName constName f args 0 namedArgs projFnType; elabAppArgs ref projFn namedArgs args expectedType? explicit else do f ← elabAppArgs ref projFn #[] #[Arg.expr f] none false; elabAppLValsAux f lvals | LValResolution.localRec baseName fullName fvar => if lvals.isEmpty then do fvarType ← inferType ref fvar; args ← addLValArg ref baseName fullName f args 0 namedArgs fvarType; elabAppArgs ref fvar namedArgs args expectedType? explicit else do f ← elabAppArgs ref fvar #[] #[Arg.expr f] none false; elabAppLValsAux f lvals | LValResolution.getOp fullName idx => do getOpFn ← mkConst ref fullName; if lvals.isEmpty then do namedArgs ← addNamedArg ref namedArgs { name := `self, val := Arg.expr f }; namedArgs ← addNamedArg ref namedArgs { name := `idx, val := Arg.stx idx }; elabAppArgs ref getOpFn namedArgs args expectedType? explicit else do f ← elabAppArgs ref getOpFn #[{ name := `self, val := Arg.expr f }, { name := `idx, val := Arg.stx idx }] #[] none false; elabAppLValsAux f lvals private def elabAppLVals (ref : Syntax) (f : Expr) (lvals : List LVal) (namedArgs : Array NamedArg) (args : Array Arg) (expectedType? : Option Expr) (explicit : Bool) : TermElabM Expr := do when (!lvals.isEmpty && explicit) $ throwError ref "invalid use of field notation with `@` modifier"; elabAppLValsAux ref namedArgs args expectedType? explicit f lvals def elabExplicitUniv (stx : Syntax) : TermElabM (List Level) := do let lvls := stx.getArg 1; lvls.foldSepRevArgsM (fun stx lvls => do lvl ← elabLevel stx; pure (lvl::lvls)) [] private partial def elabAppFnId (ref : Syntax) (fIdent : Syntax) (fExplicitUnivs : List Level) (lvals : List LVal) (namedArgs : Array NamedArg) (args : Array Arg) (expectedType? : Option Expr) (explicit : Bool) (acc : Array TermElabResult) : TermElabM (Array TermElabResult) := match fIdent with | Syntax.ident _ _ n preresolved => do funLVals ← resolveName fIdent n preresolved fExplicitUnivs; funLVals.foldlM (fun acc ⟨f, fields⟩ => do let lvals' := fields.map LVal.fieldName; s ← observing $ elabAppLVals ref f (lvals' ++ lvals) namedArgs args expectedType? explicit; pure $ acc.push s) acc | _ => throwUnsupportedSyntax private partial def elabAppFn (ref : Syntax) : Syntax → List LVal → Array NamedArg → Array Arg → Option Expr → Bool → Array TermElabResult → TermElabM (Array TermElabResult) | f, lvals, namedArgs, args, expectedType?, explicit, acc => if f.isIdent then -- A raw identifier is not a valid Term. Recall that `Term.id` is defined as `parser! ident >> optional (explicitUniv <|> namedPattern)` -- We handle it here to make macro development more comfortable. elabAppFnId ref f [] lvals namedArgs args expectedType? explicit acc else if f.getKind == choiceKind then f.getArgs.foldlM (fun acc f => elabAppFn f lvals namedArgs args expectedType? explicit 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 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 acc | `($e[$idx]) => elabAppFn e (LVal.getOp idx :: lvals) namedArgs args expectedType? explicit acc | `($id:ident$us:explicitUniv*) => do -- Remark: `id.<namedPattern>` should already have been expanded us ← if us.isEmpty then pure [] else elabExplicitUniv (us.get! 0); elabAppFnId ref id us lvals namedArgs args expectedType? explicit acc | `(@$id:id) => elabAppFn id lvals namedArgs args expectedType? true acc | `(@$t) => throwUnsupportedSyntax -- invalid occurrence of `@` | _ => do s ← observing $ do { f ← elabTerm f none; elabAppLVals ref f lvals namedArgs args expectedType? explicit }; pure $ acc.push s private def getSuccess (candidates : Array TermElabResult) : Array TermElabResult := candidates.filter $ fun c => match c with | EStateM.Result.ok _ _ => true | _ => false private def toMessageData (msg : Message) (stx : Syntax) : TermElabM MessageData := do strPos ← getPos stx; pos ← getPosition strPos; if pos == msg.pos then pure msg.data else pure $ toString msg.pos.line ++ ":" ++ toString msg.pos.column ++ " " ++ msg.data private def mergeFailures {α} (failures : Array TermElabResult) (stx : Syntax) : TermElabM α := do msgs ← failures.mapM $ fun failure => match failure with | EStateM.Result.ok _ _ => unreachable! | EStateM.Result.error errMsg s => toMessageData errMsg stx; throwError stx ("overloaded, errors " ++ MessageData.ofArray msgs) private def elabAppAux (ref : Syntax) (f : Syntax) (namedArgs : Array NamedArg) (args : Array Arg) (expectedType? : Option Expr) : TermElabM Expr := do /- TODO: if `f` contains `choice` or overloaded symbols, `mayPostpone == true`, and `expectedType? == some ?m` where `?m` is not assigned, then we should postpone until `?m` is assigned. Another (more expensive) option is: execute, and if successes > 1, `mayPostpone == true`, and `expectedType? == some ?m` where `?m` is not assigned, then we postpone `elabAppAux`. It is more expensive because we would have to re-elaborate the whole thing after we assign `?m`. We **can't** continue from `TermElabResult` since they contain a snapshot of the state, and state has changed. -/ candidates ← elabAppFn ref f [] namedArgs args expectedType? false #[]; if candidates.size == 1 then applyResult $ candidates.get! 0 else let successes := getSuccess candidates; if successes.size == 1 then applyResult $ successes.get! 0 else if successes.size > 1 then do lctx ← getLCtx; opts ← getOptions; let msgs : Array MessageData := successes.map $ fun success => match success with | EStateM.Result.ok e s => MessageData.withContext { env := s.env, mctx := s.mctx, lctx := lctx, opts := opts } e | _ => unreachable!; throwError f ("ambiguous, possible interpretations " ++ MessageData.ofArray msgs) else mergeFailures candidates f private partial def expandApp (stx : Syntax) : TermElabM (Syntax × Array NamedArg × Array Arg) := do let f := stx.getArg 0; (namedArgs, args) ← (stx.getArg 1).getArgs.foldlM (fun (acc : Array NamedArg × Array Arg) (stx : Syntax) => do let (namedArgs, args) := acc; if stx.getKind == `Lean.Parser.Term.namedArgument then do -- tparser! try ("(" >> ident >> " := ") >> termParser >> ")" let name := (stx.getArg 1).getId.eraseMacroScopes; let val := stx.getArg 3; namedArgs ← addNamedArg stx namedArgs { name := name, val := Arg.stx val }; pure (namedArgs, args) else pure (namedArgs, args.push $ Arg.stx stx)) (#[], #[]); pure (f, namedArgs, args) @[builtinTermElab app] def elabApp : TermElab := fun stx expectedType? => do (f, namedArgs, args) ← expandApp stx; elabAppAux stx f namedArgs args expectedType? def elabAtom : TermElab := fun stx expectedType? => elabAppAux stx stx #[] #[] expectedType? @[builtinTermElab «id»] def elabId : TermElab := elabAtom @[builtinTermElab explicit] def elabExplicit : TermElab := fun stx expectedType? => match_syntax stx with | `(@$id:id) => elabAtom stx expectedType? -- Recall that `elabApp` also has support for `@` | `(@($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 /- A raw identiier is not a valid term, but it is nice to have a handler for them because it allows `macros` to insert them into terms. -/ @[builtinTermElab ident] def elabRawIdent : TermElab := elabAtom @[builtinTermElab sortApp] def elabSortApp : TermElab := fun stx _ => do u ← elabLevel (stx.getArg 1); if (stx.getArg 0).getKind == `Lean.Parser.Term.sort then do pure $ mkSort u else pure $ mkSort (mkLevelSucc u) @[init] private def regTraceClasses : IO Unit := do registerTraceClass `Elab.app; pure () end Term end Elab end Lean
dd3a480960412142296c0c7807b477288cf0fc2a
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/bench/const_fold.lean
bd097844054f859013fada2dac93221ce3cc039f
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
2,230
lean
inductive Expr | Var : Nat → Expr | Val : Nat → Expr | Add : Expr → Expr → Expr | Mul : Expr → Expr → Expr namespace Expr open Nat def mkExpr : Nat → Nat → Expr | 0, v => if v = 0 then Var 1 else Val v | n+1, v => Add (mkExpr n (v+1)) (mkExpr n (v-1)) def appendAdd : Expr → Expr → Expr | Add e₁ e₂, e₃ => Add e₁ (appendAdd e₂ e₃) | e₁, e₂ => Add e₁ e₂ def appendMul : Expr → Expr → Expr | Mul e₁ e₂, e₃ => Mul e₁ (appendMul e₂ e₃) | e₁, e₂ => Mul e₁ e₂ def reassoc : Expr → Expr | Add e₁ e₂ => let e₁' := reassoc e₁; let e₂' := reassoc e₂; appendAdd e₁' e₂' | Mul e₁ e₂ => let e₁' := reassoc e₁; let e₂' := reassoc e₂; appendMul e₁' e₂' | e => e def constFolding : Expr → Expr | Add e₁ e₂ => let e₁ := constFolding e₁; let e₂ := constFolding e₂; (match e₁, e₂ with | Val a, Val b => Val (a+b) | Val a, Add e (Val b) => Add (Val (a+b)) e | Val a, Add (Val b) e => Add (Val (a+b)) e | _, _ => Add e₁ e₂) | Mul e₁ e₂ => let e₁ := constFolding e₁; let e₂ := constFolding e₂; (match e₁, e₂ with | Val a, Val b => Val (a*b) | Val a, Mul e (Val b) => Mul (Val (a*b)) e | Val a, Mul (Val b) e => Mul (Val (a*b)) e | _, _ => Mul e₁ e₂) | e => e def size : Expr → Nat | Add l r => size l + size r + 1 | Mul l r => size l + size r + 1 | e => 1 def toStringAux : Expr → String → String | Var v, r => r ++ "#" ++ toString v | Val v, r => r ++ toString v | Add e₁ e₂, r => (toStringAux e₂ ((toStringAux e₁ (r ++ "(")) ++ " + ")) ++ ")" | Mul e₁ e₂, r => (toStringAux e₂ ((toStringAux e₁ (r ++ "(")) ++ " * ")) ++ ")" def eval : Expr → Nat | Var x => 0 | Val v => v | Add l r => eval l + eval r | Mul l r => eval l * eval r end Expr open Expr unsafe def main : List String → IO UInt32 | [s] => do let n := s.toNat!; let e := (mkExpr n 1); let v₁ := eval e; let v₂ := eval (constFolding (reassoc e)); IO.println (toString v₁ ++ " " ++ toString v₂); pure 0 | _ => pure 1
1ae40f8babb648a97ba20f1bab44d1cdb49890b4
f4bff2062c030df03d65e8b69c88f79b63a359d8
/src/game/sets/sets_level09.lean
364e45330be169f9f1a323efdbf648dc201af26f
[ "Apache-2.0" ]
permissive
adastra7470/real-number-game
776606961f52db0eb824555ed2f8e16f92216ea3
f9dcb7d9255a79b57e62038228a23346c2dc301b
refs/heads/master
1,669,221,575,893
1,594,669,800,000
1,594,669,800,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
680
lean
import kb_real_defs /- # Chapter 1 : Sets ## Level 9 -/ /- This is a little more complicated example asking you to work with intervals of reals. The result will be of help in the sup-inf world. -/ notation `[` a `,` b `]` := set.Icc a b def mem_prod_sets (A : set ℝ) (B : set ℝ) := { x : ℝ | ∃ y ∈ A, ∃ z ∈ B, x = y * z} /- Lemma If $x = 0$, then `x ∈ mem_prod_sets [(-2:ℝ),-1] [(0:ℝ), 3]` -/ lemma zero_in_prod : (0:ℝ) ∈ mem_prod_sets [(-2:ℝ), -1] [(0:ℝ), 3] := begin rw mem_prod_sets, dsimp, use -2, split, { rw mem_Icc_iff, split; linarith }, use 0, split, { rw mem_Icc_iff, split; linarith }, norm_num end
4863adb5dc33a45d8f38e39b6f63d6f30c24612b
130c49f47783503e462c16b2eff31933442be6ff
/src/Lean/Expr.lean
182180f7d76c897babe38f2283246b980bac8d3c
[ "Apache-2.0" ]
permissive
Hazel-Brown/lean4
8aa5860e282435ffc30dcdfccd34006c59d1d39c
79e6732fc6bbf5af831b76f310f9c488d44e7a16
refs/heads/master
1,689,218,208,951
1,629,736,869,000
1,629,736,896,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
37,655
lean
/- Copyright (c) 2018 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Data.KVMap import Lean.Level namespace Lean inductive Literal where | natVal (val : Nat) | strVal (val : String) deriving Inhabited, BEq, Repr protected def Literal.hash : Literal → UInt64 | Literal.natVal v => hash v | Literal.strVal v => hash v instance : Hashable Literal := ⟨Literal.hash⟩ def Literal.lt : Literal → Literal → Bool | Literal.natVal _, Literal.strVal _ => true | Literal.natVal v₁, Literal.natVal v₂ => v₁ < v₂ | Literal.strVal v₁, Literal.strVal v₂ => v₁ < v₂ | _, _ => false instance : LT Literal := ⟨fun a b => a.lt b⟩ instance (a b : Literal) : Decidable (a < b) := inferInstanceAs (Decidable (a.lt b)) inductive BinderInfo where | default | implicit | strictImplicit | instImplicit | auxDecl deriving Inhabited, BEq, Repr def BinderInfo.hash : BinderInfo → UInt64 | BinderInfo.default => 947 | BinderInfo.implicit => 1019 | BinderInfo.strictImplicit => 1087 | BinderInfo.instImplicit => 1153 | BinderInfo.auxDecl => 1229 def BinderInfo.isExplicit : BinderInfo → Bool | BinderInfo.implicit => false | BinderInfo.strictImplicit => false | BinderInfo.instImplicit => false | _ => true instance : Hashable BinderInfo := ⟨BinderInfo.hash⟩ def BinderInfo.isInstImplicit : BinderInfo → Bool | BinderInfo.instImplicit => true | _ => false def BinderInfo.isImplicit : BinderInfo → Bool | BinderInfo.implicit => true | _ => false def BinderInfo.isStrictImplicit : BinderInfo → Bool | BinderInfo.strictImplicit => true | _ => false def BinderInfo.isAuxDecl : BinderInfo → Bool | BinderInfo.auxDecl => true | _ => false abbrev MData := KVMap abbrev MData.empty : MData := {} /-- Cached hash code, cached results, and other data for `Expr`. hash : 32-bits hasFVar : 1-bit hasExprMVar : 1-bit hasLevelMVar : 1-bit hasLevelParam : 1-bit nonDepLet : 1-bit binderInfo : 3-bits looseBVarRange : 24-bits -/ def Expr.Data := UInt64 instance: Inhabited Expr.Data := inferInstanceAs (Inhabited UInt64) def Expr.Data.hash (c : Expr.Data) : UInt64 := c.toUInt32.toUInt64 instance : BEq Expr.Data where beq (a b : UInt64) := a == b def Expr.Data.looseBVarRange (c : Expr.Data) : UInt32 := (c.shiftRight 40).toUInt32 def Expr.Data.hasFVar (c : Expr.Data) : Bool := ((c.shiftRight 32).land 1) == 1 def Expr.Data.hasExprMVar (c : Expr.Data) : Bool := ((c.shiftRight 33).land 1) == 1 def Expr.Data.hasLevelMVar (c : Expr.Data) : Bool := ((c.shiftRight 34).land 1) == 1 def Expr.Data.hasLevelParam (c : Expr.Data) : Bool := ((c.shiftRight 35).land 1) == 1 def Expr.Data.nonDepLet (c : Expr.Data) : Bool := ((c.shiftRight 36).land 1) == 1 @[extern c inline "(uint8_t)((#1 << 24) >> 61)"] def Expr.Data.binderInfo (c : Expr.Data) : BinderInfo := let bi := (c.shiftLeft 24).shiftRight 61 if bi == 0 then BinderInfo.default else if bi == 1 then BinderInfo.implicit else if bi == 2 then BinderInfo.strictImplicit else if bi == 3 then BinderInfo.instImplicit else BinderInfo.auxDecl @[extern c inline "(uint64_t)#1"] def BinderInfo.toUInt64 : BinderInfo → UInt64 | BinderInfo.default => 0 | BinderInfo.implicit => 1 | BinderInfo.strictImplicit => 2 | BinderInfo.instImplicit => 3 | BinderInfo.auxDecl => 4 @[inline] private def Expr.mkDataCore (h : UInt64) (looseBVarRange : Nat) (hasFVar hasExprMVar hasLevelMVar hasLevelParam nonDepLet : Bool) (bi : BinderInfo) : Expr.Data := if looseBVarRange > Nat.pow 2 24 - 1 then panic! "bound variable index is too big" else let r : UInt64 := h.toUInt32.toUInt64 + hasFVar.toUInt64.shiftLeft 32 + hasExprMVar.toUInt64.shiftLeft 33 + hasLevelMVar.toUInt64.shiftLeft 34 + hasLevelParam.toUInt64.shiftLeft 35 + nonDepLet.toUInt64.shiftLeft 36 + bi.toUInt64.shiftLeft 37 + looseBVarRange.toUInt64.shiftLeft 40 r def Expr.mkData (h : UInt64) (looseBVarRange : Nat := 0) (hasFVar hasExprMVar hasLevelMVar hasLevelParam : Bool := false) : Expr.Data := Expr.mkDataCore h looseBVarRange hasFVar hasExprMVar hasLevelMVar hasLevelParam false BinderInfo.default def Expr.mkDataForBinder (h : UInt64) (looseBVarRange : Nat) (hasFVar hasExprMVar hasLevelMVar hasLevelParam : Bool) (bi : BinderInfo) : Expr.Data := Expr.mkDataCore h looseBVarRange hasFVar hasExprMVar hasLevelMVar hasLevelParam false bi def Expr.mkDataForLet (h : UInt64) (looseBVarRange : Nat) (hasFVar hasExprMVar hasLevelMVar hasLevelParam nonDepLet : Bool) : Expr.Data := Expr.mkDataCore h looseBVarRange hasFVar hasExprMVar hasLevelMVar hasLevelParam nonDepLet BinderInfo.default open Expr abbrev MVarId := Name abbrev FVarId := Name /- We use the `E` suffix (short for `Expr`) to avoid collision with keywords. We considered using «...», but it is too inconvenient to use. -/ inductive Expr where | bvar : Nat → Data → Expr -- bound variables | fvar : FVarId → Data → Expr -- free variables | mvar : MVarId → Data → Expr -- meta variables | sort : Level → Data → Expr -- Sort | const : Name → List Level → Data → Expr -- constants | app : Expr → Expr → Data → Expr -- application | lam : Name → Expr → Expr → Data → Expr -- lambda abstraction | forallE : Name → Expr → Expr → Data → Expr -- (dependent) arrow | letE : Name → Expr → Expr → Expr → Data → Expr -- let expressions | lit : Literal → Data → Expr -- literals | mdata : MData → Expr → Data → Expr -- metadata | proj : Name → Nat → Expr → Data → Expr -- projection deriving Inhabited namespace Expr @[inline] def data : Expr → Data | bvar _ d => d | fvar _ d => d | mvar _ d => d | sort _ d => d | const _ _ d => d | app _ _ d => d | lam _ _ _ d => d | forallE _ _ _ d => d | letE _ _ _ _ d => d | lit _ d => d | mdata _ _ d => d | proj _ _ _ d => d def ctorName : Expr → String | bvar _ _ => "bvar" | fvar _ _ => "fvar" | mvar _ _ => "mvar" | sort _ _ => "sort" | const _ _ _ => "const" | app _ _ _ => "app" | lam _ _ _ _ => "lam" | forallE _ _ _ _ => "forallE" | letE _ _ _ _ _ => "letE" | lit _ _ => "lit" | mdata _ _ _ => "mdata" | proj _ _ _ _ => "proj" protected def hash (e : Expr) : UInt64 := e.data.hash instance : Hashable Expr := ⟨Expr.hash⟩ def hasFVar (e : Expr) : Bool := e.data.hasFVar def hasExprMVar (e : Expr) : Bool := e.data.hasExprMVar def hasLevelMVar (e : Expr) : Bool := e.data.hasLevelMVar def hasMVar (e : Expr) : Bool := let d := e.data d.hasExprMVar || d.hasLevelMVar def hasLevelParam (e : Expr) : Bool := e.data.hasLevelParam def looseBVarRange (e : Expr) : Nat := e.data.looseBVarRange.toNat def binderInfo (e : Expr) : BinderInfo := e.data.binderInfo @[export lean_expr_hash] def hashEx : Expr → UInt64 := hash @[export lean_expr_has_fvar] def hasFVarEx : Expr → Bool := hasFVar @[export lean_expr_has_expr_mvar] def hasExprMVarEx : Expr → Bool := hasExprMVar @[export lean_expr_has_level_mvar] def hasLevelMVarEx : Expr → Bool := hasLevelMVar @[export lean_expr_has_mvar] def hasMVarEx : Expr → Bool := hasMVar @[export lean_expr_has_level_param] def hasLevelParamEx : Expr → Bool := hasLevelParam @[export lean_expr_loose_bvar_range] def looseBVarRangeEx (e : Expr) : UInt32 := e.data.looseBVarRange @[export lean_expr_binder_info] def binderInfoEx : Expr → BinderInfo := binderInfo end Expr def mkConst (n : Name) (lvls : List Level := []) : Expr := Expr.const n lvls $ mkData (mixHash 5 $ mixHash (hash n) (hash lvls)) 0 false false (lvls.any Level.hasMVar) (lvls.any Level.hasParam) def Literal.type : Literal → Expr | Literal.natVal _ => mkConst `Nat | Literal.strVal _ => mkConst `String @[export lean_lit_type] def Literal.typeEx : Literal → Expr := Literal.type def mkBVar (idx : Nat) : Expr := Expr.bvar idx $ mkData (mixHash 7 $ hash idx) (idx+1) def mkSort (lvl : Level) : Expr := Expr.sort lvl $ mkData (mixHash 11 $ hash lvl) 0 false false lvl.hasMVar lvl.hasParam def mkFVar (fvarId : FVarId) : Expr := Expr.fvar fvarId $ mkData (mixHash 13 $ hash fvarId) 0 true def mkMVar (fvarId : MVarId) : Expr := Expr.mvar fvarId $ mkData (mixHash 17 $ hash fvarId) 0 false true def mkMData (d : MData) (e : Expr) : Expr := Expr.mdata d e $ mkData (mixHash 19 $ hash e) e.looseBVarRange e.hasFVar e.hasExprMVar e.hasLevelMVar e.hasLevelParam def mkProj (s : Name) (i : Nat) (e : Expr) : Expr := Expr.proj s i e $ mkData (mixHash 23 $ mixHash (hash s) $ mixHash (hash i) (hash e)) e.looseBVarRange e.hasFVar e.hasExprMVar e.hasLevelMVar e.hasLevelParam def mkApp (f a : Expr) : Expr := Expr.app f a $ mkData (mixHash 29 $ mixHash (hash f) (hash a)) (Nat.max f.looseBVarRange a.looseBVarRange) (f.hasFVar || a.hasFVar) (f.hasExprMVar || a.hasExprMVar) (f.hasLevelMVar || a.hasLevelMVar) (f.hasLevelParam || a.hasLevelParam) def mkLambda (x : Name) (bi : BinderInfo) (t : Expr) (b : Expr) : Expr := -- let x := x.eraseMacroScopes Expr.lam x t b $ mkDataForBinder (mixHash 31 $ mixHash (hash t) (hash b)) (Nat.max t.looseBVarRange (b.looseBVarRange - 1)) (t.hasFVar || b.hasFVar) (t.hasExprMVar || b.hasExprMVar) (t.hasLevelMVar || b.hasLevelMVar) (t.hasLevelParam || b.hasLevelParam) bi def mkForall (x : Name) (bi : BinderInfo) (t : Expr) (b : Expr) : Expr := -- let x := x.eraseMacroScopes Expr.forallE x t b $ mkDataForBinder (mixHash 37 $ mixHash (hash t) (hash b)) (Nat.max t.looseBVarRange (b.looseBVarRange - 1)) (t.hasFVar || b.hasFVar) (t.hasExprMVar || b.hasExprMVar) (t.hasLevelMVar || b.hasLevelMVar) (t.hasLevelParam || b.hasLevelParam) bi /- Return `Unit -> type`. Do not confuse with `Thunk type` -/ def mkSimpleThunkType (type : Expr) : Expr := mkForall Name.anonymous BinderInfo.default (Lean.mkConst `Unit) type /- Return `fun (_ : Unit), e` -/ def mkSimpleThunk (type : Expr) : Expr := mkLambda `_ BinderInfo.default (Lean.mkConst `Unit) type def mkLet (x : Name) (t : Expr) (v : Expr) (b : Expr) (nonDep : Bool := false) : Expr := -- let x := x.eraseMacroScopes Expr.letE x t v b $ mkDataForLet (mixHash 41 $ mixHash (hash t) $ mixHash (hash v) (hash b)) (Nat.max (Nat.max t.looseBVarRange v.looseBVarRange) (b.looseBVarRange - 1)) (t.hasFVar || v.hasFVar || b.hasFVar) (t.hasExprMVar || v.hasExprMVar || b.hasExprMVar) (t.hasLevelMVar || v.hasLevelMVar || b.hasLevelMVar) (t.hasLevelParam || v.hasLevelParam || b.hasLevelParam) nonDep def mkAppB (f a b : Expr) := mkApp (mkApp f a) b def mkApp2 (f a b : Expr) := mkAppB f a b def mkApp3 (f a b c : Expr) := mkApp (mkAppB f a b) c def mkApp4 (f a b c d : Expr) := mkAppB (mkAppB f a b) c d def mkApp5 (f a b c d e : Expr) := mkApp (mkApp4 f a b c d) e def mkApp6 (f a b c d e₁ e₂ : Expr) := mkAppB (mkApp4 f a b c d) e₁ e₂ def mkApp7 (f a b c d e₁ e₂ e₃ : Expr) := mkApp3 (mkApp4 f a b c d) e₁ e₂ e₃ def mkApp8 (f a b c d e₁ e₂ e₃ e₄ : Expr) := mkApp4 (mkApp4 f a b c d) e₁ e₂ e₃ e₄ def mkApp9 (f a b c d e₁ e₂ e₃ e₄ e₅ : Expr) := mkApp5 (mkApp4 f a b c d) e₁ e₂ e₃ e₄ e₅ def mkApp10 (f a b c d e₁ e₂ e₃ e₄ e₅ e₆ : Expr) := mkApp6 (mkApp4 f a b c d) e₁ e₂ e₃ e₄ e₅ e₆ def mkLit (l : Literal) : Expr := Expr.lit l $ mkData (mixHash 3 (hash l)) def mkRawNatLit (n : Nat) : Expr := mkLit (Literal.natVal n) def mkNatLit (n : Nat) : Expr := let r := mkRawNatLit n mkApp3 (mkConst ``OfNat.ofNat [levelZero]) (mkConst ``Nat) r (mkApp (mkConst ``instOfNatNat) r) def mkStrLit (s : String) : Expr := mkLit (Literal.strVal s) @[export lean_expr_mk_bvar] def mkBVarEx : Nat → Expr := mkBVar @[export lean_expr_mk_fvar] def mkFVarEx : FVarId → Expr := mkFVar @[export lean_expr_mk_mvar] def mkMVarEx : MVarId → Expr := mkMVar @[export lean_expr_mk_sort] def mkSortEx : Level → Expr := mkSort @[export lean_expr_mk_const] def mkConstEx (c : Name) (lvls : List Level) : Expr := mkConst c lvls @[export lean_expr_mk_app] def mkAppEx : Expr → Expr → Expr := mkApp @[export lean_expr_mk_lambda] def mkLambdaEx (n : Name) (d b : Expr) (bi : BinderInfo) : Expr := mkLambda n bi d b @[export lean_expr_mk_forall] def mkForallEx (n : Name) (d b : Expr) (bi : BinderInfo) : Expr := mkForall n bi d b @[export lean_expr_mk_let] def mkLetEx (n : Name) (t v b : Expr) : Expr := mkLet n t v b @[export lean_expr_mk_lit] def mkLitEx : Literal → Expr := mkLit @[export lean_expr_mk_mdata] def mkMDataEx : MData → Expr → Expr := mkMData @[export lean_expr_mk_proj] def mkProjEx : Name → Nat → Expr → Expr := mkProj def mkAppN (f : Expr) (args : Array Expr) : Expr := args.foldl mkApp f private partial def mkAppRangeAux (n : Nat) (args : Array Expr) (i : Nat) (e : Expr) : Expr := if i < n then mkAppRangeAux n args (i+1) (mkApp e (args.get! i)) else e /-- `mkAppRange f i j #[a_1, ..., a_i, ..., a_j, ... ]` ==> the expression `f a_i ... a_{j-1}` -/ def mkAppRange (f : Expr) (i j : Nat) (args : Array Expr) : Expr := mkAppRangeAux j args i f def mkAppRev (fn : Expr) (revArgs : Array Expr) : Expr := revArgs.foldr (fun a r => mkApp r a) fn namespace Expr -- TODO: implement it in Lean @[extern "lean_expr_dbg_to_string"] constant dbgToString (e : @& Expr) : String @[extern "lean_expr_quick_lt"] constant quickLt (a : @& Expr) (b : @& Expr) : Bool @[extern "lean_expr_lt"] constant lt (a : @& Expr) (b : @& Expr) : Bool /- Return true iff `a` and `b` are alpha equivalent. Binder annotations are ignored. -/ @[extern "lean_expr_eqv"] constant eqv (a : @& Expr) (b : @& Expr) : Bool instance : BEq Expr where beq := Expr.eqv /- Return true iff `a` and `b` are equal. Binder names and annotations are taking into account. -/ @[extern "lean_expr_equal"] constant equal (a : @& Expr) (b : @& Expr) : Bool def isSort : Expr → Bool | sort _ _ => true | _ => false def isProp : Expr → Bool | sort (Level.zero ..) _ => true | _ => false def isBVar : Expr → Bool | bvar _ _ => true | _ => false def isMVar : Expr → Bool | mvar _ _ => true | _ => false def isFVar : Expr → Bool | fvar _ _ => true | _ => false def isApp : Expr → Bool | app .. => true | _ => false def isProj : Expr → Bool | proj .. => true | _ => false def isConst : Expr → Bool | const .. => true | _ => false def isConstOf : Expr → Name → Bool | const n _ _, m => n == m | _, _ => false def isForall : Expr → Bool | forallE .. => true | _ => false def isLambda : Expr → Bool | lam .. => true | _ => false def isBinding : Expr → Bool | lam .. => true | forallE .. => true | _ => false def isLet : Expr → Bool | letE .. => true | _ => false def isMData : Expr → Bool | mdata .. => true | _ => false def isLit : Expr → Bool | lit .. => true | _ => false def getForallBody : Expr → Expr | forallE _ _ b .. => getForallBody b | e => e def getAppFn : Expr → Expr | app f a _ => getAppFn f | e => e def getAppNumArgsAux : Expr → Nat → Nat | app f a _, n => getAppNumArgsAux f (n+1) | e, n => n def getAppNumArgs (e : Expr) : Nat := getAppNumArgsAux e 0 private def getAppArgsAux : Expr → Array Expr → Nat → Array Expr | app f a _, as, i => getAppArgsAux f (as.set! i a) (i-1) | _, as, _ => as @[inline] def getAppArgs (e : Expr) : Array Expr := let dummy := mkSort levelZero let nargs := e.getAppNumArgs getAppArgsAux e (mkArray nargs dummy) (nargs-1) private def getAppRevArgsAux : Expr → Array Expr → Array Expr | app f a _, as => getAppRevArgsAux f (as.push a) | _, as => as @[inline] def getAppRevArgs (e : Expr) : Array Expr := getAppRevArgsAux e (Array.mkEmpty e.getAppNumArgs) @[specialize] def withAppAux (k : Expr → Array Expr → α) : Expr → Array Expr → Nat → α | app f a _, as, i => withAppAux k f (as.set! i a) (i-1) | f, as, i => k f as @[inline] def withApp (e : Expr) (k : Expr → Array Expr → α) : α := let dummy := mkSort levelZero let nargs := e.getAppNumArgs withAppAux k e (mkArray nargs dummy) (nargs-1) @[specialize] private def withAppRevAux (k : Expr → Array Expr → α) : Expr → Array Expr → α | app f a _, as => withAppRevAux k f (as.push a) | f, as => k f as @[inline] def withAppRev (e : Expr) (k : Expr → Array Expr → α) : α := withAppRevAux k e (Array.mkEmpty e.getAppNumArgs) def getRevArgD : Expr → Nat → Expr → Expr | app f a _, 0, _ => a | app f _ _, i+1, v => getRevArgD f i v | _, _, v => v def getRevArg! : Expr → Nat → Expr | app f a _, 0 => a | app f _ _, i+1 => getRevArg! f i | _, _ => panic! "invalid index" @[inline] def getArg! (e : Expr) (i : Nat) (n := e.getAppNumArgs) : Expr := getRevArg! e (n - i - 1) @[inline] def getArgD (e : Expr) (i : Nat) (v₀ : Expr) (n := e.getAppNumArgs) : Expr := getRevArgD e (n - i - 1) v₀ def isAppOf (e : Expr) (n : Name) : Bool := match e.getAppFn with | const c _ _ => c == n | _ => false def isAppOfArity : Expr → Name → Nat → Bool | const c _ _, n, 0 => c == n | app f _ _, n, a+1 => isAppOfArity f n a | _, _, _ => false def appFn! : Expr → Expr | app f _ _ => f | _ => panic! "application expected" def appArg! : Expr → Expr | app _ a _ => a | _ => panic! "application expected" def isNatLit : Expr → Bool | lit (Literal.natVal _) _ => true | _ => false def natLit? : Expr → Option Nat | lit (Literal.natVal v) _ => v | _ => none def isStringLit : Expr → Bool | lit (Literal.strVal _) _ => true | _ => false def isCharLit (e : Expr) : Bool := e.isAppOfArity `Char.ofNat 1 && e.appArg!.isNatLit def constName! : Expr → Name | const n _ _ => n | _ => panic! "constant expected" def constName? : Expr → Option Name | const n _ _ => some n | _ => none def constLevels! : Expr → List Level | const _ ls _ => ls | _ => panic! "constant expected" def bvarIdx! : Expr → Nat | bvar idx _ => idx | _ => panic! "bvar expected" def fvarId! : Expr → FVarId | fvar n _ => n | _ => panic! "fvar expected" def mvarId! : Expr → MVarId | mvar n _ => n | _ => panic! "mvar expected" def bindingName! : Expr → Name | forallE n _ _ _ => n | lam n _ _ _ => n | _ => panic! "binding expected" def bindingDomain! : Expr → Expr | forallE _ d _ _ => d | lam _ d _ _ => d | _ => panic! "binding expected" def bindingBody! : Expr → Expr | forallE _ _ b _ => b | lam _ _ b _ => b | _ => panic! "binding expected" def bindingInfo! : Expr → BinderInfo | forallE _ _ _ c => c.binderInfo | lam _ _ _ c => c.binderInfo | _ => panic! "binding expected" def letName! : Expr → Name | letE n _ _ _ _ => n | _ => panic! "let expression expected" def consumeMData : Expr → Expr | mdata _ e _ => consumeMData e | e => e def hasLooseBVars (e : Expr) : Bool := e.looseBVarRange > 0 /- Remark: the following function assumes `e` does not have loose bound variables. -/ def isArrow (e : Expr) : Bool := match e with | forallE _ _ b _ => !b.hasLooseBVars | _ => false @[extern "lean_expr_has_loose_bvar"] constant hasLooseBVar (e : @& Expr) (bvarIdx : @& Nat) : Bool /-- Return true if `e` contains the loose bound variable `bvarIdx` in an explicit parameter, or in the range if `tryRange == true`. -/ def hasLooseBVarInExplicitDomain : Expr → Nat → Bool → Bool | Expr.forallE _ d b c, bvarIdx, tryRange => (c.binderInfo.isExplicit && hasLooseBVar d bvarIdx) || hasLooseBVarInExplicitDomain b (bvarIdx+1) tryRange | e, bvarIdx, tryRange => tryRange && hasLooseBVar e bvarIdx /-- Lower the loose bound variables `>= s` in `e` by `d`. That is, a loose bound variable `bvar i`. `i >= s` is mapped into `bvar (i-d)`. Remark: if `s < d`, then result is `e` -/ @[extern "lean_expr_lower_loose_bvars"] constant lowerLooseBVars (e : @& Expr) (s d : @& Nat) : Expr /-- Lift loose bound variables `>= s` in `e` by `d`. -/ @[extern "lean_expr_lift_loose_bvars"] constant liftLooseBVars (e : @& Expr) (s d : @& Nat) : Expr /-- `inferImplicit e numParams considerRange` updates the first `numParams` parameter binder annotations of the `e` forall type. It marks any parameter with an explicit binder annotation if there is another explicit arguments that depends on it or the resulting type if `considerRange == true`. Remark: we use this function to infer the bind annotations of inductive datatype constructors, and structure projections. When the `{}` annotation is used in these commands, we set `considerRange == false`. -/ def inferImplicit : Expr → Nat → Bool → Expr | Expr.forallE n d b c, i+1, considerRange => let b := inferImplicit b i considerRange let newInfo := if c.binderInfo.isExplicit && hasLooseBVarInExplicitDomain b 0 considerRange then BinderInfo.implicit else c.binderInfo mkForall n newInfo d b | e, 0, _ => e | e, _, _ => e /-- Instantiate the loose bound variables in `e` using `subst`. That is, a loose `Expr.bvar i` is replaced with `subst[i]`. -/ @[extern "lean_expr_instantiate"] constant instantiate (e : @& Expr) (subst : @& Array Expr) : Expr @[extern "lean_expr_instantiate1"] constant instantiate1 (e : @& Expr) (subst : @& Expr) : Expr /-- Similar to instantiate, but `Expr.bvar i` is replaced with `subst[subst.size - i - 1]` -/ @[extern "lean_expr_instantiate_rev"] constant instantiateRev (e : @& Expr) (subst : @& Array Expr) : Expr /-- Similar to `instantiate`, but consider only the variables `xs` in the range `[beginIdx, endIdx)`. Function panics if `beginIdx <= endIdx <= xs.size` does not hold. -/ @[extern "lean_expr_instantiate_range"] constant instantiateRange (e : @& Expr) (beginIdx endIdx : @& Nat) (xs : @& Array Expr) : Expr /-- Similar to `instantiateRev`, but consider only the variables `xs` in the range `[beginIdx, endIdx)`. Function panics if `beginIdx <= endIdx <= xs.size` does not hold. -/ @[extern "lean_expr_instantiate_rev_range"] constant instantiateRevRange (e : @& Expr) (beginIdx endIdx : @& Nat) (xs : @& Array Expr) : Expr /-- Replace free variables `xs` with loose bound variables. -/ @[extern "lean_expr_abstract"] constant abstract (e : @& Expr) (xs : @& Array Expr) : Expr /-- Similar to `abstract`, but consider only the first `min n xs.size` entries in `xs`. -/ @[extern "lean_expr_abstract_range"] constant abstractRange (e : @& Expr) (n : @& Nat) (xs : @& Array Expr) : Expr /-- Replace occurrences of the free variable `fvar` in `e` with `v` -/ def replaceFVar (e : Expr) (fvar : Expr) (v : Expr) : Expr := (e.abstract #[fvar]).instantiate1 v /-- Replace occurrences of the free variable `fvarId` in `e` with `v` -/ def replaceFVarId (e : Expr) (fvarId : FVarId) (v : Expr) : Expr := replaceFVar e (mkFVar fvarId) v /-- Replace occurrences of the free variables `fvars` in `e` with `vs` -/ def replaceFVars (e : Expr) (fvars : Array Expr) (vs : Array Expr) : Expr := (e.abstract fvars).instantiateRev vs instance : ToString Expr where toString := Expr.dbgToString def isAtomic : Expr → Bool | Expr.const _ _ _ => true | Expr.sort _ _ => true | Expr.bvar _ _ => true | Expr.lit _ _ => true | Expr.mvar _ _ => true | Expr.fvar _ _ => true | _ => false end Expr def mkDecIsTrue (pred proof : Expr) := mkAppB (mkConst `Decidable.isTrue) pred proof def mkDecIsFalse (pred proof : Expr) := mkAppB (mkConst `Decidable.isFalse) pred proof open Std (HashMap HashSet PHashMap PHashSet) abbrev ExprMap (α : Type) := HashMap Expr α abbrev PersistentExprMap (α : Type) := PHashMap Expr α abbrev ExprSet := HashSet Expr abbrev PersistentExprSet := PHashSet Expr abbrev PExprSet := PersistentExprSet /- Auxiliary type for forcing `==` to be structural equality for `Expr` -/ structure ExprStructEq where val : Expr deriving Inhabited instance : Coe Expr ExprStructEq := ⟨ExprStructEq.mk⟩ namespace ExprStructEq protected def beq : ExprStructEq → ExprStructEq → Bool | ⟨e₁⟩, ⟨e₂⟩ => Expr.equal e₁ e₂ protected def hash : ExprStructEq → UInt64 | ⟨e⟩ => e.hash instance : BEq ExprStructEq := ⟨ExprStructEq.beq⟩ instance : Hashable ExprStructEq := ⟨ExprStructEq.hash⟩ instance : ToString ExprStructEq := ⟨fun e => toString e.val⟩ end ExprStructEq abbrev ExprStructMap (α : Type) := HashMap ExprStructEq α abbrev PersistentExprStructMap (α : Type) := PHashMap ExprStructEq α namespace Expr private partial def mkAppRevRangeAux (revArgs : Array Expr) (start : Nat) (b : Expr) (i : Nat) : Expr := if i == start then b else let i := i - 1 mkAppRevRangeAux revArgs start (mkApp b (revArgs.get! i)) i /-- `mkAppRevRange f b e args == mkAppRev f (revArgs.extract b e)` -/ def mkAppRevRange (f : Expr) (beginIdx endIdx : Nat) (revArgs : Array Expr) : Expr := mkAppRevRangeAux revArgs beginIdx f endIdx private def betaRevAux (revArgs : Array Expr) (sz : Nat) : Expr → Nat → Expr | Expr.lam _ _ b _, i => if i + 1 < sz then betaRevAux revArgs sz b (i+1) else let n := sz - (i + 1) mkAppRevRange (b.instantiateRange n sz revArgs) 0 n revArgs | Expr.mdata _ b _, i => betaRevAux revArgs sz b i | b, i => let n := sz - i mkAppRevRange (b.instantiateRange n sz revArgs) 0 n revArgs /-- If `f` is a lambda expression, than "beta-reduce" it using `revArgs`. This function is often used with `getAppRev` or `withAppRev`. Examples: - `betaRev (fun x y => t x y) #[]` ==> `fun x y => t x y` - `betaRev (fun x y => t x y) #[a]` ==> `fun y => t a y` - `betaRev (fun x y => t x y) #[a, b]` ==> t b a` - `betaRev (fun x y => t x y) #[a, b, c, d]` ==> t d c b a` Suppose `t` is `(fun x y => t x y) a b c d`, then `args := t.getAppRev` is `#[d, c, b, a]`, and `betaRev (fun x y => t x y) #[d, c, b, a]` is `t a b c d`. -/ def betaRev (f : Expr) (revArgs : Array Expr) : Expr := if revArgs.size == 0 then f else betaRevAux revArgs revArgs.size f 0 def isHeadBetaTargetFn : Expr → Bool | Expr.lam _ _ _ _ => true | Expr.mdata _ b _ => isHeadBetaTargetFn b | _ => false def headBeta (e : Expr) : Expr := let f := e.getAppFn if f.isHeadBetaTargetFn then betaRev f e.getAppRevArgs else e def isHeadBetaTarget (e : Expr) : Bool := e.getAppFn.isHeadBetaTargetFn private def etaExpandedBody : Expr → Nat → Nat → Option Expr | app f (bvar j _) _, n+1, i => if j == i then etaExpandedBody f n (i+1) else none | _, n+1, _ => none | f, 0, _ => if f.hasLooseBVars then none else some f private def etaExpandedAux : Expr → Nat → Option Expr | lam _ _ b _, n => etaExpandedAux b (n+1) | e, n => etaExpandedBody e n 0 /-- If `e` is of the form `(fun x₁ ... xₙ => f x₁ ... xₙ)` and `f` does not contain `x₁`, ..., `xₙ`, then return `some f`. Otherwise, return `none`. It assumes `e` does not have loose bound variables. Remark: `ₙ` may be 0 -/ def etaExpanded? (e : Expr) : Option Expr := etaExpandedAux e 0 /-- Similar to `etaExpanded?`, but only succeeds if `ₙ ≥ 1`. -/ def etaExpandedStrict? : Expr → Option Expr | lam _ _ b _ => etaExpandedAux b 1 | _ => none def getOptParamDefault? (e : Expr) : Option Expr := if e.isAppOfArity `optParam 2 then some e.appArg! else none def getAutoParamTactic? (e : Expr) : Option Expr := if e.isAppOfArity `autoParam 2 then some e.appArg! else none def isOptParam (e : Expr) : Bool := e.isAppOfArity `optParam 2 def isAutoParam (e : Expr) : Bool := e.isAppOfArity `autoParam 2 /-- Return true iff `e` contains a free variable which statisfies `p`. -/ @[inline] def hasAnyFVar (e : Expr) (p : FVarId → Bool) : Bool := let rec @[specialize] visit (e : Expr) := if !e.hasFVar then false else match e with | Expr.forallE _ d b _ => visit d || visit b | Expr.lam _ d b _ => visit d || visit b | Expr.mdata _ e _ => visit e | Expr.letE _ t v b _ => visit t || visit v || visit b | Expr.app f a _ => visit f || visit a | Expr.proj _ _ e _ => visit e | e@(Expr.fvar fvarId _) => p fvarId | e => false visit e def containsFVar (e : Expr) (fvarId : FVarId) : Bool := e.hasAnyFVar (· == fvarId) /- The update functions here are defined using C code. They will try to avoid allocating new values using pointer equality. The hypotheses `(h : e.is...)` are used to ensure Lean will not crash at runtime. The `update*!` functions are inlined and provide a convenient way of using the update proofs without providing proofs. Note that if they are used under a match-expression, the compiler will eliminate the double-match. -/ @[extern "lean_expr_update_app"] def updateApp (e : Expr) (newFn : Expr) (newArg : Expr) (h : e.isApp) : Expr := mkApp newFn newArg @[inline] def updateApp! (e : Expr) (newFn : Expr) (newArg : Expr) : Expr := match e with | app fn arg c => updateApp (app fn arg c) newFn newArg rfl | _ => panic! "application expected" @[extern "lean_expr_update_const"] def updateConst (e : Expr) (newLevels : List Level) (h : e.isConst) : Expr := mkConst e.constName! newLevels @[inline] def updateConst! (e : Expr) (newLevels : List Level) : Expr := match e with | const n ls c => updateConst (const n ls c) newLevels rfl | _ => panic! "constant expected" @[extern "lean_expr_update_sort"] def updateSort (e : Expr) (newLevel : Level) (h : e.isSort) : Expr := mkSort newLevel @[inline] def updateSort! (e : Expr) (newLevel : Level) : Expr := match e with | sort l c => updateSort (sort l c) newLevel rfl | _ => panic! "level expected" @[extern "lean_expr_update_proj"] def updateProj (e : Expr) (newExpr : Expr) (h : e.isProj) : Expr := match e with | proj s i _ _ => mkProj s i newExpr | _ => e -- unreachable because of `h` @[extern "lean_expr_update_mdata"] def updateMData (e : Expr) (newExpr : Expr) (h : e.isMData) : Expr := match e with | mdata d _ _ => mkMData d newExpr | _ => e -- unreachable because of `h` @[inline] def updateMData! (e : Expr) (newExpr : Expr) : Expr := match e with | mdata d e c => updateMData (mdata d e c) newExpr rfl | _ => panic! "mdata expected" @[inline] def updateProj! (e : Expr) (newExpr : Expr) : Expr := match e with | proj s i e c => updateProj (proj s i e c) newExpr rfl | _ => panic! "proj expected" @[extern "lean_expr_update_forall"] def updateForall (e : Expr) (newBinfo : BinderInfo) (newDomain : Expr) (newBody : Expr) (h : e.isForall) : Expr := mkForall e.bindingName! newBinfo newDomain newBody @[inline] def updateForall! (e : Expr) (newBinfo : BinderInfo) (newDomain : Expr) (newBody : Expr) : Expr := match e with | forallE n d b c => updateForall (forallE n d b c) newBinfo newDomain newBody rfl | _ => panic! "forall expected" @[inline] def updateForallE! (e : Expr) (newDomain : Expr) (newBody : Expr) : Expr := match e with | forallE n d b c => updateForall (forallE n d b c) c.binderInfo newDomain newBody rfl | _ => panic! "forall expected" @[extern "lean_expr_update_lambda"] def updateLambda (e : Expr) (newBinfo : BinderInfo) (newDomain : Expr) (newBody : Expr) (h : e.isLambda) : Expr := mkLambda e.bindingName! newBinfo newDomain newBody @[inline] def updateLambda! (e : Expr) (newBinfo : BinderInfo) (newDomain : Expr) (newBody : Expr) : Expr := match e with | lam n d b c => updateLambda (lam n d b c) newBinfo newDomain newBody rfl | _ => panic! "lambda expected" @[inline] def updateLambdaE! (e : Expr) (newDomain : Expr) (newBody : Expr) : Expr := match e with | lam n d b c => updateLambda (lam n d b c) c.binderInfo newDomain newBody rfl | _ => panic! "lambda expected" @[extern "lean_expr_update_let"] def updateLet (e : Expr) (newType : Expr) (newVal : Expr) (newBody : Expr) (h : e.isLet) : Expr := mkLet e.letName! newType newVal newBody @[inline] def updateLet! (e : Expr) (newType : Expr) (newVal : Expr) (newBody : Expr) : Expr := match e with | letE n t v b c => updateLet (letE n t v b c) newType newVal newBody rfl | _ => panic! "let expression expected" def updateFn : Expr → Expr → Expr | e@(app f a _), g => e.updateApp! (updateFn f g) a | _, g => g partial def eta (e : Expr) : Expr := match e with | Expr.lam _ d b _ => let b' := b.eta match b' with | Expr.app f (Expr.bvar 0 _) _ => if !f.hasLooseBVar 0 then f.lowerLooseBVars 1 1 else e.updateLambdaE! d b' | _ => e.updateLambdaE! d b' | _ => e /- Instantiate level parameters -/ @[inline] def instantiateLevelParamsCore (s : Name → Option Level) (e : Expr) : Expr := let rec @[specialize] visit (e : Expr) : Expr := if !e.hasLevelParam then e else match e with | lam n d b _ => e.updateLambdaE! (visit d) (visit b) | forallE n d b _ => e.updateForallE! (visit d) (visit b) | letE n t v b _ => e.updateLet! (visit t) (visit v) (visit b) | app f a _ => e.updateApp! (visit f) (visit a) | proj _ _ s _ => e.updateProj! (visit s) | mdata _ b _ => e.updateMData! (visit b) | const _ us _ => e.updateConst! (us.map (fun u => u.instantiateParams s)) | sort u _ => e.updateSort! (u.instantiateParams s) | e => e visit e private def getParamSubst : List Name → List Level → Name → Option Level | p::ps, u::us, p' => if p == p' then some u else getParamSubst ps us p' | _, _, _ => none def instantiateLevelParams (e : Expr) (paramNames : List Name) (lvls : List Level) : Expr := instantiateLevelParamsCore (getParamSubst paramNames lvls) e private partial def getParamSubstArray (ps : Array Name) (us : Array Level) (p' : Name) (i : Nat) : Option Level := if h : i < ps.size then let p := ps.get ⟨i, h⟩ if h : i < us.size then let u := us.get ⟨i, h⟩ if p == p' then some u else getParamSubstArray ps us p' (i+1) else none else none def instantiateLevelParamsArray (e : Expr) (paramNames : Array Name) (lvls : Array Level) : Expr := instantiateLevelParamsCore (fun p => getParamSubstArray paramNames lvls p 0) e /- Annotate `e` with the given option. -/ def setOption (e : Expr) (optionName : Name) [KVMap.Value α] (val : α) : Expr := mkMData (MData.empty.set optionName val) e /- Annotate `e` with `pp.explicit := true` The delaborator uses `pp` options. -/ def setPPExplicit (e : Expr) (flag : Bool) := e.setOption `pp.explicit flag def setPPUniverses (e : Expr) (flag : Bool) := e.setOption `pp.universes flag /- If `e` is an application `f a_1 ... a_n` annotate `f`, `a_1` ... `a_n` with `pp.explicit := false`, and annotate `e` with `pp.explicit := true`. -/ def setAppPPExplicit (e : Expr) : Expr := match e with | app .. => let f := e.getAppFn.setPPExplicit false let args := e.getAppArgs.map (·.setPPExplicit false) mkAppN f args |>.setPPExplicit true | _ => e /- Similar for `setAppPPExplicit`, but only annotate children with `pp.explicit := false` if `e` does not contain metavariables. -/ def setAppPPExplicitForExposingMVars (e : Expr) : Expr := match e with | app .. => let f := e.getAppFn.setPPExplicit false let args := e.getAppArgs.map fun arg => if arg.hasMVar then arg else arg.setPPExplicit false mkAppN f args |>.setPPExplicit true | _ => e end Expr def mkAnnotation (kind : Name) (e : Expr) : Expr := mkMData (KVMap.empty.insert kind (DataValue.ofBool true)) e def annotation? (kind : Name) (e : Expr) : Option Expr := match e with | Expr.mdata d b _ => if d.size == 1 && d.getBool kind false then some b else none | _ => none def mkFreshFVarId {m : Type → Type} [Monad m] [MonadNameGenerator m] : m FVarId := mkFreshId def mkFreshMVarId {m : Type → Type} [Monad m] [MonadNameGenerator m] : m FVarId := mkFreshId def mkNot (p : Expr) : Expr := mkApp (mkConst ``Not) p def mkOr (p q : Expr) : Expr := mkApp2 (mkConst ``Or) p q def mkAnd (p q : Expr) : Expr := mkApp2 (mkConst ``And) p q def mkEM (p : Expr) : Expr := mkApp (mkConst ``Classical.em) p end Lean
30b0cf6556f2db2ad7d9d73fe32b85bb29cd4a29
de91c42b87530c3bdcc2b138ef1a3c3d9bee0d41
/old/math_expr_old_4-8.lean
85452723373a57c768a1aa4dd616bdf51f63cc98
[]
no_license
kevinsullivan/lang
d3e526ba363dc1ddf5ff1c2f36607d7f891806a7
e9d869bff94fb13ad9262222a6f3c4aafba82d5e
refs/heads/master
1,687,840,064,795
1,628,047,969,000
1,628,047,969,000
282,210,749
0
1
null
1,608,153,830,000
1,595,592,637,000
Lean
UTF-8
Lean
false
false
1,950
lean
--import .expr_base import data.real.basic import .expr_base import ...math.aff1Kcoord.aff1Kcoord_std import ...phys.phys_dimensions namespace lang.math variables (K : Type*) [field K] [inhabited K] (f : fm K TIME) --only "one" space depends on f structure sp_var {K : Type*} [field K] [inhabited K] (f : fm K TIME) extends var inductive sp_expr {K : Type*} [field K] [inhabited K] (f : fm K TIME) | lit (sp : spc K f) : sp_expr | var (spv : sp_var f) : sp_expr abbreviation sp_env {K : Type*} [field K] [inhabited K] (f : fm K TIME) := sp_var f → spc K f abbreviation sp_eval {K : Type*} [field K] [inhabited K] (f : fm K TIME) := sp_env f → sp_expr f → spc K f structure fm_var extends var inductive fm_expr | lit (f : fm K TIME) : fm_expr | var (spv : fm_var) : fm_expr abbreviation fm_env := fm_var → fm K TIME abbreviation fm_eval := fm_env K → fm_expr K → fm K TIME --an environment containing a frame environment depends on a frame structure env := (sp : sp_env f) (f : fm_env K ) def env.init : env K f := ⟨ (λv, ⟨⟩), (λv, fm.base) ⟩ #check env.init K f end lang.math /- --import .expr_base import data.real.basic import .expr_base import ...math.aff1Kcoord.aff1Kcoord_std namespace lang.math variables (K : Type*) [field K] [inhabited K] (f : fm K TIME) structure sp_var extends var inductive sp_expr | lit (sp : spc K f) : sp_expr | var (spv : sp_var) : sp_expr abbreviation sp_env := sp_var → spc K f abbreviation sp_eval := sp_env K f → sp_expr K f → spc K f structure fm_var extends var inductive fm_expr | lit (f : fm K TIME) : fm_expr | var (spv : fm_var) : fm_expr abbreviation fm_env := fm_var → fm K TIME abbreviation fm_eval := fm_env K → fm_expr K → fm K TIME structure env := (sp : sp_env K f) (f : fm_env K ) def env.init : env K f := ⟨ (λv, ⟨⟩), (λv, fm.base) ⟩ #check env.init K f end lang.math-/
0bce48cd56e882297910e58f71990079ec01b753
a45212b1526d532e6e83c44ddca6a05795113ddc
/test/norm_num.lean
49578660775c6076fa1cff4b89dc6e8c13388bb9
[ "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
1,600
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 Tests for norm_num -/ import data.real.basic tactic.norm_num example : 374 + (32 - (2 * 8123) : ℤ) - 61 * 50 = 86 + 32 * 32 - 4 * 5000 ∧ 43 ≤ 74 + (33 : ℤ) := by norm_num example : ¬ (7-2)/(2*3) ≥ (1:ℝ) + 2/(3^2) := by norm_num example : (6:real) + 9 = 15 := by norm_num example : (2:real)/4 + 4 = 3*3/2 := by norm_num example : (((3:real)/4)-12)<6 := by norm_num example : (5:real) ≠ 8 := by norm_num example : (10:real) > 7 := by norm_num example : (2:real) * 2 + 3 = 7 := by norm_num example : (6:real) < 10 := by norm_num example : (7:real)/2 > 3 := by norm_num example : (4:real)⁻¹ < 1 := by norm_num example : (5 / 2:ℕ) = 2 := by norm_num example : (5 / -2:ℤ) < -1 := by norm_num example : (0 + 1) / 2 < 0 + 1 := by norm_num example (x : ℤ) (h : 1000 + 2000 < x) : 100 * 30 < x := by norm_num at *; try_for 100 {exact h} example : (1103 : ℤ) ≤ (2102 : ℤ) := by norm_num example : (110474 : ℤ) ≤ (210485 : ℤ) := by norm_num example : (11047462383473829263 : ℤ) ≤ (21048574677772382462 : ℤ) := by norm_num example : (210485742382937847263 : ℤ) ≤ (1104857462382937847262 : ℤ) := by norm_num example : (210485987642382937847263 : ℕ) ≤ (11048512347462382937847262 : ℕ) := by norm_num example : (210485987642382937847263 : ℚ) ≤ (11048512347462382937847262 : ℚ) := by norm_num example (x : ℕ) : ℕ := begin let n : ℕ, {apply_normed (2^32 - 71)}, exact n end
9f73851ef03c621ff37f6bf6f12c8fcbdfc1dee6
9dd3f3912f7321eb58ee9aa8f21778ad6221f87c
/library/init/category/functor.lean
292c2e1f2253109e58d6c01c55793f78b3235bd9
[ "Apache-2.0" ]
permissive
bre7k30/lean
de893411bcfa7b3c5572e61b9e1c52951b310aa4
5a924699d076dab1bd5af23a8f910b433e598d7a
refs/heads/master
1,610,900,145,817
1,488,006,845,000
1,488,006,845,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
472
lean
/- Copyright (c) Luke Nelson and Jared Roesch. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Luke Nelson and Jared Roesch -/ prelude import init.core universes u v class functor (f : Type u → Type v) : Type (max u+1 v) := (map : Π {a b : Type u}, (a → b) → f a → f b) @[inline] def fmap {f : Type u → Type v} [functor f] {a b : Type u} : (a → b) → f a → f b := functor.map infixr ` <$> `:100 := fmap
13bf0e78f32e0e5a81d62c4cd8f0d21453463d10
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/blast_unit_cc.lean
9d7afa02ecba327ad8882a747b3f1b860f6bd04c
[ "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
1,192
lean
-- Unit propagation with congruence closure constants (a b c d e : nat) constants (p : nat → Prop) constants (q : nat → nat → Prop) constants (f : nat → nat) set_option blast.recursor false set_option blast.subst false -- The following tests require the unit preprocessor to work /- definition lemma1 : a = d → b = e → p b → (p a → (¬ p e) ∧ p c) → ¬ p d := by blast definition lemma2a : ¬ p b → (p d → p b ∧ p c) → d = e → e = a → ¬ p a := by blast definition lemma2b : ¬ p (f b) → (p (f a) → p (f d) ∧ p (f c)) → b = d → ¬ p (f a) := by blast definition lemma3 : p (f (f b)) → (p (f a) → p (f c) ∧ (¬ p (f (f (f (f b)))))) → b = f b → ¬ p (f a) := by blast definition lemma4a : b = f b → ¬ p (f (f b)) → (p a → q c c ∧ p (f (f (f (f (f b)))))) → ¬ p a := by blast definition lemma4b : b = f b → ¬ p (f (f b)) → (p a → q c c ∧ q e c ∧ q d e ∧ p (f (f (f (f (f b))))) ∧ q e d) → ¬ p a := by blast definition lemma5 : p b → (p (f a) → (¬ p b) ∧ p e ∧ p c) → ¬ p (f a) := by blast definition lemma6 : ¬ (q b a) → d = a → (p a → p e ∧ (q b d) ∧ p c) → ¬ p a := by blast -/
9d9fc3154e29fc1c184fef82f78b0702d45703ad
968e2f50b755d3048175f176376eff7139e9df70
/examples/prop_logic_theory/unnamed_2177.lean
cb461c472d7f652346c506e8001426c705842473
[]
no_license
gihanmarasingha/mth1001_sphinx
190a003269ba5e54717b448302a27ca26e31d491
05126586cbf5786e521be1ea2ef5b4ba3c44e74a
refs/heads/master
1,672,913,933,677
1,604,516,583,000
1,604,516,583,000
309,245,750
1
0
null
null
null
null
UTF-8
Lean
false
false
443
lean
variables {p q : Prop} -- BEGIN theorem mt : (p → q) → (¬q → ¬p) := begin intros h₁ h₂, -- Assume `h₁ : p → q`, `h₂ : ¬q`. It suffices to prove `¬p`. intro h₃, -- Assume `h₃ : p`. By negation introiduction, it suffices to prove `false`. apply h₂, -- By fale introduction on `h₂`, it suffices to prove `q`. exact h₁ h₃, -- This follows by implication elimination on `h₁` and `h₃`. end -- END
e63a45ea2d4ca4a9a6083a7620c7f3b2e0f07614
367134ba5a65885e863bdc4507601606690974c1
/src/control/uliftable.lean
fd0b4678e875ce1f18321258c02c8e59db14ac6d
[ "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
5,579
lean
/- Copyright (c) 2020 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author(s): Simon Hudon -/ import control.monad.basic import control.monad.cont import control.monad.writer import data.equiv.basic import tactic.interactive /-! # Universe lifting for type families Some functors such as `option` and `list` are universe polymorphic. Unlike type polymorphism where `option α` is a function application and reasoning and generalizations that apply to functions can be used, `option.{u}` and `option.{v}` are not one function applied to two universe names but one polymorphic definition instantiated twice. This means that whatever works on `option.{u}` is hard to transport over to `option.{v}`. `uliftable` is an attempt at improving the situation. `uliftable option.{u} option.{v}` gives us a generic and composable way to use `option.{u}` in a context that requires `option.{v}`. It is often used in tandem with `ulift` but the two are purposefully decoupled. ## Main definitions * `uliftable` class ## Tags universe polymorphism functor -/ universes u₀ u₁ v₀ v₁ v₂ w w₀ w₁ /-- Given a universe polymorphic type family `M.{u} : Type u₁ → Type u₂`, this class convert between instantiations, from `M.{u} : Type u₁ → Type u₂` to `M.{v} : Type v₁ → Type v₂` and back -/ class uliftable (f : Type u₀ → Type u₁) (g : Type v₀ → Type v₁) := (congr [] {α β} : α ≃ β → f α ≃ g β) namespace uliftable /-- The most common practical use `uliftable` (together with `up`), this function takes `x : M.{u} α` and lifts it to M.{max u v} (ulift.{v} α) -/ @[reducible] def up {f : Type u₀ → Type u₁} {g : Type (max u₀ v₀) → Type v₁} [uliftable f g] {α} : f α → g (ulift α) := (uliftable.congr f g equiv.ulift.symm).to_fun /-- The most common practical use of `uliftable` (together with `up`), this function takes `x : M.{max u v} (ulift.{v} α)` and lowers it to `M.{u} α` -/ @[reducible] def down {f : Type u₀ → Type u₁} {g : Type (max u₀ v₀) → Type v₁} [uliftable f g] {α} : g (ulift α) → f α := (uliftable.congr f g equiv.ulift.symm).inv_fun /-- convenient shortcut to avoid manipulating `ulift` -/ def adapt_up (F : Type v₀ → Type v₁) (G : Type (max v₀ u₀) → Type u₁) [uliftable F G] [monad G] {α β} (x : F α) (f : α → G β) : G β := up x >>= f ∘ ulift.down /-- convenient shortcut to avoid manipulating `ulift` -/ def adapt_down {F : Type (max u₀ v₀) → Type u₁} {G : Type v₀ → Type v₁} [L : uliftable G F] [monad F] {α β} (x : F α) (f : α → G β) : G β := @down.{v₀ v₁ (max u₀ v₀)} G F L β $ x >>= @up.{v₀ v₁ (max u₀ v₀)} G F L β ∘ f /-- map function that moves up universes -/ def up_map {F : Type u₀ → Type u₁} {G : Type.{max u₀ v₀} → Type v₁} [inst : uliftable F G] [functor G] {α β} (f : α → β) (x : F α) : G β := functor.map (f ∘ ulift.down) (up x) /-- map function that moves down universes -/ def down_map {F : Type.{max u₀ v₀} → Type u₁} {G : Type → Type v₁} [inst : uliftable G F] [functor F] {α β} (f : α → β) (x : F α) : G β := down (functor.map (ulift.up ∘ f) x : F (ulift β)) @[simp] lemma up_down {f : Type u₀ → Type u₁} {g : Type (max u₀ v₀) → Type v₁} [uliftable f g] {α} (x : g (ulift α)) : up (down x : f α) = x := (uliftable.congr f g equiv.ulift.symm).right_inv _ @[simp] lemma down_up {f : Type u₀ → Type u₁} {g : Type (max u₀ v₀) → Type v₁} [uliftable f g] {α} (x : f α) : down (up x : g _) = x := (uliftable.congr f g equiv.ulift.symm).left_inv _ end uliftable open ulift instance : uliftable id id := { congr := λ α β F, F } /-- for specific state types, this function helps to create a uliftable instance -/ def state_t.uliftable' {s : Type u₀} {s' : Type u₁} {m : Type u₀ → Type v₀} {m' : Type u₁ → Type v₁} [uliftable m m'] (F : s ≃ s') : uliftable (state_t s m) (state_t s' m') := { congr := λ α β G, state_t.equiv $ equiv.Pi_congr F $ λ _, uliftable.congr _ _ $ equiv.prod_congr G F } instance {s m m'} [uliftable m m'] : uliftable (state_t s m) (state_t (ulift s) m') := state_t.uliftable' equiv.ulift.symm /-- for specific reader monads, this function helps to create a uliftable instance -/ def reader_t.uliftable' {s s' m m'} [uliftable m m'] (F : s ≃ s') : uliftable (reader_t s m) (reader_t s' m') := { congr := λ α β G, reader_t.equiv $ equiv.Pi_congr F $ λ _, uliftable.congr _ _ G } instance {s m m'} [uliftable m m'] : uliftable (reader_t s m) (reader_t (ulift s) m') := reader_t.uliftable' equiv.ulift.symm /-- for specific continuation passing monads, this function helps to create a uliftable instance -/ def cont_t.uliftable' {r r' m m'} [uliftable m m'] (F : r ≃ r') : uliftable (cont_t r m) (cont_t r' m') := { congr := λ α β, cont_t.equiv (uliftable.congr _ _ F) } instance {s m m'} [uliftable m m'] : uliftable (cont_t s m) (cont_t (ulift s) m') := cont_t.uliftable' equiv.ulift.symm /-- for specific writer monads, this function helps to create a uliftable instance -/ def writer_t.uliftable' {w w' m m'} [uliftable m m'] (F : w ≃ w') : uliftable (writer_t w m) (writer_t w' m') := { congr := λ α β G, writer_t.equiv $ uliftable.congr _ _ $ equiv.prod_congr G F } instance {s m m'} [uliftable m m'] : uliftable (writer_t s m) (writer_t (ulift s) m') := writer_t.uliftable' equiv.ulift.symm
ebbbe7f13ec01d36a3634be9e1bb0e4a0e95be95
9bf90df35bb15a2f76571e35c48192142a328c40
/src/ch3.lean
13b665ed6d0eacf36946774e93a64643da5917f4
[]
no_license
ehaskell1/set_theory
ed0726520e84990d5f3180bafa0a3674ed31fb5e
e6c829c4dd953d98c9cba08f9f79784cd91794fb
refs/heads/master
1,693,282,405,362
1,636,928,916,000
1,636,928,916,000
428,055,746
0
0
null
null
null
null
UTF-8
Lean
false
false
79,222
lean
import ch2 universe u namespace Set @[simp] lemma pair_mem_pair_sep {p : Set → Set → Prop} {x y a b : Set} : a.pair b ∈ pair_sep p x y ↔ a ∈ x ∧ b ∈ y ∧ p a b := begin simp only [mem_pair_sep], split, { rintro ⟨a', ha, b', hb, he, hp⟩, have hpe : a = a' ∧ b = b' := pair_inj he, simp only [hpe.left, hpe.right], exact ⟨ha, hb, hp⟩, }, { rintro ⟨ha, hb, hp⟩, exact ⟨a, ha, b, hb, rfl, hp⟩, }, end lemma pair_mem_pair_sep' {p : Set → Set → Prop} {x y a : Set} (a' : a ∈ x) {b : Set} (b' : b ∈ y) : a.pair b ∈ pair_sep p x y ↔ p a b := begin simp only [pair_mem_pair_sep], split, rintro ⟨-, -, pab⟩, exact pab, intro pab, exact ⟨a', b', pab⟩, end theorem pair_unordered {a b : Set} : ({a, b} : Set) = {b, a} := begin apply ext, intro z, simp only [mem_pair, or_comm], end -- We have x.pair y = {{x}, {x, y}} -- And pair_inj which shows injectivity of pair -- pair_sep p x y supplies us with the set of all ordered pairs from x × y that satisfies p -- Corralary 3C is basically mem_pair_sep -- We also have prod and mem_prod theorem ch3_p4 : ¬ ∃ S : Set, ∀ x y : Set, x.pair y ∈ S := begin rintro ⟨S, h⟩, apply univ_not_set, refine ⟨S.Union.Union, _⟩, intro x, specialize h x x, rw mem_Union, refine ⟨{x}, _, _⟩, rw mem_Union, refine ⟨x.pair x, h, _⟩, simp only [pair, true_or, eq_self_iff_true, mem_pair], simp only [mem_singleton], end def is_pair (x : Set) : Prop := ∃ (y z : Set), x = y.pair z def is_rel (R : Set) : Prop := ∀ x : Set, x ∈ R → x.is_pair def dom (R : Set) : Set := {x ∈ R.Union.Union | ∃ y, x.pair y ∈ R} def ran (R : Set) : Set := {x ∈ R.Union.Union | ∃ t : Set, t.pair x ∈ R} def fld (R : Set) : Set := R.dom ∪ R.ran lemma empty_is_rel : (∅ : Set).is_rel := begin intros x hx, exfalso, exact mem_empty _ hx, end lemma singleton_is_rel {x y : Set} : ({x.pair y} : Set).is_rel := begin intros z hz, rw mem_singleton at hz, exact ⟨_, _, hz⟩, end lemma inter_rel_is_rel {R : Set} (hR : R.is_rel) {S : Set} : (R ∩ S).is_rel := begin intros x hx, rw [mem_inter] at hx, exact hR _ hx.left, end lemma union_rel_is_rel {R : Set} (hR : R.is_rel) {S : Set} (hS : S.is_rel) : (R ∪ S).is_rel := begin intros x hx, rw [mem_union] at hx, cases hx, exact hR _ hx, exact hS _ hx, end lemma Union_is_rel {S : Set} (h : ∀ ⦃x : Set⦄, x ∈ S → x.is_rel) : S.Union.is_rel := begin intros z hz, rw mem_Union at hz, rcases hz with ⟨x, hx, hz⟩, exact h hx _ hz, end lemma rel_eq {R : Set} (hR : R.is_rel) {S : Set} (hS : S.is_rel) (h : ∀ ⦃x y : Set⦄, x.pair y ∈ R ↔ x.pair y ∈ S) : R = S := begin apply ext, intro z, split, { intro hz, have hxy := hR _ hz, rcases hxy with ⟨x, y, hxy⟩, rw hxy at hz, rw hxy, rw ←h, exact hz, }, { intro hz, have hxy := hS _ hz, rcases hxy with ⟨x, y, hxy⟩, rw hxy at hz, rw hxy, rw h, exact hz, }, end lemma rel_eq_empty {R : Set} (hR : R.is_rel) : R = ∅ ↔ ∀ ⦃x y : Set⦄, x.pair y ∉ R := begin split, { intro he, simp only [he, mem_empty, forall_const, not_false_iff], }, { intro ha, apply rel_eq hR empty_is_rel, intros x y, split, { intro h, exfalso, exact ha h, }, { intro h, exfalso, exact mem_empty _ h, }, }, end lemma is_pair_of_mem_prod {p A B : Set} (h : p ∈ A.prod B) : p.is_pair := begin simp only [mem_prod, exists_prop] at h, rcases h with ⟨a, ha, b, hb, he⟩, exact ⟨_, _, he⟩, end lemma pair_sep_is_rel {p : Set → Set → Prop} {x y : Set} : (pair_sep p x y).is_rel := begin intros z hz, simp only [mem_pair_sep] at hz, rcases hz with ⟨a, ha, b, hb, he, hp⟩, exact ⟨a, b, he⟩, end lemma prod_is_rel {X Y : Set} : (X.prod Y).is_rel := pair_sep_is_rel lemma sub_rel_is_rel {X Y : Set} (hY : Y.is_rel) (XY : X ⊆ Y) : X.is_rel := λ z, assume zX, hY _ (XY zX) lemma diff_is_rel {X Y : Set} (hX : X.is_rel) : (X \ Y).is_rel := sub_rel_is_rel hX subset_diff theorem rel_sub {R : Set} (hR : R.is_rel) {S : Set} (hext : ∀ ⦃x y : Set⦄, x.pair y ∈ R → x.pair y ∈ S) : R ⊆ S := begin intros z hz, specialize hR z hz, rcases hR with ⟨x, y, he⟩, subst he, exact hext hz, end theorem rel_ext {R : Set} (hR : R.is_rel) {S : Set} (hS : S.is_rel) (hext : ∀ ⦃x y : Set⦄, x.pair y ∈ R ↔ x.pair y ∈ S) : R = S := begin rw eq_iff_subset_and_subset, refine ⟨rel_sub hR _, rel_sub hS _⟩, intros x y hxy, exact (@hext x y).mp hxy, intros x y hxy, exact (@hext x y).mpr hxy, end theorem rel_ext' {A B R : Set} (RAB : R ⊆ A.prod B) {S : Set} (SAB : S ⊆ A.prod B) (hext : ∀ ⦃x : Set⦄, x ∈ A → ∀ ⦃y : Set⦄, y ∈ B → (x.pair y ∈ R ↔ x.pair y ∈ S)) : R = S := begin apply rel_ext (sub_rel_is_rel prod_is_rel RAB) (sub_rel_is_rel prod_is_rel SAB), intros x y, split; intros xy, have xy' := RAB xy, rw pair_mem_prod at xy', rw ←hext xy'.left xy'.right, exact xy, have xy' := SAB xy, rw pair_mem_prod at xy', rw hext xy'.left xy'.right, exact xy, end section local attribute [instance] classical.prop_decidable lemma prod_diff {A B C : Set} : A.prod B \ A.prod C = A.prod (B \ C) := begin apply rel_ext (diff_is_rel prod_is_rel) prod_is_rel, simp only [mem_diff, pair_mem_prod], tauto, end end lemma union_prod {A B C : Set} : (A ∪ B).prod C = (A.prod C) ∪ (B.prod C) := begin apply rel_ext prod_is_rel (union_rel_is_rel prod_is_rel prod_is_rel), simp only [pair_mem_prod, mem_union, or_and_distrib_right, iff_self, forall_const], end lemma prod_union {A B C : Set} : A.prod (B ∪ C) = (A.prod B) ∪ (A.prod C) := begin apply rel_ext prod_is_rel (union_rel_is_rel prod_is_rel prod_is_rel), simp only [pair_mem_prod, mem_union, and_or_distrib_left, iff_self, forall_const], end lemma prod_inter {A B C : Set} : A.prod (B ∩ C) = A.prod B ∩ A.prod C := begin apply rel_ext prod_is_rel (sub_rel_is_rel prod_is_rel inter_subset_right), simp only [pair_mem_prod, mem_inter], intros x y, nth_rewrite 3 and_comm, rw and_assoc, nth_rewrite 2 ←and_assoc, rw and_self, simp only [←and_assoc], nth_rewrite 1 and_comm, end lemma pair_sep_sub_prod {p : Set → Set → Prop} {x y : Set} : pair_sep p x y ⊆ x.prod y := begin intro p, simp only [mem_pair_sep, mem_prod, exists_prop], rintro ⟨a, ha, b, hb, he, hp⟩, exact ⟨_, ha, _, hb, he⟩, end lemma L3D_bulk {x y A : Set} (h : x.pair y ∈ A) : {x, y} ∈ A.Union := begin rw mem_Union, refine ⟨_, h, _⟩, simp only [pair, mem_pair], right, refl, end lemma L3D_left {x y A : Set} (h : x.pair y ∈ A) : x ∈ A.Union.Union := begin rw mem_Union, refine ⟨_, L3D_bulk h, _⟩, simp only [mem_pair], left, refl, end lemma L3D_right {x y A : Set} (h : x.pair y ∈ A) : y ∈ A.Union.Union := begin rw mem_Union, refine ⟨_, L3D_bulk h, _⟩, simp only [mem_pair], right, refl, end @[simp] lemma mem_dom {R : Set} (x : Set) : x ∈ R.dom ↔ ∃ y, x.pair y ∈ R := begin simp only [dom, mem_sep], apply and_iff_right_of_left_if_right, rintro ⟨y, h⟩, exact L3D_left h, end @[simp] lemma mem_ran {R : Set} (x : Set) : x ∈ R.ran ↔ ∃ t : Set, t.pair x ∈ R := begin simp only [ran, mem_sep], apply and_iff_right_of_left_if_right, rintro ⟨t, h⟩, exact L3D_right h, end lemma ran_empty_eq_empty : ran ∅ = ∅ := begin rw eq_empty, intros y hy, rw mem_ran at hy, rcases hy with ⟨x, hxy⟩, exact mem_empty _ hxy, end lemma dom_empty_eq_empty : dom ∅ = ∅ := begin rw eq_empty, intros x hx, rw mem_dom at hx, rcases hx with ⟨y, hxy⟩, exact mem_empty _ hxy, end lemma ran_ne_of_ne {C A B : Set} (CAB : C ⊆ A.prod B) (Cne : C ≠ ∅) : C.ran ≠ ∅ := begin intro Ce, apply Cne, rw eq_empty, intros z zC, specialize CAB zC, rw mem_prod at CAB, rcases CAB with ⟨a, aC, b, bB, zab⟩, subst zab, apply mem_empty b, rw [←Ce, mem_ran], exact ⟨_, zC⟩, end lemma pair_sep_dom_sub {p : Set → Set → Prop} {x y : Set} : (pair_sep p x y).dom ⊆ x := begin intros z hz, simp only [mem_dom, pair_mem_pair_sep] at hz, finish, end @[simp] lemma dom_singleton {x y : Set} : ({x.pair y} : Set).dom = {x} := begin apply ext, simp only [mem_singleton, mem_dom], intro z, split, { rintro ⟨y, hy⟩, exact (pair_inj hy).left, }, { rintro hx, rw hx, exact ⟨_, rfl⟩, }, end @[simp] lemma ran_singleton {x y : Set} : ({x.pair y} : Set).ran = {y} := begin apply ext, simp only [mem_singleton, mem_ran], intro z, split, { rintro ⟨y, hy⟩, exact (pair_inj hy).right, }, { rintro hx, rw hx, exact ⟨_, rfl⟩, }, end -- chapter 3 problem 6 lemma rel_sub_dom_ran {R : Set} : R.is_rel ↔ R ⊆ R.dom.prod R.ran := begin split, intros hR z hz, rw mem_prod, specialize hR _ hz, rcases hR with ⟨x, y, hxy⟩, rw hxy at hz, simp only [exists_prop, mem_dom, mem_ran], exact ⟨_, ⟨_, hz⟩, _, ⟨_, hz⟩, hxy⟩, intros hR z hz, specialize hR hz, simp only [mem_prod, exists_prop] at hR, rcases hR with ⟨x, hx, y, hy, he⟩, exact ⟨_, _, he⟩, end def fst (p : Set) : Set := ({p} : Set).dom.Union def snd (p : Set) : Set := ({p} : Set).ran.Union lemma fst_snd_spec {p : Set} (hp : p.is_pair) : p = p.fst.pair p.snd := begin rcases hp with ⟨x, y, hp⟩, rw hp, congr, { rw [fst, dom_singleton, Union_singleton], }, { rw [snd, ran_singleton, Union_singleton], }, end lemma fst_congr {x y : Set} : (x.pair y).fst = x := begin have h : x.pair y = (x.pair y).fst.pair (x.pair y).snd := fst_snd_spec ⟨_, _, rfl⟩, symmetry, exact (pair_inj h).left, end lemma snd_congr {x y : Set} : (x.pair y).snd = y := begin have h : x.pair y = (x.pair y).fst.pair (x.pair y).snd := fst_snd_spec ⟨_, _, rfl⟩, symmetry, exact (pair_inj h).right, end lemma pair_eq {p : Set} (hp : p.is_pair) {q : Set} (hq : q.is_pair) (hf : p.fst = q.fst) (hs : p.snd = q.snd) : p = q := begin rcases hp with ⟨a, b, pab⟩, rcases hq with ⟨c, d, qcd⟩, subst pab, subst qcd, simp only [fst_congr] at hf, simp only [snd_congr] at hs, rw [hf, hs], end lemma fst_ne_of_pair_ne {x y z : Set} (h : x.pair z ≠ y.pair z) : x ≠ y := begin intro xy, subst xy, exact h rfl, end lemma fst_snd_mem_dom_ran {p A B : Set} (hp : p ∈ A.prod B) : p.fst ∈ A ∧ p.snd ∈ B := begin simp only [mem_prod, exists_prop] at hp, rcases hp with ⟨a, ha, b, hb, he⟩, have he' : a.pair b = p.fst.pair p.snd, rw ←he, exact fst_snd_spec ⟨_, _, he⟩, rw [←(pair_inj he').left, ←(pair_inj he').right], finish, end lemma ran_subset_of_subset {H F : Set} (h : H ⊆ F) : H.ran ⊆ F.ran := begin intro z, simp only [mem_ran], rintro ⟨x, hx⟩, exact ⟨x, h hx⟩, end lemma ran_prod {A B : Set} : (A.prod B).ran ⊆ B := begin intro b, simp only [mem_ran, pair_mem_prod], rintro ⟨-, -, xB⟩, exact xB, end lemma ran_sub_of_sub_prod {C A B : Set} (CAB : C ⊆ A.prod B) : C.ran ⊆ B := subset_trans (ran_subset_of_subset CAB) ran_prod lemma ran_Union_eq_Union_ran {C A : Set} (hA : ∀ ⦃y⦄, y ∈ A ↔ ∃ f : Set, y ∈ f.ran ∧ f ∈ C) : A = C.Union.ran := begin apply ext, simp only [hA, mem_ran], intro y, split, rintro ⟨f, ⟨x, hxy⟩, hf⟩, use x, rw mem_Union, exact ⟨_, hf, hxy⟩, rintro ⟨x, hxy⟩, rw mem_Union at hxy, rcases hxy with ⟨f, hf, hxy⟩, exact ⟨_, ⟨_, hxy⟩, hf⟩, end lemma dom_Union_eq_Union_dom {C A : Set} (hA : ∀ ⦃x⦄, x ∈ A ↔ ∃ f : Set, x ∈ f.dom ∧ f ∈ C) : A = C.Union.dom := begin apply ext, simp only [hA, mem_dom], intro x, split, rintro ⟨f, ⟨y, hxy⟩, hf⟩, use y, rw mem_Union, exact ⟨_, hf, hxy⟩, rintro ⟨y, hxy⟩, rw mem_Union at hxy, rcases hxy with ⟨f, hf, hxy⟩, exact ⟨_, ⟨_, hxy⟩, hf⟩, end def pow : Set → ℕ → Set | S 0 := {∅} | S 1 := S | S (n + 1) := (S.pow n).prod S def is_n_ary (S : Set) (n : ℕ) : Prop := S ⊆ S.pow n def is_function (F : Set) : Prop := F.is_rel ∧ ∀ x : Set, x ∈ F.dom → ∃! y, x.pair y ∈ F def fun_value (F x : Set) : Set := {y ∈ F.Union.Union | x.pair y ∈ F}.Union lemma is_function_iff {F : Set} : F.is_function ↔ F.is_rel ∧ ∀ x y y' : Set, x.pair y ∈ F → x.pair y' ∈ F → y = y' := begin simp only [is_function, mem_dom, exists_imp_distrib, and.congr_right_iff], intro hr, split, { intros h x y y' hy hy', refine unique_of_exists_unique (h _ _ hy) hy hy', }, { intros h x y hy, exact exists_unique_of_exists_of_unique ⟨_, hy⟩ (h x), }, end @[simp] lemma mem_fun_value {F x z : Set} : z ∈ F.fun_value x ↔ ∃ y : Set, x.pair y ∈ F ∧ z ∈ y := begin simp only [fun_value, mem_Union], split, { rintro ⟨y, h₁, h₂⟩, simp only [mem_sep] at h₁, exact ⟨_, h₁.right, h₂⟩, }, { rintro ⟨y, h₁, h₂⟩, refine ⟨_, _, h₂⟩, simp only [mem_sep], exact ⟨L3D_right h₁, h₁⟩, }, end lemma fun_lemma {F x y z : Set} (hf : F.is_function) (hy : x.pair y ∈ F) (hz : x.pair z ∈ F) : y = z := begin have hd : x ∈ F.dom, simp only [mem_dom], exact ⟨_, hy⟩, exact unique_of_exists_unique (hf.right x hd) hy hz, end lemma fun_value_def {F x y : Set} (hf : F.is_function) (hp : x.pair y ∈ F) : y = F.fun_value x := begin apply ext, intro z, simp only [mem_fun_value], split, { intro hm, exact ⟨_, hp, hm⟩, }, { rintro ⟨w, hw, hm⟩, rw fun_lemma hf hp hw, assumption, }, end lemma fun_value_def' {F x : Set} (hf : F.is_function) (hd : x ∈ F.dom) : x.pair (F.fun_value x) ∈ F := begin simp only [mem_dom] at hd, rcases hd with ⟨y, hy⟩, rw ←fun_value_def hf hy, exact hy, end lemma fun_value_def'' {F x : Set} (hf : F.is_function) (hd : x ∈ F.dom) : (F.fun_value x) ∈ F.ran := begin simp only [mem_ran], exact ⟨x, fun_value_def' hf hd⟩, end lemma fun_value_def''' {F x y : Set} (hf : F.is_function) (hd : x ∈ F.dom) (hy : y = F.fun_value x) : x.pair y ∈ F := begin rw hy, exact fun_value_def' hf hd, end lemma eq_fun_value_of_mem_ran {F y : Set} (hf : F.is_function) (hy : y ∈ F.ran) : ∃ x ∈ F.dom, y = F.fun_value x := begin rw mem_ran at hy, rcases hy with ⟨x, hy⟩, refine ⟨x, _, _⟩, { rw mem_dom, exact ⟨_, hy⟩, }, { exact fun_value_def hf hy, }, end lemma mem_ran_iff {F : Set} (hf : F.is_function) {y : Set} : y ∈ F.ran ↔ ∃ x : Set, x ∈ F.dom ∧ y = F.fun_value x := begin split, { intro hy, have h := eq_fun_value_of_mem_ran hf hy, simp only [exists_prop] at h, assumption, }, { rintro ⟨x, hx, he⟩, rw he, exact fun_value_def'' hf hx, }, end lemma of_ran {f : Set} (ffun : f.is_function) {p : Set → Prop} (h : ∀ {x : Set}, x ∈ f.dom → p (f.fun_value x)) : ∀ ⦃y : Set⦄, y ∈ f.ran → p y := begin intro y, rw mem_ran_iff ffun, rintro ⟨x, xf, e⟩, subst e, exact h xf, end lemma dom_ran_eq_empty_iff {R : Set} : R.dom = ∅ ↔ R.ran = ∅ := begin split, intro de, rw eq_empty, intros y yr, rw mem_ran at yr, rcases yr with ⟨x, xyR⟩, apply mem_empty x, rw ←de, rw mem_dom, exact ⟨_, xyR⟩, intro re, rw eq_empty, intros x xd, rw mem_dom at xd, rcases xd with ⟨y, xyR⟩, apply mem_empty y, rw ←re, rw mem_ran, exact ⟨_, xyR⟩, end lemma ran_sub {F : Set} (hf : F.is_function) {A : Set} (h : ∀ x : Set, x ∈ F.dom → F.fun_value x ∈ A) : F.ran ⊆ A := begin intro y, rw mem_ran_iff hf, rintro ⟨x, xdom, Fx⟩, subst Fx, exact h _ xdom, end def into_fun (F A B : Set) : Prop := F.is_function ∧ F.dom = A ∧ F.ran ⊆ B lemma fun_def_equiv {F A B : Set} : F.into_fun A B ↔ A.is_func B F := begin split, { rintro ⟨⟨hf, hu⟩, hd, hr⟩, refine ⟨λ p hp, _, λ x hx, _⟩, { simp only [mem_prod], specialize hf p hp, rcases hf with ⟨x, y, he⟩, have hx : x ∈ A, rw [←hd, mem_dom], use y, rw ←he, assumption, have hy : y ∈ B, apply hr, rw mem_ran, use x, rw ←he, assumption, exact ⟨_, hx, _, hy, he⟩, }, { rw [←hd, mem_dom] at hx, apply exists_unique_of_exists_of_unique hx (λ y₁ y₂ hy₁ hy₂, _), refine unique_of_exists_unique (hu x _) hy₁ hy₂, { rw mem_dom, assumption, }, }, }, { rintro ⟨hsp, hu⟩, refine ⟨⟨λ p hp, _, λ x hx, _⟩, _, _⟩, { specialize hsp hp, rw mem_prod at hsp, rcases hsp with ⟨x, hx, y, hp, he⟩, exact ⟨_, _, he⟩, }, { apply hu, rw mem_dom at hx, rcases hx with ⟨y, hp⟩, specialize hsp hp, rw mem_prod at hsp, rcases hsp with ⟨a, ha, b, hb, he⟩, rw (pair_inj he).left, assumption, }, { apply ext, simp only [mem_dom], intro x, split, { rintro ⟨y, hp⟩, specialize hsp hp, rw mem_prod at hsp, rcases hsp with ⟨a, ha, b, hb, he⟩, rw (pair_inj he).left, assumption, }, { intro hx, exact exists_of_exists_unique (hu _ hx), }, }, { intros y hy, rw mem_ran at hy, rcases hy with ⟨x, hp⟩, specialize hsp hp, rw mem_prod at hsp, rcases hsp with ⟨a, ha, b, hb, he⟩, rw (pair_inj he).right, assumption, }, }, end lemma is_function_of_into {F A B : Set} (hf : F.into_fun A B) : F.is_function := hf.left lemma dom_eq_of_into {F A B : Set} (hf : F.into_fun A B) : F.dom = A := hf.right.left lemma ran_sub_of_into {F A B : Set} (hf : F.into_fun A B) : F.ran ⊆ B := hf.right.right def onto_fun (F A B : Set) : Prop := F.is_function ∧ F.dom = A ∧ F.ran = B def one_to_one (F : Set) : Prop := ∀ y : Set, y ∈ F.ran → ∃! x : Set, x.pair y ∈ F -- also called single-rooted def inv (F : Set) : Set := pair_sep (λ a b, b.pair a ∈ F) F.ran F.dom lemma inv_sub_prod {R A B : Set} (RAB : R ⊆ A.prod B) : R.inv ⊆ B.prod A := begin intros z zR, simp only [inv, mem_pair_sep] at zR, rcases zR with ⟨a, -, b, -, zab, baR⟩, subst zab, specialize RAB baR, rw mem_prod at RAB, rcases RAB with ⟨c, cA, d, dB, bacd⟩, obtain ⟨bc, ad⟩ := pair_inj bacd, subst bc, subst ad, rw pair_mem_prod, finish, end lemma one_to_one_of {F : Set} (hf : F.is_function) (h : ∀ {m : Set}, m ∈ F.dom → ∀ {n : Set}, n ∈ F.dom → m ≠ n → F.fun_value m ≠ F.fun_value n) : F.one_to_one := begin intros y hy, rw mem_ran at hy, rcases hy with ⟨x, hx⟩, refine ⟨_, hx, _⟩, intros x' hx', apply classical.by_contradiction, intros hne, refine @h x _ x' _ _ _, { rw mem_dom, exact ⟨_, hx⟩, }, { rw mem_dom, exact ⟨_, hx'⟩, }, { intro he, apply hne, symmetry, assumption, }, { rw ←fun_value_def hf hx, rw ←fun_value_def hf hx', }, end lemma from_one_to_one {F : Set} (hf : F.is_function) (hoto : F.one_to_one) {x x' : Set} (hx : x ∈ F.dom) (hx' : x' ∈ F.dom) (he : F.fun_value x = F.fun_value x') : x = x' := begin refine unique_of_exists_unique (hoto (F.fun_value x) _) _ _, { apply fun_value_def'' hf, assumption, }, { apply fun_value_def' hf, assumption, }, { rw he, apply fun_value_def' hf, assumption, }, end lemma eq_iff_fun_value_eq_of_oto {F : Set} (hf : F.is_function) (hoto : F.one_to_one) {x x' : Set} (hx : x ∈ F.dom) (hx' : x' ∈ F.dom) : x = x' ↔ F.fun_value x = F.fun_value x' := ⟨λ xx, xx ▸ rfl, λ fxx, from_one_to_one hf hoto hx hx' fxx⟩ lemma one_to_one_iff {R : Set} : R.one_to_one ↔ ∀ {y x x' : Set}, x.pair y ∈ R → x'.pair y ∈ R → x = x' := begin simp only [one_to_one, mem_ran], split, intros h y x x' hxy hxy', apply unique_of_exists_unique (h _ ⟨_, hxy⟩) hxy hxy', rintros h y ex, apply exists_unique_of_exists_of_unique ex, intros x x' hxy hxy', exact h hxy hxy', end lemma onto_of_into {F A B : Set} (hf : F.into_fun A B) (he : F.ran = B) : F.onto_fun A B := ⟨is_function_of_into hf, dom_eq_of_into hf, he⟩ lemma onto_ran_of_into {F A B : Set} (hf : F.into_fun A B) : F.onto_fun A F.ran := ⟨hf.left, hf.right.left, rfl⟩ lemma into_of_onto {F A B : Set} (hf : F.onto_fun A B) : F.into_fun A B := begin rcases hf with ⟨hf, hd, hr⟩, refine ⟨hf, hd, _⟩, rw hr, exact subset_self, end lemma into_of_into_ran_sub {F A B C : Set} (h : B ⊆ C) (hf : F.into_fun A B) : F.into_fun A C := ⟨hf.left, hf.right.left, subset_trans hf.right.right h⟩ lemma into_of_onto_ran_sub {F A B C : Set} (h : B ⊆ C) (hf : F.onto_fun A B) : F.into_fun A C := into_of_into_ran_sub h (into_of_onto hf) lemma singleton_is_fun {x y : Set} : is_function {x.pair y} := begin rw [is_function_iff], split, exact singleton_is_rel, intros a b b' hab hab', rw [mem_singleton] at hab hab', rw ←hab' at hab, exact (pair_inj hab).right, end lemma union_singleton_is_fun {F : Set} (hF : F.is_function) {x y : Set} (hx : x ∉ F.dom) : (F ∪ {x.pair y}).is_function := begin rw is_function_iff, split, exact union_rel_is_rel hF.left singleton_is_rel, intros a b b' hb hb', rw [mem_union, mem_singleton] at hb hb', rw is_function_iff at hF, cases hb; cases hb', exact hF.right _ _ _ hb hb', exfalso, apply hx, rw mem_dom, rw (pair_inj hb').left at hb, exact ⟨_, hb⟩, exfalso, apply hx, rw mem_dom, rw (pair_inj hb).left at hb', exact ⟨_, hb'⟩, rw ←hb' at hb, exact (pair_inj hb).right, end lemma union_singleton_one_to_one {F : Set} (hF : F.one_to_one) {x y : Set} (hy : y ∉ F.ran) : (F ∪ {x.pair y}).one_to_one := begin rw one_to_one_iff at *, simp only [mem_union, mem_singleton], rintros b a a' (hab|hab) (hab'|hab'), exact hF hab hab', exfalso, apply hy, rw mem_ran, rw (pair_inj hab').right at hab, exact ⟨_, hab⟩, exfalso, apply hy, rw mem_ran, rw (pair_inj hab).right at hab', exact ⟨_, hab'⟩, rw [(pair_inj hab).left, (pair_inj hab').left], end @[simp] lemma mem_inv {F p : Set} : p ∈ F.inv ↔ ∃ (a b : Set), p = a.pair b ∧ b.pair a ∈ F := begin simp only [inv, mem_pair_sep], split, { rintro ⟨a, ha, b, hb, he, hm⟩, exact ⟨_, _, he, hm⟩, }, { rintro ⟨a, b, he, hm⟩, refine ⟨_, _, _, _, he, hm⟩, rw mem_ran, exact ⟨_, hm⟩, rw mem_dom, exact ⟨_, hm⟩, }, end lemma inv_rel {F : Set} : F.inv.is_rel := pair_sep_is_rel @[simp] lemma pair_mem_inv {F a b : Set} : a.pair b ∈ F.inv ↔ b.pair a ∈ F := begin simp only [mem_inv], split, { rintro ⟨x, y, he, hm⟩, suffices hinj : a = x ∧ b = y, rw hinj.left, rw hinj.right, assumption, exact pair_inj he, }, { intro h, exact ⟨a, b, rfl, h⟩, }, end lemma inv_inv {F : Set} (hf : F.is_rel) : F.inv.inv = F := begin apply rel_eq inv_rel hf, simp only [pair_mem_inv], finish, end def comp (F G : Set) : Set := pair_sep (λ a b, ∃ t : Set, a.pair t ∈ G ∧ t.pair b ∈ F) G.dom F.ran lemma comp_rel {F G : Set} : (F.comp G).is_rel := pair_sep_is_rel @[simp] lemma mem_comp {F G p : Set} : p ∈ F.comp G ↔ ∃ (a b c : Set), p = a.pair c ∧ a.pair b ∈ G ∧ b.pair c ∈ F := begin simp only [comp, mem_pair_sep], split, { rintro ⟨a, ha, b, hb, he, t, hm1, hm2⟩, exact ⟨a, t, b, he, hm1, hm2⟩, }, { rintro ⟨a, b, c, he, hm1, hm2⟩, refine ⟨a, _, c, _, he, _, hm1, hm2⟩, rw mem_dom, exact ⟨_, hm1⟩, rw mem_ran, exact ⟨_, hm2⟩, }, end @[simp] lemma pair_mem_comp {F G a c : Set} : a.pair c ∈ F.comp G ↔ ∃ b : Set, a.pair b ∈ G ∧ b.pair c ∈ F := begin simp only [mem_comp], split, { rintro ⟨a', b, c', he, hg, hf⟩, have hinj : a = a' ∧ c = c' := pair_inj he, rw hinj.left, rw hinj.right, exact ⟨_, hg, hf⟩, }, { rintro ⟨b, hg, hf⟩, exact ⟨_, _, _, rfl, hg, hf⟩, }, end def restrict (F A : Set) : Set := pair_sep (λ a b, a.pair b ∈ F ∧ a ∈ A) F.dom F.ran lemma restrict_is_rel {F A : Set} : (F.restrict A).is_rel := pair_sep_is_rel @[simp] lemma mem_restrict {F A p : Set} : p ∈ F.restrict A ↔ ∃ (a b : Set), p = a.pair b ∧ a.pair b ∈ F ∧ a ∈ A := begin simp only [restrict, mem_pair_sep], split; intro h, rcases h with ⟨a, H₁, b, H₂, h₁, h₂, h₃⟩, exact ⟨_, _, h₁, h₂, h₃⟩, rcases h with ⟨a, b, h₁, h₂, h₃⟩, refine ⟨a, _, b, _, _⟩, simp only [mem_dom], exact ⟨_, h₂⟩, simp only [mem_ran], exact ⟨_, h₂⟩, exact ⟨h₁, h₂, h₃⟩, end @[simp] lemma pair_mem_restrict {F A x y : Set} : x.pair y ∈ F.restrict A ↔ x.pair y ∈ F ∧ x ∈ A := begin simp, split, { rintro ⟨a, b, he, hp, hm⟩, rw he, rw (pair_inj he).left, finish, }, { rintro ⟨hp, hm⟩, exact ⟨_, _, rfl, hp, hm⟩, }, end lemma restrict_empty {F : Set} : F.restrict ∅ = ∅ := begin simp only [rel_eq_empty restrict_is_rel, pair_mem_restrict], rintros x y ⟨-, h⟩, exact mem_empty _ h, end lemma restrict_combine {F : Set} (hf : F.is_rel) {A B : Set} (hd : A ∪ B = F.dom) : F.restrict A ∪ F.restrict B = F := begin apply ext, simp only [mem_union, mem_restrict], intro p, split, { rintro (⟨a, b, he, hp, hm⟩|⟨a, b, he, hp, hm⟩), { rw he, exact hp, }, { rw he, exact hp, }, }, { intro hp, have h := hf _ hp, rcases h with ⟨x, y, h⟩, have hx : x ∈ F.dom, rw mem_dom, finish, rw ←hd at hx, rw mem_union at hx, rcases hx with hx|hx, { finish, }, { finish, }, }, end lemma restrict_singleton_eq {F : Set} (hf : F.is_function) {x : Set} (hx : x ∈ F.dom) : F.restrict {x} = {x.pair (F.fun_value x)} := begin apply ext, intro p, simp only [mem_singleton, mem_restrict], split, { rintro ⟨x', y, he, hp, hm⟩, rw he, congr, { exact hm, }, { rw ←hm, exact fun_value_def hf hp, }, }, { rintro he, refine ⟨_, _, he, _, rfl⟩, exact fun_value_def' hf hx, }, end lemma restrict_is_function {F : Set} (hf : F.is_function) {A : Set} : (F.restrict A).is_function := begin rw is_function_iff, split, { intro z, rw [mem_restrict], rintro ⟨x, y, he, hp, hx⟩, exact ⟨_, _, he⟩, }, { simp only [pair_mem_restrict], rintros x y y' ⟨hp, hx⟩ ⟨hp', -⟩, rw is_function_iff at hf, exact hf.right x y y' hp hp', }, end lemma restrict_fun_value {F : Set} (hf : F.is_function) {A : Set} (hA : A ⊆ F.dom) {x : Set} (hx : x ∈ A) : (F.restrict A).fun_value x = F.fun_value x := begin symmetry, apply fun_value_def (restrict_is_function hf), rw pair_mem_restrict, refine ⟨fun_value_def' hf (hA hx), hx⟩, end lemma restrict_dom {F A : Set} (hA : A ⊆ F.dom) : (F.restrict A).dom = A := begin apply ext, intro x, simp only [mem_dom, pair_mem_restrict, and_iff_right_iff_imp, exists_and_distrib_right], intro hxA, rw ←mem_dom, exact hA hxA, end lemma restrict_dom_inter {F A : Set} : (F.restrict A).dom = F.dom ∩ A := begin apply ext, simp only [mem_dom, mem_inter, pair_mem_restrict, iff_self, exists_and_distrib_right, implies_true_iff], end lemma restrict_fun_value' {F : Set} (hf : F.is_function) {x : Set} (hx : x ∈ F.dom) {A : Set} (hxA : x ∈ A) : (F.restrict A).fun_value x = F.fun_value x := begin symmetry, apply fun_value_def (restrict_is_function hf), rw pair_mem_restrict, exact ⟨fun_value_def' hf hx, hxA⟩, end lemma restrict_subset {F A : Set} : F.restrict A ⊆ F := begin apply rel_sub restrict_is_rel, intros x y, rw pair_mem_restrict, finish, end lemma restrict_one_to_one {F : Set} (hf : F.is_function) (hoto : F.one_to_one) {A : Set} (hA : A ⊆ F.dom) : (F.restrict A).one_to_one := begin apply one_to_one_of (restrict_is_function hf), intros x hx x' hx' hne he, rw [restrict_dom hA] at *, rw [restrict_fun_value hf hA hx, restrict_fun_value hf hA hx'] at he, apply hne, exact from_one_to_one hf hoto (hA hx) (hA hx') he, end def img (F A : Set) : Set := (F.restrict A).ran @[simp] lemma mem_img {F A y : Set} : y ∈ F.img A ↔ ∃ x : Set, x ∈ A ∧ x.pair y ∈ F := begin simp only [img, mem_ran, mem_restrict], split, rintro ⟨t, a, b, h₁, h₂, h₃⟩, have h₄ : y = b := (pair_inj h₁).right, subst h₄, exact ⟨_, h₃, h₂⟩, rintro ⟨x, h₁, h₂⟩, exact ⟨x, x, y, rfl, h₂, h₁⟩, end lemma mem_img' {F A y : Set} (h : F.is_function) (h' : A ⊆ F.dom) : y ∈ F.img A ↔ ∃ x : Set, x ∈ A ∧ y = F.fun_value x := begin simp only [mem_img], split, rintro ⟨x, h₁, h₂⟩, refine ⟨_, h₁, fun_value_def h h₂⟩, rintros ⟨x, h₁, h₂⟩, rw h₂, refine ⟨_, h₁, _⟩, apply fun_value_def', exact h, exact h' h₁, end lemma fun_value_mem_img {F : Set} (hf : F.is_function) {A : Set} (hd : A ⊆ F.dom) {x : Set} (h : x ∈ A) : F.fun_value x ∈ F.img A := begin rw mem_img' hf hd, exact ⟨_, h, rfl⟩, end lemma img_subset_ran {F A : Set} : F.img A ⊆ F.ran := begin intro y, simp only [mem_img, mem_ran, and_imp, exists_imp_distrib], intros x hxA hxyF, exact ⟨_, hxyF⟩, end lemma img_singleton_eq {F : Set} (hF : F.is_function) {x : Set} (hx : x ∈ F.dom) : F.img {x} = {F.fun_value x} := begin have h : {x} ⊆ F.dom, intros z hz, rw mem_singleton at hz, subst hz, exact hx, apply ext, simp only [mem_singleton, mem_img' hF h], intro z, split, rintro ⟨x', hx', hz⟩, subst hx', exact hz, intro hz, exact ⟨_, rfl, hz⟩, end lemma restrict_ran {F A : Set} : (F.restrict A).ran = F.img A := begin apply ext, intro y, simp only [mem_ran, mem_img, pair_mem_restrict, and_comm], end lemma img_fun_eq {A : Set} {f : Set} (hf : f.is_function) (Af : A ⊆ f.dom) {g : Set} (hg : g.is_function) (Ag : A ⊆ g.dom) (h : ∀ {a : Set}, a ∈ A → f.fun_value a = g.fun_value a) : f.img A = g.img A := ext (λ y, calc y ∈ f.img A ↔ ∃ x : Set, x ∈ A ∧ y = f.fun_value x : by rw mem_img' hf Af ... ↔ ∃ x : Set, x ∈ A ∧ y = g.fun_value x : exists_congr (λ x, and_congr_right (λ xA, eq.congr_right (h xA))) ... ↔ y ∈ g.img A : by rw mem_img' hg Ag) lemma restrict_into_fun {F D₁ D₂ R : Set} (hF : F.into_fun D₁ R) (h : D₂ ⊆ D₁) : (F.restrict D₂).into_fun D₂ R := begin refine ⟨restrict_is_function hF.left, _, _⟩, { rw ←hF.right.left at h, exact restrict_dom h, }, { rw restrict_ran, exact subset_trans img_subset_ran hF.right.right, }, end lemma img_ne_ran_of_ne_dom {F : Set} (hF : F.is_function) (hF' : F.one_to_one) {A : Set} (hAsub : A ⊆ F.dom) (hAne : A ≠ F.dom) : F.img A ≠ F.ran := begin intro he, apply hAne, rw eq_iff_subset_and_subset, refine ⟨hAsub, _⟩, intros x hx, rw mem_dom at hx, rcases hx with ⟨y, hx⟩, have hy : y ∈ F.ran, rw mem_ran, exact ⟨_, hx⟩, rw [←he, mem_img] at hy, rcases hy with ⟨x', hx', hy⟩, have hxx' : x = x', apply unique_of_exists_unique, { refine hF' y _, rw mem_ran, exact ⟨_, hx⟩, }, { exact hx, }, { exact hy, }, rw hxx', exact hx', end lemma one_to_one_ext {F : Set} (hf : F.is_function) (ha : ∀ x y : Set, x ∈ F.dom → y ∈ F.dom → F.fun_value x = F.fun_value y → x = y) : F.one_to_one := begin intros y hy, apply exists_unique_of_exists_of_unique, simp only [mem_ran] at hy, exact hy, intros x x' hx hx', apply ha x x', rw mem_dom, exact ⟨_, hx⟩, rw mem_dom, exact ⟨_, hx'⟩, rw ←fun_value_def hf hx, rw ←fun_value_def hf hx', end @[simp] theorem T3E_a {F : Set} : F.inv.dom = F.ran := begin apply ext, intro z, simp only [mem_dom, mem_ran, pair_mem_inv], end @[simp] theorem T3E_b {F : Set} : F.inv.ran = F.dom := begin apply ext, intro z, simp only [mem_ran, mem_dom, pair_mem_inv], end theorem T3E_c {F : Set} (h : F.is_rel) : F.inv.inv = F := begin apply ext, intro z, rw mem_inv, simp only [pair_mem_inv], split, { rintro ⟨a, b, he, hm⟩, rw he, assumption, }, { intro hm, specialize h _ hm, rcases h with ⟨a, b, he⟩, rw he at hm, exact ⟨_, _, he, hm⟩, }, end theorem T3F_a {F : Set} : F.inv.is_function ↔ F.one_to_one := begin simp only [is_function, one_to_one, and_iff_right inv_rel, T3E_a, pair_mem_inv], end theorem T3F_b {F : Set} (h : F.is_rel) : F.is_function ↔ F.inv.one_to_one := begin simp only [is_function, one_to_one, and_iff_right h, T3E_b, pair_mem_inv], end theorem T3G_a {F : Set} (hf : F.is_function) (ho : F.one_to_one) : ∀ x ∈ F.dom, F.inv.fun_value (F.fun_value x) = x := begin intros x hm, have hp : x.pair (F.fun_value x) ∈ F := fun_value_def' hf hm, have hpinv : (F.fun_value x).pair x ∈ F.inv, simp only [pair_mem_inv], exact hp, have hinvfun : F.inv.is_function := T3F_a.mpr ho, symmetry, exact fun_value_def hinvfun hpinv, end theorem T3G_b {F : Set} (hf : F.is_function) (ho : F.one_to_one) : ∀ y ∈ F.ran, F.fun_value (F.inv.fun_value y) = y := begin intros y hm, rw ←T3E_a at hm, have hinvfun : F.inv.is_function := T3F_a.mpr ho, have hinvoto : F.inv.one_to_one := (T3F_b hf.left).mp hf, have h : F.inv.inv.fun_value (F.inv.fun_value y) = y := T3G_a hinvfun hinvoto y hm, rw T3E_c hf.left at h, exact h, end theorem T3H_a {F G : Set} (hf : F.is_function) (hg : G.is_function) : (F.comp G).is_function := begin split, intros p hp, rw mem_comp at hp, rcases hp with ⟨a, b, c, he, hmg, hmf⟩, exact ⟨_, _, he⟩, intros p hp, rw mem_dom at hp, rcases hp with ⟨y, hp⟩, refine ⟨_, hp, _⟩, intros w hw, simp only [pair_mem_comp] at hp, simp only [pair_mem_comp] at hw, rcases hp with ⟨u, hu⟩, rcases hw with ⟨v, hv⟩, have h : u = v := fun_lemma hg hu.left hv.left, rw h at hu, apply fun_lemma hf, exact hv.right, exact hu.right, end theorem T3H_b {F G : Set} (hf : F.is_function) (hg : G.is_function) : (F.comp G).dom = {x ∈ G.dom | G.fun_value x ∈ F.dom} := begin apply ext, intro x, simp only [mem_sep, mem_dom, pair_mem_comp], split, { rintro ⟨y, t, hx, ht⟩, refine ⟨⟨t, hx⟩, y, _⟩, rw ←fun_value_def hg hx, exact ht, }, { rintro ⟨⟨t, ht⟩, y, hy⟩, refine ⟨y, _, ht, _⟩, rw fun_value_def hg ht, exact hy, }, end theorem T3H_c {F G x : Set} (hf : F.is_function) (hg : G.is_function) (hd : x ∈ (F.comp G).dom) : (F.comp G).fun_value x = F.fun_value (G.fun_value x) := begin simp only [T3H_b hf hg, mem_sep, mem_dom] at hd, rcases hd with ⟨⟨t, ht⟩, y, hy⟩, symmetry, apply fun_value_def (T3H_a hf hg), simp only [pair_mem_comp], refine ⟨_, ht, _⟩, rw ←fun_value_def hf hy, rw fun_value_def hg ht, exact hy, end theorem T3I {F G : Set} : (F.comp G).inv = G.inv.comp F.inv := begin apply ext, intro z, simp only [mem_inv, pair_mem_comp, mem_comp, pair_mem_inv], split, { rintro ⟨a, b, he, b', t, a', hpe, hg, hf⟩, have hinj : b = b' ∧ a = a' := pair_inj hpe, refine ⟨a, t, b, he, _, _⟩, rw hinj.right, assumption, rw hinj.left, assumption, }, { rintro ⟨a, t, b, he, hf, hg⟩, exact ⟨a, b, he, b, t, a, rfl, hg, hf⟩, }, end theorem inv_onto_of_onto {F A B : Set} (Fonto : F.onto_fun A B) (Foto : F.one_to_one) : F.inv.onto_fun B A := begin rw [onto_fun, T3F_a, T3E_a, T3E_b, Fonto.right.right], exact ⟨Foto, rfl, Fonto.right.left⟩, end lemma dom_comp_sub {F G : Set} : (F.comp G).dom ⊆ G.dom := begin intros x hx, simp only [mem_dom, pair_mem_comp] at *, finish, end lemma dom_comp {F G : Set} (h : G.ran ⊆ F.dom) : (F.comp G).dom = G.dom := begin rw eq_iff_subset_and_subset, split, { exact dom_comp_sub, }, { intros x hx, simp only [mem_dom, pair_mem_comp] at *, rcases hx with ⟨y, hy⟩, have hd : y ∈ F.dom, apply h, rw mem_ran, finish, rw mem_dom at hd, finish, }, end lemma ran_comp_sub {F G : Set} : (F.comp G).ran ⊆ F.ran := begin rw [←T3E_a, T3I, ←T3E_a], exact dom_comp_sub, end lemma ran_comp {F G : Set} (h : F.dom ⊆ G.ran) : (F.comp G).ran = F.ran := begin rw [←T3E_a, ←T3E_b] at h, rw [←T3E_a, T3I, ←T3E_a], exact dom_comp h, end lemma ran_comp_complex {f g : Set} (hf : f.one_to_one) : (f.comp g).ran = f.ran \ f.img (f.dom \ g.ran) := begin apply ext, simp only [mem_ran, pair_mem_comp, mem_diff, mem_img, mem_dom], intro y, split, rintro ⟨z, x, hzx, hxy⟩, refine ⟨⟨_, hxy⟩, _⟩, rintro ⟨x', ⟨⟨y', hxy'⟩, he⟩, hx'y⟩, apply he, rw one_to_one_iff at hf, specialize hf hxy hx'y, rw ←hf, exact ⟨_, hzx⟩, rintro⟨⟨z, hzy⟩, hne⟩, apply classical.by_contradiction, intro hne', apply hne, refine ⟨_, ⟨⟨_, hzy⟩, _⟩, hzy⟩, rintro ⟨x', hx'z⟩, apply hne', exact ⟨_, _, hx'z, hzy⟩, end lemma comp_into_fun {A B C f : Set} (hf : f.into_fun A B) {g : Set} (hg : g.into_fun B C) : (g.comp f).into_fun A C := begin refine ⟨T3H_a hg.left hf.left, _, _⟩, { have h : f.ran ⊆ g.dom, rw hg.right.left, exact hf.right.right, rw ←hf.right.left, exact dom_comp h, }, { apply subset_trans, exact ran_comp_sub, exact hg.right.right, }, end lemma inv_into_fun {f A B : Set} (hfun : f.onto_fun A B) (foto : f.one_to_one) : f.inv.into_fun B A := begin refine ⟨T3F_a.mpr foto, _, _⟩, { rw T3E_a, exact hfun.right.right, }, { rw [T3E_b, hfun.right.left], exact subset_self, }, end lemma fun_ext {F G : Set} (hf : F.is_function) (hg : G.is_function) (hd : F.dom = G.dom) (ha : ∀ x ∈ F.dom, F.fun_value x = G.fun_value x) : F = G := begin have h : ∀ F G : Set, F.is_function → G.is_function → F.dom = G.dom → (∀ x ∈ F.dom, F.fun_value x = G.fun_value x) → ∀ z : Set, z ∈ F → z ∈ G, intros F G hf hg hd ha z hm, have hp : z.is_pair := hf.left _ hm, rcases hp with ⟨x, y, hp⟩, subst hp, have hxd : x ∈ F.dom, simp only [mem_dom], exact ⟨_, hm⟩, specialize ha _ hxd, rw ←fun_value_def hf hm at ha, rw ha, rw hd at hxd, exact fun_value_def' hg hxd, apply ext, intro z, split, { exact h F G hf hg hd ha z, }, { refine h G F hg hf hd.symm _ z, rw ←hd, intros x hx, exact (ha x hx).symm, }, end lemma union_of_rel_is_rel {A B : Set} (hA : A.is_rel) (hB : B.is_rel) : (A ∪ B).is_rel := begin intros x hx, simp only [mem_union] at hx, cases hx, exact hA _ hx, exact hB _ hx, end def id (A : Set) : Set := pair_sep (λ a b, a = b) A A lemma id_is_function {A : Set} : A.id.is_function := begin refine ⟨pair_sep_is_rel, _⟩, simp only [mem_dom, pair_mem_pair_sep, id], rintros x ⟨y, hx⟩, refine ⟨y, hx, _⟩, intros y' hy, rw ←hx.right.right, rw ←hy.right.right, end lemma id_onto {A : Set} : A.id.onto_fun A A := begin simp only [onto_fun], refine ⟨id_is_function, _, _⟩, apply ext, simp only [mem_dom, id, pair_mem_pair_sep], intro z, split, { rintro ⟨y, h, _⟩, exact h, }, { intro h, exact ⟨_, h, h, rfl⟩, }, apply ext, simp only [mem_ran, id, pair_mem_pair_sep], intro z, split, { rintro ⟨x, _, h, _⟩, exact h, }, { intro h, exact ⟨_, h, h, rfl⟩, }, end lemma id_into {A : Set} : A.id.into_fun A A := into_of_onto id_onto lemma id_value {A x : Set} (hx : x ∈ A) : A.id.fun_value x = x := begin have h : x.pair x ∈ A.id, simp only [id, pair_mem_pair_sep], exact ⟨hx, hx, rfl⟩, rw ←fun_value_def id_is_function h, end lemma id_singleton_value {x : Set} : (id {x}).fun_value x = x := id_value ((@mem_singleton _ _).mpr rfl) lemma id_oto {A : Set} : A.id.one_to_one := begin apply one_to_one_of id_is_function, intros m hm n hn hne he, apply hne, rw id_onto.right.left at hm, rw id_onto.right.left at hn, rw ←id_value hm, rw he, rw id_value hn, end lemma id_inv {A : Set} : A.id.inv = A.id := begin apply rel_eq inv_rel id_is_function.left, simp only [pair_mem_inv, id, pair_mem_pair_sep],finish, end lemma comp_id {f : Set} (hf : f.is_function) : f.comp f.dom.id = f := begin have hd : (f.comp f.dom.id).dom = f.dom, have h : f.dom.id.ran ⊆ f.dom, rw id_onto.right.right, exact subset_self, rw [dom_comp h, id_onto.right.left], apply fun_ext (T3H_a hf id_is_function) hf hd, intros x hx, rw T3H_c hf id_onto.left hx, rw hd at hx, rw id_value hx, end lemma id_comp {A f : Set} (hA : f.ran ⊆ A) (hf : f.is_function) : A.id.comp f = f := begin have hd : (A.id.comp f).dom = f.dom, have h : f.ran ⊆ A.id.dom, rw id_onto.right.left, exact hA, rw dom_comp h, apply fun_ext (T3H_a id_is_function hf) hf hd, intros x hx, rw T3H_c id_onto.left hf hx, have h : f.fun_value x ∈ A, apply hA, apply fun_value_def'' hf, rw hd at hx, exact hx, rw id_value h, end lemma eq_id {f : Set} (hf : f.is_function) (hf' : f.one_to_one) : f.inv.comp f = f.dom.id := begin apply ext, intro z, simp only [mem_comp, id, mem_pair_sep, exists_prop, mem_dom, pair_mem_inv], split, { rintro ⟨x, y, x', he, hxy, hxy'⟩, refine ⟨_, ⟨_, hxy⟩, _, ⟨_, hxy'⟩, he, _⟩, refine unique_of_exists_unique _ hxy hxy', apply hf', rw mem_ran, exact ⟨_, hxy⟩, }, { rintro ⟨x, ⟨y, hxy⟩, x', ⟨y', hxy'⟩, he, hxx'⟩, rw hxx' at hxy he, have hyy' : y = y', refine unique_of_exists_unique _ hxy hxy', apply hf.right, rw mem_dom, exact ⟨_, hxy⟩, rw hyy' at hxy, exact ⟨_, _, _, he, hxy, hxy⟩, }, end lemma eq_inv_id {f : Set} (hf : f.is_function) (hf' : f.one_to_one) : f.comp f.inv = f.ran.id := begin have h : f.inv.inv.comp f.inv = f.inv.dom.id, apply eq_id, { rw T3F_a, exact hf' }, { rw ←T3F_b hf.left, exact hf, }, rw [inv_inv hf.left, T3E_a] at h, exact h, end lemma union_fun {F G : Set} (hf : F.is_function) (hg : G.is_function) (hdisj : F.dom ∩ G.dom = ∅) : (F ∪ G).onto_fun (F.dom ∪ G.dom) (F.ran ∪ G.ran) := begin have hd : (F ∪ G).dom = F.dom ∪ G.dom, apply ext, simp only [mem_dom, mem_union], intro z, exact exists_or_distrib, split, { refine ⟨union_of_rel_is_rel hf.left hg.left, _⟩, simp only [hd, mem_union, mem_dom], rintros x (⟨y, hmf⟩ | ⟨y, hmg⟩), { refine ⟨y, or.inl hmf, _⟩, rintros z (hz | hz), exact fun_lemma hf hz hmf, exfalso, apply mem_empty x, simp only [←hdisj, mem_inter, mem_dom], exact ⟨⟨_, hmf⟩, _, hz⟩, }, { refine ⟨y, or.inr hmg, _⟩, rintros z (hz | hz), exfalso, apply mem_empty x, simp only [←hdisj, mem_inter, mem_dom], exact ⟨⟨_, hz⟩, _, hmg⟩, exact fun_lemma hg hz hmg, }, }, refine ⟨hd, _⟩, apply ext, simp only [mem_ran, mem_union], intro z, exact exists_or_distrib, end lemma union_dom {F G : Set} : (F ∪ G).dom = F.dom ∪ G.dom := begin apply ext, simp only [mem_dom, mem_union, exists_or_distrib, forall_const, iff_self], end lemma union_fun_into_fun {F G D₁ D₂ R : Set} (hF : F.into_fun D₁ R) (hG : G.into_fun D₂ R) (hdisj : D₁ ∩ D₂ = ∅) : (F ∪ G).into_fun (D₁ ∪ D₂) R := begin have onto : (F ∪ G).onto_fun (F.dom ∪ G.dom) (F.ran ∪ G.ran), apply union_fun hF.left hG.left, rw [hF.right.left, hG.right.left], exact hdisj, rw [←hF.right.left, ←hG.right.left], refine ⟨onto.left, onto.right.left, _⟩, rw onto.right.right, exact union_subset_of_subset_of_subset hF.right.right hG.right.right, end lemma ran_union {F G : Set} : (F ∪ G).ran = F.ran ∪ G.ran := begin apply ext, intro x, simp only [mem_ran, mem_union], exact exists_or_distrib, end lemma union_fun_value_left {F G D₁ D₂ R₁ R₂ : Set} (Fonto : F.onto_fun D₁ R₁) (Gonto : G.onto_fun D₂ R₂) (disj : D₁ ∩ D₂ = ∅) {x : Set} (xD : x ∈ D₁) : (F ∪ G).fun_value x = F.fun_value x := begin symmetry, refine fun_value_def (union_fun Fonto.left Gonto.left _).left _, rw [Fonto.right.left, Gonto.right.left], exact disj, rw mem_union, left, apply fun_value_def' Fonto.left, rw Fonto.right.left, exact xD, end lemma union_fun_value_right {F G D₁ D₂ R₁ R₂ : Set} (Fonto : F.onto_fun D₁ R₁) (Gonto : G.onto_fun D₂ R₂) (disj : D₁ ∩ D₂ = ∅) {x : Set} (xD : x ∈ D₂) : (F ∪ G).fun_value x = G.fun_value x := begin symmetry, refine fun_value_def (union_fun Fonto.left Gonto.left _).left _, rw [Fonto.right.left, Gonto.right.left], exact disj, rw mem_union, right, apply fun_value_def' Gonto.left, rw Gonto.right.left, exact xD, end lemma ran_single_pair {x y : Set} : ({x.pair y} : Set).ran = {y} := begin apply ext, intro y, simp only [mem_ran, mem_singleton], split, { rintro ⟨x, hx⟩, exact (pair_inj hx).right, }, { intro hy, rw hy, exact ⟨_, rfl⟩, }, end lemma union_one_to_one {f : Set} (hf : f.one_to_one) {g : Set} (hg : g.one_to_one) (hfg : f.ran ∩ g.ran = ∅) : (f ∪ g).one_to_one := begin intros y hy, simp only [mem_ran, mem_union] at hy, simp only [mem_union], rcases hy with ⟨x, hx|hx⟩, { refine ⟨_, or.inl hx, _⟩, have hyfr : y ∈ f.ran, rw mem_ran, exact ⟨_, hx⟩, rintros x' (hx'|hx'), { apply unique_of_exists_unique (hf _ hyfr) hx' hx, }, { have hygr : y ∈ g.ran, rw mem_ran, exact ⟨_, hx'⟩, exfalso, apply mem_empty y, rw [←hfg, mem_inter], exact ⟨hyfr, hygr⟩, }, }, { refine ⟨_, or.inr hx, _⟩, have hygr : y ∈ g.ran, rw mem_ran, exact ⟨_, hx⟩, rintros x' (hx'|hx'), { have hyfr : y ∈ f.ran, rw mem_ran, exact ⟨_, hx'⟩, exfalso, apply mem_empty y, rw [←hfg, mem_inter], exact ⟨hyfr, hygr⟩, }, { apply unique_of_exists_unique (hg _ hygr) hx' hx, }, }, end lemma restrict_union_eq {F G : Set} (hF : F.is_rel) (hdisj : F.dom ∩ G.dom = ∅) : (F ∪ G).restrict F.dom = F := begin apply rel_eq restrict_is_rel hF, simp only [pair_mem_restrict, mem_union], intros x y, split, { rintro ⟨(hxy|hxy), hd⟩, exact hxy, exfalso, apply mem_empty x, rw ←hdisj, rw mem_inter, refine ⟨hd, _⟩, rw mem_dom, exact ⟨_, hxy⟩, }, { intro hxy, rw mem_dom, refine ⟨or.inl hxy, _, hxy⟩, }, end lemma single_pair_oto {x y : Set} : ({x.pair y} : Set).one_to_one := begin intros z hz, rw [ran_single_pair, mem_singleton] at hz, simp only [mem_singleton, hz], refine ⟨_, rfl, _⟩, intros x' hx', exact (pair_inj hx').left, end lemma single_pair_into {x y R : Set} (hy : y ∈ R) : ({x.pair y} : Set).into_fun {x} R := begin rw fun_def_equiv, split, intros p hp, rw mem_singleton at hp, rw [hp, pair_mem_prod, mem_singleton], exact ⟨rfl, hy⟩, simp only [mem_singleton], intros z he, rw he, exact ⟨_, rfl, λ y' he', (pair_inj he').right⟩, end lemma single_pair_fun_value {x y : Set} : ({x.pair y} : Set).fun_value x = y := begin symmetry, apply fun_value_def (@single_pair_into _ _ {y} _).left, rw mem_singleton, rw mem_singleton, end lemma single_pair_onto {x y : Set} : onto_fun {x.pair y} {x} {y} := begin apply onto_of_into, apply single_pair_into, rw mem_singleton, exact ran_single_pair, end lemma prod_singleton_fun {A x : Set} : (A.prod {x}).is_function := begin refine ⟨prod_is_rel, _⟩, simp only [mem_dom, mem_singleton, pair_mem_prod], rintros z ⟨y, hy⟩, refine ⟨y, hy, _⟩, intros y' hy', rw hy'.right, symmetry, exact hy.right, end lemma empty_fun : is_function ∅ := begin rw is_function_iff, refine ⟨empty_is_rel, λ x y y' hxy hxy', _⟩, exfalso, exact mem_empty _ hxy, end lemma empty_onto : onto_fun ∅ ∅ ∅ := ⟨empty_fun, dom_empty_eq_empty, ran_empty_eq_empty⟩ lemma empty_oto : one_to_one ∅ := begin rw one_to_one_iff, intros y x x' hxy hxy', exfalso, exact mem_empty _ hxy, end lemma dom_prod_nonempty {A B : Set} (hb : ∃ x : Set, x ∈ B) : (A.prod B).dom = A := begin apply ext, intro z, simp only [hb, mem_dom, and_true, pair_mem_prod, exists_and_distrib_left], end lemma ran_prod_nonempty {A B : Set} : (A.prod B).ran ⊆ B := begin intros z hz, simp only [mem_ran, pair_mem_prod] at hz, rcases hz with ⟨t, hA, hB⟩, exact hB, end lemma one_to_one_of_has_left_inv {F A B : Set} (hf : F.into_fun A B) (he : ∃ G : Set, G.into_fun B A ∧ G.comp F = A.id) : F.one_to_one := begin rcases he with ⟨G, hif, hcid⟩, apply one_to_one_ext hf.left, intros x y hxd hyd he, simp only [hf.right.left] at hxd hyd, rw ←id_value hxd, rw ←id_value hyd, rw ←hcid, rw T3H_c hif.left hf.left _, rw T3H_c hif.left hf.left _, rw he, simp only [hcid, (id_onto).right.left, hyd], simp only [hcid, (id_onto).right.left, hxd], end lemma T3J_a {F A B : Set} (hf : F.into_fun A B) (hne : ∃ x, x ∈ A) : (∃ G : Set, G.into_fun B A ∧ G.comp F = A.id) ↔ F.one_to_one := begin simp only [into_fun] at *, split, { intro he, exact one_to_one_of_has_left_inv hf he, }, { rcases hne with ⟨x, hxm⟩, intro hoto, let F' := F.inv, let E := (B \ F.ran).prod {x}, let G := F' ∪ E, have honto : G.onto_fun (F'.dom ∪ E.dom) (F'.ran ∪ E.ran), refine union_fun _ _ _, { simp only [T3F_a, hoto], }, { exact prod_singleton_fun, }, { simp only [eq_empty], intros z hz, simp only [mem_inter, mem_dom, pair_mem_prod, mem_diff, pair_mem_inv, mem_ran] at hz, rcases hz with ⟨⟨y, hy⟩, y', ⟨_, him⟩, _⟩, exact him ⟨_, hy⟩, }, refine ⟨_, ⟨honto.left, _, _⟩, _⟩, { rw honto.right.left, simp only [T3E_a, dom_prod_nonempty ⟨x, mem_singleton.mpr rfl⟩], apply ext, intro z, have hz : z ∈ F.ran → z ∈ B, apply subset_def.mp, exact hf.right.right, simp only [mem_union, mem_diff, or_and_distrib_left, classical.em, and_true, or_iff_right_of_imp hz], }, { rw honto.right.right, intros z hz, simp only [mem_union, T3E_b] at hz, cases hz, { rw ←hf.right.left, assumption, }, { have hz' : z ∈ {x}, apply ran_prod_nonempty, exact hz, simp only [mem_singleton] at hz', rw hz', assumption, }, }, have hcdom : (G.comp F).dom = A, apply ext, intro z, simp only [T3H_b honto.left hf.left, mem_sep, hf.right.left, mem_dom], split, { rintro ⟨hmz, _⟩, assumption, }, { intro hmz, refine ⟨hmz, _⟩, existsi z, simp only [mem_union, pair_mem_inv], apply or.inl, apply fun_value_def' hf.left, rw hf.right.left, assumption, }, apply fun_ext, exact T3H_a honto.left hf.left, exact id_is_function, simp only [id_onto.right.left, hcdom], intros z hz, rw hcdom at hz, have hz' : z ∈ (G.comp F).dom, rw hcdom, assumption, simp only [id_value hz, T3H_c honto.left hf.left hz'], symmetry, apply fun_value_def honto.left, simp only [mem_union, pair_mem_inv], apply or.inl, apply fun_value_def' hf.left, rw hf.right.left, assumption, }, end -- For choice, we have choice which satisfies the property that if x is a set and it does not contain the empty set, -- then x.choice is a function with domain x and range x.Union and where the value of x.choice at a is a member of a for a in x. lemma choice_is_fun (x : Set) (h : ∅ ∉ x) : x.choice.into_fun x x.Union := begin have choice := choice_is_func x h, have hd : x.choice.dom = x, apply ext, intro z, simp only [mem_dom], split, { rintro ⟨y, hy⟩, exact (pair_mem_prod.mp (choice.1 hy)).1, }, { intro mz, apply exists_of_exists_unique, exact choice.2 _ mz, }, refine ⟨⟨_, _⟩, _, _⟩, { intros z hz, have hp := choice.left hz, simp only [mem_prod] at hp, rcases hp with ⟨a, H, b, H, he⟩, exact ⟨a, b, he⟩, }, { intros z hz, rw hd at hz, exact choice.2 _ hz, }, { exact hd }, { intros z hz, simp only [mem_ran] at hz, cases hz with t hz, have hp : t.pair z ∈ x.prod x.Union, exact choice.1 hz, exact (pair_mem_prod.mp hp).2, }, end lemma choice_mem' (x : Set.{u}) (hx : ∅ ∉ x) (y : Set) (hy : y ∈ x) : x.choice.fun_value y ∈ y := begin have hf := (choice_is_fun x hx), have h : (x.choice : Class.{u}).fval (y : Class.{u}) = (x.choice.fun_value y : Class.{u}), apply Class.iota_val, intro v, split, { rintro ⟨a, ha, hp⟩, simp only [Class.mem_hom_right] at hp, apply fun_value_def, exact hf.left, rw ←(Class.of_Set.inj ha), assumption, }, { intro hv, refine ⟨y, rfl, _⟩, simp only [Class.mem_hom_right], rw hv, apply fun_value_def', exact hf.left, rw (choice_is_fun x hx).right.left, assumption, }, suffices h₂ : (x.choice.fun_value y : Class.{u}) ∈ (y : Class.{u}), simp only [Class.mem_hom_left, Class.mem_hom_right] at h₂, assumption, rw ←h, exact choice_mem x hx y hy, end lemma pair_sep_eq_is_fun {A B : Set} {f : Set → Set} : (pair_sep (λ a b, b = f a) A B).is_function := begin rw is_function_iff, split, { exact pair_sep_is_rel, }, { simp only [pair_mem_pair_sep, and_imp], intros, finish, }, end lemma pair_sep_eq_dom_eq {A B : Set} {f : Set → Set} (h : ∀ a ∈ A, f a ∈ B) : (pair_sep (λ a b, b = f a) A B).dom = A := begin apply ext, intro a, simp only [mem_dom, pair_mem_pair_sep, exists_eq_right, exists_and_distrib_left, and_iff_left_iff_imp], intro ha, finish, end lemma pair_sep_eq_ran_eq {A B : Set} {f : Set → Set} (h : ∀ b ∈ B, ∃ a, a ∈ A ∧ b = f a) : (pair_sep (λ a b, b = f a) A B).ran = B := begin apply ext, intro b, simp only [mem_ran, pair_mem_pair_sep], split, { rintro ⟨t, _, hb, _⟩, assumption, }, { intro hb, specialize h _ hb, finish, }, end lemma pair_sep_eq_ran_sub {A B : Set} {p : Set → Set → Prop} : (pair_sep p A B).ran ⊆ B := begin intros b hb, simp only [mem_ran, pair_mem_pair_sep] at hb, finish, end lemma pair_sep_eq_oto {A B : Set} {f : Set → Set} (hf : ∀ ⦃a₁ : Set⦄, a₁ ∈ A → ∀ ⦃a₂ : Set⦄, a₂ ∈ A → f a₁ = f a₂ → a₁ = a₂) : (pair_sep (λ a b, b = f a) A B).one_to_one := begin intros b hb, simp only [mem_ran, pair_mem_pair_sep] at hb, rcases hb with ⟨a, ha, hb, he⟩, simp only [pair_mem_pair_sep], refine ⟨_, ⟨ha, hb, he⟩, λ a' ha', _⟩, rcases ha' with ⟨ha', -, he'⟩, rw he' at he, exact hf ha' ha he, end def pair_sep_eq (A B : Set) (f : Set → Set) : Set := pair_sep (λ a b, b = f a) A B @[simp] lemma pair_mem_pair_sep_eq {A B : Set} {f : Set → Set} {a b : Set} : a.pair b ∈ pair_sep_eq A B f ↔ a ∈ A ∧ b ∈ B ∧ b = f a := by simp only [pair_sep_eq, pair_mem_pair_sep] lemma pair_sep_eq_fun_value {A B : Set} {f : Set → Set} {a : Set} (ha : a ∈ (pair_sep_eq A B f).dom) : (pair_sep_eq A B f).fun_value a = f a := begin symmetry, apply fun_value_def pair_sep_eq_is_fun, rw [pair_mem_pair_sep], simp only [mem_dom, pair_mem_pair_sep_eq] at ha, rcases ha with ⟨b, ha, hb, he⟩, rw he at hb, exact ⟨ha, hb, rfl⟩, end lemma pair_sep_eq_into {A B : Set} {f : Set → Set} (h : ∀ a ∈ A, f a ∈ B) : (pair_sep_eq A B f).into_fun A B := ⟨pair_sep_eq_is_fun, pair_sep_eq_dom_eq h, pair_sep_eq_ran_sub⟩ -- These are all stated and proved equivalent in chapter 6, but some are stated earlier. def Axiom_of_choice_I : Prop := ∀ {R : Set}, R.is_rel → ∃ F : Set, F.is_function ∧ F ⊆ R ∧ F.dom = R.dom def Axiom_of_choice_II : Prop := ∀ {I H : Set}, (H.is_function ∧ H.dom = I ∧ (∀ i : Set, i ∈ I → H.fun_value i ≠ ∅)) → ∃ f : Set, f.is_function ∧ f.dom = I ∧ ∀ i : Set, i ∈ I → f.fun_value i ∈ H.fun_value i def Axiom_of_choice_III : Prop := ∀ {A : Set}, ∃ F : Set, F.is_function ∧ F.dom = {x ∈ A.powerset | x ≠ ∅} ∧ ∀ B : Set, B ∈ F.dom → F.fun_value B ∈ B def Axiom_of_choice_IV : Prop := ∀ {𝓐 : Set}, (∀ a ∈ 𝓐, a ≠ ∅ ∧ ∀ b ∈ 𝓐, b ≠ a → a ∩ b = ∅) → ∃ C : Set, ∀ B ∈ 𝓐, ∃ x : Set, C ∩ B = {x} theorem ax_ch_3 : Axiom_of_choice_III := begin intro A, let A' := {x ∈ A.powerset | x ≠ ∅}, have hne : ∅ ∉ A', intro h, simp at h, assumption, have hf := choice_is_fun _ hne, refine ⟨A'.choice, hf.left, _, (λ B hB, _)⟩, { apply ext, intro z, simp only [hf.right.left, mem_sep, mem_dom], }, { apply choice_mem' _ hne, rw hf.right.left at hB, assumption, }, end -- first 4 parts of theorem 6M theorem choice_equiv : list.tfae [Axiom_of_choice_I.{u}, Axiom_of_choice_II.{u}, Axiom_of_choice_III.{u}, Axiom_of_choice_IV.{u}] := begin tfae_have : 1 → 2, { dsimp only [Axiom_of_choice_I, Axiom_of_choice_II], rintros ax1 I H ⟨Hfun, Hdom, Hne⟩, let R : Set := pair_sep (λ i y, y ∈ H.fun_value i) I H.ran.Union, specialize @ax1 R pair_sep_is_rel, rcases ax1 with ⟨F, Ffun, FR, Fdom⟩, have Rdom : R.dom = I, rw eq_iff_subset_and_subset, split, exact pair_sep_dom_sub, intros i hi, simp only [mem_dom, pair_mem_pair_sep], specialize Hne _ hi, replace Hne := inhabited_of_ne_empty Hne, rcases Hne with ⟨y, hy⟩, simp only [mem_Union, exists_prop], refine ⟨_, hi, ⟨_, _, hy⟩, hy⟩, apply fun_value_def'' Hfun, rw Hdom, exact hi, rw Rdom at Fdom, refine ⟨_, Ffun, Fdom, _⟩, intros i hi, have hiy : i.pair (F.fun_value i) ∈ R, apply FR, apply fun_value_def' Ffun, rw Fdom, exact hi, simp only [pair_mem_pair_sep] at hiy, exact hiy.right.right, }, tfae_have : 2 → 4, { dsimp only [Axiom_of_choice_II, Axiom_of_choice_IV], rintros ax2 A hA, let H := A.id, have Hh : ∀ i : Set, i ∈ H.dom → H.fun_value i ≠ ∅, rw id_into.right.left, intros i hi, rw id_value hi, specialize hA _ hi, exact hA.left, specialize ax2 ⟨id_is_function, rfl, Hh⟩, rcases ax2 with ⟨f, ffun, fdom, hf⟩, use f.ran, intros B hBA, use f.fun_value B, apply ext, simp only [mem_singleton, mem_inter, mem_ran], rw id_into.right.left at hf, intro C, split, rintros ⟨⟨X, hXC⟩, hCB⟩, have hXA : X ∈ f.dom, rw mem_dom, exact ⟨_, hXC⟩, rw [fdom, id_into.right.left] at hXA, have hCfX : C = f.fun_value X := fun_value_def ffun hXC, rw hCfX, suffices hXB : X = B, rw hXB, apply classical.by_contradiction, intro hXB, apply @mem_empty (f.fun_value X), rw [←(hA _ hBA).right _ hXA hXB, mem_inter], split, rw ←hCfX, exact hCB, specialize hf X hXA, rw id_value hXA at hf, exact hf, intro he, split, use B, refine fun_value_def''' ffun _ he, rw [fdom, id_into.right.left], exact hBA, specialize hf _ hBA, rw [id_value hBA] at hf, rw he, exact hf, }, tfae_have : 4 → 3, { dsimp only [Axiom_of_choice_IV, Axiom_of_choice_III], rintro ax4 A, let 𝓐 := {x ∈ (A.powerset.Union ∪ A.powerset).powerset.powerset.powerset | ∃ B, B ⊆ A ∧ B ≠ ∅ ∧ x = prod {B} B}, have h𝓐 : ∀ x, x ∈ 𝓐 ↔ ∃ B, B ⊆ A ∧ B ≠ ∅ ∧ x = prod {B} B, simp only [and_imp, mem_powerset, and_iff_right_iff_imp, ne.def, exists_imp_distrib, mem_sep], intros X B hBA hBne hXB z hz, rw mem_powerset, intros y hy, rw mem_powerset, intros x hx, simp only [mem_powerset, mem_union], rw hXB at hz, simp only [mem_prod, exists_prop, mem_singleton] at hz, rcases hz with ⟨B', hBB', b, hb, hbp⟩, rw hbp at hy, simp only [pair, mem_insert, mem_singleton] at hy, cases hy, rw [hy, mem_singleton] at hx, right, rw [hx, hBB'], exact hBA, rw hy at hx, simp only [mem_insert, mem_singleton] at hx, cases hx, right, rw [hx, hBB'], exact hBA, left, simp only [hx, mem_Union, exists_prop, mem_powerset], exact ⟨_, hBA, hb⟩, have h𝓐' : ∀ a ∈ 𝓐, a ≠ ∅ ∧ ∀ b ∈ 𝓐, b ≠ a → a ∩ b = ∅, intros a ha, rw h𝓐 _ at ha, rcases ha with ⟨B, -, hBne, he⟩, split, apply ne_empty_of_inhabited, rw he, replace hBne := inhabited_of_ne_empty hBne, rcases hBne with ⟨b, hb⟩, use B.pair b, rw [pair_mem_prod, mem_singleton], exact ⟨rfl, hb⟩, intros b hb hba, rw eq_empty, intros z hz, rw h𝓐 _ at hb, rcases hb with ⟨B', -, hBne', he'⟩, apply hba, rw [he, he'], have hBB' : B = B', simp only [he, he', mem_inter, mem_prod, exists_prop, mem_singleton] at hz, rcases hz with ⟨⟨x, hx, y, hy, hxy⟩, x', hx', y', hy', hxy'⟩, rw [←hx, ←hx'], rw hxy at hxy', exact (pair_inj hxy').left, rw hBB', specialize ax4 h𝓐', rcases ax4 with ⟨C, hC⟩, let F := C ∩ 𝓐.Union, use F, have hFinto : F.into_fun {x ∈ A.powerset | x ≠ ∅} F.ran, rw fun_def_equiv, have Fsubprod : F ⊆ {x ∈ A.powerset | x ≠ ∅}.prod F.ran, intros z hz, simp only [mem_inter, mem_Union, exists_prop] at hz, rcases hz with ⟨hzC, X, hX𝓐, hzX⟩, simp only [mem_prod, exists_prop, mem_ran, mem_sep, mem_inter, mem_powerset], rw h𝓐 _ at hX𝓐, rcases hX𝓐 with ⟨B, hBA, hBne, hX⟩, refine ⟨_, ⟨hBA, hBne⟩, _⟩, rw hX at hzX, simp only [mem_prod, exists_prop, mem_singleton] at hzX, rcases hzX with ⟨B', hB', b, hb, he⟩, rw he at hzC, rw ←hB', refine ⟨_, ⟨_, hzC, _⟩, he⟩, simp only [mem_Union, exists_prop, h𝓐 _], refine ⟨_, ⟨_, hBA, hBne, rfl⟩, _⟩, simp only [pair_mem_prod, mem_singleton], exact ⟨hB', hb⟩, refine ⟨Fsubprod, _⟩, intros B hB, simp only [mem_sep, exists_prop, mem_powerset] at hB, simp only [mem_inter, mem_Union], have hB𝓐 : prod {B} B ∈ 𝓐, rw h𝓐 _, exact ⟨_, hB.left, hB.right, rfl⟩, have he : ∃ x, C ∩ prod {B} B = {x}, apply hC _ hB𝓐, replace he : ∃! x, x ∈ C ∩ prod {B} B, rcases he with ⟨x, he⟩, rw ←ext_iff at he, simp only [mem_singleton] at he, refine ⟨x, (he x).mpr rfl, λ x' hx, _⟩, apply (he x').mp, exact hx, simp only [mem_inter, mem_prod, exists_prop, mem_singleton] at he, rcases he with ⟨x, ⟨hxC, B', hBB', b, hb, he⟩, ha⟩, rw [he, hBB'] at hxC, refine ⟨_, ⟨hxC, _, hB𝓐, _⟩, λ b' hb', _⟩, rw [pair_mem_prod, mem_singleton], exact ⟨rfl, hb⟩, rcases hb' with ⟨hxC', X, hX𝓐, he'⟩, rw h𝓐 X at hX𝓐, rcases hX𝓐 with ⟨B'', hBA'', hBne'', hB''⟩, refine (@pair_inj B _ B _ _).right, rw [he, hBB'] at ha, apply ha _, refine ⟨hxC', _, rfl, b', _, rfl⟩, rw [hB'', pair_mem_prod, mem_singleton] at he', rw he'.left, exact he'.right, refine ⟨hFinto.left, hFinto.right.left, λ B hB, _⟩, rw mem_dom at hB, rcases hB with ⟨b, hb⟩, have hb' : ∃ X, X ∈ 𝓐 ∧ B.pair b ∈ X, simp only [mem_inter, mem_Union, exists_prop] at hb, exact hb.right, rcases hb' with ⟨X, hX𝓐, hBX⟩, rw h𝓐 _ at hX𝓐, rcases hX𝓐 with ⟨B', hBA', hB', he⟩, simp only [he, pair_mem_prod, exists_prop, mem_singleton] at hBX, rw hBX.left, rw hBX.left at hb, rw fun_value_def hFinto.left hb at hBX, exact hBX.right, }, tfae_have : 3 → 1, { dsimp only [Axiom_of_choice_III, Axiom_of_choice_I], intros ax3 R hR, specialize @ax3 R.ran, rcases ax3 with ⟨G, Gfun, GsubR, hG⟩, let F := pair_sep_eq R.dom G.ran (λ x, G.fun_value {y ∈ R.ran | x.pair y ∈ R}), have Ffun : F.is_function := pair_sep_eq_is_fun, have BGdom : ∀ {a : Set}, a ∈ R.dom → {y ∈ R.ran | a.pair y ∈ R} ∈ G.dom, intros a ha, simp only [GsubR, mem_sep, mem_powerset], split, exact sep_subset, apply ne_empty_of_inhabited, rw mem_dom at ha, simp only [inhab, mem_sep, mem_ran], rcases ha with ⟨b, hab⟩, exact ⟨b, ⟨a, hab⟩, hab⟩, refine ⟨_, Ffun, _, _⟩, intros z hz, simp only [F, pair_sep_eq, mem_pair_sep, exists_prop] at hz, rcases hz with ⟨a, ha, b, hb, he, he'⟩, subst he, subst he', specialize hG _ (BGdom ha), rw mem_sep at hG, exact hG.right, apply pair_sep_eq_dom_eq, intros a ha, apply fun_value_def'' Gfun (BGdom ha), }, tfae_finish, end theorem ax_ch_1 : Axiom_of_choice_I := begin refine list.tfae_prf choice_equiv _ _ @ax_ch_3, finish, finish, end theorem ax_ch_2 : Axiom_of_choice_II := begin refine list.tfae_prf choice_equiv _ _ @ax_ch_3, finish, finish, end lemma T3J_b {F A B : Set} (hf : F.into_fun A B) : (∃ H : Set, H.into_fun B A ∧ F.comp H = B.id) ↔ F.onto_fun A B := begin rcases hf with ⟨hf, hd, hr⟩, split, { rintro ⟨H, ⟨hhf, hhd, hhr⟩, heq⟩, refine ⟨hf, hd, _⟩, apply ext, intro z, split, { intro hz, exact hr hz, }, { intro hz, rw mem_ran, existsi H.fun_value z, apply fun_value_def''' hf, rw hd, apply hhr, refine fun_value_def'' hhf _, rw hhd, assumption, rw ←T3H_c hf hhf, rw heq, symmetry, exact id_value hz, rw heq, rw id_onto.right.left, assumption, }, }, { rintro ⟨-, -, hre⟩, rcases @ax_ch_1 F.inv inv_rel with ⟨H, hhf, hhs, hhd⟩, existsi H, split, refine ⟨hhf, _, _⟩, simp only [hhd, T3E_a, hre], rw ←hd, rw ←T3E_b, exact ran_subset_of_subset hhs, apply fun_ext (T3H_a hf hhf) id_is_function, apply ext, intro z, simp only [T3H_b hf hhf, mem_sep, hhd, T3E_a, hre, id_onto.right.left, and_iff_left_iff_imp], intro hz, simp only [←T3E_b], apply ran_subset_of_subset hhs, apply fun_value_def'' hhf, simp only [hhd, T3E_a, hre, hz], intros x hx, rw id_value, rw T3H_c hf hhf hx, symmetry, apply fun_value_def hf, rw ←pair_mem_inv, apply hhs, apply fun_value_def' hhf, simp only [T3H_b hf hhf, mem_sep] at hx, finish, simp only [T3H_b hf hhf, mem_sep] at hx, finish, }, end def img_fun_img (F 𝓐 : Set) : Set := {B ∈ F.ran.powerset | ∃ A ∈ 𝓐, B = F.img A} @[simp] lemma mem_img_fun_img {F 𝓐 B : Set} : B ∈ F.img_fun_img 𝓐 ↔ ∃ A ∈ 𝓐, B = F.img A := begin simp only [img_fun_img, mem_sep, and_imp, exists_prop, mem_powerset, and_iff_right_iff_imp, exists_imp_distrib], intros A hA hB y hy, rw hB at hy, simp only [mem_ran, mem_img] at *, finish, end theorem T3K_a {F 𝓐 : Set} : F.img 𝓐.Union = (F.img_fun_img 𝓐).Union := begin apply ext, intro y, simp only [exists_prop, mem_img_fun_img, mem_img, mem_Union], split, { rintro ⟨x, ⟨A, hA, hx⟩, hp⟩, refine ⟨F.img A, ⟨A, hA, rfl⟩, _⟩, simp only [mem_img], exact ⟨_, hx, hp⟩, }, { rintro ⟨B, ⟨A, hA, hB⟩, hy⟩, rw [hB, mem_img] at hy, rcases hy with ⟨x, hx, hp⟩, exact ⟨_, ⟨_, hA, hx⟩, hp⟩, }, end theorem T3K_b {F 𝓐 : Set} : F.img 𝓐.Inter ⊆ (F.img_fun_img 𝓐).Inter := begin intro y, simp only [and_imp, mem_img, exists_imp_distrib, inhab, exists_prop, mem_img_fun_img, mem_Inter], intros x A hA ha hp, refine ⟨⟨F.img A, _, hA, rfl⟩, (λ B X hX hB, _)⟩, rw [hB, mem_img], exact ⟨_, ha _ hX, hp⟩, end theorem T3K_b_eq {F 𝓐 : Set} (hf : F.one_to_one) : F.img 𝓐.Inter = (F.img_fun_img 𝓐).Inter := begin rw eq_iff_subset_and_subset, refine ⟨T3K_b, _⟩, intro y, simp only [mem_Inter, inhab, and_imp, exists_prop, mem_img_fun_img, mem_img, exists_imp_distrib], intros B A hA hB ha, have hy : y ∈ F.img A, exact ha _ _ hA rfl, rw mem_img at hy, rcases hy with ⟨x, hx, hp⟩, refine ⟨_, ⟨⟨_, hA⟩, (λ X hX, _)⟩, hp⟩, have hy : y ∈ F.img X, exact ha _ _ hX rfl, rw mem_img at hy, rcases hy with ⟨x', hx', hp'⟩, have he : x = x', refine unique_of_exists_unique (hf y _) hp hp', rw mem_ran, exact ⟨_, hp⟩, rw he, assumption, end theorem T3K_c {F A B : Set} : F.img A \ F.img B ⊆ F.img (A \ B) := begin intro y, simp only [mem_img, mem_diff, not_exists, and_imp, not_and, exists_imp_distrib], intros x hx hp ha, exact ⟨_, ⟨hx, (λ h, ha _ h hp)⟩, hp⟩, end theorem T3K_c_eq {F A B : Set} (hf : F.one_to_one) : F.img A \ F.img B = F.img (A \ B) := begin rw eq_iff_subset_and_subset, refine ⟨T3K_c, _⟩, intro y, simp only [not_exists, and_imp, not_and, mem_diff, mem_img, exists_imp_distrib], intros x hA hB hp, refine ⟨⟨_, hA, hp⟩, (λ x' hB' hp', _)⟩, apply hB, have he : x = x', refine unique_of_exists_unique (hf y _) hp hp', rw mem_ran, exact ⟨_, hp⟩, rw he, assumption, end def into_funs (X Y : Set) : Set := {f ∈ (X.prod Y).powerset | f.into_fun X Y} @[simp] lemma mem_into_funs {X Y f : Set} : f ∈ X.into_funs Y ↔ f.into_fun X Y := begin simp only [into_funs, mem_powerset, and_iff_right_iff_imp, mem_sep], rintros ⟨hf, hd, hr⟩ p hp, have hp' : ∃ x y : Set, p = x.pair y, from hf.left _ hp, rcases hp' with ⟨x, y, hp'⟩, simp *, have hd' : x ∈ f.dom, rw hp' at hp, simp, exact ⟨_, hp⟩, have hr' : y ∈ f.ran, rw hp' at hp, simp, exact ⟨_, hp⟩, rw hd at hd', refine ⟨hd', hr hr'⟩, end -- these examples are from the very end of the section on functions theorem ex1 {A : Set} (h : A.inhab) : A.into_funs ∅ = ∅ := begin rw eq_empty, intros f hf, rw mem_into_funs at hf, rcases h with ⟨x, hx⟩, rcases hf with ⟨hf, hd, hr⟩, rw ←hd at hx, rw mem_dom at hx, rcases hx with ⟨y, hy⟩, apply (mem_empty y), apply hr, rw mem_ran, exact ⟨_, hy⟩, end theorem ex2 {A : Set} : (∅ : Set).into_funs A = {∅} := begin apply ext, simp only [mem_singleton, mem_into_funs], intro f, split, { rintro ⟨⟨hre, hf⟩, hd, hr⟩, rw eq_empty, intros p hp, have hx := hre _ hp, rcases hx with ⟨x, y, hx⟩, rw hx at hp, apply mem_empty x, rw ←hd, rw mem_dom, exact ⟨_, hp⟩, }, { have hd : (∅ : Set).dom = ∅, rw eq_empty, intros x hx, rw mem_dom at hx, rcases hx with ⟨y, hy⟩, exact mem_empty _ hy, intro he, rw he, refine ⟨⟨(λ p hp, _), (λ x hx, _)⟩, _, _⟩, { exfalso, exact p.mem_empty hp, }, { rw hd at hx, exfalso, exact x.mem_empty hx, }, { exact hd, }, { intros y hy, rw mem_ran at hy, rcases hy with ⟨y, hy⟩, exfalso, exact mem_empty _ hy, }, }, end theorem p16 : ¬ ∃ X : Set, ∀ f : Set, f ∈ X ↔ f.is_function := begin rintro ⟨X, hX⟩, apply univ_not_set, refine ⟨X.Union.Union.Union, (λ x, _)⟩, simp only [exists_prop, mem_Union], refine ⟨{x}, ⟨x.pair x, ⟨{x.pair x}, _, _⟩, _⟩, _⟩, { rw hX, refine ⟨(λ p hp, _), (λ t ht, ⟨x, _, _⟩)⟩, { rw mem_singleton at hp, rw hp, exact ⟨_, _, rfl⟩, }, { change t.pair x ∈ {x.pair x}, rw mem_singleton, rw mem_dom at ht, rcases ht with ⟨y, hy⟩, rw mem_singleton at hy, rw (pair_inj hy).left, }, { intros x' hx', rw mem_singleton at hx', exact (pair_inj hx').right, }, }, { rw mem_singleton, }, { rw [pair, mem_pair], left, refl, }, { rw mem_singleton, }, end -- Chapter 3, problem 17 theorem comp_one_to_one {f : Set} (hf : f.one_to_one) {g : Set} (hg : g.one_to_one) : (f.comp g).one_to_one := begin intros y hy, rw [mem_ran] at hy, apply exists_unique_of_exists_of_unique hy, intros x x' hx hx', rw [pair_mem_comp] at hx hx', rcases hx with ⟨z, hxz, hzy⟩, rcases hx' with ⟨z', hxz', hzy'⟩, have hze : z = z', refine unique_of_exists_unique (hf _ _) hzy hzy', rw mem_ran, finish, subst hze, refine unique_of_exists_unique (hg _ _) hxz hxz', rw mem_ran, finish, end -- chapter 3, problem 21 theorem comp_assoc {R S T : Set} : (R.comp S).comp T = R.comp (S.comp T) := begin apply ext, simp only [mem_comp, pair_mem_comp], intro z, split, { rintro ⟨a, b, d, hz, hT, c, hS, hR⟩, exact ⟨a, c, d, hz, ⟨b, hT, hS⟩, hR⟩, }, { rintro ⟨a, c, d, hz, ⟨b, hT, hS⟩, hR⟩, exact ⟨a, b, d, hz, hT, c, hS, hR⟩, }, end section p30 parameters {A F : Set.{u}} def B : Set := {X ∈ A.powerset | F.fun_value X ⊆ X}.Inter def C : Set := {X ∈ A.powerset | X ⊆ F.fun_value X}.Union lemma F_sub_of_self (hf : F.into_fun A.powerset A.powerset) {X : Set} (h : X ∈ A.powerset) : F.fun_value X ∈ A.powerset := begin apply ran_sub_of_into hf, apply fun_value_def'' (is_function_of_into hf), rw dom_eq_of_into hf, assumption, end lemma C_subset_A : C ∈ A.powerset := begin rw mem_powerset, intro z, simp only [C, mem_Union, exists_prop, mem_sep, mem_powerset], rintro ⟨X, ⟨hX, -⟩, hz⟩, exact hX hz, end lemma B_subset_A (hf : F.into_fun A.powerset A.powerset) : B ∈ A.powerset := begin rw mem_powerset, intro z, simp only [B, mem_Inter, mem_sep], rintro ⟨hin, ha⟩, apply ha, refine ⟨mem_powerset_self, _⟩, rw ←mem_powerset, apply F_sub_of_self hf, exact mem_powerset_self, end lemma subset_C {X : Set} (hA : X ∈ A.powerset) (hX : X ⊆ F.fun_value X) : X ⊆ C := begin rw C, apply subset_Union, rw [mem_sep, mem_powerset], finish, end lemma B_subset {X : Set} (hA : X ∈ A.powerset) (hX : F.fun_value X ⊆ X) : B ⊆ X := begin rw B, apply subset_Inter, rw [mem_sep, mem_powerset], finish, end theorem p30_b {X : Set} (hA : X ⊆ A) (hX : F.fun_value X = X) : B ⊆ X ∧ X ⊆ C := begin rw eq_iff_subset_and_subset at hX, refine ⟨(λ x hx, _), (λ x hx, _)⟩, { rw B at hx, simp only [mem_Inter, mem_sep, mem_powerset] at hx, apply hx.right, exact ⟨hA, hX.left⟩, }, { rw C, simp only [mem_Union, mem_sep, mem_powerset, exists_prop], exact ⟨_, ⟨hA, hX.right⟩, hx⟩, }, end theorem p30_a {hf : F.into_fun A.powerset A.powerset} {hmon : ∀ {X Y : Set}, X ⊆ Y → Y ∈ A.powerset → F.fun_value X ⊆ F.fun_value Y} : F.fun_value B = B ∧ F.fun_value C = C := begin have hC : C ⊆ F.fun_value C, intros z hz, simp only [C, mem_Union, exists_prop, mem_sep] at hz, rcases hz with ⟨X, ⟨hA, hX⟩, hz⟩, exact hmon (subset_C hA hX) C_subset_A (hX hz), have hB : F.fun_value B ⊆ B, intros z hz, simp only [B, mem_Inter, mem_sep], refine ⟨⟨A, _⟩, (λ X ⟨hA, hX⟩, hX (hmon (B_subset hA hX) hA hz))⟩, simp only [mem_sep], rw ←mem_powerset, refine ⟨mem_powerset_self, _⟩, apply F_sub_of_self hf, exact mem_powerset_self, simp only [eq_iff_subset_and_subset], refine ⟨⟨hB, _⟩, _, hC⟩, { apply B_subset, apply F_sub_of_self hf, exact B_subset_A hf, apply hmon hB (B_subset_A hf), }, { apply subset_C, apply F_sub_of_self hf, exact C_subset_A, apply hmon hC, apply F_sub_of_self hf, exact C_subset_A, }, end end p30 def inf_prod (H I : Set) : Set := {f ∈ I.into_funs (H.img I).Union | f.is_function ∧ f.dom = I ∧ ∀ i : Set, i ∈ I → f.fun_value i ∈ H.fun_value i} @[simp] lemma mem_inf_prod {H I f : Set} (hF : H.is_function) (hD : I ⊆ H.dom) : f ∈ H.inf_prod I ↔ f.is_function ∧ f.dom = I ∧ ∀ i : Set, i ∈ I → f.fun_value i ∈ H.fun_value i := begin simp only [inf_prod, mem_sep, and_imp, mem_fun_value, and_iff_right_iff_imp, mem_into_funs], intros hf hd ha, refine ⟨hf, hd, (λ y hy, _)⟩, simp only [mem_Union, exists_prop, mem_img_fun_img], rw mem_ran at hy, rcases hy with ⟨x, hy⟩, have hxi : x ∈ I, rw [←hd, mem_dom], exact ⟨_, hy⟩, have hY := ha _ hxi, rcases hY with ⟨Y, hH, hY⟩, refine ⟨Y, _, _⟩, { simp only [mem_img], refine ⟨x, hxi, hH⟩, }, { rw fun_value_def hf hy, assumption, }, end theorem inf_prod_inhab {H I : Set} (hF : H.is_function) (hD : H.dom = I) (hA : ∀ i : Set, i ∈ I → H.fun_value i ≠ ∅) : (H.inf_prod I ).inhab := begin have hD' : I ⊆ H.dom, rw hD, exact subset_self, simp only [inhab, mem_inf_prod hF hD'], exact @ax_ch_2 _ _ ⟨hF, hD, hA⟩, end def symmetric (R : Set) : Prop := ∀ ⦃x y : Set⦄, x.pair y ∈ R → y.pair x ∈ R def transitive (R : Set) : Prop := ∀ ⦃x y z : Set⦄, x.pair y ∈ R → y.pair z ∈ R → x.pair z ∈ R structure equiv_rel (R A : Set) : Prop := (rel : R ⊆ A.prod A) (refl : ∀ ⦃x : Set⦄, x ∈ A → x.pair x ∈ R) (symm : R.symmetric) (trans : R.transitive) theorem T3M {R : Set} (hr : R.is_rel) (hs : R.symmetric) (ht : R.transitive) : R.equiv_rel R.fld := begin refine ⟨(λ p hp, _), _, hs, ht⟩, { have h : ∃ x y : Set, p = x.pair y := hr _ hp, rcases h with ⟨x, y, h⟩, rw h at hp, simp only [mem_prod, exists_prop, fld, mem_union, mem_dom, mem_ran], exact ⟨_, or.inl ⟨_, hp⟩, _, or.inr ⟨_, hp⟩, h⟩, }, have h : ∀ {x y : Set}, x.pair y ∈ R → x.pair x ∈ R, intros x y h, exact ht h (hs h), simp only [fld, mem_union, mem_dom, mem_ran], rintros x (⟨y, hp⟩|⟨y, hp⟩), { exact h hp, }, { exact h (hs hp), }, end def eq_class (R x : Set) : Set := {t ∈ R.ran | x.pair t ∈ R} @[simp] lemma mem_eq_class {R x t : Set} : t ∈ R.eq_class x ↔ x.pair t ∈ R := begin simp only [eq_class, and_iff_right_iff_imp, mem_ran, mem_sep], intro h, exact ⟨_, h⟩, end lemma mem_eq_class_of_self {R A x : Set} (hr : R.equiv_rel A) (hx : x ∈ A) : x ∈ R.eq_class x := begin rw mem_eq_class, exact hr.refl hx, end def eq_classes (R A : Set) : Set := {X ∈ R.ran.powerset | ∃ x : Set, X = R.eq_class x ∧ x ∈ A} @[simp] lemma mem_eq_classes {R A X : Set} : X ∈ R.eq_classes A ↔ ∃ x : Set, X = R.eq_class x ∧ x ∈ A := begin simp only [eq_classes, mem_powerset, and_iff_right_iff_imp, exists_imp_distrib, mem_sep], rintros x ⟨hX, hx⟩, rw hX, intro t, rw [eq_class, mem_sep], finish, end lemma L3N {R A : Set} (hr : R.equiv_rel A) {x y : Set} (hx : x ∈ A) (hy : y ∈ A) : R.eq_class x = R.eq_class y ↔ x.pair y ∈ R := begin refine ⟨(λ h, _), (λ h, _)⟩, { rw [←mem_eq_class, h, mem_eq_class], exact hr.refl hy, }, { apply ext, intro t, simp only [mem_eq_class], split, { exact (λ ht, hr.trans (hr.symm h) ht), }, { exact (λ ht, hr.trans h ht), }, }, end structure partition (P A : Set) : Prop := (subs : ∀ ⦃x : Set⦄, x ∈ P → x ⊆ A) (nonem : ∀ ⦃x : Set⦄, x ∈ P → x ≠ ∅) (disj : ∀ ⦃x y : Set⦄, x ∈ P → y ∈ P → x ≠ y → (x ∩ y) = ∅) (exhaust : ∀ ⦃x : Set⦄, x ∈ A → ∃ X : Set, X ∈ P ∧ x ∈ X) theorem T3P {R A : Set} (hr : R.equiv_rel A) : (R.eq_classes A).partition A := begin refine ⟨_, _, _, _⟩, { simp only [mem_eq_classes], rintros X ⟨x, hX⟩ t ht, simp only [hX, mem_eq_class] at ht, replace ht : x.pair t ∈ A.prod A := hr.rel ht, simp only [pair_mem_prod] at ht, exact ht.right }, { simp only [mem_eq_classes], rintros X ⟨x, hX, hx⟩, apply ne_empty_of_inhabited, existsi x, rw hX, exact mem_eq_class_of_self hr hx, }, { simp only [mem_eq_classes], rintros X Y ⟨x, hX, hx⟩ ⟨y, hY, hy⟩ hne, rw eq_empty, intros t ht, simp only [mem_inter, hX, hY, mem_eq_class] at ht, apply hne, rw [hX, hY, L3N hr hx hy], exact hr.trans ht.left (hr.symm ht.right), }, { simp only [mem_eq_classes], intros x hx, exact ⟨_, ⟨_, rfl, hx⟩, mem_eq_class_of_self hr hx⟩, }, end -- I'm not writing any lemmas for this unless we use it def natural_map (R A : Set) : Set := pair_sep (λ x X, X = R.eq_class x) A (R.eq_classes A) -- thm 3Q --37 --38, maybe --39, maybe --42 --delay 3Q until it's needed structure lin_order (A R : Set) : Prop := (rel : R ⊆ A.prod A) (trans : R.transitive) (irrefl : ∀ ⦃x : Set⦄, x.pair x ∉ R) (conn : ∀ ⦃x y : Set⦄, x ∈ A → y ∈ A → x ≠ y → x.pair y ∈ R ∨ y.pair x ∈ R) lemma inv_lin_order {A R : Set} (lin : A.lin_order R) : A.lin_order R.inv := begin split, { exact inv_sub_prod lin.rel, }, { intros x y z xy yz, rw pair_mem_inv at xy yz ⊢, exact lin.trans yz xy, }, { intros x xx, rw pair_mem_inv at xx, exact lin.irrefl xx, }, { intros x y xA yA xy, simp only [pair_mem_inv, or_comm], exact lin.conn xA yA xy, }, end lemma prod_disj {A B C D : Set} (h : C ∩ D = ∅) : A.prod C ∩ B.prod D = ∅ := begin rw eq_empty, intros z hz, simp only [mem_inter, mem_prod, exists_prop] at hz, rcases hz with ⟨⟨a, ha, b, hb, he⟩, a', ha', b', hb', he'⟩, rw he' at he, rw (pair_inj he).right at hb', have hb'' : b ∈ C ∩ D, rw mem_inter, finish, rw h at hb'', exact mem_empty _ hb'', end lemma singleton_disj_of_ne {A B : Set} (hne : A ≠ B) : {A} ∩ {B} = (∅ : Set) := begin rw eq_empty, intros z hz, simp only [mem_inter, mem_singleton] at hz, apply hne, rw ←hz.left, rw ←hz.right, end end Set
0cde48eeff4eb17afed701afac0d04989d8460c9
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/set_theory/zfc.lean
b963750a3bff8578d8d5e13e16b9277660270b68
[ "Apache-2.0" ]
permissive
lacker/mathlib
f2439c743c4f8eb413ec589430c82d0f73b2d539
ddf7563ac69d42cfa4a1bfe41db1fed521bd795f
refs/heads/master
1,671,948,326,773
1,601,479,268,000
1,601,479,268,000
298,686,743
0
0
Apache-2.0
1,601,070,794,000
1,601,070,794,000
null
UTF-8
Lean
false
false
30,802
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro A model of ZFC in Lean. -/ import data.set.basic universes u v /-- The type of `n`-ary functions `α → α → ... → α`. -/ def arity (α : Type u) : nat → Type u | 0 := α | (n+1) := α → arity n namespace arity /-- Constant `n`-ary function with value `a`. -/ def const {α : Type u} (a : α) : ∀ n, arity α n | 0 := a | (n+1) := λ _, const n instance arity.inhabited {α n} [inhabited α] : inhabited (arity α n) := ⟨const (default _) _⟩ end arity /-- The type of pre-sets in universe `u`. A pre-set is a family of pre-sets indexed by a type in `Type u`. The ZFC universe is defined as a quotient of this to ensure extensionality. -/ inductive pSet : Type (u+1) | mk (α : Type u) (A : α → pSet) : pSet namespace pSet /-- The underlying type of a pre-set -/ def type : pSet → Type u | ⟨α, A⟩ := α /-- The underlying pre-set family of a pre-set -/ def func : Π (x : pSet), x.type → pSet | ⟨α, A⟩ := A theorem mk_type_func : Π (x : pSet), mk x.type x.func = x | ⟨α, A⟩ := rfl /-- Two pre-sets are extensionally equivalent if every element of the first family is extensionally equivalent to some element of the second family and vice-versa. -/ def equiv (x y : pSet) : Prop := pSet.rec (λα z m ⟨β, B⟩, (∀a, ∃b, m a (B b)) ∧ (∀b, ∃a, m a (B b))) x y theorem equiv.refl (x) : equiv x x := pSet.rec_on x $ λα A IH, ⟨λa, ⟨a, IH a⟩, λa, ⟨a, IH a⟩⟩ theorem equiv.euc {x} : Π {y z}, equiv x y → equiv z y → equiv x z := pSet.rec_on x $ λα A IH y, pSet.cases_on y $ λβ B ⟨γ, Γ⟩ ⟨αβ, βα⟩ ⟨γβ, βγ⟩, ⟨λa, let ⟨b, ab⟩ := αβ a, ⟨c, bc⟩ := βγ b in ⟨c, IH a ab bc⟩, λc, let ⟨b, cb⟩ := γβ c, ⟨a, ba⟩ := βα b in ⟨a, IH a ba cb⟩⟩ theorem equiv.symm {x y} : equiv x y → equiv y x := equiv.euc (equiv.refl y) theorem equiv.trans {x y z} (h1 : equiv x y) (h2 : equiv y z) : equiv x z := equiv.euc h1 (equiv.symm h2) instance setoid : setoid pSet := ⟨pSet.equiv, equiv.refl, λx y, equiv.symm, λx y z, equiv.trans⟩ protected def subset : pSet → pSet → Prop | ⟨α, A⟩ ⟨β, B⟩ := ∀a, ∃b, equiv (A a) (B b) instance : has_subset pSet := ⟨pSet.subset⟩ theorem equiv.ext : Π (x y : pSet), equiv x y ↔ (x ⊆ y ∧ y ⊆ x) | ⟨α, A⟩ ⟨β, B⟩ := ⟨λ⟨αβ, βα⟩, ⟨αβ, λb, let ⟨a, h⟩ := βα b in ⟨a, equiv.symm h⟩⟩, λ⟨αβ, βα⟩, ⟨αβ, λb, let ⟨a, h⟩ := βα b in ⟨a, equiv.symm h⟩⟩⟩ theorem subset.congr_left : Π {x y z : pSet}, equiv x y → (x ⊆ z ↔ y ⊆ z) | ⟨α, A⟩ ⟨β, B⟩ ⟨γ, Γ⟩ ⟨αβ, βα⟩ := ⟨λαγ b, let ⟨a, ba⟩ := βα b, ⟨c, ac⟩ := αγ a in ⟨c, equiv.trans (equiv.symm ba) ac⟩, λβγ a, let ⟨b, ab⟩ := αβ a, ⟨c, bc⟩ := βγ b in ⟨c, equiv.trans ab bc⟩⟩ theorem subset.congr_right : Π {x y z : pSet}, equiv x y → (z ⊆ x ↔ z ⊆ y) | ⟨α, A⟩ ⟨β, B⟩ ⟨γ, Γ⟩ ⟨αβ, βα⟩ := ⟨λγα c, let ⟨a, ca⟩ := γα c, ⟨b, ab⟩ := αβ a in ⟨b, equiv.trans ca ab⟩, λγβ c, let ⟨b, cb⟩ := γβ c, ⟨a, ab⟩ := βα b in ⟨a, equiv.trans cb (equiv.symm ab)⟩⟩ /-- `x ∈ y` as pre-sets if `x` is extensionally equivalent to a member of the family `y`. -/ def mem : pSet → pSet → Prop | x ⟨β, B⟩ := ∃b, equiv x (B b) instance : has_mem pSet.{u} pSet.{u} := ⟨mem⟩ theorem mem.mk {α: Type u} (A : α → pSet) (a : α) : A a ∈ mk α A := show mem (A a) ⟨α, A⟩, from ⟨a, equiv.refl (A a)⟩ theorem mem.ext : Π {x y : pSet.{u}}, (∀w:pSet.{u}, w ∈ x ↔ w ∈ y) → equiv x y | ⟨α, A⟩ ⟨β, B⟩ h := ⟨λa, (h (A a)).1 (mem.mk A a), λb, let ⟨a, ha⟩ := (h (B b)).2 (mem.mk B b) in ⟨a, equiv.symm ha⟩⟩ theorem mem.congr_right : Π {x y : pSet.{u}}, equiv x y → (∀{w:pSet.{u}}, w ∈ x ↔ w ∈ y) | ⟨α, A⟩ ⟨β, B⟩ ⟨αβ, βα⟩ w := ⟨λ⟨a, ha⟩, let ⟨b, hb⟩ := αβ a in ⟨b, equiv.trans ha hb⟩, λ⟨b, hb⟩, let ⟨a, ha⟩ := βα b in ⟨a, equiv.euc hb ha⟩⟩ theorem equiv_iff_mem {x y : pSet.{u}} : equiv x y ↔ (∀{w:pSet.{u}}, w ∈ x ↔ w ∈ y) := ⟨mem.congr_right, match x, y with | ⟨α, A⟩, ⟨β, B⟩, h := ⟨λ a, h.1 (mem.mk A a), λ b, let ⟨a, h⟩ := h.2 (mem.mk B b) in ⟨a, h.symm⟩⟩ end⟩ theorem mem.congr_left : Π {x y : pSet.{u}}, equiv x y → (∀{w : pSet.{u}}, x ∈ w ↔ y ∈ w) | x y h ⟨α, A⟩ := ⟨λ⟨a, ha⟩, ⟨a, equiv.trans (equiv.symm h) ha⟩, λ⟨a, ha⟩, ⟨a, equiv.trans h ha⟩⟩ /-- Convert a pre-set to a `set` of pre-sets. -/ def to_set (u : pSet.{u}) : set pSet.{u} := {x | x ∈ u} /-- Two pre-sets are equivalent iff they have the same members. -/ theorem equiv.eq {x y : pSet} : equiv x y ↔ to_set x = to_set y := equiv_iff_mem.trans set.ext_iff.symm instance : has_coe pSet (set pSet) := ⟨to_set⟩ /-- The empty pre-set -/ protected def empty : pSet := ⟨ulift empty, λe, match e with end⟩ instance : has_emptyc pSet := ⟨pSet.empty⟩ instance : inhabited pSet := ⟨∅⟩ theorem mem_empty (x : pSet.{u}) : x ∉ (∅:pSet.{u}) := λe, match e with end /-- Insert an element into a pre-set -/ protected def insert : pSet → pSet → pSet | u ⟨α, A⟩ := ⟨option α, λo, option.rec u A o⟩ instance : has_insert pSet pSet := ⟨pSet.insert⟩ instance : has_singleton pSet pSet := ⟨λ s, insert s ∅⟩ instance : is_lawful_singleton pSet pSet := ⟨λ _, rfl⟩ /-- The n-th von Neumann ordinal -/ def of_nat : ℕ → pSet | 0 := ∅ | (n+1) := pSet.insert (of_nat n) (of_nat n) /-- The von Neumann ordinal ω -/ def omega : pSet := ⟨ulift ℕ, λn, of_nat n.down⟩ /-- The separation operation `{x ∈ a | p x}` -/ protected def sep (p : set pSet) : pSet → pSet | ⟨α, A⟩ := ⟨{a // p (A a)}, λx, A x.1⟩ instance : has_sep pSet pSet := ⟨pSet.sep⟩ /-- The powerset operator -/ def powerset : pSet → pSet | ⟨α, A⟩ := ⟨set α, λp, ⟨{a // p a}, λx, A x.1⟩⟩ theorem mem_powerset : Π {x y : pSet}, y ∈ powerset x ↔ y ⊆ x | ⟨α, A⟩ ⟨β, B⟩ := ⟨λ⟨p, e⟩, (subset.congr_left e).2 $ λ⟨a, pa⟩, ⟨a, equiv.refl (A a)⟩, λβα, ⟨{a | ∃b, equiv (B b) (A a)}, λb, let ⟨a, ba⟩ := βα b in ⟨⟨a, b, ba⟩, ba⟩, λ⟨a, b, ba⟩, ⟨b, ba⟩⟩⟩ /-- The set union operator -/ def Union : pSet → pSet | ⟨α, A⟩ := ⟨Σx, (A x).type, λ⟨x, y⟩, (A x).func y⟩ theorem mem_Union : Π {x y : pSet.{u}}, y ∈ Union x ↔ ∃ z:pSet.{u}, ∃_:z ∈ x, y ∈ z | ⟨α, A⟩ y := ⟨λ⟨⟨a, c⟩, (e : equiv y ((A a).func c))⟩, have func (A a) c ∈ mk (A a).type (A a).func, from mem.mk (A a).func c, ⟨_, mem.mk _ _, (mem.congr_left e).2 (by rwa mk_type_func at this)⟩, λ⟨⟨β, B⟩, ⟨a, (e:equiv (mk β B) (A a))⟩, ⟨b, yb⟩⟩, by rw ←(mk_type_func (A a)) at e; exact let ⟨βt, tβ⟩ := e, ⟨c, bc⟩ := βt b in ⟨⟨a, c⟩, equiv.trans yb bc⟩⟩ /-- The image of a function -/ def image (f : pSet.{u} → pSet.{u}) : pSet.{u} → pSet | ⟨α, A⟩ := ⟨α, λa, f (A a)⟩ theorem mem_image {f : pSet.{u} → pSet.{u}} (H : ∀{x y}, equiv x y → equiv (f x) (f y)) : Π {x y : pSet.{u}}, y ∈ image f x ↔ ∃z ∈ x, equiv y (f z) | ⟨α, A⟩ y := ⟨λ⟨a, ya⟩, ⟨A a, mem.mk A a, ya⟩, λ⟨z, ⟨a, za⟩, yz⟩, ⟨a, equiv.trans yz (H za)⟩⟩ /-- Universe lift operation -/ protected def lift : pSet.{u} → pSet.{max u v} | ⟨α, A⟩ := ⟨ulift α, λ⟨x⟩, lift (A x)⟩ /-- Embedding of one universe in another -/ def embed : pSet.{max (u+1) v} := ⟨ulift.{v u+1} pSet, λ⟨x⟩, pSet.lift.{u (max (u+1) v)} x⟩ theorem lift_mem_embed : Π (x : pSet.{u}), pSet.lift.{u (max (u+1) v)} x ∈ embed.{u v} := λx, ⟨⟨x⟩, equiv.refl _⟩ /-- Function equivalence is defined so that `f ~ g` iff `∀ x y, x ~ y → f x ~ g y`. This extends to equivalence of n-ary functions. -/ def arity.equiv : Π {n}, arity pSet.{u} n → arity pSet.{u} n → Prop | 0 a b := equiv a b | (n+1) a b := ∀ x y, equiv x y → arity.equiv (a x) (b y) lemma arity.equiv_const {a : pSet.{u}} : ∀ n, arity.equiv (arity.const a n) (arity.const a n) | 0 := equiv.refl _ | (n+1) := λ x y h, arity.equiv_const _ /-- `resp n` is the collection of n-ary functions on `pSet` that respect equivalence, i.e. when the inputs are equivalent the output is as well. -/ def resp (n) := { x : arity pSet.{u} n // arity.equiv x x } instance resp.inhabited {n} : inhabited (resp n) := ⟨⟨arity.const (default _) _, arity.equiv_const _⟩⟩ def resp.f {n} (f : resp (n+1)) (x : pSet) : resp n := ⟨f.1 x, f.2 _ _ $ equiv.refl x⟩ def resp.equiv {n} (a b : resp n) : Prop := arity.equiv a.1 b.1 theorem resp.refl {n} (a : resp n) : resp.equiv a a := a.2 theorem resp.euc : Π {n} {a b c : resp n}, resp.equiv a b → resp.equiv c b → resp.equiv a c | 0 a b c hab hcb := equiv.euc hab hcb | (n+1) a b c hab hcb := by delta resp.equiv; simp [arity.equiv]; exact λx y h, @resp.euc n (a.f x) (b.f y) (c.f y) (hab _ _ h) (hcb _ _ $ equiv.refl y) instance resp.setoid {n} : setoid (resp n) := ⟨resp.equiv, resp.refl, λx y h, resp.euc (resp.refl y) h, λx y z h1 h2, resp.euc h1 $ resp.euc (resp.refl z) h2⟩ end pSet /-- The ZFC universe of sets consists of the type of pre-sets, quotiented by extensional equivalence. -/ def Set : Type (u+1) := quotient pSet.setoid.{u} namespace pSet namespace resp def eval_aux : Π {n}, { f : resp n → arity Set.{u} n // ∀ (a b : resp n), resp.equiv a b → f a = f b } | 0 := ⟨λa, ⟦a.1⟧, λa b h, quotient.sound h⟩ | (n+1) := let F : resp (n + 1) → arity Set (n + 1) := λa, @quotient.lift _ _ pSet.setoid (λx, eval_aux.1 (a.f x)) (λb c h, eval_aux.2 _ _ (a.2 _ _ h)) in ⟨F, λb c h, funext $ @quotient.ind _ _ (λq, F b q = F c q) $ λz, eval_aux.2 (resp.f b z) (resp.f c z) (h _ _ (equiv.refl z))⟩ /-- An equivalence-respecting function yields an n-ary Set function. -/ def eval (n) : resp n → arity Set.{u} n := eval_aux.1 theorem eval_val {n f x} : (@eval (n+1) f : Set → arity Set n) ⟦x⟧ = eval n (resp.f f x) := rfl end resp /-- A set function is "definable" if it is the image of some n-ary pre-set function. This isn't exactly definability, but is useful as a sufficient condition for functions that have a computable image. -/ @[class] inductive definable (n) : arity Set.{u} n → Type (u+1) | mk (f) : definable (resp.eval _ f) attribute [instance] definable.mk def definable.eq_mk {n} (f) : Π {s : arity Set.{u} n} (H : resp.eval _ f = s), definable n s | ._ rfl := ⟨f⟩ def definable.resp {n} : Π (s : arity Set.{u} n) [definable n s], resp n | ._ ⟨f⟩ := f theorem definable.eq {n} : Π (s : arity Set.{u} n) [H : definable n s], (@definable.resp n s H).eval _ = s | ._ ⟨f⟩ := rfl end pSet namespace classical open pSet noncomputable def all_definable : Π {n} (F : arity Set.{u} n), definable n F | 0 F := let p := @quotient.exists_rep pSet _ F in definable.eq_mk ⟨some p, equiv.refl _⟩ (some_spec p) | (n+1) (F : arity Set.{u} (n + 1)) := begin have I := λx, (all_definable (F x)), refine definable.eq_mk ⟨λx:pSet, (@definable.resp _ _ (I ⟦x⟧)).1, _⟩ _, { dsimp [arity.equiv], introsI x y h, rw @quotient.sound pSet _ _ _ h, exact (definable.resp (F ⟦y⟧)).2 }, exact funext (λq, quotient.induction_on q $ λx, by simp [resp.eval_val, resp.f]; exact @definable.eq _ (F ⟦x⟧) (I ⟦x⟧)) end end classical namespace Set open pSet def mk : pSet → Set := quotient.mk @[simp] theorem mk_eq (x : pSet) : @eq Set ⟦x⟧ (mk x) := rfl @[simp] lemma eval_mk {n f x} : (@resp.eval (n+1) f : Set → arity Set n) (mk x) = resp.eval n (resp.f f x) := rfl def mem : Set → Set → Prop := quotient.lift₂ pSet.mem (λx y x' y' hx hy, propext (iff.trans (mem.congr_left hx) (mem.congr_right hy))) instance : has_mem Set Set := ⟨mem⟩ /-- Convert a ZFC set into a `set` of sets -/ def to_set (u : Set.{u}) : set Set.{u} := {x | x ∈ u} protected def subset (x y : Set.{u}) := ∀ ⦃z⦄, z ∈ x → z ∈ y instance has_subset : has_subset Set := ⟨Set.subset⟩ theorem subset_iff : Π (x y : pSet), mk x ⊆ mk y ↔ x ⊆ y | ⟨α, A⟩ ⟨β, B⟩ := ⟨λh a, @h ⟦A a⟧ (mem.mk A a), λh z, quotient.induction_on z (λz ⟨a, za⟩, let ⟨b, ab⟩ := h a in ⟨b, equiv.trans za ab⟩)⟩ theorem ext {x y : Set.{u}} : (∀z:Set.{u}, z ∈ x ↔ z ∈ y) → x = y := quotient.induction_on₂ x y (λu v h, quotient.sound (mem.ext (λw, h ⟦w⟧))) theorem ext_iff {x y : Set.{u}} : (∀z:Set.{u}, z ∈ x ↔ z ∈ y) ↔ x = y := ⟨ext, λh, by simp [h]⟩ /-- The empty set -/ def empty : Set := mk ∅ instance : has_emptyc Set := ⟨empty⟩ instance : inhabited Set := ⟨∅⟩ @[simp] theorem mem_empty (x) : x ∉ (∅:Set.{u}) := quotient.induction_on x pSet.mem_empty theorem eq_empty (x : Set.{u}) : x = ∅ ↔ ∀y:Set.{u}, y ∉ x := ⟨λh, by rw h; exact mem_empty, λh, ext (λy, ⟨λyx, absurd yx (h y), λy0, absurd y0 (mem_empty _)⟩)⟩ /-- `insert x y` is the set `{x} ∪ y` -/ protected def insert : Set → Set → Set := resp.eval 2 ⟨pSet.insert, λu v uv ⟨α, A⟩ ⟨β, B⟩ ⟨αβ, βα⟩, ⟨λo, match o with | some a := let ⟨b, hb⟩ := αβ a in ⟨some b, hb⟩ | none := ⟨none, uv⟩ end, λo, match o with | some b := let ⟨a, ha⟩ := βα b in ⟨some a, ha⟩ | none := ⟨none, uv⟩ end⟩⟩ instance : has_insert Set Set := ⟨Set.insert⟩ instance : has_singleton Set Set := ⟨λ x, insert x ∅⟩ instance : is_lawful_singleton Set Set := ⟨λ x, rfl⟩ @[simp] theorem mem_insert {x y z : Set.{u}} : x ∈ insert y z ↔ x = y ∨ x ∈ z := quotient.induction_on₃ x y z (λx y ⟨α, A⟩, show x ∈ pSet.mk (option α) (λo, option.rec y A o) ↔ mk x = mk y ∨ x ∈ pSet.mk α A, from ⟨λm, match m with | ⟨some a, ha⟩ := or.inr ⟨a, ha⟩ | ⟨none, h⟩ := or.inl (quotient.sound h) end, λm, match m with | or.inr ⟨a, ha⟩ := ⟨some a, ha⟩ | or.inl h := ⟨none, quotient.exact h⟩ end⟩) @[simp] theorem mem_singleton {x y : Set.{u}} : x ∈ @singleton Set.{u} Set.{u} _ y ↔ x = y := iff.trans mem_insert ⟨λo, or.rec (λh, h) (λn, absurd n (mem_empty _)) o, or.inl⟩ @[simp] theorem mem_pair {x y z : Set.{u}} : x ∈ ({y, z} : Set) ↔ x = y ∨ x = z := iff.trans mem_insert $ or_congr iff.rfl mem_singleton /-- `omega` is the first infinite von Neumann ordinal -/ def omega : Set := mk omega @[simp] theorem omega_zero : ∅ ∈ omega := show pSet.mem ∅ pSet.omega, from ⟨⟨0⟩, equiv.refl _⟩ @[simp] theorem omega_succ {n} : n ∈ omega.{u} → insert n n ∈ omega.{u} := quotient.induction_on n (λx ⟨⟨n⟩, h⟩, ⟨⟨n+1⟩, have Set.insert ⟦x⟧ ⟦x⟧ = Set.insert ⟦of_nat n⟧ ⟦of_nat n⟧, by rw (@quotient.sound pSet _ _ _ h), quotient.exact this⟩) /-- `{x ∈ a | p x}` is the set of elements in `a` satisfying `p` -/ protected def sep (p : Set → Prop) : Set → Set := resp.eval 1 ⟨pSet.sep (λy, p ⟦y⟧), λ⟨α, A⟩ ⟨β, B⟩ ⟨αβ, βα⟩, ⟨λ⟨a, pa⟩, let ⟨b, hb⟩ := αβ a in ⟨⟨b, by rwa ←(@quotient.sound pSet _ _ _ hb)⟩, hb⟩, λ⟨b, pb⟩, let ⟨a, ha⟩ := βα b in ⟨⟨a, by rwa (@quotient.sound pSet _ _ _ ha)⟩, ha⟩⟩⟩ instance : has_sep Set Set := ⟨Set.sep⟩ @[simp] theorem mem_sep {p : Set.{u} → Prop} {x y : Set.{u}} : y ∈ {y ∈ x | p y} ↔ y ∈ x ∧ p y := quotient.induction_on₂ x y (λ⟨α, A⟩ y, ⟨λ⟨⟨a, pa⟩, h⟩, ⟨⟨a, h⟩, by rw (@quotient.sound pSet _ _ _ h); exact pa⟩, λ⟨⟨a, h⟩, pa⟩, ⟨⟨a, by rw ←(@quotient.sound pSet _ _ _ h); exact pa⟩, h⟩⟩) /-- The powerset operation, the collection of subsets of a set -/ def powerset : Set → Set := resp.eval 1 ⟨powerset, λ⟨α, A⟩ ⟨β, B⟩ ⟨αβ, βα⟩, ⟨λp, ⟨{b | ∃a, p a ∧ equiv (A a) (B b)}, λ⟨a, pa⟩, let ⟨b, ab⟩ := αβ a in ⟨⟨b, a, pa, ab⟩, ab⟩, λ⟨b, a, pa, ab⟩, ⟨⟨a, pa⟩, ab⟩⟩, λq, ⟨{a | ∃b, q b ∧ equiv (A a) (B b)}, λ⟨a, b, qb, ab⟩, ⟨⟨b, qb⟩, ab⟩, λ⟨b, qb⟩, let ⟨a, ab⟩ := βα b in ⟨⟨a, b, qb, ab⟩, ab⟩⟩⟩⟩ @[simp] theorem mem_powerset {x y : Set} : y ∈ powerset x ↔ y ⊆ x := quotient.induction_on₂ x y (λ⟨α, A⟩ ⟨β, B⟩, show (⟨β, B⟩ : pSet) ∈ (pSet.powerset ⟨α, A⟩) ↔ _, by simp [mem_powerset, subset_iff]) theorem Union_lem {α β : Type u} (A : α → pSet) (B : β → pSet) (αβ : ∀a, ∃b, equiv (A a) (B b)) : ∀a, ∃b, (equiv ((Union ⟨α, A⟩).func a) ((Union ⟨β, B⟩).func b)) | ⟨a, c⟩ := let ⟨b, hb⟩ := αβ a in begin induction ea : A a with γ Γ, induction eb : B b with δ Δ, rw [ea, eb] at hb, cases hb with γδ δγ, exact let c : type (A a) := c, ⟨d, hd⟩ := γδ (by rwa ea at c) in have equiv ((A a).func c) ((B b).func (eq.rec d (eq.symm eb))), from match A a, B b, ea, eb, c, d, hd with ._, ._, rfl, rfl, x, y, hd := hd end, ⟨⟨b, eq.rec d (eq.symm eb)⟩, this⟩ end /-- The union operator, the collection of elements of elements of a set -/ def Union : Set → Set := resp.eval 1 ⟨pSet.Union, λ⟨α, A⟩ ⟨β, B⟩ ⟨αβ, βα⟩, ⟨Union_lem A B αβ, λa, exists.elim (Union_lem B A (λb, exists.elim (βα b) (λc hc, ⟨c, equiv.symm hc⟩)) a) (λb hb, ⟨b, equiv.symm hb⟩)⟩⟩ notation `⋃` := Union @[simp] theorem mem_Union {x y : Set.{u}} : y ∈ Union x ↔ ∃ z ∈ x, y ∈ z := quotient.induction_on₂ x y (λx y, iff.trans mem_Union ⟨λ⟨z, h⟩, ⟨⟦z⟧, h⟩, λ⟨z, h⟩, quotient.induction_on z (λz h, ⟨z, h⟩) h⟩) @[simp] theorem Union_singleton {x : Set.{u}} : Union {x} = x := ext $ λy, by simp; exact ⟨λ⟨z, zx, yz⟩, by subst z; exact yz, λyx, ⟨x, by simp, yx⟩⟩ theorem singleton_inj {x y : Set.{u}} (H : ({x} : Set) = {y}) : x = y := let this := congr_arg Union H in by rwa [Union_singleton, Union_singleton] at this /-- The binary union operation -/ protected def union (x y : Set.{u}) : Set.{u} := ⋃ {x, y} /-- The binary intersection operation -/ protected def inter (x y : Set.{u}) : Set.{u} := {z ∈ x | z ∈ y} /-- The set difference operation -/ protected def diff (x y : Set.{u}) : Set.{u} := {z ∈ x | z ∉ y} instance : has_union Set := ⟨Set.union⟩ instance : has_inter Set := ⟨Set.inter⟩ instance : has_sdiff Set := ⟨Set.diff⟩ @[simp] theorem mem_union {x y z : Set.{u}} : z ∈ x ∪ y ↔ z ∈ x ∨ z ∈ y := iff.trans mem_Union ⟨λ⟨w, wxy, zw⟩, match mem_pair.1 wxy with | or.inl wx := or.inl (by rwa ←wx) | or.inr wy := or.inr (by rwa ←wy) end, λzxy, match zxy with | or.inl zx := ⟨x, mem_pair.2 (or.inl rfl), zx⟩ | or.inr zy := ⟨y, mem_pair.2 (or.inr rfl), zy⟩ end⟩ @[simp] theorem mem_inter {x y z : Set.{u}} : z ∈ x ∩ y ↔ z ∈ x ∧ z ∈ y := @@mem_sep (λz:Set.{u}, z ∈ y) @[simp] theorem mem_diff {x y z : Set.{u}} : z ∈ x \ y ↔ z ∈ x ∧ z ∉ y := @@mem_sep (λz:Set.{u}, z ∉ y) theorem induction_on {p : Set → Prop} (x) (h : ∀x, (∀y ∈ x, p y) → p x) : p x := quotient.induction_on x $ λu, pSet.rec_on u $ λα A IH, h _ $ λy, show @has_mem.mem _ _ Set.has_mem y ⟦⟨α, A⟩⟧ → p y, from quotient.induction_on y (λv ⟨a, ha⟩, by rw (@quotient.sound pSet _ _ _ ha); exact IH a) theorem regularity (x : Set.{u}) (h : x ≠ ∅) : ∃ y ∈ x, x ∩ y = ∅ := classical.by_contradiction $ λne, h $ (eq_empty x).2 $ λy, induction_on y $ λz (IH : ∀w:Set.{u}, w ∈ z → w ∉ x), show z ∉ x, from λzx, ne ⟨z, zx, (eq_empty _).2 (λw wxz, let ⟨wx, wz⟩ := mem_inter.1 wxz in IH w wz wx)⟩ /-- The image of a (definable) set function -/ def image (f : Set → Set) [H : definable 1 f] : Set → Set := let r := @definable.resp 1 f _ in resp.eval 1 ⟨image r.1, λx y e, mem.ext $ λz, iff.trans (mem_image r.2) $ iff.trans (by exact ⟨λ⟨w, h1, h2⟩, ⟨w, (mem.congr_right e).1 h1, h2⟩, λ⟨w, h1, h2⟩, ⟨w, (mem.congr_right e).2 h1, h2⟩⟩) $ iff.symm (mem_image r.2)⟩ theorem image.mk : Π (f : Set.{u} → Set.{u}) [H : definable 1 f] (x) {y} (h : y ∈ x), f y ∈ @image f H x | ._ ⟨F⟩ x y := quotient.induction_on₂ x y $ λ⟨α, A⟩ y ⟨a, ya⟩, ⟨a, F.2 _ _ ya⟩ @[simp] theorem mem_image : Π {f : Set.{u} → Set.{u}} [H : definable 1 f] {x y : Set.{u}}, y ∈ @image f H x ↔ ∃z ∈ x, f z = y | ._ ⟨F⟩ x y := quotient.induction_on₂ x y $ λ⟨α, A⟩ y, ⟨λ⟨a, ya⟩, ⟨⟦A a⟧, mem.mk A a, eq.symm $ quotient.sound ya⟩, λ⟨z, hz, e⟩, e ▸ image.mk _ _ hz⟩ /-- Kuratowski ordered pair -/ def pair (x y : Set.{u}) : Set.{u} := {{x}, {x, y}} /-- A subset of pairs `{(a, b) ∈ x × y | p a b}` -/ def pair_sep (p : Set.{u} → Set.{u} → Prop) (x y : Set.{u}) : Set.{u} := {z ∈ powerset (powerset (x ∪ y)) | ∃a ∈ x, ∃b ∈ y, z = pair a b ∧ p a b} @[simp] theorem mem_pair_sep {p} {x y z : Set.{u}} : z ∈ pair_sep p x y ↔ ∃a ∈ x, ∃b ∈ y, z = pair a b ∧ p a b := by refine iff.trans mem_sep ⟨and.right, λe, ⟨_, e⟩⟩; exact let ⟨a, ax, b, bY, ze, pab⟩ := e in by rw ze; exact mem_powerset.2 (λu uz, mem_powerset.2 $ (mem_pair.1 uz).elim (λua, by rw ua; exact λv vu, by rw mem_singleton.1 vu; exact mem_union.2 (or.inl ax)) (λuab, by rw uab; exact λv vu, (mem_pair.1 vu).elim (λva, by rw va; exact mem_union.2 (or.inl ax)) (λvb, by rw vb; exact mem_union.2 (or.inr bY)))) theorem pair_inj {x y x' y' : Set.{u}} (H : pair x y = pair x' y') : x = x' ∧ y = y' := begin have ae := ext_iff.2 H, simp [pair] at ae, have : x = x', { cases (ae {x}).1 (by simp) with h h, { exact singleton_inj h }, { have m : x' ∈ ({x} : Set), { rw h, simp }, simp at m, simp [*] } }, subst x', have he : y = x → y = y', { intro yx, subst y, cases (ae {x, y'}).2 (by simp) with xy'x xy'xx, { have y'x : y' ∈ ({x} : Set) := by rw ← xy'x; simp, simp at y'x, simp [*] }, { have yxx := (ext_iff.2 xy'xx y').1 (by simp), simp at yxx, subst y' } }, have xyxy' := (ae {x, y}).1 (by simp), cases xyxy' with xyx xyy', { have yx := (ext_iff.2 xyx y).1 (by simp), simp at yx, simp [he yx] }, { have yxy' := (ext_iff.2 xyy' y).1 (by simp), simp at yxy', cases yxy' with yx yy', { simp [he yx] }, { simp [yy'] } } end /-- The cartesian product, `{(a, b) | a ∈ x, b ∈ y}` -/ def prod : Set.{u} → Set.{u} → Set.{u} := pair_sep (λa b, true) @[simp] theorem mem_prod {x y z : Set.{u}} : z ∈ prod x y ↔ ∃a ∈ x, ∃b ∈ y, z = pair a b := by simp [prod] @[simp] theorem pair_mem_prod {x y a b : Set.{u}} : pair a b ∈ prod x y ↔ a ∈ x ∧ b ∈ y := ⟨λh, let ⟨a', a'x, b', b'y, e⟩ := mem_prod.1 h in match a', b', pair_inj e, a'x, b'y with ._, ._, ⟨rfl, rfl⟩, ax, bY := ⟨ax, bY⟩ end, λ⟨ax, bY⟩, by simp; exact ⟨a, ax, b, bY, rfl⟩⟩ /-- `is_func x y f` is the assertion `f : x → y` where `f` is a ZFC function (a set of ordered pairs) -/ def is_func (x y f : Set.{u}) : Prop := f ⊆ prod x y ∧ ∀z:Set.{u}, z ∈ x → ∃! w, pair z w ∈ f /-- `funs x y` is `y ^ x`, the set of all set functions `x → y` -/ def funs (x y : Set.{u}) : Set.{u} := {f ∈ powerset (prod x y) | is_func x y f} @[simp] theorem mem_funs {x y f : Set.{u}} : f ∈ funs x y ↔ is_func x y f := by simp [funs, is_func] -- TODO(Mario): Prove this computably noncomputable instance map_definable_aux (f : Set → Set) [H : definable 1 f] : definable 1 (λy, pair y (f y)) := @classical.all_definable 1 _ /-- Graph of a function: `map f x` is the ZFC function which maps `a ∈ x` to `f a` -/ noncomputable def map (f : Set → Set) [H : definable 1 f] : Set → Set := image (λy, pair y (f y)) @[simp] theorem mem_map {f : Set → Set} [H : definable 1 f] {x y : Set} : y ∈ map f x ↔ ∃z ∈ x, pair z (f z) = y := mem_image theorem map_unique {f : Set.{u} → Set.{u}} [H : definable 1 f] {x z : Set.{u}} (zx : z ∈ x) : ∃! w, pair z w ∈ map f x := ⟨f z, image.mk _ _ zx, λy yx, let ⟨w, wx, we⟩ := mem_image.1 yx, ⟨wz, fy⟩ := pair_inj we in by rw[←fy, wz]⟩ @[simp] theorem map_is_func {f : Set → Set} [H : definable 1 f] {x y : Set} : is_func x y (map f x) ↔ ∀z ∈ x, f z ∈ y := ⟨λ⟨ss, h⟩ z zx, let ⟨t, t1, t2⟩ := h z zx in by rw (t2 (f z) (image.mk _ _ zx)); exact (pair_mem_prod.1 (ss t1)).right, λh, ⟨λy yx, let ⟨z, zx, ze⟩ := mem_image.1 yx in by rw ←ze; exact pair_mem_prod.2 ⟨zx, h z zx⟩, λz, map_unique⟩⟩ end Set def Class := set Set namespace Class instance : has_subset Class := ⟨set.subset⟩ instance : has_sep Set Class := ⟨set.sep⟩ instance : has_emptyc Class := ⟨λ a, false⟩ instance : inhabited Class := ⟨∅⟩ instance : has_insert Set Class := ⟨set.insert⟩ instance : has_union Class := ⟨set.union⟩ instance : has_inter Class := ⟨set.inter⟩ instance : has_neg Class := ⟨set.compl⟩ instance : has_sdiff Class := ⟨set.diff⟩ /-- Coerce a set into a class -/ def of_Set (x : Set.{u}) : Class.{u} := {y | y ∈ x} instance : has_coe Set Class := ⟨of_Set⟩ /-- The universal class -/ def univ : Class := set.univ /-- Assert that `A` is a set satisfying `p` -/ def to_Set (p : Set.{u} → Prop) (A : Class.{u}) : Prop := ∃x, ↑x = A ∧ p x /-- `A ∈ B` if `A` is a set which is a member of `B` -/ protected def mem (A B : Class.{u}) : Prop := to_Set.{u} B A instance : has_mem Class Class := ⟨Class.mem⟩ theorem mem_univ {A : Class.{u}} : A ∈ univ.{u} ↔ ∃ x : Set.{u}, ↑x = A := exists_congr $ λx, and_true _ /-- Convert a conglomerate (a collection of classes) into a class -/ def Cong_to_Class (x : set Class.{u}) : Class.{u} := {y | ↑y ∈ x} /-- Convert a class into a conglomerate (a collection of classes) -/ def Class_to_Cong (x : Class.{u}) : set Class.{u} := {y | y ∈ x} /-- The power class of a class is the class of all subclasses that are sets -/ def powerset (x : Class) : Class := Cong_to_Class (set.powerset x) /-- The union of a class is the class of all members of sets in the class -/ def Union (x : Class) : Class := set.sUnion (Class_to_Cong x) notation `⋃` := Union theorem of_Set.inj {x y : Set.{u}} (h : (x : Class.{u}) = y) : x = y := Set.ext $ λz, by change (x : Class.{u}) z ↔ (y : Class.{u}) z; simp [*] @[simp] theorem to_Set_of_Set (p : Set.{u} → Prop) (x : Set.{u}) : to_Set p x ↔ p x := ⟨λ⟨y, yx, py⟩, by rwa of_Set.inj yx at py, λpx, ⟨x, rfl, px⟩⟩ @[simp] theorem mem_hom_left (x : Set.{u}) (A : Class.{u}) : (x : Class.{u}) ∈ A ↔ A x := to_Set_of_Set _ _ @[simp] theorem mem_hom_right (x y : Set.{u}) : (y : Class.{u}) x ↔ x ∈ y := iff.rfl @[simp] theorem subset_hom (x y : Set.{u}) : (x : Class.{u}) ⊆ y ↔ x ⊆ y := iff.rfl @[simp] theorem sep_hom (p : Set.{u} → Prop) (x : Set.{u}) : (↑{y ∈ x | p y} : Class.{u}) = {y ∈ x | p y} := set.ext $ λy, Set.mem_sep @[simp] theorem empty_hom : ↑(∅ : Set.{u}) = (∅ : Class.{u}) := set.ext $ λy, show _ ↔ false, by simp; exact Set.mem_empty y @[simp] theorem insert_hom (x y : Set.{u}) : (@insert Set.{u} Class.{u} _ x y) = ↑(insert x y) := set.ext $ λz, iff.symm Set.mem_insert @[simp] theorem union_hom (x y : Set.{u}) : (x : Class.{u}) ∪ y = (x ∪ y : Set.{u}) := set.ext $ λz, iff.symm Set.mem_union @[simp] theorem inter_hom (x y : Set.{u}) : (x : Class.{u}) ∩ y = (x ∩ y : Set.{u}) := set.ext $ λz, iff.symm Set.mem_inter @[simp] theorem diff_hom (x y : Set.{u}) : (x : Class.{u}) \ y = (x \ y : Set.{u}) := set.ext $ λz, iff.symm Set.mem_diff @[simp] theorem powerset_hom (x : Set.{u}) : powerset.{u} x = Set.powerset x := set.ext $ λz, iff.symm Set.mem_powerset @[simp] theorem Union_hom (x : Set.{u}) : Union.{u} x = Set.Union x := set.ext $ λz, by refine iff.trans _ (iff.symm Set.mem_Union); exact ⟨λ⟨._, ⟨a, rfl, ax⟩, za⟩, ⟨a, ax, za⟩, λ⟨a, ax, za⟩, ⟨_, ⟨a, rfl, ax⟩, za⟩⟩ /-- The definite description operator, which is {x} if `{a | p a} = {x}` and ∅ otherwise -/ def iota (p : Set → Prop) : Class := Union {x | ∀y, p y ↔ y = x} theorem iota_val (p : Set → Prop) (x : Set) (H : ∀y, p y ↔ y = x) : iota p = ↑x := set.ext $ λy, ⟨λ⟨._, ⟨x', rfl, h⟩, yx'⟩, by rwa ←((H x').1 $ (h x').2 rfl), λyx, ⟨_, ⟨x, rfl, H⟩, yx⟩⟩ /-- Unlike the other set constructors, the `iota` definite descriptor is a set for any set input, but not constructively so, so there is no associated `(Set → Prop) → Set` function. -/ theorem iota_ex (p) : iota.{u} p ∈ univ.{u} := mem_univ.2 $ or.elim (classical.em $ ∃x, ∀y, p y ↔ y = x) (λ⟨x, h⟩, ⟨x, eq.symm $ iota_val p x h⟩) (λhn, ⟨∅, by simp; exact set.ext (λz, ⟨false.rec _, λ⟨._, ⟨x, rfl, H⟩, zA⟩, hn ⟨x, H⟩⟩)⟩) /-- Function value -/ def fval (F A : Class.{u}) : Class.{u} := iota (λy, to_Set (λx, F (Set.pair x y)) A) infixl `′`:100 := fval theorem fval_ex (F A : Class.{u}) : F ′ A ∈ univ.{u} := iota_ex _ end Class namespace Set @[simp] theorem map_fval {f : Set.{u} → Set.{u}} [H : pSet.definable 1 f] {x y : Set.{u}} (h : y ∈ x) : (Set.map f x ′ y : Class.{u}) = f y := Class.iota_val _ _ (λz, by simp; exact ⟨λ⟨w, wz, pr⟩, let ⟨wy, fw⟩ := Set.pair_inj pr in by rw[←fw, wy], λe, by cases e; exact ⟨_, h, rfl⟩⟩) variables (x : Set.{u}) (h : ∅ ∉ x) /-- A choice function on the set of nonempty sets `x` -/ noncomputable def choice : Set := @map (λy, classical.epsilon (λz, z ∈ y)) (classical.all_definable _) x include h theorem choice_mem_aux (y : Set.{u}) (yx : y ∈ x) : classical.epsilon (λz:Set.{u}, z ∈ y) ∈ y := @classical.epsilon_spec _ (λz:Set.{u}, z ∈ y) $ classical.by_contradiction $ λn, h $ by rwa ←((eq_empty y).2 $ λz zx, n ⟨z, zx⟩) theorem choice_is_func : is_func x (Union x) (choice x) := (@map_is_func _ (classical.all_definable _) _ _).2 $ λy yx, by simp; exact ⟨y, yx, choice_mem_aux x h y yx⟩ theorem choice_mem (y : Set.{u}) (yx : y ∈ x) : (choice x ′ y : Class.{u}) ∈ (y : Class.{u}) := by delta choice; rw map_fval yx; simp [choice_mem_aux x h y yx] end Set
19eeb0805bbe5bd95cd83d4b431efcbcfe98bd99
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/436.lean
35cf79c474f94330002f4272772023d855c632c4
[ "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
390
lean
section universe u variable (A : Type u) class abbrev AddAbbrev := Add A end section universe v variable {A : Sort v} class Bar (A : Sort u) (f : A -> Prop) := (bar : (a : A) -> f a) class abbrev BarAbbrev (f : A -> Prop) := Bar A f end section universe u class Foo (A : Sort u) (f : A -> Prop) := (foo : (a : A) -> f a) class abbrev FooAbbrev {A : Sort u} (f : A -> Prop) := Foo A f end
05a2705cc05d009976185d6e9097ca4c58c50f44
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/data/real/hyperreal.lean
453bc2f1ac4521e2d51f42e9a17cf50b375e635b
[ "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
36,957
lean
/- Copyright (c) 2019 Abhimanyu Pallavi Sudhir. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Abhimanyu Pallavi Sudhir -/ import order.filter.filter_product import analysis.specific_limits /-! # Construction of the hyperreal numbers as an ultraproduct of real sequences. -/ open filter filter.germ open_locale topological_space classical /-- Hyperreal numbers on the ultrafilter extending the cofinite filter -/ @[derive [linear_ordered_field, inhabited]] def hyperreal : Type := germ (hyperfilter ℕ : filter ℕ) ℝ namespace hyperreal notation `ℝ*` := hyperreal noncomputable instance : has_coe_t ℝ ℝ* := ⟨λ x, (↑x : germ _ _)⟩ @[simp, norm_cast] lemma coe_eq_coe {x y : ℝ} : (x : ℝ*) = y ↔ x = y := germ.const_inj @[simp, norm_cast] lemma coe_eq_zero {x : ℝ} : (x : ℝ*) = 0 ↔ x = 0 := coe_eq_coe @[simp, norm_cast] lemma coe_eq_one {x : ℝ} : (x : ℝ*) = 1 ↔ x = 1 := coe_eq_coe @[simp, norm_cast] lemma coe_one : ↑(1 : ℝ) = (1 : ℝ*) := rfl @[simp, norm_cast] lemma coe_zero : ↑(0 : ℝ) = (0 : ℝ*) := rfl @[simp, norm_cast] lemma coe_inv (x : ℝ) : ↑(x⁻¹) = (x⁻¹ : ℝ*) := rfl @[simp, norm_cast] lemma coe_neg (x : ℝ) : ↑(-x) = (-x : ℝ*) := rfl @[simp, norm_cast] lemma coe_add (x y : ℝ) : ↑(x + y) = (x + y : ℝ*) := rfl @[simp, norm_cast] lemma coe_bit0 (x : ℝ) : ↑(bit0 x) = (bit0 x : ℝ*) := rfl @[simp, norm_cast] lemma coe_bit1 (x : ℝ) : ↑(bit1 x) = (bit1 x : ℝ*) := rfl @[simp, norm_cast] lemma coe_mul (x y : ℝ) : ↑(x * y) = (x * y : ℝ*) := rfl @[simp, norm_cast] lemma coe_div (x y : ℝ) : ↑(x / y) = (x / y : ℝ*) := rfl @[simp, norm_cast] lemma coe_sub (x y : ℝ) : ↑(x - y) = (x - y : ℝ*) := rfl @[simp, norm_cast] lemma coe_lt_coe {x y : ℝ} : (x : ℝ*) < y ↔ x < y := germ.const_lt @[simp, norm_cast] lemma coe_pos {x : ℝ} : 0 < (x : ℝ*) ↔ 0 < x := coe_lt_coe @[simp, norm_cast] lemma coe_le_coe {x y : ℝ} : (x : ℝ*) ≤ y ↔ x ≤ y := germ.const_le_iff @[simp, norm_cast] lemma coe_abs (x : ℝ) : ((abs x : ℝ) : ℝ*) = abs x := germ.const_abs _ @[simp, norm_cast] lemma coe_max (x y : ℝ) : ((max x y : ℝ) : ℝ*) = max x y := germ.const_max _ _ @[simp, norm_cast] lemma coe_min (x y : ℝ) : ((min x y : ℝ) : ℝ*) = min x y := germ.const_min _ _ /-- Construct a hyperreal number from a sequence of real numbers. -/ noncomputable def of_seq (f : ℕ → ℝ) : ℝ* := (↑f : germ (hyperfilter ℕ : filter ℕ) ℝ) /-- A sample infinitesimal hyperreal-/ noncomputable def epsilon : ℝ* := of_seq $ λ n, n⁻¹ /-- A sample infinite hyperreal-/ noncomputable def omega : ℝ* := of_seq coe localized "notation `ε` := hyperreal.epsilon" in hyperreal localized "notation `ω` := hyperreal.omega" in hyperreal lemma epsilon_eq_inv_omega : ε = ω⁻¹ := rfl lemma inv_epsilon_eq_omega : ε⁻¹ = ω := @inv_inv' _ _ ω lemma epsilon_pos : 0 < ε := suffices ∀ᶠ i in hyperfilter ℕ, (0 : ℝ) < (i : ℕ)⁻¹, by rwa lt_def, have h0' : {n : ℕ | ¬ 0 < n} = {0} := by simp only [not_lt, (set.set_of_eq_eq_singleton).symm]; ext; exact nat.le_zero_iff, begin simp only [inv_pos, nat.cast_pos], exact mem_hyperfilter_of_finite_compl (by convert set.finite_singleton _), end lemma epsilon_ne_zero : ε ≠ 0 := ne_of_gt epsilon_pos lemma omega_pos : 0 < ω := by rw ←inv_epsilon_eq_omega; exact inv_pos.2 epsilon_pos lemma omega_ne_zero : ω ≠ 0 := ne_of_gt omega_pos theorem epsilon_mul_omega : ε * ω = 1 := @inv_mul_cancel _ _ ω omega_ne_zero lemma lt_of_tendsto_zero_of_pos {f : ℕ → ℝ} (hf : tendsto f at_top (𝓝 0)) : ∀ {r : ℝ}, 0 < r → of_seq f < (r : ℝ*) := begin simp only [metric.tendsto_at_top, dist_zero_right, norm, lt_def] at hf ⊢, intros r hr, cases hf r hr with N hf', have hs : {i : ℕ | f i < r}ᶜ ⊆ {i : ℕ | i ≤ N} := λ i hi1, le_of_lt (by simp only [lt_iff_not_ge]; exact λ hi2, hi1 (lt_of_le_of_lt (le_abs_self _) (hf' i hi2)) : i < N), exact mem_hyperfilter_of_finite_compl ((set.finite_le_nat N).subset hs) end lemma neg_lt_of_tendsto_zero_of_pos {f : ℕ → ℝ} (hf : tendsto f at_top (𝓝 0)) : ∀ {r : ℝ}, 0 < r → (-r : ℝ*) < of_seq f := λ r hr, have hg : _ := hf.neg, neg_lt_of_neg_lt (by rw [neg_zero] at hg; exact lt_of_tendsto_zero_of_pos hg hr) lemma gt_of_tendsto_zero_of_neg {f : ℕ → ℝ} (hf : tendsto f at_top (𝓝 0)) : ∀ {r : ℝ}, r < 0 → (r : ℝ*) < of_seq f := λ r hr, by rw [←neg_neg r, coe_neg]; exact neg_lt_of_tendsto_zero_of_pos hf (neg_pos.mpr hr) lemma epsilon_lt_pos (x : ℝ) : 0 < x → ε < x := lt_of_tendsto_zero_of_pos tendsto_inverse_at_top_nhds_0_nat /-- Standard part predicate -/ def is_st (x : ℝ*) (r : ℝ) := ∀ δ : ℝ, 0 < δ → (r - δ : ℝ*) < x ∧ x < r + δ /-- Standard part function: like a "round" to ℝ instead of ℤ -/ noncomputable def st : ℝ* → ℝ := λ x, if h : ∃ r, is_st x r then classical.some h else 0 /-- A hyperreal number is infinitesimal if its standard part is 0 -/ def infinitesimal (x : ℝ*) := is_st x 0 /-- A hyperreal number is positive infinite if it is larger than all real numbers -/ def infinite_pos (x : ℝ*) := ∀ r : ℝ, ↑r < x /-- A hyperreal number is negative infinite if it is smaller than all real numbers -/ def infinite_neg (x : ℝ*) := ∀ r : ℝ, x < r /-- A hyperreal number is infinite if it is infinite positive or infinite negative -/ def infinite (x : ℝ*) := infinite_pos x ∨ infinite_neg x /-! ### Some facts about `st` -/ private lemma is_st_unique' (x : ℝ*) (r s : ℝ) (hr : is_st x r) (hs : is_st x s) (hrs : r < s) : false := have hrs' : _ := half_pos $ sub_pos_of_lt hrs, have hr' : _ := (hr _ hrs').2, have hs' : _ := (hs _ hrs').1, have h : s - ((s - r) / 2) = r + (s - r) / 2 := by linarith, begin norm_cast at *, rw h at hs', exact not_lt_of_lt hs' hr' end theorem is_st_unique {x : ℝ*} {r s : ℝ} (hr : is_st x r) (hs : is_st x s) : r = s := begin rcases lt_trichotomy r s with h | h | h, { exact false.elim (is_st_unique' x r s hr hs h) }, { exact h }, { exact false.elim (is_st_unique' x s r hs hr h) } end theorem not_infinite_of_exists_st {x : ℝ*} : (∃ r : ℝ, is_st x r) → ¬ infinite x := λ he hi, Exists.dcases_on he $ λ r hr, hi.elim (λ hip, not_lt_of_lt (hr 2 zero_lt_two).2 (hip $ r + 2)) (λ hin, not_lt_of_lt (hr 2 zero_lt_two).1 (hin $ r - 2)) theorem is_st_Sup {x : ℝ*} (hni : ¬ infinite x) : is_st x (Sup {y : ℝ | (y : ℝ*) < x}) := let S : set ℝ := {y : ℝ | (y : ℝ*) < x} in let R : _ := Sup S in have hnile : _ := not_forall.mp (not_or_distrib.mp hni).1, have hnige : _ := not_forall.mp (not_or_distrib.mp hni).2, Exists.dcases_on hnile $ Exists.dcases_on hnige $ λ r₁ hr₁ r₂ hr₂, have HR₁ : ∃ y : ℝ, y ∈ S := ⟨r₁ - 1, lt_of_lt_of_le (coe_lt_coe.2 $ sub_one_lt _) (not_lt.mp hr₁) ⟩, have HR₂ : ∃ z : ℝ, ∀ y ∈ S, y ≤ z := ⟨ r₂, λ y hy, le_of_lt (coe_lt_coe.1 (lt_of_lt_of_le hy (not_lt.mp hr₂))) ⟩, λ δ hδ, ⟨ lt_of_not_ge' $ λ c, have hc : ∀ y ∈ S, y ≤ R - δ := λ y hy, coe_le_coe.1 $ le_of_lt $ lt_of_lt_of_le hy c, not_lt_of_le ((real.Sup_le _ HR₁ HR₂).mpr hc) $ sub_lt_self R hδ, lt_of_not_ge' $ λ c, have hc : ↑(R + δ / 2) < x := lt_of_lt_of_le (add_lt_add_left (coe_lt_coe.2 (half_lt_self hδ)) R) c, not_lt_of_le (real.le_Sup _ HR₂ hc) $ (lt_add_iff_pos_right _).mpr $ half_pos hδ⟩ theorem exists_st_of_not_infinite {x : ℝ*} (hni : ¬ infinite x) : ∃ r : ℝ, is_st x r := ⟨Sup {y : ℝ | (y : ℝ*) < x}, is_st_Sup hni⟩ theorem st_eq_Sup {x : ℝ*} : st x = Sup {y : ℝ | (y : ℝ*) < x} := begin unfold st, split_ifs, { exact is_st_unique (classical.some_spec h) (is_st_Sup (not_infinite_of_exists_st h)) }, { cases not_imp_comm.mp exists_st_of_not_infinite h with H H, { rw (set.ext (λ i, ⟨λ hi, set.mem_univ i, λ hi, H i⟩) : {y : ℝ | (y : ℝ*) < x} = set.univ), exact (real.Sup_univ).symm }, { rw (set.ext (λ i, ⟨λ hi, false.elim (not_lt_of_lt (H i) hi), λ hi, false.elim (set.not_mem_empty i hi)⟩) : {y : ℝ | (y : ℝ*) < x} = ∅), exact (real.Sup_empty).symm } } end theorem exists_st_iff_not_infinite {x : ℝ*} : (∃ r : ℝ, is_st x r) ↔ ¬ infinite x := ⟨ not_infinite_of_exists_st, exists_st_of_not_infinite ⟩ theorem infinite_iff_not_exists_st {x : ℝ*} : infinite x ↔ ¬ ∃ r : ℝ, is_st x r := iff_not_comm.mp exists_st_iff_not_infinite theorem st_infinite {x : ℝ*} (hi : infinite x) : st x = 0 := begin unfold st, split_ifs, { exact false.elim ((infinite_iff_not_exists_st.mp hi) h) }, { refl } end lemma st_of_is_st {x : ℝ*} {r : ℝ} (hxr : is_st x r) : st x = r := begin unfold st, split_ifs, { exact is_st_unique (classical.some_spec h) hxr }, { exact false.elim (h ⟨r, hxr⟩) } end lemma is_st_st_of_is_st {x : ℝ*} {r : ℝ} (hxr : is_st x r) : is_st x (st x) := by rwa [st_of_is_st hxr] lemma is_st_st_of_exists_st {x : ℝ*} (hx : ∃ r : ℝ, is_st x r) : is_st x (st x) := Exists.dcases_on hx (λ r, is_st_st_of_is_st) lemma is_st_st {x : ℝ*} (hx : st x ≠ 0) : is_st x (st x) := begin unfold st, split_ifs, { exact classical.some_spec h }, { exact false.elim (hx (by unfold st; split_ifs; refl)) } end lemma is_st_st' {x : ℝ*} (hx : ¬ infinite x) : is_st x (st x) := is_st_st_of_exists_st $ exists_st_of_not_infinite hx lemma is_st_refl_real (r : ℝ) : is_st r r := λ δ hδ, ⟨ sub_lt_self _ (coe_lt_coe.2 hδ), (lt_add_of_pos_right _ (coe_lt_coe.2 hδ)) ⟩ lemma st_id_real (r : ℝ) : st r = r := st_of_is_st (is_st_refl_real r) lemma eq_of_is_st_real {r s : ℝ} : is_st r s → r = s := is_st_unique (is_st_refl_real r) lemma is_st_real_iff_eq {r s : ℝ} : is_st r s ↔ r = s := ⟨eq_of_is_st_real, λ hrs, by rw [hrs]; exact is_st_refl_real s⟩ lemma is_st_symm_real {r s : ℝ} : is_st r s ↔ is_st s r := by rw [is_st_real_iff_eq, is_st_real_iff_eq, eq_comm] lemma is_st_trans_real {r s t : ℝ} : is_st r s → is_st s t → is_st r t := by rw [is_st_real_iff_eq, is_st_real_iff_eq, is_st_real_iff_eq]; exact eq.trans lemma is_st_inj_real {r₁ r₂ s : ℝ} (h1 : is_st r₁ s) (h2 : is_st r₂ s) : r₁ = r₂ := eq.trans (eq_of_is_st_real h1) (eq_of_is_st_real h2).symm lemma is_st_iff_abs_sub_lt_delta {x : ℝ*} {r : ℝ} : is_st x r ↔ ∀ (δ : ℝ), 0 < δ → abs (x - r) < δ := by simp only [abs_sub_lt_iff, sub_lt_iff_lt_add, is_st, and_comm, add_comm] lemma is_st_add {x y : ℝ*} {r s : ℝ} : is_st x r → is_st y s → is_st (x + y) (r + s) := λ hxr hys d hd, have hxr' : _ := hxr (d / 2) (half_pos hd), have hys' : _ := hys (d / 2) (half_pos hd), ⟨by convert add_lt_add hxr'.1 hys'.1 using 1; norm_cast; linarith, by convert add_lt_add hxr'.2 hys'.2 using 1; norm_cast; linarith⟩ lemma is_st_neg {x : ℝ*} {r : ℝ} (hxr : is_st x r) : is_st (-x) (-r) := λ d hd, show -(r : ℝ*) - d < -x ∧ -x < -r + d, by cases (hxr d hd); split; linarith lemma is_st_sub {x y : ℝ*} {r s : ℝ} : is_st x r → is_st y s → is_st (x - y) (r - s) := λ hxr hys, by rw [sub_eq_add_neg, sub_eq_add_neg]; exact is_st_add hxr (is_st_neg hys) /- (st x < st y) → (x < y) → (x ≤ y) → (st x ≤ st y) -/ lemma lt_of_is_st_lt {x y : ℝ*} {r s : ℝ} (hxr : is_st x r) (hys : is_st y s) : r < s → x < y := λ hrs, have hrs' : 0 < (s - r) / 2 := half_pos (sub_pos.mpr hrs), have hxr' : _ := (hxr _ hrs').2, have hys' : _ := (hys _ hrs').1, have H1 : r + ((s - r) / 2) = (r + s) / 2 := by linarith, have H2 : s - ((s - r) / 2) = (r + s) / 2 := by linarith, begin norm_cast at *, rw H1 at hxr', rw H2 at hys', exact lt_trans hxr' hys' end lemma is_st_le_of_le {x y : ℝ*} {r s : ℝ} (hrx : is_st x r) (hsy : is_st y s) : x ≤ y → r ≤ s := by rw [←not_lt, ←not_lt, not_imp_not]; exact lt_of_is_st_lt hsy hrx lemma st_le_of_le {x y : ℝ*} (hix : ¬ infinite x) (hiy : ¬ infinite y) : x ≤ y → st x ≤ st y := have hx' : _ := is_st_st' hix, have hy' : _ := is_st_st' hiy, is_st_le_of_le hx' hy' lemma lt_of_st_lt {x y : ℝ*} (hix : ¬ infinite x) (hiy : ¬ infinite y) : st x < st y → x < y := have hx' : _ := is_st_st' hix, have hy' : _ := is_st_st' hiy, lt_of_is_st_lt hx' hy' /-! ### Basic lemmas about infinite -/ lemma infinite_pos_def {x : ℝ*} : infinite_pos x ↔ ∀ r : ℝ, ↑r < x := by rw iff_eq_eq; refl lemma infinite_neg_def {x : ℝ*} : infinite_neg x ↔ ∀ r : ℝ, x < r := by rw iff_eq_eq; refl lemma ne_zero_of_infinite {x : ℝ*} : infinite x → x ≠ 0 := λ hI h0, or.cases_on hI (λ hip, lt_irrefl (0 : ℝ*) ((by rwa ←h0 : infinite_pos 0) 0)) (λ hin, lt_irrefl (0 : ℝ*) ((by rwa ←h0 : infinite_neg 0) 0)) lemma not_infinite_zero : ¬ infinite 0 := λ hI, ne_zero_of_infinite hI rfl lemma pos_of_infinite_pos {x : ℝ*} : infinite_pos x → 0 < x := λ hip, hip 0 lemma neg_of_infinite_neg {x : ℝ*} : infinite_neg x → x < 0 := λ hin, hin 0 lemma not_infinite_pos_of_infinite_neg {x : ℝ*} : infinite_neg x → ¬ infinite_pos x := λ hn hp, not_lt_of_lt (hn 1) (hp 1) lemma not_infinite_neg_of_infinite_pos {x : ℝ*} : infinite_pos x → ¬ infinite_neg x := imp_not_comm.mp not_infinite_pos_of_infinite_neg lemma infinite_neg_neg_of_infinite_pos {x : ℝ*} : infinite_pos x → infinite_neg (-x) := λ hp r, neg_lt.mp (hp (-r)) lemma infinite_pos_neg_of_infinite_neg {x : ℝ*} : infinite_neg x → infinite_pos (-x) := λ hp r, lt_neg.mp (hp (-r)) lemma infinite_pos_iff_infinite_neg_neg {x : ℝ*} : infinite_pos x ↔ infinite_neg (-x) := ⟨ infinite_neg_neg_of_infinite_pos, λ hin, neg_neg x ▸ infinite_pos_neg_of_infinite_neg hin ⟩ lemma infinite_neg_iff_infinite_pos_neg {x : ℝ*} : infinite_neg x ↔ infinite_pos (-x) := ⟨ infinite_pos_neg_of_infinite_neg, λ hin, neg_neg x ▸ infinite_neg_neg_of_infinite_pos hin ⟩ lemma infinite_iff_infinite_neg {x : ℝ*} : infinite x ↔ infinite (-x) := ⟨ λ hi, or.cases_on hi (λ hip, or.inr (infinite_neg_neg_of_infinite_pos hip)) (λ hin, or.inl (infinite_pos_neg_of_infinite_neg hin)), λ hi, or.cases_on hi (λ hipn, or.inr (infinite_neg_iff_infinite_pos_neg.mpr hipn)) (λ hinp, or.inl (infinite_pos_iff_infinite_neg_neg.mpr hinp))⟩ lemma not_infinite_of_infinitesimal {x : ℝ*} : infinitesimal x → ¬ infinite x := λ hi hI, have hi' : _ := (hi 2 zero_lt_two), or.dcases_on hI (λ hip, have hip' : _ := hip 2, not_lt_of_lt hip' (by convert hi'.2; exact (zero_add 2).symm)) (λ hin, have hin' : _ := hin (-2), not_lt_of_lt hin' (by convert hi'.1; exact (zero_sub 2).symm)) lemma not_infinitesimal_of_infinite {x : ℝ*} : infinite x → ¬ infinitesimal x := imp_not_comm.mp not_infinite_of_infinitesimal lemma not_infinitesimal_of_infinite_pos {x : ℝ*} : infinite_pos x → ¬ infinitesimal x := λ hp, not_infinitesimal_of_infinite (or.inl hp) lemma not_infinitesimal_of_infinite_neg {x : ℝ*} : infinite_neg x → ¬ infinitesimal x := λ hn, not_infinitesimal_of_infinite (or.inr hn) lemma infinite_pos_iff_infinite_and_pos {x : ℝ*} : infinite_pos x ↔ (infinite x ∧ 0 < x) := ⟨ λ hip, ⟨or.inl hip, hip 0⟩, λ ⟨hi, hp⟩, hi.cases_on (λ hip, hip) (λ hin, false.elim (not_lt_of_lt hp (hin 0))) ⟩ lemma infinite_neg_iff_infinite_and_neg {x : ℝ*} : infinite_neg x ↔ (infinite x ∧ x < 0) := ⟨ λ hip, ⟨or.inr hip, hip 0⟩, λ ⟨hi, hp⟩, hi.cases_on (λ hin, false.elim (not_lt_of_lt hp (hin 0))) (λ hip, hip) ⟩ lemma infinite_pos_iff_infinite_of_pos {x : ℝ*} (hp : 0 < x) : infinite_pos x ↔ infinite x := by rw [infinite_pos_iff_infinite_and_pos]; exact ⟨λ hI, hI.1, λ hI, ⟨hI, hp⟩⟩ lemma infinite_pos_iff_infinite_of_nonneg {x : ℝ*} (hp : 0 ≤ x) : infinite_pos x ↔ infinite x := or.cases_on (lt_or_eq_of_le hp) (infinite_pos_iff_infinite_of_pos) (λ h, by rw h.symm; exact ⟨λ hIP, false.elim (not_infinite_zero (or.inl hIP)), λ hI, false.elim (not_infinite_zero hI)⟩) lemma infinite_neg_iff_infinite_of_neg {x : ℝ*} (hn : x < 0) : infinite_neg x ↔ infinite x := by rw [infinite_neg_iff_infinite_and_neg]; exact ⟨λ hI, hI.1, λ hI, ⟨hI, hn⟩⟩ lemma infinite_pos_abs_iff_infinite_abs {x : ℝ*} : infinite_pos (abs x) ↔ infinite (abs x) := infinite_pos_iff_infinite_of_nonneg (abs_nonneg _) lemma infinite_iff_infinite_pos_abs {x : ℝ*} : infinite x ↔ infinite_pos (abs x) := ⟨ λ hi d, or.cases_on hi (λ hip, by rw [abs_of_pos (hip 0)]; exact hip d) (λ hin, by rw [abs_of_neg (hin 0)]; exact lt_neg.mp (hin (-d))), λ hipa, by { rcases (lt_trichotomy x 0) with h | h | h, { exact or.inr (infinite_neg_iff_infinite_pos_neg.mpr (by rwa abs_of_neg h at hipa)) }, { exact false.elim (ne_zero_of_infinite (or.inl (by rw [h]; rwa [h, abs_zero] at hipa)) h) }, { exact or.inl (by rwa abs_of_pos h at hipa) } } ⟩ lemma infinite_iff_infinite_abs {x : ℝ*} : infinite x ↔ infinite (abs x) := by rw [←infinite_pos_iff_infinite_of_nonneg (abs_nonneg _), infinite_iff_infinite_pos_abs] lemma infinite_iff_abs_lt_abs {x : ℝ*} : infinite x ↔ ∀ r : ℝ, (abs r : ℝ*) < abs x := ⟨ λ hI r, (coe_abs r) ▸ infinite_iff_infinite_pos_abs.mp hI (abs r), λ hR, or.cases_on (max_choice x (-x)) (λ h, or.inl $ λ r, lt_of_le_of_lt (le_abs_self _) (h ▸ (hR r))) (λ h, or.inr $ λ r, neg_lt_neg_iff.mp $ lt_of_le_of_lt (neg_le_abs_self _) (h ▸ (hR r)))⟩ lemma infinite_pos_add_not_infinite_neg {x y : ℝ*} : infinite_pos x → ¬ infinite_neg y → infinite_pos (x + y) := begin intros hip hnin r, cases not_forall.mp hnin with r₂ hr₂, convert add_lt_add_of_lt_of_le (hip (r + -r₂)) (not_lt.mp hr₂) using 1, simp end lemma not_infinite_neg_add_infinite_pos {x y : ℝ*} : ¬ infinite_neg x → infinite_pos y → infinite_pos (x + y) := λ hx hy, by rw [add_comm]; exact infinite_pos_add_not_infinite_neg hy hx lemma infinite_neg_add_not_infinite_pos {x y : ℝ*} : infinite_neg x → ¬ infinite_pos y → infinite_neg (x + y) := by rw [@infinite_neg_iff_infinite_pos_neg x, @infinite_pos_iff_infinite_neg_neg y, @infinite_neg_iff_infinite_pos_neg (x + y), neg_add]; exact infinite_pos_add_not_infinite_neg lemma not_infinite_pos_add_infinite_neg {x y : ℝ*} : ¬ infinite_pos x → infinite_neg y → infinite_neg (x + y) := λ hx hy, by rw [add_comm]; exact infinite_neg_add_not_infinite_pos hy hx lemma infinite_pos_add_infinite_pos {x y : ℝ*} : infinite_pos x → infinite_pos y → infinite_pos (x + y) := λ hx hy, infinite_pos_add_not_infinite_neg hx (not_infinite_neg_of_infinite_pos hy) lemma infinite_neg_add_infinite_neg {x y : ℝ*} : infinite_neg x → infinite_neg y → infinite_neg (x + y) := λ hx hy, infinite_neg_add_not_infinite_pos hx (not_infinite_pos_of_infinite_neg hy) lemma infinite_pos_add_not_infinite {x y : ℝ*} : infinite_pos x → ¬ infinite y → infinite_pos (x + y) := λ hx hy, infinite_pos_add_not_infinite_neg hx (not_or_distrib.mp hy).2 lemma infinite_neg_add_not_infinite {x y : ℝ*} : infinite_neg x → ¬ infinite y → infinite_neg (x + y) := λ hx hy, infinite_neg_add_not_infinite_pos hx (not_or_distrib.mp hy).1 theorem infinite_pos_of_tendsto_top {f : ℕ → ℝ} (hf : tendsto f at_top at_top) : infinite_pos (of_seq f) := λ r, have hf' : _ := tendsto_at_top_at_top.mp hf, Exists.cases_on (hf' (r + 1)) $ λ i hi, have hi' : ∀ (a : ℕ), f a < (r + 1) → a < i := λ a, by rw [←not_le, ←not_le]; exact not_imp_not.mpr (hi a), have hS : {a : ℕ | r < f a}ᶜ ⊆ {a : ℕ | a ≤ i} := by simp only [set.compl_set_of, not_lt]; exact λ a har, le_of_lt (hi' a (lt_of_le_of_lt har (lt_add_one _))), germ.coe_lt.2 $ mem_hyperfilter_of_finite_compl $ (set.finite_le_nat _).subset hS theorem infinite_neg_of_tendsto_bot {f : ℕ → ℝ} (hf : tendsto f at_top at_bot) : infinite_neg (of_seq f) := λ r, have hf' : _ := tendsto_at_top_at_bot.mp hf, Exists.cases_on (hf' (r - 1)) $ λ i hi, have hi' : ∀ (a : ℕ), r - 1 < f a → a < i := λ a, by rw [←not_le, ←not_le]; exact not_imp_not.mpr (hi a), have hS : {a : ℕ | f a < r}ᶜ ⊆ {a : ℕ | a ≤ i} := by simp only [set.compl_set_of, not_lt]; exact λ a har, le_of_lt (hi' a (lt_of_lt_of_le (sub_one_lt _) har)), germ.coe_lt.2 $ mem_hyperfilter_of_finite_compl $ (set.finite_le_nat _).subset hS lemma not_infinite_neg {x : ℝ*} : ¬ infinite x → ¬ infinite (-x) := not_imp_not.mpr infinite_iff_infinite_neg.mpr lemma not_infinite_add {x y : ℝ*} (hx : ¬ infinite x) (hy : ¬ infinite y) : ¬ infinite (x + y) := have hx' : _ := exists_st_of_not_infinite hx, have hy' : _ := exists_st_of_not_infinite hy, Exists.cases_on hx' $ Exists.cases_on hy' $ λ r hr s hs, not_infinite_of_exists_st $ ⟨s + r, is_st_add hs hr⟩ theorem not_infinite_iff_exist_lt_gt {x : ℝ*} : ¬ infinite x ↔ ∃ r s : ℝ, (r : ℝ*) < x ∧ x < s := ⟨ λ hni, Exists.dcases_on (not_forall.mp (not_or_distrib.mp hni).1) $ Exists.dcases_on (not_forall.mp (not_or_distrib.mp hni).2) $ λ r hr s hs, by rw [not_lt] at hr hs; exact ⟨r - 1, s + 1, ⟨ lt_of_lt_of_le (by rw sub_eq_add_neg; norm_num) hr, lt_of_le_of_lt hs (by norm_num)⟩ ⟩, λ hrs, Exists.dcases_on hrs $ λ r hr, Exists.dcases_on hr $ λ s hs, not_or_distrib.mpr ⟨not_forall.mpr ⟨s, lt_asymm (hs.2)⟩, not_forall.mpr ⟨r, lt_asymm (hs.1) ⟩⟩⟩ theorem not_infinite_real (r : ℝ) : ¬ infinite r := by rw not_infinite_iff_exist_lt_gt; exact ⟨ r - 1, r + 1, coe_lt_coe.2 $ sub_one_lt r, coe_lt_coe.2 $ lt_add_one r⟩ theorem not_real_of_infinite {x : ℝ*} : infinite x → ∀ r : ℝ, x ≠ r := λ hi r hr, not_infinite_real r $ @eq.subst _ infinite _ _ hr hi /-! ### Facts about `st` that require some infinite machinery -/ private lemma is_st_mul' {x y : ℝ*} {r s : ℝ} (hxr : is_st x r) (hys : is_st y s) (hs : s ≠ 0) : is_st (x * y) (r * s) := have hxr' : _ := is_st_iff_abs_sub_lt_delta.mp hxr, have hys' : _ := is_st_iff_abs_sub_lt_delta.mp hys, have h : _ := not_infinite_iff_exist_lt_gt.mp $ not_imp_not.mpr infinite_iff_infinite_abs.mpr $ not_infinite_of_exists_st ⟨r, hxr⟩, Exists.cases_on h $ λ u h', Exists.cases_on h' $ λ t ⟨hu, ht⟩, is_st_iff_abs_sub_lt_delta.mpr $ λ d hd, calc abs (x * y - r * s) = abs (x * (y - s) + (x - r) * s) : by rw [mul_sub, sub_mul, add_sub, sub_add_cancel] ... ≤ abs (x * (y - s)) + abs ((x - r) * s) : abs_add _ _ ... ≤ abs x * abs (y - s) + abs (x - r) * abs s : by simp only [abs_mul] ... ≤ abs x * ((d / t) / 2 : ℝ) + ((d / abs s) / 2 : ℝ) * abs s : add_le_add (mul_le_mul_of_nonneg_left (le_of_lt $ hys' _ $ half_pos $ div_pos hd $ coe_pos.1 $ lt_of_le_of_lt (abs_nonneg x) ht) $ abs_nonneg _) (mul_le_mul_of_nonneg_right (le_of_lt $ hxr' _ $ half_pos $ div_pos hd $ abs_pos.2 hs) $ abs_nonneg _) ... = (d / 2 * (abs x / t) + d / 2 : ℝ*) : by { push_cast [-filter.germ.const_div], -- TODO: Why wasn't `hyperreal.coe_div` used? have : (abs s : ℝ*) ≠ 0, by simpa, have : (2 : ℝ*) ≠ 0 := two_ne_zero, field_simp [*, add_mul, mul_add, mul_assoc, mul_comm, mul_left_comm] } ... < (d / 2 * 1 + d / 2 : ℝ*) : add_lt_add_right (mul_lt_mul_of_pos_left ((div_lt_one $ lt_of_le_of_lt (abs_nonneg x) ht).mpr ht) $ half_pos $ coe_pos.2 hd) _ ... = (d : ℝ*) : by rw [mul_one, add_halves] lemma is_st_mul {x y : ℝ*} {r s : ℝ} (hxr : is_st x r) (hys : is_st y s) : is_st (x * y) (r * s) := have h : _ := not_infinite_iff_exist_lt_gt.mp $ not_imp_not.mpr infinite_iff_infinite_abs.mpr $ not_infinite_of_exists_st ⟨r, hxr⟩, Exists.cases_on h $ λ u h', Exists.cases_on h' $ λ t ⟨hu, ht⟩, begin by_cases hs : s = 0, { apply is_st_iff_abs_sub_lt_delta.mpr, intros d hd, have hys' : _ := is_st_iff_abs_sub_lt_delta.mp hys (d / t) (div_pos hd (coe_pos.1 (lt_of_le_of_lt (abs_nonneg x) ht))), rw [hs, coe_zero, sub_zero] at hys', rw [hs, mul_zero, coe_zero, sub_zero, abs_mul, mul_comm, ←div_mul_cancel (d : ℝ*) (ne_of_gt (lt_of_le_of_lt (abs_nonneg x) ht)), ←coe_div], exact mul_lt_mul'' hys' ht (abs_nonneg _) (abs_nonneg _) }, exact is_st_mul' hxr hys hs, end --AN INFINITE LEMMA THAT REQUIRES SOME MORE ST MACHINERY lemma not_infinite_mul {x y : ℝ*} (hx : ¬ infinite x) (hy : ¬ infinite y) : ¬ infinite (x * y) := have hx' : _ := exists_st_of_not_infinite hx, have hy' : _ := exists_st_of_not_infinite hy, Exists.cases_on hx' $ Exists.cases_on hy' $ λ r hr s hs, not_infinite_of_exists_st $ ⟨s * r, is_st_mul hs hr⟩ --- lemma st_add {x y : ℝ*} (hx : ¬infinite x) (hy : ¬infinite y) : st (x + y) = st x + st y := have hx' : _ := is_st_st' hx, have hy' : _ := is_st_st' hy, have hxy : _ := is_st_st' (not_infinite_add hx hy), have hxy' : _ := is_st_add hx' hy', is_st_unique hxy hxy' lemma st_neg (x : ℝ*) : st (-x) = - st x := if h : infinite x then by rw [st_infinite h, st_infinite (infinite_iff_infinite_neg.mp h), neg_zero] else is_st_unique (is_st_st' (not_infinite_neg h)) (is_st_neg (is_st_st' h)) lemma st_mul {x y : ℝ*} (hx : ¬infinite x) (hy : ¬infinite y) : st (x * y) = (st x) * (st y) := have hx' : _ := is_st_st' hx, have hy' : _ := is_st_st' hy, have hxy : _ := is_st_st' (not_infinite_mul hx hy), have hxy' : _ := is_st_mul hx' hy', is_st_unique hxy hxy' /-! ### Basic lemmas about infinitesimal -/ theorem infinitesimal_def {x : ℝ*} : infinitesimal x ↔ (∀ r : ℝ, 0 < r → -(r : ℝ*) < x ∧ x < r) := ⟨ λ hi r hr, by { convert (hi r hr); simp }, λ hi d hd, by { convert (hi d hd); simp } ⟩ theorem lt_of_pos_of_infinitesimal {x : ℝ*} : infinitesimal x → ∀ r : ℝ, 0 < r → x < r := λ hi r hr, ((infinitesimal_def.mp hi) r hr).2 theorem lt_neg_of_pos_of_infinitesimal {x : ℝ*} : infinitesimal x → ∀ r : ℝ, 0 < r → -↑r < x := λ hi r hr, ((infinitesimal_def.mp hi) r hr).1 theorem gt_of_neg_of_infinitesimal {x : ℝ*} : infinitesimal x → ∀ r : ℝ, r < 0 → ↑r < x := λ hi r hr, by convert ((infinitesimal_def.mp hi) (-r) (neg_pos.mpr hr)).1; exact (neg_neg ↑r).symm theorem abs_lt_real_iff_infinitesimal {x : ℝ*} : infinitesimal x ↔ ∀ r : ℝ, r ≠ 0 → abs x < abs r := ⟨ λ hi r hr, abs_lt.mpr (by rw ←coe_abs; exact infinitesimal_def.mp hi (abs r) (abs_pos.2 hr)), λ hR, infinitesimal_def.mpr $ λ r hr, abs_lt.mp $ (abs_of_pos $ coe_pos.2 hr) ▸ hR r $ ne_of_gt hr ⟩ lemma infinitesimal_zero : infinitesimal 0 := is_st_refl_real 0 lemma zero_of_infinitesimal_real {r : ℝ} : infinitesimal r → r = 0 := eq_of_is_st_real lemma zero_iff_infinitesimal_real {r : ℝ} : infinitesimal r ↔ r = 0 := ⟨zero_of_infinitesimal_real, λ hr, by rw hr; exact infinitesimal_zero⟩ lemma infinitesimal_add {x y : ℝ*} (hx : infinitesimal x) (hy : infinitesimal y) : infinitesimal (x + y) := by simpa only [add_zero] using is_st_add hx hy lemma infinitesimal_neg {x : ℝ*} (hx : infinitesimal x) : infinitesimal (-x) := by simpa only [neg_zero] using is_st_neg hx lemma infinitesimal_neg_iff {x : ℝ*} : infinitesimal x ↔ infinitesimal (-x) := ⟨infinitesimal_neg, λ h, (neg_neg x) ▸ @infinitesimal_neg (-x) h⟩ lemma infinitesimal_mul {x y : ℝ*} (hx : infinitesimal x) (hy : infinitesimal y) : infinitesimal (x * y) := by simpa only [mul_zero] using is_st_mul hx hy theorem infinitesimal_of_tendsto_zero {f : ℕ → ℝ} : tendsto f at_top (𝓝 0) → infinitesimal (of_seq f) := λ hf d hd, by rw [sub_eq_add_neg, ←coe_neg, ←coe_add, ←coe_add, zero_add, zero_add]; exact ⟨neg_lt_of_tendsto_zero_of_pos hf hd, lt_of_tendsto_zero_of_pos hf hd⟩ theorem infinitesimal_epsilon : infinitesimal ε := infinitesimal_of_tendsto_zero tendsto_inverse_at_top_nhds_0_nat lemma not_real_of_infinitesimal_ne_zero (x : ℝ*) : infinitesimal x → x ≠ 0 → ∀ r : ℝ, x ≠ r := λ hi hx r hr, hx $ hr.trans $ coe_eq_zero.2 $ is_st_unique (hr.symm ▸ is_st_refl_real r : is_st x r) hi theorem infinitesimal_sub_is_st {x : ℝ*} {r : ℝ} (hxr : is_st x r) : infinitesimal (x - r) := show is_st (x - r) 0, by { rw [sub_eq_add_neg, ← add_neg_self r], exact is_st_add hxr (is_st_refl_real (-r)) } theorem infinitesimal_sub_st {x : ℝ*} (hx : ¬infinite x) : infinitesimal (x - st x) := infinitesimal_sub_is_st $ is_st_st' hx lemma infinite_pos_iff_infinitesimal_inv_pos {x : ℝ*} : infinite_pos x ↔ (infinitesimal x⁻¹ ∧ 0 < x⁻¹) := ⟨ λ hip, ⟨ infinitesimal_def.mpr $ λ r hr, ⟨ lt_trans (coe_lt_coe.2 (neg_neg_of_pos hr)) (inv_pos.2 (hip 0)), (inv_lt (coe_lt_coe.2 hr) (hip 0)).mp (by convert hip r⁻¹) ⟩, inv_pos.2 $ hip 0 ⟩, λ ⟨hi, hp⟩ r, @classical.by_cases (r = 0) (↑r < x) (λ h, eq.substr h (inv_pos.mp hp)) $ λ h, lt_of_le_of_lt (coe_le_coe.2 (le_abs_self r)) ((inv_lt_inv (inv_pos.mp hp) (coe_lt_coe.2 (abs_pos.2 h))).mp ((infinitesimal_def.mp hi) ((abs r)⁻¹) (inv_pos.2 (abs_pos.2 h))).2) ⟩ lemma infinite_neg_iff_infinitesimal_inv_neg {x : ℝ*} : infinite_neg x ↔ (infinitesimal x⁻¹ ∧ x⁻¹ < 0) := ⟨ λ hin, have hin' : _ := infinite_pos_iff_infinitesimal_inv_pos.mp (infinite_pos_neg_of_infinite_neg hin), by rwa [infinitesimal_neg_iff, ←neg_pos, neg_inv], λ hin, by rwa [←neg_pos, infinitesimal_neg_iff, neg_inv, ←infinite_pos_iff_infinitesimal_inv_pos, ←infinite_neg_iff_infinite_pos_neg] at hin ⟩ theorem infinitesimal_inv_of_infinite {x : ℝ*} : infinite x → infinitesimal x⁻¹ := λ hi, or.cases_on hi (λ hip, (infinite_pos_iff_infinitesimal_inv_pos.mp hip).1) (λ hin, (infinite_neg_iff_infinitesimal_inv_neg.mp hin).1) theorem infinite_of_infinitesimal_inv {x : ℝ*} (h0 : x ≠ 0) (hi : infinitesimal x⁻¹ ) : infinite x := begin cases (lt_or_gt_of_ne h0) with hn hp, { exact or.inr (infinite_neg_iff_infinitesimal_inv_neg.mpr ⟨hi, inv_lt_zero.mpr hn⟩) }, { exact or.inl (infinite_pos_iff_infinitesimal_inv_pos.mpr ⟨hi, inv_pos.mpr hp⟩) } end theorem infinite_iff_infinitesimal_inv {x : ℝ*} (h0 : x ≠ 0) : infinite x ↔ infinitesimal x⁻¹ := ⟨ infinitesimal_inv_of_infinite, infinite_of_infinitesimal_inv h0 ⟩ lemma infinitesimal_pos_iff_infinite_pos_inv {x : ℝ*} : infinite_pos x⁻¹ ↔ (infinitesimal x ∧ 0 < x) := by convert infinite_pos_iff_infinitesimal_inv_pos; simp only [inv_inv'] lemma infinitesimal_neg_iff_infinite_neg_inv {x : ℝ*} : infinite_neg x⁻¹ ↔ (infinitesimal x ∧ x < 0) := by convert infinite_neg_iff_infinitesimal_inv_neg; simp only [inv_inv'] theorem infinitesimal_iff_infinite_inv {x : ℝ*} (h : x ≠ 0) : infinitesimal x ↔ infinite x⁻¹ := by convert (infinite_iff_infinitesimal_inv (inv_ne_zero h)).symm; simp only [inv_inv'] /-! ### `st` stuff that requires infinitesimal machinery -/ theorem is_st_of_tendsto {f : ℕ → ℝ} {r : ℝ} (hf : tendsto f at_top (𝓝 r)) : is_st (of_seq f) r := have hg : tendsto (λ n, f n - r) at_top (𝓝 0) := (sub_self r) ▸ (hf.sub tendsto_const_nhds), by rw [←(zero_add r), ←(sub_add_cancel f (λ n, r))]; exact is_st_add (infinitesimal_of_tendsto_zero hg) (is_st_refl_real r) lemma is_st_inv {x : ℝ*} {r : ℝ} (hi : ¬ infinitesimal x) : is_st x r → is_st x⁻¹ r⁻¹ := λ hxr, have h : x ≠ 0 := (λ h, hi (h.symm ▸ infinitesimal_zero)), have H : _ := exists_st_of_not_infinite $ not_imp_not.mpr (infinitesimal_iff_infinite_inv h).mpr hi, Exists.cases_on H $ λ s hs, have H' : is_st 1 (r * s) := mul_inv_cancel h ▸ is_st_mul hxr hs, have H'' : s = r⁻¹ := one_div r ▸ eq_one_div_of_mul_eq_one (eq_of_is_st_real H').symm, H'' ▸ hs lemma st_inv (x : ℝ*) : st x⁻¹ = (st x)⁻¹ := begin by_cases h0 : x = 0, rw [h0, inv_zero, ←coe_zero, st_id_real, inv_zero], by_cases h1 : infinitesimal x, rw [st_infinite ((infinitesimal_iff_infinite_inv h0).mp h1), st_of_is_st h1, inv_zero], by_cases h2 : infinite x, rw [st_of_is_st (infinitesimal_inv_of_infinite h2), st_infinite h2, inv_zero], exact st_of_is_st (is_st_inv h1 (is_st_st' h2)), end /-! ### Infinite stuff that requires infinitesimal machinery -/ lemma infinite_pos_omega : infinite_pos ω := infinite_pos_iff_infinitesimal_inv_pos.mpr ⟨infinitesimal_epsilon, epsilon_pos⟩ lemma infinite_omega : infinite ω := (infinite_iff_infinitesimal_inv omega_ne_zero).mpr infinitesimal_epsilon lemma infinite_pos_mul_of_infinite_pos_not_infinitesimal_pos {x y : ℝ*} : infinite_pos x → ¬ infinitesimal y → 0 < y → infinite_pos (x * y) := λ hx hy₁ hy₂ r, have hy₁' : _ := not_forall.mp (by rw infinitesimal_def at hy₁; exact hy₁), Exists.dcases_on hy₁' $ λ r₁ hy₁'', have hyr : _ := by rw [not_imp, ←abs_lt, not_lt, abs_of_pos hy₂] at hy₁''; exact hy₁'', by rw [←div_mul_cancel r (ne_of_gt hyr.1), coe_mul]; exact mul_lt_mul (hx (r / r₁)) hyr.2 (coe_lt_coe.2 hyr.1) (le_of_lt (hx 0)) lemma infinite_pos_mul_of_not_infinitesimal_pos_infinite_pos {x y : ℝ*} : ¬ infinitesimal x → 0 < x → infinite_pos y → infinite_pos (x * y) := λ hx hp hy, by rw mul_comm; exact infinite_pos_mul_of_infinite_pos_not_infinitesimal_pos hy hx hp lemma infinite_pos_mul_of_infinite_neg_not_infinitesimal_neg {x y : ℝ*} : infinite_neg x → ¬ infinitesimal y → y < 0 → infinite_pos (x * y) := by rw [infinite_neg_iff_infinite_pos_neg, ←neg_pos, ←neg_mul_neg, infinitesimal_neg_iff]; exact infinite_pos_mul_of_infinite_pos_not_infinitesimal_pos lemma infinite_pos_mul_of_not_infinitesimal_neg_infinite_neg {x y : ℝ*} : ¬ infinitesimal x → x < 0 → infinite_neg y → infinite_pos (x * y) := λ hx hp hy, by rw mul_comm; exact infinite_pos_mul_of_infinite_neg_not_infinitesimal_neg hy hx hp lemma infinite_neg_mul_of_infinite_pos_not_infinitesimal_neg {x y : ℝ*} : infinite_pos x → ¬ infinitesimal y → y < 0 → infinite_neg (x * y) := by rw [infinite_neg_iff_infinite_pos_neg, ←neg_pos, neg_mul_eq_mul_neg, infinitesimal_neg_iff]; exact infinite_pos_mul_of_infinite_pos_not_infinitesimal_pos lemma infinite_neg_mul_of_not_infinitesimal_neg_infinite_pos {x y : ℝ*} : ¬ infinitesimal x → x < 0 → infinite_pos y → infinite_neg (x * y) := λ hx hp hy, by rw mul_comm; exact infinite_neg_mul_of_infinite_pos_not_infinitesimal_neg hy hx hp lemma infinite_neg_mul_of_infinite_neg_not_infinitesimal_pos {x y : ℝ*} : infinite_neg x → ¬ infinitesimal y → 0 < y → infinite_neg (x * y) := by rw [infinite_neg_iff_infinite_pos_neg, infinite_neg_iff_infinite_pos_neg, neg_mul_eq_neg_mul]; exact infinite_pos_mul_of_infinite_pos_not_infinitesimal_pos lemma infinite_neg_mul_of_not_infinitesimal_pos_infinite_neg {x y : ℝ*} : ¬ infinitesimal x → 0 < x → infinite_neg y → infinite_neg (x * y) := λ hx hp hy, by rw mul_comm; exact infinite_neg_mul_of_infinite_neg_not_infinitesimal_pos hy hx hp lemma infinite_pos_mul_infinite_pos {x y : ℝ*} : infinite_pos x → infinite_pos y → infinite_pos (x * y) := λ hx hy, infinite_pos_mul_of_infinite_pos_not_infinitesimal_pos hx (not_infinitesimal_of_infinite_pos hy) (hy 0) lemma infinite_neg_mul_infinite_neg {x y : ℝ*} : infinite_neg x → infinite_neg y → infinite_pos (x * y) := λ hx hy, infinite_pos_mul_of_infinite_neg_not_infinitesimal_neg hx (not_infinitesimal_of_infinite_neg hy) (hy 0) lemma infinite_pos_mul_infinite_neg {x y : ℝ*} : infinite_pos x → infinite_neg y → infinite_neg (x * y) := λ hx hy, infinite_neg_mul_of_infinite_pos_not_infinitesimal_neg hx (not_infinitesimal_of_infinite_neg hy) (hy 0) lemma infinite_neg_mul_infinite_pos {x y : ℝ*} : infinite_neg x → infinite_pos y → infinite_neg (x * y) := λ hx hy, infinite_neg_mul_of_infinite_neg_not_infinitesimal_pos hx (not_infinitesimal_of_infinite_pos hy) (hy 0) lemma infinite_mul_of_infinite_not_infinitesimal {x y : ℝ*} : infinite x → ¬ infinitesimal y → infinite (x * y) := λ hx hy, have h0 : y < 0 ∨ 0 < y := lt_or_gt_of_ne (λ H0, hy (eq.substr H0 (is_st_refl_real 0))), or.dcases_on hx (or.dcases_on h0 (λ H0 Hx, or.inr (infinite_neg_mul_of_infinite_pos_not_infinitesimal_neg Hx hy H0)) (λ H0 Hx, or.inl (infinite_pos_mul_of_infinite_pos_not_infinitesimal_pos Hx hy H0))) (or.dcases_on h0 (λ H0 Hx, or.inl (infinite_pos_mul_of_infinite_neg_not_infinitesimal_neg Hx hy H0)) (λ H0 Hx, or.inr (infinite_neg_mul_of_infinite_neg_not_infinitesimal_pos Hx hy H0))) lemma infinite_mul_of_not_infinitesimal_infinite {x y : ℝ*} : ¬ infinitesimal x → infinite y → infinite (x * y) := λ hx hy, by rw [mul_comm]; exact infinite_mul_of_infinite_not_infinitesimal hy hx lemma infinite_mul_infinite {x y : ℝ*} : infinite x → infinite y → infinite (x * y) := λ hx hy, infinite_mul_of_infinite_not_infinitesimal hx (not_infinitesimal_of_infinite hy) end hyperreal
ca64339c1126f85d49e58ac1b34a9ab34bf2291b
41e069072396dcd54bd9fdadb27cfd35fd07016a
/src/K/size.lean
b05aeaa82348db003cb5ef870ec3e7e6463bb858
[ "MIT" ]
permissive
semorrison/ModalTab
438ad601bd2631ab9cfe1e61f0d1337a36e2367e
cc94099194a2b69f84eb7a770b7aac711825179f
refs/heads/master
1,585,939,884,891
1,540,961,947,000
1,540,961,947,000
155,500,181
0
0
MIT
1,540,961,175,000
1,540,961,175,000
null
UTF-8
Lean
false
false
1,713
lean
import defs open list lemma size_erase_add_eq_size_sum {φ} : Π (Γ : list nnf) (h : φ ∈ Γ), node_size (Γ.erase φ) + sizeof φ = node_size Γ | [] h := absurd h $ not_mem_nil _ | (hd :: tl) h := begin by_cases eq : φ = hd, {dsimp [list.erase], rw if_pos, rw eq, apply add_comm, rw eq}, {dsimp [list.erase], rw if_neg, dsimp, rw [add_assoc], have : node_size (list.erase tl φ) + sizeof φ = node_size tl, {apply size_erase_add_eq_size_sum, cases h, contradiction, assumption}, rw this, intro h', rw h' at eq, contradiction} end theorem split_lt_and {φ ψ} (Γ : list nnf) (h : nnf.and φ ψ ∈ Γ) : node_size (φ :: ψ :: Γ.erase (nnf.and φ ψ)) < node_size Γ := begin dsimp [node_size], rw ←size_erase_add_eq_size_sum Γ, swap, exact h, rw [←add_assoc, add_comm], apply add_lt_add_left, dsimp [sizeof, has_sizeof.sizeof, nnf.sizeof], rw [add_assoc], rw [nat.one_add], apply nat.lt_succ_self end theorem split_lt_or_left {φ ψ} (Γ : list nnf) (h : nnf.or φ ψ ∈ Γ) : node_size (φ :: Γ.erase (nnf.or φ ψ)) < node_size Γ := begin dsimp, rw ←size_erase_add_eq_size_sum Γ, swap, exact h, rw [add_comm], apply add_lt_add_left, dsimp [sizeof, has_sizeof.sizeof, nnf.sizeof], rw [add_comm, ←add_assoc], apply nat.lt_add_of_pos_left, apply nat.succ_pos end theorem split_lt_or_right {φ ψ} (Γ : list nnf) (h : nnf.or φ ψ ∈ Γ) : node_size (ψ :: Γ.erase (nnf.or φ ψ)) < node_size Γ := begin dsimp, rw ←size_erase_add_eq_size_sum Γ, swap, exact h, rw [add_comm], apply add_lt_add_left, dsimp [sizeof, has_sizeof.sizeof, nnf.sizeof], apply nat.lt_add_of_pos_left, rw nat.one_add, apply nat.succ_pos end
57ffbeb8a93d76558e9514e68d6daf34776d65e6
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/category_theory/adjunction/opposites.lean
bd4da65aaaf9f0a4b2700ee86c9904930263cd7a
[ "Apache-2.0" ]
permissive
lacker/mathlib
f2439c743c4f8eb413ec589430c82d0f73b2d539
ddf7563ac69d42cfa4a1bfe41db1fed521bd795f
refs/heads/master
1,671,948,326,773
1,601,479,268,000
1,601,479,268,000
298,686,743
0
0
Apache-2.0
1,601,070,794,000
1,601,070,794,000
null
UTF-8
Lean
false
false
4,007
lean
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta, Thomas Read -/ import category_theory.adjunction.basic import category_theory.yoneda import category_theory.opposites /-! # Opposite adjunctions This file contains constructions to relate adjunctions of functors to adjunctions of their opposites. These constructions are used to show uniqueness of adjoints (up to natural isomorphism). ## Tags adjunction, opposite, uniqueness -/ open category_theory universes v₁ v₂ u₁ u₂ -- declare the `v`'s first; see `category_theory.category` for an explanation variables {C : Type u₁} [category.{v₁} C] {D : Type u₂} [category.{v₂} D] namespace adjunction /-- If `G.op` is adjoint to `F.op` then `F` is adjoint to `G`. -/ def adjoint_of_op_adjoint_op (F : C ⥤ D) (G : D ⥤ C) (h : G.op ⊣ F.op) : F ⊣ G := adjunction.mk_of_hom_equiv { hom_equiv := λ X Y, ((h.hom_equiv (opposite.op Y) (opposite.op X)).trans (op_equiv _ _)).symm.trans (op_equiv _ _) } /-- If `G` is adjoint to `F.op` then `F` is adjoint to `G.unop`. -/ def adjoint_unop_of_adjoint_op (F : C ⥤ D) (G : Dᵒᵖ ⥤ Cᵒᵖ) (h : G ⊣ F.op) : F ⊣ G.unop := adjoint_of_op_adjoint_op F G.unop (h.of_nat_iso_left G.op_unop_iso.symm) /-- If `G.op` is adjoint to `F` then `F.unop` is adjoint to `G`. -/ def unop_adjoint_of_op_adjoint (F : Cᵒᵖ ⥤ Dᵒᵖ) (G : D ⥤ C) (h : G.op ⊣ F) : F.unop ⊣ G := adjoint_of_op_adjoint_op _ _ (h.of_nat_iso_right F.op_unop_iso.symm) /-- If `G` is adjoint to `F` then `F.unop` is adjoint to `G.unop`. -/ def unop_adjoint_unop_of_adjoint (F : Cᵒᵖ ⥤ Dᵒᵖ) (G : Dᵒᵖ ⥤ Cᵒᵖ) (h : G ⊣ F) : F.unop ⊣ G.unop := adjoint_unop_of_adjoint_op F.unop G (h.of_nat_iso_right F.op_unop_iso.symm) /-- If `G` is adjoint to `F` then `F.op` is adjoint to `G.op`. -/ def op_adjoint_op_of_adjoint (F : C ⥤ D) (G : D ⥤ C) (h : G ⊣ F) : F.op ⊣ G.op := adjunction.mk_of_hom_equiv { hom_equiv := λ X Y, (op_equiv _ Y).trans ((h.hom_equiv _ _).symm.trans (op_equiv X (opposite.op _)).symm) } /-- If `G` is adjoint to `F.unop` then `F` is adjoint to `G.op`. -/ def adjoint_op_of_adjoint_unop (F : Cᵒᵖ ⥤ Dᵒᵖ) (G : D ⥤ C) (h : G ⊣ F.unop) : F ⊣ G.op := (op_adjoint_op_of_adjoint F.unop _ h).of_nat_iso_left F.op_unop_iso /-- If `G.unop` is adjoint to `F` then `F.op` is adjoint to `G`. -/ def op_adjoint_of_unop_adjoint (F : C ⥤ D) (G : Dᵒᵖ ⥤ Cᵒᵖ) (h : G.unop ⊣ F) : F.op ⊣ G := (op_adjoint_op_of_adjoint _ G.unop h).of_nat_iso_right G.op_unop_iso /-- If `G.unop` is adjoint to `F.unop` then `F` is adjoint to `G`. -/ def adjoint_of_unop_adjoint_unop (F : Cᵒᵖ ⥤ Dᵒᵖ) (G : Dᵒᵖ ⥤ Cᵒᵖ) (h : G.unop ⊣ F.unop) : F ⊣ G := (adjoint_op_of_adjoint_unop _ _ h).of_nat_iso_right G.op_unop_iso /-- If `F` and `F'` are both adjoint to `G`, there is a natural isomorphism `F.op ⋙ coyoneda ≅ F'.op ⋙ coyoneda`. We use this in combination with `fully_faithful_cancel_right` to show left adjoints are unique. -/ def left_adjoints_coyoneda_equiv {F F' : C ⥤ D} {G : D ⥤ C} (adj1 : F ⊣ G) (adj2 : F' ⊣ G): F.op ⋙ coyoneda ≅ F'.op ⋙ coyoneda := nat_iso.of_components (λ X, nat_iso.of_components (λ Y, ((adj1.hom_equiv X.unop Y).trans (adj2.hom_equiv X.unop Y).symm).to_iso) (by tidy)) (by tidy) /-- If `F` and `F'` are both left adjoint to `G`, then they are naturally isomorphic. -/ def left_adjoint_uniq {F F' : C ⥤ D} {G : D ⥤ C} (adj1 : F ⊣ G) (adj2 : F' ⊣ G) : F ≅ F' := nat_iso.unop (fully_faithful_cancel_right _ (left_adjoints_coyoneda_equiv adj2 adj1)) /-- If `G` and `G'` are both right adjoint to `F`, then they are naturally isomorphic. -/ def right_adjoint_uniq {F : C ⥤ D} {G G' : D ⥤ C} (adj1 : F ⊣ G) (adj2 : F ⊣ G') : G ≅ G' := nat_iso.unop (left_adjoint_uniq (op_adjoint_op_of_adjoint _ F adj2) (op_adjoint_op_of_adjoint _ _ adj1)) end adjunction
367d952dc56a6da31097bd7721f7a5f35d52d098
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/congr_imp_bug.lean
a9ec9ef30e08fd2a8719188cacbbad63813dabf7
[ "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
2,116
lean
---------------------------------------------------------------------------------------------------- --- Copyright (c) 2014 Microsoft Corporation. All rights reserved. --- Released under Apache 2.0 license as described in the file LICENSE. --- Author: Jeremy Avigad ---------------------------------------------------------------------------------------------------- open function namespace congr inductive struc [class] {T1 : Type} {T2 : Type} (R1 : T1 → T1 → Prop) (R2 : T2 → T2 → Prop) (f : T1 → T2) : Prop := mk : (∀x y : T1, R1 x y → R2 (f x) (f y)) → struc R1 R2 f definition app {T1 : Type} {T2 : Type} {R1 : T1 → T1 → Prop} {R2 : T2 → T2 → Prop} {f : T1 → T2} (C : struc R1 R2 f) {x y : T1} : R1 x y → R2 (f x) (f y) := struc.rec id C x y inductive struc2 {T1 : Type} {T2 : Type} {T3 : Type} (R1 : T1 → T1 → Prop) (R2 : T2 → T2 → Prop) (R3 : T3 → T3 → Prop) (f : T1 → T2 → T3) : Prop := mk2 : (∀(x1 y1 : T1) (x2 y2 : T2), R1 x1 y1 → R2 x2 y2 → R3 (f x1 x2) (f y1 y2)) → struc2 R1 R2 R3 f definition app2 {T1 : Type} {T2 : Type} {T3 : Type} {R1 : T1 → T1 → Prop} {R2 : T2 → T2 → Prop} {R3 : T3 → T3 → Prop} {f : T1 → T2 → T3} (C : struc2 R1 R2 R3 f) {x1 y1 : T1} {x2 y2 : T2} : R1 x1 y1 → R2 x2 y2 → R3 (f x1 x2) (f y1 y2) := struc2.rec id C x1 y1 x2 y2 theorem compose21 {T2 : Type} {R2 : T2 → T2 → Prop} {T3 : Type} {R3 : T3 → T3 → Prop} {T4 : Type} {R4 : T4 → T4 → Prop} {g : T2 → T3 → T4} (C3 : congr.struc2 R2 R3 R4 g) ⦃T1 : Type⦄ -- nice! {R1 : T1 → T1 → Prop} {f1 : T1 → T2} (C1 : congr.struc R1 R2 f1) {f2 : T1 → T3} (C2 : congr.struc R1 R3 f2) : congr.struc R1 R4 (λx, g (f1 x) (f2 x)) := struc.mk (take x1 x2 H, app2 C3 (app C1 H) (app C2 H)) theorem congr_and : congr.struc2 iff iff iff and := sorry theorem congr_and_comp [instance] {T : Type} {R : T → T → Prop} {f1 f2 : T → Prop} (C1 : struc R iff f1) (C2 : struc R iff f2) : congr.struc R iff (λx, f1 x ∧ f2 x) := congr.compose21 congr_and C1 C2 end congr
5ab041c4c410783b5f09a1fa1a9ad09acaebb80b
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/11_Tactic-Style_Proofs.org.23.lean
1e0b5ef5c09089f27f9af33594011639e4644f35
[]
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
226
lean
import standard example (p q : Prop) (H : p ∧ q) : p ∧ q ∧ p := have Hp : p, from and.left H, have Hq : q, from and.right H, show _, using Hp Hq, begin apply and.intro, assumption, apply and.intro, repeat assumption end
03f25fda01260117e049a2e5c7f040e29c21c118
9dc8cecdf3c4634764a18254e94d43da07142918
/src/data/typevec.lean
70b5a41af691f5ce4c31b0132ab241d4825b53f2
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
24,638
lean
/- Copyright (c) 2018 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Mario Carneiro, Simon Hudon -/ import data.fin.fin2 import logic.function.basic import tactic.basic /-! # Tuples of types, and their categorical structure. ## Features * `typevec n` - n-tuples of types * `α ⟹ β` - n-tuples of maps * `f ⊚ g` - composition Also, support functions for operating with n-tuples of types, such as: * `append1 α β` - append type `β` to n-tuple `α` to obtain an (n+1)-tuple * `drop α` - drops the last element of an (n+1)-tuple * `last α` - returns the last element of an (n+1)-tuple * `append_fun f g` - appends a function g to an n-tuple of functions * `drop_fun f` - drops the last function from an n+1-tuple * `last_fun f` - returns the last function of a tuple. Since e.g. `append1 α.drop α.last` is propositionally equal to `α` but not definitionally equal to it, we need support functions and lemmas to mediate between constructions. -/ universes u v w /-- n-tuples of types, as a category -/ def typevec (n : ℕ) := fin2 n → Type* instance {n} : inhabited (typevec.{u} n) := ⟨ λ _, punit ⟩ namespace typevec variable {n : ℕ} /-- arrow in the category of `typevec` -/ def arrow (α β : typevec n) := Π i : fin2 n, α i → β i localized "infixl (name := typevec.arrow) ` ⟹ `:40 := typevec.arrow" in mvfunctor instance arrow.inhabited (α β : typevec n) [Π i, inhabited (β i)] : inhabited (α ⟹ β) := ⟨ λ _ _, default ⟩ /-- identity of arrow composition -/ def id {α : typevec n} : α ⟹ α := λ i x, x /-- arrow composition in the category of `typevec` -/ def comp {α β γ : typevec n} (g : β ⟹ γ) (f : α ⟹ β) : α ⟹ γ := λ i x, g i (f i x) localized "infixr (name := typevec.comp) ` ⊚ `:80 := typevec.comp" in mvfunctor -- type as \oo @[simp] theorem id_comp {α β : typevec n} (f : α ⟹ β) : id ⊚ f = f := rfl @[simp] theorem comp_id {α β : typevec n} (f : α ⟹ β) : f ⊚ id = f := rfl theorem comp_assoc {α β γ δ : typevec n} (h : γ ⟹ δ) (g : β ⟹ γ) (f : α ⟹ β) : (h ⊚ g) ⊚ f = h ⊚ g ⊚ f := rfl /-- Support for extending a typevec by one element. -/ def append1 (α : typevec n) (β : Type*) : typevec (n+1) | (fin2.fs i) := α i | fin2.fz := β infixl (name := typevec.append1) ` ::: `:67 := append1 /-- retain only a `n-length` prefix of the argument -/ def drop (α : typevec.{u} (n+1)) : typevec n := λ i, α i.fs /-- take the last value of a `(n+1)-length` vector -/ def last (α : typevec.{u} (n+1)) : Type* := α fin2.fz instance last.inhabited (α : typevec (n+1)) [inhabited (α fin2.fz)] : inhabited (last α) := ⟨show α fin2.fz, from default⟩ theorem drop_append1 {α : typevec n} {β : Type*} {i : fin2 n} : drop (append1 α β) i = α i := rfl theorem drop_append1' {α : typevec n} {β : Type*} : drop (append1 α β) = α := by ext; apply drop_append1 theorem last_append1 {α : typevec n} {β : Type*} : last (append1 α β) = β := rfl @[simp] theorem append1_drop_last (α : typevec (n+1)) : append1 (drop α) (last α) = α := funext $ λ i, by cases i; refl /-- cases on `(n+1)-length` vectors -/ @[elab_as_eliminator] def append1_cases {C : typevec (n+1) → Sort u} (H : ∀ α β, C (append1 α β)) (γ) : C γ := by rw [← @append1_drop_last _ γ]; apply H @[simp] theorem append1_cases_append1 {C : typevec (n+1) → Sort u} (H : ∀ α β, C (append1 α β)) (α β) : @append1_cases _ C H (append1 α β) = H α β := rfl /-- append an arrow and a function for arbitrary source and target type vectors -/ def split_fun {α α' : typevec (n+1)} (f : drop α ⟹ drop α') (g : last α → last α') : α ⟹ α' | (fin2.fs i) := f i | fin2.fz := g /-- append an arrow and a function as well as their respective source and target types / typevecs -/ def append_fun {α α' : typevec n} {β β' : Type*} (f : α ⟹ α') (g : β → β') : append1 α β ⟹ append1 α' β' := split_fun f g infixl (name := typevec.append_fun) ` ::: ` := append_fun /-- split off the prefix of an arrow -/ def drop_fun {α β : typevec (n+1)} (f : α ⟹ β) : drop α ⟹ drop β := λ i, f i.fs /-- split off the last function of an arrow -/ def last_fun {α β : typevec (n+1)} (f : α ⟹ β) : last α → last β := f fin2.fz /-- arrow in the category of `0-length` vectors -/ def nil_fun {α : typevec 0} {β : typevec 0} : α ⟹ β := λ i, fin2.elim0 i theorem eq_of_drop_last_eq {α β : typevec (n+1)} {f g : α ⟹ β} (h₀ : drop_fun f = drop_fun g) (h₁ : last_fun f = last_fun g) : f = g := by replace h₀ := congr_fun h₀; ext1 (ieq | ⟨j, ieq⟩); apply_assumption @[simp] theorem drop_fun_split_fun {α α' : typevec (n+1)} (f : drop α ⟹ drop α') (g : last α → last α') : drop_fun (split_fun f g) = f := rfl /-- turn an equality into an arrow -/ def arrow.mp {α β : typevec n} (h : α = β) : α ⟹ β | i := eq.mp (congr_fun h _) /-- turn an equality into an arrow, with reverse direction -/ def arrow.mpr {α β : typevec n} (h : α = β) : β ⟹ α | i := eq.mpr (congr_fun h _) /-- decompose a vector into its prefix appended with its last element -/ def to_append1_drop_last {α : typevec (n+1)} : α ⟹ drop α ::: last α := arrow.mpr (append1_drop_last _) /-- stitch two bits of a vector back together -/ def from_append1_drop_last {α : typevec (n+1)} : drop α ::: last α ⟹ α := arrow.mp (append1_drop_last _) @[simp] theorem last_fun_split_fun {α α' : typevec (n+1)} (f : drop α ⟹ drop α') (g : last α → last α') : last_fun (split_fun f g) = g := rfl @[simp] theorem drop_fun_append_fun {α α' : typevec n} {β β' : Type*} (f : α ⟹ α') (g : β → β') : drop_fun (f ::: g) = f := rfl @[simp] theorem last_fun_append_fun {α α' : typevec n} {β β' : Type*} (f : α ⟹ α') (g : β → β') : last_fun (f ::: g) = g := rfl theorem split_drop_fun_last_fun {α α' : typevec (n+1)} (f : α ⟹ α') : split_fun (drop_fun f) (last_fun f) = f := eq_of_drop_last_eq rfl rfl theorem split_fun_inj {α α' : typevec (n+1)} {f f' : drop α ⟹ drop α'} {g g' : last α → last α'} (H : split_fun f g = split_fun f' g') : f = f' ∧ g = g' := by rw [← drop_fun_split_fun f g, H, ← last_fun_split_fun f g, H]; simp theorem append_fun_inj {α α' : typevec n} {β β' : Type*} {f f' : α ⟹ α'} {g g' : β → β'} : f ::: g = f' ::: g' → f = f' ∧ g = g' := split_fun_inj theorem split_fun_comp {α₀ α₁ α₂ : typevec (n+1)} (f₀ : drop α₀ ⟹ drop α₁) (f₁ : drop α₁ ⟹ drop α₂) (g₀ : last α₀ → last α₁) (g₁ : last α₁ → last α₂) : split_fun (f₁ ⊚ f₀) (g₁ ∘ g₀) = split_fun f₁ g₁ ⊚ split_fun f₀ g₀ := eq_of_drop_last_eq rfl rfl theorem append_fun_comp_split_fun {α γ : typevec n} {β δ : Type*} {ε : typevec (n + 1)} (f₀ : drop ε ⟹ α) (f₁ : α ⟹ γ) (g₀ : last ε → β) (g₁ : β → δ) : append_fun f₁ g₁ ⊚ split_fun f₀ g₀ = split_fun (f₁ ⊚ f₀) (g₁ ∘ g₀) := (split_fun_comp _ _ _ _).symm lemma append_fun_comp {α₀ α₁ α₂ : typevec n} {β₀ β₁ β₂ : Type*} (f₀ : α₀ ⟹ α₁) (f₁ : α₁ ⟹ α₂) (g₀ : β₀ → β₁) (g₁ : β₁ → β₂) : f₁ ⊚ f₀ ::: g₁ ∘ g₀ = (f₁ ::: g₁) ⊚ (f₀ ::: g₀) := eq_of_drop_last_eq rfl rfl lemma append_fun_comp' {α₀ α₁ α₂ : typevec n} {β₀ β₁ β₂ : Type*} (f₀ : α₀ ⟹ α₁) (f₁ : α₁ ⟹ α₂) (g₀ : β₀ → β₁) (g₁ : β₁ → β₂) : (f₁ ::: g₁) ⊚ (f₀ ::: g₀) = f₁ ⊚ f₀ ::: g₁ ∘ g₀ := eq_of_drop_last_eq rfl rfl lemma nil_fun_comp {α₀ : typevec 0} (f₀ : α₀ ⟹ fin2.elim0) : nil_fun ⊚ f₀ = f₀ := funext $ λ x, fin2.elim0 x theorem append_fun_comp_id {α : typevec n} {β₀ β₁ β₂ : Type*} (g₀ : β₀ → β₁) (g₁ : β₁ → β₂) : @id _ α ::: g₁ ∘ g₀ = (id ::: g₁) ⊚ (id ::: g₀) := eq_of_drop_last_eq rfl rfl @[simp] theorem drop_fun_comp {α₀ α₁ α₂ : typevec (n+1)} (f₀ : α₀ ⟹ α₁) (f₁ : α₁ ⟹ α₂) : drop_fun (f₁ ⊚ f₀) = drop_fun f₁ ⊚ drop_fun f₀ := rfl @[simp] theorem last_fun_comp {α₀ α₁ α₂ : typevec (n+1)} (f₀ : α₀ ⟹ α₁) (f₁ : α₁ ⟹ α₂) : last_fun (f₁ ⊚ f₀) = last_fun f₁ ∘ last_fun f₀ := rfl theorem append_fun_aux {α α' : typevec n} {β β' : Type*} (f : α ::: β ⟹ α' ::: β') : drop_fun f ::: last_fun f = f := eq_of_drop_last_eq rfl rfl theorem append_fun_id_id {α : typevec n} {β : Type*} : @typevec.id n α ::: @_root_.id β = typevec.id := eq_of_drop_last_eq rfl rfl instance subsingleton0 : subsingleton (typevec 0) := ⟨ λ a b, funext $ λ a, fin2.elim0 a ⟩ run_cmd do mk_simp_attr `typevec, tactic.add_doc_string `simp_attr.typevec "simp set for the manipulation of typevec and arrow expressions" local prefix `♯`:0 := cast (by try { simp }; congr' 1; try { simp }) /-- cases distinction for 0-length type vector -/ protected def cases_nil {β : typevec 0 → Sort*} (f : β fin2.elim0) : Π v, β v := λ v, ♯ f /-- cases distinction for (n+1)-length type vector -/ protected def cases_cons (n : ℕ) {β : typevec (n+1) → Sort*} (f : Π t (v : typevec n), β (v ::: t)) : Π v, β v := λ v : typevec (n+1), ♯ f v.last v.drop protected lemma cases_nil_append1 {β : typevec 0 → Sort*} (f : β fin2.elim0) : typevec.cases_nil f fin2.elim0 = f := rfl protected lemma cases_cons_append1 (n : ℕ) {β : typevec (n+1) → Sort*} (f : Π t (v : typevec n), β (v ::: t)) (v : typevec n) (α) : typevec.cases_cons n f (v ::: α) = f α v := rfl /-- cases distinction for an arrow in the category of 0-length type vectors -/ def typevec_cases_nil₃ {β : Π v v' : typevec 0, v ⟹ v' → Sort*} (f : β fin2.elim0 fin2.elim0 nil_fun) : Π v v' fs, β v v' fs := λ v v' fs, begin refine cast _ f; congr' 1; ext; try { intros; casesm fin2 0 }, refl end /-- cases distinction for an arrow in the category of (n+1)-length type vectors -/ def typevec_cases_cons₃ (n : ℕ) {β : Π v v' : typevec (n+1), v ⟹ v' → Sort*} (F : Π t t' (f : t → t') (v v' : typevec n) (fs : v ⟹ v'), β (v ::: t) (v' ::: t') (fs ::: f)) : Π v v' fs, β v v' fs := begin intros v v', rw [←append1_drop_last v, ←append1_drop_last v'], intro fs, rw [←split_drop_fun_last_fun fs], apply F end /-- specialized cases distinction for an arrow in the category of 0-length type vectors -/ def typevec_cases_nil₂ {β : fin2.elim0 ⟹ fin2.elim0 → Sort*} (f : β nil_fun) : Π f, β f := begin intro g, have : g = nil_fun, ext ⟨ ⟩, rw this, exact f end /-- specialized cases distinction for an arrow in the category of (n+1)-length type vectors -/ def typevec_cases_cons₂ (n : ℕ) (t t' : Type*) (v v' : typevec (n)) {β : (v ::: t) ⟹ (v' ::: t') → Sort*} (F : Π (f : t → t') (fs : v ⟹ v'), β (fs ::: f)) : Π fs, β fs := begin intro fs, rw [←split_drop_fun_last_fun fs], apply F end lemma typevec_cases_nil₂_append_fun {β : fin2.elim0 ⟹ fin2.elim0 → Sort*} (f : β nil_fun) : typevec_cases_nil₂ f nil_fun = f := rfl lemma typevec_cases_cons₂_append_fun (n : ℕ) (t t' : Type*) (v v' : typevec (n)) {β : (v ::: t) ⟹ (v' ::: t') → Sort*} (F : Π (f : t → t') (fs : v ⟹ v'), β (fs ::: f)) (f fs) : typevec_cases_cons₂ n t t' v v' F (fs ::: f) = F f fs := rfl /- for lifting predicates and relations -/ /-- `pred_last α p x` predicates `p` of the last element of `x : α.append1 β`. -/ def pred_last (α : typevec n) {β : Type*} (p : β → Prop) : Π ⦃i⦄, (α.append1 β) i → Prop | (fin2.fs i) := λ x, true | fin2.fz := p /-- `rel_last α r x y` says that `p` the last elements of `x y : α.append1 β` are related by `r` and all the other elements are equal. -/ def rel_last (α : typevec n) {β γ : Type*} (r : β → γ → Prop) : Π ⦃i⦄, (α.append1 β) i → (α.append1 γ) i → Prop | (fin2.fs i) := eq | fin2.fz := r section liftp' open nat /-- `repeat n t` is a `n-length` type vector that contains `n` occurences of `t` -/ def repeat : Π (n : ℕ) (t : Sort*), typevec n | 0 t := fin2.elim0 | (nat.succ i) t := append1 (repeat i t) t /-- `prod α β` is the pointwise product of the components of `α` and `β` -/ def prod : Π {n} (α β : typevec.{u} n), typevec n | 0 α β := fin2.elim0 | (n+1) α β := prod (drop α) (drop β) ::: (last α × last β) localized "infix (name := typevec.prod) ` ⊗ `:45 := typevec.prod" in mvfunctor /-- `const x α` is an arrow that ignores its source and constructs a `typevec` that contains nothing but `x` -/ protected def const {β} (x : β) : Π {n} (α : typevec n), α ⟹ repeat _ β | (succ n) α (fin2.fs i) := const (drop α) _ | (succ n) α fin2.fz := λ _, x open function (uncurry) /-- vector of equality on a product of vectors -/ def repeat_eq : Π {n} (α : typevec n), α ⊗ α ⟹ repeat _ Prop | 0 α := nil_fun | (succ n) α := repeat_eq (drop α) ::: uncurry eq lemma const_append1 {β γ} (x : γ) {n} (α : typevec n) : typevec.const x (α ::: β) = append_fun (typevec.const x α) (λ _, x) := by ext i : 1; cases i; refl lemma eq_nil_fun {α β : typevec 0} (f : α ⟹ β) : f = nil_fun := by ext x; cases x lemma id_eq_nil_fun {α : typevec 0} : @id _ α = nil_fun := by ext x; cases x lemma const_nil {β} (x : β) (α : typevec 0) : typevec.const x α = nil_fun := by ext i : 1; cases i; refl @[typevec] lemma repeat_eq_append1 {β} {n} (α : typevec n) : repeat_eq (α ::: β) = split_fun (repeat_eq α) (uncurry eq) := by induction n; refl @[typevec] lemma repeat_eq_nil (α : typevec 0) : repeat_eq α = nil_fun := by ext i : 1; cases i; refl /-- predicate on a type vector to constrain only the last object -/ def pred_last' (α : typevec n) {β : Type*} (p : β → Prop) : α ::: β ⟹ repeat (n+1) Prop := split_fun (typevec.const true α) p /-- predicate on the product of two type vectors to constrain only their last object -/ def rel_last' (α : typevec n) {β : Type*} (p : β → β → Prop) : (α ::: β ⊗ α ::: β) ⟹ repeat (n+1) Prop := split_fun (repeat_eq α) (uncurry p) /-- given `F : typevec.{u} (n+1) → Type u`, `curry F : Type u → typevec.{u} → Type u`, i.e. its first argument can be fed in separately from the rest of the vector of arguments -/ def curry (F : typevec.{u} (n+1) → Type*) (α : Type u) (β : typevec.{u} n) : Type* := F (β ::: α) instance curry.inhabited (F : typevec.{u} (n+1) → Type*) (α : Type u) (β : typevec.{u} n) [I : inhabited (F $ β ::: α)]: inhabited (curry F α β) := I /-- arrow to remove one element of a `repeat` vector -/ def drop_repeat (α : Type*) : Π {n}, drop (repeat (succ n) α) ⟹ repeat n α | (succ n) (fin2.fs i) := drop_repeat i | (succ n) fin2.fz := _root_.id /-- projection for a repeat vector -/ def of_repeat {α : Sort*} : Π {n i}, repeat n α i → α | ._ fin2.fz := _root_.id | ._ (fin2.fs i) := @of_repeat _ i lemma const_iff_true {α : typevec n} {i x p} : of_repeat (typevec.const p α i x) ↔ p := by induction i; [refl, erw [typevec.const,@i_ih (drop α) x]] -- variables {F : typevec.{u} n → Type*} [mvfunctor F] variables {α β γ : typevec.{u} n} variables (p : α ⟹ repeat n Prop) (r : α ⊗ α ⟹ repeat n Prop) /-- left projection of a `prod` vector -/ def prod.fst : Π {n} {α β : typevec.{u} n}, α ⊗ β ⟹ α | (succ n) α β (fin2.fs i) := @prod.fst _ (drop α) (drop β) i | (succ n) α β fin2.fz := _root_.prod.fst /-- right projection of a `prod` vector -/ def prod.snd : Π {n} {α β : typevec.{u} n}, α ⊗ β ⟹ β | (succ n) α β (fin2.fs i) := @prod.snd _ (drop α) (drop β) i | (succ n) α β fin2.fz := _root_.prod.snd /-- introduce a product where both components are the same -/ def prod.diag : Π {n} {α : typevec.{u} n}, α ⟹ α ⊗ α | (succ n) α (fin2.fs i) x := @prod.diag _ (drop α) _ x | (succ n) α fin2.fz x := (x,x) /-- constructor for `prod` -/ def prod.mk : Π {n} {α β : typevec.{u} n} (i : fin2 n), α i → β i → (α ⊗ β) i | (succ n) α β (fin2.fs i) := prod.mk i | (succ n) α β fin2.fz := _root_.prod.mk @[simp] lemma prod_fst_mk {α β : typevec n} (i : fin2 n) (a : α i) (b : β i) : typevec.prod.fst i (prod.mk i a b) = a := by induction i; simp [prod.fst, prod.mk, *] at * @[simp] lemma prod_snd_mk {α β : typevec n} (i : fin2 n) (a : α i) (b : β i) : typevec.prod.snd i (prod.mk i a b) = b := by induction i; simp [prod.snd, prod.mk, *] at * /-- `prod` is functorial -/ protected def prod.map : Π {n} {α α' β β' : typevec.{u} n}, (α ⟹ β) → (α' ⟹ β') → α ⊗ α' ⟹ β ⊗ β' | (succ n) α α' β β' x y (fin2.fs i) a := @prod.map _ (drop α) (drop α') (drop β) (drop β') (drop_fun x) (drop_fun y) _ a | (succ n) α α' β β' x y fin2.fz a := (x _ a.1,y _ a.2) localized "infix (name := typevec.prod.map) ` ⊗' `:45 := typevec.prod.map" in mvfunctor theorem fst_prod_mk {α α' β β' : typevec n} (f : α ⟹ β) (g : α' ⟹ β') : typevec.prod.fst ⊚ (f ⊗' g) = f ⊚ typevec.prod.fst := by ext i; induction i; [refl, apply i_ih] theorem snd_prod_mk {α α' β β' : typevec n} (f : α ⟹ β) (g : α' ⟹ β') : typevec.prod.snd ⊚ (f ⊗' g) = g ⊚ typevec.prod.snd := by ext i; induction i; [refl, apply i_ih] theorem fst_diag {α : typevec n} : typevec.prod.fst ⊚ (prod.diag : α ⟹ _) = id := by ext i; induction i; [refl, apply i_ih] theorem snd_diag {α : typevec n} : typevec.prod.snd ⊚ (prod.diag : α ⟹ _) = id := by ext i; induction i; [refl, apply i_ih] lemma repeat_eq_iff_eq {α : typevec n} {i x y} : of_repeat (repeat_eq α i (prod.mk _ x y)) ↔ x = y := by induction i; [refl, erw [repeat_eq,@i_ih (drop α) x y]] /-- given a predicate vector `p` over vector `α`, `subtype_ p` is the type of vectors that contain an `α` that satisfies `p` -/ def subtype_ : Π {n} {α : typevec.{u} n} (p : α ⟹ repeat n Prop), typevec n | ._ α p fin2.fz := _root_.subtype (λ x, p fin2.fz x) | ._ α p (fin2.fs i) := subtype_ (drop_fun p) i /-- projection on `subtype_` -/ def subtype_val : Π {n} {α : typevec.{u} n} (p : α ⟹ repeat n Prop), subtype_ p ⟹ α | (succ n) α p (fin2.fs i) := @subtype_val n _ _ i | (succ n) α p fin2.fz := _root_.subtype.val /-- arrow that rearranges the type of `subtype_` to turn a subtype of vector into a vector of subtypes -/ def to_subtype : Π {n} {α : typevec.{u} n} (p : α ⟹ repeat n Prop), (λ (i : fin2 n), { x // of_repeat $ p i x }) ⟹ subtype_ p | (succ n) α p (fin2.fs i) x := to_subtype (drop_fun p) i x | (succ n) α p fin2.fz x := x /-- arrow that rearranges the type of `subtype_` to turn a vector of subtypes into a subtype of vector -/ def of_subtype : Π {n} {α : typevec.{u} n} (p : α ⟹ repeat n Prop), subtype_ p ⟹ (λ (i : fin2 n), { x // of_repeat $ p i x }) | (succ n) α p (fin2.fs i) x := of_subtype _ i x | (succ n) α p fin2.fz x := x /-- similar to `to_subtype` adapted to relations (i.e. predicate on product) -/ def to_subtype' : Π {n} {α : typevec.{u} n} (p : α ⊗ α ⟹ repeat n Prop), (λ (i : fin2 n), { x : α i × α i // of_repeat $ p i (prod.mk _ x.1 x.2) }) ⟹ subtype_ p | (succ n) α p (fin2.fs i) x := to_subtype' (drop_fun p) i x | (succ n) α p fin2.fz x := ⟨x.val,cast (by congr; simp [prod.mk]) x.property⟩ /-- similar to `of_subtype` adapted to relations (i.e. predicate on product) -/ def of_subtype' : Π {n} {α : typevec.{u} n} (p : α ⊗ α ⟹ repeat n Prop), subtype_ p ⟹ (λ (i : fin2 n), { x : α i × α i // of_repeat $ p i (prod.mk _ x.1 x.2) }) | ._ α p (fin2.fs i) x := of_subtype' _ i x | ._ α p fin2.fz x := ⟨x.val,cast (by congr; simp [prod.mk]) x.property⟩ /-- similar to `diag` but the target vector is a `subtype_` guaranteeing the equality of the components -/ def diag_sub : Π {n} {α : typevec.{u} n}, α ⟹ subtype_ (repeat_eq α) | (succ n) α (fin2.fs i) x := @diag_sub _ (drop α) _ x | (succ n) α fin2.fz x := ⟨(x,x), rfl⟩ lemma subtype_val_nil {α : typevec.{u} 0} (ps : α ⟹ repeat 0 Prop) : typevec.subtype_val ps = nil_fun := funext $ by rintro ⟨ ⟩; refl lemma diag_sub_val {n} {α : typevec.{u} n} : subtype_val (repeat_eq α) ⊚ diag_sub = prod.diag := by ext i; induction i; [refl, apply i_ih] lemma prod_id : Π {n} {α β : typevec.{u} n}, (id ⊗' id) = (id : α ⊗ β ⟹ _) := begin intros, ext i a, induction i, { cases a, refl }, { apply i_ih }, end lemma append_prod_append_fun {n} {α α' β β' : typevec.{u} n} {φ φ' ψ ψ' : Type u} {f₀ : α ⟹ α'} {g₀ : β ⟹ β'} {f₁ : φ → φ'} {g₁ : ψ → ψ'} : (f₀ ⊗' g₀) ::: _root_.prod.map f₁ g₁ = ((f₀ ::: f₁) ⊗' (g₀ ::: g₁)) := by ext i a; cases i; [cases a, skip]; refl end liftp' @[simp] lemma drop_fun_diag {α} : drop_fun (@prod.diag (n+1) α) = prod.diag := by { ext i : 2, induction i; simp [drop_fun,*]; refl } @[simp] lemma drop_fun_subtype_val {α} (p : α ⟹ repeat (n+1) Prop) : drop_fun (subtype_val p) = subtype_val _ := rfl @[simp] lemma last_fun_subtype_val {α} (p : α ⟹ repeat (n+1) Prop) : last_fun (subtype_val p) = subtype.val := rfl @[simp] lemma drop_fun_to_subtype {α} (p : α ⟹ repeat (n+1) Prop) : drop_fun (to_subtype p) = to_subtype _ := by { ext i : 2, induction i; simp [drop_fun,*]; refl } @[simp] lemma last_fun_to_subtype {α} (p : α ⟹ repeat (n+1) Prop) : last_fun (to_subtype p) = _root_.id := by { ext i : 2, induction i; simp [drop_fun,*]; refl } @[simp] lemma drop_fun_of_subtype {α} (p : α ⟹ repeat (n+1) Prop) : drop_fun (of_subtype p) = of_subtype _ := by { ext i : 2, induction i; simp [drop_fun,*]; refl } @[simp] lemma last_fun_of_subtype {α} (p : α ⟹ repeat (n+1) Prop) : last_fun (of_subtype p) = _root_.id := by { ext i : 2, induction i; simp [drop_fun,*]; refl } @[simp] lemma drop_fun_rel_last {α : typevec n} {β} (R : β → β → Prop) : drop_fun (rel_last' α R) = repeat_eq α := rfl attribute [simp] drop_append1' open_locale mvfunctor @[simp] lemma drop_fun_prod {α α' β β' : typevec (n+1)} (f : α ⟹ β) (f' : α' ⟹ β') : drop_fun (f ⊗' f') = (drop_fun f ⊗' drop_fun f') := by { ext i : 2, induction i; simp [drop_fun,*]; refl } @[simp] lemma last_fun_prod {α α' β β' : typevec (n+1)} (f : α ⟹ β) (f' : α' ⟹ β') : last_fun (f ⊗' f') = _root_.prod.map (last_fun f) (last_fun f') := by { ext i : 1, induction i; simp [last_fun,*]; refl } @[simp] lemma drop_fun_from_append1_drop_last {α : typevec (n+1)} : drop_fun (@from_append1_drop_last _ α) = id := rfl @[simp] lemma last_fun_from_append1_drop_last {α : typevec (n+1)} : last_fun (@from_append1_drop_last _ α) = _root_.id := rfl @[simp] lemma drop_fun_id {α : typevec (n+1)} : drop_fun (@typevec.id _ α) = id := rfl @[simp] lemma prod_map_id {α β : typevec n} : (@typevec.id _ α ⊗' @typevec.id _ β) = id := by { ext i : 2, induction i; simp only [typevec.prod.map,*,drop_fun_id], cases x, refl, refl } @[simp] lemma subtype_val_diag_sub {α : typevec n} : subtype_val (repeat_eq α) ⊚ diag_sub = prod.diag := by { clear_except, ext i, induction i; [refl, apply i_ih], } @[simp] lemma to_subtype_of_subtype {α : typevec n} (p : α ⟹ repeat n Prop) : to_subtype p ⊚ of_subtype p = id := by ext i x; induction i; dsimp only [id, to_subtype, comp, of_subtype] at *; simp * @[simp] lemma subtype_val_to_subtype {α : typevec n} (p : α ⟹ repeat n Prop) : subtype_val p ⊚ to_subtype p = λ _, subtype.val := by ext i x; induction i; dsimp only [to_subtype, comp, subtype_val] at *; simp * @[simp] lemma to_subtype_of_subtype_assoc {α β : typevec n} (p : α ⟹ repeat n Prop) (f : β ⟹ subtype_ p) : @to_subtype n _ p ⊚ of_subtype _ ⊚ f = f := by rw [← comp_assoc,to_subtype_of_subtype]; simp @[simp] lemma to_subtype'_of_subtype' {α : typevec n} (r : α ⊗ α ⟹ repeat n Prop) : to_subtype' r ⊚ of_subtype' r = id := by ext i x; induction i; dsimp only [id, to_subtype', comp, of_subtype'] at *; simp [subtype.eta, *] lemma subtype_val_to_subtype' {α : typevec n} (r : α ⊗ α ⟹ repeat n Prop) : subtype_val r ⊚ to_subtype' r = λ i x, prod.mk i x.1.fst x.1.snd := by ext i x; induction i; dsimp only [id, to_subtype', comp, subtype_val, prod.mk] at *; simp * end typevec
c9a342f60d38499d0b4ba1b053bbb72f6c426e02
9dc8cecdf3c4634764a18254e94d43da07142918
/src/group_theory/perm/cycle/basic.lean
ad15315bd79e636c6a6b276d612aa81ab85a7e58
[ "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
60,385
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.finset.noncomm_prod import group_theory.perm.sign import logic.equiv.fintype /-! # 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 [zpow_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 [zpow_neg, inv_zpow, 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_zpow, simp [hi] }, { contrapose! hb, rw [perm.mul_apply, perm.mul_apply, hb, apply_inv_self] } end lemma is_cycle.exists_zpow_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, ← zpow_add, sub_add_cancel, hb]⟩ lemma is_cycle.exists_pow_eq [finite β] {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_zpow_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 [← zpow_coe_nat, int.to_nat_of_nonneg this, ← zpow_eq_mod_order_of] }⟩ lemma is_cycle.exists_pow_eq_one [finite β] {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.zpowers_equiv_support {σ : perm α} (hσ : is_cycle σ) : (↑(subgroup.zpowers σ) : 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, zpow_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, zpow_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, zpow_apply_comm σ m i, zpow_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.zpowers_equiv_support_apply {σ : perm α} (hσ : is_cycle σ) {n : ℕ} : hσ.zpowers_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.zpowers_equiv_support_symm_apply {σ : perm α} (hσ : is_cycle σ) (n : ℕ) : hσ.zpowers_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σ.zpowers_equiv_support_apply lemma order_of_is_cycle {σ : perm α} (hσ : is_cycle σ) : order_of σ = σ.support.card := begin rw [order_eq_card_zpowers, ←fintype.card_coe], convert fintype.card_congr (is_cycle.zpowers_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, zpow_add, mul_apply, hi, zpow_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 ⟨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, zpow_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 [← zpow_coe_nat, ← h, ← mul_apply, ← mul_apply, ← mul_apply, zpow_neg_succ_of_nat, ← inv_pow, pow_succ', mul_assoc, mul_assoc, inv_mul_self, mul_one, zpow_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, zpow_add, zpow_one, zpow_neg, ← inv_zpow, mul_inv_rev, swap_inv, mul_swap_eq_swap_mul, inv_apply_self, swap_comm _ x, zpow_add, zpow_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, zpow_add, mul_apply, hi] at hj, cases zpow_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 [swap_apply_def, mul_apply, if_neg hffx, f.injective.eq_iff, if_neg hx, hx], }, λ y hy, let ⟨i, hi⟩ := hf.exists_zpow_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 [zpow_one, mul_apply] ... = y : by rwa [← zpow_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, neg_neg, one_mul, mul_neg, eq_self_iff_true, pow_one, 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 zpow_mul⟩ end -- The lemma `support_zpow_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_zpow {σ : 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, zpow_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 [zpow_of_nat, zpow_of_nat, hnat] }, rw [zpow_neg_succ_of_nat, zpow_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 [zpow_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 [zpow_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, ← zpow_one_add, add_comm, zpow_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_zpow_eq hx hy lemma same_cycle.nat' [finite β] {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⟩ := h, use ((k % order_of f).nat_abs), have h₀ := int.coe_nat_pos.mpr (order_of_pos f), have h₁ := int.mod_nonneg k h₀.ne', rw [←zpow_coe_nat, int.nat_abs_of_nonneg h₁, ←zpow_eq_mod_order_of], refine ⟨_, rfl⟩, rw [←int.coe_nat_lt, int.nat_abs_of_nonneg h₁], exact int.mod_lt_of_pos _ h₀, end lemma same_cycle.nat'' [finite β] {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 _))), { refine (int.mod_lt _ $ int.coe_nat_ne_zero_iff_pos.2 $ order_of_pos _).trans_le _, simp [order_of_le_card_univ] }, apply_instance }), by { rw [← zpow_coe_nat, int.nat_abs_of_nonneg (int.mod_nonneg _ (int.coe_nat_ne_zero_iff_pos.2 (order_of_pos _))), ← zpow_eq_mod_order_of, hi], apply_instance }⟩⟩ 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 [zpow_add, mul_apply, hi, zpow_neg_one, inv_apply_self]⟩, λ ⟨i, hi⟩, ⟨1 + i, by rw [zpow_add, mul_apply, hi, zpow_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 [← zpow_apply_eq_self_of_apply_eq_self hy i, (f ^ i).injective.eq_iff] at hi, rw [hi, hy] }, hf.exists_zpow_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 [zpow_neg, ← inv_zpow, hi]⟩, λ ⟨i, hi⟩, ⟨-i, by rw [zpow_neg, ← inv_zpow, 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 [zpow_add] }, { rintro ⟨k, rfl⟩, use (k - n), rw [←zpow_coe_nat, ←mul_apply, ←zpow_add, int.sub_add_cancel] } end @[simp] lemma same_cycle_zpow_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 [zpow_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 [finite β] {f : perm β} (hf : is_cycle f) {n : ℕ} : is_cycle (f ^ n) ↔ n.coprime (order_of f) := begin classical, casesI nonempty_fintype β, 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 [finite β] {f : perm β} (hf : is_cycle f) {n : ℕ} : f ^ n = 1 ↔ ∃ x, f x ≠ x ∧ (f ^ n) x = x := begin classical, casesI nonempty_fintype β, split, { intro h, obtain ⟨x, hx, -⟩ := id hf, exact ⟨x, hx, by simp [h]⟩ }, { rintro ⟨x, hx, hx'⟩, by_cases h : support (f ^ n) = support f, { rw [← mem_support, ← 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.pow_eq_pow_iff [finite β] {f : perm β} (hf : is_cycle f) {a b : ℕ} : f ^ a = f ^ b ↔ ∃ x, f x ≠ x ∧ (f ^ a) x = (f ^ b) x := begin classical, casesI nonempty_fintype β, split, { intro h, obtain ⟨x, hx, -⟩ := id hf, exact ⟨x, hx, by simp [h]⟩ }, { rintro ⟨x, hx, hx'⟩, wlog hab : a ≤ b, suffices : f ^ (b - a) = 1, { rw [pow_sub _ hab, mul_inv_eq_one] at this, rw this }, rw hf.pow_eq_one_iff, by_cases hfa : (f ^ a) x ∈ f.support, { refine ⟨(f ^ a) x, mem_support.mp hfa, _⟩, simp only [pow_sub _ hab, equiv.perm.coe_mul, function.comp_app, inv_apply_self, ← hx'] }, { have h := @equiv.perm.zpow_apply_comm _ f 1 a x, simp only [zpow_one, zpow_coe_nat] at h, rw [not_mem_support, h, function.injective.eq_iff (f ^ a).injective] at hfa, contradiction }} 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 [finite β] {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, casesI nonempty_fintype β, 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 := begin dsimp only [cycle_of], split_ifs, { apply of_subtype_apply_of_mem, exact h, }, { apply of_subtype_apply_of_not_mem, exact h }, end 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_zpow_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 [zpow_neg_succ_of_nat, ← inv_pow, cycle_of_inv, zpow_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 := begin apply of_subtype_apply_of_mem, exact h, end 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 := begin apply of_subtype_apply_of_not_mem, exact h, end 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_zpow_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, zpow_add, zpow_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_zpow_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_zpow [fintype α] (f : perm α) (n : ℤ) (x : α) : cycle_of f ((f ^ n) x) = cycle_of f x := (same_cycle_zpow_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_zpow_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_zpow_self, simp [h.mul_zpow, zpow_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_zpow, zpow_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 /-- x is in the support of f iff cycle_of f x is a cycle.-/ lemma is_cycle_cycle_of_iff [fintype α] (f : perm α) {x : α} : is_cycle (cycle_of f x) ↔ (f x ≠ x) := begin split, { intro hx, rw ne.def, rw ← cycle_of_eq_one_iff f, exact equiv.perm.is_cycle.ne_one hx, }, { intro hx, apply equiv.perm.is_cycle_cycle_of, exact hx } 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*} [finite α] {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, casesI nonempty_fintype α, 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*} [finite α] {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.mono' (λ _ _, disjoint.commute) h ha 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.pairwise.forall 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 /-- If c is a cycle, a ∈ c.support and c is a cycle of f, then `c = f.cycle_of a` -/ lemma cycle_is_cycle_of {f c : equiv.perm α} {a : α} (ha : a ∈ c.support) (hc : c ∈ f.cycle_factors_finset) : c = f.cycle_of a := begin suffices : f.cycle_of a = c.cycle_of a, { rw this, apply symm, exact equiv.perm.is_cycle.cycle_of_eq ((equiv.perm.mem_cycle_factors_finset_iff.mp hc).left) (equiv.perm.mem_support.mp ha), }, let hfc := (equiv.perm.disjoint_mul_inv_of_mem_cycle_factors_finset hc).symm, let hfc2 := (perm.disjoint.commute hfc), rw ← equiv.perm.cycle_of_mul_of_apply_right_eq_self hfc2, simp only [hfc2.eq, inv_mul_cancel_right], -- a est dans le support de c, donc pas dans celui de g c⁻¹ exact equiv.perm.not_mem_support.mp (finset.disjoint_left.mp (equiv.perm.disjoint.disjoint_support hfc) ha), end end cycle_factors_finset @[elab_as_eliminator] lemma cycle_induction_on [finite β] (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 casesI nonempty_fintype β, 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τ)) h2.of_cons) } 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_zpow] }, rw zpow_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 [←zpow_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_zpow] }, rw zpow_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 [←zpow_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, zpow_apply_eq_self_of_apply_eq_self hx] } end section generation variables [finite β] open subgroup lemma closure_is_cycle : closure {σ : perm β | is_cycle σ} = ⊤ := begin classical, casesI nonempty_fintype β, exact top_le_iff.mp (le_trans (ge_of_eq closure_is_swap) (closure_mono (λ _, is_swap.is_cycle))), end variables [fintype α] 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σ.zpowers_equiv_support.symm.trans ((zpowers_equiv_zpowers begin rw [order_of_is_cycle hσ, h, order_of_is_cycle hτ], end).trans hτ.zpowers_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σ.zpowers_equiv_support_symm_apply n).symm)))), apply (congr rfl (congr rfl (congr rfl (hσ.zpowers_equiv_support_symm_apply (n + 1))))).trans _, simp only [ne.def, is_cycle.zpowers_equiv_support_apply, subtype.coe_mk, zpowers_equiv_zpowers_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*} [finite α] {σ τ π ρ : perm α} (hc1 : is_conj σ π) (hc2 : is_conj τ ρ) (hd1 : disjoint σ τ) (hd2 : disjoint π ρ) : is_conj (σ * τ) (π * ρ) := begin classical, casesI nonempty_fintype α, 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_coe.2 (disjoint_iff_disjoint_support.1 hd1), have hd2'' := disjoint_coe.2 (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_tsub_iff_left, ← lt_tsub_iff_right, ← finset.card_compl, finset.compl_filter], exact one_lt_card_support_of_ne_one h end end fixed_points end equiv.perm
167eabbd676228b7e9abc52e5d8b082c5ffcbdd7
367134ba5a65885e863bdc4507601606690974c1
/src/algebra/squarefree.lean
4e29a88be499e1a1d3b7b1c24358c4ff16e98020
[ "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
7,646
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 ring_theory.unique_factorization_domain import ring_theory.int.basic import number_theory.divisors /-! # Squarefree elements of monoids An element of a monoid is squarefree when it is not divisible by any squares except the squares of units. ## Main Definitions - `squarefree r` indicates that `r` is only divisible by `x * x` if `x` is a unit. ## Main Results - `multiplicity.squarefree_iff_multiplicity_le_one`: `x` is `squarefree` iff for every `y`, either `multiplicity y x ≤ 1` or `is_unit y`. - `unique_factorization_monoid.squarefree_iff_nodup_factors`: A nonzero element `x` of a unique factorization monoid is squarefree iff `factors x` has no duplicate factors. - `nat.squarefree_iff_nodup_factors`: A positive natural number `x` is squarefree iff the list `factors x` has no duplicate factors. ## Tags squarefree, multiplicity -/ variables {R : Type*} /-- An element of a monoid is squarefree if the only squares that divide it are the squares of units. -/ def squarefree [monoid R] (r : R) : Prop := ∀ x : R, x * x ∣ r → is_unit x @[simp] lemma is_unit.squarefree [comm_monoid R] {x : R} (h : is_unit x) : squarefree x := λ y hdvd, is_unit_of_mul_is_unit_left (is_unit_of_dvd_unit hdvd h) @[simp] lemma squarefree_one [comm_monoid R] : squarefree (1 : R) := is_unit_one.squarefree @[simp] lemma not_squarefree_zero [monoid_with_zero R] [nontrivial R] : ¬ squarefree (0 : R) := begin erw [not_forall], exact ⟨0, (by simp)⟩, end @[simp] lemma irreducible.squarefree [comm_monoid R] {x : R} (h : irreducible x) : squarefree x := begin rintros y ⟨z, hz⟩, rw mul_assoc at hz, rcases h.is_unit_or_is_unit hz with hu | hu, { exact hu }, { apply is_unit_of_mul_is_unit_left hu }, end @[simp] lemma prime.squarefree [comm_cancel_monoid_with_zero R] {x : R} (h : prime x) : squarefree x := (irreducible_of_prime h).squarefree lemma squarefree_of_dvd_of_squarefree [comm_monoid R] {x y : R} (hdvd : x ∣ y) (hsq : squarefree y) : squarefree x := λ a h, hsq _ (dvd.trans h hdvd) namespace multiplicity variables [comm_monoid R] [decidable_rel (has_dvd.dvd : R → R → Prop)] lemma squarefree_iff_multiplicity_le_one (r : R) : squarefree r ↔ ∀ x : R, multiplicity x r ≤ 1 ∨ is_unit x := begin refine forall_congr (λ a, _), rw [← pow_two, pow_dvd_iff_le_multiplicity, or_iff_not_imp_left, not_le, imp_congr], swap, { refl }, convert enat.add_one_le_iff_lt (enat.coe_ne_top _), norm_cast, end end multiplicity namespace unique_factorization_monoid variables [comm_cancel_monoid_with_zero R] [nontrivial R] [unique_factorization_monoid R] variables [normalization_monoid R] lemma squarefree_iff_nodup_factors [decidable_eq R] {x : R} (x0 : x ≠ 0) : squarefree x ↔ multiset.nodup (factors x) := begin have drel : decidable_rel (has_dvd.dvd : R → R → Prop), { classical, apply_instance, }, haveI := drel, rw [multiplicity.squarefree_iff_multiplicity_le_one, multiset.nodup_iff_count_le_one], split; intros h a, { by_cases hmem : a ∈ factors x, { have ha := irreducible_of_factor _ hmem, rcases h a with h | h, { rw ← normalize_factor _ hmem, rw [multiplicity_eq_count_factors ha x0] at h, assumption_mod_cast }, { have := ha.1, contradiction, } }, { simp [multiset.count_eq_zero_of_not_mem hmem] } }, { rw or_iff_not_imp_right, intro hu, by_cases h0 : a = 0, { simp [h0, x0] }, rcases wf_dvd_monoid.exists_irreducible_factor hu h0 with ⟨b, hib, hdvd⟩, apply le_trans (multiplicity.multiplicity_le_multiplicity_of_dvd hdvd), rw [multiplicity_eq_count_factors hib x0], specialize h (normalize b), assumption_mod_cast } end lemma dvd_pow_iff_dvd_of_squarefree {x y : R} {n : ℕ} (hsq : squarefree x) (h0 : n ≠ 0) : x ∣ y ^ n ↔ x ∣ y := begin classical, by_cases hx : x = 0, { simp [hx, pow_eq_zero_iff (nat.pos_of_ne_zero h0)] }, by_cases hy : y = 0, { simp [hy, zero_pow (nat.pos_of_ne_zero h0)] }, refine ⟨λ h, _, λ h, dvd_pow h h0⟩, rw [dvd_iff_factors_le_factors hx (pow_ne_zero n hy), factors_pow, ((squarefree_iff_nodup_factors hx).1 hsq).le_nsmul_iff_le h0] at h, rwa dvd_iff_factors_le_factors hx hy, end end unique_factorization_monoid namespace nat lemma squarefree_iff_nodup_factors {n : ℕ} (h0 : n ≠ 0) : squarefree n ↔ n.factors.nodup := begin rw [unique_factorization_monoid.squarefree_iff_nodup_factors h0, nat.factors_eq], simp, end instance : decidable_pred (squarefree : ℕ → Prop) | 0 := is_false not_squarefree_zero | (n + 1) := decidable_of_iff _ (squarefree_iff_nodup_factors (nat.succ_ne_zero n)).symm open unique_factorization_monoid lemma divisors_filter_squarefree {n : ℕ} (h0 : n ≠ 0) : (n.divisors.filter squarefree).val = (unique_factorization_monoid.factors n).to_finset.powerset.val.map (λ x, x.val.prod) := begin rw multiset.nodup_ext (finset.nodup _) (multiset.nodup_map_on _ (finset.nodup _)), { intro a, simp only [multiset.mem_filter, id.def, multiset.mem_map, finset.filter_val, ← finset.mem_def, mem_divisors], split, { rintro ⟨⟨an, h0⟩, hsq⟩, use (unique_factorization_monoid.factors a).to_finset, simp only [id.def, finset.mem_powerset], rcases an with ⟨b, rfl⟩, rw mul_ne_zero_iff at h0, rw unique_factorization_monoid.squarefree_iff_nodup_factors h0.1 at hsq, rw [multiset.to_finset_subset, multiset.to_finset_val, multiset.erase_dup_eq_self.2 hsq, ← associated_iff_eq, factors_mul h0.1 h0.2], exact ⟨multiset.subset_of_le (multiset.le_add_right _ _), factors_prod h0.1⟩ }, { rintro ⟨s, hs, rfl⟩, rw [finset.mem_powerset, ← finset.val_le_iff, multiset.to_finset_val] at hs, have hs0 : s.val.prod ≠ 0, { rw [ne.def, multiset.prod_eq_zero_iff], simp only [exists_prop, id.def, exists_eq_right], intro con, apply not_irreducible_zero (irreducible_of_factor 0 (multiset.mem_erase_dup.1 (multiset.mem_of_le hs con))) }, rw [dvd_iff_dvd_of_rel_right (factors_prod h0).symm], refine ⟨⟨multiset.prod_dvd_prod (le_trans hs (multiset.erase_dup_le _)), h0⟩, _⟩, have h := unique_factorization_monoid.factors_unique irreducible_of_factor (λ x hx, irreducible_of_factor x (multiset.mem_of_le (le_trans hs (multiset.erase_dup_le _)) hx)) (factors_prod hs0), rw [associated_eq_eq, multiset.rel_eq] at h, rw [unique_factorization_monoid.squarefree_iff_nodup_factors hs0, h], apply s.nodup } }, { intros x hx y hy h, rw [← finset.val_inj, ← multiset.rel_eq, ← associated_eq_eq], rw [← finset.mem_def, finset.mem_powerset] at hx hy, apply unique_factorization_monoid.factors_unique _ _ (associated_iff_eq.2 h), { intros z hz, apply irreducible_of_factor z, rw ← multiset.mem_to_finset, apply hx hz }, { intros z hz, apply irreducible_of_factor z, rw ← multiset.mem_to_finset, apply hy hz } } end open_locale big_operators lemma sum_divisors_filter_squarefree {n : ℕ} (h0 : n ≠ 0) {α : Type*} [add_comm_monoid α] {f : ℕ → α} : ∑ i in (n.divisors.filter squarefree), f i = ∑ i in (unique_factorization_monoid.factors n).to_finset.powerset, f (i.val.prod) := by rw [finset.sum_eq_multiset_sum, divisors_filter_squarefree h0, multiset.map_map, finset.sum_eq_multiset_sum] end nat
bb2281846fb67fadc934a460691dbcc731efa685
947b78d97130d56365ae2ec264df196ce769371a
/tests/lean/run/34.lean
e2fd9519b586c3000aad55406a37461434f6bfcc
[ "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
152
lean
new_frontend partial def foo : ∀ (n : Nat), StateM Unit Unit | n => if n == 0 then pure () else match n with | 0 => pure () | n+1 => foo n
065697edfe01385207d2282167d0a63067a09144
9dc8cecdf3c4634764a18254e94d43da07142918
/src/topology/sequences.lean
c849be6c687bf3f022ad153f8946843f5f27e999
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
20,282
lean
/- Copyright (c) 2018 Jan-David Salchow. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jan-David Salchow, Patrick Massot, Yury Kudryashov -/ import topology.subset_properties import topology.metric_space.basic /-! # Sequences in topological spaces In this file we define sequences in topological spaces and show how they are related to filters and the topology. ## Main definitions ### Set operation * `seq_closure s`: sequential closure of a set, the set of limits of sequences of points of `s`; ### Predicates * `is_seq_closed s`: predicate saying that a set is sequentially closed, i.e., `seq_closure s ⊆ s`; * `seq_continuous f`: predicate saying that a function is sequentially continuous, i.e., for any sequence `u : ℕ → X` that converges to a point `x`, the sequence `f ∘ u` converges to `f x`; * `is_seq_compact s`: predicate saying that a set is sequentially compact, i.e., every sequence taking values in `s` has a converging subsequence. ### Type classes * `frechet_urysohn_space X`: a typeclass saying that a topological space is a *Fréchet-Urysohn space*, i.e., the sequential closure of any set is equal to its closure. * `sequential_space X`: a typeclass saying that a topological space is a *sequential space*, i.e., any sequentially closed set in this space is closed. This condition is weaker than being a Fréchet-Urysohn space. * `seq_compact_space X`: a typeclass saying that a topological space is sequentially compact, i.e., every sequence in `X` has a converging subsequence. ## Main results * `seq_closure_subset_closure`: closure of a set includes its sequential closure; * `is_closed.is_seq_closed`: a closed set is sequentially closed; * `is_seq_closed.seq_closure_eq`: sequential closure of a sequentially closed set `s` is equal to `s`; * `seq_closure_eq_closure`: in a Fréchet-Urysohn space, the sequential closure of a set is equal to its closure; * `tendsto_nhds_iff_seq_tendsto`, `frechet_urysohn_space.of_seq_tendsto_imp_tendsto`: a topological space is a Fréchet-Urysohn space if and only if sequential convergence implies convergence; * `topological_space.first_countable_topology.frechet_urysohn_space`: every topological space with first countable topology is a Fréchet-Urysohn space; * `frechet_urysohn_space.to_sequential_space`: every Fréchet-Urysohn space is a sequential space; * `is_seq_compact.is_compact`: a sequentially compact set in a uniform space with countably generated uniformity is compact. ## Tags sequentially closed, sequentially compact, sequential space -/ open set function filter topological_space open_locale topological_space variables {X Y : Type*} /-! ### Sequential closures, sequential continuity, and sequential spaces. -/ section topological_space variables [topological_space X] [topological_space Y] /-- The sequential closure of a set `s : set X` in a topological space `X` is the set of all `a : X` which arise as limit of sequences in `s`. Note that the sequential closure of a set is not guaranteed to be sequentially closed. -/ def seq_closure (s : set X) : set X := {a | ∃ x : ℕ → X, (∀ n : ℕ, x n ∈ s) ∧ tendsto x at_top (𝓝 a)} lemma subset_seq_closure {s : set X} : s ⊆ seq_closure s := λ p hp, ⟨const ℕ p, λ _, hp, tendsto_const_nhds⟩ /-- The sequential closure of a set is contained in the closure of that set. The converse is not true. -/ lemma seq_closure_subset_closure {s : set X} : seq_closure s ⊆ closure s := λ p ⟨x, xM, xp⟩, mem_closure_of_tendsto xp (univ_mem' xM) /-- A set `s` is sequentially closed if for any converging sequence `x n` of elements of `s`, the limit belongs to `s` as well. Note that the sequential closure of a set is not guaranteed to be sequentially closed. -/ def is_seq_closed (s : set X) : Prop := ∀ ⦃x : ℕ → X⦄ ⦃p : X⦄, (∀ n, x n ∈ s) → tendsto x at_top (𝓝 p) → p ∈ s /-- The sequential closure of a sequentially closed set is the set itself. -/ lemma is_seq_closed.seq_closure_eq {s : set X} (hs : is_seq_closed s) : seq_closure s = s := subset.antisymm (λ p ⟨x, hx, hp⟩, hs hx hp) subset_seq_closure /-- If a set is equal to its sequential closure, then it is sequentially closed. -/ lemma is_seq_closed_of_seq_closure_eq {s : set X} (hs : seq_closure s = s) : is_seq_closed s := λ x p hxs hxp, hs ▸ ⟨x, hxs, hxp⟩ /-- A set is sequentially closed iff it is equal to its sequential closure. -/ lemma is_seq_closed_iff {s : set X} : is_seq_closed s ↔ seq_closure s = s := ⟨is_seq_closed.seq_closure_eq, is_seq_closed_of_seq_closure_eq⟩ /-- A set is sequentially closed if it is closed. -/ protected lemma is_closed.is_seq_closed {s : set X} (hc : is_closed s) : is_seq_closed s := λ u x hu hx, hc.mem_of_tendsto hx (eventually_of_forall hu) /-- A topological space is called a *Fréchet-Urysohn space*, if the sequential closure of any set is equal to its closure. Since one of the inclusions is trivial, we require only the non-trivial one in the definition. -/ class frechet_urysohn_space (X : Type*) [topological_space X] : Prop := (closure_subset_seq_closure : ∀ s : set X, closure s ⊆ seq_closure s) lemma seq_closure_eq_closure [frechet_urysohn_space X] (s : set X) : seq_closure s = closure s := seq_closure_subset_closure.antisymm $ frechet_urysohn_space.closure_subset_seq_closure s /-- In a Fréchet-Urysohn space, a point belongs to the closure of a set iff it is a limit of a sequence taking values in this set. -/ lemma mem_closure_iff_seq_limit [frechet_urysohn_space X] {s : set X} {a : X} : a ∈ closure s ↔ ∃ x : ℕ → X, (∀ n : ℕ, x n ∈ s) ∧ tendsto x at_top (𝓝 a) := by { rw [← seq_closure_eq_closure], refl } /-- If the domain of a function `f : α → β` is a Fréchet-Urysohn space, then convergence is equivalent to sequential convergence. See also `filter.tendsto_iff_seq_tendsto` for a version that works for any pair of filters assuming that the filter in the domain is countably generated. This property is equivalent to the definition of `frechet_urysohn_space`, see `frechet_urysohn_space.of_seq_tendsto_imp_tendsto`. -/ lemma tendsto_nhds_iff_seq_tendsto [frechet_urysohn_space X] {f : X → Y} {a : X} {b : Y} : tendsto f (𝓝 a) (𝓝 b) ↔ ∀ u : ℕ → X, tendsto u at_top (𝓝 a) → tendsto (f ∘ u) at_top (𝓝 b) := begin refine ⟨λ hf u hu, hf.comp hu, λ h, ((nhds_basis_closeds _).tendsto_iff (nhds_basis_closeds _)).2 _⟩, rintro s ⟨hbs, hsc⟩, refine ⟨closure (f ⁻¹' s), ⟨mt _ hbs, is_closed_closure⟩, λ x, mt $ λ hx, subset_closure hx⟩, rw [← seq_closure_eq_closure], rintro ⟨u, hus, hu⟩, exact hsc.mem_of_tendsto (h u hu) (eventually_of_forall hus) end /-- An alternative construction for `frechet_urysohn_space`: if sequential convergence implies convergence, then the space is a Fréchet-Urysohn space. -/ lemma frechet_urysohn_space.of_seq_tendsto_imp_tendsto (h : ∀ (f : X → Prop) (a : X), (∀ u : ℕ → X, tendsto u at_top (𝓝 a) → tendsto (f ∘ u) at_top (𝓝 (f a))) → continuous_at f a) : frechet_urysohn_space X := begin refine ⟨λ s x hcx, _⟩, specialize h (∉ s) x, by_cases hx : x ∈ s, { exact subset_seq_closure hx }, simp_rw [(∘), continuous_at, hx, not_false_iff, nhds_true, tendsto_pure, eq_true, ← mem_compl_iff, eventually_mem_set, ← mem_interior_iff_mem_nhds, interior_compl] at h, rw [mem_compl_iff, imp_not_comm] at h, simp only [not_forall, not_eventually, mem_compl_iff, not_not] at h, rcases h hcx with ⟨u, hux, hus⟩, rcases extraction_of_frequently_at_top hus with ⟨φ, φ_mono, hφ⟩, exact ⟨u ∘ φ, hφ, hux.comp φ_mono.tendsto_at_top⟩ end /-- Every first-countable space is a Fréchet-Urysohn space. -/ @[priority 100] -- see Note [lower instance priority] instance topological_space.first_countable_topology.frechet_urysohn_space [first_countable_topology X] : frechet_urysohn_space X := frechet_urysohn_space.of_seq_tendsto_imp_tendsto $ λ f a, tendsto_iff_seq_tendsto.2 /-- A topological space is said to be a *sequential space* if any sequentially closed set in this space is closed. This condition is weaker than being a Fréchet-Urysohn space. -/ class sequential_space (X : Type*) [topological_space X] : Prop := (is_closed_of_seq : ∀ s : set X, is_seq_closed s → is_closed s) /-- Every Fréchet-Urysohn space is a sequential space. -/ @[priority 100] -- see Note [lower instance priority] instance frechet_urysohn_space.to_sequential_space [frechet_urysohn_space X] : sequential_space X := ⟨λ s hs, by rw [← closure_eq_iff_is_closed, ← seq_closure_eq_closure, hs.seq_closure_eq]⟩ /-- In a sequential space, a sequentially closed set is closed. -/ protected lemma is_seq_closed.is_closed [sequential_space X] {s : set X} (hs : is_seq_closed s) : is_closed s := sequential_space.is_closed_of_seq s hs /-- In a sequential space, a set is closed iff it's sequentially closed. -/ lemma is_seq_closed_iff_is_closed [sequential_space X] {M : set X} : is_seq_closed M ↔ is_closed M := ⟨is_seq_closed.is_closed, is_closed.is_seq_closed⟩ /-- A function between topological spaces is sequentially continuous if it commutes with limit of convergent sequences. -/ def seq_continuous (f : X → Y) : Prop := ∀ ⦃x : ℕ → X⦄ ⦃p : X⦄, tendsto x at_top (𝓝 p) → tendsto (f ∘ x) at_top (𝓝 (f p)) /-- The preimage of a sequentially closed set under a sequentially continuous map is sequentially closed. -/ lemma is_seq_closed.preimage {f : X → Y} {s : set Y} (hs : is_seq_closed s) (hf : seq_continuous f) : is_seq_closed (f ⁻¹' s) := λ x p hx hp, hs hx (hf hp) /- A continuous function is sequentially continuous. -/ protected lemma continuous.seq_continuous {f : X → Y} (hf : continuous f) : seq_continuous f := λ x p hx, (hf.tendsto p).comp hx /-- A sequentially continuous function defined on a sequential space is continuous. -/ protected lemma seq_continuous.continuous [sequential_space X] {f : X → Y} (hf : seq_continuous f) : continuous f := continuous_iff_is_closed.mpr $ λ s hs, (hs.is_seq_closed.preimage hf).is_closed /-- If the domain of a function is a sequential space, then continuity of this function is equivalent to its sequential continuity. -/ lemma continuous_iff_seq_continuous [sequential_space X] {f : X → Y} : continuous f ↔ seq_continuous f := ⟨continuous.seq_continuous, seq_continuous.continuous⟩ lemma quotient_map.sequential_space [sequential_space X] {f : X → Y} (hf : quotient_map f) : sequential_space Y := ⟨λ s hs, hf.is_closed_preimage.mp $ (hs.preimage $ hf.continuous.seq_continuous).is_closed⟩ /-- The quotient of a sequential space is a sequential space. -/ instance [sequential_space X] {s : setoid X} : sequential_space (quotient s) := quotient_map_quot_mk.sequential_space end topological_space section seq_compact open topological_space topological_space.first_countable_topology variables [topological_space X] /-- A set `s` is sequentially compact if every sequence taking values in `s` has a converging subsequence. -/ def is_seq_compact (s : set X) := ∀ ⦃x : ℕ → X⦄, (∀ n, x n ∈ s) → ∃ (a ∈ s) (φ : ℕ → ℕ), strict_mono φ ∧ tendsto (x ∘ φ) at_top (𝓝 a) /-- A space `X` is sequentially compact if every sequence in `X` has a converging subsequence. -/ class seq_compact_space (X : Type*) [topological_space X] : Prop := (seq_compact_univ : is_seq_compact (univ : set X)) lemma is_seq_compact.subseq_of_frequently_in {s : set X} (hs : is_seq_compact s) {x : ℕ → X} (hx : ∃ᶠ n in at_top, x n ∈ s) : ∃ (a ∈ s) (φ : ℕ → ℕ), strict_mono φ ∧ tendsto (x ∘ φ) at_top (𝓝 a) := let ⟨ψ, hψ, huψ⟩ := extraction_of_frequently_at_top hx, ⟨a, a_in, φ, hφ, h⟩ := hs huψ in ⟨a, a_in, ψ ∘ φ, hψ.comp hφ, h⟩ lemma seq_compact_space.tendsto_subseq [seq_compact_space X] (x : ℕ → X) : ∃ a (φ : ℕ → ℕ), strict_mono φ ∧ tendsto (x ∘ φ) at_top (𝓝 a) := let ⟨a, _, φ, mono, h⟩ := seq_compact_space.seq_compact_univ (λ n, mem_univ (x n)) in ⟨a, φ, mono, h⟩ section first_countable_topology variables [first_countable_topology X] open topological_space.first_countable_topology lemma is_compact.is_seq_compact {s : set X} (hs : is_compact s) : is_seq_compact s := λ x x_in, let ⟨a, a_in, ha⟩ := @hs (map x at_top) _ (le_principal_iff.mpr (univ_mem' x_in : _)) in ⟨a, a_in, tendsto_subseq ha⟩ lemma is_compact.tendsto_subseq' {s : set X} {x : ℕ → X} (hs : is_compact s) (hx : ∃ᶠ n in at_top, x n ∈ s) : ∃ (a ∈ s) (φ : ℕ → ℕ), strict_mono φ ∧ tendsto (x ∘ φ) at_top (𝓝 a) := hs.is_seq_compact.subseq_of_frequently_in hx lemma is_compact.tendsto_subseq {s : set X} {x : ℕ → X} (hs : is_compact s) (hx : ∀ n, x n ∈ s) : ∃ (a ∈ s) (φ : ℕ → ℕ), strict_mono φ ∧ tendsto (x ∘ φ) at_top (𝓝 a) := hs.is_seq_compact hx @[priority 100] -- see Note [lower instance priority] instance first_countable_topology.seq_compact_of_compact [compact_space X] : seq_compact_space X := ⟨compact_univ.is_seq_compact⟩ lemma compact_space.tendsto_subseq [compact_space X] (x : ℕ → X) : ∃ a (φ : ℕ → ℕ), strict_mono φ ∧ tendsto (x ∘ φ) at_top (𝓝 a) := seq_compact_space.tendsto_subseq x end first_countable_topology end seq_compact section uniform_space_seq_compact open_locale uniformity open uniform_space prod variables [uniform_space X] {s : set X} lemma lebesgue_number_lemma_seq {ι : Type*} [is_countably_generated (𝓤 X)] {c : ι → set X} (hs : is_seq_compact s) (hc₁ : ∀ i, is_open (c i)) (hc₂ : s ⊆ ⋃ i, c i) : ∃ V ∈ 𝓤 X, symmetric_rel V ∧ ∀ x ∈ s, ∃ i, ball x V ⊆ c i := begin classical, obtain ⟨V, hV, Vsymm⟩ : ∃ V : ℕ → set (X × X), (𝓤 X).has_antitone_basis V ∧ ∀ n, swap ⁻¹' V n = V n, from uniform_space.has_seq_basis X, rsuffices ⟨n, hn⟩ : ∃ n, ∀ x ∈ s, ∃ i, ball x (V n) ⊆ c i, { exact ⟨V n, hV.to_has_basis.mem_of_mem trivial, Vsymm n, hn⟩ }, by_contradiction H, obtain ⟨x, x_in, hx⟩ : ∃ x : ℕ → X, (∀ n, x n ∈ s) ∧ ∀ n i, ¬ ball (x n) (V n) ⊆ c i, { push_neg at H, choose x hx using H, exact ⟨x, forall_and_distrib.mp hx⟩ }, clear H, obtain ⟨x₀, x₀_in, φ, φ_mono, hlim⟩ : ∃ (x₀ ∈ s) (φ : ℕ → ℕ), strict_mono φ ∧ tendsto (x ∘ φ) at_top (𝓝 x₀), from hs x_in, clear hs, obtain ⟨i₀, x₀_in⟩ : ∃ i₀, x₀ ∈ c i₀, { rcases hc₂ x₀_in with ⟨_, ⟨i₀, rfl⟩, x₀_in_c⟩, exact ⟨i₀, x₀_in_c⟩ }, clear hc₂, obtain ⟨n₀, hn₀⟩ : ∃ n₀, ball x₀ (V n₀) ⊆ c i₀, { rcases (nhds_basis_uniformity hV.to_has_basis).mem_iff.mp (is_open_iff_mem_nhds.mp (hc₁ i₀) _ x₀_in) with ⟨n₀, _, h⟩, use n₀, rwa ← ball_eq_of_symmetry (Vsymm n₀) at h }, clear hc₁, obtain ⟨W, W_in, hWW⟩ : ∃ W ∈ 𝓤 X, W ○ W ⊆ V n₀, from comp_mem_uniformity_sets (hV.to_has_basis.mem_of_mem trivial), obtain ⟨N, x_φ_N_in, hVNW⟩ : ∃ N, x (φ N) ∈ ball x₀ W ∧ V (φ N) ⊆ W, { obtain ⟨N₁, h₁⟩ : ∃ N₁, ∀ n ≥ N₁, x (φ n) ∈ ball x₀ W, from tendsto_at_top'.mp hlim _ (mem_nhds_left x₀ W_in), obtain ⟨N₂, h₂⟩ : ∃ N₂, V (φ N₂) ⊆ W, { rcases hV.to_has_basis.mem_iff.mp W_in with ⟨N, _, hN⟩, use N, exact subset.trans (hV.antitone $ φ_mono.id_le _) hN }, have : φ N₂ ≤ φ (max N₁ N₂), from φ_mono.le_iff_le.mpr (le_max_right _ _), exact ⟨max N₁ N₂, h₁ _ (le_max_left _ _), trans (hV.antitone this) h₂⟩ }, suffices : ball (x (φ N)) (V (φ N)) ⊆ c i₀, from hx (φ N) i₀ this, calc ball (x $ φ N) (V $ φ N) ⊆ ball (x $ φ N) W : preimage_mono hVNW ... ⊆ ball x₀ (V n₀) : ball_subset_of_comp_subset x_φ_N_in hWW ... ⊆ c i₀ : hn₀, end lemma is_seq_compact.totally_bounded (h : is_seq_compact s) : totally_bounded s := begin classical, apply totally_bounded_of_forall_symm, unfold is_seq_compact at h, contrapose! h, rcases h with ⟨V, V_in, V_symm, h⟩, simp_rw [not_subset] at h, have : ∀ (t : set X), t.finite → ∃ a, a ∈ s ∧ a ∉ ⋃ y ∈ t, ball y V, { intros t ht, obtain ⟨a, a_in, H⟩ : ∃ a ∈ s, ∀ x ∈ t, (x, a) ∉ V, by simpa [ht] using h t, use [a, a_in], intro H', obtain ⟨x, x_in, hx⟩ := mem_Union₂.mp H', exact H x x_in hx }, cases seq_of_forall_finite_exists this with u hu, clear h this, simp [forall_and_distrib] at hu, cases hu with u_in hu, use [u, u_in], clear u_in, intros x x_in φ, intros hφ huφ, obtain ⟨N, hN⟩ : ∃ N, ∀ p q, p ≥ N → q ≥ N → (u (φ p), u (φ q)) ∈ V, from huφ.cauchy_seq.mem_entourage V_in, specialize hN N (N+1) (le_refl N) (nat.le_succ N), specialize hu (φ $ N+1) (φ N) (hφ $ lt_add_one N), exact hu hN, end protected lemma is_seq_compact.is_compact [is_countably_generated $ 𝓤 X] (hs : is_seq_compact s) : is_compact s := begin classical, rw is_compact_iff_finite_subcover, intros ι U Uop s_sub, rcases lebesgue_number_lemma_seq hs Uop s_sub with ⟨V, V_in, Vsymm, H⟩, rcases totally_bounded_iff_subset.mp hs.totally_bounded V V_in with ⟨t,t_sub, tfin, ht⟩, have : ∀ x : t, ∃ (i : ι), ball x.val V ⊆ U i, { rintros ⟨x, x_in⟩, exact H x (t_sub x_in) }, choose i hi using this, haveI : fintype t := tfin.fintype, use finset.image i finset.univ, transitivity ⋃ y ∈ t, ball y V, { intros x x_in, specialize ht x_in, rw mem_Union₂ at *, simp_rw ball_eq_of_symmetry Vsymm, exact ht }, { refine Union₂_mono' (λ x x_in, _), exact ⟨i ⟨x, x_in⟩, finset.mem_image_of_mem _ (finset.mem_univ _), hi ⟨x, x_in⟩⟩ }, end /-- A version of Bolzano-Weistrass: in a uniform space with countably generated uniformity filter (e.g., in a metric space), a set is compact if and only if it is sequentially compact. -/ protected lemma uniform_space.compact_iff_seq_compact [is_countably_generated $ 𝓤 X] : is_compact s ↔ is_seq_compact s := ⟨λ H, H.is_seq_compact, λ H, H.is_compact⟩ lemma uniform_space.compact_space_iff_seq_compact_space [is_countably_generated $ 𝓤 X] : compact_space X ↔ seq_compact_space X := have key : is_compact (univ : set X) ↔ is_seq_compact univ := uniform_space.compact_iff_seq_compact, ⟨λ ⟨h⟩, ⟨key.mp h⟩, λ ⟨h⟩, ⟨key.mpr h⟩⟩ end uniform_space_seq_compact section metric_seq_compact variables [pseudo_metric_space X] open metric lemma seq_compact.lebesgue_number_lemma_of_metric {ι : Sort*} {c : ι → set X} {s : set X} (hs : is_seq_compact s) (hc₁ : ∀ i, is_open (c i)) (hc₂ : s ⊆ ⋃ i, c i) : ∃ δ > 0, ∀ a ∈ s, ∃ i, ball a δ ⊆ c i := lebesgue_number_lemma_of_metric hs.is_compact hc₁ hc₂ variables [proper_space X] {s : set X} /-- A version of **Bolzano-Weistrass**: in a proper metric space (eg. $ℝ^n$), every bounded sequence has a converging subsequence. This version assumes only that the sequence is frequently in some bounded set. -/ lemma tendsto_subseq_of_frequently_bounded (hs : bounded s) {x : ℕ → X} (hx : ∃ᶠ n in at_top, x n ∈ s) : ∃ a ∈ closure s, ∃ φ : ℕ → ℕ, strict_mono φ ∧ tendsto (x ∘ φ) at_top (𝓝 a) := have hcs : is_seq_compact (closure s), from hs.is_compact_closure.is_seq_compact, have hu' : ∃ᶠ n in at_top, x n ∈ closure s, from hx.mono (λ n hn, subset_closure hn), hcs.subseq_of_frequently_in hu' /-- A version of Bolzano-Weistrass: in a proper metric space (eg. $ℝ^n$), every bounded sequence has a converging subsequence. -/ lemma tendsto_subseq_of_bounded (hs : bounded s) {x : ℕ → X} (hx : ∀ n, x n ∈ s) : ∃ a ∈ closure s, ∃ φ : ℕ → ℕ, strict_mono φ ∧ tendsto (x ∘ φ) at_top (𝓝 a) := tendsto_subseq_of_frequently_bounded hs $ frequently_of_forall hx end metric_seq_compact
7abf2f21862176420c25cc76e8c46bd8a6fee3df
3618c6e11aa822fd542440674dfb9a7b9921dba0
/src/golf.lean
19ebfdcfcaeb834d75de3a964a892ad47bd01802
[]
no_license
ChrisHughes24/single_relation
99ceedcc02d236ce46d6c65d72caa669857533c5
057e157a59de6d0e43b50fcb537d66792ec20450
refs/heads/master
1,683,652,062,698
1,683,360,089,000
1,683,360,089,000
279,346,432
0
0
null
null
null
null
UTF-8
Lean
false
false
3,394
lean
import initial import P import order.lexicographic open free_group multiplicative semidirect_product variables {ι : Type} [decidable_eq ι] [has_lt ι] [decidable_rel ((<) : ι → ι → Prop)] def lex_length : Π (w₁ w₂ : free_group ι), Prop := λ w₁ w₂, prod.lex (<) (list.lex (λ i₁ i₂ : Σ i : ι, C∞, prod.lex (<) (<) (i₁.2.to_add.nat_abs, i₁.1) (i₂.2.to_add.nat_abs, i₂.1))) (w₁.to_list.length, w₁.to_list) (w₂.to_list.length, w₂.to_list) instance lex_length_decidable : decidable_rel (@lex_length ι _ _ _) := by dunfold lex_length; apply_instance meta def golf_single_aux (r : free_group ι) : Π (w : free_group ι), free_group ι | w := let wr := w * r in if h : lex_length wr w then golf_single_aux wr else w -- using_well_founded { rel_tac := λ _ _, `[exact ⟨_, measure_wf psigma.snd⟩] } /-- Returns the shortest word of the form `w * r^n` with `n ∈ ℤ` -/ meta def golf_single (r : free_group ι) (w : free_group ι) : free_group ι := let wr := w * r in -- let wrl := wr.to_list.length in -- let wl := w.to_list.length in if lex_length wr w then golf_single_aux r wr else let rn := r⁻¹ in let wrn := w * rn in -- let wrnl := wrn.to_list.length in if lex_length wrn w then golf_single_aux rn wrn else w meta def golf₁ (r : free_group ι) (p : P (free_group ι)) : P (free_group ι) := ⟨free_group.map (golf_single r) p.left, p.right⟩ /-- Returns the shortest word of the form `r^n * w` with `n ∈ ℕ` -/ meta def golf_right (r : free_group ι) (max : ℕ) : Π (w : free_group ι), free_group ι × ℕ | w := let rw := r * w in if h : lex_length rw w then let g := golf_right rw in if g.2 < max then (g.1, g.2 + 1) else (rw, g.2) else (w, 0) meta def golf₂_core (r : free_group ι) : Π (p₁ p₂ : free_group (free_group ι)), free_group (free_group ι) | ⟨[], _⟩ ⟨p₂, _⟩ := of_list p₂ | ⟨(w::l), _⟩ ⟨[], _⟩ := golf₂_core (of_list l) (of_list [w]) | ⟨(⟨w₁,a⟩::l₁), _⟩ ⟨(⟨w₂,b⟩::l₂), _⟩ := if w₁ = w₂ then if a * b = 1 then golf₂_core (of_list l₁) (of_list l₂) else golf₂_core (of_list l₁) (of_list (⟨w₁, a * b⟩ :: l₂)) else let ε := (to_add a).sign in let w₁rw₁ := w₁ * (r ^ ε) * w₁⁻¹ in let (g, n) := golf_right w₁rw₁ (to_add a).nat_abs w₂ in if n ≠ 0 then golf₂_core (of_list [⟨w₁, of_add (ε * n)⟩] * of_list [⟨g, b⟩] * of' w₁ (of_add (to_add a - ε * n)) * of_list l₁) (of_list l₂) else let ε := (to_add b).sign in let w₂rw₂ := w₂ * (r ^ (-ε)) * w₂⁻¹ in let (g, n) := golf_right w₂rw₂ (to_add b).nat_abs w₁ in if n ≠ 0 then golf₂_core (of' w₂ (of_add (to_add b - ε * n)) * of_list [⟨g, a⟩] * of_list [⟨w₂, of_add (ε * n)⟩] * of_list l₁) (of_list l₂) else golf₂_core (of_list l₁) (of_list (⟨w₁, a⟩ :: ⟨w₂, b⟩ :: l₂)) meta def golf₂ (r : free_group ι) (p : P (free_group ι)) : P (free_group ι) := ⟨golf₂_core r (of_list p.left.to_list.reverse) 1, p.right⟩
35bbf672dbdced476a36340375a40434bffffa91
8e6cad62ec62c6c348e5faaa3c3f2079012bdd69
/src/group_theory/solvable.lean
f460f4a13707facd2a99813cc367049934e708c0
[ "Apache-2.0" ]
permissive
benjamindavidson/mathlib
8cc81c865aa8e7cf4462245f58d35ae9a56b150d
fad44b9f670670d87c8e25ff9cdf63af87ad731e
refs/heads/master
1,679,545,578,362
1,615,343,014,000
1,615,343,014,000
312,926,983
0
0
Apache-2.0
1,615,360,301,000
1,605,399,418,000
Lean
UTF-8
Lean
false
false
9,922
lean
/- Copyright (c) 2021 Jordan Brown, Thomas Browning and Patrick Lutz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jordan Brown, Thomas Browning and Patrick Lutz -/ import group_theory.abelianization import data.bracket /-! # Solvable Groups In this file we introduce the notion of a solvable group. We define a solvable group as one whose derived series is eventually trivial. This requires defining the commutator of two subgroups and the derived series of a group. ## Main definitions * `general_commutator H₁ H₂` : the commutator of the subgroups `H₁` and `H₂` * `derived_series G n` : the `n`th term in the derived series of `G`, defined by iterating `general_commutator` starting with the top subgroup * `is_solvable G` : the group `G` is solvable -/ open subgroup variables {G : Type*} [group G] section general_commutator /-- The commutator of two subgroups `H₁` and `H₂`. -/ instance general_commutator : has_bracket (subgroup G) (subgroup G) := ⟨λ H₁ H₂, closure {x | ∃ (p ∈ H₁) (q ∈ H₂), p * q * p⁻¹ * q⁻¹ = x}⟩ lemma general_commutator_def (H₁ H₂ : subgroup G) : ⁅H₁, H₂⁆ = closure {x | ∃ (p ∈ H₁) (q ∈ H₂), p * q * p⁻¹ * q⁻¹ = x} := rfl instance general_commutator_normal (H₁ H₂ : subgroup G) [h₁ : H₁.normal] [h₂ : H₂.normal] : normal ⁅H₁, H₂⁆ := begin let base : set G := {x | ∃ (p ∈ H₁) (q ∈ H₂), p * q * p⁻¹ * q⁻¹ = x}, suffices h_base : base = group.conjugates_of_set base, { dsimp only [general_commutator_def, ←base], rw h_base, exact subgroup.normal_closure_normal }, apply set.subset.antisymm group.subset_conjugates_of_set, intros a h, rw group.mem_conjugates_of_set_iff at h, rcases h with ⟨b, ⟨c, hc, e, he, rfl⟩, d, rfl⟩, exact ⟨d * c * d⁻¹, h₁.conj_mem c hc d, d * e * d⁻¹, h₂.conj_mem e he d, by group⟩, end lemma general_commutator_mono {H₁ H₂ K₁ K₂ : subgroup G} (h₁ : H₁ ≤ K₁) (h₂ : H₂ ≤ K₂) : ⁅H₁, H₂⁆ ≤ ⁅K₁, K₂⁆ := begin apply closure_mono, rintros x ⟨p, hp, q, hq, rfl⟩, exact ⟨p, h₁ hp, q, h₂ hq, rfl⟩, end lemma general_commutator_def' (H₁ H₂ : subgroup G) [H₁.normal] [H₂.normal] : ⁅H₁, H₂⁆ = normal_closure {x | ∃ (p ∈ H₁) (q ∈ H₂), p * q * p⁻¹ * q⁻¹ = x} := by rw [← normal_closure_eq_self ⁅H₁, H₂⁆, general_commutator_def, normal_closure_closure_eq_normal_closure] lemma general_commutator_le (H₁ H₂ : subgroup G) (K : subgroup G) : ⁅H₁, H₂⁆ ≤ K ↔ ∀ (p ∈ H₁) (q ∈ H₂), p * q * p⁻¹ * q⁻¹ ∈ K := begin rw [general_commutator, closure_le], split, { intros h p hp q hq, exact h ⟨p, hp, q, hq, rfl⟩, }, { rintros h x ⟨p, hp, q, hq, rfl⟩, exact h p hp q hq, } end lemma general_commutator_comm (H₁ H₂ : subgroup G) : ⁅H₁, H₂⁆ = ⁅H₂, H₁⁆ := begin suffices : ∀ H₁ H₂ : subgroup G, ⁅H₁, H₂⁆ ≤ ⁅H₂, H₁⁆, { exact le_antisymm (this _ _) (this _ _) }, intros H₁ H₂, rw general_commutator_le, intros p hp q hq, have h : (p * q * p⁻¹ * q⁻¹)⁻¹ ∈ ⁅H₂, H₁⁆ := subset_closure ⟨q, hq, p, hp, by group⟩, convert inv_mem ⁅H₂, H₁⁆ h, group, end lemma general_commutator_le_right (H₁ H₂ : subgroup G) [h : normal H₂] : ⁅H₁, H₂⁆ ≤ H₂ := begin rw general_commutator_le, intros p hp q hq, exact mul_mem H₂ (h.conj_mem q hq p) (inv_mem H₂ hq), end lemma general_commutator_le_left (H₁ H₂ : subgroup G) [h : normal H₁] : ⁅H₁, H₂⁆ ≤ H₁ := begin rw general_commutator_comm, exact general_commutator_le_right H₂ H₁, end @[simp] lemma general_commutator_bot (H : subgroup G) : ⁅H, ⊥⁆ = (⊥ : subgroup G) := by { rw eq_bot_iff, exact general_commutator_le_right H ⊥ } @[simp] lemma bot_general_commutator (H : subgroup G) : ⁅(⊥ : subgroup G), H⁆ = (⊥ : subgroup G) := by { rw eq_bot_iff, exact general_commutator_le_left ⊥ H } lemma general_commutator_le_inf (H₁ H₂ : subgroup G) [normal H₁] [normal H₂] : ⁅H₁, H₂⁆ ≤ H₁ ⊓ H₂ := by simp only [general_commutator_le_left, general_commutator_le_right, le_inf_iff, and_self] end general_commutator section derived_series variables (G) /-- The derived series of the group `G`, obtained by starting from the subgroup `⊤` and repeatedly taking the commutator of the previous subgroup with itself for `n` times. -/ def derived_series : ℕ → subgroup G | 0 := ⊤ | (n + 1) := ⁅(derived_series n), (derived_series n)⁆ @[simp] lemma derived_series_zero : derived_series G 0 = ⊤ := rfl @[simp] lemma derived_series_succ (n : ℕ) : derived_series G (n + 1) = ⁅(derived_series G n), (derived_series G n)⁆ := rfl lemma derived_series_normal (n : ℕ) : (derived_series G n).normal := begin induction n with n ih, { exact subgroup.top_normal, }, { rw derived_series_succ, exactI general_commutator_normal (derived_series G n) (derived_series G n), } end @[simp] lemma general_commutator_eq_commutator : ⁅(⊤ : subgroup G), (⊤ : subgroup G)⁆ = commutator G := begin rw [commutator, general_commutator_def'], apply le_antisymm; apply normal_closure_mono, { exact λ x ⟨p, _, q, _, h⟩, ⟨p, q, h⟩, }, { exact λ x ⟨p, q, h⟩, ⟨p, mem_top p, q, mem_top q, h⟩, } end lemma commutator_def' : commutator G = subgroup.closure {x : G | ∃ p q, p * q * p⁻¹ * q⁻¹ = x} := begin rw [← general_commutator_eq_commutator, general_commutator], apply le_antisymm; apply closure_mono, { exact λ x ⟨p, _, q, _, h⟩, ⟨p, q, h⟩ }, { exact λ x ⟨p, q, h⟩, ⟨p, mem_top p, q, mem_top q, h⟩ } end @[simp] lemma derived_series_one : derived_series G 1 = commutator G := general_commutator_eq_commutator G end derived_series section commutator_map variables {G} {G' : Type*} [group G'] {f : G →* G'} lemma map_commutator_eq_commutator_map (H₁ H₂ : subgroup G) : ⁅H₁, H₂⁆.map f = ⁅H₁.map f, H₂.map f⁆ := begin rw [general_commutator, general_commutator, monoid_hom.map_closure], apply le_antisymm; apply closure_mono, { rintros _ ⟨x, ⟨p, hp, q, hq, rfl⟩, rfl⟩, refine ⟨f p, mem_map.mpr ⟨p, hp, rfl⟩, f q, mem_map.mpr ⟨q, hq, rfl⟩, by simp *⟩, }, { rintros x ⟨_, ⟨p, hp, rfl⟩, _, ⟨q, hq, rfl⟩, rfl⟩, refine ⟨p * q * p⁻¹ * q⁻¹, ⟨p, hp, q, hq, rfl⟩, by simp *⟩, }, end lemma commutator_le_map_commutator {H₁ H₂ : subgroup G} {K₁ K₂ : subgroup G'} (h₁ : K₁ ≤ H₁.map f) (h₂ : K₂ ≤ H₂.map f) : ⁅K₁, K₂⁆ ≤ ⁅H₁, H₂⁆.map f := by { rw map_commutator_eq_commutator_map, exact general_commutator_mono h₁ h₂ } section derived_series_map variables (f) lemma map_derived_series_le_derived_series (n : ℕ) : (derived_series G n).map f ≤ derived_series G' n := begin induction n with n ih, { simp only [derived_series_zero, le_top], }, { simp only [derived_series_succ, map_commutator_eq_commutator_map, general_commutator_mono, *], } end variables {f} lemma derived_series_le_map_derived_series (hf : function.surjective f) (n : ℕ) : derived_series G' n ≤ (derived_series G n).map f := begin induction n with n ih, { rwa [derived_series_zero, derived_series_zero, top_le_iff, ← monoid_hom.range_eq_map, ← monoid_hom.range_top_iff_surjective.mpr], }, { simp only [*, derived_series_succ, commutator_le_map_commutator], } end lemma map_derived_series_eq (hf : function.surjective f) (n : ℕ) : (derived_series G n).map f = derived_series G' n := le_antisymm (map_derived_series_le_derived_series f n) (derived_series_le_map_derived_series hf n) end derived_series_map end commutator_map section solvable variables (G) /-- A group `G` is solvable if its derived series is eventually trivial. We use this definition because it's the most convenient one to work with. -/ class is_solvable : Prop := (solvable : ∃ n : ℕ, derived_series G n = ⊥) lemma is_solvable_def : is_solvable G ↔ ∃ n : ℕ, derived_series G n = ⊥ := ⟨λ h, h.solvable, λ h, ⟨h⟩⟩ @[priority 100] instance is_solvable_of_comm {G : Type*} [comm_group G] : is_solvable G := begin use 1, rw [eq_bot_iff, derived_series_one], calc commutator G ≤ (monoid_hom.id G).ker : abelianization.commutator_subset_ker (monoid_hom.id G) ... = ⊥ : rfl, end lemma is_solvable_of_top_eq_bot (h : (⊤ : subgroup G) = ⊥) : is_solvable G := ⟨⟨0, h⟩⟩ @[priority 100] instance is_solvable_of_subsingleton [subsingleton G] : is_solvable G := is_solvable_of_top_eq_bot G (by ext; simp at *) variables {G} {G' : Type*} [group G'] {f : G →* G'} lemma solvable_of_solvable_injective (hf : function.injective f) [h : is_solvable G'] : is_solvable G := begin rw is_solvable_def at *, cases h with n hn, use n, rw ← map_eq_bot_iff hf, rw eq_bot_iff at *, calc map f (derived_series G n) ≤ derived_series G' n : map_derived_series_le_derived_series f n ... ≤ ⊥ : hn, end instance subgroup_solvable_of_solvable (H : subgroup G) [h : is_solvable G] : is_solvable H := solvable_of_solvable_injective (show function.injective (subtype H), from subtype.val_injective) lemma solvable_of_surjective (hf : function.surjective f) [h : is_solvable G] : is_solvable G' := begin rw is_solvable_def at *, cases h with n hn, use n, calc derived_series G' n = (derived_series G n).map f : eq.symm (map_derived_series_eq hf n) ... = (⊥ : subgroup G).map f : by rw hn ... = ⊥ : map_bot f, end instance solvable_quotient_of_solvable (H : subgroup G) [H.normal] [h : is_solvable G] : is_solvable (quotient_group.quotient H) := solvable_of_surjective (show function.surjective (quotient_group.mk' H), by tidy) end solvable
4e8fdc2ba9dfe3948d2e88dfbdf30b770a83ceb4
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/stage0/src/Lean/Linter/Builtin.lean
e1f10a05cfa91b7959a2f89b9859dbd2730e1182
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
EdAyers/lean4
57ac632d6b0789cb91fab2170e8c9e40441221bd
37ba0df5841bde51dbc2329da81ac23d4f6a4de4
refs/heads/master
1,676,463,245,298
1,660,619,433,000
1,660,619,433,000
183,433,437
1
0
Apache-2.0
1,657,612,672,000
1,556,196,574,000
Lean
UTF-8
Lean
false
false
1,205
lean
import Lean.Linter.Util namespace Lean.Linter register_builtin_option linter.suspiciousUnexpanderPatterns : Bool := { defValue := true, descr := "enable the 'suspicious unexpander patterns' linter" } def getLinterSuspiciousUnexpanderPatterns (o : Options) : Bool := getLinterValue linter.suspiciousUnexpanderPatterns o def suspiciousUnexpanderPatterns : Linter := fun cmdStx => do unless getLinterSuspiciousUnexpanderPatterns (← getOptions) do return -- check `[appUnexpander _]` defs defined by pattern matching let `($[$_:docComment]? @[$[$attrs:attr],*] $(_vis)? def $_ : $_ $[| $pats => $_]*) := cmdStx | return unless attrs.any (· matches `(attr| appUnexpander $_)) do return for pat in pats do let patHead ← match pat with | `(`($patHead:ident $_args*)) => pure patHead | `(`($patHead:ident)) => pure patHead | _ => continue logLint linter.suspiciousUnexpanderPatterns patHead "Unexpanders should match the function name against an antiquotation `$_` so as to be independent of the specific pretty printing of the name." builtin_initialize addLinter suspiciousUnexpanderPatterns end Lean.Linter
2177eeabfd1a594eb0f660834456a4e17d8dc563
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/04_Quantifiers_and_Equality.org.1.lean
043105b02f26ffe2cbe38f2ca32ff4af26a26a22
[]
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
212
lean
/- page 48 -/ import standard variables (A : Type) (p q : A → Prop) example : (∀ x : A, p x ∧ q x) → ∀ y : A, p y := assume H : ∀ x : A, p x ∧ q x, take y : A, show p y, from and.elim_left (H y)
3900ccf605e26f073d45578a895b024bcf36c13b
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/archive/wiedijk_100_theorems/ascending_descending_sequences.lean
14232f57243c4b28e657c523118ba4eb6b4ef9d5
[ "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
8,155
lean
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import data.fintype.powerset /-! # Erdős–Szekeres theorem > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file proves Theorem 73 from the [100 Theorems List](https://www.cs.ru.nl/~freek/100/), also known as the Erdős–Szekeres theorem: given a sequence of more than `r * s` distinct values, there is an increasing sequence of length longer than `r` or a decreasing sequence of length longer than `s`. We use the proof outlined at https://en.wikipedia.org/wiki/Erdos-Szekeres_theorem#Pigeonhole_principle. ## Tags sequences, increasing, decreasing, Ramsey, Erdos-Szekeres, Erdős–Szekeres, Erdős-Szekeres -/ variables {α : Type*} [linear_order α] {β : Type*} open function finset namespace theorems_100 /-- **Erdős–Szekeres Theorem**: Given a sequence of more than `r * s` distinct values, there is an increasing sequence of length longer than `r` or a decreasing sequence of length longer than `s`. Proof idea: We label each value in the sequence with two numbers specifying the longest increasing subsequence ending there, and the longest decreasing subsequence ending there. We then show the pair of labels must be unique. Now if there is no increasing sequence longer than `r` and no decreasing sequence longer than `s`, then there are at most `r * s` possible labels, which is a contradiction if there are more than `r * s` elements. -/ theorem erdos_szekeres {r s n : ℕ} {f : fin n → α} (hn : r * s < n) (hf : injective f) : (∃ (t : finset (fin n)), r < t.card ∧ strict_mono_on f ↑t) ∨ (∃ (t : finset (fin n)), s < t.card ∧ strict_anti_on f ↑t) := begin -- Given an index `i`, produce the set of increasing (resp., decreasing) subsequences which ends -- at `i`. let inc_sequences_ending_in : fin n → finset (finset (fin n)) := λ i, univ.powerset.filter (λ t, finset.max t = i ∧ strict_mono_on f ↑t), let dec_sequences_ending_in : fin n → finset (finset (fin n)) := λ i, univ.powerset.filter (λ t, finset.max t = i ∧ strict_anti_on f ↑t), -- The singleton sequence is in both of the above collections. -- (This is useful to show that the maximum length subsequence is at least 1, and that the set -- of subsequences is nonempty.) have inc_i : ∀ i, {i} ∈ inc_sequences_ending_in i := λ i, by simp [strict_mono_on], have dec_i : ∀ i, {i} ∈ dec_sequences_ending_in i := λ i, by simp [strict_anti_on], -- Define the pair of labels: at index `i`, the pair is the maximum length of an increasing -- subsequence ending at `i`, paired with the maximum length of a decreasing subsequence ending -- at `i`. -- We call these labels `(a_i, b_i)`. let ab : fin n → ℕ × ℕ, { intro i, apply (max' ((inc_sequences_ending_in i).image card) (nonempty.image ⟨{i}, inc_i i⟩ _), max' ((dec_sequences_ending_in i).image card) (nonempty.image ⟨{i}, dec_i i⟩ _)) }, -- It now suffices to show that one of the labels is 'big' somewhere. In particular, if the -- first in the pair is more than `r` somewhere, then we have an increasing subsequence in our -- set, and if the second is more than `s` somewhere, then we have a decreasing subsequence. rsuffices ⟨i, hi⟩ : ∃ i, r < (ab i).1 ∨ s < (ab i).2, { apply or.imp _ _ hi, work_on_goal 1 { have : (ab i).1 ∈ _ := max'_mem _ _ }, work_on_goal 2 { have : (ab i).2 ∈ _ := max'_mem _ _ }, all_goals { intro hi, rw mem_image at this, obtain ⟨t, ht₁, ht₂⟩ := this, refine ⟨t, by rwa ht₂, _⟩, rw mem_filter at ht₁, apply ht₁.2.2 } }, -- Show first that the pair of labels is unique. have : injective ab, { apply injective_of_lt_imp_ne, intros i j k q, injection q with q₁ q₂, -- We have two cases: `f i < f j` or `f j < f i`. -- In the former we'll show `a_i < a_j`, and in the latter we'll show `b_i < b_j`. cases lt_or_gt_of_ne (λ _, ne_of_lt ‹i < j› (hf ‹f i = f j›)), work_on_goal 1 { apply ne_of_lt _ q₁, have : (ab i).1 ∈ _ := max'_mem _ _ }, work_on_goal 2 { apply ne_of_lt _ q₂, have : (ab i).2 ∈ _ := max'_mem _ _ }, all_goals { -- Reduce to showing there is a subsequence of length `a_i + 1` which ends at `j`. rw nat.lt_iff_add_one_le, apply le_max', rw mem_image at this ⊢, -- In particular we take the subsequence `t` of length `a_i` which ends at `i`, by definition -- of `a_i` rcases this with ⟨t, ht₁, ht₂⟩, rw mem_filter at ht₁, -- Ensure `t` ends at `i`. have : t.max = i, simp [ht₁.2.1], -- Now our new subsequence is given by adding `j` at the end of `t`. refine ⟨insert j t, _, _⟩, -- First make sure it's valid, i.e., that this subsequence ends at `j` and is increasing { rw mem_filter, refine ⟨_, _, _⟩, { rw mem_powerset, apply subset_univ }, -- It ends at `j` since `i < j`. { convert max_insert, rw [ht₁.2.1, max_eq_left], apply with_bot.coe_le_coe.mpr (le_of_lt ‹i < j›) }, -- To show it's increasing (i.e., `f` is monotone increasing on `t.insert j`), we do cases -- on what the possibilities could be - either in `t` or equals `j`. simp only [strict_mono_on, strict_anti_on, coe_insert, set.mem_insert_iff, mem_coe], -- Most of the cases are just bashes. rintros x ⟨rfl | _⟩ y ⟨rfl | _⟩ _, { apply (irrefl _ ‹j < j›).elim }, { exfalso, apply not_le_of_lt (trans ‹i < j› ‹j < y›) (le_max_of_eq ‹y ∈ t› ‹t.max = i›) }, { apply lt_of_le_of_lt _ ‹f i < f j› <|> apply lt_of_lt_of_le ‹f j < f i› _, rcases lt_or_eq_of_le (le_max_of_eq ‹x ∈ t› ‹t.max = i›) with _ | rfl, { apply le_of_lt (ht₁.2.2 ‹x ∈ t› (mem_of_max ‹t.max = i›) ‹x < i›) }, { refl } }, { apply ht₁.2.2 ‹x ∈ t› ‹y ∈ t› ‹x < y› } }, -- Finally show that this new subsequence is one longer than the old one. { rw [card_insert_of_not_mem, ht₂], intro _, apply not_le_of_lt ‹i < j› (le_max_of_eq ‹j ∈ t› ‹t.max = i›) } } }, -- Finished both goals! -- Now that we have uniqueness of each label, it remains to do some counting to finish off. -- Suppose all the labels are small. by_contra q, push_neg at q, -- Then the labels `(a_i, b_i)` all fit in the following set: `{ (x,y) | 1 ≤ x ≤ r, 1 ≤ y ≤ s }` let ran : finset (ℕ × ℕ) := (range r).image nat.succ ×ˢ (range s).image nat.succ, -- which we prove here. have : image ab univ ⊆ ran, -- First some logical shuffling { rintro ⟨x₁, x₂⟩, simp only [mem_image, exists_prop, mem_range, mem_univ, mem_product, true_and, prod.mk.inj_iff], rintros ⟨i, rfl, rfl⟩, specialize q i, -- Show `1 ≤ a_i` and `1 ≤ b_i`, which is easy from the fact that `{i}` is a increasing and -- decreasing subsequence which we did right near the top. have z : 1 ≤ (ab i).1 ∧ 1 ≤ (ab i).2, { split; { apply le_max', rw mem_image, refine ⟨{i}, by solve_by_elim, card_singleton i⟩ } }, refine ⟨_, _⟩, -- Need to get `a_i ≤ r`, here phrased as: there is some `a < r` with `a+1 = a_i`. { refine ⟨(ab i).1 - 1, _, nat.succ_pred_eq_of_pos z.1⟩, rw tsub_lt_iff_right z.1, apply nat.lt_succ_of_le q.1 }, { refine ⟨(ab i).2 - 1, _, nat.succ_pred_eq_of_pos z.2⟩, rw tsub_lt_iff_right z.2, apply nat.lt_succ_of_le q.2 } }, -- To get our contradiction, it suffices to prove `n ≤ r * s` apply not_le_of_lt hn, -- Which follows from considering the cardinalities of the subset above, since `ab` is injective. simpa [nat.succ_injective, card_image_of_injective, ‹injective ab›] using card_le_of_subset this, end end theorems_100
3d53d5b4a5ca6c8525b29f0d9b67c7614fb9fd1d
c777c32c8e484e195053731103c5e52af26a25d1
/src/measure_theory/covering/vitali.lean
16df444849fe1ebf7e3b642fcd3391a49b8164c8
[ "Apache-2.0" ]
permissive
kbuzzard/mathlib
2ff9e85dfe2a46f4b291927f983afec17e946eb8
58537299e922f9c77df76cb613910914a479c1f7
refs/heads/master
1,685,313,702,744
1,683,974,212,000
1,683,974,212,000
128,185,277
1
0
null
1,522,920,600,000
1,522,920,600,000
null
UTF-8
Lean
false
false
25,941
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 topology.metric_space.basic import measure_theory.constructions.borel_space import measure_theory.covering.vitali_family /-! # Vitali covering theorems The topological Vitali covering theorem, in its most classical version, states the following. Consider a family of balls `(B (x_i, r_i))_{i ∈ I}` in a metric space, with uniformly bounded radii. Then one can extract a disjoint subfamily indexed by `J ⊆ I`, such that any `B (x_i, r_i)` is included in a ball `B (x_j, 5 r_j)`. We prove this theorem in `vitali.exists_disjoint_subfamily_covering_enlargment_closed_ball`. It is deduced from a more general version, called `vitali.exists_disjoint_subfamily_covering_enlargment`, which applies to any family of sets together with a size function `δ` (think "radius" or "diameter"). We deduce the measurable Vitali covering theorem. Assume one is given a family `t` of closed sets with nonempty interior, such that each `a ∈ t` is included in a ball `B (x, r)` and covers a definite proportion of the ball `B (x, 6 r)` for a given measure `μ` (think of the situation where `μ` is a doubling measure and `t` is a family of balls). Consider a set `s` at which the family is fine, i.e., every point of `s` belongs to arbitrarily small elements of `t`. Then one can extract from `t` a disjoint subfamily that covers almost all `s`. It is proved in `vitali.exists_disjoint_covering_ae`. A way to restate this theorem is to say that the set of closed sets `a` with nonempty interior covering a fixed proportion `1/C` of the ball `closed_ball x (3 * diam a)` forms a Vitali family. This version is given in `vitali.vitali_family`. -/ variables {α ι : Type*} open set metric measure_theory topological_space filter open_locale nnreal classical ennreal topology namespace vitali /-- Vitali covering theorem: given a set `t` of subsets of a type, one may extract a disjoint subfamily `u` such that the `τ`-enlargment of this family covers all elements of `t`, where `τ > 1` is any fixed number. When `t` is a family of balls, the `τ`-enlargment of `ball x r` is `ball x ((1+2τ) r)`. In general, it is expressed in terms of a function `δ` (think "radius" or "diameter"), positive and bounded on all elements of `t`. The condition is that every element `a` of `t` should intersect an element `b` of `u` of size larger than that of `a` up to `τ`, i.e., `δ b ≥ δ a / τ`. We state the lemma slightly more generally, with an indexed family of sets `B a` for `a ∈ t`, for wider applicability. -/ theorem exists_disjoint_subfamily_covering_enlargment (B : ι → set α) (t : set ι) (δ : ι → ℝ) (τ : ℝ) (hτ : 1 < τ) (δnonneg : ∀ a ∈ t, 0 ≤ δ a) (R : ℝ) (δle : ∀ a ∈ t, δ a ≤ R) (hne : ∀ a ∈ t, (B a).nonempty) : ∃ u ⊆ t, u.pairwise_disjoint B ∧ ∀ a ∈ t, ∃ b ∈ u, (B a ∩ B b).nonempty ∧ δ a ≤ τ * δ b := begin /- The proof could be formulated as a transfinite induction. First pick an element of `t` with `δ` as large as possible (up to a factor of `τ`). Then among the remaining elements not intersecting the already chosen one, pick another element with large `δ`. Go on forever (transfinitely) until there is nothing left. Instead, we give a direct Zorn-based argument. Consider a maximal family `u` of disjoint sets with the following property: if an element `a` of `t` intersects some element `b` of `u`, then it intersects some `b' ∈ u` with `δ b' ≥ δ a / τ`. Such a maximal family exists by Zorn. If this family did not intersect some element `a ∈ t`, then take an element `a' ∈ t` which does not intersect any element of `u`, with `δ a'` almost as large as possible. One checks easily that `u ∪ {a'}` still has this property, contradicting the maximality. Therefore, `u` intersects all elements of `t`, and by definition it satisfies all the desired properties. -/ let T : set (set ι) := {u | u ⊆ t ∧ u.pairwise_disjoint B ∧ ∀ a ∈ t, ∀ b ∈ u, (B a ∩ B b).nonempty → ∃ c ∈ u, (B a ∩ B c).nonempty ∧ δ a ≤ τ * δ c}, -- By Zorn, choose a maximal family in the good set `T` of disjoint families. obtain ⟨u, uT, hu⟩ : ∃ u ∈ T, ∀ v ∈ T, u ⊆ v → v = u, { refine zorn_subset _ (λ U UT hU, _), refine ⟨⋃₀ U, _, λ s hs, subset_sUnion_of_mem hs⟩, simp only [set.sUnion_subset_iff, and_imp, exists_prop, forall_exists_index, mem_sUnion, set.mem_set_of_eq], refine ⟨λ u hu, (UT hu).1, (pairwise_disjoint_sUnion hU.directed_on).2 (λ u hu, (UT hu).2.1), λ a hat b u uU hbu hab, _⟩, obtain ⟨c, cu, ac, hc⟩ : ∃ (c : ι) (H : c ∈ u), (B a ∩ B c).nonempty ∧ δ a ≤ τ * δ c := (UT uU).2.2 a hat b hbu hab, exact ⟨c, ⟨u, uU, cu⟩, ac, hc⟩ }, -- the only nontrivial bit is to check that every `a ∈ t` intersects an element `b ∈ u` with -- comparatively large `δ b`. Assume this is not the case, then we will contradict the maximality. refine ⟨u, uT.1, uT.2.1, λ a hat, _⟩, contrapose! hu, have a_disj : ∀ c ∈ u, disjoint (B a) (B c), { assume c hc, by_contra, rw not_disjoint_iff_nonempty_inter at h, obtain ⟨d, du, ad, hd⟩ : ∃ (d : ι) (H : d ∈ u), (B a ∩ B d).nonempty ∧ δ a ≤ τ * δ d := uT.2.2 a hat c hc h, exact lt_irrefl _ ((hu d du ad).trans_le hd) }, -- Let `A` be all the elements of `t` which do not intersect the family `u`. It is nonempty as it -- contains `a`. We will pick an element `a'` of `A` with `δ a'` almost as large as possible. let A := {a' | a' ∈ t ∧ ∀ c ∈ u, disjoint (B a') (B c)}, have Anonempty : A.nonempty := ⟨a, hat, a_disj⟩, let m := Sup (δ '' A), have bddA : bdd_above (δ '' A), { refine ⟨R, λ x xA, _⟩, rcases (mem_image _ _ _).1 xA with ⟨a', ha', rfl⟩, exact δle a' ha'.1 }, obtain ⟨a', a'A, ha'⟩ : ∃ a' ∈ A, m / τ ≤ δ a', { have : 0 ≤ m := (δnonneg a hat).trans (le_cSup bddA (mem_image_of_mem _ ⟨hat, a_disj⟩)), rcases eq_or_lt_of_le this with mzero|mpos, { refine ⟨a, ⟨hat, a_disj⟩, _⟩, simpa only [← mzero, zero_div] using δnonneg a hat }, { have I : m / τ < m, { rw div_lt_iff (zero_lt_one.trans hτ), conv_lhs { rw ← mul_one m }, exact (mul_lt_mul_left mpos).2 hτ }, rcases exists_lt_of_lt_cSup (nonempty_image_iff.2 Anonempty) I with ⟨x, xA, hx⟩, rcases (mem_image _ _ _).1 xA with ⟨a', ha', rfl⟩, exact ⟨a', ha', hx.le⟩, } }, clear hat hu a_disj a, have a'_ne_u : a' ∉ u := λ H, (hne _ a'A.1).ne_empty (disjoint_self.1 (a'A.2 _ H)), -- we claim that `u ∪ {a'}` still belongs to `T`, contradicting the maximality of `u`. refine ⟨insert a' u, ⟨_, _, _⟩, subset_insert _ _, (ne_insert_of_not_mem _ a'_ne_u).symm⟩, -- check that `u ∪ {a'}` is made of elements of `t`. { rw insert_subset, exact ⟨a'A.1, uT.1⟩ }, -- check that `u ∪ {a'}` is a disjoint family. This follows from the fact that `a'` does not -- intersect `u`. { exact uT.2.1.insert (λ b bu ba', a'A.2 b bu) }, -- check that every element `c` of `t` intersecting `u ∪ {a'}` intersects an element of this -- family with large `δ`. { assume c ct b ba'u hcb, -- if `c` already intersects an element of `u`, then it intersects an element of `u` with -- large `δ` by the assumption on `u`, and there is nothing left to do. by_cases H : ∃ d ∈ u, (B c ∩ B d).nonempty, { rcases H with ⟨d, du, hd⟩, rcases uT.2.2 c ct d du hd with ⟨d', d'u, hd'⟩, exact ⟨d', mem_insert_of_mem _ d'u, hd'⟩ }, -- otherwise, `c` belongs to `A`. The element of `u ∪ {a'}` that it intersects has to be `a'`. -- moreover, `δ c` is smaller than the maximum `m` of `δ` over `A`, which is `≤ δ a' / τ` -- thanks to the good choice of `a'`. This is the desired inequality. { push_neg at H, simp only [← not_disjoint_iff_nonempty_inter, not_not] at H, rcases mem_insert_iff.1 ba'u with rfl|H', { refine ⟨b, mem_insert _ _, hcb, _⟩, calc δ c ≤ m : le_cSup bddA (mem_image_of_mem _ ⟨ct, H⟩) ... = τ * (m / τ) : by { field_simp [(zero_lt_one.trans hτ).ne'], ring } ... ≤ τ * δ b : mul_le_mul_of_nonneg_left ha' (zero_le_one.trans hτ.le) }, { rw ← not_disjoint_iff_nonempty_inter at hcb, exact (hcb (H _ H')).elim } } } end /-- Vitali covering theorem, closed balls version: given a family `t` of closed balls, one can extract a disjoint subfamily `u ⊆ t` so that all balls in `t` are covered by the 5-times dilations of balls in `u`. -/ theorem exists_disjoint_subfamily_covering_enlargment_closed_ball [metric_space α] (t : set ι) (x : ι → α) (r : ι → ℝ) (R : ℝ) (hr : ∀ a ∈ t, r a ≤ R) : ∃ u ⊆ t, u.pairwise_disjoint (λ a, closed_ball (x a) (r a)) ∧ ∀ a ∈ t, ∃ b ∈ u, closed_ball (x a) (r a) ⊆ closed_ball (x b) (5 * r b) := begin rcases eq_empty_or_nonempty t with rfl|tnonempty, { exact ⟨∅, subset.refl _, pairwise_disjoint_empty, by simp⟩ }, by_cases ht : ∀ a ∈ t, r a < 0, { exact ⟨t, subset.rfl, λ a ha b hb hab, by simp only [function.on_fun, closed_ball_eq_empty.2 (ht a ha), empty_disjoint], λ a ha, ⟨a, ha, by simp only [closed_ball_eq_empty.2 (ht a ha), empty_subset]⟩⟩ }, push_neg at ht, let t' := {a ∈ t | 0 ≤ r a}, rcases exists_disjoint_subfamily_covering_enlargment (λ a, closed_ball (x a) (r a)) t' r 2 one_lt_two (λ a ha, ha.2) R (λ a ha, hr a ha.1) (λ a ha, ⟨x a, mem_closed_ball_self ha.2⟩) with ⟨u, ut', u_disj, hu⟩, have A : ∀ a ∈ t', ∃ b ∈ u, closed_ball (x a) (r a) ⊆ closed_ball (x b) (5 * r b), { assume a ha, rcases hu a ha with ⟨b, bu, hb, rb⟩, refine ⟨b, bu, _⟩, have : dist (x a) (x b) ≤ r a + r b := dist_le_add_of_nonempty_closed_ball_inter_closed_ball hb, apply closed_ball_subset_closed_ball', linarith }, refine ⟨u, ut'.trans (λ a ha, ha.1), u_disj, λ a ha, _⟩, rcases le_or_lt 0 (r a) with h'a|h'a, { exact A a ⟨ha, h'a⟩ }, { rcases ht with ⟨b, rb⟩, rcases A b ⟨rb.1, rb.2⟩ with ⟨c, cu, hc⟩, refine ⟨c, cu, by simp only [closed_ball_eq_empty.2 h'a, empty_subset]⟩ }, end /-- The measurable Vitali covering theorem. Assume one is given a family `t` of closed sets with nonempty interior, such that each `a ∈ t` is included in a ball `B (x, r)` and covers a definite proportion of the ball `B (x, 3 r)` for a given measure `μ` (think of the situation where `μ` is a doubling measure and `t` is a family of balls). Consider a (possibly non-measurable) set `s` at which the family is fine, i.e., every point of `s` belongs to arbitrarily small elements of `t`. Then one can extract from `t` a disjoint subfamily that covers almost all `s`. For more flexibility, we give a statement with a parameterized family of sets. -/ theorem exists_disjoint_covering_ae [metric_space α] [measurable_space α] [opens_measurable_space α] [second_countable_topology α] (μ : measure α) [is_locally_finite_measure μ] (s : set α) (t : set ι) (C : ℝ≥0) (r : ι → ℝ) (c : ι → α) (B : ι → set α) (hB : ∀ a ∈ t, B a ⊆ closed_ball (c a) (r a)) (μB : ∀ a ∈ t, μ (closed_ball (c a) (3 * r a)) ≤ C * μ (B a)) (ht : ∀ a ∈ t, (interior (B a)).nonempty) (h't : ∀ a ∈ t, is_closed (B a)) (hf : ∀ x ∈ s, ∀ (ε > (0 : ℝ)), ∃ a ∈ t, r a ≤ ε ∧ c a = x) : ∃ u ⊆ t, u.countable ∧ u.pairwise_disjoint B ∧ μ (s \ ⋃ a ∈ u, B a) = 0 := begin /- The idea of the proof is the following. Assume for simplicity that `μ` is finite. Applying the abstract Vitali covering theorem with `δ = r` given by `hf`, one obtains a disjoint subfamily `u`, such that any element of `t` intersects an element of `u` with comparable radius. Fix `ε > 0`. Since the elements of `u` have summable measure, one can remove finitely elements `w_1, ..., w_n`. so that the measure of the remaining elements is `< ε`. Consider now a point `z` not in the `w_i`. There is a small ball around `z` not intersecting the `w_i` (as they are closed), an element `a ∈ t` contained in this small ball (as the family `t` is fine at `z`) and an element `b ∈ u` intersecting `a`, with comparable radius (by definition of `u`). Then `z` belongs to the enlargement of `b`. This shows that `s \ (w_1 ∪ ... ∪ w_n)` is contained in `⋃ (b ∈ u \ {w_1, ... w_n}) (enlargement of b)`. The measure of the latter set is bounded by `∑ (b ∈ u \ {w_1, ... w_n}) C * μ b` (by the doubling property of the measure), which is at most `C ε`. Letting `ε` tend to `0` shows that `s` is almost everywhere covered by the family `u`. For the real argument, the measure is only locally finite. Therefore, we implement the same strategy, but locally restricted to balls on which the measure is finite. For this, we do not use the whole family `t`, but a subfamily `t'` supported on small balls (which is possible since the family is assumed to be fine at every point of `s`). -/ -- choose around each `x` a small ball on which the measure is finite have : ∀ x, ∃ R, 0 < R ∧ R ≤ 1 ∧ μ (closed_ball x (20 * R)) < ∞, { assume x, obtain ⟨R, Rpos, μR⟩ : ∃ (R : ℝ) (hR : 0 < R), μ (closed_ball x R) < ∞ := (μ.finite_at_nhds x).exists_mem_basis nhds_basis_closed_ball, refine ⟨min 1 (R/20), _, min_le_left _ _, _⟩, { simp only [true_and, lt_min_iff, zero_lt_one], linarith }, { apply lt_of_le_of_lt (measure_mono _) μR, apply closed_ball_subset_closed_ball, calc 20 * min 1 (R / 20) ≤ 20 * (R/20) : mul_le_mul_of_nonneg_left (min_le_right _ _) (by norm_num) ... = R : by ring } }, choose R hR0 hR1 hRμ, -- we restrict to a subfamily `t'` of `t`, made of elements small enough to ensure that -- they only see a finite part of the measure, and with a doubling property let t' := {a ∈ t | r a ≤ R (c a)}, -- extract a disjoint subfamily `u` of `t'` thanks to the abstract Vitali covering theorem. obtain ⟨u, ut', u_disj, hu⟩ : ∃ u ⊆ t', u.pairwise_disjoint B ∧ ∀ a ∈ t', ∃ b ∈ u, (B a ∩ B b).nonempty ∧ r a ≤ 2 * r b, { have A : ∀ a ∈ t', r a ≤ 1, { assume a ha, apply ha.2.trans (hR1 (c a)), }, have A' : ∀ a ∈ t', (B a).nonempty := λ a hat', set.nonempty.mono interior_subset (ht a hat'.1), refine exists_disjoint_subfamily_covering_enlargment B t' r 2 one_lt_two (λ a ha, _) 1 A A', exact nonempty_closed_ball.1 ((A' a ha).mono (hB a ha.1)) }, have ut : u ⊆ t := λ a hau, (ut' hau).1, -- As the space is second countable, the family is countable since all its sets have nonempty -- interior. have u_count : u.countable := u_disj.countable_of_nonempty_interior (λ a ha, ht a (ut ha)), -- the family `u` will be the desired family refine ⟨u, λ a hat', (ut' hat').1, u_count, u_disj, _⟩, -- it suffices to show that it covers almost all `s` locally around each point `x`. refine null_of_locally_null _ (λ x hx, _), -- let `v` be the subfamily of `u` made of those sets intersecting the small ball `ball x (r x)` let v := {a ∈ u | (B a ∩ ball x (R x)).nonempty }, have vu : v ⊆ u := λ a ha, ha.1, -- they are all contained in a fixed ball of finite measure, thanks to our choice of `t'` obtain ⟨K, μK, hK⟩ : ∃ K, μ (closed_ball x K) < ∞ ∧ ∀ a ∈ u, (B a ∩ ball x (R x)).nonempty → B a ⊆ closed_ball x K, { have Idist_v : ∀ a ∈ v, dist (c a) x ≤ r a + R x, { assume a hav, apply dist_le_add_of_nonempty_closed_ball_inter_closed_ball, refine hav.2.mono _, apply inter_subset_inter _ ball_subset_closed_ball, exact hB a (ut (vu hav)) }, set R0 := Sup (r '' v) with R0_def, have R0_bdd : bdd_above (r '' v), { refine ⟨1, λ r' hr', _⟩, rcases (mem_image _ _ _).1 hr' with ⟨b, hb, rfl⟩, exact le_trans (ut' (vu hb)).2 (hR1 (c b)) }, rcases le_total R0 (R x) with H|H, { refine ⟨20 * R x, hRμ x, λ a au hax, _⟩, refine (hB a (ut au)).trans _, apply closed_ball_subset_closed_ball', have : r a ≤ R0 := le_cSup R0_bdd (mem_image_of_mem _ ⟨au, hax⟩), linarith [Idist_v a ⟨au, hax⟩, hR0 x] }, { have R0pos : 0 < R0 := (hR0 x).trans_le H, have vnonempty : v.nonempty, { by_contra, rw [nonempty_iff_ne_empty, not_not] at h, simp only [h, real.Sup_empty, image_empty] at R0_def, exact lt_irrefl _ (R0pos.trans_le (le_of_eq R0_def)) }, obtain ⟨a, hav, R0a⟩ : ∃ a ∈ v, R0/2 < r a, { obtain ⟨r', r'mem, hr'⟩ : ∃ r' ∈ r '' v, R0 / 2 < r' := exists_lt_of_lt_cSup (nonempty_image_iff.2 vnonempty) (half_lt_self R0pos), rcases (mem_image _ _ _).1 r'mem with ⟨a, hav, rfl⟩, exact ⟨a, hav, hr'⟩ }, refine ⟨8 * R0, _, _⟩, { apply lt_of_le_of_lt (measure_mono _) (hRμ (c a)), apply closed_ball_subset_closed_ball', rw dist_comm, linarith [Idist_v a hav, (ut' (vu hav)).2] }, { assume b bu hbx, refine (hB b (ut bu)).trans _, apply closed_ball_subset_closed_ball', have : r b ≤ R0 := le_cSup R0_bdd (mem_image_of_mem _ ⟨bu, hbx⟩), linarith [Idist_v b ⟨bu, hbx⟩] } } }, -- we will show that, in `ball x (R x)`, almost all `s` is covered by the family `u`. refine ⟨_ ∩ ball x (R x), inter_mem_nhds_within _ (ball_mem_nhds _ (hR0 _)), nonpos_iff_eq_zero.mp (le_of_forall_le_of_dense (λ ε εpos, _))⟩, -- the elements of `v` are disjoint and all contained in a finite volume ball, hence the sum -- of their measures is finite. have I : ∑' (a : v), μ (B a) < ∞, { calc ∑' (a : v), μ (B a) = μ (⋃ (a ∈ v), B a) : begin rw measure_bUnion (u_count.mono vu) _ (λ a ha, (h't _ (vu.trans ut ha)).measurable_set), exact u_disj.subset vu end ... ≤ μ (closed_ball x K) : measure_mono (Union₂_subset (λ a ha, hK a (vu ha) ha.2)) ... < ∞ : μK }, -- we can obtain a finite subfamily of `v`, such that the measures of the remaining elements -- add up to an arbitrarily small number, say `ε / C`. obtain ⟨w, hw⟩ : ∃ (w : finset ↥v), ∑' (a : {a // a ∉ w}), μ (B a) < ε / C, { have : 0 < ε / C, by simp only [ennreal.div_pos_iff, εpos.ne', ennreal.coe_ne_top, ne.def, not_false_iff, and_self], exact ((tendsto_order.1 (ennreal.tendsto_tsum_compl_at_top_zero I.ne)).2 _ this).exists }, -- main property: the points `z` of `s` which are not covered by `u` are contained in the -- enlargements of the elements not in `w`. have M : (s \ ⋃ a ∈ u, B a) ∩ ball x (R x) ⊆ ⋃ (a : {a // a ∉ w}), closed_ball (c a) (3 * r a), { assume z hz, set k := ⋃ (a : v) (ha : a ∈ w), B a with hk, have k_closed : is_closed k := is_closed_bUnion w.finite_to_set (λ i hi, h't _ (ut (vu i.2))), have z_notmem_k : z ∉ k, { simp only [not_exists, exists_prop, mem_Union, mem_sep_iff, forall_exists_index, set_coe.exists, not_and, exists_and_distrib_right, subtype.coe_mk], assume b hbv h'b h'z, have : z ∈ (s \ ⋃ a ∈ u, B a) ∩ (⋃ a ∈ u, B a) := mem_inter (mem_of_mem_inter_left hz) (mem_bUnion (vu hbv) h'z), simpa only [diff_inter_self] }, -- since the elements of `w` are closed and finitely many, one can find a small ball around `z` -- not intersecting them have : ball x (R x) \ k ∈ 𝓝 z, { apply is_open.mem_nhds (is_open_ball.sdiff k_closed) _, exact (mem_diff _).2 ⟨mem_of_mem_inter_right hz, z_notmem_k⟩ }, obtain ⟨d, dpos, hd⟩ : ∃ (d : ℝ) (dpos : 0 < d), closed_ball z d ⊆ ball x (R x) \ k := nhds_basis_closed_ball.mem_iff.1 this, -- choose an element `a` of the family `t` contained in this small ball obtain ⟨a, hat, ad, rfl⟩ : ∃ a ∈ t, r a ≤ min d (R z) ∧ c a = z, from hf z ((mem_diff _).1 (mem_of_mem_inter_left hz)).1 (min d (R z)) (lt_min dpos (hR0 z)), have ax : B a ⊆ ball x (R x), { refine (hB a hat).trans _, refine subset.trans _ (hd.trans (diff_subset (ball x (R x)) k)), exact closed_ball_subset_closed_ball (ad.trans (min_le_left _ _)), }, -- it intersects an element `b` of `u` with comparable diameter, by definition of `u` obtain ⟨b, bu, ab, bdiam⟩ : ∃ b ∈ u, (B a ∩ B b).nonempty ∧ r a ≤ 2 * r b, from hu a ⟨hat, ad.trans (min_le_right _ _)⟩, have bv : b ∈ v, { refine ⟨bu, ab.mono _⟩, rw inter_comm, exact inter_subset_inter_right _ ax }, let b' : v := ⟨b, bv⟩, -- `b` can not belong to `w`, as the elements of `w` do not intersect `closed_ball z d`, -- contrary to `b` have b'_notmem_w : b' ∉ w, { assume b'w, have b'k : B b' ⊆ k, from @finset.subset_set_bUnion_of_mem _ _ _ (λ (y : v), B y) _ b'w, have : ((ball x (R x) \ k) ∩ k).nonempty, { apply ab.mono (inter_subset_inter _ b'k), refine ((hB _ hat).trans _).trans hd, exact (closed_ball_subset_closed_ball (ad.trans (min_le_left _ _))) }, simpa only [diff_inter_self, not_nonempty_empty] }, let b'' : {a // a ∉ w} := ⟨b', b'_notmem_w⟩, -- since `a` and `b` have comparable diameters, it follows that `z` belongs to the -- enlargement of `b` have zb : c a ∈ closed_ball (c b) (3 * r b), { rcases ab with ⟨e, ⟨ea, eb⟩⟩, have A : dist (c a) e ≤ r a, from mem_closed_ball'.1 (hB a hat ea), have B : dist e (c b) ≤ r b, from mem_closed_ball.1 (hB b (ut bu) eb), simp only [mem_closed_ball], linarith [dist_triangle (c a) e (c b)] }, suffices H : closed_ball (c b'') (3 * r b'') ⊆ ⋃ (a : {a // a ∉ w}), closed_ball (c a) (3 * r a), from H zb, exact subset_Union (λ (a : {a // a ∉ w}), closed_ball (c a) (3 * r a)) b'' }, -- now that we have proved our main inclusion, we can use it to estimate the measure of the points -- in `ball x (r x)` not covered by `u`. haveI : encodable v := (u_count.mono vu).to_encodable, calc μ ((s \ ⋃ a ∈ u, B a) ∩ ball x (R x)) ≤ μ (⋃ (a : {a // a ∉ w}), closed_ball (c a) (3 * r a)) : measure_mono M ... ≤ ∑' (a : {a // a ∉ w}), μ (closed_ball (c a) (3 * r a)) : measure_Union_le _ ... ≤ ∑' (a : {a // a ∉ w}), C * μ (B a) : ennreal.tsum_le_tsum (λ a, μB a (ut (vu a.1.2))) ... = C * ∑' (a : {a // a ∉ w}), μ (B a) : ennreal.tsum_mul_left ... ≤ C * (ε / C) : mul_le_mul_left' hw.le _ ... ≤ ε : ennreal.mul_div_le end /-- Assume that around every point there are arbitrarily small scales at which the measure is doubling. Then the set of closed sets `a` with nonempty interior contained in `closed_ball x r` and covering a fixed proportion `1/C` of the ball `closed_ball x (3 * r)` forms a Vitali family. This is essentially a restatement of the measurable Vitali theorem. -/ protected def vitali_family [metric_space α] [measurable_space α] [opens_measurable_space α] [second_countable_topology α] (μ : measure α) [is_locally_finite_measure μ] (C : ℝ≥0) (h : ∀ x, ∃ᶠ r in 𝓝[>] 0, μ (closed_ball x (3 * r)) ≤ C * μ (closed_ball x r)) : vitali_family μ := { sets_at := λ x, {a | is_closed a ∧ (interior a).nonempty ∧ ∃ r, (a ⊆ closed_ball x r ∧ μ (closed_ball x (3 * r)) ≤ C * μ a)}, measurable_set' := λ x a ha, ha.1.measurable_set, nonempty_interior := λ x a ha, ha.2.1, nontrivial := λ x ε εpos, begin obtain ⟨r, μr, rpos, rε⟩ : ∃ r, μ (closed_ball x (3 * r)) ≤ C * μ (closed_ball x r) ∧ r ∈ Ioc (0 : ℝ) ε := ((h x).and_eventually (Ioc_mem_nhds_within_Ioi ⟨le_rfl, εpos⟩)).exists, refine ⟨closed_ball x r, ⟨is_closed_ball, _, ⟨r, subset.rfl, μr⟩⟩, closed_ball_subset_closed_ball rε⟩, exact (nonempty_ball.2 rpos).mono (ball_subset_interior_closed_ball) end, covering := begin assume s f fsubset ffine, let t : set (ℝ × α × set α) := {p | p.2.2 ⊆ closed_ball p.2.1 p.1 ∧ μ (closed_ball p.2.1 (3 * p.1)) ≤ C * μ p.2.2 ∧ (interior p.2.2).nonempty ∧ is_closed p.2.2 ∧ p.2.2 ∈ f p.2.1 ∧ p.2.1 ∈ s}, have A : ∀ x ∈ s, ∀ (ε : ℝ), ε > 0 → (∃ (p : ℝ × α × set α) (Hp : p ∈ t), p.1 ≤ ε ∧ p.2.1 = x), { assume x xs ε εpos, rcases ffine x xs ε εpos with ⟨a, ha, h'a⟩, rcases fsubset x xs ha with ⟨a_closed, a_int, ⟨r, ar, μr⟩⟩, refine ⟨⟨min r ε, x, a⟩, ⟨_, _, a_int, a_closed, ha, xs⟩, min_le_right _ _, rfl⟩, { rcases min_cases r ε with h'|h'; rwa h'.1 }, { apply le_trans (measure_mono (closed_ball_subset_closed_ball _)) μr, exact mul_le_mul_of_nonneg_left (min_le_left _ _) zero_le_three } }, rcases exists_disjoint_covering_ae μ s t C (λ p, p.1) (λ p, p.2.1) (λ p, p.2.2) (λ p hp, hp.1) (λ p hp, hp.2.1) (λ p hp, hp.2.2.1) (λ p hp, hp.2.2.2.1) A with ⟨t', t't, t'_count, t'_disj, μt'⟩, refine ⟨(λ (p : ℝ × α × set α), p.2) '' t', _, _, _, _⟩, { rintros - ⟨q, hq, rfl⟩, exact (t't hq).2.2.2.2.2 }, { rintros p ⟨q, hq, rfl⟩ p' ⟨q', hq', rfl⟩ hqq', exact t'_disj hq hq' (ne_of_apply_ne _ hqq') }, { rintros - ⟨q, hq, rfl⟩, exact (t't hq).2.2.2.2.1 }, { convert μt' using 3, rw bUnion_image } end } end vitali
3eabc0a0a59557ee1a46d0d7ec2c03034825ffb0
367134ba5a65885e863bdc4507601606690974c1
/src/field_theory/fixed.lean
1139691e2c9674c4623773ed3107f3b302a80596
[ "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
12,498
lean
/- Copyright (c) 2020 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import algebra.polynomial.group_ring_action import deprecated.subfield import field_theory.normal import field_theory.separable import field_theory.tower import linear_algebra.matrix import ring_theory.polynomial /-! # Fixed field under a group action. This is the basis of the Fundamental Theorem of Galois Theory. Given a (finite) group `G` that acts on a field `F`, we define `fixed_points G F`, the subfield consisting of elements of `F` fixed_points by every element of `G`. This subfield is then normal and separable, and in addition (TODO) if `G` acts faithfully on `F` then `findim (fixed_points G F) F = fintype.card G`. ## Main Definitions - `fixed_points G F`, the subfield consisting of elements of `F` fixed_points by every element of `G`, where `G` is a group that acts on `F`. -/ noncomputable theory open_locale classical big_operators open mul_action finset finite_dimensional universes u v w variables (G : Type u) [group G] (F : Type v) [field F] [mul_semiring_action G F] (g : G) instance fixed_by.is_subfield : is_subfield (fixed_by G F g) := { zero_mem := smul_zero g, add_mem := λ x y hx hy, (smul_add g x y).trans $ congr_arg2 _ hx hy, neg_mem := λ x hx, (smul_neg g x).trans $ congr_arg _ hx, one_mem := smul_one g, mul_mem := λ x y hx hy, (smul_mul' g x y).trans $ congr_arg2 _ hx hy, inv_mem := λ x hx, (smul_inv F g x).trans $ congr_arg _ hx } namespace fixed_points instance : is_subfield (fixed_points G F) := by convert @is_subfield.Inter F _ G (fixed_by G F) _; rw fixed_eq_Inter_fixed_by instance : is_invariant_subring G (fixed_points G F) := { smul_mem := λ g x hx g', by rw [hx, hx] } @[simp] theorem smul (g : G) (x : fixed_points G F) : g • x = x := subtype.eq $ x.2 g -- Why is this so slow? @[simp] theorem smul_polynomial (g : G) (p : polynomial (fixed_points G F)) : g • p = p := polynomial.induction_on p (λ x, by rw [polynomial.smul_C, smul]) (λ p q ihp ihq, by rw [smul_add, ihp, ihq]) (λ n x ih, by rw [smul_mul', polynomial.smul_C, smul, smul_pow, polynomial.smul_X]) instance : algebra (fixed_points G F) F := algebra.of_is_subring _ theorem coe_algebra_map : algebra_map (fixed_points G F) F = is_subring.subtype (fixed_points G F) := rfl lemma linear_independent_smul_of_linear_independent {s : finset F} : linear_independent (fixed_points G F) (λ i : (↑s : set F), (i : F)) → linear_independent F (λ i : (↑s : set F), mul_action.to_fun G F i) := begin refine finset.induction_on s (λ _, linear_independent_empty_type $ λ ⟨x⟩, x.2) (λ a s has ih hs, _), rw coe_insert at hs ⊢, rw linear_independent_insert (mt mem_coe.1 has) at hs, rw linear_independent_insert' (mt mem_coe.1 has), refine ⟨ih hs.1, λ ha, _⟩, rw finsupp.mem_span_iff_total at ha, rcases ha with ⟨l, hl, hla⟩, rw [finsupp.total_apply_of_mem_supported F hl] at hla, suffices : ∀ i ∈ s, l i ∈ fixed_points G F, { replace hla := (sum_apply _ _ (λ i, l i • to_fun G F i)).symm.trans (congr_fun hla 1), simp_rw [pi.smul_apply, to_fun_apply, one_smul] at hla, refine hs.2 (hla ▸ submodule.sum_mem _ (λ c hcs, _)), change (⟨l c, this c hcs⟩ : fixed_points G F) • c ∈ _, exact submodule.smul_mem _ _ (submodule.subset_span $ mem_coe.2 hcs) }, intros i his g, refine eq_of_sub_eq_zero (linear_independent_iff'.1 (ih hs.1) s.attach (λ i, g • l i - l i) _ ⟨i, his⟩ (mem_attach _ _) : _), refine (@sum_attach _ _ s _ (λ i, (g • l i - l i) • (to_fun G F) i)).trans _, ext g', dsimp only, conv_lhs { rw sum_apply, congr, skip, funext, rw [pi.smul_apply, sub_smul, smul_eq_mul] }, rw [sum_sub_distrib, pi.zero_apply, sub_eq_zero], conv_lhs { congr, skip, funext, rw [to_fun_apply, ← mul_inv_cancel_left g g', mul_smul, ← smul_mul', ← to_fun_apply _ x] }, show ∑ x in s, g • (λ y, l y • to_fun G F y) x (g⁻¹ * g') = ∑ x in s, (λ y, l y • to_fun G F y) x g', rw [← smul_sum, ← sum_apply _ _ (λ y, l y • to_fun G F y), ← sum_apply _ _ (λ y, l y • to_fun G F y)], dsimp only, rw [hla, to_fun_apply, to_fun_apply, smul_smul, mul_inv_cancel_left] end variables [fintype G] (x : F) /-- `minpoly G F x` is the minimal polynomial of `(x : F)` over `fixed_points G F`. -/ def minpoly : polynomial (fixed_points G F) := (prod_X_sub_smul G F x).to_subring _ $ λ c hc g, let ⟨hc0, n, hn⟩ := finsupp.mem_frange.1 hc in hn ▸ prod_X_sub_smul.coeff G F x g n namespace minpoly theorem monic : (minpoly G F x).monic := subtype.eq $ prod_X_sub_smul.monic G F x theorem eval₂ : polynomial.eval₂ (is_subring.subtype $ fixed_points G F) x (minpoly G F x) = 0 := begin rw [← prod_X_sub_smul.eval G F x, polynomial.eval₂_eq_eval_map], simp [minpoly], end theorem ne_one : minpoly G F x ≠ (1 : polynomial (fixed_points G F)) := λ H, have _ := eval₂ G F x, (one_ne_zero : (1 : F) ≠ 0) $ by rwa [H, polynomial.eval₂_one] at this theorem of_eval₂ (f : polynomial (fixed_points G F)) (hf : polynomial.eval₂ (is_subring.subtype $ fixed_points G F) x f = 0) : minpoly G F x ∣ f := begin rw [← polynomial.map_dvd_map' (is_subring.subtype $ fixed_points G F), minpoly, polynomial.map_to_subring, prod_X_sub_smul], refine fintype.prod_dvd_of_coprime (polynomial.pairwise_coprime_X_sub $ mul_action.injective_of_quotient_stabilizer G x) (λ y, quotient_group.induction_on y $ λ g, _), rw [polynomial.dvd_iff_is_root, polynomial.is_root.def, mul_action.of_quotient_stabilizer_mk, polynomial.eval_smul', ← is_invariant_subring.coe_subtype_hom' G (fixed_points G F), ← mul_semiring_action_hom.coe_polynomial, ← mul_semiring_action_hom.map_smul, smul_polynomial, mul_semiring_action_hom.coe_polynomial, is_invariant_subring.coe_subtype_hom', polynomial.eval_map, hf, smul_zero] end /- Why is this so slow? -/ theorem irreducible_aux (f g : polynomial (fixed_points G F)) (hf : f.monic) (hg : g.monic) (hfg : f * g = minpoly G F x) : f = 1 ∨ g = 1 := begin have hf2 : f ∣ minpoly G F x, { rw ← hfg, exact dvd_mul_right _ _ }, have hg2 : g ∣ minpoly G F x, { rw ← hfg, exact dvd_mul_left _ _ }, have := eval₂ G F x, rw [← hfg, polynomial.eval₂_mul, mul_eq_zero] at this, cases this, { right, have hf3 : f = minpoly G F x, { exact polynomial.eq_of_monic_of_associated hf (monic G F x) (associated_of_dvd_dvd hf2 $ @of_eval₂ G _ F _ _ _ x f this) }, rwa [← mul_one (minpoly G F x), hf3, mul_right_inj' (monic G F x).ne_zero] at hfg }, { left, have hg3 : g = minpoly G F x, { exact polynomial.eq_of_monic_of_associated hg (monic G F x) (associated_of_dvd_dvd hg2 $ @of_eval₂ G _ F _ _ _ x g this) }, rwa [← one_mul (minpoly G F x), hg3, mul_left_inj' (monic G F x).ne_zero] at hfg } end theorem irreducible : irreducible (minpoly G F x) := (polynomial.irreducible_of_monic (monic G F x) (ne_one G F x)).2 (irreducible_aux G F x) end minpoly theorem is_integral : is_integral (fixed_points G F) x := ⟨minpoly G F x, minpoly.monic G F x, minpoly.eval₂ G F x⟩ theorem minpoly_eq_minpoly : minpoly G F x = _root_.minpoly (fixed_points G F) x := minpoly.unique' (is_integral G F x) (minpoly.irreducible G F x) (minpoly.eval₂ G F x) (minpoly.monic G F x) instance normal : normal (fixed_points G F) F := ⟨λ x, is_integral G F x, λ x, (polynomial.splits_id_iff_splits _).1 $ by { rw [← minpoly_eq_minpoly, minpoly, coe_algebra_map, polynomial.map_to_subring, prod_X_sub_smul], exact polynomial.splits_prod _ (λ _ _, polynomial.splits_X_sub_C _) }⟩ instance separable : is_separable (fixed_points G F) F := ⟨λ x, is_integral G F x, λ x, by { rw [← minpoly_eq_minpoly, ← polynomial.separable_map (is_subring.subtype (fixed_points G F)), minpoly, polynomial.map_to_subring], exact polynomial.separable_prod_X_sub_C_iff.2 (injective_of_quotient_stabilizer G x) }⟩ lemma dim_le_card : vector_space.dim (fixed_points G F) F ≤ fintype.card G := begin refine dim_le (λ s hs, cardinal.nat_cast_le.1 _), rw [← @dim_fun' F G, ← cardinal.lift_nat_cast.{v (max u v)}, cardinal.finset_card, ← cardinal.lift_id (vector_space.dim F (G → F))], exact linear_independent_le_dim'.{_ _ _ (max u v)} (linear_independent_smul_of_linear_independent G F hs) end instance : finite_dimensional (fixed_points G F) F := finite_dimensional.finite_dimensional_iff_dim_lt_omega.2 $ lt_of_le_of_lt (dim_le_card G F) (cardinal.nat_lt_omega _) lemma findim_le_card : findim (fixed_points G F) F ≤ fintype.card G := by exact_mod_cast trans_rel_right (≤) (findim_eq_dim _ _) (dim_le_card G F) end fixed_points lemma linear_independent_to_linear_map (R : Type u) (A : Type v) (B : Type w) [comm_semiring R] [integral_domain A] [algebra R A] [integral_domain B] [algebra R B] : linear_independent B (alg_hom.to_linear_map : (A →ₐ[R] B) → (A →ₗ[R] B)) := have linear_independent B (linear_map.lto_fun R A B ∘ alg_hom.to_linear_map), from ((linear_independent_monoid_hom A B).comp (coe : (A →ₐ[R] B) → (A →* B)) (λ f g hfg, alg_hom.ext $ monoid_hom.ext_iff.1 hfg) : _), this.of_comp _ lemma cardinal_mk_alg_hom (K : Type u) (V : Type v) (W : Type w) [field K] [field V] [algebra K V] [finite_dimensional K V] [field W] [algebra K W] [finite_dimensional K W] : cardinal.mk (V →ₐ[K] W) ≤ findim W (V →ₗ[K] W) := cardinal_mk_le_findim_of_linear_independent $ linear_independent_to_linear_map K V W noncomputable instance alg_hom.fintype (K : Type u) (V : Type v) (W : Type w) [field K] [field V] [algebra K V] [finite_dimensional K V] [field W] [algebra K W] [finite_dimensional K W] : fintype (V →ₐ[K] W) := classical.choice $ cardinal.lt_omega_iff_fintype.1 $ lt_of_le_of_lt (cardinal_mk_alg_hom K V W) (cardinal.nat_lt_omega _) noncomputable instance alg_equiv.fintype (K : Type u) (V : Type v) [field K] [field V] [algebra K V] [finite_dimensional K V] : fintype (V ≃ₐ[K] V) := fintype.of_equiv (V →ₐ[K] V) (alg_equiv_equiv_alg_hom K V).symm lemma findim_alg_hom (K : Type u) (V : Type v) [field K] [field V] [algebra K V] [finite_dimensional K V] : fintype.card (V →ₐ[K] V) ≤ findim V (V →ₗ[K] V) := fintype_card_le_findim_of_linear_independent $ linear_independent_to_linear_map K V V namespace fixed_points /-- Embedding produced from a faithful action. -/ @[simps apply {fully_applied := ff}] def to_alg_hom (G : Type u) (F : Type v) [group G] [field F] [faithful_mul_semiring_action G F] : G ↪ (F →ₐ[fixed_points G F] F) := { to_fun := λ g, { commutes' := λ x, x.2 g, .. mul_semiring_action.to_semiring_hom G F g }, inj' := λ g₁ g₂ hg, injective_to_semiring_hom G F $ ring_hom.ext $ λ x, alg_hom.ext_iff.1 hg x, } lemma to_alg_hom_apply_apply {G : Type u} {F : Type v} [group G] [field F] [faithful_mul_semiring_action G F] (g : G) (x : F) : to_alg_hom G F g x = g • x := rfl theorem findim_eq_card (G : Type u) (F : Type v) [group G] [field F] [fintype G] [faithful_mul_semiring_action G F] : findim (fixed_points G F) F = fintype.card G := le_antisymm (fixed_points.findim_le_card G F) $ calc fintype.card G ≤ fintype.card (F →ₐ[fixed_points G F] F) : fintype.card_le_of_injective _ (to_alg_hom G F).2 ... ≤ findim F (F →ₗ[fixed_points G F] F) : findim_alg_hom (fixed_points G F) F ... = findim (fixed_points G F) F : findim_linear_map' _ _ _ theorem to_alg_hom_bijective (G : Type u) (F : Type v) [group G] [field F] [fintype G] [faithful_mul_semiring_action G F] : function.bijective (to_alg_hom G F) := begin rw fintype.bijective_iff_injective_and_card, split, { exact (to_alg_hom G F).injective }, { apply le_antisymm, { exact fintype.card_le_of_injective _ (to_alg_hom G F).injective }, { rw ← findim_eq_card G F, exact has_le.le.trans_eq (findim_alg_hom _ F) (findim_linear_map' _ _ _) } }, end /-- Bijection between G and algebra homomorphisms that fix the fixed points -/ def to_alg_hom_equiv (G : Type u) (F : Type v) [group G] [field F] [fintype G] [faithful_mul_semiring_action G F] : G ≃ (F →ₐ[fixed_points G F] F) := function.embedding.equiv_of_surjective (to_alg_hom G F) (to_alg_hom_bijective G F).2 end fixed_points
fcbbf4407afbcd180c29e55d4aac37ce9a691e60
367134ba5a65885e863bdc4507601606690974c1
/src/order/basic.lean
268065763ffc529260199d13b7c0a9f9081f151e
[ "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
24,370
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Mario Carneiro -/ import data.subtype import data.prod open function /-! # Basic definitions about `≤` and `<` ## Definitions ### Predicates on functions - `monotone f`: a function between two types equipped with `≤` is monotone if `a ≤ b` implies `f a ≤ f b`. - `strict_mono f` : a function between two types equipped with `<` is strictly monotone if `a < b` implies `f a < f b`. - `order_dual α` : a type tag reversing the meaning of all inequalities. ### Transfering orders - `order.preimage`, `preorder.lift`: transfer a (pre)order on `β` to an order on `α` using a function `f : α → β`. - `partial_order.lift`, `linear_order.lift`: transfer a partial (resp., linear) order on `β` to a partial (resp., linear) order on `α` using an injective function `f`. ### Extra classes - `no_top_order`, `no_bot_order`: an order without a maximal/minimal element. - `densely_ordered`: an order with no gaps, i.e. for any two elements `a<b` there exists `c`, `a<c<b`. ## Main theorems - `monotone_of_monotone_nat`: if `f : ℕ → α` and `f n ≤ f (n + 1)` for all `n`, then `f` is monotone; - `strict_mono.nat`: if `f : ℕ → α` and `f n < f (n + 1)` for all `n`, then f is strictly monotone. ## TODO - expand module docs - automatic construction of dual definitions / theorems ## See also - `algebra.order` for basic lemmas about orders, and projection notation for orders ## Tags preorder, order, partial order, linear order, monotone, strictly monotone -/ universes u v w variables {α : Type u} {β : Type v} {γ : Type w} {r : α → α → Prop} @[simp] lemma lt_self_iff_false [preorder α] (a : α) : a < a ↔ false := by simp [lt_irrefl a] attribute [ext] has_le @[ext] lemma preorder.to_has_le_injective {α : Type*} : function.injective (@preorder.to_has_le α) := λ A B h, begin cases A, cases B, injection h with h_le, have : A_lt = B_lt, { funext a b, dsimp [(≤)] at A_lt_iff_le_not_le B_lt_iff_le_not_le h_le, simp [A_lt_iff_le_not_le, B_lt_iff_le_not_le, h_le], }, congr', end @[ext] lemma partial_order.to_preorder_injective {α : Type*} : function.injective (@partial_order.to_preorder α) := λ A B h, by { cases A, cases B, injection h, congr' } @[ext] lemma linear_order.to_partial_order_injective {α : Type*} : function.injective (@linear_order.to_partial_order α) := λ A B h, by { cases A, cases B, injection h, congr' } theorem preorder.ext {α} {A B : preorder α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := by { ext x y, exact H x y } theorem partial_order.ext {α} {A B : partial_order α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := by { ext x y, exact H x y } theorem linear_order.ext {α} {A B : linear_order α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := by { ext x y, exact H x y } /-- Given a relation `R` on `β` and a function `f : α → β`, the preimage relation on `α` is defined by `x ≤ y ↔ f x ≤ f y`. It is the unique relation on `α` making `f` a `rel_embedding` (assuming `f` is injective). -/ @[simp] def order.preimage {α β} (f : α → β) (s : β → β → Prop) (x y : α) := s (f x) (f y) infix ` ⁻¹'o `:80 := order.preimage /-- The preimage of a decidable order is decidable. -/ instance order.preimage.decidable {α β} (f : α → β) (s : β → β → Prop) [H : decidable_rel s] : decidable_rel (f ⁻¹'o s) := λ x y, H _ _ section monotone variables [preorder α] [preorder β] [preorder γ] /-- A function between preorders is monotone if `a ≤ b` implies `f a ≤ f b`. -/ def monotone (f : α → β) := ∀⦃a b⦄, a ≤ b → f a ≤ f b theorem monotone_id : @monotone α α _ _ id := assume x y h, h theorem monotone_const {b : β} : monotone (λ(a:α), b) := assume x y h, le_refl b protected theorem monotone.comp {g : β → γ} {f : α → β} (m_g : monotone g) (m_f : monotone f) : monotone (g ∘ f) := assume a b h, m_g (m_f h) protected theorem monotone.iterate {f : α → α} (hf : monotone f) (n : ℕ) : monotone (f^[n]) := nat.rec_on n monotone_id (λ n ihn, ihn.comp hf) lemma monotone_of_monotone_nat {f : ℕ → α} (hf : ∀n, f n ≤ f (n + 1)) : monotone f | n m h := begin induction h, { refl }, { transitivity, assumption, exact hf _ } end lemma monotone.reflect_lt {α β} [linear_order α] [preorder β] {f : α → β} (hf : monotone f) {x x' : α} (h : f x < f x') : x < x' := by { rw [← not_le], intro h', apply not_le_of_lt h, exact hf h' } /-- If `f` is a monotone function from `ℕ` to a preorder such that `y` lies between `f x` and `f (x + 1)`, then `y` doesn't lie in the range of `f`. -/ lemma monotone.ne_of_lt_of_lt_nat {α} [preorder α] {f : ℕ → α} (hf : monotone f) (x x' : ℕ) {y : α} (h1 : f x < y) (h2 : y < f (x + 1)) : f x' ≠ y := by { rintro rfl, apply (hf.reflect_lt h1).not_le, exact nat.le_of_lt_succ (hf.reflect_lt h2) } /-- If `f` is a monotone function from `ℤ` to a preorder such that `y` lies between `f x` and `f (x + 1)`, then `y` doesn't lie in the range of `f`. -/ lemma monotone.ne_of_lt_of_lt_int {α} [preorder α] {f : ℤ → α} (hf : monotone f) (x x' : ℤ) {y : α} (h1 : f x < y) (h2 : y < f (x + 1)) : f x' ≠ y := by { rintro rfl, apply (hf.reflect_lt h1).not_le, exact int.le_of_lt_add_one (hf.reflect_lt h2) } end monotone /-- A function `f` is strictly monotone if `a < b` implies `f a < f b`. -/ def strict_mono [has_lt α] [has_lt β] (f : α → β) : Prop := ∀ ⦃a b⦄, a < b → f a < f b lemma strict_mono_id [has_lt α] : strict_mono (id : α → α) := λ a b, id /-- A function `f` is strictly monotone increasing on `t` if `x < y` for `x,y ∈ t` implies `f x < f y`. -/ def strict_mono_incr_on [has_lt α] [has_lt β] (f : α → β) (t : set α) : Prop := ∀ ⦃x⦄ (hx : x ∈ t) ⦃y⦄ (hy : y ∈ t), x < y → f x < f y /-- A function `f` is strictly monotone decreasing on `t` if `x < y` for `x,y ∈ t` implies `f y < f x`. -/ def strict_mono_decr_on [has_lt α] [has_lt β] (f : α → β) (t : set α) : Prop := ∀ ⦃x⦄ (hx : x ∈ t) ⦃y⦄ (hy : y ∈ t), x < y → f y < f x /-- Type tag for a set with dual order: `≤` means `≥` and `<` means `>`. -/ def order_dual (α : Type*) := α namespace order_dual instance (α : Type*) [h : nonempty α] : nonempty (order_dual α) := h instance (α : Type*) [h : subsingleton α] : subsingleton (order_dual α) := h instance (α : Type*) [has_le α] : has_le (order_dual α) := ⟨λx y:α, y ≤ x⟩ instance (α : Type*) [has_lt α] : has_lt (order_dual α) := ⟨λx y:α, y < x⟩ -- `dual_le` and `dual_lt` should not be simp lemmas: -- they cause a loop since `α` and `order_dual α` are definitionally equal lemma dual_le [has_le α] {a b : α} : @has_le.le (order_dual α) _ a b ↔ @has_le.le α _ b a := iff.rfl lemma dual_lt [has_lt α] {a b : α} : @has_lt.lt (order_dual α) _ a b ↔ @has_lt.lt α _ b a := iff.rfl lemma dual_compares [has_lt α] {a b : α} {o : ordering} : @ordering.compares (order_dual α) _ o a b ↔ @ordering.compares α _ o b a := by { cases o, exacts [iff.rfl, eq_comm, iff.rfl] } instance (α : Type*) [preorder α] : preorder (order_dual α) := { le_refl := le_refl, le_trans := assume a b c hab hbc, hbc.trans hab, lt_iff_le_not_le := λ _ _, lt_iff_le_not_le, .. order_dual.has_le α, .. order_dual.has_lt α } instance (α : Type*) [partial_order α] : partial_order (order_dual α) := { le_antisymm := assume a b hab hba, @le_antisymm α _ a b hba hab, .. order_dual.preorder α } instance (α : Type*) [linear_order α] : linear_order (order_dual α) := { le_total := assume a b:α, le_total b a, decidable_le := show decidable_rel (λa b:α, b ≤ a), by apply_instance, decidable_lt := show decidable_rel (λa b:α, b < a), by apply_instance, .. order_dual.partial_order α } instance : Π [inhabited α], inhabited (order_dual α) := id theorem preorder.dual_dual (α : Type*) [H : preorder α] : order_dual.preorder (order_dual α) = H := preorder.ext $ λ _ _, iff.rfl theorem partial_order.dual_dual (α : Type*) [H : partial_order α] : order_dual.partial_order (order_dual α) = H := partial_order.ext $ λ _ _, iff.rfl theorem linear_order.dual_dual (α : Type*) [H : linear_order α] : order_dual.linear_order (order_dual α) = H := linear_order.ext $ λ _ _, iff.rfl theorem cmp_le_flip {α} [has_le α] [@decidable_rel α (≤)] (x y : α) : @cmp_le (order_dual α) _ _ x y = cmp_le y x := rfl end order_dual namespace strict_mono_incr_on section dual variables [preorder α] [preorder β] {f : α → β} {s : set α} protected lemma dual (H : strict_mono_incr_on f s) : @strict_mono_incr_on (order_dual α) (order_dual β) _ _ f s := λ x hx y hy, H hy hx protected lemma dual_right (H : strict_mono_incr_on f s) : @strict_mono_decr_on α (order_dual β) _ _ f s := H end dual variables [linear_order α] [preorder β] {f : α → β} {s : set α} {x y : α} lemma le_iff_le (H : strict_mono_incr_on f s) (hx : x ∈ s) (hy : y ∈ s) : f x ≤ f y ↔ x ≤ y := ⟨λ h, le_of_not_gt $ λ h', not_le_of_lt (H hy hx h') h, λ h, (lt_or_eq_of_le h).elim (λ h', le_of_lt (H hx hy h')) (λ h', h' ▸ le_refl _)⟩ lemma lt_iff_lt (H : strict_mono_incr_on f s) (hx : x ∈ s) (hy : y ∈ s) : f x < f y ↔ x < y := by simp only [H.le_iff_le, hx, hy, lt_iff_le_not_le] protected theorem compares (H : strict_mono_incr_on f s) (hx : x ∈ s) (hy : y ∈ s) : ∀ {o}, ordering.compares o (f x) (f y) ↔ ordering.compares o x y | ordering.lt := H.lt_iff_lt hx hy | ordering.eq := ⟨λ h, le_antisymm ((H.le_iff_le hx hy).1 h.le) ((H.le_iff_le hy hx).1 h.symm.le), congr_arg _⟩ | ordering.gt := H.lt_iff_lt hy hx end strict_mono_incr_on namespace strict_mono_decr_on section dual variables [preorder α] [preorder β] {f : α → β} {s : set α} protected lemma dual (H : strict_mono_decr_on f s) : @strict_mono_decr_on (order_dual α) (order_dual β) _ _ f s := λ x hx y hy, H hy hx protected lemma dual_right (H : strict_mono_decr_on f s) : @strict_mono_incr_on α (order_dual β) _ _ f s := H end dual variables [linear_order α] [preorder β] {f : α → β} {s : set α} {x y : α} lemma le_iff_le (H : strict_mono_decr_on f s) (hx : x ∈ s) (hy : y ∈ s) : f x ≤ f y ↔ y ≤ x := H.dual_right.le_iff_le hy hx lemma lt_iff_lt (H : strict_mono_decr_on f s) (hx : x ∈ s) (hy : y ∈ s) : f x < f y ↔ y < x := H.dual_right.lt_iff_lt hy hx protected theorem compares (H : strict_mono_decr_on f s) (hx : x ∈ s) (hy : y ∈ s) {o : ordering} : ordering.compares o (f x) (f y) ↔ ordering.compares o y x := order_dual.dual_compares.trans $ H.dual_right.compares hy hx end strict_mono_decr_on namespace strict_mono open ordering function protected lemma strict_mono_incr_on [has_lt α] [has_lt β] {f : α → β} (hf : strict_mono f) (s : set α) : strict_mono_incr_on f s := λ x hx y hy hxy, hf hxy lemma comp [has_lt α] [has_lt β] [has_lt γ] {g : β → γ} {f : α → β} (hg : strict_mono g) (hf : strict_mono f) : strict_mono (g ∘ f) := λ a b h, hg (hf h) protected theorem iterate [has_lt α] {f : α → α} (hf : strict_mono f) (n : ℕ) : strict_mono (f^[n]) := nat.rec_on n strict_mono_id (λ n ihn, ihn.comp hf) lemma id_le {φ : ℕ → ℕ} (h : strict_mono φ) : ∀ n, n ≤ φ n := λ n, nat.rec_on n (nat.zero_le _) (λ n hn, nat.succ_le_of_lt (lt_of_le_of_lt hn $ h $ nat.lt_succ_self n)) protected lemma ite' [preorder α] [has_lt β] {f g : α → β} (hf : strict_mono f) (hg : strict_mono g) {p : α → Prop} [decidable_pred p] (hp : ∀ ⦃x y⦄, x < y → p y → p x) (hfg : ∀ ⦃x y⦄, p x → ¬p y → x < y → f x < g y) : strict_mono (λ x, if p x then f x else g x) := begin intros x y h, by_cases hy : p y, { have hx : p x := hp h hy, simpa [hx, hy] using hf h }, { by_cases hx : p x, { simpa [hx, hy] using hfg hx hy h }, { simpa [hx, hy] using hg h} } end protected lemma ite [preorder α] [preorder β] {f g : α → β} (hf : strict_mono f) (hg : strict_mono g) {p : α → Prop} [decidable_pred p] (hp : ∀ ⦃x y⦄, x < y → p y → p x) (hfg : ∀ x, f x ≤ g x) : strict_mono (λ x, if p x then f x else g x) := hf.ite' hg hp $ λ x y hx hy h, (hf h).trans_le (hfg y) section variables [linear_order α] [preorder β] {f : α → β} lemma lt_iff_lt (H : strict_mono f) {a b} : f a < f b ↔ a < b := (H.strict_mono_incr_on set.univ).lt_iff_lt trivial trivial protected theorem compares (H : strict_mono f) {a b} {o} : compares o (f a) (f b) ↔ compares o a b := (H.strict_mono_incr_on set.univ).compares trivial trivial lemma injective (H : strict_mono f) : injective f := λ x y h, show compares eq x y, from H.compares.1 h lemma le_iff_le (H : strict_mono f) {a b} : f a ≤ f b ↔ a ≤ b := (H.strict_mono_incr_on set.univ).le_iff_le trivial trivial lemma top_preimage_top (H : strict_mono f) {a} (h_top : ∀ p, p ≤ f a) (x : α) : x ≤ a := H.le_iff_le.mp (h_top (f x)) lemma bot_preimage_bot (H : strict_mono f) {a} (h_bot : ∀ p, f a ≤ p) (x : α) : a ≤ x := H.le_iff_le.mp (h_bot (f x)) end protected lemma nat {β} [preorder β] {f : ℕ → β} (h : ∀n, f n < f (n+1)) : strict_mono f := by { intros n m hnm, induction hnm with m' hnm' ih, apply h, exact ih.trans (h _) } -- `preorder α` isn't strong enough: if the preorder on α is an equivalence relation, -- then `strict_mono f` is vacuously true. lemma monotone [partial_order α] [preorder β] {f : α → β} (H : strict_mono f) : monotone f := λ a b h, (lt_or_eq_of_le h).rec (le_of_lt ∘ (@H _ _)) (by rintro rfl; refl) end strict_mono section open function lemma injective_of_lt_imp_ne [linear_order α] {f : α → β} (h : ∀ x y, x < y → f x ≠ f y) : injective f := begin intros x y k, contrapose k, rw [←ne.def, ne_iff_lt_or_gt] at k, cases k, { apply h _ _ k }, { rw eq_comm, apply h _ _ k } end lemma strict_mono_of_monotone_of_injective [partial_order α] [partial_order β] {f : α → β} (h₁ : monotone f) (h₂ : injective f) : strict_mono f := λ a b h, begin rw lt_iff_le_and_ne at ⊢ h, exact ⟨h₁ h.1, λ e, h.2 (h₂ e)⟩ end lemma monotone.strict_mono_iff_injective [linear_order α] [partial_order β] {f : α → β} (h : monotone f) : strict_mono f ↔ injective f := ⟨λ h, h.injective, strict_mono_of_monotone_of_injective h⟩ lemma strict_mono_of_le_iff_le [preorder α] [preorder β] {f : α → β} (h : ∀ x y, x ≤ y ↔ f x ≤ f y) : strict_mono f := λ a b, by simp [lt_iff_le_not_le, h] {contextual := tt} end /-! ### Order instances on the function space -/ instance pi.preorder {ι : Type u} {α : ι → Type v} [∀i, preorder (α i)] : preorder (Πi, α i) := { le := λx y, ∀i, x i ≤ y i, le_refl := assume a i, le_refl (a i), le_trans := assume a b c h₁ h₂ i, le_trans (h₁ i) (h₂ i) } lemma pi.le_def {ι : Type u} {α : ι → Type v} [∀i, preorder (α i)] {x y : Π i, α i} : x ≤ y ↔ ∀ i, x i ≤ y i := iff.rfl lemma pi.lt_def {ι : Type u} {α : ι → Type v} [∀i, preorder (α i)] {x y : Π i, α i} : x < y ↔ x ≤ y ∧ ∃ i, x i < y i := by simp [lt_iff_le_not_le, pi.le_def] {contextual := tt} lemma le_update_iff {ι : Type u} {α : ι → Type v} [∀i, preorder (α i)] [decidable_eq ι] {x y : Π i, α i} {i : ι} {a : α i} : x ≤ function.update y i a ↔ x i ≤ a ∧ ∀ j ≠ i, x j ≤ y j := function.forall_update_iff _ (λ j z, x j ≤ z) lemma update_le_iff {ι : Type u} {α : ι → Type v} [∀i, preorder (α i)] [decidable_eq ι] {x y : Π i, α i} {i : ι} {a : α i} : function.update x i a ≤ y ↔ a ≤ y i ∧ ∀ j ≠ i, x j ≤ y j := function.forall_update_iff _ (λ j z, z ≤ y j) lemma update_le_update_iff {ι : Type u} {α : ι → Type v} [∀i, preorder (α i)] [decidable_eq ι] {x y : Π i, α i} {i : ι} {a b : α i} : function.update x i a ≤ function.update y i b ↔ a ≤ b ∧ ∀ j ≠ i, x j ≤ y j := by simp [update_le_iff] {contextual := tt} instance pi.partial_order {ι : Type u} {α : ι → Type v} [∀i, partial_order (α i)] : partial_order (Πi, α i) := { le_antisymm := λf g h1 h2, funext (λb, le_antisymm (h1 b) (h2 b)), ..pi.preorder } theorem comp_le_comp_left_of_monotone [preorder α] [preorder β] {f : β → α} {g h : γ → β} (m_f : monotone f) (le_gh : g ≤ h) : has_le.le.{max w u} (f ∘ g) (f ∘ h) := assume x, m_f (le_gh x) section monotone variables [preorder α] [preorder γ] protected theorem monotone.order_dual {f : α → γ} (hf : monotone f) : @monotone (order_dual α) (order_dual γ) _ _ f := λ x y hxy, hf hxy theorem monotone_lam {f : α → β → γ} (m : ∀b, monotone (λa, f a b)) : monotone f := assume a a' h b, m b h theorem monotone_app (f : β → α → γ) (b : β) (m : monotone (λa b, f b a)) : monotone (f b) := assume a a' h, m h b end monotone theorem strict_mono.order_dual [has_lt α] [has_lt β] {f : α → β} (hf : strict_mono f) : @strict_mono (order_dual α) (order_dual β) _ _ f := λ x y hxy, hf hxy /-- Transfer a `preorder` on `β` to a `preorder` on `α` using a function `f : α → β`. -/ def preorder.lift {α β} [preorder β] (f : α → β) : preorder α := { le := λx y, f x ≤ f y, le_refl := λ a, le_refl _, le_trans := λ a b c, le_trans, lt := λx y, f x < f y, lt_iff_le_not_le := λ a b, lt_iff_le_not_le } /-- Transfer a `partial_order` on `β` to a `partial_order` on `α` using an injective function `f : α → β`. -/ def partial_order.lift {α β} [partial_order β] (f : α → β) (inj : injective f) : partial_order α := { le_antisymm := λ a b h₁ h₂, inj (le_antisymm h₁ h₂), .. preorder.lift f } /-- Transfer a `linear_order` on `β` to a `linear_order` on `α` using an injective function `f : α → β`. -/ def linear_order.lift {α β} [linear_order β] (f : α → β) (inj : injective f) : linear_order α := { le_total := λx y, le_total (f x) (f y), decidable_le := λ x y, (infer_instance : decidable (f x ≤ f y)), decidable_lt := λ x y, (infer_instance : decidable (f x < f y)), decidable_eq := λ x y, decidable_of_iff _ inj.eq_iff, .. partial_order.lift f inj } instance subtype.preorder {α} [preorder α] (p : α → Prop) : preorder (subtype p) := preorder.lift subtype.val @[simp] lemma subtype.mk_le_mk {α} [preorder α] {p : α → Prop} {x y : α} {hx : p x} {hy : p y} : (⟨x, hx⟩ : subtype p) ≤ ⟨y, hy⟩ ↔ x ≤ y := iff.rfl @[simp] lemma subtype.mk_lt_mk {α} [preorder α] {p : α → Prop} {x y : α} {hx : p x} {hy : p y} : (⟨x, hx⟩ : subtype p) < ⟨y, hy⟩ ↔ x < y := iff.rfl @[simp, norm_cast] lemma subtype.coe_le_coe {α} [preorder α] {p : α → Prop} {x y : subtype p} : (x : α) ≤ y ↔ x ≤ y := iff.rfl @[simp, norm_cast] lemma subtype.coe_lt_coe {α} [preorder α] {p : α → Prop} {x y : subtype p} : (x : α) < y ↔ x < y := iff.rfl instance subtype.partial_order {α} [partial_order α] (p : α → Prop) : partial_order (subtype p) := partial_order.lift subtype.val subtype.val_injective instance subtype.linear_order {α} [linear_order α] (p : α → Prop) : linear_order (subtype p) := linear_order.lift subtype.val subtype.val_injective lemma subtype.mono_coe [preorder α] (t : set α) : monotone (coe : (subtype t) → α) := λ x y, id lemma subtype.strict_mono_coe [preorder α] (t : set α) : strict_mono (coe : (subtype t) → α) := λ x y, id instance prod.has_le (α : Type u) (β : Type v) [has_le α] [has_le β] : has_le (α × β) := ⟨λp q, p.1 ≤ q.1 ∧ p.2 ≤ q.2⟩ instance prod.preorder (α : Type u) (β : Type v) [preorder α] [preorder β] : preorder (α × β) := { le_refl := assume ⟨a, b⟩, ⟨le_refl a, le_refl b⟩, le_trans := assume ⟨a, b⟩ ⟨c, d⟩ ⟨e, f⟩ ⟨hac, hbd⟩ ⟨hce, hdf⟩, ⟨le_trans hac hce, le_trans hbd hdf⟩, .. prod.has_le α β } /-- The pointwise partial order on a product. (The lexicographic ordering is defined in order/lexicographic.lean, and the instances are available via the type synonym `lex α β = α × β`.) -/ instance prod.partial_order (α : Type u) (β : Type v) [partial_order α] [partial_order β] : partial_order (α × β) := { le_antisymm := assume ⟨a, b⟩ ⟨c, d⟩ ⟨hac, hbd⟩ ⟨hca, hdb⟩, prod.ext (le_antisymm hac hca) (le_antisymm hbd hdb), .. prod.preorder α β } /-! ### Additional order classes -/ /-- order without a top element; somtimes called cofinal -/ class no_top_order (α : Type u) [preorder α] : Prop := (no_top : ∀a:α, ∃a', a < a') lemma no_top [preorder α] [no_top_order α] : ∀a:α, ∃a', a < a' := no_top_order.no_top instance nonempty_gt {α : Type u} [preorder α] [no_top_order α] (a : α) : nonempty {x // a < x} := nonempty_subtype.2 (no_top a) /-- order without a bottom element; somtimes called coinitial or dense -/ class no_bot_order (α : Type u) [preorder α] : Prop := (no_bot : ∀a:α, ∃a', a' < a) lemma no_bot [preorder α] [no_bot_order α] : ∀a:α, ∃a', a' < a := no_bot_order.no_bot instance order_dual.no_top_order (α : Type u) [preorder α] [no_bot_order α] : no_top_order (order_dual α) := ⟨λ a, @no_bot α _ _ a⟩ instance order_dual.no_bot_order (α : Type u) [preorder α] [no_top_order α] : no_bot_order (order_dual α) := ⟨λ a, @no_top α _ _ a⟩ instance nonempty_lt {α : Type u} [preorder α] [no_bot_order α] (a : α) : nonempty {x // x < a} := nonempty_subtype.2 (no_bot a) /-- An order is dense if there is an element between any pair of distinct elements. -/ class densely_ordered (α : Type u) [preorder α] : Prop := (dense : ∀a₁ a₂:α, a₁ < a₂ → ∃a, a₁ < a ∧ a < a₂) lemma exists_between [preorder α] [densely_ordered α] : ∀{a₁ a₂:α}, a₁ < a₂ → ∃a, a₁ < a ∧ a < a₂ := densely_ordered.dense instance order_dual.densely_ordered (α : Type u) [preorder α] [densely_ordered α] : densely_ordered (order_dual α) := ⟨λ a₁ a₂ ha, (@exists_between α _ _ _ _ ha).imp $ λ a, and.symm⟩ lemma le_of_forall_le_of_dense [linear_order α] [densely_ordered α] {a₁ a₂ : α} (h : ∀a₃>a₂, a₁ ≤ a₃) : a₁ ≤ a₂ := le_of_not_gt $ assume ha, let ⟨a, ha₁, ha₂⟩ := exists_between ha in lt_irrefl a $ lt_of_lt_of_le ‹a < a₁› (h _ ‹a₂ < a›) lemma eq_of_le_of_forall_le_of_dense [linear_order α] [densely_ordered α] {a₁ a₂ : α} (h₁ : a₂ ≤ a₁) (h₂ : ∀a₃>a₂, a₁ ≤ a₃) : a₁ = a₂ := le_antisymm (le_of_forall_le_of_dense h₂) h₁ lemma le_of_forall_ge_of_dense [linear_order α] [densely_ordered α] {a₁ a₂ : α} (h : ∀a₃<a₁, a₃ ≤ a₂) : a₁ ≤ a₂ := le_of_not_gt $ assume ha, let ⟨a, ha₁, ha₂⟩ := exists_between ha in lt_irrefl a $ lt_of_le_of_lt (h _ ‹a < a₁›) ‹a₂ < a› lemma eq_of_le_of_forall_ge_of_dense [linear_order α] [densely_ordered α] {a₁ a₂ : α} (h₁ : a₂ ≤ a₁) (h₂ : ∀a₃<a₁, a₃ ≤ a₂) : a₁ = a₂ := le_antisymm (le_of_forall_ge_of_dense h₂) h₁ lemma dense_or_discrete [linear_order α] (a₁ a₂ : α) : (∃a, a₁ < a ∧ a < a₂) ∨ ((∀a>a₁, a₂ ≤ a) ∧ (∀a<a₂, a ≤ a₁)) := or_iff_not_imp_left.2 $ assume h, ⟨assume a ha₁, le_of_not_gt $ assume ha₂, h ⟨a, ha₁, ha₂⟩, assume a ha₂, le_of_not_gt $ assume ha₁, h ⟨a, ha₁, ha₂⟩⟩ variables {s : β → β → Prop} {t : γ → γ → Prop} /-- Type synonym to create an instance of `linear_order` from a `partial_order` and `[is_total α (≤)]` -/ def as_linear_order (α : Type u) := α instance {α} [inhabited α] : inhabited (as_linear_order α) := ⟨ (default α : α) ⟩ noncomputable instance as_linear_order.linear_order {α} [partial_order α] [is_total α (≤)] : linear_order (as_linear_order α) := { le_total := @total_of α (≤) _, decidable_le := classical.dec_rel _, .. (_ : partial_order α) }
4603bc903c84488473102a28a2fe35fe5d64a941
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/algebra/group_ring_action.lean
c2fef4d912f9d16a443e8623ad688ce7f3ac5558
[]
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,811
lean
/- Copyright (c) 2020 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.group_theory.group_action.group import Mathlib.data.equiv.ring import Mathlib.deprecated.subring import Mathlib.PostPort universes u v l u_1 namespace Mathlib /-! # Group action on rings This file defines the typeclass of monoid acting on semirings `mul_semiring_action M R`, and the corresponding typeclass of invariant subrings. Note that `algebra` does not satisfy the axioms of `mul_semiring_action`. ## Implementation notes There is no separate typeclass for group acting on rings, group acting on fields, etc. They are all grouped under `mul_semiring_action`. ## Tags group action, invariant subring -/ /-- Typeclass for multiplicative actions by monoids on semirings. -/ class mul_semiring_action (M : Type u) [monoid M] (R : Type v) [semiring R] extends distrib_mul_action M R where smul_one : ∀ (g : M), g • 1 = 1 smul_mul : ∀ (g : M) (x y : R), g • (x * y) = g • x * g • y /-- Typeclass for faithful multiplicative actions by monoids on semirings. -/ class faithful_mul_semiring_action (M : Type u) [monoid M] (R : Type v) [semiring R] extends mul_semiring_action M R where eq_of_smul_eq_smul' : ∀ {m₁ m₂ : M}, (∀ (r : R), m₁ • r = m₂ • r) → m₁ = m₂ @[simp] theorem smul_mul' {M : Type u} [monoid M] {R : Type v} [semiring R] [mul_semiring_action M R] (g : M) (x : R) (y : R) : g • (x * y) = g • x * g • y := mul_semiring_action.smul_mul g x y theorem eq_of_smul_eq_smul {M : Type u} [monoid M] (R : Type v) [semiring R] [faithful_mul_semiring_action M R] {m₁ : M} {m₂ : M} : (∀ (r : R), m₁ • r = m₂ • r) → m₁ = m₂ := faithful_mul_semiring_action.eq_of_smul_eq_smul' /-- Each element of the monoid defines a additive monoid homomorphism. -/ def distrib_mul_action.to_add_monoid_hom (M : Type u) [monoid M] (A : Type v) [add_monoid A] [distrib_mul_action M A] (x : M) : A →+ A := add_monoid_hom.mk (has_scalar.smul x) (smul_zero x) (smul_add x) /-- Each element of the group defines an additive monoid isomorphism. -/ def distrib_mul_action.to_add_equiv (G : Type u) [group G] (A : Type v) [add_monoid A] [distrib_mul_action G A] (x : G) : A ≃+ A := add_equiv.mk (add_monoid_hom.to_fun (distrib_mul_action.to_add_monoid_hom G A x)) (equiv.inv_fun (coe_fn (mul_action.to_perm G A) x)) sorry sorry sorry /-- Each element of the group defines an additive monoid homomorphism. -/ def distrib_mul_action.hom_add_monoid_hom (M : Type u) [monoid M] (A : Type v) [add_monoid A] [distrib_mul_action M A] : M →* add_monoid.End A := monoid_hom.mk (distrib_mul_action.to_add_monoid_hom M A) sorry sorry /-- Each element of the monoid defines a semiring homomorphism. -/ def mul_semiring_action.to_semiring_hom (M : Type u) [monoid M] (R : Type v) [semiring R] [mul_semiring_action M R] (x : M) : R →+* R := ring_hom.mk (add_monoid_hom.to_fun (distrib_mul_action.to_add_monoid_hom M R x)) (smul_one x) (smul_mul' x) sorry sorry theorem injective_to_semiring_hom (M : Type u) [monoid M] (R : Type v) [semiring R] [faithful_mul_semiring_action M R] : function.injective (mul_semiring_action.to_semiring_hom M R) := fun (m₁ m₂ : M) (h : mul_semiring_action.to_semiring_hom M R m₁ = mul_semiring_action.to_semiring_hom M R m₂) => eq_of_smul_eq_smul R fun (r : R) => iff.mp ring_hom.ext_iff h r /-- Each element of the group defines a semiring isomorphism. -/ def mul_semiring_action.to_semiring_equiv (G : Type u) [group G] (R : Type v) [semiring R] [mul_semiring_action G R] (x : G) : R ≃+* R := ring_equiv.mk (add_equiv.to_fun (distrib_mul_action.to_add_equiv G R x)) (add_equiv.inv_fun (distrib_mul_action.to_add_equiv G R x)) sorry sorry sorry sorry theorem list.smul_prod (M : Type u) [monoid M] (R : Type v) [semiring R] [mul_semiring_action M R] (g : M) (L : List R) : g • list.prod L = list.prod (list.map (has_scalar.smul g) L) := monoid_hom.map_list_prod (↑(mul_semiring_action.to_semiring_hom M R g)) L theorem multiset.smul_prod (M : Type u) [monoid M] (S : Type v) [comm_semiring S] [mul_semiring_action M S] (g : M) (m : multiset S) : g • multiset.prod m = multiset.prod (multiset.map (has_scalar.smul g) m) := monoid_hom.map_multiset_prod (↑(mul_semiring_action.to_semiring_hom M S g)) m theorem smul_prod (M : Type u) [monoid M] (S : Type v) [comm_semiring S] [mul_semiring_action M S] (g : M) {ι : Type u_1} (f : ι → S) (s : finset ι) : (g • finset.prod s fun (i : ι) => f i) = finset.prod s fun (i : ι) => g • f i := monoid_hom.map_prod (↑(mul_semiring_action.to_semiring_hom M S g)) f s @[simp] theorem smul_inv {M : Type u} [monoid M] (F : Type v) [field F] [mul_semiring_action M F] (x : M) (m : F) : x • (m⁻¹) = (x • m⁻¹) := ring_hom.map_inv (mul_semiring_action.to_semiring_hom M F x) m @[simp] theorem smul_pow {M : Type u} [monoid M] {R : Type v} [semiring R] [mul_semiring_action M R] (x : M) (m : R) (n : ℕ) : x • m ^ n = (x • m) ^ n := nat.rec_on n (smul_one x) fun (n : ℕ) (ih : x • m ^ n = (x • m) ^ n) => Eq.trans (smul_mul' x m (m ^ n)) (congr_arg (Mul.mul (x • m)) ih) /-- A subring invariant under the action. -/ class is_invariant_subring (M : Type u) [monoid M] {R : Type v} [ring R] [mul_semiring_action M R] (S : set R) [is_subring S] where smul_mem : ∀ (m : M) {x : R}, x ∈ S → m • x ∈ S protected instance is_invariant_subring.to_mul_semiring_action (M : Type u) [monoid M] {R : Type v} [ring R] [mul_semiring_action M R] (S : set R) [is_subring S] [is_invariant_subring M S] : mul_semiring_action M ↥S := mul_semiring_action.mk sorry sorry
0d8ab3af403d7f70a46893ae35f8b5b450d54557
63abd62053d479eae5abf4951554e1064a4c45b4
/src/algebra/associated.lean
fe67c79709dd8a5a9fee97a4745c5b5d14bc9b78
[ "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
28,226
lean
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Jens Wagemaker -/ import data.multiset.basic import algebra.divisibility /-! # Associated, prime, and irreducible elements. -/ variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} lemma is_unit.pow [monoid α] {a : α} (n : ℕ) : is_unit a → is_unit (a ^ n) := λ ⟨u, hu⟩, ⟨u ^ n, by simp *⟩ theorem is_unit_iff_dvd_one [comm_monoid α] {x : α} : is_unit x ↔ x ∣ 1 := ⟨by rintro ⟨u, rfl⟩; exact ⟨_, u.mul_inv.symm⟩, λ ⟨y, h⟩, ⟨⟨x, y, h.symm, by rw [h, mul_comm]⟩, rfl⟩⟩ theorem is_unit_iff_forall_dvd [comm_monoid α] {x : α} : is_unit x ↔ ∀ y, x ∣ y := is_unit_iff_dvd_one.trans ⟨λ h y, dvd.trans h (one_dvd _), λ h, h _⟩ theorem is_unit_of_dvd_unit {α} [comm_monoid α] {x y : α} (xy : x ∣ y) (hu : is_unit y) : is_unit x := is_unit_iff_dvd_one.2 $ dvd_trans xy $ is_unit_iff_dvd_one.1 hu theorem is_unit_int {n : ℤ} : is_unit n ↔ n.nat_abs = 1 := ⟨begin rintro ⟨u, rfl⟩, exact (int.units_eq_one_or u).elim (by simp) (by simp) end, λ h, is_unit_iff_dvd_one.2 ⟨n, by rw [← int.nat_abs_mul_self, h]; refl⟩⟩ lemma is_unit_of_dvd_one [comm_monoid α] : ∀a ∣ 1, is_unit (a:α) | a ⟨b, eq⟩ := ⟨units.mk_of_mul_eq_one a b eq.symm, rfl⟩ lemma dvd_and_not_dvd_iff [comm_cancel_monoid_with_zero α] {x y : α} : x ∣ y ∧ ¬y ∣ x ↔ dvd_not_unit x y := ⟨λ ⟨⟨d, hd⟩, hyx⟩, ⟨λ hx0, by simpa [hx0] using hyx, ⟨d, mt is_unit_iff_dvd_one.1 (λ ⟨e, he⟩, hyx ⟨e, by rw [hd, mul_assoc, ← he, mul_one]⟩), hd⟩⟩, λ ⟨hx0, d, hdu, hdx⟩, ⟨⟨d, hdx⟩, λ ⟨e, he⟩, hdu (is_unit_of_dvd_one _ ⟨e, mul_left_cancel' hx0 $ by conv {to_lhs, rw [he, hdx]};simp [mul_assoc]⟩)⟩⟩ lemma pow_dvd_pow_iff [comm_cancel_monoid_with_zero α] {x : α} {n m : ℕ} (h0 : x ≠ 0) (h1 : ¬ is_unit x) : x ^ n ∣ x ^ m ↔ n ≤ m := begin split, { intro h, rw [← not_lt], intro hmn, apply h1, have : x ^ m * x ∣ x ^ m * 1, { rw [← pow_succ', mul_one], exact dvd_trans (pow_dvd_pow _ (nat.succ_le_of_lt hmn)) h }, rwa [mul_dvd_mul_iff_left, ← is_unit_iff_dvd_one] at this, apply pow_ne_zero m h0 }, { apply pow_dvd_pow } end section prime variables [comm_monoid_with_zero α] /-- prime element of a `comm_monoid_with_zero` -/ def prime (p : α) : Prop := p ≠ 0 ∧ ¬ is_unit p ∧ (∀a b, p ∣ a * b → p ∣ a ∨ p ∣ b) namespace prime variables {p : α} (hp : prime p) lemma ne_zero (hp : prime p) : p ≠ 0 := hp.1 lemma not_unit (hp : prime p) : ¬ is_unit p := hp.2.1 lemma ne_one (hp : prime p) : p ≠ 1 := λ h, hp.2.1 (h.symm ▸ is_unit_one) lemma div_or_div (hp : prime p) {a b : α} (h : p ∣ a * b) : p ∣ a ∨ p ∣ b := hp.2.2 a b h lemma dvd_of_dvd_pow (hp : prime p) {a : α} {n : ℕ} (h : p ∣ a^n) : p ∣ a := begin induction n with n ih, { rw pow_zero at h, have := is_unit_of_dvd_one _ h, have := not_unit hp, contradiction }, rw pow_succ at h, cases div_or_div hp h with dvd_a dvd_pow, { assumption }, exact ih dvd_pow end end prime @[simp] lemma not_prime_zero : ¬ prime (0 : α) := λ h, h.ne_zero rfl @[simp] lemma not_prime_one : ¬ prime (1 : α) := λ h, h.not_unit is_unit_one lemma exists_mem_multiset_dvd_of_prime {s : multiset α} {p : α} (hp : prime p) : p ∣ s.prod → ∃a∈s, p ∣ a := multiset.induction_on s (assume h, (hp.not_unit $ is_unit_of_dvd_one _ h).elim) $ assume a s ih h, have p ∣ a * s.prod, by simpa using h, match hp.div_or_div this with | or.inl h := ⟨a, multiset.mem_cons_self a s, h⟩ | or.inr h := let ⟨a, has, h⟩ := ih h in ⟨a, multiset.mem_cons_of_mem has, h⟩ end end prime lemma left_dvd_or_dvd_right_of_dvd_prime_mul [comm_cancel_monoid_with_zero α] {a : α} : ∀ {b p : α}, prime p → a ∣ p * b → p ∣ a ∨ a ∣ b := begin rintros b p hp ⟨c, hc⟩, rcases hp.2.2 a c (hc ▸ dvd_mul_right _ _) with h | ⟨x, rfl⟩, { exact or.inl h }, { rw [mul_left_comm, mul_right_inj' hp.ne_zero] at hc, exact or.inr (hc.symm ▸ dvd_mul_right _ _) } end /-- `irreducible p` states that `p` is non-unit and only factors into units. We explicitly avoid stating that `p` is non-zero, this would require a semiring. Assuming only a monoid allows us to reuse irreducible for associated elements. -/ @[class] def irreducible [monoid α] (p : α) : Prop := ¬ is_unit p ∧ ∀a b, p = a * b → is_unit a ∨ is_unit b namespace irreducible lemma not_unit [monoid α] {p : α} (hp : irreducible p) : ¬ is_unit p := hp.1 lemma is_unit_or_is_unit [monoid α] {p : α} (hp : irreducible p) {a b : α} (h : p = a * b) : is_unit a ∨ is_unit b := hp.2 a b h end irreducible @[simp] theorem not_irreducible_one [monoid α] : ¬ irreducible (1 : α) := by simp [irreducible] @[simp] theorem not_irreducible_zero [monoid_with_zero α] : ¬ irreducible (0 : α) | ⟨hn0, h⟩ := have is_unit (0:α) ∨ is_unit (0:α), from h 0 0 ((mul_zero 0).symm), this.elim hn0 hn0 theorem irreducible.ne_zero [monoid_with_zero α] : ∀ {p:α}, irreducible p → p ≠ 0 | _ hp rfl := not_irreducible_zero hp theorem of_irreducible_mul {α} [monoid α] {x y : α} : irreducible (x * y) → is_unit x ∨ is_unit y | ⟨_, h⟩ := h _ _ rfl theorem irreducible_or_factor {α} [monoid α] (x : α) (h : ¬ is_unit x) : irreducible x ∨ ∃ a b, ¬ is_unit a ∧ ¬ is_unit b ∧ a * b = x := begin haveI := classical.dec, refine or_iff_not_imp_right.2 (λ H, _), simp [h, irreducible] at H ⊢, refine λ a b h, classical.by_contradiction $ λ o, _, simp [not_or_distrib] at o, exact H _ o.1 _ o.2 h.symm end lemma irreducible_of_prime [comm_cancel_monoid_with_zero α] {p : α} (hp : prime p) : irreducible p := ⟨hp.not_unit, λ a b hab, (show a * b ∣ a ∨ a * b ∣ b, from hab ▸ hp.div_or_div (hab ▸ (dvd_refl _))).elim (λ ⟨x, hx⟩, or.inr (is_unit_iff_dvd_one.2 ⟨x, mul_right_cancel' (show a ≠ 0, from λ h, by simp [*, prime] at *) $ by conv {to_lhs, rw hx}; simp [mul_comm, mul_assoc, mul_left_comm]⟩)) (λ ⟨x, hx⟩, or.inl (is_unit_iff_dvd_one.2 ⟨x, mul_right_cancel' (show b ≠ 0, from λ h, by simp [*, prime] at *) $ by conv {to_lhs, rw hx}; simp [mul_comm, mul_assoc, mul_left_comm]⟩))⟩ lemma succ_dvd_or_succ_dvd_of_succ_sum_dvd_mul [comm_cancel_monoid_with_zero α] {p : α} (hp : prime p) {a b : α} {k l : ℕ} : p ^ k ∣ a → p ^ l ∣ b → p ^ ((k + l) + 1) ∣ a * b → p ^ (k + 1) ∣ a ∨ p ^ (l + 1) ∣ b := λ ⟨x, hx⟩ ⟨y, hy⟩ ⟨z, hz⟩, have h : p ^ (k + l) * (x * y) = p ^ (k + l) * (p * z), by simpa [mul_comm, pow_add, hx, hy, mul_assoc, mul_left_comm] using hz, have hp0: p ^ (k + l) ≠ 0, from pow_ne_zero _ hp.ne_zero, have hpd : p ∣ x * y, from ⟨z, by rwa [mul_right_inj' hp0] at h⟩, (hp.div_or_div hpd).elim (λ ⟨d, hd⟩, or.inl ⟨d, by simp [*, pow_succ, mul_comm, mul_left_comm, mul_assoc]⟩) (λ ⟨d, hd⟩, or.inr ⟨d, by simp [*, pow_succ, mul_comm, mul_left_comm, mul_assoc]⟩) /-- If `p` and `q` are irreducible, then `p ∣ q` implies `q ∣ p`. -/ lemma dvd_symm_of_irreducible [monoid α] {p q : α} (hp : irreducible p) (hq : irreducible q) : p ∣ q → q ∣ p := begin tactic.unfreeze_local_instances, rintros ⟨q', rfl⟩, rw is_unit.mul_right_dvd (or.resolve_left (of_irreducible_mul hq) hp.not_unit), end lemma dvd_symm_iff_of_irreducible [monoid α] {p q : α} (hp : irreducible p) (hq : irreducible q) : p ∣ q ↔ q ∣ p := ⟨dvd_symm_of_irreducible hp hq, dvd_symm_of_irreducible hq hp⟩ /-- Two elements of a `monoid` are `associated` if one of them is another one multiplied by a unit on the right. -/ def associated [monoid α] (x y : α) : Prop := ∃u:units α, x * u = y local infix ` ~ᵤ ` : 50 := associated namespace associated @[refl] protected theorem refl [monoid α] (x : α) : x ~ᵤ x := ⟨1, by simp⟩ @[symm] protected theorem symm [monoid α] : ∀{x y : α}, x ~ᵤ y → y ~ᵤ x | x _ ⟨u, rfl⟩ := ⟨u⁻¹, by rw [mul_assoc, units.mul_inv, mul_one]⟩ @[trans] protected theorem trans [monoid α] : ∀{x y z : α}, x ~ᵤ y → y ~ᵤ z → x ~ᵤ z | x _ _ ⟨u, rfl⟩ ⟨v, rfl⟩ := ⟨u * v, by rw [units.coe_mul, mul_assoc]⟩ /-- The setoid of the relation `x ~ᵤ y` iff there is a unit `u` such that `x * u = y` -/ protected def setoid (α : Type*) [monoid α] : setoid α := { r := associated, iseqv := ⟨associated.refl, λa b, associated.symm, λa b c, associated.trans⟩ } end associated local attribute [instance] associated.setoid theorem unit_associated_one [monoid α] {u : units α} : (u : α) ~ᵤ 1 := ⟨u⁻¹, units.mul_inv u⟩ theorem associated_one_iff_is_unit [monoid α] {a : α} : (a : α) ~ᵤ 1 ↔ is_unit a := iff.intro (assume h, let ⟨c, h⟩ := h.symm in h ▸ ⟨c, (one_mul _).symm⟩) (assume ⟨c, h⟩, associated.symm ⟨c, by simp [h]⟩) theorem associated_zero_iff_eq_zero [monoid_with_zero α] (a : α) : a ~ᵤ 0 ↔ a = 0 := iff.intro (assume h, let ⟨u, h⟩ := h.symm in by simpa using h.symm) (assume h, h ▸ associated.refl a) theorem associated_one_of_mul_eq_one [comm_monoid α] {a : α} (b : α) (hab : a * b = 1) : a ~ᵤ 1 := show (units.mk_of_mul_eq_one a b hab : α) ~ᵤ 1, from unit_associated_one theorem associated_one_of_associated_mul_one [comm_monoid α] {a b : α} : a * b ~ᵤ 1 → a ~ᵤ 1 | ⟨u, h⟩ := associated_one_of_mul_eq_one (b * u) $ by simpa [mul_assoc] using h lemma associated_mul_mul [comm_monoid α] {a₁ a₂ b₁ b₂ : α} : a₁ ~ᵤ b₁ → a₂ ~ᵤ b₂ → (a₁ * a₂) ~ᵤ (b₁ * b₂) | ⟨c₁, h₁⟩ ⟨c₂, h₂⟩ := ⟨c₁ * c₂, by simp [h₁.symm, h₂.symm, mul_assoc, mul_comm, mul_left_comm]⟩ lemma dvd_of_associated [monoid α] {a b : α} : a ~ᵤ b → a ∣ b := λ ⟨u, hu⟩, ⟨u, hu.symm⟩ lemma dvd_dvd_of_associated [monoid α] {a b : α} (h : a ~ᵤ b) : a ∣ b ∧ b ∣ a := ⟨dvd_of_associated h, dvd_of_associated h.symm⟩ theorem associated_of_dvd_dvd [cancel_monoid_with_zero α] {a b : α} (hab : a ∣ b) (hba : b ∣ a) : a ~ᵤ b := begin rcases hab with ⟨c, rfl⟩, rcases hba with ⟨d, a_eq⟩, by_cases ha0 : a = 0, { simp [*] at * }, have hac0 : a * c ≠ 0, { intro con, rw [con, zero_mul] at a_eq, apply ha0 a_eq, }, have : a * (c * d) = a * 1 := by rw [← mul_assoc, ← a_eq, mul_one], have hcd : (c * d) = 1, from mul_left_cancel' ha0 this, have : a * c * (d * c) = a * c * 1 := by rw [← mul_assoc, ← a_eq, mul_one], have hdc : d * c = 1, from mul_left_cancel' hac0 this, exact ⟨⟨c, d, hcd, hdc⟩, rfl⟩ end theorem dvd_dvd_iff_associated [cancel_monoid_with_zero α] {a b : α} : a ∣ b ∧ b ∣ a ↔ a ~ᵤ b := ⟨λ ⟨h1, h2⟩, associated_of_dvd_dvd h1 h2, dvd_dvd_of_associated⟩ lemma exists_associated_mem_of_dvd_prod [comm_cancel_monoid_with_zero α] {p : α} (hp : prime p) {s : multiset α} : (∀ r ∈ s, prime r) → p ∣ s.prod → ∃ q ∈ s, p ~ᵤ q := multiset.induction_on s (by simp [mt is_unit_iff_dvd_one.2 hp.not_unit]) (λ a s ih hs hps, begin rw [multiset.prod_cons] at hps, cases hp.div_or_div hps with h h, { use [a, by simp], cases h with u hu, cases ((irreducible_of_prime (hs a (multiset.mem_cons.2 (or.inl rfl)))).2 p u hu).resolve_left hp.not_unit with v hv, exact ⟨v, by simp [hu, hv]⟩ }, { rcases ih (λ r hr, hs _ (multiset.mem_cons.2 (or.inr hr))) h with ⟨q, hq₁, hq₂⟩, exact ⟨q, multiset.mem_cons.2 (or.inr hq₁), hq₂⟩ } end) lemma dvd_iff_dvd_of_rel_left [comm_monoid_with_zero α] {a b c : α} (h : a ~ᵤ b) : a ∣ c ↔ b ∣ c := let ⟨u, hu⟩ := h in hu ▸ units.mul_right_dvd.symm lemma dvd_iff_dvd_of_rel_right [comm_monoid_with_zero α] {a b c : α} (h : b ~ᵤ c) : a ∣ b ↔ a ∣ c := let ⟨u, hu⟩ := h in hu ▸ units.dvd_mul_right.symm lemma eq_zero_iff_of_associated [comm_monoid_with_zero α] {a b : α} (h : a ~ᵤ b) : a = 0 ↔ b = 0 := ⟨λ ha, let ⟨u, hu⟩ := h in by simp [hu.symm, ha], λ hb, let ⟨u, hu⟩ := h.symm in by simp [hu.symm, hb]⟩ lemma ne_zero_iff_of_associated [comm_monoid_with_zero α] {a b : α} (h : a ~ᵤ b) : a ≠ 0 ↔ b ≠ 0 := by haveI := classical.dec; exact not_iff_not.2 (eq_zero_iff_of_associated h) lemma prime_of_associated [comm_monoid_with_zero α] {p q : α} (h : p ~ᵤ q) (hp : prime p) : prime q := ⟨(ne_zero_iff_of_associated h).1 hp.ne_zero, let ⟨u, hu⟩ := h in ⟨λ ⟨v, hv⟩, hp.not_unit ⟨v * u⁻¹, by simp [hv, hu.symm]⟩, hu ▸ by { simp [units.mul_right_dvd], intros a b, exact hp.div_or_div }⟩⟩ lemma prime_iff_of_associated [comm_monoid_with_zero α] {p q : α} (h : p ~ᵤ q) : prime p ↔ prime q := ⟨prime_of_associated h, prime_of_associated h.symm⟩ lemma is_unit_iff_of_associated [monoid α] {a b : α} (h : a ~ᵤ b) : is_unit a ↔ is_unit b := ⟨let ⟨u, hu⟩ := h in λ ⟨v, hv⟩, ⟨v * u, by simp [hv, hu.symm]⟩, let ⟨u, hu⟩ := h.symm in λ ⟨v, hv⟩, ⟨v * u, by simp [hv, hu.symm]⟩⟩ lemma irreducible_of_associated [comm_monoid_with_zero α] {p q : α} (h : p ~ᵤ q) (hp : irreducible p) : irreducible q := ⟨mt (is_unit_iff_of_associated h).2 hp.1, let ⟨u, hu⟩ := h in λ a b hab, have hpab : p = a * (b * (u⁻¹ : units α)), from calc p = (p * u) * (u ⁻¹ : units α) : by simp ... = _ : by rw hu; simp [hab, mul_assoc], (hp.2 _ _ hpab).elim or.inl (λ ⟨v, hv⟩, or.inr ⟨v * u, by simp [hv]⟩)⟩ lemma irreducible_iff_of_associated [comm_monoid_with_zero α] {p q : α} (h : p ~ᵤ q) : irreducible p ↔ irreducible q := ⟨irreducible_of_associated h, irreducible_of_associated h.symm⟩ lemma associated_mul_left_cancel [comm_cancel_monoid_with_zero α] {a b c d : α} (h : a * b ~ᵤ c * d) (h₁ : a ~ᵤ c) (ha : a ≠ 0) : b ~ᵤ d := let ⟨u, hu⟩ := h in let ⟨v, hv⟩ := associated.symm h₁ in ⟨u * (v : units α), mul_left_cancel' ha begin rw [← hv, mul_assoc c (v : α) d, mul_left_comm c, ← hu], simp [hv.symm, mul_assoc, mul_comm, mul_left_comm] end⟩ lemma associated_mul_right_cancel [comm_cancel_monoid_with_zero α] {a b c d : α} : a * b ~ᵤ c * d → b ~ᵤ d → b ≠ 0 → a ~ᵤ c := by rw [mul_comm a, mul_comm c]; exact associated_mul_left_cancel section unique_units variables [monoid α] [unique (units α)] theorem associated_iff_eq {x y : α} : x ~ᵤ y ↔ x = y := begin split, { rintro ⟨c, rfl⟩, simp [subsingleton.elim c 1] }, { rintro rfl, refl }, end theorem associated_eq_eq : (associated : α → α → Prop) = eq := by { ext, rw associated_iff_eq } end unique_units /-- The quotient of a monoid by the `associated` relation. Two elements `x` and `y` are associated iff there is a unit `u` such that `x * u = y`. There is a natural monoid structure on `associates α`. -/ def associates (α : Type*) [monoid α] : Type* := quotient (associated.setoid α) namespace associates open associated /-- The canonical quotient map from a monoid `α` into the `associates` of `α` -/ protected def mk {α : Type*} [monoid α] (a : α) : associates α := ⟦ a ⟧ instance [monoid α] : inhabited (associates α) := ⟨⟦1⟧⟩ theorem mk_eq_mk_iff_associated [monoid α] {a b : α} : associates.mk a = associates.mk b ↔ a ~ᵤ b := iff.intro quotient.exact quot.sound theorem quotient_mk_eq_mk [monoid α] (a : α) : ⟦ a ⟧ = associates.mk a := rfl theorem quot_mk_eq_mk [monoid α] (a : α) : quot.mk setoid.r a = associates.mk a := rfl theorem forall_associated [monoid α] {p : associates α → Prop} : (∀a, p a) ↔ (∀a, p (associates.mk a)) := iff.intro (assume h a, h _) (assume h a, quotient.induction_on a h) theorem mk_surjective [monoid α] : function.surjective (@associates.mk α _) := forall_associated.2 (λ a, ⟨a, rfl⟩) instance [monoid α] : has_one (associates α) := ⟨⟦ 1 ⟧⟩ theorem one_eq_mk_one [monoid α] : (1 : associates α) = associates.mk 1 := rfl instance [monoid α] : has_bot (associates α) := ⟨1⟩ lemma exists_rep [monoid α] (a : associates α) : ∃ a0 : α, associates.mk a0 = a := quot.exists_rep a section comm_monoid variable [comm_monoid α] instance : has_mul (associates α) := ⟨λa' b', quotient.lift_on₂ a' b' (λa b, ⟦ a * b ⟧) $ assume a₁ a₂ b₁ b₂ ⟨c₁, h₁⟩ ⟨c₂, h₂⟩, quotient.sound $ ⟨c₁ * c₂, by simp [h₁.symm, h₂.symm, mul_assoc, mul_comm, mul_left_comm]⟩⟩ theorem mk_mul_mk {x y : α} : associates.mk x * associates.mk y = associates.mk (x * y) := rfl instance : comm_monoid (associates α) := { one := 1, mul := (*), mul_one := assume a', quotient.induction_on a' $ assume a, show ⟦a * 1⟧ = ⟦ a ⟧, by simp, one_mul := assume a', quotient.induction_on a' $ assume a, show ⟦1 * a⟧ = ⟦ a ⟧, by simp, mul_assoc := assume a' b' c', quotient.induction_on₃ a' b' c' $ assume a b c, show ⟦a * b * c⟧ = ⟦a * (b * c)⟧, by rw [mul_assoc], mul_comm := assume a' b', quotient.induction_on₂ a' b' $ assume a b, show ⟦a * b⟧ = ⟦b * a⟧, by rw [mul_comm] } instance : preorder (associates α) := { le := has_dvd.dvd, le_refl := dvd_refl, le_trans := λ a b c, dvd_trans} @[simp] lemma mk_one : associates.mk (1 : α) = 1 := rfl /-- `associates.mk` as a `monoid_hom`. -/ protected def mk_monoid_hom : α →* (associates α) := ⟨associates.mk, mk_one, λ x y, mk_mul_mk⟩ @[simp] lemma mk_monoid_hom_apply (a : α) : associates.mk_monoid_hom a = associates.mk a := rfl lemma associated_map_mk {f : associates α →* α} (hinv : function.right_inverse f associates.mk) (a : α) : a ~ᵤ f (associates.mk a) := associates.mk_eq_mk_iff_associated.1 (hinv (associates.mk a)).symm lemma mk_pow (a : α) (n : ℕ) : associates.mk (a ^ n) = (associates.mk a) ^ n := by induction n; simp [*, pow_succ, associates.mk_mul_mk.symm] lemma dvd_eq_le : ((∣) : associates α → associates α → Prop) = (≤) := rfl theorem prod_mk {p : multiset α} : (p.map associates.mk).prod = associates.mk p.prod := multiset.induction_on p (by simp; refl) $ assume a s ih, by simp [ih]; refl theorem rel_associated_iff_map_eq_map {p q : multiset α} : multiset.rel associated p q ↔ p.map associates.mk = q.map associates.mk := by rw [← multiset.rel_eq]; simp [multiset.rel_map_left, multiset.rel_map_right, mk_eq_mk_iff_associated] theorem mul_eq_one_iff {x y : associates α} : x * y = 1 ↔ (x = 1 ∧ y = 1) := iff.intro (quotient.induction_on₂ x y $ assume a b h, have a * b ~ᵤ 1, from quotient.exact h, ⟨quotient.sound $ associated_one_of_associated_mul_one this, quotient.sound $ associated_one_of_associated_mul_one $ by rwa [mul_comm] at this⟩) (by simp {contextual := tt}) theorem prod_eq_one_iff {p : multiset (associates α)} : p.prod = 1 ↔ (∀a ∈ p, (a:associates α) = 1) := multiset.induction_on p (by simp) (by simp [mul_eq_one_iff, or_imp_distrib, forall_and_distrib] {contextual := tt}) theorem units_eq_one (u : units (associates α)) : u = 1 := units.ext (mul_eq_one_iff.1 u.val_inv).1 instance unique_units : unique (units (associates α)) := { default := 1, uniq := associates.units_eq_one } theorem coe_unit_eq_one (u : units (associates α)): (u : associates α) = 1 := by simp theorem is_unit_iff_eq_one (a : associates α) : is_unit a ↔ a = 1 := iff.intro (assume ⟨u, h⟩, h ▸ coe_unit_eq_one _) (assume h, h.symm ▸ is_unit_one) theorem is_unit_mk {a : α} : is_unit (associates.mk a) ↔ is_unit a := calc is_unit (associates.mk a) ↔ a ~ᵤ 1 : by rw [is_unit_iff_eq_one, one_eq_mk_one, mk_eq_mk_iff_associated] ... ↔ is_unit a : associated_one_iff_is_unit section order theorem mul_mono {a b c d : associates α} (h₁ : a ≤ b) (h₂ : c ≤ d) : a * c ≤ b * d := let ⟨x, hx⟩ := h₁, ⟨y, hy⟩ := h₂ in ⟨x * y, by simp [hx, hy, mul_comm, mul_assoc, mul_left_comm]⟩ theorem one_le {a : associates α} : 1 ≤ a := dvd.intro _ (one_mul a) theorem prod_le_prod {p q : multiset (associates α)} (h : p ≤ q) : p.prod ≤ q.prod := begin haveI := classical.dec_eq (associates α), haveI := classical.dec_eq α, suffices : p.prod ≤ (p + (q - p)).prod, { rwa [multiset.add_sub_of_le h] at this }, suffices : p.prod * 1 ≤ p.prod * (q - p).prod, { simpa }, exact mul_mono (le_refl p.prod) one_le end theorem le_mul_right {a b : associates α} : a ≤ a * b := ⟨b, rfl⟩ theorem le_mul_left {a b : associates α} : a ≤ b * a := by rw [mul_comm]; exact le_mul_right end order end comm_monoid instance [has_zero α] [monoid α] : has_zero (associates α) := ⟨⟦ 0 ⟧⟩ instance [has_zero α] [monoid α] : has_top (associates α) := ⟨0⟩ section comm_monoid_with_zero variables [comm_monoid_with_zero α] @[simp] theorem mk_eq_zero {a : α} : associates.mk a = 0 ↔ a = 0 := ⟨assume h, (associated_zero_iff_eq_zero a).1 $ quotient.exact h, assume h, h.symm ▸ rfl⟩ instance : comm_monoid_with_zero (associates α) := { zero_mul := by { rintro ⟨a⟩, show associates.mk (0 * a) = associates.mk 0, rw [zero_mul] }, mul_zero := by { rintro ⟨a⟩, show associates.mk (a * 0) = associates.mk 0, rw [mul_zero] }, .. associates.comm_monoid, .. associates.has_zero } instance [nontrivial α] : nontrivial (associates α) := ⟨⟨0, 1, assume h, have (0 : α) ~ᵤ 1, from quotient.exact h, have (0 : α) = 1, from ((associated_zero_iff_eq_zero 1).1 this.symm).symm, zero_ne_one this⟩⟩ lemma exists_non_zero_rep {a : associates α} : a ≠ 0 → ∃ a0 : α, a0 ≠ 0 ∧ associates.mk a0 = a := quotient.induction_on a (λ b nz, ⟨b, mt (congr_arg quotient.mk) nz, rfl⟩) theorem dvd_of_mk_le_mk {a b : α} : associates.mk a ≤ associates.mk b → a ∣ b | ⟨c', hc'⟩ := (quotient.induction_on c' $ assume c hc, let ⟨d, hd⟩ := (quotient.exact hc).symm in ⟨(↑d) * c, calc b = (a * c) * ↑d : hd.symm ... = a * (↑d * c) : by ac_refl⟩) hc' theorem mk_le_mk_of_dvd {a b : α} : a ∣ b → associates.mk a ≤ associates.mk b := assume ⟨c, hc⟩, ⟨associates.mk c, by simp [hc]; refl⟩ theorem mk_le_mk_iff_dvd_iff {a b : α} : associates.mk a ≤ associates.mk b ↔ a ∣ b := iff.intro dvd_of_mk_le_mk mk_le_mk_of_dvd theorem mk_dvd_mk {a b : α} : associates.mk a ∣ associates.mk b ↔ a ∣ b := iff.intro dvd_of_mk_le_mk mk_le_mk_of_dvd lemma prime.le_or_le {p : associates α} (hp : prime p) {a b : associates α} (h : p ≤ a * b) : p ≤ a ∨ p ≤ b := hp.2.2 a b h lemma exists_mem_multiset_le_of_prime {s : multiset (associates α)} {p : associates α} (hp : prime p) : p ≤ s.prod → ∃a∈s, p ≤ a := multiset.induction_on s (assume ⟨d, eq⟩, (hp.ne_one (mul_eq_one_iff.1 eq.symm).1).elim) $ assume a s ih h, have p ≤ a * s.prod, by simpa using h, match prime.le_or_le hp this with | or.inl h := ⟨a, multiset.mem_cons_self a s, h⟩ | or.inr h := let ⟨a, has, h⟩ := ih h in ⟨a, multiset.mem_cons_of_mem has, h⟩ end lemma prime_mk (p : α) : prime (associates.mk p) ↔ _root_.prime p := begin rw [prime, _root_.prime, forall_associated], transitivity, { apply and_congr, refl, apply and_congr, refl, apply forall_congr, assume a, exact forall_associated }, apply and_congr, { rw [(≠), mk_eq_zero] }, apply and_congr, { rw [is_unit_mk], }, apply forall_congr, assume a, apply forall_congr, assume b, rw [mk_mul_mk, mk_dvd_mk, mk_dvd_mk, mk_dvd_mk], end theorem irreducible_mk (a : α) : irreducible (associates.mk a) ↔ irreducible a := begin simp only [irreducible, is_unit_mk], apply and_congr iff.rfl, split, { rintro h x y rfl, simpa [is_unit_mk] using h (associates.mk x) (associates.mk y) rfl }, { intros h x y, refine quotient.induction_on₂ x y (assume x y a_eq, _), rcases quotient.exact a_eq.symm with ⟨u, a_eq⟩, rw mul_assoc at a_eq, show is_unit (associates.mk x) ∨ is_unit (associates.mk y), simpa [is_unit_mk] using h _ _ a_eq.symm } end theorem mk_dvd_not_unit_mk_iff {a b : α} : dvd_not_unit (associates.mk a) (associates.mk b) ↔ dvd_not_unit a b := begin rw [dvd_not_unit, dvd_not_unit, ne, ne, mk_eq_zero], apply and_congr_right, intro ane0, split, { contrapose!, rw forall_associated, intros h x hx hbax, rw [mk_mul_mk, mk_eq_mk_iff_associated] at hbax, cases hbax with u hu, apply h (x * ↑u⁻¹), { rw is_unit_mk at hx, rw is_unit_iff_of_associated, apply hx, use u, simp, }, simp [← mul_assoc, ← hu] }, { rintro ⟨x, ⟨hx, rfl⟩⟩, use associates.mk x, simp [is_unit_mk, mk_mul_mk, hx], } end theorem dvd_not_unit_of_lt {a b : associates α} (hlt : a < b) : dvd_not_unit a b := begin split, { rintro rfl, apply not_lt_of_le _ hlt, apply dvd_zero }, rcases hlt with ⟨⟨x, rfl⟩, ndvd⟩, refine ⟨x, _, rfl⟩, contrapose! ndvd, rcases ndvd with ⟨u, rfl⟩, simp, end end comm_monoid_with_zero section comm_cancel_monoid_with_zero variable [comm_cancel_monoid_with_zero α] instance : partial_order (associates α) := { le_antisymm := λ a' b', quotient.induction_on₂ a' b' (λ a b hab hba, quot.sound $ associated_of_dvd_dvd (dvd_of_mk_le_mk hab) (dvd_of_mk_le_mk hba)) .. associates.preorder } instance : order_bot (associates α) := { bot := 1, bot_le := assume a, one_le, .. associates.partial_order } instance : order_top (associates α) := { top := 0, le_top := assume a, ⟨0, (mul_zero a).symm⟩, .. associates.partial_order } instance : no_zero_divisors (associates α) := ⟨λ x y, (quotient.induction_on₂ x y $ assume a b h, have a * b = 0, from (associated_zero_iff_eq_zero _).1 (quotient.exact h), have a = 0 ∨ b = 0, from mul_eq_zero.1 this, this.imp (assume h, h.symm ▸ rfl) (assume h, h.symm ▸ rfl))⟩ theorem irreducible_iff_prime_iff : (∀ a : α, irreducible a ↔ prime a) ↔ (∀ a : (associates α), irreducible a ↔ prime a) := begin rw forall_associated, split; intros h a; have ha := h a; rw irreducible_mk at *; rw prime_mk at *; exact ha, end lemma eq_of_mul_eq_mul_left : ∀(a b c : associates α), a ≠ 0 → a * b = a * c → b = c := begin rintros ⟨a⟩ ⟨b⟩ ⟨c⟩ ha h, rcases quotient.exact' h with ⟨u, hu⟩, have hu : a * (b * ↑u) = a * c, { rwa [← mul_assoc] }, exact quotient.sound' ⟨u, mul_left_cancel' (mt mk_eq_zero.2 ha) hu⟩ end lemma eq_of_mul_eq_mul_right : ∀(a b c : associates α), b ≠ 0 → a * b = c * b → a = c := λ a b c bne0, (mul_comm b a) ▸ (mul_comm b c) ▸ (eq_of_mul_eq_mul_left b a c bne0) lemma le_of_mul_le_mul_left (a b c : associates α) (ha : a ≠ 0) : a * b ≤ a * c → b ≤ c | ⟨d, hd⟩ := ⟨d, eq_of_mul_eq_mul_left a _ _ ha $ by rwa ← mul_assoc⟩ lemma one_or_eq_of_le_of_prime : ∀(p m : associates α), prime p → m ≤ p → (m = 1 ∨ m = p) | _ m ⟨hp0, hp1, h⟩ ⟨d, rfl⟩ := match h m d (dvd_refl _) with | or.inl h := classical.by_cases (assume : m = 0, by simp [this]) $ assume : m ≠ 0, have m * d ≤ m * 1, by simpa using h, have d ≤ 1, from associates.le_of_mul_le_mul_left m d 1 ‹m ≠ 0› this, have d = 1, from bot_unique this, by simp [this] | or.inr h := classical.by_cases (assume : d = 0, by simp [this] at hp0; contradiction) $ assume : d ≠ 0, have d * m ≤ d * 1, by simpa [mul_comm] using h, or.inl $ bot_unique $ associates.le_of_mul_le_mul_left d m 1 ‹d ≠ 0› this end instance : comm_cancel_monoid_with_zero (associates α) := { mul_left_cancel_of_ne_zero := eq_of_mul_eq_mul_left, mul_right_cancel_of_ne_zero := eq_of_mul_eq_mul_right, .. (infer_instance : comm_monoid_with_zero (associates α)) } theorem dvd_not_unit_iff_lt {a b : associates α} : dvd_not_unit a b ↔ a < b := dvd_and_not_dvd_iff.symm end comm_cancel_monoid_with_zero end associates
d97862d921cfb1e5c48eb38c25a0873e03014701
05f637fa14ac28031cb1ea92086a0f4eb23ff2b1
/tests/lean/bad7.lean
8b015e25d65b2a214d0bea9adc76381b05fea38c
[ "Apache-2.0" ]
permissive
codyroux/lean0.1
1ce92751d664aacff0529e139083304a7bbc8a71
0dc6fb974aa85ed6f305a2f4b10a53a44ee5f0ef
refs/heads/master
1,610,830,535,062
1,402,150,480,000
1,402,150,480,000
19,588,851
2
0
null
null
null
null
UTF-8
Lean
false
false
153
lean
import Real. variable f {A : Type} (a b : A) : Bool variable a : Int variable b : Real definition tst : Bool := (fun x y, f x y) a b print environment 1
b0cb63421fb2767e330201c942881fb280fc8d91
6dc0c8ce7a76229dd81e73ed4474f15f88a9e294
/stage0/src/Lean/Data/Options.lean
57ff1429a4c16402ffc0f7cfa8f81ae17cd3c860
[ "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,351
lean
/- Copyright (c) 2018 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich and Leonardo de Moura -/ import Lean.Data.KVMap namespace Lean def Options := KVMap def Options.empty : Options := {} instance : Inhabited Options where default := {} instance : ToString Options := inferInstanceAs (ToString KVMap) structure OptionDecl where defValue : DataValue group : String := "" descr : String := "" deriving Inhabited def OptionDecls := NameMap OptionDecl instance : Inhabited OptionDecls := ⟨({} : NameMap OptionDecl)⟩ private def initOptionDeclsRef : IO (IO.Ref OptionDecls) := IO.mkRef (mkNameMap OptionDecl) @[builtinInit initOptionDeclsRef] private constant optionDeclsRef : IO.Ref OptionDecls @[export lean_register_option] def registerOption (name : Name) (decl : OptionDecl) : IO Unit := do let decls ← optionDeclsRef.get if decls.contains name then throw $ IO.userError s!"invalid option declaration '{name}', option already exists" optionDeclsRef.set $ decls.insert name decl def getOptionDecls : IO OptionDecls := optionDeclsRef.get @[export lean_get_option_decls_array] def getOptionDeclsArray : IO (Array (Name × OptionDecl)) := do let decls ← getOptionDecls pure $ decls.fold (fun (r : Array (Name × OptionDecl)) k v => r.push (k, v)) #[] def getOptionDecl (name : Name) : IO OptionDecl := do let decls ← getOptionDecls let (some decl) ← pure (decls.find? name) | throw $ IO.userError s!"unknown option '{name}'" pure decl def getOptionDefaulValue (name : Name) : IO DataValue := do let decl ← getOptionDecl name pure decl.defValue def getOptionDescr (name : Name) : IO String := do let decl ← getOptionDecl name pure decl.descr def setOptionFromString (opts : Options) (entry : String) : IO Options := do let ps := (entry.splitOn "=").map String.trim let [key, val] ← pure ps | throw $ IO.userError "invalid configuration option entry, it must be of the form '<key> = <value>'" let key := Name.mkSimple key let defValue ← getOptionDefaulValue key match defValue with | DataValue.ofString v => pure $ opts.setString key val | DataValue.ofBool v => if key == `true then pure $ opts.setBool key true else if key == `false then pure $ opts.setBool key false else throw $ IO.userError s!"invalid Bool option value '{val}'" | DataValue.ofName v => pure $ opts.setName key val.toName | DataValue.ofNat v => match val.toNat? with | none => throw (IO.userError s!"invalid Nat option value '{val}'") | some v => pure $ opts.setNat key v | DataValue.ofInt v => match val.toInt? with | none => throw (IO.userError s!"invalid Int option value '{val}'") | some v => pure $ opts.setInt key v class MonadOptions (m : Type → Type) where getOptions : m Options export MonadOptions (getOptions) instance (m n) [MonadLift m n] [MonadOptions m] : MonadOptions n where getOptions := liftM (getOptions : m _) variable {m} [Monad m] [MonadOptions m] def getBoolOption (k : Name) (defValue := false) : m Bool := do let opts ← getOptions pure $ opts.getBool k defValue def getNatOption (k : Name) (defValue := 0) : m Nat := do let opts ← getOptions pure $ opts.getNat k defValue /-- A strongly-typed reference to an option. -/ protected structure Option (α : Type) where name : Name defValue : α deriving Inhabited namespace Option protected structure Decl (α : Type) where defValue : α group : String := "" descr : String := "" protected def get [KVMap.Value α] (opts : Options) (opt : Lean.Option α) : α := opts.get opt.name opt.defValue protected def set [KVMap.Value α] (opts : Options) (opt : Lean.Option α) (val: α) : Options := opts.set opt.name val protected def register [KVMap.Value α] (name : Name) (decl : Lean.Option.Decl α) : IO (Lean.Option α) := do registerOption name { defValue := KVMap.Value.toDataValue decl.defValue, group := decl.group, descr := decl.descr } return { name := name, defValue := decl.defValue } macro "register_builtin_option" name:ident " : " type:term " := " decl:term : command => `(builtin_initialize $name : Lean.Option $type ← Lean.Option.register $(quote name.getId) $decl) end Option end Lean
ec98baebea5c27820a039bbcd2b7a4bb432bfa69
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/library/data/finset/bigops.lean
a700cdc338356bc98fb09a779c7d1bc98333c091
[ "Apache-2.0" ]
permissive
soonhokong/lean-osx
4a954262c780e404c1369d6c06516161d07fcb40
3670278342d2f4faa49d95b46d86642d7875b47c
refs/heads/master
1,611,410,334,552
1,474,425,686,000
1,474,425,686,000
12,043,103
5
1
null
null
null
null
UTF-8
Lean
false
false
5,565
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad, Haitao Zhang Finite unions and intersections on finsets. Note: for the moment we only do unions. We need to generalize bigops for intersections. -/ import data.finset.comb algebra.group_bigops open list namespace finset variables {A B : Type} [deceqA : decidable_eq A] [deceqB : decidable_eq B] /- Unionl and Union -/ section union definition to_comm_monoid_Union (B : Type) [decidable_eq B] : comm_monoid (finset B) := ⦃ comm_monoid, mul := union, mul_assoc := union_assoc, one := empty, mul_one := union_empty, one_mul := empty_union, mul_comm := union_comm ⦄ local attribute finset.to_comm_monoid_Union [instance] include deceqB definition Unionl (l : list A) (f : A → finset B) : finset B := Prodl l f notation `⋃` binders `←` l, r:(scoped f, Unionl l f) := r definition Union (s : finset A) (f : A → finset B) : finset B := finset.Prod s f notation `⋃` binders `∈` s, r:(scoped f, finset.Union s f) := r theorem Unionl_nil (f : A → finset B) : Unionl [] f = ∅ := Prodl_nil f theorem Unionl_cons (f : A → finset B) (a : A) (l : list A) : Unionl (a::l) f = f a ∪ Unionl l f := Prodl_cons f a l theorem Unionl_append (l₁ l₂ : list A) (f : A → finset B) : Unionl (l₁++l₂) f = Unionl l₁ f ∪ Unionl l₂ f := Prodl_append l₁ l₂ f theorem Unionl_mul (l : list A) (f g : A → finset B) : Unionl l (λx, f x ∪ g x) = Unionl l f ∪ Unionl l g := Prodl_mul l f g section deceqA include deceqA theorem Unionl_insert_of_mem (f : A → finset B) {a : A} {l : list A} (H : a ∈ l) : Unionl (list.insert a l) f = Unionl l f := Prodl_insert_of_mem f H theorem Unionl_insert_of_not_mem (f : A → finset B) {a : A} {l : list A} (H : a ∉ l) : Unionl (list.insert a l) f = f a ∪ Unionl l f := Prodl_insert_of_not_mem f H theorem Unionl_union {l₁ l₂ : list A} (f : A → finset B) (d : list.disjoint l₁ l₂) : Unionl (list.union l₁ l₂) f = Unionl l₁ f ∪ Unionl l₂ f := Prodl_union f d theorem Unionl_empty (l : list A) : Unionl l (λ x, ∅) = (∅ : finset B) := Prodl_one l end deceqA theorem Union_empty (f : A → finset B) : Union ∅ f = ∅ := finset.Prod_empty f theorem Union_mul (s : finset A) (f g : A → finset B) : Union s (λx, f x ∪ g x) = Union s f ∪ Union s g := finset.Prod_mul s f g section deceqA include deceqA theorem Union_insert_of_mem (f : A → finset B) {a : A} {s : finset A} (H : a ∈ s) : Union (insert a s) f = Union s f := finset.Prod_insert_of_mem f H private theorem Union_insert_of_not_mem (f : A → finset B) {a : A} {s : finset A} (H : a ∉ s) : Union (insert a s) f = f a ∪ Union s f := finset.Prod_insert_of_not_mem f H theorem Union_union (f : A → finset B) {s₁ s₂ : finset A} (disj : s₁ ∩ s₂ = ∅) : Union (s₁ ∪ s₂) f = Union s₁ f ∪ Union s₂ f := finset.Prod_union f disj theorem Union_ext {s : finset A} {f g : A → finset B} (H : ∀x, x ∈ s → f x = g x) : Union s f = Union s g := finset.Prod_ext H theorem Union_empty' (s : finset A) : Union s (λ x, ∅) = (∅ : finset B) := finset.Prod_one s -- this will eventually be an instance of something more general theorem inter_Union (s : finset B) (t : finset A) (f : A → finset B) : s ∩ (⋃ x ∈ t, f x) = (⋃ x ∈ t, s ∩ f x) := begin induction t with s' x H IH, rewrite [*Union_empty, inter_empty], rewrite [*Union_insert_of_not_mem _ H, inter_distrib_left, IH], end theorem mem_Union_iff (s : finset A) (f : A → finset B) (b : B) : b ∈ (⋃ x ∈ s, f x) ↔ (∃ x, x ∈ s ∧ b ∈ f x ) := begin induction s with s' a H IH, rewrite [exists_mem_empty_eq], rewrite [Union_insert_of_not_mem _ H, mem_union_eq, IH, exists_mem_insert_eq] end theorem mem_Union_eq (s : finset A) (f : A → finset B) (b : B) : b ∈ (⋃ x ∈ s, f x) = (∃ x, x ∈ s ∧ b ∈ f x ) := propext !mem_Union_iff theorem Union_insert (f : A → finset B) {a : A} {s : finset A} : Union (insert a s) f = f a ∪ Union s f := decidable.by_cases (assume Pin : a ∈ s, begin rewrite [Union_insert_of_mem f Pin], apply ext, intro x, apply iff.intro, exact mem_union_r, rewrite [mem_union_eq], intro Por, exact or.elim Por (assume Pl, begin rewrite mem_Union_eq, exact (exists.intro a (and.intro Pin Pl)) end) (assume Pr, Pr) end) (assume H : a ∉ s, !Union_insert_of_not_mem H) lemma image_eq_Union_index_image (s : finset A) (f : A → finset B) : Union s f = Union (image f s) id := finset.induction_on s (by rewrite Union_empty) (take s1 a Pa IH, by rewrite [image_insert, *Union_insert, IH]) lemma Union_const [decidable_eq B] {f : A → finset B} {s : finset A} {t : finset B} : s ≠ ∅ → (∀ x, x ∈ s → f x = t) → Union s f = t := begin induction s with a' s' H IH, {intros [H1, H2], exfalso, apply H1 !rfl}, intros [H1, H2], rewrite [Union_insert, H2 _ !mem_insert], cases (decidable.em (s' = ∅)) with [seq, sne], {rewrite [seq, Union_empty, union_empty]}, have H3 : ∀ x, x ∈ s' → f x = t, from (λ x H', H2 x (mem_insert_of_mem _ H')), rewrite [IH sne H3, union_self] end end deceqA end union end finset
ccbf8eb50382e516d3389d82a5e69b62d80ba6f9
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/data/real/basic.lean
bfe62d352fbb4e0ec01985b39b7074bf15bdf494
[ "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
22,783
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Floris van Doorn -/ import order.conditionally_complete_lattice import data.real.cau_seq_completion import algebra.archimedean import algebra.star.basic import algebra.bounds /-! # Real numbers from Cauchy sequences This file defines `ℝ` as the type of equivalence classes of Cauchy sequences of rational numbers. This choice is motivated by how easy it is to prove that `ℝ` is a commutative ring, by simply lifting everything to `ℚ`. -/ open_locale pointwise /-- The type `ℝ` of real numbers constructed as equivalence classes of Cauchy sequences of rational numbers. -/ structure real := of_cauchy :: (cauchy : @cau_seq.completion.Cauchy ℚ _ _ _ abs _) notation `ℝ` := real attribute [pp_using_anonymous_constructor] real namespace real open cau_seq cau_seq.completion variables {x y : ℝ} lemma ext_cauchy_iff : ∀ {x y : real}, x = y ↔ x.cauchy = y.cauchy | ⟨a⟩ ⟨b⟩ := by split; cc lemma ext_cauchy {x y : real} : x.cauchy = y.cauchy → x = y := ext_cauchy_iff.2 /-- The real numbers are isomorphic to the quotient of Cauchy sequences on the rationals. -/ def equiv_Cauchy : ℝ ≃ cau_seq.completion.Cauchy := ⟨real.cauchy, real.of_cauchy, λ ⟨_⟩, rfl, λ _, rfl⟩ -- irreducible doesn't work for instances: https://github.com/leanprover-community/lean/issues/511 @[irreducible] private def zero : ℝ := ⟨0⟩ @[irreducible] private def one : ℝ := ⟨1⟩ @[irreducible] private def add : ℝ → ℝ → ℝ | ⟨a⟩ ⟨b⟩ := ⟨a + b⟩ @[irreducible] private def neg : ℝ → ℝ | ⟨a⟩ := ⟨-a⟩ @[irreducible] private def mul : ℝ → ℝ → ℝ | ⟨a⟩ ⟨b⟩ := ⟨a * b⟩ instance : has_zero ℝ := ⟨zero⟩ instance : has_one ℝ := ⟨one⟩ instance : has_add ℝ := ⟨add⟩ instance : has_neg ℝ := ⟨neg⟩ instance : has_mul ℝ := ⟨mul⟩ lemma zero_cauchy : (⟨0⟩ : ℝ) = 0 := show _ = zero, by rw zero lemma one_cauchy : (⟨1⟩ : ℝ) = 1 := show _ = one, by rw one lemma add_cauchy {a b} : (⟨a⟩ + ⟨b⟩ : ℝ) = ⟨a + b⟩ := show add _ _ = _, by rw add lemma neg_cauchy {a} : (-⟨a⟩ : ℝ) = ⟨-a⟩ := show neg _ = _, by rw neg lemma mul_cauchy {a b} : (⟨a⟩ * ⟨b⟩ : ℝ) = ⟨a * b⟩ := show mul _ _ = _, by rw mul instance : comm_ring ℝ := begin refine_struct { zero := 0, one := 1, mul := (*), add := (+), neg := @has_neg.neg ℝ _, sub := λ a b, a + (-b), npow := @npow_rec _ ⟨1⟩ ⟨(*)⟩, nsmul := @nsmul_rec _ ⟨0⟩ ⟨(+)⟩, gsmul := @gsmul_rec _ ⟨0⟩ ⟨(+)⟩ ⟨@has_neg.neg ℝ _⟩ }; repeat { rintro ⟨_⟩, }; try { refl }; simp [← zero_cauchy, ← one_cauchy, add_cauchy, neg_cauchy, mul_cauchy]; apply add_assoc <|> apply add_comm <|> apply mul_assoc <|> apply mul_comm <|> apply left_distrib <|> apply right_distrib <|> apply sub_eq_add_neg <|> skip end /-! Extra instances to short-circuit type class resolution. These short-circuits have an additional property of ensuring that a computable path is found; if `field ℝ` is found first, then decaying it to these typeclasses would result in a `noncomputable` version of them. -/ instance : ring ℝ := by apply_instance instance : comm_semiring ℝ := by apply_instance instance : semiring ℝ := by apply_instance instance : add_comm_group ℝ := by apply_instance instance : add_group ℝ := by apply_instance instance : add_comm_monoid ℝ := by apply_instance instance : add_monoid ℝ := by apply_instance instance : add_left_cancel_semigroup ℝ := by apply_instance instance : add_right_cancel_semigroup ℝ := by apply_instance instance : add_comm_semigroup ℝ := by apply_instance instance : add_semigroup ℝ := by apply_instance instance : comm_monoid ℝ := by apply_instance instance : monoid ℝ := by apply_instance instance : comm_semigroup ℝ := by apply_instance instance : semigroup ℝ := by apply_instance instance : has_sub ℝ := by apply_instance instance : module ℝ ℝ := by apply_instance instance : inhabited ℝ := ⟨0⟩ /-- The real numbers are a `*`-ring, with the trivial `*`-structure. -/ instance : star_ring ℝ := star_ring_of_comm /-- Coercion `ℚ` → `ℝ` as a `ring_hom`. Note that this is `cau_seq.completion.of_rat`, not `rat.cast`. -/ def of_rat : ℚ →+* ℝ := by refine_struct { to_fun := of_cauchy ∘ of_rat }; simp [of_rat_one, of_rat_zero, of_rat_mul, of_rat_add, one_cauchy, zero_cauchy, ← mul_cauchy, ← add_cauchy] lemma of_rat_apply (x : ℚ) : of_rat x = of_cauchy (cau_seq.completion.of_rat x) := rfl /-- Make a real number from a Cauchy sequence of rationals (by taking the equivalence class). -/ def mk (x : cau_seq ℚ abs) : ℝ := ⟨cau_seq.completion.mk x⟩ theorem mk_eq {f g : cau_seq ℚ abs} : mk f = mk g ↔ f ≈ g := ext_cauchy_iff.trans mk_eq @[irreducible] private def lt : ℝ → ℝ → Prop | ⟨x⟩ ⟨y⟩ := quotient.lift_on₂ x y (<) $ λ f₁ g₁ f₂ g₂ hf hg, propext $ ⟨λ h, lt_of_eq_of_lt (setoid.symm hf) (lt_of_lt_of_eq h hg), λ h, lt_of_eq_of_lt hf (lt_of_lt_of_eq h (setoid.symm hg))⟩ instance : has_lt ℝ := ⟨lt⟩ lemma lt_cauchy {f g} : (⟨⟦f⟧⟩ : ℝ) < ⟨⟦g⟧⟩ ↔ f < g := show lt _ _ ↔ _, by rw lt; refl @[simp] theorem mk_lt {f g : cau_seq ℚ abs} : mk f < mk g ↔ f < g := lt_cauchy lemma mk_zero : mk 0 = 0 := by rw ← zero_cauchy; refl lemma mk_one : mk 1 = 1 := by rw ← one_cauchy; refl lemma mk_add {f g : cau_seq ℚ abs} : mk (f + g) = mk f + mk g := by simp [mk, add_cauchy] lemma mk_mul {f g : cau_seq ℚ abs} : mk (f * g) = mk f * mk g := by simp [mk, mul_cauchy] lemma mk_neg {f : cau_seq ℚ abs} : mk (-f) = -mk f := by simp [mk, neg_cauchy] @[simp] theorem mk_pos {f : cau_seq ℚ abs} : 0 < mk f ↔ pos f := by rw [← mk_zero, mk_lt]; exact iff_of_eq (congr_arg pos (sub_zero f)) @[irreducible] private def le (x y : ℝ) : Prop := x < y ∨ x = y instance : has_le ℝ := ⟨le⟩ private lemma le_def {x y : ℝ} : x ≤ y ↔ x < y ∨ x = y := show le _ _ ↔ _, by rw le @[simp] theorem mk_le {f g : cau_seq ℚ abs} : mk f ≤ mk g ↔ f ≤ g := by simp [le_def, mk_eq]; refl @[elab_as_eliminator] protected lemma ind_mk {C : real → Prop} (x : real) (h : ∀ y, C (mk y)) : C x := begin cases x with x, induction x using quot.induction_on with x, exact h x end theorem add_lt_add_iff_left {a b : ℝ} (c : ℝ) : c + a < c + b ↔ a < b := begin induction a using real.ind_mk, induction b using real.ind_mk, induction c using real.ind_mk, simp only [mk_lt, ← mk_add], show pos _ ↔ pos _, rw add_sub_add_left_eq_sub end instance : partial_order ℝ := { le := (≤), lt := (<), lt_iff_le_not_le := λ a b, real.ind_mk a $ λ a, real.ind_mk b $ λ b, by simpa using lt_iff_le_not_le, le_refl := λ a, a.ind_mk (by intro a; rw mk_le), le_trans := λ a b c, real.ind_mk a $ λ a, real.ind_mk b $ λ b, real.ind_mk c $ λ c, by simpa using le_trans, lt_iff_le_not_le := λ a b, real.ind_mk a $ λ a, real.ind_mk b $ λ b, by simpa using lt_iff_le_not_le, le_antisymm := λ a b, real.ind_mk a $ λ a, real.ind_mk b $ λ b, by simpa [mk_eq] using @cau_seq.le_antisymm _ _ a b } instance : preorder ℝ := by apply_instance theorem of_rat_lt {x y : ℚ} : of_rat x < of_rat y ↔ x < y := begin rw [mk_lt] {md := tactic.transparency.semireducible}, exact const_lt end protected theorem zero_lt_one : (0 : ℝ) < 1 := by convert of_rat_lt.2 zero_lt_one; simp protected theorem mul_pos {a b : ℝ} : 0 < a → 0 < b → 0 < a * b := begin induction a using real.ind_mk with a, induction b using real.ind_mk with b, simpa only [mk_lt, mk_pos, ← mk_mul] using cau_seq.mul_pos end instance : ordered_ring ℝ := { add_le_add_left := begin simp only [le_iff_eq_or_lt], rintros a b ⟨rfl, h⟩, { simp }, { exact λ c, or.inr ((add_lt_add_iff_left c).2 ‹_›) } end, zero_le_one := le_of_lt real.zero_lt_one, mul_pos := @real.mul_pos, .. real.comm_ring, .. real.partial_order, .. real.semiring } instance : ordered_semiring ℝ := by apply_instance instance : ordered_add_comm_group ℝ := by apply_instance instance : ordered_cancel_add_comm_monoid ℝ := by apply_instance instance : ordered_add_comm_monoid ℝ := by apply_instance instance : nontrivial ℝ := ⟨⟨0, 1, ne_of_lt real.zero_lt_one⟩⟩ open_locale classical noncomputable instance : linear_order ℝ := { le_total := begin intros a b, induction a using real.ind_mk with a, induction b using real.ind_mk with b, simpa using le_total a b, end, decidable_le := by apply_instance, .. real.partial_order } noncomputable instance : linear_ordered_comm_ring ℝ := { .. real.nontrivial, .. real.ordered_ring, .. real.comm_ring, .. real.linear_order } /- Extra instances to short-circuit type class resolution -/ noncomputable instance : linear_ordered_ring ℝ := by apply_instance noncomputable instance : linear_ordered_semiring ℝ := by apply_instance instance : domain ℝ := { .. real.nontrivial, .. real.comm_ring, .. linear_ordered_ring.to_domain } /-- The real numbers are an ordered `*`-ring, with the trivial `*`-structure. -/ instance : star_ordered_ring ℝ := { star_mul_self_nonneg := λ r, mul_self_nonneg r, } @[irreducible] private noncomputable def inv' : ℝ → ℝ | ⟨a⟩ := ⟨a⁻¹⟩ noncomputable instance : has_inv ℝ := ⟨inv'⟩ lemma inv_cauchy {f} : (⟨f⟩ : ℝ)⁻¹ = ⟨f⁻¹⟩ := show inv' _ = _, by rw inv' noncomputable instance : linear_ordered_field ℝ := { inv := has_inv.inv, mul_inv_cancel := begin rintros ⟨a⟩ h, rw mul_comm, simp only [inv_cauchy, mul_cauchy, ← one_cauchy, ← zero_cauchy, ne.def] at *, exact cau_seq.completion.inv_mul_cancel h, end, inv_zero := by simp [← zero_cauchy, inv_cauchy], ..real.linear_ordered_comm_ring, ..real.domain } /- Extra instances to short-circuit type class resolution -/ noncomputable instance : linear_ordered_add_comm_group ℝ := by apply_instance noncomputable instance field : field ℝ := by apply_instance noncomputable instance : division_ring ℝ := by apply_instance instance : integral_domain ℝ := by apply_instance noncomputable instance : distrib_lattice ℝ := by apply_instance noncomputable instance : lattice ℝ := by apply_instance noncomputable instance : semilattice_inf ℝ := by apply_instance noncomputable instance : semilattice_sup ℝ := by apply_instance noncomputable instance : has_inf ℝ := by apply_instance noncomputable instance : has_sup ℝ := by apply_instance noncomputable instance decidable_lt (a b : ℝ) : decidable (a < b) := by apply_instance noncomputable instance decidable_le (a b : ℝ) : decidable (a ≤ b) := by apply_instance noncomputable instance decidable_eq (a b : ℝ) : decidable (a = b) := by apply_instance open rat @[simp] theorem of_rat_eq_cast : ∀ x : ℚ, of_rat x = x := of_rat.eq_rat_cast theorem le_mk_of_forall_le {f : cau_seq ℚ abs} : (∃ i, ∀ j ≥ i, x ≤ f j) → x ≤ mk f := begin intro h, induction x using real.ind_mk with x, apply le_of_not_lt, rw mk_lt, rintro ⟨K, K0, hK⟩, obtain ⟨i, H⟩ := exists_forall_ge_and h (exists_forall_ge_and hK (f.cauchy₃ $ half_pos K0)), apply not_lt_of_le (H _ (le_refl _)).1, rw ← of_rat_eq_cast, rw [mk_lt] {md := tactic.transparency.semireducible}, refine ⟨_, half_pos K0, i, λ j ij, _⟩, have := add_le_add (H _ ij).2.1 (le_of_lt (abs_lt.1 $ (H _ (le_refl _)).2.2 _ ij).1), rwa [← sub_eq_add_neg, sub_self_div_two, sub_apply, sub_add_sub_cancel] at this end theorem mk_le_of_forall_le {f : cau_seq ℚ abs} {x : ℝ} (h : ∃ i, ∀ j ≥ i, (f j : ℝ) ≤ x) : mk f ≤ x := begin cases h with i H, rw [← neg_le_neg_iff, ← mk_neg], exact le_mk_of_forall_le ⟨i, λ j ij, by simp [H _ ij]⟩ end theorem mk_near_of_forall_near {f : cau_seq ℚ abs} {x : ℝ} {ε : ℝ} (H : ∃ i, ∀ j ≥ i, |(f j : ℝ) - x| ≤ ε) : |mk f - x| ≤ ε := abs_sub_le_iff.2 ⟨sub_le_iff_le_add'.2 $ mk_le_of_forall_le $ H.imp $ λ i h j ij, sub_le_iff_le_add'.1 (abs_sub_le_iff.1 $ h j ij).1, sub_le.1 $ le_mk_of_forall_le $ H.imp $ λ i h j ij, sub_le.1 (abs_sub_le_iff.1 $ h j ij).2⟩ instance : archimedean ℝ := archimedean_iff_rat_le.2 $ λ x, real.ind_mk x $ λ f, let ⟨M, M0, H⟩ := f.bounded' 0 in ⟨M, mk_le_of_forall_le ⟨0, λ i _, rat.cast_le.2 $ le_of_lt (abs_lt.1 (H i)).2⟩⟩ noncomputable instance : floor_ring ℝ := archimedean.floor_ring _ theorem is_cau_seq_iff_lift {f : ℕ → ℚ} : is_cau_seq abs f ↔ is_cau_seq abs (λ i, (f i : ℝ)) := ⟨λ H ε ε0, let ⟨δ, δ0, δε⟩ := exists_pos_rat_lt ε0 in (H _ δ0).imp $ λ i hi j ij, lt_trans (by simpa using (@rat.cast_lt ℝ _ _ _).2 (hi _ ij)) δε, λ H ε ε0, (H _ (rat.cast_pos.2 ε0)).imp $ λ i hi j ij, (@rat.cast_lt ℝ _ _ _).1 $ by simpa using hi _ ij⟩ theorem of_near (f : ℕ → ℚ) (x : ℝ) (h : ∀ ε > 0, ∃ i, ∀ j ≥ i, |(f j : ℝ) - x| < ε) : ∃ h', real.mk ⟨f, h'⟩ = x := ⟨is_cau_seq_iff_lift.2 (of_near _ (const abs x) h), sub_eq_zero.1 $ abs_eq_zero.1 $ eq_of_le_of_forall_le_of_dense (abs_nonneg _) $ λ ε ε0, mk_near_of_forall_near $ (h _ ε0).imp (λ i h j ij, le_of_lt (h j ij))⟩ theorem exists_floor (x : ℝ) : ∃ (ub : ℤ), (ub:ℝ) ≤ x ∧ ∀ (z : ℤ), (z:ℝ) ≤ x → z ≤ ub := int.exists_greatest_of_bdd (let ⟨n, hn⟩ := exists_int_gt x in ⟨n, λ z h', int.cast_le.1 $ le_trans h' $ le_of_lt hn⟩) (let ⟨n, hn⟩ := exists_int_lt x in ⟨n, le_of_lt hn⟩) theorem exists_is_lub (S : set ℝ) (hne : S.nonempty) (hbdd : bdd_above S) : ∃ x, is_lub S x := begin rcases ⟨hne, hbdd⟩ with ⟨⟨L, hL⟩, ⟨U, hU⟩⟩, have : ∀ d : ℕ, bdd_above {m : ℤ | ∃ y ∈ S, (m : ℝ) ≤ y * d}, { cases exists_int_gt U with k hk, refine λ d, ⟨k * d, λ z h, _⟩, rcases h with ⟨y, yS, hy⟩, refine int.cast_le.1 (hy.trans _), push_cast, exact mul_le_mul_of_nonneg_right ((hU yS).trans hk.le) d.cast_nonneg }, choose f hf using λ d : ℕ, int.exists_greatest_of_bdd (this d) ⟨⌊L * d⌋, L, hL, int.floor_le _⟩, have hf₁ : ∀ n > 0, ∃ y ∈ S, ((f n / n:ℚ):ℝ) ≤ y := λ n n0, let ⟨y, yS, hy⟩ := (hf n).1 in ⟨y, yS, by simpa using (div_le_iff ((nat.cast_pos.2 n0):((_:ℝ) < _))).2 hy⟩, have hf₂ : ∀ (n > 0) (y ∈ S), (y - (n:ℕ)⁻¹ : ℝ) < (f n / n:ℚ), { intros n n0 y yS, have := (int.sub_one_lt_floor _).trans_le (int.cast_le.2 $ (hf n).2 _ ⟨y, yS, int.floor_le _⟩), simp [-sub_eq_add_neg], rwa [lt_div_iff ((nat.cast_pos.2 n0):((_:ℝ) < _)), sub_mul, _root_.inv_mul_cancel], exact ne_of_gt (nat.cast_pos.2 n0) }, have hg : is_cau_seq abs (λ n, f n / n : ℕ → ℚ), { intros ε ε0, suffices : ∀ j k ≥ ⌈ε⁻¹⌉₊, (f j / j - f k / k : ℚ) < ε, { refine ⟨_, λ j ij, abs_lt.2 ⟨_, this _ _ ij (le_refl _)⟩⟩, rw [neg_lt, neg_sub], exact this _ _ (le_refl _) ij }, intros j k ij ik, replace ij := le_trans (nat.le_ceil _) (nat.cast_le.2 ij), replace ik := le_trans (nat.le_ceil _) (nat.cast_le.2 ik), have j0 := nat.cast_pos.1 (lt_of_lt_of_le (inv_pos.2 ε0) ij), have k0 := nat.cast_pos.1 (lt_of_lt_of_le (inv_pos.2 ε0) ik), rcases hf₁ _ j0 with ⟨y, yS, hy⟩, refine lt_of_lt_of_le ((@rat.cast_lt ℝ _ _ _).1 _) ((inv_le ε0 (nat.cast_pos.2 k0)).1 ik), simpa using sub_lt_iff_lt_add'.2 (lt_of_le_of_lt hy $ sub_lt_iff_lt_add.1 $ hf₂ _ k0 _ yS) }, let g : cau_seq ℚ abs := ⟨λ n, f n / n, hg⟩, refine ⟨mk g, ⟨λ x xS, _, λ y h, _⟩⟩, { refine le_of_forall_ge_of_dense (λ z xz, _), cases exists_nat_gt (x - z)⁻¹ with K hK, refine le_mk_of_forall_le ⟨K, λ n nK, _⟩, replace xz := sub_pos.2 xz, replace hK := le_trans (le_of_lt hK) (nat.cast_le.2 nK), have n0 : 0 < n := nat.cast_pos.1 (lt_of_lt_of_le (inv_pos.2 xz) hK), refine le_trans _ (le_of_lt $ hf₂ _ n0 _ xS), rwa [le_sub, inv_le ((nat.cast_pos.2 n0):((_:ℝ) < _)) xz] }, { exact mk_le_of_forall_le ⟨1, λ n n1, let ⟨x, xS, hx⟩ := hf₁ _ n1 in le_trans hx (h xS)⟩ } end noncomputable instance : has_Sup ℝ := ⟨λ S, if h : S.nonempty ∧ bdd_above S then classical.some (exists_is_lub S h.1 h.2) else 0⟩ lemma Sup_def (S : set ℝ) : Sup S = if h : S.nonempty ∧ bdd_above S then classical.some (exists_is_lub S h.1 h.2) else 0 := rfl protected theorem is_lub_Sup (S : set ℝ) (h₁ : S.nonempty) (h₂ : bdd_above S) : is_lub S (Sup S) := by { simp only [Sup_def, dif_pos (and.intro h₁ h₂)], apply classical.some_spec } noncomputable instance : has_Inf ℝ := ⟨λ S, -Sup (-S)⟩ lemma Inf_def (S : set ℝ) : Inf S = -Sup (-S) := rfl protected theorem is_glb_Inf (S : set ℝ) (h₁ : S.nonempty) (h₂ : bdd_below S) : is_glb S (Inf S) := begin rw [Inf_def, ← is_lub_neg', neg_neg], exact real.is_lub_Sup _ h₁.neg h₂.neg end noncomputable instance : conditionally_complete_linear_order ℝ := { Sup := has_Sup.Sup, Inf := has_Inf.Inf, le_cSup := λ s a hs ha, (real.is_lub_Sup s ⟨a, ha⟩ hs).1 ha, cSup_le := λ s a hs ha, (real.is_lub_Sup s hs ⟨a, ha⟩).2 ha, cInf_le := λ s a hs ha, (real.is_glb_Inf s ⟨a, ha⟩ hs).1 ha, le_cInf := λ s a hs ha, (real.is_glb_Inf s hs ⟨a, ha⟩).2 ha, ..real.linear_order, ..real.lattice} lemma lt_Inf_add_pos {s : set ℝ} (h : s.nonempty) {ε : ℝ} (hε : 0 < ε) : ∃ a ∈ s, a < Inf s + ε := exists_lt_of_cInf_lt h $ lt_add_of_pos_right _ hε lemma add_neg_lt_Sup {s : set ℝ} (h : s.nonempty) {ε : ℝ} (hε : ε < 0) : ∃ a ∈ s, Sup s + ε < a := exists_lt_of_lt_cSup h $ add_lt_iff_neg_left.2 hε lemma Inf_le_iff {s : set ℝ} (h : bdd_below s) (h' : s.nonempty) {a : ℝ} : Inf s ≤ a ↔ ∀ ε, 0 < ε → ∃ x ∈ s, x < a + ε := begin rw le_iff_forall_pos_lt_add, split; intros H ε ε_pos, { exact exists_lt_of_cInf_lt h' (H ε ε_pos) }, { rcases H ε ε_pos with ⟨x, x_in, hx⟩, exact cInf_lt_of_lt h x_in hx } end lemma le_Sup_iff {s : set ℝ} (h : bdd_above s) (h' : s.nonempty) {a : ℝ} : a ≤ Sup s ↔ ∀ ε, ε < 0 → ∃ x ∈ s, a + ε < x := begin rw le_iff_forall_pos_lt_add, refine ⟨λ H ε ε_neg, _, λ H ε ε_pos, _⟩, { exact exists_lt_of_lt_cSup h' (lt_sub_iff_add_lt.mp (H _ (neg_pos.mpr ε_neg))) }, { rcases H _ (neg_lt_zero.mpr ε_pos) with ⟨x, x_in, hx⟩, exact sub_lt_iff_lt_add.mp (lt_cSup_of_lt h x_in hx) } end @[simp] theorem Sup_empty : Sup (∅ : set ℝ) = 0 := dif_neg $ by simp theorem Sup_of_not_bdd_above {s : set ℝ} (hs : ¬ bdd_above s) : Sup s = 0 := dif_neg $ assume h, hs h.2 theorem Sup_univ : Sup (@set.univ ℝ) = 0 := real.Sup_of_not_bdd_above $ λ ⟨x, h⟩, not_le_of_lt (lt_add_one _) $ h (set.mem_univ _) @[simp] theorem Inf_empty : Inf (∅ : set ℝ) = 0 := by simp [Inf_def, Sup_empty] theorem Inf_of_not_bdd_below {s : set ℝ} (hs : ¬ bdd_below s) : Inf s = 0 := neg_eq_zero.2 $ Sup_of_not_bdd_above $ mt bdd_above_neg.1 hs /-- As `0` is the default value for `real.Sup` of the empty set or sets which are not bounded above, it suffices to show that `S` is bounded below by `0` to show that `0 ≤ Inf S`. -/ lemma Sup_nonneg (S : set ℝ) (hS : ∀ x ∈ S, (0:ℝ) ≤ x) : 0 ≤ Sup S := begin rcases S.eq_empty_or_nonempty with rfl | ⟨y, hy⟩, { exact Sup_empty.ge }, { apply dite _ (λ h, le_cSup_of_le h hy $ hS y hy) (λ h, (Sup_of_not_bdd_above h).ge) } end /-- As `0` is the default value for `real.Sup` of the empty set, it suffices to show that `S` is bounded above by `0` to show that `Sup S ≤ 0`. -/ lemma Sup_nonpos (S : set ℝ) (hS : ∀ x ∈ S, x ≤ (0:ℝ)) : Sup S ≤ 0 := begin rcases S.eq_empty_or_nonempty with rfl | hS₂, exacts [Sup_empty.le, cSup_le hS₂ hS], end /-- As `0` is the default value for `real.Inf` of the empty set, it suffices to show that `S` is bounded below by `0` to show that `0 ≤ Inf S`. -/ lemma Inf_nonneg (S : set ℝ) (hS : ∀ x ∈ S, (0:ℝ) ≤ x) : 0 ≤ Inf S := begin rcases S.eq_empty_or_nonempty with rfl | hS₂, exacts [Inf_empty.ge, le_cInf hS₂ hS] end /-- As `0` is the default value for `real.Inf` of the empty set or sets which are not bounded below, it suffices to show that `S` is bounded above by `0` to show that `Inf S ≤ 0`. -/ lemma Inf_nonpos (S : set ℝ) (hS : ∀ x ∈ S, x ≤ (0:ℝ)) : Inf S ≤ 0 := begin rcases S.eq_empty_or_nonempty with rfl | ⟨y, hy⟩, { exact Inf_empty.le }, { apply dite _ (λ h, cInf_le_of_le h hy $ hS y hy) (λ h, (Inf_of_not_bdd_below h).le) } end lemma Inf_le_Sup (s : set ℝ) (h₁ : bdd_below s) (h₂ : bdd_above s) : Inf s ≤ Sup s := begin rcases s.eq_empty_or_nonempty with rfl | hne, { rw [Inf_empty, Sup_empty] }, { exact cInf_le_cSup h₁ h₂ hne } end theorem cau_seq_converges (f : cau_seq ℝ abs) : ∃ x, f ≈ const abs x := begin let S := {x : ℝ | const abs x < f}, have lb : ∃ x, x ∈ S := exists_lt f, have ub' : ∀ x, f < const abs x → ∀ y ∈ S, y ≤ x := λ x h y yS, le_of_lt $ const_lt.1 $ cau_seq.lt_trans yS h, have ub : ∃ x, ∀ y ∈ S, y ≤ x := (exists_gt f).imp ub', refine ⟨Sup S, ((lt_total _ _).resolve_left (λ h, _)).resolve_right (λ h, _)⟩, { rcases h with ⟨ε, ε0, i, ih⟩, refine (cSup_le lb (ub' _ _)).not_lt (sub_lt_self _ (half_pos ε0)), refine ⟨_, half_pos ε0, i, λ j ij, _⟩, rw [sub_apply, const_apply, sub_right_comm, le_sub_iff_add_le, add_halves], exact ih _ ij }, { rcases h with ⟨ε, ε0, i, ih⟩, refine (le_cSup ub _).not_lt ((lt_add_iff_pos_left _).2 (half_pos ε0)), refine ⟨_, half_pos ε0, i, λ j ij, _⟩, rw [sub_apply, const_apply, add_comm, ← sub_sub, le_sub_iff_add_le, add_halves], exact ih _ ij } end noncomputable instance : cau_seq.is_complete ℝ abs := ⟨cau_seq_converges⟩ end real
cb167aaef13f59b86f322f5a1500a28449ade6a7
41ebf3cb010344adfa84907b3304db00e02db0a6
/uexp/src/uexp/rules/conjunctive.lean
780a806124b8048c67aed009cbafd9af5d05756f
[ "BSD-2-Clause" ]
permissive
ReinierKoops/Cosette
e061b2ba58b26f4eddf4cd052dcf7abd16dfe8fb
eb8dadd06ee05fe7b6b99de431dd7c4faef5cb29
refs/heads/master
1,686,483,953,198
1,624,293,498,000
1,624,293,498,000
378,997,885
0
0
BSD-2-Clause
1,624,293,485,000
1,624,293,484,000
null
UTF-8
Lean
false
false
922
lean
import ..u_semiring import ..sql import ..meta.cosette_tactics open SQL open Pred open Expr open Proj lemma CQExample0: forall Γ s1 s2 (a: SQL Γ s1) (b: SQL Γ s2) ty0 ty1 (x: Column ty0 s1) (ya: Column ty1 s1) (yb: Column ty1 s2), denoteSQL ((DISTINCT (SELECT1 (right⋅left⋅x) (FROM1 (product a b) WHERE (equal (uvariable (right⋅left⋅ya)) (uvariable (right⋅right⋅yb)))))) : SQL Γ _) = denoteSQL ((DISTINCT (SELECT1 (right⋅left⋅left⋅x) (FROM1 (product (product a a) b) WHERE (and (equal (uvariable (right⋅left⋅left⋅x)) (uvariable (right⋅left⋅right⋅x))) (equal (uvariable (right⋅left⋅left⋅ya)) (uvariable (right⋅right⋅yb))))))) : SQL Γ _ ) := begin intros, unfold_all_denotations, funext, simp, sorry -- TODO: SDP should be used here end
2b55e4f9fe7b703697a4265527203ee24fa533f3
75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2
/tests/lean/t1.lean
a8290155db52c16f382730f53bc36ec27ce66059
[ "Apache-2.0" ]
permissive
jroesch/lean
30ef0860fa905d35b9ad6f76de1a4f65c9af6871
3de4ec1a6ce9a960feb2a48eeea8b53246fa34f2
refs/heads/master
1,586,090,835,348
1,455,142,203,000
1,455,142,277,000
51,536,958
1
0
null
1,455,215,811,000
1,455,215,811,000
null
UTF-8
Lean
false
false
195
lean
(* print("testing...") local env = get_env() env = add_decl(env, mk_constant_assumption("x", Prop)) assert(env:find("x")) set_env(env) *) (* local env = get_env() print(env:find("x"):type()) *)
22f5212e4600515e895e2e757625405a71d9e6c6
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/number_theory/zsqrtd/basic.lean
339fa34f9b9feac61ac6ca10b3d9c09550595d95
[ "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
33,389
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 ring_theory.int.basic import tactic.ring import algebra.star.unitary /-! # ℤ[√d] > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. The ring of integers adjoined with a square root of `d : ℤ`. After defining the norm, we show that it is a linearly ordered commutative ring, as well as an integral domain. We provide the universal property, that ring homomorphisms `ℤ√d →+* R` correspond to choices of square roots of `d` in `R`. -/ /-- 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. -/ 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 -/ instance : has_zero ℤ√d := ⟨of_int 0⟩ @[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 -/ instance : has_one ℤ√d := ⟨of_int 1⟩ @[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` -/ instance : has_add ℤ√d := ⟨λ z w, ⟨z.1 + w.1, z.2 + w.2⟩⟩ @[simp] lemma add_def (x y x' y' : ℤ) : (⟨x, y⟩ + ⟨x', y'⟩ : ℤ√d) = ⟨x + x', y + y'⟩ := rfl @[simp] lemma add_re (z w : ℤ√d) : (z + w).re = z.re + w.re := rfl @[simp] lemma add_im (z w : ℤ√d) : (z + w).im = z.im + w.im := rfl @[simp] lemma bit0_re (z) : (bit0 z : ℤ√d).re = bit0 z.re := rfl @[simp] lemma bit0_im (z) : (bit0 z : ℤ√d).im = bit0 z.im := rfl @[simp] theorem bit1_re (z) : (bit1 z : ℤ√d).re = bit1 z.re := rfl @[simp] theorem bit1_im (z) : (bit1 z : ℤ√d).im = bit0 z.im := by simp [bit1] /-- Negation in `ℤ√d` -/ instance : has_neg ℤ√d := ⟨λ z, ⟨-z.1, -z.2⟩⟩ @[simp] lemma neg_re (z : ℤ√d) : (-z).re = -z.re := rfl @[simp] lemma neg_im (z : ℤ√d) : (-z).im = -z.im := rfl /-- Multiplication in `ℤ√d` -/ instance : has_mul ℤ√d := ⟨λ z w, ⟨z.1 * w.1 + d * z.2 * w.2, z.1 * w.2 + z.2 * w.1⟩⟩ @[simp] lemma mul_re (z w : ℤ√d) : (z * w).re = z.re * w.re + d * z.im * w.im := rfl @[simp] lemma mul_im (z w : ℤ√d) : (z * w).im = z.re * w.im + z.im * w.re := rfl instance : add_comm_group ℤ√d := by refine_struct { add := (+), zero := (0 : ℤ√d), sub := λ a b, a + -b, neg := has_neg.neg, zsmul := @zsmul_rec (ℤ√d) ⟨0⟩ ⟨(+)⟩ ⟨has_neg.neg⟩, nsmul := @nsmul_rec (ℤ√d) ⟨0⟩ ⟨(+)⟩ }; intros; try { refl }; simp [ext, add_comm, add_left_comm] instance : add_group_with_one ℤ√d := { nat_cast := λ n, of_int n, int_cast := of_int, one := 1, .. zsqrtd.add_comm_group } instance : comm_ring ℤ√d := by refine_struct { add := (+), zero := (0 : ℤ√d), mul := (*), one := 1, npow := @npow_rec (ℤ√d) ⟨1⟩ ⟨(*)⟩, .. zsqrtd.add_group_with_one }; intros; try { refl }; simp [ext, add_mul, mul_add, add_comm, add_left_comm, mul_comm, mul_left_comm] 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 /-- Conjugation in `ℤ√d`. The conjugate of `a + b √d` is `a - b √d`. -/ instance : has_star ℤ√d := { star := λ z, ⟨z.1, -z.2⟩ } @[simp] lemma star_mk (x y : ℤ) : star (⟨x, y⟩ : ℤ√d) = ⟨x, -y⟩ := rfl @[simp] lemma star_re (z : ℤ√d) : (star z).re = z.re := rfl @[simp] lemma star_im (z : ℤ√d) : (star z).im = -z.im := rfl instance : star_ring ℤ√d := { star_involutive := λ x, ext.mpr ⟨rfl, neg_neg _⟩, star_mul := λ a b, ext.mpr ⟨by simp; ring, by simp; ring⟩, star_add := λ a b, ext.mpr ⟨rfl, neg_add _ _⟩ } instance : nontrivial ℤ√d := ⟨⟨0, 1, dec_trivial⟩⟩ @[simp] theorem coe_nat_re (n : ℕ) : (n : ℤ√d).re = n := rfl @[simp] theorem coe_nat_im (n : ℕ) : (n : ℤ√d).im = 0 := rfl theorem coe_nat_val (n : ℕ) : (n : ℤ√d) = ⟨n, 0⟩ := rfl @[simp] theorem coe_int_re (n : ℤ) : (n : ℤ√d).re = n := by cases n; refl @[simp] theorem coe_int_im (n : ℤ) : (n : ℤ√d).im = 0 := by cases n; refl 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] theorem smul_re (a : ℤ) (b : ℤ√d) : (↑a * b).re = a * b.re := by simp theorem smul_im (a : ℤ) (b : ℤ√d) : (↑a * b).im = a * b.im := by simp @[simp] theorem muld_val (x y : ℤ) : sqrtd * ⟨x, y⟩ = ⟨d * y, x⟩ := by simp [ext] @[simp] theorem dmuld : sqrtd * sqrtd = d := 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_star {x y : ℤ} : (⟨x, y⟩ * star ⟨x, y⟩ : ℤ√d) = x * x - d * y * y := by simp [ext, sub_eq_add_neg, mul_comm] protected lemma coe_int_add (m n : ℤ) : (↑(m + n) : ℤ√d) = ↑m + ↑n := (int.cast_ring_hom _).map_add _ _ protected lemma coe_int_sub (m n : ℤ) : (↑(m - n) : ℤ√d) = ↑m - ↑n := (int.cast_ring_hom _).map_sub _ _ protected lemma coe_int_mul (m n : ℤ) : (↑(m * n) : ℤ√d) = ↑m * ↑n := (int.cast_ring_hom _).map_mul _ _ protected lemma coe_int_inj {m n : ℤ} (h : (↑m : ℤ√d) = ↑n) : m = n := by simpa using congr_arg re h lemma coe_int_dvd_iff (z : ℤ) (a : ℤ√d) : ↑z ∣ a ↔ z ∣ a.re ∧ z ∣ a.im := begin split, { rintro ⟨x, rfl⟩, simp only [add_zero, coe_int_re, zero_mul, mul_im, dvd_mul_right, and_self, mul_re, mul_zero, coe_int_im] }, { rintro ⟨⟨r, hr⟩, ⟨i, hi⟩⟩, use ⟨r, i⟩, rw [smul_val, ext], exact ⟨hr, hi⟩ }, end @[simp, norm_cast] lemma coe_int_dvd_coe_int (a b : ℤ) : (a : ℤ√d) ∣ b ↔ a ∣ b := begin rw coe_int_dvd_iff, split, { rintro ⟨hre, -⟩, rwa [coe_int_re] at hre }, { rw [coe_int_re, coe_int_im], exact λ hc, ⟨hc, dvd_zero a⟩ }, end protected lemma eq_of_smul_eq_smul_left {a : ℤ} {b c : ℤ√d} (ha : a ≠ 0) (h : ↑a * b = a * c) : b = c := begin rw ext at h ⊢, apply and.imp _ _ h; { simpa only [smul_re, smul_im] using mul_left_cancel₀ ha }, end section gcd lemma gcd_eq_zero_iff (a : ℤ√d) : int.gcd a.re a.im = 0 ↔ a = 0 := by simp only [int.gcd_eq_zero_iff, ext, eq_self_iff_true, zero_im, zero_re] lemma gcd_pos_iff (a : ℤ√d) : 0 < int.gcd a.re a.im ↔ a ≠ 0 := pos_iff_ne_zero.trans $ not_congr a.gcd_eq_zero_iff lemma coprime_of_dvd_coprime {a b : ℤ√d} (hcoprime : is_coprime a.re a.im) (hdvd : b ∣ a) : is_coprime b.re b.im := begin apply is_coprime_of_dvd, { rintro ⟨hre, him⟩, obtain rfl : b = 0, { simp only [ext, hre, eq_self_iff_true, zero_im, him, and_self, zero_re] }, rw zero_dvd_iff at hdvd, simpa only [hdvd, zero_im, zero_re, not_coprime_zero_zero] using hcoprime }, { intros z hz hznezero hzdvdu hzdvdv, apply hz, obtain ⟨ha, hb⟩ : z ∣ a.re ∧ z ∣ a.im, { rw ←coe_int_dvd_iff, apply dvd_trans _ hdvd, rw coe_int_dvd_iff, exact ⟨hzdvdu, hzdvdv⟩ }, exact hcoprime.is_unit_of_dvd' ha hb }, end lemma exists_coprime_of_gcd_pos {a : ℤ√d} (hgcd : 0 < int.gcd a.re a.im) : ∃ b : ℤ√d, a = ((int.gcd a.re a.im : ℤ) : ℤ√d) * b ∧ is_coprime b.re b.im := begin obtain ⟨re, im, H1, Hre, Him⟩ := int.exists_gcd_one hgcd, rw [mul_comm] at Hre Him, refine ⟨⟨re, im⟩, _, _⟩, { rw [smul_val, ext, ←Hre, ←Him], split; refl }, { rw [←int.gcd_eq_one_iff_coprime, H1] } end end gcd /-- 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 /-- The norm of an element of `ℤ[√d]`. -/ def norm (n : ℤ√d) : ℤ := n.re * n.re - d * n.im * n.im lemma norm_def (n : ℤ√d) : n.norm = n.re * n.re - d * n.im * n.im := rfl @[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 } /-- `norm` as a `monoid_hom`. -/ def norm_monoid_hom : ℤ√d →* ℤ := { to_fun := norm, map_mul' := norm_mul, map_one' := norm_one } lemma norm_eq_mul_conj (n : ℤ√d) : (norm n : ℤ√d) = n * star n := by cases n; simp [norm, star, zsqrtd.ext, mul_comm, sub_eq_add_neg] @[simp] lemma norm_neg (x : ℤ√d) : (-x).norm = x.norm := coe_int_inj $ by simp only [norm_eq_mul_conj, star_neg, neg_mul, mul_neg, neg_neg] @[simp] lemma norm_conj (x : ℤ√d) : (star x).norm = x.norm := coe_int_inj $ by simp only [norm_eq_mul_conj, star_star, mul_comm] 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 ⟨star x, 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 ⟨- star x, 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, mul_eq_one] at this, exact this.1 end⟩ lemma is_unit_iff_norm_is_unit {d : ℤ} (z : ℤ√d) : is_unit z ↔ is_unit z.norm := by rw [int.is_unit_iff_nat_abs_eq, norm_eq_one_iff] lemma norm_eq_one_iff' {d : ℤ} (hd : d ≤ 0) (z : ℤ√d) : z.norm = 1 ↔ is_unit z := by rw [←norm_eq_one_iff, ←int.coe_nat_inj', int.nat_abs_of_nonneg (norm_nonneg hd z), int.coe_nat_one] lemma norm_eq_zero_iff {d : ℤ} (hd : d < 0) (z : ℤ√d) : z.norm = 0 ↔ z = 0 := begin split, { intro h, rw [ext, zero_re, zero_im], rw [norm_def, sub_eq_add_neg, mul_assoc] at h, have left := mul_self_nonneg z.re, have right := neg_nonneg.mpr (mul_nonpos_of_nonpos_of_nonneg hd.le (mul_self_nonneg z.im)), obtain ⟨ha, hb⟩ := (add_eq_zero_iff' left right).mp h, split; apply eq_zero_of_mul_self_eq_zero, { exact ha }, { rw [neg_eq_zero, mul_eq_zero] at hb, exact hb.resolve_left hd.ne } }, { rintro rfl, exact norm_zero } end lemma norm_eq_of_associated {d : ℤ} (hd : d ≤ 0) {x y : ℤ√d} (h : associated x y) : x.norm = y.norm := begin obtain ⟨u, rfl⟩ := h, rw [norm_mul, (norm_eq_one_iff' hd _).mpr u.is_unit, mul_one], end end norm end section parameter {d : ℕ} /-- Nonnegativity of an element of `ℤ√d`. -/ def nonneg : ℤ√d → Prop | ⟨a, b⟩ := nonnegg d 1 a b instance : has_le ℤ√d := ⟨λ a b, nonneg (b - a)⟩ instance : has_lt ℤ√d := ⟨λ a b, ¬ b ≤ a⟩ 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 : @decidable_rel (ℤ√d) (≤) := λ _ _, 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_rfl 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 lemma 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⟩, { 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 h)) }, { apply nat.le_add_right } }, { dsimp, 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 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 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 := begin have t := (b - a).nonneg_total, rwa neg_sub at t, end instance : preorder ℤ√d := { le := (≤), le_refl := λ a, show nonneg (a - a), by simp only [sub_self], le_trans := λ a b c hab hbc, by simpa [sub_add_sub_cancel'] using hab.add hbc, lt := (<), lt_iff_le_not_le := λ a b, (and_iff_right_of_imp (zsqrtd.le_total _ _).resolve_left).symm } 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, h.trans _⟩, 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 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 simp only [← int.cast_coe_nat] {single_pass := tt}; 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_smul ha).add (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) := mul_left_cancel₀ (mul_pos gpos gpos).ne' (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_sq (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_sq _ _) | ⟨-[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_sq _ _) 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 : 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_left h1, have h2 : x*w = -(y*z), from eq_neg_of_add_eq_zero_left 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 $ mul_right_cancel₀ 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 $ mul_right_cancel₀ 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 : no_zero_divisors ℤ√d := { eq_zero_or_eq_zero_of_mul_eq_zero := @zsqrtd.eq_zero_or_eq_zero_of_mul_eq_zero } instance : is_domain ℤ√d := by exact no_zero_divisors.to_is_domain _ 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 : linear_ordered_comm_ring ℤ√d := { add_le_add_left := @zsqrtd.add_le_add_left, mul_pos := @zsqrtd.mul_pos, zero_le_one := dec_trivial, .. zsqrtd.comm_ring, .. zsqrtd.linear_order, .. zsqrtd.nontrivial } instance : linear_ordered_ring ℤ√d := by apply_instance instance : ordered_ring ℤ√d := by apply_instance end lemma norm_eq_zero {d : ℤ} (h_nonsquare : ∀ n : ℤ, d ≠ n*n) (a : ℤ√d) : norm a = 0 ↔ a = 0 := begin refine ⟨λ ha, ext.mpr _, λ h, by rw [h, norm_zero]⟩, delta norm at ha, rw sub_eq_zero at ha, by_cases h : 0 ≤ d, { obtain ⟨d', rfl⟩ := int.eq_coe_of_zero_le h, haveI : nonsquare d' := ⟨λ n h, h_nonsquare n $ by exact_mod_cast h⟩, exact divides_sq_eq_zero_z ha, }, { push_neg at h, suffices : a.re * a.re = 0, { rw eq_zero_of_mul_self_eq_zero this at ha ⊢, simpa only [true_and, or_self_right, zero_re, zero_im, eq_self_iff_true, zero_eq_mul, mul_zero, mul_eq_zero, h.ne, false_or, or_self] using ha }, apply _root_.le_antisymm _ (mul_self_nonneg _), rw [ha, mul_assoc], exact mul_nonpos_of_nonpos_of_nonneg h.le (mul_self_nonneg _) } end variables {R : Type} @[ext] lemma hom_ext [ring R] {d : ℤ} (f g : ℤ√d →+* R) (h : f sqrtd = g sqrtd) : f = g := begin ext ⟨x_re, x_im⟩, simp [decompose, h], end variables [comm_ring R] /-- The unique `ring_hom` from `ℤ√d` to a ring `R`, constructed by replacing `√d` with the provided root. Conversely, this associates to every mapping `ℤ√d →+* R` a value of `√d` in `R`. -/ @[simps] def lift {d : ℤ} : {r : R // r * r = ↑d} ≃ (ℤ√d →+* R) := { to_fun := λ r, { to_fun := λ a, a.1 + a.2*(r : R), map_zero' := by simp, map_add' := λ a b, by { simp, ring, }, map_one' := by simp, map_mul' := λ a b, by { have : (a.re + a.im * r : R) * (b.re + b.im * r) = a.re * b.re + (a.re * b.im + a.im * b.re) * r + a.im * b.im * (r * r) := by ring, simp [this, r.prop], ring, } }, inv_fun := λ f, ⟨f sqrtd, by rw [←f.map_mul, dmuld, map_int_cast]⟩, left_inv := λ r, by { ext, simp }, right_inv := λ f, by { ext, simp } } /-- `lift r` is injective if `d` is non-square, and R has characteristic zero (that is, the map from `ℤ` into `R` is injective). -/ lemma lift_injective [char_zero R] {d : ℤ} (r : {r : R // r * r = ↑d}) (hd : ∀ n : ℤ, d ≠ n*n) : function.injective (lift r) := (injective_iff_map_eq_zero (lift r)).mpr $ λ a ha, begin have h_inj : function.injective (coe : ℤ → R) := int.cast_injective, suffices : lift r a.norm = 0, { simp only [coe_int_re, add_zero, lift_apply_apply, coe_int_im, int.cast_zero, zero_mul] at this, rwa [← int.cast_zero, h_inj.eq_iff, norm_eq_zero hd] at this }, rw [norm_eq_mul_conj, ring_hom.map_mul, ha, zero_mul] end /-- An element of `ℤ√d` has norm equal to `1` if and only if it is contained in the submonoid of unitary elements. -/ lemma norm_eq_one_iff_mem_unitary {d : ℤ} {a : ℤ√d} : a.norm = 1 ↔ a ∈ unitary ℤ√d := begin rw [unitary.mem_iff_self_mul_star, ← norm_eq_mul_conj], norm_cast, end /-- The kernel of the norm map on `ℤ√d` equals the submonoid of unitary elements. -/ lemma mker_norm_eq_unitary {d : ℤ} : (@norm_monoid_hom d).mker = unitary ℤ√d := submonoid.ext (λ x, norm_eq_one_iff_mem_unitary) end zsqrtd
b56a1c410001a5e8f49161254c1b348d75c3bcab
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/category_theory/limits/has_limits.lean
ede3eb66aa739240cda35614c09db9400dc7269f
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
41,600
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Reid Barton, Mario Carneiro, Scott Morrison, Floris van Doorn -/ import category_theory.limits.is_limit import category_theory.category.ulift /-! # Existence of limits and colimits In `category_theory.limits.is_limit` we defined `is_limit c`, the data showing that a cone `c` is a limit cone. The two main structures defined in this file are: * `limit_cone F`, which consists of a choice of cone for `F` and the fact it is a limit cone, and * `has_limit F`, asserting the mere existence of some limit cone for `F`. `has_limit` is a propositional typeclass (it's important that it is a proposition merely asserting the existence of a limit, as otherwise we would have non-defeq problems from incompatible instances). While `has_limit` only asserts the existence of a limit cone, we happily use the axiom of choice in mathlib, so there are convenience functions all depending on `has_limit F`: * `limit F : C`, producing some limit object (of course all such are isomorphic) * `limit.π F j : limit F ⟶ F.obj j`, the morphisms out of the limit, * `limit.lift F c : c.X ⟶ limit F`, the universal morphism from any other `c : cone F`, etc. Key to using the `has_limit` interface is that there is an `@[ext]` lemma stating that to check `f = g`, for `f g : Z ⟶ limit F`, it suffices to check `f ≫ limit.π F j = g ≫ limit.π F j` for every `j`. This, combined with `@[simp]` lemmas, makes it possible to prove many easy facts about limits using automation (e.g. `tidy`). There are abbreviations `has_limits_of_shape J C` and `has_limits C` asserting the existence of classes of limits. Later more are introduced, for finite limits, special shapes of limits, etc. Ideally, many results about limits should be stated first in terms of `is_limit`, and then a result in terms of `has_limit` derived from this. At this point, however, this is far from uniformly achieved in mathlib --- often statements are only written in terms of `has_limit`. ## Implementation At present we simply say everything twice, in order to handle both limits and colimits. It would be highly desirable to have some automation support, e.g. a `@[dualize]` attribute that behaves similarly to `@[to_additive]`. ## References * [Stacks: Limits and colimits](https://stacks.math.columbia.edu/tag/002D) -/ noncomputable theory open category_theory category_theory.category category_theory.functor opposite namespace category_theory.limits -- morphism levels before object levels. See note [category_theory universes]. universes v₁ u₁ v₂ u₂ v₃ u₃ v v' v'' u u' u'' variables {J : Type u₁} [category.{v₁} J] {K : Type u₂} [category.{v₂} K] variables {C : Type u} [category.{v} C] variables {F : J ⥤ C} section limit /-- `limit_cone F` contains a cone over `F` together with the information that it is a limit. -/ @[nolint has_inhabited_instance] structure limit_cone (F : J ⥤ C) := (cone : cone F) (is_limit : is_limit cone) /-- `has_limit F` represents the mere existence of a limit for `F`. -/ class has_limit (F : J ⥤ C) : Prop := mk' :: (exists_limit : nonempty (limit_cone F)) lemma has_limit.mk {F : J ⥤ C} (d : limit_cone F) : has_limit F := ⟨nonempty.intro d⟩ /-- Use the axiom of choice to extract explicit `limit_cone F` from `has_limit F`. -/ def get_limit_cone (F : J ⥤ C) [has_limit F] : limit_cone F := classical.choice $ has_limit.exists_limit variables (J C) /-- `C` has limits of shape `J` if there exists a limit for every functor `F : J ⥤ C`. -/ class has_limits_of_shape : Prop := (has_limit : Π F : J ⥤ C, has_limit F . tactic.apply_instance) /-- `C` has all limits of size `v₁ u₁` (`has_limits_of_size.{v₁ u₁} C`) if it has limits of every shape `J : Type u₁` with `[category.{v₁} J]`. -/ class has_limits_of_size (C : Type u) [category.{v} C] : Prop := (has_limits_of_shape : Π (J : Type u₁) [𝒥 : category.{v₁} J], has_limits_of_shape J C . tactic.apply_instance) /-- `C` has all (small) limits if it has limits of every shape that is as big as its hom-sets. -/ abbreviation has_limits (C : Type u) [category.{v} C] : Prop := has_limits_of_size.{v v} C lemma has_limits.has_limits_of_shape {C : Type u} [category.{v} C] [has_limits C] (J : Type v) [category.{v} J] : has_limits_of_shape J C := has_limits_of_size.has_limits_of_shape J variables {J C} @[priority 100] -- see Note [lower instance priority] instance has_limit_of_has_limits_of_shape {J : Type u₁} [category.{v₁} J] [H : has_limits_of_shape J C] (F : J ⥤ C) : has_limit F := has_limits_of_shape.has_limit F @[priority 100] -- see Note [lower instance priority] instance has_limits_of_shape_of_has_limits {J : Type u₁} [category.{v₁} J] [H : has_limits_of_size.{v₁ u₁} C] : has_limits_of_shape J C := has_limits_of_size.has_limits_of_shape J /- Interface to the `has_limit` class. -/ /-- An arbitrary choice of limit cone for a functor. -/ def limit.cone (F : J ⥤ C) [has_limit F] : cone F := (get_limit_cone F).cone /-- An arbitrary choice of limit object of a functor. -/ def limit (F : J ⥤ C) [has_limit F] := (limit.cone F).X /-- The projection from the limit object to a value of the functor. -/ def limit.π (F : J ⥤ C) [has_limit F] (j : J) : limit F ⟶ F.obj j := (limit.cone F).π.app j @[simp] lemma limit.cone_X {F : J ⥤ C} [has_limit F] : (limit.cone F).X = limit F := rfl @[simp] lemma limit.cone_π {F : J ⥤ C} [has_limit F] : (limit.cone F).π.app = limit.π _ := rfl @[simp, reassoc] lemma limit.w (F : J ⥤ C) [has_limit F] {j j' : J} (f : j ⟶ j') : limit.π F j ≫ F.map f = limit.π F j' := (limit.cone F).w f /-- Evidence that the arbitrary choice of cone provied by `limit.cone F` is a limit cone. -/ def limit.is_limit (F : J ⥤ C) [has_limit F] : is_limit (limit.cone F) := (get_limit_cone F).is_limit /-- The morphism from the cone point of any other cone to the limit object. -/ def limit.lift (F : J ⥤ C) [has_limit F] (c : cone F) : c.X ⟶ limit F := (limit.is_limit F).lift c @[simp] lemma limit.is_limit_lift {F : J ⥤ C} [has_limit F] (c : cone F) : (limit.is_limit F).lift c = limit.lift F c := rfl @[simp, reassoc] lemma limit.lift_π {F : J ⥤ C} [has_limit F] (c : cone F) (j : J) : limit.lift F c ≫ limit.π F j = c.π.app j := is_limit.fac _ c j /-- Functoriality of limits. Usually this morphism should be accessed through `lim.map`, but may be needed separately when you have specified limits for the source and target functors, but not necessarily for all functors of shape `J`. -/ def lim_map {F G : J ⥤ C} [has_limit F] [has_limit G] (α : F ⟶ G) : limit F ⟶ limit G := is_limit.map _ (limit.is_limit G) α @[simp, reassoc] lemma lim_map_π {F G : J ⥤ C} [has_limit F] [has_limit G] (α : F ⟶ G) (j : J) : lim_map α ≫ limit.π G j = limit.π F j ≫ α.app j := limit.lift_π _ j /-- The cone morphism from any cone to the arbitrary choice of limit cone. -/ def limit.cone_morphism {F : J ⥤ C} [has_limit F] (c : cone F) : c ⟶ limit.cone F := (limit.is_limit F).lift_cone_morphism c @[simp] lemma limit.cone_morphism_hom {F : J ⥤ C} [has_limit F] (c : cone F) : (limit.cone_morphism c).hom = limit.lift F c := rfl lemma limit.cone_morphism_π {F : J ⥤ C} [has_limit F] (c : cone F) (j : J) : (limit.cone_morphism c).hom ≫ limit.π F j = c.π.app j := by simp @[simp, reassoc] lemma limit.cone_point_unique_up_to_iso_hom_comp {F : J ⥤ C} [has_limit F] {c : cone F} (hc : is_limit c) (j : J) : (is_limit.cone_point_unique_up_to_iso hc (limit.is_limit _)).hom ≫ limit.π F j = c.π.app j := is_limit.cone_point_unique_up_to_iso_hom_comp _ _ _ @[simp, reassoc] lemma limit.cone_point_unique_up_to_iso_inv_comp {F : J ⥤ C} [has_limit F] {c : cone F} (hc : is_limit c) (j : J) : (is_limit.cone_point_unique_up_to_iso (limit.is_limit _) hc).inv ≫ limit.π F j = c.π.app j := is_limit.cone_point_unique_up_to_iso_inv_comp _ _ _ /-- Given any other limit cone for `F`, the chosen `limit F` is isomorphic to the cone point. -/ def limit.iso_limit_cone {F : J ⥤ C} [has_limit F] (t : limit_cone F) : limit F ≅ t.cone.X := is_limit.cone_point_unique_up_to_iso (limit.is_limit F) t.is_limit @[simp, reassoc] lemma limit.iso_limit_cone_hom_π {F : J ⥤ C} [has_limit F] (t : limit_cone F) (j : J) : (limit.iso_limit_cone t).hom ≫ t.cone.π.app j = limit.π F j := by { dsimp [limit.iso_limit_cone, is_limit.cone_point_unique_up_to_iso], tidy, } @[simp, reassoc] lemma limit.iso_limit_cone_inv_π {F : J ⥤ C} [has_limit F] (t : limit_cone F) (j : J) : (limit.iso_limit_cone t).inv ≫ limit.π F j = t.cone.π.app j := by { dsimp [limit.iso_limit_cone, is_limit.cone_point_unique_up_to_iso], tidy, } @[ext] lemma limit.hom_ext {F : J ⥤ C} [has_limit F] {X : C} {f f' : X ⟶ limit F} (w : ∀ j, f ≫ limit.π F j = f' ≫ limit.π F j) : f = f' := (limit.is_limit F).hom_ext w @[simp] lemma limit.lift_map {F G : J ⥤ C} [has_limit F] [has_limit G] (c : cone F) (α : F ⟶ G) : limit.lift F c ≫ lim_map α = limit.lift G ((cones.postcompose α).obj c) := by { ext, rw [assoc, lim_map_π, limit.lift_π_assoc, limit.lift_π], refl } @[simp] lemma limit.lift_cone {F : J ⥤ C} [has_limit F] : limit.lift F (limit.cone F) = 𝟙 (limit F) := (limit.is_limit _).lift_self /-- The isomorphism (in `Type`) between morphisms from a specified object `W` to the limit object, and cones with cone point `W`. -/ def limit.hom_iso (F : J ⥤ C) [has_limit F] (W : C) : ulift.{u₁} (W ⟶ limit F : Type v) ≅ (F.cones.obj (op W)) := (limit.is_limit F).hom_iso W @[simp] lemma limit.hom_iso_hom (F : J ⥤ C) [has_limit F] {W : C} (f : ulift (W ⟶ limit F)) : (limit.hom_iso F W).hom f = (const J).map f.down ≫ (limit.cone F).π := (limit.is_limit F).hom_iso_hom f /-- The isomorphism (in `Type`) between morphisms from a specified object `W` to the limit object, and an explicit componentwise description of cones with cone point `W`. -/ def limit.hom_iso' (F : J ⥤ C) [has_limit F] (W : C) : ulift.{u₁} ((W ⟶ limit F) : Type v) ≅ { p : Π j, W ⟶ F.obj j // ∀ {j j' : J} (f : j ⟶ j'), p j ≫ F.map f = p j' } := (limit.is_limit F).hom_iso' W lemma limit.lift_extend {F : J ⥤ C} [has_limit F] (c : cone F) {X : C} (f : X ⟶ c.X) : limit.lift F (c.extend f) = f ≫ limit.lift F c := by obviously /-- If a functor `F` has a limit, so does any naturally isomorphic functor. -/ lemma has_limit_of_iso {F G : J ⥤ C} [has_limit F] (α : F ≅ G) : has_limit G := has_limit.mk { cone := (cones.postcompose α.hom).obj (limit.cone F), is_limit := { lift := λ s, limit.lift F ((cones.postcompose α.inv).obj s), fac' := λ s j, begin rw [cones.postcompose_obj_π, nat_trans.comp_app, limit.cone_π, ←category.assoc, limit.lift_π], simp end, uniq' := λ s m w, begin apply limit.hom_ext, intro j, rw [limit.lift_π, cones.postcompose_obj_π, nat_trans.comp_app, ←nat_iso.app_inv, iso.eq_comp_inv], simpa using w j end } } /-- If a functor `G` has the same collection of cones as a functor `F` which has a limit, then `G` also has a limit. -/ -- See the construction of limits from products and equalizers -- for an example usage. lemma has_limit.of_cones_iso {J K : Type u₁} [category.{v₁} J] [category.{v₂} K] (F : J ⥤ C) (G : K ⥤ C) (h : F.cones ≅ G.cones) [has_limit F] : has_limit G := has_limit.mk ⟨_, is_limit.of_nat_iso ((is_limit.nat_iso (limit.is_limit F)) ≪≫ h)⟩ /-- The limits of `F : J ⥤ C` and `G : J ⥤ C` are isomorphic, if the functors are naturally isomorphic. -/ def has_limit.iso_of_nat_iso {F G : J ⥤ C} [has_limit F] [has_limit G] (w : F ≅ G) : limit F ≅ limit G := is_limit.cone_points_iso_of_nat_iso (limit.is_limit F) (limit.is_limit G) w @[simp, reassoc] lemma has_limit.iso_of_nat_iso_hom_π {F G : J ⥤ C} [has_limit F] [has_limit G] (w : F ≅ G) (j : J) : (has_limit.iso_of_nat_iso w).hom ≫ limit.π G j = limit.π F j ≫ w.hom.app j := is_limit.cone_points_iso_of_nat_iso_hom_comp _ _ _ _ @[simp, reassoc] lemma has_limit.lift_iso_of_nat_iso_hom {F G : J ⥤ C} [has_limit F] [has_limit G] (t : cone F) (w : F ≅ G) : limit.lift F t ≫ (has_limit.iso_of_nat_iso w).hom = limit.lift G ((cones.postcompose w.hom).obj _) := is_limit.lift_comp_cone_points_iso_of_nat_iso_hom _ _ _ /-- The limits of `F : J ⥤ C` and `G : K ⥤ C` are isomorphic, if there is an equivalence `e : J ≌ K` making the triangle commute up to natural isomorphism. -/ def has_limit.iso_of_equivalence {F : J ⥤ C} [has_limit F] {G : K ⥤ C} [has_limit G] (e : J ≌ K) (w : e.functor ⋙ G ≅ F) : limit F ≅ limit G := is_limit.cone_points_iso_of_equivalence (limit.is_limit F) (limit.is_limit G) e w @[simp] lemma has_limit.iso_of_equivalence_hom_π {F : J ⥤ C} [has_limit F] {G : K ⥤ C} [has_limit G] (e : J ≌ K) (w : e.functor ⋙ G ≅ F) (k : K) : (has_limit.iso_of_equivalence e w).hom ≫ limit.π G k = limit.π F (e.inverse.obj k) ≫ w.inv.app (e.inverse.obj k) ≫ G.map (e.counit.app k) := begin simp only [has_limit.iso_of_equivalence, is_limit.cone_points_iso_of_equivalence_hom], dsimp, simp, end @[simp] lemma has_limit.iso_of_equivalence_inv_π {F : J ⥤ C} [has_limit F] {G : K ⥤ C} [has_limit G] (e : J ≌ K) (w : e.functor ⋙ G ≅ F) (j : J) : (has_limit.iso_of_equivalence e w).inv ≫ limit.π F j = limit.π G (e.functor.obj j) ≫ w.hom.app j := begin simp only [has_limit.iso_of_equivalence, is_limit.cone_points_iso_of_equivalence_hom], dsimp, simp, end section pre variables (F) [has_limit F] (E : K ⥤ J) [has_limit (E ⋙ F)] /-- The canonical morphism from the limit of `F` to the limit of `E ⋙ F`. -/ def limit.pre : limit F ⟶ limit (E ⋙ F) := limit.lift (E ⋙ F) ((limit.cone F).whisker E) @[simp, reassoc] lemma limit.pre_π (k : K) : limit.pre F E ≫ limit.π (E ⋙ F) k = limit.π F (E.obj k) := by { erw is_limit.fac, refl } @[simp] lemma limit.lift_pre (c : cone F) : limit.lift F c ≫ limit.pre F E = limit.lift (E ⋙ F) (c.whisker E) := by ext; simp variables {L : Type u₃} [category.{v₃} L] variables (D : L ⥤ K) [has_limit (D ⋙ E ⋙ F)] @[simp] lemma limit.pre_pre : limit.pre F E ≫ limit.pre (E ⋙ F) D = limit.pre F (D ⋙ E) := by ext j; erw [assoc, limit.pre_π, limit.pre_π, limit.pre_π]; refl variables {E F} /--- If we have particular limit cones available for `E ⋙ F` and for `F`, we obtain a formula for `limit.pre F E`. -/ lemma limit.pre_eq (s : limit_cone (E ⋙ F)) (t : limit_cone F) : limit.pre F E = (limit.iso_limit_cone t).hom ≫ s.is_limit.lift ((t.cone).whisker E) ≫ (limit.iso_limit_cone s).inv := by tidy end pre section post variables {D : Type u'} [category.{v'} D] variables (F) [has_limit F] (G : C ⥤ D) [has_limit (F ⋙ G)] /-- The canonical morphism from `G` applied to the limit of `F` to the limit of `F ⋙ G`. -/ def limit.post : G.obj (limit F) ⟶ limit (F ⋙ G) := limit.lift (F ⋙ G) (G.map_cone (limit.cone F)) @[simp, reassoc] lemma limit.post_π (j : J) : limit.post F G ≫ limit.π (F ⋙ G) j = G.map (limit.π F j) := by { erw is_limit.fac, refl } @[simp] lemma limit.lift_post (c : cone F) : G.map (limit.lift F c) ≫ limit.post F G = limit.lift (F ⋙ G) (G.map_cone c) := by { ext, rw [assoc, limit.post_π, ←G.map_comp, limit.lift_π, limit.lift_π], refl } @[simp] lemma limit.post_post {E : Type u''} [category.{v''} E] (H : D ⥤ E) [has_limit ((F ⋙ G) ⋙ H)] : /- H G (limit F) ⟶ H (limit (F ⋙ G)) ⟶ limit ((F ⋙ G) ⋙ H) equals -/ /- H G (limit F) ⟶ limit (F ⋙ (G ⋙ H)) -/ H.map (limit.post F G) ≫ limit.post (F ⋙ G) H = limit.post F (G ⋙ H) := by ext; erw [assoc, limit.post_π, ←H.map_comp, limit.post_π, limit.post_π]; refl end post lemma limit.pre_post {D : Type u'} [category.{v'} D] (E : K ⥤ J) (F : J ⥤ C) (G : C ⥤ D) [has_limit F] [has_limit (E ⋙ F)] [has_limit (F ⋙ G)] [has_limit ((E ⋙ F) ⋙ G)] : /- G (limit F) ⟶ G (limit (E ⋙ F)) ⟶ limit ((E ⋙ F) ⋙ G) vs -/ /- G (limit F) ⟶ limit F ⋙ G ⟶ limit (E ⋙ (F ⋙ G)) or -/ G.map (limit.pre F E) ≫ limit.post (E ⋙ F) G = limit.post F G ≫ limit.pre (F ⋙ G) E := by ext; erw [assoc, limit.post_π, ←G.map_comp, limit.pre_π, assoc, limit.pre_π, limit.post_π]; refl open category_theory.equivalence instance has_limit_equivalence_comp (e : K ≌ J) [has_limit F] : has_limit (e.functor ⋙ F) := has_limit.mk { cone := cone.whisker e.functor (limit.cone F), is_limit := is_limit.whisker_equivalence (limit.is_limit F) e, } local attribute [elab_simple] inv_fun_id_assoc -- not entirely sure why this is needed /-- If a `E ⋙ F` has a limit, and `E` is an equivalence, we can construct a limit of `F`. -/ lemma has_limit_of_equivalence_comp (e : K ≌ J) [has_limit (e.functor ⋙ F)] : has_limit F := begin haveI : has_limit (e.inverse ⋙ e.functor ⋙ F) := limits.has_limit_equivalence_comp e.symm, apply has_limit_of_iso (e.inv_fun_id_assoc F), end -- `has_limit_comp_equivalence` and `has_limit_of_comp_equivalence` -- are proved in `category_theory/adjunction/limits.lean`. section lim_functor variables [has_limits_of_shape J C] section /-- `limit F` is functorial in `F`, when `C` has all limits of shape `J`. -/ @[simps obj] def lim : (J ⥤ C) ⥤ C := { obj := λ F, limit F, map := λ F G α, lim_map α, map_id' := λ F, by { ext, erw [lim_map_π, category.id_comp, category.comp_id] }, map_comp' := λ F G H α β, by ext; erw [assoc, is_limit.fac, is_limit.fac, ←assoc, is_limit.fac, assoc]; refl } end variables {F} {G : J ⥤ C} (α : F ⟶ G) -- We generate this manually since `simps` gives it a weird name. @[simp] lemma lim_map_eq_lim_map : lim.map α = lim_map α := rfl lemma limit.map_pre [has_limits_of_shape K C] (E : K ⥤ J) : lim.map α ≫ limit.pre G E = limit.pre F E ≫ lim.map (whisker_left E α) := by { ext, simp } lemma limit.map_pre' [has_limits_of_shape K C] (F : J ⥤ C) {E₁ E₂ : K ⥤ J} (α : E₁ ⟶ E₂) : limit.pre F E₂ = limit.pre F E₁ ≫ lim.map (whisker_right α F) := by ext1; simp [← category.assoc] lemma limit.id_pre (F : J ⥤ C) : limit.pre F (𝟭 _) = lim.map (functor.left_unitor F).inv := by tidy lemma limit.map_post {D : Type u'} [category.{v'} D] [has_limits_of_shape J D] (H : C ⥤ D) : /- H (limit F) ⟶ H (limit G) ⟶ limit (G ⋙ H) vs H (limit F) ⟶ limit (F ⋙ H) ⟶ limit (G ⋙ H) -/ H.map (lim_map α) ≫ limit.post G H = limit.post F H ≫ lim_map (whisker_right α H) := begin ext, simp only [whisker_right_app, lim_map_π, assoc, limit.post_π_assoc, limit.post_π, ← H.map_comp], end /-- The isomorphism between morphisms from `W` to the cone point of the limit cone for `F` and cones over `F` with cone point `W` is natural in `F`. -/ def lim_yoneda : lim ⋙ yoneda ⋙ (whiskering_right _ _ _).obj ulift_functor.{u₁} ≅ category_theory.cones J C := nat_iso.of_components (λ F, nat_iso.of_components (λ W, limit.hom_iso F (unop W)) (by tidy)) (by tidy) end lim_functor /-- We can transport limits of shape `J` along an equivalence `J ≌ J'`. -/ lemma has_limits_of_shape_of_equivalence {J' : Type u₂} [category.{v₂} J'] (e : J ≌ J') [has_limits_of_shape J C] : has_limits_of_shape J' C := by { constructor, intro F, apply has_limit_of_equivalence_comp e, apply_instance } variable (C) /-- `has_limits_of_size.{v u} C` tries to obtain `has_limits_of_size.{v u} C` from some other `has_limits_of_size C`. -/ lemma has_limits_of_size_shrink [has_limits_of_size.{(max v₁ v₂) (max u₁ u₂)} C] : has_limits_of_size.{v₁ u₁} C := ⟨λ J hJ, by exactI has_limits_of_shape_of_equivalence (ulift_hom_ulift_category.equiv.{v₂ u₂} J).symm⟩ lemma has_smallest_limits_of_has_limits [has_limits C] : has_limits_of_size.{0 0} C := has_limits_of_size_shrink.{0 0} C end limit section colimit /-- `colimit_cocone F` contains a cocone over `F` together with the information that it is a colimit. -/ @[nolint has_inhabited_instance] structure colimit_cocone (F : J ⥤ C) := (cocone : cocone F) (is_colimit : is_colimit cocone) /-- `has_colimit F` represents the mere existence of a colimit for `F`. -/ class has_colimit (F : J ⥤ C) : Prop := mk' :: (exists_colimit : nonempty (colimit_cocone F)) lemma has_colimit.mk {F : J ⥤ C} (d : colimit_cocone F) : has_colimit F := ⟨nonempty.intro d⟩ /-- Use the axiom of choice to extract explicit `colimit_cocone F` from `has_colimit F`. -/ def get_colimit_cocone (F : J ⥤ C) [has_colimit F] : colimit_cocone F := classical.choice $ has_colimit.exists_colimit variables (J C) /-- `C` has colimits of shape `J` if there exists a colimit for every functor `F : J ⥤ C`. -/ class has_colimits_of_shape : Prop := (has_colimit : Π F : J ⥤ C, has_colimit F . tactic.apply_instance) /-- `C` has all colimits of size `v₁ u₁` (`has_colimits_of_size.{v₁ u₁} C`) if it has colimits of every shape `J : Type u₁` with `[category.{v₁} J]`. -/ class has_colimits_of_size (C : Type u) [category.{v} C] : Prop := (has_colimits_of_shape : Π (J : Type u₁) [𝒥 : category.{v₁} J], has_colimits_of_shape J C . tactic.apply_instance) /-- `C` has all (small) colimits if it has colimits of every shape that is as big as its hom-sets. -/ abbreviation has_colimits (C : Type u) [category.{v} C] : Prop := has_colimits_of_size.{v v} C lemma has_colimits.has_colimits_of_shape {C : Type u} [category.{v} C] [has_colimits C] (J : Type v) [category.{v} J] : has_colimits_of_shape J C := has_colimits_of_size.has_colimits_of_shape J variables {J C} @[priority 100] -- see Note [lower instance priority] instance has_colimit_of_has_colimits_of_shape {J : Type u₁} [category.{v₁} J] [H : has_colimits_of_shape J C] (F : J ⥤ C) : has_colimit F := has_colimits_of_shape.has_colimit F @[priority 100] -- see Note [lower instance priority] instance has_colimits_of_shape_of_has_colimits_of_size {J : Type u₁} [category.{v₁} J] [H : has_colimits_of_size.{v₁ u₁} C] : has_colimits_of_shape J C := has_colimits_of_size.has_colimits_of_shape J /- Interface to the `has_colimit` class. -/ /-- An arbitrary choice of colimit cocone of a functor. -/ def colimit.cocone (F : J ⥤ C) [has_colimit F] : cocone F := (get_colimit_cocone F).cocone /-- An arbitrary choice of colimit object of a functor. -/ def colimit (F : J ⥤ C) [has_colimit F] := (colimit.cocone F).X /-- The coprojection from a value of the functor to the colimit object. -/ def colimit.ι (F : J ⥤ C) [has_colimit F] (j : J) : F.obj j ⟶ colimit F := (colimit.cocone F).ι.app j @[simp] lemma colimit.cocone_ι {F : J ⥤ C} [has_colimit F] (j : J) : (colimit.cocone F).ι.app j = colimit.ι _ j := rfl @[simp] lemma colimit.cocone_X {F : J ⥤ C} [has_colimit F] : (colimit.cocone F).X = colimit F := rfl @[simp, reassoc] lemma colimit.w (F : J ⥤ C) [has_colimit F] {j j' : J} (f : j ⟶ j') : F.map f ≫ colimit.ι F j' = colimit.ι F j := (colimit.cocone F).w f /-- Evidence that the arbitrary choice of cocone is a colimit cocone. -/ def colimit.is_colimit (F : J ⥤ C) [has_colimit F] : is_colimit (colimit.cocone F) := (get_colimit_cocone F).is_colimit /-- The morphism from the colimit object to the cone point of any other cocone. -/ def colimit.desc (F : J ⥤ C) [has_colimit F] (c : cocone F) : colimit F ⟶ c.X := (colimit.is_colimit F).desc c @[simp] lemma colimit.is_colimit_desc {F : J ⥤ C} [has_colimit F] (c : cocone F) : (colimit.is_colimit F).desc c = colimit.desc F c := rfl /-- We have lots of lemmas describing how to simplify `colimit.ι F j ≫ _`, and combined with `colimit.ext` we rely on these lemmas for many calculations. However, since `category.assoc` is a `@[simp]` lemma, often expressions are right associated, and it's hard to apply these lemmas about `colimit.ι`. We thus use `reassoc` to define additional `@[simp]` lemmas, with an arbitrary extra morphism. (see `tactic/reassoc_axiom.lean`) -/ @[simp, reassoc] lemma colimit.ι_desc {F : J ⥤ C} [has_colimit F] (c : cocone F) (j : J) : colimit.ι F j ≫ colimit.desc F c = c.ι.app j := is_colimit.fac _ c j /-- Functoriality of colimits. Usually this morphism should be accessed through `colim.map`, but may be needed separately when you have specified colimits for the source and target functors, but not necessarily for all functors of shape `J`. -/ def colim_map {F G : J ⥤ C} [has_colimit F] [has_colimit G] (α : F ⟶ G) : colimit F ⟶ colimit G := is_colimit.map (colimit.is_colimit F) _ α @[simp, reassoc] lemma ι_colim_map {F G : J ⥤ C} [has_colimit F] [has_colimit G] (α : F ⟶ G) (j : J) : colimit.ι F j ≫ colim_map α = α.app j ≫ colimit.ι G j := colimit.ι_desc _ j /-- The cocone morphism from the arbitrary choice of colimit cocone to any cocone. -/ def colimit.cocone_morphism {F : J ⥤ C} [has_colimit F] (c : cocone F) : (colimit.cocone F) ⟶ c := (colimit.is_colimit F).desc_cocone_morphism c @[simp] lemma colimit.cocone_morphism_hom {F : J ⥤ C} [has_colimit F] (c : cocone F) : (colimit.cocone_morphism c).hom = colimit.desc F c := rfl lemma colimit.ι_cocone_morphism {F : J ⥤ C} [has_colimit F] (c : cocone F) (j : J) : colimit.ι F j ≫ (colimit.cocone_morphism c).hom = c.ι.app j := by simp @[simp, reassoc] lemma colimit.comp_cocone_point_unique_up_to_iso_hom {F : J ⥤ C} [has_colimit F] {c : cocone F} (hc : is_colimit c) (j : J) : colimit.ι F j ≫ (is_colimit.cocone_point_unique_up_to_iso (colimit.is_colimit _) hc).hom = c.ι.app j := is_colimit.comp_cocone_point_unique_up_to_iso_hom _ _ _ @[simp, reassoc] lemma colimit.comp_cocone_point_unique_up_to_iso_inv {F : J ⥤ C} [has_colimit F] {c : cocone F} (hc : is_colimit c) (j : J) : colimit.ι F j ≫ (is_colimit.cocone_point_unique_up_to_iso hc (colimit.is_colimit _)).inv = c.ι.app j := is_colimit.comp_cocone_point_unique_up_to_iso_inv _ _ _ /-- Given any other colimit cocone for `F`, the chosen `colimit F` is isomorphic to the cocone point. -/ def colimit.iso_colimit_cocone {F : J ⥤ C} [has_colimit F] (t : colimit_cocone F) : colimit F ≅ t.cocone.X := is_colimit.cocone_point_unique_up_to_iso (colimit.is_colimit F) t.is_colimit @[simp, reassoc] lemma colimit.iso_colimit_cocone_ι_hom {F : J ⥤ C} [has_colimit F] (t : colimit_cocone F) (j : J) : colimit.ι F j ≫ (colimit.iso_colimit_cocone t).hom = t.cocone.ι.app j := by { dsimp [colimit.iso_colimit_cocone, is_colimit.cocone_point_unique_up_to_iso], tidy, } @[simp, reassoc] lemma colimit.iso_colimit_cocone_ι_inv {F : J ⥤ C} [has_colimit F] (t : colimit_cocone F) (j : J) : t.cocone.ι.app j ≫ (colimit.iso_colimit_cocone t).inv = colimit.ι F j := by { dsimp [colimit.iso_colimit_cocone, is_colimit.cocone_point_unique_up_to_iso], tidy, } @[ext] lemma colimit.hom_ext {F : J ⥤ C} [has_colimit F] {X : C} {f f' : colimit F ⟶ X} (w : ∀ j, colimit.ι F j ≫ f = colimit.ι F j ≫ f') : f = f' := (colimit.is_colimit F).hom_ext w @[simp] lemma colimit.desc_cocone {F : J ⥤ C} [has_colimit F] : colimit.desc F (colimit.cocone F) = 𝟙 (colimit F) := (colimit.is_colimit _).desc_self /-- The isomorphism (in `Type`) between morphisms from the colimit object to a specified object `W`, and cocones with cone point `W`. -/ def colimit.hom_iso (F : J ⥤ C) [has_colimit F] (W : C) : ulift.{u₁} (colimit F ⟶ W : Type v) ≅ (F.cocones.obj W) := (colimit.is_colimit F).hom_iso W @[simp] lemma colimit.hom_iso_hom (F : J ⥤ C) [has_colimit F] {W : C} (f : ulift (colimit F ⟶ W)) : (colimit.hom_iso F W).hom f = (colimit.cocone F).ι ≫ (const J).map f.down := (colimit.is_colimit F).hom_iso_hom f /-- The isomorphism (in `Type`) between morphisms from the colimit object to a specified object `W`, and an explicit componentwise description of cocones with cone point `W`. -/ def colimit.hom_iso' (F : J ⥤ C) [has_colimit F] (W : C) : ulift.{u₁} ((colimit F ⟶ W) : Type v) ≅ { p : Π j, F.obj j ⟶ W // ∀ {j j'} (f : j ⟶ j'), F.map f ≫ p j' = p j } := (colimit.is_colimit F).hom_iso' W lemma colimit.desc_extend (F : J ⥤ C) [has_colimit F] (c : cocone F) {X : C} (f : c.X ⟶ X) : colimit.desc F (c.extend f) = colimit.desc F c ≫ f := begin ext1, rw [←category.assoc], simp end /-- If `F` has a colimit, so does any naturally isomorphic functor. -/ -- This has the isomorphism pointing in the opposite direction than in `has_limit_of_iso`. -- This is intentional; it seems to help with elaboration. lemma has_colimit_of_iso {F G : J ⥤ C} [has_colimit F] (α : G ≅ F) : has_colimit G := has_colimit.mk { cocone := (cocones.precompose α.hom).obj (colimit.cocone F), is_colimit := { desc := λ s, colimit.desc F ((cocones.precompose α.inv).obj s), fac' := λ s j, begin rw [cocones.precompose_obj_ι, nat_trans.comp_app, colimit.cocone_ι], rw [category.assoc, colimit.ι_desc, ←nat_iso.app_hom, ←iso.eq_inv_comp], refl end, uniq' := λ s m w, begin apply colimit.hom_ext, intro j, rw [colimit.ι_desc, cocones.precompose_obj_ι, nat_trans.comp_app, ←nat_iso.app_inv, iso.eq_inv_comp], simpa using w j end } } /-- If a functor `G` has the same collection of cocones as a functor `F` which has a colimit, then `G` also has a colimit. -/ lemma has_colimit.of_cocones_iso {K : Type u₁} [category.{v₂} K] (F : J ⥤ C) (G : K ⥤ C) (h : F.cocones ≅ G.cocones) [has_colimit F] : has_colimit G := has_colimit.mk ⟨_, is_colimit.of_nat_iso (is_colimit.nat_iso (colimit.is_colimit F) ≪≫ h)⟩ /-- The colimits of `F : J ⥤ C` and `G : J ⥤ C` are isomorphic, if the functors are naturally isomorphic. -/ def has_colimit.iso_of_nat_iso {F G : J ⥤ C} [has_colimit F] [has_colimit G] (w : F ≅ G) : colimit F ≅ colimit G := is_colimit.cocone_points_iso_of_nat_iso (colimit.is_colimit F) (colimit.is_colimit G) w @[simp, reassoc] lemma has_colimit.iso_of_nat_iso_ι_hom {F G : J ⥤ C} [has_colimit F] [has_colimit G] (w : F ≅ G) (j : J) : colimit.ι F j ≫ (has_colimit.iso_of_nat_iso w).hom = w.hom.app j ≫ colimit.ι G j := is_colimit.comp_cocone_points_iso_of_nat_iso_hom _ _ _ _ @[simp, reassoc] lemma has_colimit.iso_of_nat_iso_hom_desc {F G : J ⥤ C} [has_colimit F] [has_colimit G] (t : cocone G) (w : F ≅ G) : (has_colimit.iso_of_nat_iso w).hom ≫ colimit.desc G t = colimit.desc F ((cocones.precompose w.hom).obj _) := is_colimit.cocone_points_iso_of_nat_iso_hom_desc _ _ _ /-- The colimits of `F : J ⥤ C` and `G : K ⥤ C` are isomorphic, if there is an equivalence `e : J ≌ K` making the triangle commute up to natural isomorphism. -/ def has_colimit.iso_of_equivalence {F : J ⥤ C} [has_colimit F] {G : K ⥤ C} [has_colimit G] (e : J ≌ K) (w : e.functor ⋙ G ≅ F) : colimit F ≅ colimit G := is_colimit.cocone_points_iso_of_equivalence (colimit.is_colimit F) (colimit.is_colimit G) e w @[simp] lemma has_colimit.iso_of_equivalence_hom_π {F : J ⥤ C} [has_colimit F] {G : K ⥤ C} [has_colimit G] (e : J ≌ K) (w : e.functor ⋙ G ≅ F) (j : J) : colimit.ι F j ≫ (has_colimit.iso_of_equivalence e w).hom = F.map (e.unit.app j) ≫ w.inv.app _ ≫ colimit.ι G _ := begin simp [has_colimit.iso_of_equivalence, is_colimit.cocone_points_iso_of_equivalence_inv], dsimp, simp, end @[simp] lemma has_colimit.iso_of_equivalence_inv_π {F : J ⥤ C} [has_colimit F] {G : K ⥤ C} [has_colimit G] (e : J ≌ K) (w : e.functor ⋙ G ≅ F) (k : K) : colimit.ι G k ≫ (has_colimit.iso_of_equivalence e w).inv = G.map (e.counit_inv.app k) ≫ w.hom.app (e.inverse.obj k) ≫ colimit.ι F (e.inverse.obj k) := begin simp [has_colimit.iso_of_equivalence, is_colimit.cocone_points_iso_of_equivalence_inv], dsimp, simp, end section pre variables (F) [has_colimit F] (E : K ⥤ J) [has_colimit (E ⋙ F)] /-- The canonical morphism from the colimit of `E ⋙ F` to the colimit of `F`. -/ def colimit.pre : colimit (E ⋙ F) ⟶ colimit F := colimit.desc (E ⋙ F) ((colimit.cocone F).whisker E) @[simp, reassoc] lemma colimit.ι_pre (k : K) : colimit.ι (E ⋙ F) k ≫ colimit.pre F E = colimit.ι F (E.obj k) := by { erw is_colimit.fac, refl, } @[simp, reassoc] lemma colimit.pre_desc (c : cocone F) : colimit.pre F E ≫ colimit.desc F c = colimit.desc (E ⋙ F) (c.whisker E) := by ext; rw [←assoc, colimit.ι_pre]; simp variables {L : Type u₃} [category.{v₃} L] variables (D : L ⥤ K) [has_colimit (D ⋙ E ⋙ F)] @[simp] lemma colimit.pre_pre : colimit.pre (E ⋙ F) D ≫ colimit.pre F E = colimit.pre F (D ⋙ E) := begin ext j, rw [←assoc, colimit.ι_pre, colimit.ι_pre], letI : has_colimit ((D ⋙ E) ⋙ F) := show has_colimit (D ⋙ E ⋙ F), by apply_instance, exact (colimit.ι_pre F (D ⋙ E) j).symm end variables {E F} /--- If we have particular colimit cocones available for `E ⋙ F` and for `F`, we obtain a formula for `colimit.pre F E`. -/ lemma colimit.pre_eq (s : colimit_cocone (E ⋙ F)) (t : colimit_cocone F) : colimit.pre F E = (colimit.iso_colimit_cocone s).hom ≫ s.is_colimit.desc ((t.cocone).whisker E) ≫ (colimit.iso_colimit_cocone t).inv := by tidy end pre section post variables {D : Type u'} [category.{v'} D] variables (F) [has_colimit F] (G : C ⥤ D) [has_colimit (F ⋙ G)] /-- The canonical morphism from `G` applied to the colimit of `F ⋙ G` to `G` applied to the colimit of `F`. -/ def colimit.post : colimit (F ⋙ G) ⟶ G.obj (colimit F) := colimit.desc (F ⋙ G) (G.map_cocone (colimit.cocone F)) @[simp, reassoc] lemma colimit.ι_post (j : J) : colimit.ι (F ⋙ G) j ≫ colimit.post F G = G.map (colimit.ι F j) := by { erw is_colimit.fac, refl, } @[simp] lemma colimit.post_desc (c : cocone F) : colimit.post F G ≫ G.map (colimit.desc F c) = colimit.desc (F ⋙ G) (G.map_cocone c) := by { ext, rw [←assoc, colimit.ι_post, ←G.map_comp, colimit.ι_desc, colimit.ι_desc], refl } @[simp] lemma colimit.post_post {E : Type u''} [category.{v''} E] (H : D ⥤ E) [has_colimit ((F ⋙ G) ⋙ H)] : /- H G (colimit F) ⟶ H (colimit (F ⋙ G)) ⟶ colimit ((F ⋙ G) ⋙ H) equals -/ /- H G (colimit F) ⟶ colimit (F ⋙ (G ⋙ H)) -/ colimit.post (F ⋙ G) H ≫ H.map (colimit.post F G) = colimit.post F (G ⋙ H) := begin ext, rw [←assoc, colimit.ι_post, ←H.map_comp, colimit.ι_post], exact (colimit.ι_post F (G ⋙ H) j).symm end end post lemma colimit.pre_post {D : Type u'} [category.{v'} D] (E : K ⥤ J) (F : J ⥤ C) (G : C ⥤ D) [has_colimit F] [has_colimit (E ⋙ F)] [has_colimit (F ⋙ G)] [H : has_colimit ((E ⋙ F) ⋙ G)] : /- G (colimit F) ⟶ G (colimit (E ⋙ F)) ⟶ colimit ((E ⋙ F) ⋙ G) vs -/ /- G (colimit F) ⟶ colimit F ⋙ G ⟶ colimit (E ⋙ (F ⋙ G)) or -/ colimit.post (E ⋙ F) G ≫ G.map (colimit.pre F E) = (@@colimit.pre _ _ _ (F ⋙ G) _ E H ≫ colimit.post F G : _) := begin ext, rw [←assoc, colimit.ι_post, ←G.map_comp, colimit.ι_pre, ←assoc], letI : has_colimit (E ⋙ F ⋙ G) := show has_colimit ((E ⋙ F) ⋙ G), by apply_instance, erw [colimit.ι_pre (F ⋙ G) E j, colimit.ι_post] end open category_theory.equivalence instance has_colimit_equivalence_comp (e : K ≌ J) [has_colimit F] : has_colimit (e.functor ⋙ F) := has_colimit.mk { cocone := cocone.whisker e.functor (colimit.cocone F), is_colimit := is_colimit.whisker_equivalence (colimit.is_colimit F) e, } /-- If a `E ⋙ F` has a colimit, and `E` is an equivalence, we can construct a colimit of `F`. -/ lemma has_colimit_of_equivalence_comp (e : K ≌ J) [has_colimit (e.functor ⋙ F)] : has_colimit F := begin haveI : has_colimit (e.inverse ⋙ e.functor ⋙ F) := limits.has_colimit_equivalence_comp e.symm, apply has_colimit_of_iso (e.inv_fun_id_assoc F).symm, end section colim_functor variables [has_colimits_of_shape J C] section local attribute [simp] colim_map /-- `colimit F` is functorial in `F`, when `C` has all colimits of shape `J`. -/ @[simps obj] def colim : (J ⥤ C) ⥤ C := { obj := λ F, colimit F, map := λ F G α, colim_map α, map_id' := λ F, by { ext, erw [ι_colim_map, id_comp, comp_id] }, map_comp' := λ F G H α β, by { ext, erw [←assoc, is_colimit.fac, is_colimit.fac, assoc, is_colimit.fac, ←assoc], refl } } end variables {F} {G : J ⥤ C} (α : F ⟶ G) @[simp, reassoc] lemma colimit.ι_map (j : J) : colimit.ι F j ≫ colim.map α = α.app j ≫ colimit.ι G j := by apply is_colimit.fac @[simp] lemma colimit.map_desc (c : cocone G) : colim.map α ≫ colimit.desc G c = colimit.desc F ((cocones.precompose α).obj c) := by ext; rw [←assoc, colimit.ι_map, assoc, colimit.ι_desc, colimit.ι_desc]; refl lemma colimit.pre_map [has_colimits_of_shape K C] (E : K ⥤ J) : colimit.pre F E ≫ colim.map α = colim.map (whisker_left E α) ≫ colimit.pre G E := by ext; rw [←assoc, colimit.ι_pre, colimit.ι_map, ←assoc, colimit.ι_map, assoc, colimit.ι_pre]; refl lemma colimit.pre_map' [has_colimits_of_shape K C] (F : J ⥤ C) {E₁ E₂ : K ⥤ J} (α : E₁ ⟶ E₂) : colimit.pre F E₁ = colim.map (whisker_right α F) ≫ colimit.pre F E₂ := by ext1; simp [← category.assoc] lemma colimit.pre_id (F : J ⥤ C) : colimit.pre F (𝟭 _) = colim.map (functor.left_unitor F).hom := by tidy lemma colimit.map_post {D : Type u'} [category.{v'} D] [has_colimits_of_shape J D] (H : C ⥤ D) : /- H (colimit F) ⟶ H (colimit G) ⟶ colimit (G ⋙ H) vs H (colimit F) ⟶ colimit (F ⋙ H) ⟶ colimit (G ⋙ H) -/ colimit.post F H ≫ H.map (colim.map α) = colim.map (whisker_right α H) ≫ colimit.post G H:= begin ext, rw [←assoc, colimit.ι_post, ←H.map_comp, colimit.ι_map, H.map_comp], rw [←assoc, colimit.ι_map, assoc, colimit.ι_post], refl end /-- The isomorphism between morphisms from the cone point of the colimit cocone for `F` to `W` and cocones over `F` with cone point `W` is natural in `F`. -/ def colim_coyoneda : colim.op ⋙ coyoneda ⋙ (whiskering_right _ _ _).obj ulift_functor.{u₁} ≅ category_theory.cocones J C := nat_iso.of_components (λ F, nat_iso.of_components (colimit.hom_iso (unop F)) (by tidy)) (by tidy) end colim_functor /-- We can transport colimits of shape `J` along an equivalence `J ≌ J'`. -/ lemma has_colimits_of_shape_of_equivalence {J' : Type u₂} [category.{v₂} J'] (e : J ≌ J') [has_colimits_of_shape J C] : has_colimits_of_shape J' C := by { constructor, intro F, apply has_colimit_of_equivalence_comp e, apply_instance } variable (C) /-- `has_colimits_of_size.{v u} C` tries to obtain `has_colimits_of_size.{v u} C` from some other `has_colimits_of_size C`. -/ lemma has_colimits_of_size_shrink [has_colimits_of_size.{(max v₁ v₂) (max u₁ u₂)} C] : has_colimits_of_size.{v₁ u₁} C := ⟨λ J hJ, by exactI has_colimits_of_shape_of_equivalence (ulift_hom_ulift_category.equiv.{v₂ u₂} J).symm⟩ lemma has_smallest_colimits_of_has_colimits [has_colimits C] : has_colimits_of_size.{0 0} C := has_colimits_of_size_shrink.{0 0} C end colimit section opposite /-- If `t : cone F` is a limit cone, then `t.op : cocone F.op` is a colimit cocone. -/ def is_limit.op {t : cone F} (P : is_limit t) : is_colimit t.op := { desc := λ s, (P.lift s.unop).op, fac' := λ s j, congr_arg quiver.hom.op (P.fac s.unop (unop j)), uniq' := λ s m w, begin rw ← P.uniq s.unop m.unop, { refl, }, { dsimp, intro j, rw ← w, refl, } end } /-- If `t : cocone F` is a colimit cocone, then `t.op : cone F.op` is a limit cone. -/ def is_colimit.op {t : cocone F} (P : is_colimit t) : is_limit t.op := { lift := λ s, (P.desc s.unop).op, fac' := λ s j, congr_arg quiver.hom.op (P.fac s.unop (unop j)), uniq' := λ s m w, begin rw ← P.uniq s.unop m.unop, { refl, }, { dsimp, intro j, rw ← w, refl, } end } /-- If `t : cone F.op` is a limit cone, then `t.unop : cocone F` is a colimit cocone. -/ def is_limit.unop {t : cone F.op} (P : is_limit t) : is_colimit t.unop := { desc := λ s, (P.lift s.op).unop, fac' := λ s j, congr_arg quiver.hom.unop (P.fac s.op (op j)), uniq' := λ s m w, begin rw ← P.uniq s.op m.op, { refl, }, { dsimp, intro j, rw ← w, refl, } end } /-- If `t : cocone F.op` is a colimit cocone, then `t.unop : cone F.` is a limit cone. -/ def is_colimit.unop {t : cocone F.op} (P : is_colimit t) : is_limit t.unop := { lift := λ s, (P.desc s.op).unop, fac' := λ s j, congr_arg quiver.hom.unop (P.fac s.op (op j)), uniq' := λ s m w, begin rw ← P.uniq s.op m.op, { refl, }, { dsimp, intro j, rw ← w, refl, } end } /-- `t : cone F` is a limit cone if and only is `t.op : cocone F.op` is a colimit cocone. -/ def is_limit_equiv_is_colimit_op {t : cone F} : is_limit t ≃ is_colimit t.op := equiv_of_subsingleton_of_subsingleton is_limit.op (λ P, P.unop.of_iso_limit (cones.ext (iso.refl _) (by tidy))) /-- `t : cocone F` is a colimit cocone if and only is `t.op : cone F.op` is a limit cone. -/ def is_colimit_equiv_is_limit_op {t : cocone F} : is_colimit t ≃ is_limit t.op := equiv_of_subsingleton_of_subsingleton is_colimit.op (λ P, P.unop.of_iso_colimit (cocones.ext (iso.refl _) (by tidy))) end opposite end category_theory.limits
300e47a1b2f7aa8d29654f91f0c50083984493e8
e39f04f6ff425fe3b3f5e26a8998b817d1dba80f
/data/zmod/quadratic_reciprocity.lean
1fbda99abbc90e53cb7abf482e08eb144166f9d0
[ "Apache-2.0" ]
permissive
kristychoi/mathlib
c504b5e8f84e272ea1d8966693c42de7523bf0ec
257fd84fe98927ff4a5ffe044f68c4e9d235cc75
refs/heads/master
1,586,520,722,896
1,544,030,145,000
1,544,031,933,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
32,276
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 field_theory.finite data.zmod.basic algebra.pi_instances open function finset nat finite_field zmodp namespace zmodp variables {p q : ℕ} (hp : prime p) (hq : prime q) @[simp] lemma card_units_zmodp : fintype.card (units (zmodp p hp)) = p - 1 := by rw [card_units, card_zmodp] theorem fermat_little {p : ℕ} (hp : prime p) {a : zmodp p hp} (ha : a ≠ 0) : a ^ (p - 1) = 1 := by rw [← units.mk0_val ha, ← @units.coe_one (zmodp p hp), ← units.coe_pow, ← units.ext_iff, ← card_units_zmodp hp, pow_card_eq_one] lemma euler_criterion_units {x : units (zmodp p hp)} : (∃ y : units (zmodp p hp), y ^ 2 = x) ↔ x ^ (p / 2) = 1 := hp.eq_two_or_odd.elim (λ h, by subst h; revert x; exact dec_trivial) (λ hp1, let ⟨g, hg⟩ := is_cyclic.exists_generator (units (zmodp p hp)) in let ⟨n, hn⟩ := show x ∈ powers g, from (powers_eq_gpowers g).symm ▸ hg x in ⟨λ ⟨y, hy⟩, by rw [← hy, ← pow_mul, two_mul_odd_div_two hp1, ← card_units_zmodp hp, pow_card_eq_one], λ hx, have 2 * (p / 2) ∣ n * (p / 2), by rw [two_mul_odd_div_two hp1, ← card_units_zmodp hp, ← order_of_eq_card_of_forall_mem_gpowers hg]; exact order_of_dvd_of_pow_eq_one (by rwa [pow_mul, hn]), let ⟨m, hm⟩ := dvd_of_mul_dvd_mul_right (nat.div_pos hp.ge_two dec_trivial) this in ⟨g ^ m, by rwa [← pow_mul, mul_comm, ← hm]⟩⟩) lemma euler_criterion {a : zmodp p hp} (ha : a ≠ 0) : (∃ y : zmodp p hp, y ^ 2 = a) ↔ a ^ (p / 2) = 1 := ⟨λ ⟨y, hy⟩, have hy0 : y ≠ 0, from λ h, by simp [h, _root_.zero_pow (succ_pos 1)] at hy; cc, by simpa using (units.ext_iff.1 $ (euler_criterion_units hp).1 ⟨units.mk0 _ hy0, show _ = units.mk0 _ ha, by rw [units.ext_iff]; simpa⟩), λ h, let ⟨y, hy⟩ := (euler_criterion_units hp).2 (show units.mk0 _ ha ^ (p / 2) = 1, by simpa [units.ext_iff]) in ⟨y, by simpa [units.ext_iff] using hy⟩⟩ lemma pow_div_two_eq_neg_one_or_one {a : zmodp p hp} (ha : a ≠ 0) : a ^ (p / 2) = 1 ∨ a ^ (p / 2) = -1 := hp.eq_two_or_odd.elim (λ h, by revert a ha; subst h; exact dec_trivial) (λ hp1, by rw [← mul_self_eq_one_iff, ← _root_.pow_add, ← two_mul, two_mul_odd_div_two hp1]; exact fermat_little hp ha) @[simp] lemma wilsons_lemma {p : ℕ} (hp : prime p) : (fact (p - 1) : zmodp p hp) = -1 := begin rw [← finset.prod_range_id_eq_fact, ← @units.coe_one (zmodp p hp), ← units.coe_neg, ← @prod_univ_units_id_eq_neg_one (zmodp p hp), ← prod_hom (coe : units (zmodp p hp) → zmodp p hp) units.coe_one units.coe_mul, ← prod_hom (coe : ℕ → zmodp p hp) nat.cast_one nat.cast_mul], exact eq.symm (prod_bij (λ a _, (a : zmodp p hp).1) (λ a ha, mem_erase.2 ⟨λ h, units.coe_ne_zero a $ fin.eq_of_veq h, by rw [mem_range, ← succ_sub hp.pos, succ_sub_one]; exact a.1.2⟩) (λ a _, by simp) (λ _ _ _ _, units.ext_iff.2 ∘ fin.eq_of_veq) (λ b hb, have b ≠ 0 ∧ b < p, by rwa [mem_erase, mem_range, ← succ_sub hp.pos, succ_sub_one] at hb, ⟨units.mk0 _ (show (b : zmodp p hp) ≠ 0, from fin.ne_of_vne $ by rw [zmod.val_cast_nat, ← @nat.cast_zero (zmodp p hp), zmod.val_cast_nat]; simp [mod_eq_of_lt this.2, this.1]), mem_univ _, by simp [val_cast_of_lt hp this.2]⟩)) end @[simp] lemma prod_range_prime_erase_zero {p : ℕ} (hp : prime p) : ((range p).erase 0).prod (λ x, (x : zmodp p hp)) = -1 := by conv in (range p) { rw [← succ_sub_one p, succ_sub hp.pos] }; rw [prod_hom (coe : ℕ → zmodp p hp) nat.cast_one nat.cast_mul, finset.prod_range_id_eq_fact, wilsons_lemma] end zmodp namespace quadratic_reciprocity_aux variables {p q : ℕ} (hp : prime p) (hq : prime q) (hp1 : p % 2 = 1) (hq1 : q % 2 = 1) (hpq : p ≠ q) include hp hq hp1 hq1 hpq lemma filter_range_p_mul_q_div_two_eq : (range ((p * q) / 2).succ).filter (coprime p) = (range (q / 2)).bind (λ x, (erase (range p) 0).image (+ p * x)) ∪ (erase (range (succ (p / 2))) 0).image (+ q / 2 * p) := finset.ext.2 $ λ x, ⟨λ h, have hxp0 : x % p ≠ 0, by rw [ne.def, ← dvd_iff_mod_eq_zero, ← hp.coprime_iff_not_dvd]; exact (mem_filter.1 h).2, mem_union.2 $ or_iff_not_imp_right.2 (λ h₁, mem_bind.2 ⟨x / p, mem_range.2 $ nat.div_lt_of_lt_mul (by_contradiction (λ h₂, let ⟨c, hc⟩ := le_iff_exists_add.1 (le_of_not_gt h₂) in have hcp : c ≤ p / 2, from @nat.le_of_add_le_add_left (p * (q / 2)) _ _ (by rw [← hc, ← odd_mul_odd_div_two hp1 hq1]; exact le_of_lt_succ (mem_range.1 (mem_filter.1 h).1)), h₁ $ mem_image.2 ⟨c, mem_erase.2 ⟨λ h, hxp0 $ by simp [h, hc], mem_range.2 $ lt_succ_of_le $ hcp⟩, by rw hc; simp [mul_comm]⟩)), mem_image.2 ⟨x % p, mem_erase.2 $ by rw [ne.def, ← dvd_iff_mod_eq_zero, ← hp.coprime_iff_not_dvd, mem_range]; exact ⟨(mem_filter.1 h).2, mod_lt _ hp.pos⟩, nat.mod_add_div _ _⟩⟩), λ h, mem_filter.2 $ (mem_union.1 h).elim (λ h, let ⟨m, hm₁, hm₂⟩ := mem_bind.1 h in let ⟨k, hk₁, hk₂⟩ := mem_image.1 hm₂ in ⟨mem_range.2 $ hk₂ ▸ (mul_lt_mul_left (show 0 < 2, from dec_trivial)).1 begin rw [mul_succ, two_mul_odd_div_two (nat.odd_mul_odd hp1 hq1), mul_add], clear _let_match _let_match, exact calc 2 * k + 2 * (p * m) < 2 * p + 2 * (p * m) : add_lt_add_right ((mul_lt_mul_left dec_trivial).2 (by simp at hk₁; tauto)) _ ... = 2 * (p * (m + 1)) : by simp [mul_add, mul_assoc, mul_comm, mul_left_comm] ... ≤ 2 * (p * (q / 2)) : (mul_le_mul_left (show 0 < 2, from dec_trivial)).2 ((mul_le_mul_left hp.pos).2 $ succ_le_of_lt $ mem_range.1 hm₁) ... ≤ _ : by rw [mul_left_comm, two_mul_odd_div_two hq1, nat.mul_sub_left_distrib, ← nat.sub_add_comm (mul_pos hp.pos hq.pos), add_succ, succ_eq_add_one, nat.add_sub_cancel]; exact le_trans (nat.sub_le_self _ _) (nat.le_add_right _ _), end, by rw [prime.coprime_iff_not_dvd hp, ← hk₂, ← nat.dvd_add_iff_left (dvd_mul_right _ _), dvd_iff_mod_eq_zero, mod_eq_of_lt]; clear _let_match _let_match; simp at hk₁; tauto⟩) (λ h, let ⟨m, hm₁, hm₂⟩ := mem_image.1 h in ⟨mem_range.2 $ hm₂ ▸ begin refine (mul_lt_mul_left (show 0 < 2, from dec_trivial)).1 _, rw [mul_succ, two_mul_odd_div_two (nat.odd_mul_odd hp1 hq1), mul_add, ← mul_assoc 2, two_mul_odd_div_two hq1], exact calc 2 * m + (q - 1) * p ≤ 2 * (p / 2) + (q - 1) * p : add_le_add_right ((mul_le_mul_left dec_trivial).2 (le_of_lt_succ (mem_range.1 (by simp * at *)))) _ ... < _ : begin rw [two_mul_odd_div_two hp1, nat.mul_sub_right_distrib, one_mul], rw [← nat.sub_add_comm hp.pos, nat.add_sub_cancel' (le_mul_of_ge_one_left' (nat.zero_le _) hq.pos), mul_comm], exact lt_add_of_pos_right _ dec_trivial end, end, by rw [hp.coprime_iff_not_dvd, dvd_iff_mod_eq_zero, ← hm₂, nat.add_mul_mod_self_right, mod_eq_of_lt (lt_of_lt_of_le _ (nat.div_lt_self hp.pos (show 1 < 2, from dec_trivial)))]; simp at hm₁; clear _let_match; tauto⟩)⟩ lemma prod_filter_range_p_mul_q_div_two_eq : (range (q / 2)).prod (λ n, ((range p).erase 0).prod (+ p * n)) * ((range (p / 2).succ).erase 0).prod (+ (q / 2) * p) = ((range ((p * q) / 2).succ).filter (coprime p)).prod (λ x, x) := calc (range (q / 2)).prod (λ n, ((range p).erase 0).prod (+ p * n)) * ((range (p / 2).succ).erase 0).prod (+ (q / 2) * p) = (range (q / 2)).prod (λ n, (((range p).erase 0).image (+ p * n)).prod (λ x, x)) * (((range (p / 2).succ).erase 0).image (+ (q / 2) * p)).prod (λ x, x) : by simp only [prod_image (λ _ _ _ _ h, add_right_cancel h)]; refl ... = ((range (q / 2)).bind (λ x, (erase (range p) 0).image (+ p * x)) ∪ (erase (range (succ (p / 2))) 0).image (+ q / 2 * p)).prod (λ x, x) : have h₁ : finset.bind (range (q / 2)) (λ x, ((range p).erase 0).image (+ p * x)) ∩ image (+ q / 2 * p) (erase (range (succ (p / 2))) 0) = ∅ := eq_empty_iff_forall_not_mem.2 $ λ x, begin suffices : ∀ a, a ≠ 0 → a ≤ p / 2 → a + q / 2 * p = x → ∀ b, b < q / 2 → ∀ c, c ≠ 0 → c < p → ¬c + p * b = x, { simpa [lt_succ_iff] }, assume a ha0 hap ha b hbq c hc0 hcp hc, rw mul_comm at ha, rw [← ((nat.div_mod_unique hp.pos).2 ⟨hc, hcp⟩).1, ← ((nat.div_mod_unique hp.pos).2 ⟨ha, lt_of_le_of_lt hap (nat.div_lt_self hp.pos dec_trivial)⟩).1] at hbq, exact lt_irrefl _ hbq end, have h₂ : ∀ x, x ∈ range (q / 2) → ∀ y, y ∈ range (q / 2) → x ≠ y → (erase (range p) 0).image (+ p * x) ∩ image (+ p * y) (erase (range p) 0) = ∅ := λ x hx y hy hxy, begin suffices : ∀ z a, a ≠ 0 → a < p → a + p * x = z → ∀ b, b ≠ 0 → b < p → b + p * y ≠ z, { simpa [finset.ext] }, assume z a ha0 hap ha b hb0 hbp hb, have : (a + p * x) / p = (b + p * y) / p, { rw [ha, hb] }, rw [nat.add_mul_div_left _ _ hp.pos, nat.add_mul_div_left _ _ hp.pos, (nat.div_eq_zero_iff hp.pos).2 hap, (nat.div_eq_zero_iff hp.pos).2 hbp] at this, simpa [hxy] end, by rw [prod_union h₁, prod_bind h₂] ... = (((range ((p * q) / 2).succ)).filter (coprime p)).prod (λ x, x) : prod_congr (filter_range_p_mul_q_div_two_eq hp hq hp1 hq1 hpq).symm (λ _ _, rfl) lemma prod_filter_range_p_mul_q_div_two_mod_p_eq : ((((range ((p * q) / 2).succ).filter (coprime p)).prod (λ x, x) : ℕ) : zmodp p hp) = (-1) ^ (q / 2) * ((range (p / 2).succ).erase 0).prod (λ x, x) := begin rw [← prod_filter_range_p_mul_q_div_two_eq hp hq hp1 hq1 hpq, nat.cast_mul, ← prod_hom (coe : ℕ → zmodp p hp) nat.cast_one nat.cast_mul, ← prod_hom (coe : ℕ → zmodp p hp) nat.cast_one nat.cast_mul], conv in ((finset.prod (erase (range p) 0) _ : ℕ) : zmodp p hp) { rw ← prod_hom (coe : ℕ → zmodp p hp) nat.cast_one nat.cast_mul }, simp end lemma prod_filter_range_p_mul_q_not_coprime_eq : (((((range ((p * q) / 2).succ).filter (coprime p)).filter (λ x, ¬ coprime q x)).prod (λ x, x) : ℕ) : zmodp p hp) = q ^ (p / 2) * ((range (p / 2).succ).erase 0).prod (λ x, x) := have hcard : ((range (p / 2).succ).erase 0).card = p / 2 := by rw [card_erase_of_mem (mem_range.2 (succ_pos _)), card_range, pred_succ], begin conv in ((q : zmodp p hp) ^ (p / 2)) { rw ← hcard }, rw [← prod_const, ← prod_mul_distrib, ← prod_hom (coe : ℕ → zmodp p hp) nat.cast_one nat.cast_mul], exact eq.symm (prod_bij (λ a _, a * q) (λ a ha, have ha' : a ≤ p / 2 ∧ a > 0, by simp [nat.pos_iff_ne_zero, lt_succ_iff] at *; tauto, mem_filter.2 ⟨mem_filter.2 ⟨mem_range.2 $ lt_succ_of_le $ (calc a * q ≤ q * (p / 2) : by rw mul_comm; exact mul_le_mul_left _ ha'.1 ... ≤ _ : by rw [mul_comm p, odd_mul_odd_div_two hq1 hp1]; exact nat.le_add_right _ _), by rw [hp.coprime_iff_not_dvd, hp.dvd_mul, not_or_distrib]; refine ⟨λ hpa, not_le_of_gt (show p / 2 < p, from nat.div_lt_self hp.pos dec_trivial) (le_trans (le_of_dvd ha'.2 hpa) ha'.1), by rwa [← hp.coprime_iff_not_dvd, coprime_primes hp hq]⟩⟩, by simp [hq.coprime_iff_not_dvd]⟩) (by simp [mul_comm]) (by simp [nat.mul_right_inj hq.pos]) (λ b hb, have hb' : (b ≤ p * q / 2 ∧ coprime p b) ∧ q ∣ b, by simpa [hq.coprime_iff_not_dvd, lt_succ_iff] using hb, have hb0 : b > 0, from nat.pos_of_ne_zero (λ hb0, by simpa [hb0, hp.coprime_iff_not_dvd] using hb'), ⟨b / q, mem_erase.2 ⟨nat.pos_iff_ne_zero.1 (nat.div_pos (le_of_dvd hb0 hb'.2) hq.pos), mem_range.2 $ lt_succ_of_le $ by rw [mul_comm, odd_mul_odd_div_two hq1 hp1] at hb'; have := @nat.div_le_div_right _ _ hb'.1.1 q; rwa [add_comm, nat.add_mul_div_left _ _ hq.pos, ((nat.div_eq_zero_iff hq.pos).2 (nat.div_lt_self hq.pos (lt_succ_self _))), zero_add] at this⟩, by rw nat.div_mul_cancel hb'.2⟩)) end lemma prod_range_p_mul_q_filter_coprime_mod_p (hq : prime q) (hp1 : p % 2 = 1) (hq1 : q % 2 = 1) (hpq : p ≠ q) : ((((range ((p * q) / 2).succ).filter (coprime (p * q))).prod (λ x, x) : ℕ) : zmodp p hp) = (-1) ^ (q / 2) * q ^ (p / 2) := have hq0 : (q : zmodp p hp) ≠ 0, by rwa [← nat.cast_zero, ne.def, zmodp.eq_iff_modeq_nat, nat.modeq.modeq_zero_iff, ← hp.coprime_iff_not_dvd, coprime_primes hp hq], (domain.mul_right_inj (show (q ^ (p / 2) * ((range (p / 2).succ).erase 0).prod (λ x, x) : zmodp p hp) ≠ 0, from mul_ne_zero (pow_ne_zero _ hq0) (suffices h : ∀ (x : ℕ), ¬x = 0 → x ≤ p / 2 → ¬(x : zmodp p hp) = 0, by simpa [prod_eq_zero_iff, lt_succ_iff], assume x hx0 hxp, by rwa [← @nat.cast_zero (zmodp p hp), zmodp.eq_iff_modeq_nat, nat.modeq, zero_mod, mod_eq_of_lt (lt_of_le_of_lt hxp (nat.div_lt_self hp.pos (lt_succ_self _)))]))).1 $ have h₁ : (range (succ (p * q / 2))).filter (coprime (p * q)) ∩ filter (λ x, ¬coprime q x) (filter (coprime p) (range (succ (p * q / 2)))) = ∅, by have := @coprime.coprime_mul_left p q; simp [finset.ext, *] at * {contextual := tt}, calc ((((range ((p * q) / 2).succ).filter (coprime (p * q))).prod (λ x, x) : ℕ) : zmodp p hp) * (q ^ (p / 2) * ((range (p / 2).succ).erase 0).prod (λ x, x) : zmodp p hp) = (((range (succ (p * q / 2))).filter (coprime (p * q)) ∪ filter (λ x, ¬coprime q x) (filter (coprime p) (range (succ (p * q / 2))))).prod (λ x, x) : ℕ) : by rw [← prod_filter_range_p_mul_q_not_coprime_eq hp hq hp1 hq1 hpq, ← nat.cast_mul, ← prod_union h₁] ... = (((range ((p * q) / 2).succ).filter (coprime p)).prod (λ x, x) : ℕ) : congr_arg coe (prod_congr (by simp [finset.ext, coprime_mul_iff_left]; tauto) (λ _ _, rfl)) ... = _ : by rw [prod_filter_range_p_mul_q_div_two_mod_p_eq hp hq hp1 hq1 hpq]; cases zmodp.pow_div_two_eq_neg_one_or_one hp hq0; simp [h, _root_.pow_succ] lemma card_range_p_mul_q_filter_not_coprime : card (filter (λ x, ¬coprime p x) (range (succ (p * q / 2)))) = (q / 2).succ := calc card (filter (λ x, ¬coprime p x) (range (succ (p * q / 2)))) = card ((range (q / 2).succ).image (* p)) : congr_arg card $ finset.ext.2 $ λ x, begin rw [mem_filter, mem_range, hp.coprime_iff_not_dvd, not_not, mem_image], exact ⟨λ ⟨h, ⟨m, hm⟩⟩, ⟨m, mem_range.2 (lt_of_mul_lt_mul_left (by rw ← hm; exact lt_of_lt_of_le h (by rw [succ_le_iff, mul_succ, odd_mul_odd_div_two hp1 hq1]; exact add_lt_add_left (div_lt_self hp.pos (lt_succ_self 1)) _)) (nat.zero_le p)), hm.symm ▸ mul_comm m p⟩, λ ⟨m, hm₁, hm₂⟩, ⟨lt_succ_of_le (by rw [← hm₂, odd_mul_odd_div_two hp1 hq1]; exact le_trans (by rw mul_comm; exact mul_le_mul_left _ (le_of_lt_succ (mem_range.1 hm₁))) (le_add_right _ _)), by simp [hm₂.symm]⟩⟩ end ... = _ : by rw [card_image_of_injective _ (λ _ _ h, (nat.mul_right_inj hp.pos).1 h), card_range] lemma prod_filter_range_p_mul_q_div_two_eq_prod_product : ((range ((p * q) / 2).succ).filter (coprime (p * q))).prod (λ x, if (x : zmodp q hq).1 ≤ q / 2 then ((x : zmodp p hp), (x : zmodp q hq)) else -((x : zmodp p hp), (x : zmodp q hq))) = (((range p).erase 0).product ((range (q / 2).succ).erase 0)).prod (λ x, ((x.1 : zmodp p hp), (x.2 : zmodp q hq))) := have hpqpnat : (((⟨p * q, mul_pos hp.pos hq.pos⟩ : ℕ+) : ℕ) : ℤ) = (p * q : ℤ), by simp, have hpqpnat' : ((⟨p * q, mul_pos hp.pos hq.pos⟩ : ℕ+) : ℕ) = p * q, by simp, have hpq1 : ((⟨p * q, mul_pos hp.pos hq.pos⟩ : ℕ+) : ℕ) % 2 = 1, from nat.odd_mul_odd hp1 hq1, have hpq1' : p * q > 1, from one_lt_mul hp.pos hq.gt_one, have hhq0 : ∀ a : ℕ, coprime q a → a ≠ 0, from λ a, imp_not_comm.1 $ by simp [hq.coprime_iff_not_dvd] {contextual := tt}, have hpq0 : 0 < p * q / 2, from nat.div_pos (succ_le_of_lt $ one_lt_mul hp.pos hq.gt_one) dec_trivial, have hinj : ∀ a₁ a₂ : ℕ, a₁ ∈ (range (p * q / 2).succ).filter (coprime (p * q)) → a₂ ∈ (range (p * q / 2).succ).filter (coprime (p * q)) → (if (a₁ : zmodp q hq).1 ≤ q / 2 then ((a₁ : zmodp p hp).1, (a₁ : zmodp q hq).1) else ((-a₁ : zmodp p hp).1, (-a₁ : zmodp q hq).1)) = (if (a₂ : zmodp q hq).1 ≤ q / 2 then ((a₂ : zmodp p hp).1, (a₂ : zmodp q hq).1) else ((-a₂ : zmodp p hp).1, (-a₂ : zmodp q hq).1)) → a₁ = a₂, from λ a b ha hb h, have ha' : a ≤ (p * q) / 2 ∧ coprime (p * q) a, by simpa [lt_succ_iff] using ha, have hapq' : a < ((⟨p * q, mul_pos hp.pos hq.pos⟩ : ℕ+) : ℕ) := lt_of_le_of_lt ha'.1 (div_lt_self (mul_pos hp.pos hq.pos) dec_trivial), have hb' : b ≤ (p * q) / 2 ∧ coprime (p * q) b, by simpa [lt_succ_iff, coprime_mul_iff_left] using hb, have hbpq' : b < ((⟨p * q, mul_pos hp.pos hq.pos⟩ : ℕ+) : ℕ) := lt_of_le_of_lt hb'.1 (div_lt_self (mul_pos hp.pos hq.pos) dec_trivial), have val_inj : ∀ {p : ℕ} (hp : prime p) (x y : zmodp p hp), x.val = y.val ↔ x = y, from λ _ _ _ _, ⟨fin.eq_of_veq, fin.veq_of_eq⟩, have hbpq0 : (b : zmod (⟨p * q, mul_pos hp.pos hq.pos⟩)) ≠ 0, by rw [ne.def, zmod.eq_zero_iff_dvd_nat]; exact λ h, not_coprime_of_dvd_of_dvd hpq1' (dvd_refl (p * q)) h hb'.2, have habneg : ¬((a : zmodp p hp) = -b ∧ (a : zmodp q hq) = -b), begin rw [← int.cast_coe_nat a, ← int.cast_coe_nat b, ← int.cast_coe_nat a, ← int.cast_coe_nat b, ← int.cast_neg, ← int.cast_neg, zmodp.eq_iff_modeq_int, zmodp.eq_iff_modeq_int, @int.modeq.modeq_and_modeq_iff_modeq_mul _ _ p q ((coprime_primes hp hq).2 hpq), ← hpqpnat, ← zmod.eq_iff_modeq_int, int.cast_coe_nat, int.cast_neg, int.cast_coe_nat], assume h, rw [← hpqpnat', ← zmod.val_cast_of_lt hbpq', zmod.le_div_two_iff_lt_neg hpq1 hbpq0, ← h, zmod.val_cast_of_lt hapq', ← not_le] at hb', exact hb'.1 ha'.1, end, have habneg' : ¬((-a : zmodp p hp) = b ∧ (-a : zmodp q hq) = b), by rwa [← neg_inj', neg_neg, ← @neg_inj' _ _ (-a : zmodp q hq), neg_neg], suffices (a : zmodp p hp) = b ∧ (a : zmodp q hq) = b, by rw [← mod_eq_of_lt hapq', ← mod_eq_of_lt hbpq']; rwa [zmodp.eq_iff_modeq_nat, zmodp.eq_iff_modeq_nat, nat.modeq.modeq_and_modeq_iff_modeq_mul ((coprime_primes hp hq).2 hpq)] at this, by split_ifs at h; simp * at *, have hmem : ∀ a : ℕ, a ∈ (range (p * q / 2).succ).filter (coprime (p * q)) → (if (a : zmodp q hq).1 ≤ q / 2 then ((a : zmodp p hp).1, (a : zmodp q hq).1) else ((-a : zmodp p hp).1, (-a : zmodp q hq).1)) ∈ ((range p).erase 0).product ((range (succ (q / 2))).erase 0), from λ x, have hxp : ∀ {p : ℕ} (hp : prime p), (x : zmodp p hp).val = 0 ↔ p ∣ x, from λ p hp, by rw [zmodp.val_cast_nat, nat.dvd_iff_mod_eq_zero], have hxpneg : ∀ {p : ℕ} (hp : prime p), (-x : zmodp p hp).val = 0 ↔ p ∣ x, from λ p hp, by rw [← int.cast_coe_nat x, ← int.cast_neg, ← int.coe_nat_inj', zmodp.coe_val_cast_int, int.coe_nat_zero, ← int.dvd_iff_mod_eq_zero, dvd_neg, int.coe_nat_dvd], have hxplt : (x : zmodp p hp).val < p := (x : zmodp p hp).2, have hxpltneg : (-x : zmodp p hp).val < p := (-x : zmodp p hp).2, have hneglt : ¬(x : zmodp q hq).val ≤ q / 2 → (x : zmodp q hq) ≠ 0 → (-x : zmodp q hq).val ≤ q / 2, from λ hx₁ hx0, by rwa [zmodp.le_div_two_iff_lt_neg hq hq1 hx0, not_lt] at hx₁, by split_ifs; simp [zmodp.eq_zero_iff_dvd_nat hq, (x : zmodp p hp).2, coprime_mul_iff_left, lt_succ_iff, h, *, hp.coprime_iff_not_dvd, hq.coprime_iff_not_dvd, (x : zmodp p hp).2, (-x : zmodp p hp).2] {contextual := tt}, prod_bij (λ x _, if (x : zmodp q hq).1 ≤ (q / 2) then ((x : zmodp p hp).val, (x : zmodp q hq).val) else ((-x : zmodp p hp).val, (-x : zmodp q hq).val)) hmem (λ a ha, by split_ifs; simp [*, prod.ext_iff] at *) hinj (surj_on_of_inj_on_of_card_le _ hmem hinj (@nat.le_of_add_le_add_right (q / 2 + (p / 2).succ) _ _ (calc card (finset.product (erase (range p) 0) (erase (range (succ (q / 2))) 0)) + (q / 2 + (p / 2).succ) = (p * q) / 2 + 1 : by rw [card_product, card_erase_of_mem (mem_range.2 hp.pos), card_erase_of_mem (mem_range.2 (succ_pos _)), card_range, card_range, pred_succ, ← add_assoc, ← succ_mul, succ_pred_eq_of_pos hp.pos, odd_mul_odd_div_two hp1 hq1, add_succ] ... = card (range (p * q / 2).succ) : by rw card_range ... = card ((range (p * q / 2).succ).filter (coprime (p * q)) ∪ ((range (p * q / 2).succ).filter (λ x, ¬coprime p x)).erase 0 ∪ (range (p * q / 2).succ).filter (λ x, ¬coprime q x)) : congr_arg card (by simp [finset.ext, coprime_mul_iff_left]; tauto) ... ≤ card ((range (p * q / 2).succ).filter (coprime (p * q))) + card (((range (p * q / 2).succ).filter (λ x, ¬coprime p x)).erase 0) + card ((range (p * q / 2).succ).filter (λ x, ¬coprime q x)) : le_trans (card_union_le _ _) (add_le_add_right (card_union_le _ _) _) ... = _ : by rw [card_erase_of_mem, card_range_p_mul_q_filter_not_coprime hp hq hp1 hq1 hpq, mul_comm p q, card_range_p_mul_q_filter_not_coprime hq hp hq1 hp1 hpq.symm, pred_succ, add_assoc]; simp [range_succ, hp.coprime_iff_not_dvd, hpq0]))) lemma prod_range_div_two_erase_zero : ((range (p / 2).succ).erase 0).prod (λ x, (x : zmodp p hp)) ^ 2 * (-1) ^ (p / 2) = -1 := have hcard : card (erase (range (succ (p / 2))) 0) = p / 2, by rw [card_erase_of_mem (mem_range.2 (succ_pos _)), card_range, pred_succ], have hp2 : p / 2 < p, from div_lt_self hp.pos dec_trivial, have h₁ : (range (p / 2).succ).erase 0 = ((range p).erase 0).filter (λ x, (x : zmodp p hp).val ≤ p / 2) := finset.ext.2 (λ a, ⟨λ h, mem_filter.2 $ by rw [mem_erase, mem_range, lt_succ_iff] at h; exact ⟨mem_erase.2 ⟨h.1, mem_range.2 (lt_of_le_of_lt h.2 hp2)⟩, by rw zmodp.val_cast_of_lt hp (lt_of_le_of_lt h.2 hp2); exact h.2⟩, λ h, mem_erase.2 ⟨by simp at h; tauto, by rw [mem_filter, mem_erase, mem_range] at h; rw [mem_range, lt_succ_iff, ← zmodp.val_cast_of_lt hp h.1.2]; exact h.2⟩⟩), have hmem : ∀ x ∈ (range (p / 2).succ).erase 0, x ≠ 0 ∧ x ≤ p / 2, from λ x hx, by simpa [lt_succ_iff] using hx, have hmemv : ∀ x ∈ (range (p / 2).succ).erase 0, (x : zmodp p hp).val = x, from λ x hx, zmodp.val_cast_of_lt hp (lt_of_le_of_lt (hmem x hx).2 hp2), have hmem0 : ∀ x ∈ (range (p / 2).succ).erase 0, (x : zmodp p hp) ≠ 0, from λ x hx, fin.ne_of_vne $ by simp [hmemv x hx, (hmem x hx).1], have hmem0' : ∀ x ∈ (range (p / 2).succ).erase 0, (-x : zmodp p hp) ≠ 0, from λ x hx, neg_ne_zero.2 (hmem0 x hx), have h₂ : ((range (p / 2).succ).erase 0).prod (λ x : ℕ, (x : zmodp p hp) * -1) = (((range p).erase 0).filter (λ x : ℕ, ¬(x : zmodp p hp).val ≤ p / 2)).prod (λ x, (x : zmodp p hp)) := prod_bij (λ a _, (-a : zmodp p hp).1) (λ a ha, mem_filter.2 ⟨mem_erase.2 ⟨fin.vne_of_ne (hmem0' a ha), mem_range.2 (-a : zmodp p hp).2⟩, by simp [zmodp.le_div_two_iff_lt_neg hp hp1 (hmem0' a ha), hmemv a ha, (hmem a ha).2]; tauto⟩) (by simp) (λ a₁ a₂ ha₁ ha₂ h, by rw [← hmemv a₁ ha₁, ← hmemv a₂ ha₂]; exact fin.veq_of_eq (by rw neg_inj (fin.eq_of_veq h))) (λ b hb, have hb' : (b ≠ 0 ∧ b < p) ∧ (¬(b : zmodp p hp).1 ≤ p / 2), by simpa using hb, have hbv : (b : zmodp p hp).1 = b, from zmodp.val_cast_of_lt hp hb'.1.2, have hb0 : (b : zmodp p hp) ≠ 0, from fin.ne_of_vne $ by simp [hbv, hb'.1.1], ⟨(-b : zmodp p hp).1, mem_erase.2 ⟨fin.vne_of_ne (neg_ne_zero.2 hb0 : _), mem_range.2 $ lt_succ_of_le $ by rw [← not_lt, ← zmodp.le_div_two_iff_lt_neg hp hp1 hb0]; exact hb'.2⟩, by simp [hbv]⟩), calc ((((range (p / 2).succ).erase 0).prod (λ x, (x : zmodp p hp)) ^ 2)) * (-1) ^ (p / 2) = ((range (p / 2).succ).erase 0).prod (λ x, (x : zmodp p hp)) * ((range (p / 2).succ).erase 0).prod (λ x, (x : zmodp p hp) * -1) : by rw prod_mul_distrib; simp [_root_.pow_two, hcard, mul_assoc] ... = (((range p).erase 0).filter (λ x : ℕ, (x : zmodp p hp).val ≤ p / 2)).prod (λ x, (x : zmodp p hp)) * (((range p).erase 0).filter (λ x : ℕ, ¬(x : zmodp p hp).val ≤ p / 2)).prod (λ x, (x : zmodp p hp)) : by rw [h₂, h₁] ... = ((range p).erase 0).prod (λ x, (x : zmodp p hp)) : begin rw ← prod_union, { exact finset.prod_congr (by simp [finset.ext, -not_lt, -not_le]; tauto) (λ _ _, rfl) }, { simp [finset.ext, -not_lt, - not_le]; tauto } end ... = -1 : by simp lemma range_p_product_range_q_div_two_prod : (((range p).erase 0).product ((range (q / 2).succ).erase 0)).prod (λ x, ((x.1 : zmodp p hp), (x.2 : zmodp q hq))) = ((-1) ^ (q / 2), (-1) ^ (p / 2) * (-1) ^ (p / 2 * (q / 2))) := have hcard : card (erase (range (succ (q / 2))) 0) = q / 2, by rw [card_erase_of_mem (mem_range.2 (succ_pos _)), card_range, pred_succ], have finset.prod (erase (range (succ (q / 2))) 0) (λ x : ℕ, (x : zmodp q hq)) ^ 2 = -((-1 : zmodp q hq) ^ (q / 2)), from (domain.mul_right_inj (show (-1 : zmodp q hq) ^ (q / 2) ≠ 0, from pow_ne_zero _ (neg_ne_zero.2 zero_ne_one.symm))).1 $ by rw [prod_range_div_two_erase_zero hq hp hq1 hp1 hpq.symm, ← neg_mul_eq_neg_mul, ← _root_.pow_add, ← two_mul, pow_mul, _root_.pow_two]; simp, have finset.prod (erase (range (succ (q / 2))) 0) (λ x, (x : zmodp q hq)) ^ card (erase (range p) 0) = (- 1) ^ (p / 2) * ((-1) ^ (p / 2 * (q / 2))), by rw [card_erase_of_mem (mem_range.2 hp.pos), card_range, pred_eq_sub_one, ← two_mul_odd_div_two hp1, pow_mul, this, mul_comm (p / 2), pow_mul, ← _root_.mul_pow]; simp, by simp [prod_product, (prod_mk_prod _ _ _).symm, prod_pow, prod_nat_pow, prod_const, *, zmodp.prod_range_prime_erase_zero hp] lemma prod_range_p_mul_q_div_two_ite_eq : ((range ((p * q) / 2).succ).filter (coprime (p * q))).prod (λ x, if (x : zmodp q hq).1 ≤ (q / 2) then ((x : zmodp p hp), (x : zmodp q hq)) else -((x : zmodp p hp), (x : zmodp q hq))) = ((range ((p * q) / 2).succ).filter (coprime (p * q))).prod (λ x, if (x : zmodp q hq).1 ≤ q / 2 then 1 else -1) * ((-1) ^ (q / 2) * q ^ (p / 2), (-1) ^ (p / 2) * p ^ (q / 2)) := calc ((range ((p * q) / 2).succ).filter (coprime (p * q))).prod (λ x, if (x : zmodp q hq).1 ≤ (q / 2) then ((x : zmodp p hp), (x : zmodp q hq)) else -((x : zmodp p hp), (x : zmodp q hq))) = ((range ((p * q) / 2).succ).filter (coprime (p * q))).prod (λ x, (if (x : zmodp q hq).1 ≤ (q / 2) then 1 else -1) * ((x : zmodp p hp), (x : zmodp q hq))) : prod_congr rfl (λ _ _, by split_ifs; simp) ... = _ : by rw [prod_mul_distrib, ← prod_mk_prod, prod_hom (coe : ℕ → zmodp p hp) nat.cast_one nat.cast_mul, prod_range_p_mul_q_filter_coprime_mod_p hp hq hp1 hq1 hpq, prod_hom (coe : ℕ → zmodp q hq) nat.cast_one nat.cast_mul, mul_comm p q, prod_range_p_mul_q_filter_coprime_mod_p hq hp hq1 hp1 hpq.symm] end quadratic_reciprocity_aux open quadratic_reciprocity_aux variables {p q : ℕ} (hp : prime p) (hq : prime q) namespace zmodp def legendre_sym (a p : ℕ) (hp : prime p) : ℤ := if (a : zmodp p hp) = 0 then 0 else if ∃ b : zmodp p hp, b ^ 2 = a then 1 else -1 lemma legendre_sym_eq_pow (a p : ℕ) (hp : prime p) : (legendre_sym a p hp : zmodp p hp) = (a ^ (p / 2)) := if ha : (a : zmodp p hp) = 0 then by simp [*, legendre_sym, _root_.zero_pow (nat.div_pos hp.ge_two (succ_pos 1))] else (prime.eq_two_or_odd hp).elim (λ hp2, begin subst hp2, suffices : ∀ a : zmodp 2 prime_two, (((ite (a = 0) 0 (ite (∃ (b : zmodp 2 hp), b ^ 2 = a) 1 (-1))) : ℤ) : zmodp 2 prime_two) = a ^ (2 / 2), { exact this a }, exact dec_trivial, end) (λ hp1, have _ := euler_criterion hp ha, have (-1 : zmodp p hp) ≠ 1, from (ne_neg_self hp hp1 zero_ne_one.symm).symm, by cases zmodp.pow_div_two_eq_neg_one_or_one hp ha; simp [legendre_sym, *] at *) lemma legendre_sym_eq_one_or_neg_one (a : ℕ) (hp : prime p) (ha : (a : zmodp p hp) ≠ 0) : legendre_sym a p hp = -1 ∨ legendre_sym a p hp = 1 := by unfold legendre_sym; split_ifs; simp * at * theorem quadratic_reciprocity (hp : prime p) (hq : prime q) (hp1 : p % 2 = 1) (hq1 : q % 2 = 1) (hpq : p ≠ q) : legendre_sym p q hq * legendre_sym q p hp = (-1) ^ ((p / 2) * (q / 2)) := have hneg_one_or_one : ((range (p * q / 2).succ).filter (coprime (p * q))).prod (λ (x : ℕ), if (x : zmodp q hq).val ≤ q / 2 then (1 : zmodp p hp × zmodp q hq) else -1) = 1 ∨ ((range (p * q / 2).succ).filter (coprime (p * q))).prod (λ (x : ℕ), if (x : zmodp q hq).val ≤ q / 2 then (1 : zmodp p hp × zmodp q hq) else -1) = -1 := finset.induction_on ((range (p * q / 2).succ).filter (coprime (p * q))) (or.inl rfl) (λ a s h, by simp [prod_insert h]; split_ifs; finish), have h : (((-1) ^ (q / 2), (-1) ^ (p / 2) * (-1) ^ (p / 2 * (q / 2))) : zmodp p hp × zmodp q hq) = ((-1) ^ (q / 2) * q ^ (p / 2), (-1) ^ (p / 2) * p ^ (q / 2)) ∨ (((-1) ^ (q / 2), (-1) ^ (p / 2) * (-1) ^ (p / 2 * (q / 2))) : zmodp p hp × zmodp q hq) = - ((-1) ^ (q / 2) * q ^ (p / 2), (-1) ^ (p / 2) * p ^ (q / 2)) := begin have := prod_filter_range_p_mul_q_div_two_eq_prod_product hp hq hp1 hq1 hpq, rw [prod_range_p_mul_q_div_two_ite_eq hp hq hp1 hq1 hpq, range_p_product_range_q_div_two_prod hp hq hp1 hq1 hpq] at this, cases hneg_one_or_one with h h; simp * at * end, begin have := ne_neg_self hp hp1 one_ne_zero, have := ne_neg_self hq hq1 one_ne_zero, generalize hnp : (-1 : ℤ) ^ (p / 2) = np, have hnpp : (-1 : zmodp q hq) ^ (p / 2) = np, by simp [hnp.symm], generalize hnq : (-1 : ℤ) ^ (q / 2) = nq, have hnqp : (-1 : zmodp p hp) ^ (q / 2) = nq, by simp [hnq.symm], have hnqq : (-1 : zmodp q hq) ^ (q / 2) = nq, by simp [hnq.symm], cases legendre_sym_eq_one_or_neg_one q hp (zmodp.prime_ne_zero hp hq hpq); cases legendre_sym_eq_one_or_neg_one p hq (zmodp.prime_ne_zero hq hp hpq.symm); cases @neg_one_pow_eq_or ℤ _ (p / 2); cases @neg_one_pow_eq_or ℤ _ (q / 2); simp [*, pow_mul, (legendre_sym_eq_pow p q hq).symm, (legendre_sym_eq_pow q p hp).symm, prod.ext_iff] at *; cc end lemma is_square_iff_is_square_of_mod_four_eq_one (hp1 : p % 4 = 1) (hq1 : q % 2 = 1) : (∃ a : zmodp p hp, a ^ 2 = q) ↔ ∃ b : zmodp q hq, b ^ 2 = p := if hpq : p = q then by subst hpq else have h1 : ((p / 2) * (q / 2)) % 2 = 0, from (dvd_iff_mod_eq_zero _ _).1 (dvd_mul_of_dvd_left ((dvd_iff_mod_eq_zero _ _).2 $ by rw [← mod_mul_right_div_self, show 2 * 2 = 4, from rfl, hp1]; refl) _), begin have := quadratic_reciprocity hp hq (odd_of_mod_four_eq_one hp1) hq1 hpq, rw [neg_one_pow_eq_pow_mod_two, h1, legendre_sym, legendre_sym, if_neg (zmodp.prime_ne_zero hp hq hpq), if_neg (zmodp.prime_ne_zero hq hp (ne.symm hpq))] at this, split_ifs at this; simp *; contradiction end lemma is_square_iff_is_not_square_of_mod_four_eq_three (hp3 : p % 4 = 3) (hq3 : q % 4 = 3) (hpq : p ≠ q) : (∃ a : zmodp p hp, a ^ 2 = q) ↔ ¬∃ b : zmodp q hq, b ^ 2 = p := have h1 : ((p / 2) * (q / 2)) % 2 = 1, from nat.odd_mul_odd (by rw [← mod_mul_right_div_self, show 2 * 2 = 4, from rfl, hp3]; refl) (by rw [← mod_mul_right_div_self, show 2 * 2 = 4, from rfl, hq3]; refl), begin have := quadratic_reciprocity hp hq (odd_of_mod_four_eq_three hp3) (odd_of_mod_four_eq_three hq3) hpq, rw [neg_one_pow_eq_pow_mod_two, h1, legendre_sym, legendre_sym, if_neg (zmodp.prime_ne_zero hp hq hpq), if_neg (zmodp.prime_ne_zero hq hp hpq.symm)] at this, split_ifs at this; simp *; contradiction end end zmodp
f4eb67bf9e371cbde55edc29a5516f5449d574ca
ce6917c5bacabee346655160b74a307b4a5ab620
/src/ch3/ex0503.lean
db047c86674881d7212df3713cfa579b2e240ce8
[]
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
132
lean
open classical variable p : Prop example (h : ¬¬p) : p := by_cases (assume h1 : p, h1) (assume h1 : ¬p, absurd h1 h)
8e2e02f5443b0dd9617dab82aa2d181c319007f3
367134ba5a65885e863bdc4507601606690974c1
/src/topology/metric_space/gromov_hausdorff.lean
65e82fc32c67d4b2ef95d50204739496e5e95617
[ "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
55,686
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Sébastien Gouëzel -/ import topology.metric_space.closeds import set_theory.cardinal import topology.metric_space.gromov_hausdorff_realized import topology.metric_space.completion /-! # Gromov-Hausdorff distance This file defines the Gromov-Hausdorff distance on the space of nonempty compact metric spaces up to isometry. We introduce the space of all nonempty compact metric spaces, up to isometry, called `GH_space`, and endow it with a metric space structure. The distance, known as the Gromov-Hausdorff distance, is defined as follows: given two nonempty compact spaces `X` and `Y`, their distance is the minimum Hausdorff distance between all possible isometric embeddings of `X` and `Y` in all metric spaces. To define properly the Gromov-Hausdorff space, we consider the non-empty compact subsets of `ℓ^∞(ℝ)` up to isometry, which is a well-defined type, and define the distance as the infimum of the Hausdorff distance over all embeddings in `ℓ^∞(ℝ)`. We prove that this coincides with the previous description, as all separable metric spaces embed isometrically into `ℓ^∞(ℝ)`, through an embedding called the Kuratowski embedding. To prove that we have a distance, we should show that if spaces can be coupled to be arbitrarily close, then they are isometric. More generally, the Gromov-Hausdorff distance is realized, i.e., there is a coupling for which the Hausdorff distance is exactly the Gromov-Hausdorff distance. This follows from a compactness argument, essentially following from Arzela-Ascoli. ## Main results We prove the most important properties of the Gromov-Hausdorff space: it is a polish space, i.e., it is complete and second countable. We also prove the Gromov compactness criterion. -/ noncomputable theory open_locale classical topological_space universes u v w open classical set function topological_space filter metric quotient open bounded_continuous_function nat Kuratowski_embedding open sum (inl inr) local attribute [instance] metric_space_sum namespace Gromov_Hausdorff section GH_space /- In this section, we define the Gromov-Hausdorff space, denoted `GH_space` as the quotient of nonempty compact subsets of `ℓ^∞(ℝ)` by identifying isometric sets. Using the Kuratwoski embedding, we get a canonical map `to_GH_space` mapping any nonempty compact type to `GH_space`. -/ /-- Equivalence relation identifying two nonempty compact sets which are isometric -/ private definition isometry_rel : nonempty_compacts ℓ_infty_ℝ → nonempty_compacts ℓ_infty_ℝ → Prop := λx y, nonempty (x.val ≃ᵢ y.val) /-- This is indeed an equivalence relation -/ private lemma is_equivalence_isometry_rel : equivalence isometry_rel := ⟨λx, ⟨isometric.refl _⟩, λx y ⟨e⟩, ⟨e.symm⟩, λ x y z ⟨e⟩ ⟨f⟩, ⟨e.trans f⟩⟩ /-- setoid instance identifying two isometric nonempty compact subspaces of ℓ^∞(ℝ) -/ instance isometry_rel.setoid : setoid (nonempty_compacts ℓ_infty_ℝ) := setoid.mk isometry_rel is_equivalence_isometry_rel /-- The Gromov-Hausdorff space -/ definition GH_space : Type := quotient (isometry_rel.setoid) /-- Map any nonempty compact type to `GH_space` -/ definition to_GH_space (α : Type u) [metric_space α] [compact_space α] [nonempty α] : GH_space := ⟦nonempty_compacts.Kuratowski_embedding α⟧ instance : inhabited GH_space := ⟨quot.mk _ ⟨{0}, by simp⟩⟩ /-- A metric space representative of any abstract point in `GH_space` -/ definition GH_space.rep (p : GH_space) : Type := (quot.out p).val lemma eq_to_GH_space_iff {α : Type u} [metric_space α] [compact_space α] [nonempty α] {p : nonempty_compacts ℓ_infty_ℝ} : ⟦p⟧ = to_GH_space α ↔ ∃Ψ : α → ℓ_infty_ℝ, isometry Ψ ∧ range Ψ = p.val := begin simp only [to_GH_space, quotient.eq], split, { assume h, rcases setoid.symm h with ⟨e⟩, have f := (Kuratowski_embedding.isometry α).isometric_on_range.trans e, use λx, f x, split, { apply isometry_subtype_coe.comp f.isometry }, { rw [range_comp, f.range_eq_univ, set.image_univ, subtype.range_coe] } }, { rintros ⟨Ψ, ⟨isomΨ, rangeΨ⟩⟩, have f := ((Kuratowski_embedding.isometry α).isometric_on_range.symm.trans isomΨ.isometric_on_range).symm, have E : (range Ψ ≃ᵢ (nonempty_compacts.Kuratowski_embedding α).val) = (p.val ≃ᵢ range (Kuratowski_embedding α)), by { dunfold nonempty_compacts.Kuratowski_embedding, rw [rangeΨ]; refl }, have g := cast E f, exact ⟨g⟩ } end lemma eq_to_GH_space {p : nonempty_compacts ℓ_infty_ℝ} : ⟦p⟧ = to_GH_space p.val := begin refine eq_to_GH_space_iff.2 ⟨((λx, x) : p.val → ℓ_infty_ℝ), _, subtype.range_coe⟩, apply isometry_subtype_coe end section local attribute [reducible] GH_space.rep instance rep_GH_space_metric_space {p : GH_space} : metric_space (p.rep) := by apply_instance instance rep_GH_space_compact_space {p : GH_space} : compact_space (p.rep) := by apply_instance instance rep_GH_space_nonempty {p : GH_space} : nonempty (p.rep) := by apply_instance end lemma GH_space.to_GH_space_rep (p : GH_space) : to_GH_space (p.rep) = p := begin change to_GH_space (quot.out p).val = p, rw ← eq_to_GH_space, exact quot.out_eq p end /-- Two nonempty compact spaces have the same image in `GH_space` if and only if they are isometric. -/ lemma to_GH_space_eq_to_GH_space_iff_isometric {α : Type u} [metric_space α] [compact_space α] [nonempty α] {β : Type u} [metric_space β] [compact_space β] [nonempty β] : to_GH_space α = to_GH_space β ↔ nonempty (α ≃ᵢ β) := ⟨begin simp only [to_GH_space, quotient.eq], assume h, rcases h with ⟨e⟩, have I : ((nonempty_compacts.Kuratowski_embedding α).val ≃ᵢ (nonempty_compacts.Kuratowski_embedding β).val) = ((range (Kuratowski_embedding α)) ≃ᵢ (range (Kuratowski_embedding β))), by { dunfold nonempty_compacts.Kuratowski_embedding, refl }, have e' := cast I e, have f := (Kuratowski_embedding.isometry α).isometric_on_range, have g := (Kuratowski_embedding.isometry β).isometric_on_range.symm, have h := (f.trans e').trans g, exact ⟨h⟩ end, begin rintros ⟨e⟩, simp only [to_GH_space, quotient.eq], have f := (Kuratowski_embedding.isometry α).isometric_on_range.symm, have g := (Kuratowski_embedding.isometry β).isometric_on_range, have h := (f.trans e).trans g, have I : ((range (Kuratowski_embedding α)) ≃ᵢ (range (Kuratowski_embedding β))) = ((nonempty_compacts.Kuratowski_embedding α).val ≃ᵢ (nonempty_compacts.Kuratowski_embedding β).val), by { dunfold nonempty_compacts.Kuratowski_embedding, refl }, have h' := cast I h, exact ⟨h'⟩ end⟩ /-- Distance on `GH_space`: the distance between two nonempty compact spaces is the infimum Hausdorff distance between isometric copies of the two spaces in a metric space. For the definition, we only consider embeddings in `ℓ^∞(ℝ)`, but we will prove below that it works for all spaces. -/ instance : has_dist (GH_space) := { dist := λx y, Inf $ (λ p : nonempty_compacts ℓ_infty_ℝ × nonempty_compacts ℓ_infty_ℝ, Hausdorff_dist p.1.val p.2.val) '' (set.prod {a | ⟦a⟧ = x} {b | ⟦b⟧ = y}) } /-- The Gromov-Hausdorff distance between two nonempty compact metric spaces, equal by definition to the distance of the equivalence classes of these spaces in the Gromov-Hausdorff space. -/ def GH_dist (α : Type u) (β : Type v) [metric_space α] [nonempty α] [compact_space α] [metric_space β] [nonempty β] [compact_space β] : ℝ := dist (to_GH_space α) (to_GH_space β) lemma dist_GH_dist (p q : GH_space) : dist p q = GH_dist (p.rep) (q.rep) := by rw [GH_dist, p.to_GH_space_rep, q.to_GH_space_rep] /-- The Gromov-Hausdorff distance between two spaces is bounded by the Hausdorff distance of isometric copies of the spaces, in any metric space. -/ theorem GH_dist_le_Hausdorff_dist {α : Type u} [metric_space α] [compact_space α] [nonempty α] {β : Type v} [metric_space β] [compact_space β] [nonempty β] {γ : Type w} [metric_space γ] {Φ : α → γ} {Ψ : β → γ} (ha : isometry Φ) (hb : isometry Ψ) : GH_dist α β ≤ Hausdorff_dist (range Φ) (range Ψ) := begin /- For the proof, we want to embed `γ` in `ℓ^∞(ℝ)`, to say that the Hausdorff distance is realized in `ℓ^∞(ℝ)` and therefore bounded below by the Gromov-Hausdorff-distance. However, `γ` is not separable in general. We restrict to the union of the images of `α` and `β` in `γ`, which is separable and therefore embeddable in `ℓ^∞(ℝ)`. -/ rcases exists_mem_of_nonempty α with ⟨xα, _⟩, let s : set γ := (range Φ) ∪ (range Ψ), let Φ' : α → subtype s := λy, ⟨Φ y, mem_union_left _ (mem_range_self _)⟩, let Ψ' : β → subtype s := λy, ⟨Ψ y, mem_union_right _ (mem_range_self _)⟩, have IΦ' : isometry Φ' := λx y, ha x y, have IΨ' : isometry Ψ' := λx y, hb x y, have : is_compact s, from (compact_range ha.continuous).union (compact_range hb.continuous), letI : metric_space (subtype s) := by apply_instance, haveI : compact_space (subtype s) := ⟨compact_iff_compact_univ.1 ‹is_compact s›⟩, haveI : nonempty (subtype s) := ⟨Φ' xα⟩, have ΦΦ' : Φ = subtype.val ∘ Φ', by { funext, refl }, have ΨΨ' : Ψ = subtype.val ∘ Ψ', by { funext, refl }, have : Hausdorff_dist (range Φ) (range Ψ) = Hausdorff_dist (range Φ') (range Ψ'), { rw [ΦΦ', ΨΨ', range_comp, range_comp], exact Hausdorff_dist_image (isometry_subtype_coe) }, rw this, -- Embed `s` in `ℓ^∞(ℝ)` through its Kuratowski embedding let F := Kuratowski_embedding (subtype s), have : Hausdorff_dist (F '' (range Φ')) (F '' (range Ψ')) = Hausdorff_dist (range Φ') (range Ψ') := Hausdorff_dist_image (Kuratowski_embedding.isometry _), rw ← this, -- Let `A` and `B` be the images of `α` and `β` under this embedding. They are in `ℓ^∞(ℝ)`, and -- their Hausdorff distance is the same as in the original space. let A : nonempty_compacts ℓ_infty_ℝ := ⟨F '' (range Φ'), ⟨(range_nonempty _).image _, (compact_range IΦ'.continuous).image (Kuratowski_embedding.isometry _).continuous⟩⟩, let B : nonempty_compacts ℓ_infty_ℝ := ⟨F '' (range Ψ'), ⟨(range_nonempty _).image _, (compact_range IΨ'.continuous).image (Kuratowski_embedding.isometry _).continuous⟩⟩, have Aα : ⟦A⟧ = to_GH_space α, { rw eq_to_GH_space_iff, exact ⟨λx, F (Φ' x), ⟨(Kuratowski_embedding.isometry _).comp IΦ', by rw range_comp⟩⟩ }, have Bβ : ⟦B⟧ = to_GH_space β, { rw eq_to_GH_space_iff, exact ⟨λx, F (Ψ' x), ⟨(Kuratowski_embedding.isometry _).comp IΨ', by rw range_comp⟩⟩ }, refine cInf_le ⟨0, begin simp [lower_bounds], assume t _ _ _ _ ht, rw ← ht, exact Hausdorff_dist_nonneg end⟩ _, apply (mem_image _ _ _).2, existsi (⟨A, B⟩ : nonempty_compacts ℓ_infty_ℝ × nonempty_compacts ℓ_infty_ℝ), simp [Aα, Bβ] end /-- The optimal coupling constructed above realizes exactly the Gromov-Hausdorff distance, essentially by design. -/ lemma Hausdorff_dist_optimal {α : Type u} [metric_space α] [compact_space α] [nonempty α] {β : Type v} [metric_space β] [compact_space β] [nonempty β] : Hausdorff_dist (range (optimal_GH_injl α β)) (range (optimal_GH_injr α β)) = GH_dist α β := begin inhabit α, inhabit β, /- we only need to check the inequality `≤`, as the other one follows from the previous lemma. As the Gromov-Hausdorff distance is an infimum, we need to check that the Hausdorff distance in the optimal coupling is smaller than the Hausdorff distance of any coupling. First, we check this for couplings which already have small Hausdorff distance: in this case, the induced "distance" on `α ⊕ β` belongs to the candidates family introduced in the definition of the optimal coupling, and the conclusion follows from the optimality of the optimal coupling within this family. -/ have A : ∀p q : nonempty_compacts (ℓ_infty_ℝ), ⟦p⟧ = to_GH_space α → ⟦q⟧ = to_GH_space β → Hausdorff_dist (p.val) (q.val) < diam (univ : set α) + 1 + diam (univ : set β) → Hausdorff_dist (range (optimal_GH_injl α β)) (range (optimal_GH_injr α β)) ≤ Hausdorff_dist (p.val) (q.val), { assume p q hp hq bound, rcases eq_to_GH_space_iff.1 hp with ⟨Φ, ⟨Φisom, Φrange⟩⟩, rcases eq_to_GH_space_iff.1 hq with ⟨Ψ, ⟨Ψisom, Ψrange⟩⟩, have I : diam (range Φ ∪ range Ψ) ≤ 2 * diam (univ : set α) + 1 + 2 * diam (univ : set β), { rcases exists_mem_of_nonempty α with ⟨xα, _⟩, have : ∃y ∈ range Ψ, dist (Φ xα) y < diam (univ : set α) + 1 + diam (univ : set β), { rw Ψrange, have : Φ xα ∈ p.val := Φrange ▸ mem_range_self _, exact exists_dist_lt_of_Hausdorff_dist_lt this bound (Hausdorff_edist_ne_top_of_nonempty_of_bounded p.2.1 q.2.1 p.2.2.bounded q.2.2.bounded) }, rcases this with ⟨y, hy, dy⟩, rcases mem_range.1 hy with ⟨z, hzy⟩, rw ← hzy at dy, have DΦ : diam (range Φ) = diam (univ : set α) := Φisom.diam_range, have DΨ : diam (range Ψ) = diam (univ : set β) := Ψisom.diam_range, calc diam (range Φ ∪ range Ψ) ≤ diam (range Φ) + dist (Φ xα) (Ψ z) + diam (range Ψ) : diam_union (mem_range_self _) (mem_range_self _) ... ≤ diam (univ : set α) + (diam (univ : set α) + 1 + diam (univ : set β)) + diam (univ : set β) : by { rw [DΦ, DΨ], apply add_le_add (add_le_add (le_refl _) (le_of_lt dy)) (le_refl _) } ... = 2 * diam (univ : set α) + 1 + 2 * diam (univ : set β) : by ring }, let f : α ⊕ β → ℓ_infty_ℝ := λx, match x with | inl y := Φ y | inr z := Ψ z end, let F : (α ⊕ β) × (α ⊕ β) → ℝ := λp, dist (f p.1) (f p.2), -- check that the induced "distance" is a candidate have Fgood : F ∈ candidates α β, { simp only [candidates, forall_const, and_true, add_comm, eq_self_iff_true, dist_eq_zero, and_self, set.mem_set_of_eq], repeat {split}, { exact λx y, calc F (inl x, inl y) = dist (Φ x) (Φ y) : rfl ... = dist x y : Φisom.dist_eq x y }, { exact λx y, calc F (inr x, inr y) = dist (Ψ x) (Ψ y) : rfl ... = dist x y : Ψisom.dist_eq x y }, { exact λx y, dist_comm _ _ }, { exact λx y z, dist_triangle _ _ _ }, { exact λx y, calc F (x, y) ≤ diam (range Φ ∪ range Ψ) : begin have A : ∀z : α ⊕ β, f z ∈ range Φ ∪ range Ψ, { assume z, cases z, { apply mem_union_left, apply mem_range_self }, { apply mem_union_right, apply mem_range_self } }, refine dist_le_diam_of_mem _ (A _) (A _), rw [Φrange, Ψrange], exact (p.2.2.union q.2.2).bounded, end ... ≤ 2 * diam (univ : set α) + 1 + 2 * diam (univ : set β) : I } }, let Fb := candidates_b_of_candidates F Fgood, have : Hausdorff_dist (range (optimal_GH_injl α β)) (range (optimal_GH_injr α β)) ≤ HD Fb := Hausdorff_dist_optimal_le_HD _ _ (candidates_b_of_candidates_mem F Fgood), refine le_trans this (le_of_forall_le_of_dense (λr hr, _)), have I1 : ∀x : α, (⨅ y, Fb (inl x, inr y)) ≤ r, { assume x, have : f (inl x) ∈ p.val, by { rw [← Φrange], apply mem_range_self }, rcases exists_dist_lt_of_Hausdorff_dist_lt this hr (Hausdorff_edist_ne_top_of_nonempty_of_bounded p.2.1 q.2.1 p.2.2.bounded q.2.2.bounded) with ⟨z, zq, hz⟩, have : z ∈ range Ψ, by rwa [← Ψrange] at zq, rcases mem_range.1 this with ⟨y, hy⟩, calc (⨅ y, Fb (inl x, inr y)) ≤ Fb (inl x, inr y) : cinfi_le (by simpa using HD_below_aux1 0) y ... = dist (Φ x) (Ψ y) : rfl ... = dist (f (inl x)) z : by rw hy ... ≤ r : le_of_lt hz }, have I2 : ∀y : β, (⨅ x, Fb (inl x, inr y)) ≤ r, { assume y, have : f (inr y) ∈ q.val, by { rw [← Ψrange], apply mem_range_self }, rcases exists_dist_lt_of_Hausdorff_dist_lt' this hr (Hausdorff_edist_ne_top_of_nonempty_of_bounded p.2.1 q.2.1 p.2.2.bounded q.2.2.bounded) with ⟨z, zq, hz⟩, have : z ∈ range Φ, by rwa [← Φrange] at zq, rcases mem_range.1 this with ⟨x, hx⟩, calc (⨅ x, Fb (inl x, inr y)) ≤ Fb (inl x, inr y) : cinfi_le (by simpa using HD_below_aux2 0) x ... = dist (Φ x) (Ψ y) : rfl ... = dist z (f (inr y)) : by rw hx ... ≤ r : le_of_lt hz }, simp [HD, csupr_le I1, csupr_le I2] }, /- Get the same inequality for any coupling. If the coupling is quite good, the desired inequality has been proved above. If it is bad, then the inequality is obvious. -/ have B : ∀p q : nonempty_compacts (ℓ_infty_ℝ), ⟦p⟧ = to_GH_space α → ⟦q⟧ = to_GH_space β → Hausdorff_dist (range (optimal_GH_injl α β)) (range (optimal_GH_injr α β)) ≤ Hausdorff_dist (p.val) (q.val), { assume p q hp hq, by_cases h : Hausdorff_dist (p.val) (q.val) < diam (univ : set α) + 1 + diam (univ : set β), { exact A p q hp hq h }, { calc Hausdorff_dist (range (optimal_GH_injl α β)) (range (optimal_GH_injr α β)) ≤ HD (candidates_b_dist α β) : Hausdorff_dist_optimal_le_HD _ _ (candidates_b_dist_mem_candidates_b) ... ≤ diam (univ : set α) + 1 + diam (univ : set β) : HD_candidates_b_dist_le ... ≤ Hausdorff_dist (p.val) (q.val) : not_lt.1 h } }, refine le_antisymm _ _, { apply le_cInf, { refine (set.nonempty.prod _ _).image _; exact ⟨_, rfl⟩ }, { rintro b ⟨⟨p, q⟩, ⟨hp, hq⟩, rfl⟩, exact B p q hp hq } }, { exact GH_dist_le_Hausdorff_dist (isometry_optimal_GH_injl α β) (isometry_optimal_GH_injr α β) } end /-- The Gromov-Hausdorff distance can also be realized by a coupling in `ℓ^∞(ℝ)`, by embedding the optimal coupling through its Kuratowski embedding. -/ theorem GH_dist_eq_Hausdorff_dist (α : Type u) [metric_space α] [compact_space α] [nonempty α] (β : Type v) [metric_space β] [compact_space β] [nonempty β] : ∃Φ : α → ℓ_infty_ℝ, ∃Ψ : β → ℓ_infty_ℝ, isometry Φ ∧ isometry Ψ ∧ GH_dist α β = Hausdorff_dist (range Φ) (range Ψ) := begin let F := Kuratowski_embedding (optimal_GH_coupling α β), let Φ := F ∘ optimal_GH_injl α β, let Ψ := F ∘ optimal_GH_injr α β, refine ⟨Φ, Ψ, _, _, _⟩, { exact (Kuratowski_embedding.isometry _).comp (isometry_optimal_GH_injl α β) }, { exact (Kuratowski_embedding.isometry _).comp (isometry_optimal_GH_injr α β) }, { rw [← image_univ, ← image_univ, image_comp F, image_univ, image_comp F (optimal_GH_injr α β), image_univ, ← Hausdorff_dist_optimal], exact (Hausdorff_dist_image (Kuratowski_embedding.isometry _)).symm }, end -- without the next two lines, `{ exact hΦ.is_closed }` in the next -- proof is very slow, as the `t2_space` instance is very hard to find local attribute [instance, priority 10] order_topology.t2_space local attribute [instance, priority 10] order_closed_topology.to_t2_space /-- The Gromov-Hausdorff distance defines a genuine distance on the Gromov-Hausdorff space. -/ instance GH_space_metric_space : metric_space GH_space := { dist_self := λx, begin rcases exists_rep x with ⟨y, hy⟩, refine le_antisymm _ _, { apply cInf_le, { exact ⟨0, by { rintro b ⟨⟨u, v⟩, ⟨hu, hv⟩, rfl⟩, exact Hausdorff_dist_nonneg } ⟩}, { simp, existsi [y, y], simpa } }, { apply le_cInf, { exact (nonempty.prod ⟨y, hy⟩ ⟨y, hy⟩).image _ }, { rintro b ⟨⟨u, v⟩, ⟨hu, hv⟩, rfl⟩, exact Hausdorff_dist_nonneg } }, end, dist_comm := λx y, begin have A : (λ (p : nonempty_compacts ℓ_infty_ℝ × nonempty_compacts ℓ_infty_ℝ), Hausdorff_dist ((p.fst).val) ((p.snd).val)) '' (set.prod {a | ⟦a⟧ = x} {b | ⟦b⟧ = y}) = ((λ (p : nonempty_compacts ℓ_infty_ℝ × nonempty_compacts ℓ_infty_ℝ), Hausdorff_dist ((p.fst).val) ((p.snd).val)) ∘ prod.swap) '' (set.prod {a | ⟦a⟧ = x} {b | ⟦b⟧ = y}) := by { congr, funext, simp, rw Hausdorff_dist_comm }, simp only [dist, A, image_comp, image_swap_prod], end, eq_of_dist_eq_zero := λx y hxy, begin /- To show that two spaces at zero distance are isometric, we argue that the distance is realized by some coupling. In this coupling, the two spaces are at zero Hausdorff distance, i.e., they coincide. Therefore, the original spaces are isometric. -/ rcases GH_dist_eq_Hausdorff_dist x.rep y.rep with ⟨Φ, Ψ, Φisom, Ψisom, DΦΨ⟩, rw [← dist_GH_dist, hxy] at DΦΨ, have : range Φ = range Ψ, { have hΦ : is_compact (range Φ) := compact_range Φisom.continuous, have hΨ : is_compact (range Ψ) := compact_range Ψisom.continuous, apply (Hausdorff_dist_zero_iff_eq_of_closed _ _ _).1 (DΦΨ.symm), { exact hΦ.is_closed }, { exact hΨ.is_closed }, { exact Hausdorff_edist_ne_top_of_nonempty_of_bounded (range_nonempty _) (range_nonempty _) hΦ.bounded hΨ.bounded } }, have T : ((range Ψ) ≃ᵢ y.rep) = ((range Φ) ≃ᵢ y.rep), by rw this, have eΨ := cast T Ψisom.isometric_on_range.symm, have e := Φisom.isometric_on_range.trans eΨ, rw [← x.to_GH_space_rep, ← y.to_GH_space_rep, to_GH_space_eq_to_GH_space_iff_isometric], exact ⟨e⟩ end, dist_triangle := λx y z, begin /- To show the triangular inequality between `X`, `Y` and `Z`, realize an optimal coupling between `X` and `Y` in a space `γ1`, and an optimal coupling between `Y` and `Z` in a space `γ2`. Then, glue these metric spaces along `Y`. We get a new space `γ` in which `X` and `Y` are optimally coupled, as well as `Y` and `Z`. Apply the triangle inequality for the Hausdorff distance in `γ` to conclude. -/ let X := x.rep, let Y := y.rep, let Z := z.rep, let γ1 := optimal_GH_coupling X Y, let γ2 := optimal_GH_coupling Y Z, let Φ : Y → γ1 := optimal_GH_injr X Y, have hΦ : isometry Φ := isometry_optimal_GH_injr X Y, let Ψ : Y → γ2 := optimal_GH_injl Y Z, have hΨ : isometry Ψ := isometry_optimal_GH_injl Y Z, let γ := glue_space hΦ hΨ, letI : metric_space γ := metric.metric_space_glue_space hΦ hΨ, have Comm : (to_glue_l hΦ hΨ) ∘ (optimal_GH_injr X Y) = (to_glue_r hΦ hΨ) ∘ (optimal_GH_injl Y Z) := to_glue_commute hΦ hΨ, calc dist x z = dist (to_GH_space X) (to_GH_space Z) : by rw [x.to_GH_space_rep, z.to_GH_space_rep] ... ≤ Hausdorff_dist (range ((to_glue_l hΦ hΨ) ∘ (optimal_GH_injl X Y))) (range ((to_glue_r hΦ hΨ) ∘ (optimal_GH_injr Y Z))) : GH_dist_le_Hausdorff_dist ((to_glue_l_isometry hΦ hΨ).comp (isometry_optimal_GH_injl X Y)) ((to_glue_r_isometry hΦ hΨ).comp (isometry_optimal_GH_injr Y Z)) ... ≤ Hausdorff_dist (range ((to_glue_l hΦ hΨ) ∘ (optimal_GH_injl X Y))) (range ((to_glue_l hΦ hΨ) ∘ (optimal_GH_injr X Y))) + Hausdorff_dist (range ((to_glue_l hΦ hΨ) ∘ (optimal_GH_injr X Y))) (range ((to_glue_r hΦ hΨ) ∘ (optimal_GH_injr Y Z))) : begin refine Hausdorff_dist_triangle (Hausdorff_edist_ne_top_of_nonempty_of_bounded (range_nonempty _) (range_nonempty _) _ _), { exact (compact_range (isometry.continuous ((to_glue_l_isometry hΦ hΨ).comp (isometry_optimal_GH_injl X Y)))).bounded }, { exact (compact_range (isometry.continuous ((to_glue_l_isometry hΦ hΨ).comp (isometry_optimal_GH_injr X Y)))).bounded } end ... = Hausdorff_dist ((to_glue_l hΦ hΨ) '' (range (optimal_GH_injl X Y))) ((to_glue_l hΦ hΨ) '' (range (optimal_GH_injr X Y))) + Hausdorff_dist ((to_glue_r hΦ hΨ) '' (range (optimal_GH_injl Y Z))) ((to_glue_r hΦ hΨ) '' (range (optimal_GH_injr Y Z))) : by simp only [← range_comp, Comm, eq_self_iff_true, add_right_inj] ... = Hausdorff_dist (range (optimal_GH_injl X Y)) (range (optimal_GH_injr X Y)) + Hausdorff_dist (range (optimal_GH_injl Y Z)) (range (optimal_GH_injr Y Z)) : by rw [Hausdorff_dist_image (to_glue_l_isometry hΦ hΨ), Hausdorff_dist_image (to_glue_r_isometry hΦ hΨ)] ... = dist (to_GH_space X) (to_GH_space Y) + dist (to_GH_space Y) (to_GH_space Z) : by rw [Hausdorff_dist_optimal, Hausdorff_dist_optimal, GH_dist, GH_dist] ... = dist x y + dist y z: by rw [x.to_GH_space_rep, y.to_GH_space_rep, z.to_GH_space_rep] end } end GH_space --section end Gromov_Hausdorff /-- In particular, nonempty compacts of a metric space map to `GH_space`. We register this in the topological_space namespace to take advantage of the notation `p.to_GH_space`. -/ definition topological_space.nonempty_compacts.to_GH_space {α : Type u} [metric_space α] (p : nonempty_compacts α) : Gromov_Hausdorff.GH_space := Gromov_Hausdorff.to_GH_space p.val open topological_space namespace Gromov_Hausdorff section nonempty_compacts variables {α : Type u} [metric_space α] theorem GH_dist_le_nonempty_compacts_dist (p q : nonempty_compacts α) : dist p.to_GH_space q.to_GH_space ≤ dist p q := begin have ha : isometry (coe : p.val → α) := isometry_subtype_coe, have hb : isometry (coe : q.val → α) := isometry_subtype_coe, have A : dist p q = Hausdorff_dist p.val q.val := rfl, have I : p.val = range (coe : p.val → α), by simp, have J : q.val = range (coe : q.val → α), by simp, rw [I, J] at A, rw A, exact GH_dist_le_Hausdorff_dist ha hb end lemma to_GH_space_lipschitz : lipschitz_with 1 (nonempty_compacts.to_GH_space : nonempty_compacts α → GH_space) := lipschitz_with.mk_one GH_dist_le_nonempty_compacts_dist lemma to_GH_space_continuous : continuous (nonempty_compacts.to_GH_space : nonempty_compacts α → GH_space) := to_GH_space_lipschitz.continuous end nonempty_compacts section /- In this section, we show that if two metric spaces are isometric up to `ε₂`, then their Gromov-Hausdorff distance is bounded by `ε₂ / 2`. More generally, if there are subsets which are `ε₁`-dense and `ε₃`-dense in two spaces, and isometric up to `ε₂`, then the Gromov-Hausdorff distance between the spaces is bounded by `ε₁ + ε₂/2 + ε₃`. For this, we construct a suitable coupling between the two spaces, by gluing them (approximately) along the two matching subsets. -/ variables {α : Type u} [metric_space α] [compact_space α] [nonempty α] {β : Type v} [metric_space β] [compact_space β] [nonempty β] -- we want to ignore these instances in the following theorem local attribute [instance, priority 10] sum.topological_space sum.uniform_space /-- If there are subsets which are `ε₁`-dense and `ε₃`-dense in two spaces, and isometric up to `ε₂`, then the Gromov-Hausdorff distance between the spaces is bounded by `ε₁ + ε₂/2 + ε₃`. -/ theorem GH_dist_le_of_approx_subsets {s : set α} (Φ : s → β) {ε₁ ε₂ ε₃ : ℝ} (hs : ∀x : α, ∃y ∈ s, dist x y ≤ ε₁) (hs' : ∀x : β, ∃y : s, dist x (Φ y) ≤ ε₃) (H : ∀x y : s, abs (dist x y - dist (Φ x) (Φ y)) ≤ ε₂) : GH_dist α β ≤ ε₁ + ε₂ / 2 + ε₃ := begin refine le_of_forall_pos_le_add (λδ δ0, _), rcases exists_mem_of_nonempty α with ⟨xα, _⟩, rcases hs xα with ⟨xs, hxs, Dxs⟩, have sne : s.nonempty := ⟨xs, hxs⟩, letI : nonempty s := sne.to_subtype, have : 0 ≤ ε₂ := le_trans (abs_nonneg _) (H ⟨xs, hxs⟩ ⟨xs, hxs⟩), have : ∀ p q : s, abs (dist p q - dist (Φ p) (Φ q)) ≤ 2 * (ε₂/2 + δ) := λp q, calc abs (dist p q - dist (Φ p) (Φ q)) ≤ ε₂ : H p q ... ≤ 2 * (ε₂/2 + δ) : by linarith, -- glue `α` and `β` along the almost matching subsets letI : metric_space (α ⊕ β) := glue_metric_approx (λ x:s, (x:α)) (λx, Φ x) (ε₂/2 + δ) (by linarith) this, let Fl := @sum.inl α β, let Fr := @sum.inr α β, have Il : isometry Fl := isometry_emetric_iff_metric.2 (λx y, rfl), have Ir : isometry Fr := isometry_emetric_iff_metric.2 (λx y, rfl), /- The proof goes as follows : the `GH_dist` is bounded by the Hausdorff distance of the images in the coupling, which is bounded (using the triangular inequality) by the sum of the Hausdorff distances of `α` and `s` (in the coupling or, equivalently in the original space), of `s` and `Φ s`, and of `Φ s` and `β` (in the coupling or, equivalently, in the original space). The first term is bounded by `ε₁`, by `ε₁`-density. The third one is bounded by `ε₃`. And the middle one is bounded by `ε₂/2` as in the coupling the points `x` and `Φ x` are at distance `ε₂/2` by construction of the coupling (in fact `ε₂/2 + δ` where `δ` is an arbitrarily small positive constant where positivity is used to ensure that the coupling is really a metric space and not a premetric space on `α ⊕ β`). -/ have : GH_dist α β ≤ Hausdorff_dist (range Fl) (range Fr) := GH_dist_le_Hausdorff_dist Il Ir, have : Hausdorff_dist (range Fl) (range Fr) ≤ Hausdorff_dist (range Fl) (Fl '' s) + Hausdorff_dist (Fl '' s) (range Fr), { have B : bounded (range Fl) := (compact_range Il.continuous).bounded, exact Hausdorff_dist_triangle (Hausdorff_edist_ne_top_of_nonempty_of_bounded (range_nonempty _) (sne.image _) B (B.subset (image_subset_range _ _))) }, have : Hausdorff_dist (Fl '' s) (range Fr) ≤ Hausdorff_dist (Fl '' s) (Fr '' (range Φ)) + Hausdorff_dist (Fr '' (range Φ)) (range Fr), { have B : bounded (range Fr) := (compact_range Ir.continuous).bounded, exact Hausdorff_dist_triangle' (Hausdorff_edist_ne_top_of_nonempty_of_bounded ((range_nonempty _).image _) (range_nonempty _) (bounded.subset (image_subset_range _ _) B) B) }, have : Hausdorff_dist (range Fl) (Fl '' s) ≤ ε₁, { rw [← image_univ, Hausdorff_dist_image Il], have : 0 ≤ ε₁ := le_trans dist_nonneg Dxs, refine Hausdorff_dist_le_of_mem_dist this (λx hx, hs x) (λx hx, ⟨x, mem_univ _, by simpa⟩) }, have : Hausdorff_dist (Fl '' s) (Fr '' (range Φ)) ≤ ε₂/2 + δ, { refine Hausdorff_dist_le_of_mem_dist (by linarith) _ _, { assume x' hx', rcases (set.mem_image _ _ _).1 hx' with ⟨x, ⟨x_in_s, xx'⟩⟩, rw ← xx', use [Fr (Φ ⟨x, x_in_s⟩), mem_image_of_mem Fr (mem_range_self _)], exact le_of_eq (glue_dist_glued_points (λ x:s, (x:α)) Φ (ε₂/2 + δ) ⟨x, x_in_s⟩) }, { assume x' hx', rcases (set.mem_image _ _ _).1 hx' with ⟨y, ⟨y_in_s', yx'⟩⟩, rcases mem_range.1 y_in_s' with ⟨x, xy⟩, use [Fl x, mem_image_of_mem _ x.2], rw [← yx', ← xy, dist_comm], exact le_of_eq (glue_dist_glued_points (@subtype.val α s) Φ (ε₂/2 + δ) x) } }, have : Hausdorff_dist (Fr '' (range Φ)) (range Fr) ≤ ε₃, { rw [← @image_univ _ _ Fr, Hausdorff_dist_image Ir], rcases exists_mem_of_nonempty β with ⟨xβ, _⟩, rcases hs' xβ with ⟨xs', Dxs'⟩, have : 0 ≤ ε₃ := le_trans dist_nonneg Dxs', refine Hausdorff_dist_le_of_mem_dist this (λx hx, ⟨x, mem_univ _, by simpa⟩) (λx _, _), rcases hs' x with ⟨y, Dy⟩, exact ⟨Φ y, mem_range_self _, Dy⟩ }, linarith end end --section /-- The Gromov-Hausdorff space is second countable. -/ instance second_countable : second_countable_topology GH_space := begin refine second_countable_of_countable_discretization (λδ δpos, _), let ε := (2/5) * δ, have εpos : 0 < ε := mul_pos (by norm_num) δpos, have : ∀p:GH_space, ∃s : set (p.rep), finite s ∧ (univ ⊆ (⋃x∈s, ball x ε)) := λp, by simpa using finite_cover_balls_of_compact (@compact_univ p.rep _ _) εpos, -- for each `p`, `s p` is a finite `ε`-dense subset of `p` (or rather the metric space -- `p.rep` representing `p`) choose s hs using this, have : ∀p:GH_space, ∀t:set (p.rep), finite t → ∃n:ℕ, ∃e:equiv t (fin n), true, { assume p t ht, letI : fintype t := finite.fintype ht, rcases fintype.exists_equiv_fin t with ⟨n, hn⟩, rcases hn with ⟨e⟩, exact ⟨n, e, trivial⟩ }, choose N e hne using this, -- cardinality of the nice finite subset `s p` of `p.rep`, called `N p` let N := λp:GH_space, N p (s p) (hs p).1, -- equiv from `s p`, a nice finite subset of `p.rep`, to `fin (N p)`, called `E p` let E := λp:GH_space, e p (s p) (hs p).1, -- A function `F` associating to `p : GH_space` the data of all distances between points -- in the `ε`-dense set `s p`. let F : GH_space → Σn:ℕ, (fin n → fin n → ℤ) := λp, ⟨N p, λa b, floor (ε⁻¹ * dist ((E p).symm a) ((E p).symm b))⟩, refine ⟨_, by apply_instance, F, λp q hpq, _⟩, /- As the target space of F is countable, it suffices to show that two points `p` and `q` with `F p = F q` are at distance `≤ δ`. For this, we construct a map `Φ` from `s p ⊆ p.rep` (representing `p`) to `q.rep` (representing `q`) which is almost an isometry on `s p`, and with image `s q`. For this, we compose the identification of `s p` with `fin (N p)` and the inverse of the identification of `s q` with `fin (N q)`. Together with the fact that `N p = N q`, this constructs `Ψ` between `s p` and `s q`, and then composing with the canonical inclusion we get `Φ`. -/ have Npq : N p = N q := (sigma.mk.inj_iff.1 hpq).1, let Ψ : s p → s q := λx, (E q).symm (fin.cast Npq ((E p) x)), let Φ : s p → q.rep := λx, Ψ x, -- Use the almost isometry `Φ` to show that `p.rep` and `q.rep` -- are within controlled Gromov-Hausdorff distance. have main : GH_dist p.rep q.rep ≤ ε + ε/2 + ε, { refine GH_dist_le_of_approx_subsets Φ _ _ _, show ∀x : p.rep, ∃ (y : p.rep) (H : y ∈ s p), dist x y ≤ ε, { -- by construction, `s p` is `ε`-dense assume x, have : x ∈ ⋃y∈(s p), ball y ε := (hs p).2 (mem_univ _), rcases mem_bUnion_iff.1 this with ⟨y, ys, hy⟩, exact ⟨y, ys, le_of_lt hy⟩ }, show ∀x : q.rep, ∃ (z : s p), dist x (Φ z) ≤ ε, { -- by construction, `s q` is `ε`-dense, and it is the range of `Φ` assume x, have : x ∈ ⋃y∈(s q), ball y ε := (hs q).2 (mem_univ _), rcases mem_bUnion_iff.1 this with ⟨y, ys, hy⟩, let i : ℕ := E q ⟨y, ys⟩, let hi := ((E q) ⟨y, ys⟩).is_lt, have ihi_eq : (⟨i, hi⟩ : fin (N q)) = (E q) ⟨y, ys⟩, by rw [fin.ext_iff, fin.coe_mk], have hiq : i < N q := hi, have hip : i < N p, { rwa Npq.symm at hiq }, let z := (E p).symm ⟨i, hip⟩, use z, have C1 : (E p) z = ⟨i, hip⟩ := (E p).apply_symm_apply ⟨i, hip⟩, have C2 : fin.cast Npq ⟨i, hip⟩ = ⟨i, hi⟩ := rfl, have C3 : (E q).symm ⟨i, hi⟩ = ⟨y, ys⟩, by { rw ihi_eq, exact (E q).symm_apply_apply ⟨y, ys⟩ }, have : Φ z = y := by { simp only [Φ, Ψ], rw [C1, C2, C3], refl }, rw this, exact le_of_lt hy }, show ∀x y : s p, abs (dist x y - dist (Φ x) (Φ y)) ≤ ε, { /- the distance between `x` and `y` is encoded in `F p`, and the distance between `Φ x` and `Φ y` (two points of `s q`) is encoded in `F q`, all this up to `ε`. As `F p = F q`, the distances are almost equal. -/ assume x y, have : dist (Φ x) (Φ y) = dist (Ψ x) (Ψ y) := rfl, rw this, -- introduce `i`, that codes both `x` and `Φ x` in `fin (N p) = fin (N q)` let i : ℕ := E p x, have hip : i < N p := ((E p) x).2, have hiq : i < N q, by rwa Npq at hip, have i' : i = ((E q) (Ψ x)), by { simp [Ψ] }, -- introduce `j`, that codes both `y` and `Φ y` in `fin (N p) = fin (N q)` let j : ℕ := E p y, have hjp : j < N p := ((E p) y).2, have hjq : j < N q, by rwa Npq at hjp, have j' : j = ((E q) (Ψ y)).1, by { simp [Ψ] }, -- Express `dist x y` in terms of `F p` have : (F p).2 ((E p) x) ((E p) y) = floor (ε⁻¹ * dist x y), by simp only [F, (E p).symm_apply_apply], have Ap : (F p).2 ⟨i, hip⟩ ⟨j, hjp⟩ = floor (ε⁻¹ * dist x y), by { rw ← this, congr; apply (fin.ext_iff _ _).2; refl }, -- Express `dist (Φ x) (Φ y)` in terms of `F q` have : (F q).2 ((E q) (Ψ x)) ((E q) (Ψ y)) = floor (ε⁻¹ * dist (Ψ x) (Ψ y)), by simp only [F, (E q).symm_apply_apply], have Aq : (F q).2 ⟨i, hiq⟩ ⟨j, hjq⟩ = floor (ε⁻¹ * dist (Ψ x) (Ψ y)), by { rw ← this, congr; apply (fin.ext_iff _ _).2; [exact i', exact j'] }, -- use the equality between `F p` and `F q` to deduce that the distances have equal -- integer parts have : (F p).2 ⟨i, hip⟩ ⟨j, hjp⟩ = (F q).2 ⟨i, hiq⟩ ⟨j, hjq⟩, { -- we want to `subst hpq` where `hpq : F p = F q`, except that `subst` only works -- with a constant, so replace `F q` (and everything that depends on it) by a constant `f` -- then `subst` revert hiq hjq, change N q with (F q).1, generalize_hyp : F q = f at hpq ⊢, subst hpq, intros, refl }, rw [Ap, Aq] at this, -- deduce that the distances coincide up to `ε`, by a straightforward computation -- that should be automated have I := calc abs (ε⁻¹) * abs (dist x y - dist (Ψ x) (Ψ y)) = abs (ε⁻¹ * (dist x y - dist (Ψ x) (Ψ y))) : (abs_mul _ _).symm ... = abs ((ε⁻¹ * dist x y) - (ε⁻¹ * dist (Ψ x) (Ψ y))) : by { congr, ring } ... ≤ 1 : le_of_lt (abs_sub_lt_one_of_floor_eq_floor this), calc abs (dist x y - dist (Ψ x) (Ψ y)) = (ε * ε⁻¹) * abs (dist x y - dist (Ψ x) (Ψ y)) : by rw [mul_inv_cancel (ne_of_gt εpos), one_mul] ... = ε * (abs (ε⁻¹) * abs (dist x y - dist (Ψ x) (Ψ y))) : by rw [abs_of_nonneg (le_of_lt (inv_pos.2 εpos)), mul_assoc] ... ≤ ε * 1 : mul_le_mul_of_nonneg_left I (le_of_lt εpos) ... = ε : mul_one _ } }, calc dist p q = GH_dist (p.rep) (q.rep) : dist_GH_dist p q ... ≤ ε + ε/2 + ε : main ... = δ : by { simp [ε], ring } end /-- Compactness criterion: a closed set of compact metric spaces is compact if the spaces have a uniformly bounded diameter, and for all `ε` the number of balls of radius `ε` required to cover the spaces is uniformly bounded. This is an equivalence, but we only prove the interesting direction that these conditions imply compactness. -/ lemma totally_bounded {t : set GH_space} {C : ℝ} {u : ℕ → ℝ} {K : ℕ → ℕ} (ulim : tendsto u at_top (𝓝 0)) (hdiam : ∀p ∈ t, diam (univ : set (GH_space.rep p)) ≤ C) (hcov : ∀p ∈ t, ∀n:ℕ, ∃s : set (GH_space.rep p), cardinal.mk s ≤ K n ∧ univ ⊆ ⋃x∈s, ball x (u n)) : totally_bounded t := begin /- Let `δ>0`, and `ε = δ/5`. For each `p`, we construct a finite subset `s p` of `p`, which is `ε`-dense and has cardinality at most `K n`. Encoding the mutual distances of points in `s p`, up to `ε`, we will get a map `F` associating to `p` finitely many data, and making it possible to reconstruct `p` up to `ε`. This is enough to prove total boundedness. -/ refine metric.totally_bounded_of_finite_discretization (λδ δpos, _), let ε := (1/5) * δ, have εpos : 0 < ε := mul_pos (by norm_num) δpos, -- choose `n` for which `u n < ε` rcases metric.tendsto_at_top.1 ulim ε εpos with ⟨n, hn⟩, have u_le_ε : u n ≤ ε, { have := hn n (le_refl _), simp only [real.dist_eq, add_zero, sub_eq_add_neg, neg_zero] at this, exact le_of_lt (lt_of_le_of_lt (le_abs_self _) this) }, -- construct a finite subset `s p` of `p` which is `ε`-dense and has cardinal `≤ K n` have : ∀p:GH_space, ∃s : set (p.rep), ∃N ≤ K n, ∃E : equiv s (fin N), p ∈ t → univ ⊆ ⋃x∈s, ball x (u n), { assume p, by_cases hp : p ∉ t, { have : nonempty (equiv (∅ : set (p.rep)) (fin 0)), { rw ← fintype.card_eq, simp }, use [∅, 0, bot_le, choice (this)] }, { rcases hcov _ (set.not_not_mem.1 hp) n with ⟨s, ⟨scard, scover⟩⟩, rcases cardinal.lt_omega.1 (lt_of_le_of_lt scard (cardinal.nat_lt_omega _)) with ⟨N, hN⟩, rw [hN, cardinal.nat_cast_le] at scard, have : cardinal.mk s = cardinal.mk (fin N), by rw [hN, cardinal.mk_fin], cases quotient.exact this with E, use [s, N, scard, E], simp [hp, scover] } }, choose s N hN E hs using this, -- Define a function `F` taking values in a finite type and associating to `p` enough data -- to reconstruct it up to `ε`, namely the (discretized) distances between elements of `s p`. let M := (floor (ε⁻¹ * max C 0)).to_nat, let F : GH_space → (Σk:fin ((K n).succ), (fin k → fin k → fin (M.succ))) := λp, ⟨⟨N p, lt_of_le_of_lt (hN p) (nat.lt_succ_self _)⟩, λa b, ⟨min M (floor (ε⁻¹ * dist ((E p).symm a) ((E p).symm b))).to_nat, lt_of_le_of_lt ( min_le_left _ _) (nat.lt_succ_self _) ⟩ ⟩, refine ⟨_, by apply_instance, (λp, F p), _⟩, -- It remains to show that if `F p = F q`, then `p` and `q` are `ε`-close rintros ⟨p, pt⟩ ⟨q, qt⟩ hpq, have Npq : N p = N q := (fin.ext_iff _ _).1 (sigma.mk.inj_iff.1 hpq).1, let Ψ : s p → s q := λx, (E q).symm (fin.cast Npq ((E p) x)), let Φ : s p → q.rep := λx, Ψ x, have main : GH_dist (p.rep) (q.rep) ≤ ε + ε/2 + ε, { -- to prove the main inequality, argue that `s p` is `ε`-dense in `p`, and `s q` is `ε`-dense -- in `q`, and `s p` and `s q` are almost isometric. Then closeness follows -- from `GH_dist_le_of_approx_subsets` refine GH_dist_le_of_approx_subsets Φ _ _ _, show ∀x : p.rep, ∃ (y : p.rep) (H : y ∈ s p), dist x y ≤ ε, { -- by construction, `s p` is `ε`-dense assume x, have : x ∈ ⋃y∈(s p), ball y (u n) := (hs p pt) (mem_univ _), rcases mem_bUnion_iff.1 this with ⟨y, ys, hy⟩, exact ⟨y, ys, le_trans (le_of_lt hy) u_le_ε⟩ }, show ∀x : q.rep, ∃ (z : s p), dist x (Φ z) ≤ ε, { -- by construction, `s q` is `ε`-dense, and it is the range of `Φ` assume x, have : x ∈ ⋃y∈(s q), ball y (u n) := (hs q qt) (mem_univ _), rcases mem_bUnion_iff.1 this with ⟨y, ys, hy⟩, let i : ℕ := E q ⟨y, ys⟩, let hi := ((E q) ⟨y, ys⟩).2, have ihi_eq : (⟨i, hi⟩ : fin (N q)) = (E q) ⟨y, ys⟩, by rw [fin.ext_iff, fin.coe_mk], have hiq : i < N q := hi, have hip : i < N p, { rwa Npq.symm at hiq }, let z := (E p).symm ⟨i, hip⟩, use z, have C1 : (E p) z = ⟨i, hip⟩ := (E p).apply_symm_apply ⟨i, hip⟩, have C2 : fin.cast Npq ⟨i, hip⟩ = ⟨i, hi⟩ := rfl, have C3 : (E q).symm ⟨i, hi⟩ = ⟨y, ys⟩, by { rw ihi_eq, exact (E q).symm_apply_apply ⟨y, ys⟩ }, have : Φ z = y := by { simp only [Φ, Ψ], rw [C1, C2, C3], refl }, rw this, exact le_trans (le_of_lt hy) u_le_ε }, show ∀x y : s p, abs (dist x y - dist (Φ x) (Φ y)) ≤ ε, { /- the distance between `x` and `y` is encoded in `F p`, and the distance between `Φ x` and `Φ y` (two points of `s q`) is encoded in `F q`, all this up to `ε`. As `F p = F q`, the distances are almost equal. -/ assume x y, have : dist (Φ x) (Φ y) = dist (Ψ x) (Ψ y) := rfl, rw this, -- introduce `i`, that codes both `x` and `Φ x` in `fin (N p) = fin (N q)` let i : ℕ := E p x, have hip : i < N p := ((E p) x).2, have hiq : i < N q, by rwa Npq at hip, have i' : i = ((E q) (Ψ x)), by { simp [Ψ] }, -- introduce `j`, that codes both `y` and `Φ y` in `fin (N p) = fin (N q)` let j : ℕ := E p y, have hjp : j < N p := ((E p) y).2, have hjq : j < N q, by rwa Npq at hjp, have j' : j = ((E q) (Ψ y)), by { simp [Ψ] }, -- Express `dist x y` in terms of `F p` have Ap : ((F p).2 ⟨i, hip⟩ ⟨j, hjp⟩).1 = (floor (ε⁻¹ * dist x y)).to_nat := calc ((F p).2 ⟨i, hip⟩ ⟨j, hjp⟩).1 = ((F p).2 ((E p) x) ((E p) y)).1 : by { congr; apply (fin.ext_iff _ _).2; refl } ... = min M (floor (ε⁻¹ * dist x y)).to_nat : by simp only [F, (E p).symm_apply_apply] ... = (floor (ε⁻¹ * dist x y)).to_nat : begin refine min_eq_right (int.to_nat_le_to_nat (floor_mono _)), refine mul_le_mul_of_nonneg_left (le_trans _ (le_max_left _ _)) ((inv_pos.2 εpos).le), change dist (x : p.rep) y ≤ C, refine le_trans (dist_le_diam_of_mem compact_univ.bounded (mem_univ _) (mem_univ _)) _, exact hdiam p pt end, -- Express `dist (Φ x) (Φ y)` in terms of `F q` have Aq : ((F q).2 ⟨i, hiq⟩ ⟨j, hjq⟩).1 = (floor (ε⁻¹ * dist (Ψ x) (Ψ y))).to_nat := calc ((F q).2 ⟨i, hiq⟩ ⟨j, hjq⟩).1 = ((F q).2 ((E q) (Ψ x)) ((E q) (Ψ y))).1 : by { congr; apply (fin.ext_iff _ _).2; [exact i', exact j'] } ... = min M (floor (ε⁻¹ * dist (Ψ x) (Ψ y))).to_nat : by simp only [F, (E q).symm_apply_apply] ... = (floor (ε⁻¹ * dist (Ψ x) (Ψ y))).to_nat : begin refine min_eq_right (int.to_nat_le_to_nat (floor_mono _)), refine mul_le_mul_of_nonneg_left (le_trans _ (le_max_left _ _)) ((inv_pos.2 εpos).le), change dist (Ψ x : q.rep) (Ψ y) ≤ C, refine le_trans (dist_le_diam_of_mem compact_univ.bounded (mem_univ _) (mem_univ _)) _, exact hdiam q qt end, -- use the equality between `F p` and `F q` to deduce that the distances have equal -- integer parts have : ((F p).2 ⟨i, hip⟩ ⟨j, hjp⟩).1 = ((F q).2 ⟨i, hiq⟩ ⟨j, hjq⟩).1, { -- we want to `subst hpq` where `hpq : F p = F q`, except that `subst` only works -- with a constant, so replace `F q` (and everything that depends on it) by a constant `f` -- then `subst` revert hiq hjq, change N q with (F q).1, generalize_hyp : F q = f at hpq ⊢, subst hpq, intros, refl }, have : floor (ε⁻¹ * dist x y) = floor (ε⁻¹ * dist (Ψ x) (Ψ y)), { rw [Ap, Aq] at this, have D : 0 ≤ floor (ε⁻¹ * dist x y) := floor_nonneg.2 (mul_nonneg (le_of_lt (inv_pos.2 εpos)) dist_nonneg), have D' : floor (ε⁻¹ * dist (Ψ x) (Ψ y)) ≥ 0 := floor_nonneg.2 (mul_nonneg (le_of_lt (inv_pos.2 εpos)) dist_nonneg), rw [← int.to_nat_of_nonneg D, ← int.to_nat_of_nonneg D', this] }, -- deduce that the distances coincide up to `ε`, by a straightforward computation -- that should be automated have I := calc abs (ε⁻¹) * abs (dist x y - dist (Ψ x) (Ψ y)) = abs (ε⁻¹ * (dist x y - dist (Ψ x) (Ψ y))) : (abs_mul _ _).symm ... = abs ((ε⁻¹ * dist x y) - (ε⁻¹ * dist (Ψ x) (Ψ y))) : by { congr, ring } ... ≤ 1 : le_of_lt (abs_sub_lt_one_of_floor_eq_floor this), calc abs (dist x y - dist (Ψ x) (Ψ y)) = (ε * ε⁻¹) * abs (dist x y - dist (Ψ x) (Ψ y)) : by rw [mul_inv_cancel (ne_of_gt εpos), one_mul] ... = ε * (abs (ε⁻¹) * abs (dist x y - dist (Ψ x) (Ψ y))) : by rw [abs_of_nonneg (le_of_lt (inv_pos.2 εpos)), mul_assoc] ... ≤ ε * 1 : mul_le_mul_of_nonneg_left I (le_of_lt εpos) ... = ε : mul_one _ } }, calc dist p q = GH_dist (p.rep) (q.rep) : dist_GH_dist p q ... ≤ ε + ε/2 + ε : main ... = δ/2 : by { simp [ε], ring } ... < δ : half_lt_self δpos end section complete /- We will show that a sequence `u n` of compact metric spaces satisfying `dist (u n) (u (n+1)) < 1/2^n` converges, which implies completeness of the Gromov-Hausdorff space. We need to exhibit the limiting compact metric space. For this, start from a sequence `X n` of representatives of `u n`, and glue in an optimal way `X n` to `X (n+1)` for all `n`, in a common metric space. Formally, this is done as follows. Start from `Y 0 = X 0`. Then, glue `X 0` to `X 1` in an optimal way, yielding a space `Y 1` (with an embedding of `X 1`). Then, consider an optimal gluing of `X 1` and `X 2`, and glue it to `Y 1` along their common subspace `X 1`. This gives a new space `Y 2`, with an embedding of `X 2`. Go on, to obtain a sequence of spaces `Y n`. Let `Z0` be the inductive limit of the `Y n`, and finally let `Z` be the completion of `Z0`. The images `X2 n` of `X n` in `Z` are at Hausdorff distance `< 1/2^n` by construction, hence they form a Cauchy sequence for the Hausdorff distance. By completeness (of `Z`, and therefore of its set of nonempty compact subsets), they converge to a limit `L`. This is the nonempty compact metric space we are looking for. -/ variables (X : ℕ → Type) [∀n, metric_space (X n)] [∀n, compact_space (X n)] [∀n, nonempty (X n)] /-- Auxiliary structure used to glue metric spaces below, recording an isometric embedding of a type `A` in another metric space. -/ structure aux_gluing_struct (A : Type) [metric_space A] : Type 1 := (space : Type) (metric : metric_space space) (embed : A → space) (isom : isometry embed) /-- Auxiliary sequence of metric spaces, containing copies of `X 0`, ..., `X n`, where each `X i` is glued to `X (i+1)` in an optimal way. The space at step `n+1` is obtained from the space at step `n` by adding `X (n+1)`, glued in an optimal way to the `X n` already sitting there. -/ def aux_gluing (n : ℕ) : aux_gluing_struct (X n) := nat.rec_on n { space := X 0, metric := by apply_instance, embed := id, isom := λx y, rfl } (λn a, by letI : metric_space a.space := a.metric; exact { space := glue_space a.isom (isometry_optimal_GH_injl (X n) (X n.succ)), metric := metric.metric_space_glue_space a.isom (isometry_optimal_GH_injl (X n) (X n.succ)), embed := (to_glue_r a.isom (isometry_optimal_GH_injl (X n) (X n.succ))) ∘ (optimal_GH_injr (X n) (X n.succ)), isom := (to_glue_r_isometry _ _).comp (isometry_optimal_GH_injr (X n) (X n.succ)) }) /-- The Gromov-Hausdorff space is complete. -/ instance : complete_space (GH_space) := begin have : ∀ (n : ℕ), 0 < ((1:ℝ) / 2) ^ n, by { apply pow_pos, norm_num }, -- start from a sequence of nonempty compact metric spaces within distance `1/2^n` of each other refine metric.complete_of_convergent_controlled_sequences (λn, (1/2)^n) this (λu hu, _), -- `X n` is a representative of `u n` let X := λn, (u n).rep, -- glue them together successively in an optimal way, getting a sequence of metric spaces `Y n` let Y := aux_gluing X, letI : ∀n, metric_space (Y n).space := λn, (Y n).metric, have E : ∀ n : ℕ, glue_space (Y n).isom (isometry_optimal_GH_injl (X n) (X n.succ)) = (Y n.succ).space := λ n, by { simp [Y, aux_gluing], refl }, let c := λn, cast (E n), have ic : ∀n, isometry (c n) := λn x y, rfl, -- there is a canonical embedding of `Y n` in `Y (n+1)`, by construction let f : Πn, (Y n).space → (Y n.succ).space := λn, (c n) ∘ (to_glue_l (aux_gluing X n).isom (isometry_optimal_GH_injl (X n) (X n.succ))), have I : ∀n, isometry (f n), { assume n, apply isometry.comp, { assume x y, refl }, { apply to_glue_l_isometry } }, -- consider the inductive limit `Z0` of the `Y n`, and then its completion `Z` let Z0 := metric.inductive_limit I, let Z := uniform_space.completion Z0, let Φ := to_inductive_limit I, let coeZ := (coe : Z0 → Z), -- let `X2 n` be the image of `X n` in the space `Z` let X2 := λn, range (coeZ ∘ (Φ n) ∘ (Y n).embed), have isom : ∀n, isometry (coeZ ∘ (Φ n) ∘ (Y n).embed), { assume n, apply isometry.comp completion.coe_isometry _, apply isometry.comp _ (Y n).isom, apply to_inductive_limit_isometry }, -- The Hausdorff distance of `X2 n` and `X2 (n+1)` is by construction the distance between -- `u n` and `u (n+1)`, therefore bounded by `1/2^n` have D2 : ∀n, Hausdorff_dist (X2 n) (X2 n.succ) < (1/2)^n, { assume n, have X2n : X2 n = range ((coeZ ∘ (Φ n.succ) ∘ (c n) ∘ (to_glue_r (Y n).isom (isometry_optimal_GH_injl (X n) (X n.succ)))) ∘ (optimal_GH_injl (X n) (X n.succ))), { change X2 n = range (coeZ ∘ (Φ n.succ) ∘ (c n) ∘ (to_glue_r (Y n).isom (isometry_optimal_GH_injl (X n) (X n.succ))) ∘ (optimal_GH_injl (X n) (X n.succ))), simp only [X2, Φ], rw [← to_inductive_limit_commute I], simp only [f], rw ← to_glue_commute }, rw range_comp at X2n, have X2nsucc : X2 n.succ = range ((coeZ ∘ (Φ n.succ) ∘ (c n) ∘ (to_glue_r (Y n).isom (isometry_optimal_GH_injl (X n) (X n.succ)))) ∘ (optimal_GH_injr (X n) (X n.succ))), by refl, rw range_comp at X2nsucc, rw [X2n, X2nsucc, Hausdorff_dist_image, Hausdorff_dist_optimal, ← dist_GH_dist], { exact hu n n n.succ (le_refl n) (le_succ n) }, { apply isometry.comp completion.coe_isometry _, apply isometry.comp _ ((ic n).comp (to_glue_r_isometry _ _)), apply to_inductive_limit_isometry } }, -- consider `X2 n` as a member `X3 n` of the type of nonempty compact subsets of `Z`, which -- is a metric space let X3 : ℕ → nonempty_compacts Z := λn, ⟨X2 n, ⟨range_nonempty _, compact_range (isom n).continuous ⟩⟩, -- `X3 n` is a Cauchy sequence by construction, as the successive distances are -- bounded by `(1/2)^n` have : cauchy_seq X3, { refine cauchy_seq_of_le_geometric (1/2) 1 (by norm_num) (λn, _), rw one_mul, exact le_of_lt (D2 n) }, -- therefore, it converges to a limit `L` rcases cauchy_seq_tendsto_of_complete this with ⟨L, hL⟩, -- the images of `X3 n` in the Gromov-Hausdorff space converge to the image of `L` have M : tendsto (λn, (X3 n).to_GH_space) at_top (𝓝 L.to_GH_space) := tendsto.comp (to_GH_space_continuous.tendsto _) hL, -- By construction, the image of `X3 n` in the Gromov-Hausdorff space is `u n`. have : ∀n, (X3 n).to_GH_space = u n, { assume n, rw [nonempty_compacts.to_GH_space, ← (u n).to_GH_space_rep, to_GH_space_eq_to_GH_space_iff_isometric], constructor, convert (isom n).isometric_on_range.symm, }, -- Finally, we have proved the convergence of `u n` exact ⟨L.to_GH_space, by simpa [this] using M⟩ end end complete--section end Gromov_Hausdorff --namespace
7610350b35ba8fe7c8307c3100a29f40c21fe331
b70031c8e2c5337b91d7e70f1e0c5f528f7b0e77
/src/data/fintype/basic.lean
8445b53bb2f8cb4f6cdc41920ce2714afa92d436
[ "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
51,882
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro Finite types. -/ import tactic.wlog import data.finset.powerset import data.finset.lattice import data.finset.pi import data.array.lemmas import order.well_founded open_locale nat universes u v variables {α : Type*} {β : Type*} {γ : Type*} /-- `fintype α` means that `α` is finite, i.e. there are only finitely many distinct elements of type `α`. The evidence of this is a finset `elems` (a list up to permutation without duplicates), together with a proof that everything of type `α` is in the list. -/ class fintype (α : Type*) := (elems [] : finset α) (complete : ∀ x : α, x ∈ elems) namespace finset variable [fintype α] /-- `univ` is the universal finite set of type `finset α` implied from the assumption `fintype α`. -/ def univ : finset α := fintype.elems α @[simp] theorem mem_univ (x : α) : x ∈ (univ : finset α) := fintype.complete x @[simp] theorem mem_univ_val : ∀ x, x ∈ (univ : finset α).1 := mem_univ @[simp] lemma coe_univ : ↑(univ : finset α) = (set.univ : set α) := by ext; simp lemma univ_nonempty_iff : (univ : finset α).nonempty ↔ nonempty α := by rw [← coe_nonempty, coe_univ, set.nonempty_iff_univ_nonempty] lemma univ_nonempty [nonempty α] : (univ : finset α).nonempty := univ_nonempty_iff.2 ‹_› lemma univ_eq_empty : (univ : finset α) = ∅ ↔ ¬nonempty α := by rw [← univ_nonempty_iff, nonempty_iff_ne_empty, ne.def, not_not] theorem subset_univ (s : finset α) : s ⊆ univ := λ a _, mem_univ a instance : order_top (finset α) := { top := univ, le_top := subset_univ, .. finset.partial_order } instance [decidable_eq α] : boolean_algebra (finset α) := { compl := λ s, univ \ s, sdiff_eq := λ s t, by simp [ext_iff], inf_compl_le_bot := λ s x hx, by simpa using hx, top_le_sup_compl := λ s x hx, by simp, ..finset.distrib_lattice, ..finset.semilattice_inf_bot, ..finset.order_top, ..finset.has_sdiff } lemma compl_eq_univ_sdiff [decidable_eq α] (s : finset α) : sᶜ = univ \ s := rfl @[simp] lemma mem_compl [decidable_eq α] {s : finset α} {x : α} : x ∈ sᶜ ↔ x ∉ s := by simp [compl_eq_univ_sdiff] @[simp, norm_cast] lemma coe_compl [decidable_eq α] (s : finset α) : ↑(sᶜ) = (↑s : set α)ᶜ := set.ext $ λ x, mem_compl theorem eq_univ_iff_forall {s : finset α} : s = univ ↔ ∀ x, x ∈ s := by simp [ext_iff] @[simp] lemma univ_inter [decidable_eq α] (s : finset α) : univ ∩ s = s := ext $ λ a, by simp @[simp] lemma inter_univ [decidable_eq α] (s : finset α) : s ∩ univ = s := by rw [inter_comm, univ_inter] @[simp] lemma piecewise_univ [∀i : α, decidable (i ∈ (univ : finset α))] {δ : α → Sort*} (f g : Πi, δ i) : univ.piecewise f g = f := by { ext i, simp [piecewise] } lemma univ_map_equiv_to_embedding {α β : Type*} [fintype α] [fintype β] (e : α ≃ β) : univ.map e.to_embedding = univ := begin apply eq_univ_iff_forall.mpr, intro b, rw [mem_map], use e.symm b, simp, end end finset open finset function namespace fintype instance decidable_pi_fintype {α} {β : α → Type*} [∀a, decidable_eq (β a)] [fintype α] : decidable_eq (Πa, β a) := assume f g, decidable_of_iff (∀ a ∈ fintype.elems α, f a = g a) (by simp [function.funext_iff, fintype.complete]) instance decidable_forall_fintype {p : α → Prop} [decidable_pred p] [fintype α] : decidable (∀ a, p a) := decidable_of_iff (∀ a ∈ @univ α _, p a) (by simp) instance decidable_exists_fintype {p : α → Prop} [decidable_pred p] [fintype α] : decidable (∃ a, p a) := decidable_of_iff (∃ a ∈ @univ α _, p a) (by simp) instance decidable_eq_equiv_fintype [decidable_eq β] [fintype α] : decidable_eq (α ≃ β) := λ a b, decidable_of_iff (a.1 = b.1) ⟨λ h, equiv.ext (congr_fun h), congr_arg _⟩ instance decidable_injective_fintype [decidable_eq α] [decidable_eq β] [fintype α] : decidable_pred (injective : (α → β) → Prop) := λ x, by unfold injective; apply_instance instance decidable_surjective_fintype [decidable_eq β] [fintype α] [fintype β] : decidable_pred (surjective : (α → β) → Prop) := λ x, by unfold surjective; apply_instance instance decidable_bijective_fintype [decidable_eq α] [decidable_eq β] [fintype α] [fintype β] : decidable_pred (bijective : (α → β) → Prop) := λ x, by unfold bijective; apply_instance instance decidable_left_inverse_fintype [decidable_eq α] [fintype α] (f : α → β) (g : β → α) : decidable (function.right_inverse f g) := show decidable (∀ x, g (f x) = x), by apply_instance instance decidable_right_inverse_fintype [decidable_eq β] [fintype β] (f : α → β) (g : β → α) : decidable (function.left_inverse f g) := show decidable (∀ x, f (g x) = x), by apply_instance /-- Construct a proof of `fintype α` from a universal multiset -/ def of_multiset [decidable_eq α] (s : multiset α) (H : ∀ x : α, x ∈ s) : fintype α := ⟨s.to_finset, by simpa using H⟩ /-- Construct a proof of `fintype α` from a universal list -/ def of_list [decidable_eq α] (l : list α) (H : ∀ x : α, x ∈ l) : fintype α := ⟨l.to_finset, by simpa using H⟩ theorem exists_univ_list (α) [fintype α] : ∃ l : list α, l.nodup ∧ ∀ x : α, x ∈ l := let ⟨l, e⟩ := quotient.exists_rep (@univ α _).1 in by have := and.intro univ.2 mem_univ_val; exact ⟨_, by rwa ← e at this⟩ /-- `card α` is the number of elements in `α`, defined when `α` is a fintype. -/ def card (α) [fintype α] : ℕ := (@univ α _).card /-- If `l` lists all the elements of `α` without duplicates, then `α ≃ fin (l.length)`. -/ def equiv_fin_of_forall_mem_list {α} [decidable_eq α] {l : list α} (h : ∀ x:α, x ∈ l) (nd : l.nodup) : α ≃ fin (l.length) := ⟨λ a, ⟨_, list.index_of_lt_length.2 (h a)⟩, λ i, l.nth_le i.1 i.2, λ a, by simp, λ ⟨i, h⟩, fin.eq_of_veq $ list.nodup_iff_nth_le_inj.1 nd _ _ (list.index_of_lt_length.2 (list.nth_le_mem _ _ _)) h $ by simp⟩ /-- There is (computably) a bijection between `α` and `fin n` where `n = card α`. Since it is not unique, and depends on which permutation of the universe list is used, the bijection is wrapped in `trunc` to preserve computability. -/ def equiv_fin (α) [decidable_eq α] [fintype α] : trunc (α ≃ fin (card α)) := by unfold card finset.card; exact quot.rec_on_subsingleton (@univ α _).1 (λ l (h : ∀ x:α, x ∈ l) (nd : l.nodup), trunc.mk (equiv_fin_of_forall_mem_list h nd)) mem_univ_val univ.2 theorem exists_equiv_fin (α) [fintype α] : ∃ n, nonempty (α ≃ fin n) := by haveI := classical.dec_eq α; exact ⟨card α, nonempty_of_trunc (equiv_fin α)⟩ instance (α : Type*) : subsingleton (fintype α) := ⟨λ ⟨s₁, h₁⟩ ⟨s₂, h₂⟩, by congr; simp [finset.ext_iff, h₁, h₂]⟩ /-- Given a predicate that can be represented by a finset, the subtype associated to the predicate is a fintype. -/ protected def subtype {p : α → Prop} (s : finset α) (H : ∀ x : α, x ∈ s ↔ p x) : fintype {x // p x} := ⟨⟨multiset.pmap subtype.mk s.1 (λ x, (H x).1), multiset.nodup_pmap (λ a _ b _, congr_arg subtype.val) s.2⟩, λ ⟨x, px⟩, multiset.mem_pmap.2 ⟨x, (H x).2 px, rfl⟩⟩ theorem subtype_card {p : α → Prop} (s : finset α) (H : ∀ x : α, x ∈ s ↔ p x) : @card {x // p x} (fintype.subtype s H) = s.card := multiset.card_pmap _ _ _ theorem card_of_subtype {p : α → Prop} (s : finset α) (H : ∀ x : α, x ∈ s ↔ p x) [fintype {x // p x}] : card {x // p x} = s.card := by { rw ← subtype_card s H, congr } /-- Construct a fintype from a finset with the same elements. -/ def of_finset {p : set α} (s : finset α) (H : ∀ x, x ∈ s ↔ x ∈ p) : fintype p := fintype.subtype s H @[simp] theorem card_of_finset {p : set α} (s : finset α) (H : ∀ x, x ∈ s ↔ x ∈ p) : @fintype.card p (of_finset s H) = s.card := fintype.subtype_card s H theorem card_of_finset' {p : set α} (s : finset α) (H : ∀ x, x ∈ s ↔ x ∈ p) [fintype p] : fintype.card p = s.card := by rw ← card_of_finset s H; congr /-- If `f : α → β` is a bijection and `α` is a fintype, then `β` is also a fintype. -/ def of_bijective [fintype α] (f : α → β) (H : function.bijective f) : fintype β := ⟨univ.map ⟨f, H.1⟩, λ b, let ⟨a, e⟩ := H.2 b in e ▸ mem_map_of_mem _ (mem_univ _)⟩ /-- If `f : α → β` is a surjection and `α` is a fintype, then `β` is also a fintype. -/ def of_surjective [decidable_eq β] [fintype α] (f : α → β) (H : function.surjective f) : fintype β := ⟨univ.image f, λ b, let ⟨a, e⟩ := H b in e ▸ mem_image_of_mem _ (mem_univ _)⟩ /-- Given an injective function to a fintype, the domain is also a fintype. This is noncomputable because injectivity alone cannot be used to construct preimages. -/ noncomputable def of_injective [fintype β] (f : α → β) (H : function.injective f) : fintype α := by letI := classical.dec; exact if hα : nonempty α then by letI := classical.inhabited_of_nonempty hα; exact of_surjective (inv_fun f) (inv_fun_surjective H) else ⟨∅, λ x, (hα ⟨x⟩).elim⟩ /-- If `f : α ≃ β` and `α` is a fintype, then `β` is also a fintype. -/ def of_equiv (α : Type*) [fintype α] (f : α ≃ β) : fintype β := of_bijective _ f.bijective theorem of_equiv_card [fintype α] (f : α ≃ β) : @card β (of_equiv α f) = card α := multiset.card_map _ _ theorem card_congr {α β} [fintype α] [fintype β] (f : α ≃ β) : card α = card β := by rw ← of_equiv_card f; congr theorem card_eq {α β} [F : fintype α] [G : fintype β] : card α = card β ↔ nonempty (α ≃ β) := ⟨λ h, ⟨by classical; calc α ≃ fin (card α) : trunc.out (equiv_fin α) ... ≃ fin (card β) : by rw h ... ≃ β : (trunc.out (equiv_fin β)).symm⟩, λ ⟨f⟩, card_congr f⟩ /-- Subsingleton types are fintypes (with zero or one terms). -/ def of_subsingleton (a : α) [subsingleton α] : fintype α := ⟨{a}, λ b, finset.mem_singleton.2 (subsingleton.elim _ _)⟩ @[simp] theorem univ_of_subsingleton (a : α) [subsingleton α] : @univ _ (of_subsingleton a) = {a} := rfl @[simp] theorem card_of_subsingleton (a : α) [subsingleton α] : @fintype.card _ (of_subsingleton a) = 1 := rfl end fintype namespace set /-- Construct a finset enumerating a set `s`, given a `fintype` instance. -/ def to_finset (s : set α) [fintype s] : finset α := ⟨(@finset.univ s _).1.map subtype.val, multiset.nodup_map (λ a b, subtype.eq) finset.univ.2⟩ @[simp] theorem mem_to_finset {s : set α} [fintype s] {a : α} : a ∈ s.to_finset ↔ a ∈ s := by simp [to_finset] @[simp] theorem mem_to_finset_val {s : set α} [fintype s] {a : α} : a ∈ s.to_finset.1 ↔ a ∈ s := mem_to_finset -- We use an arbitrary `[fintype s]` instance here, -- not necessarily coming from a `[fintype α]`. @[simp] lemma to_finset_card {α : Type*} (s : set α) [fintype s] : s.to_finset.card = fintype.card s := multiset.card_map subtype.val finset.univ.val @[simp] theorem coe_to_finset (s : set α) [fintype s] : (↑s.to_finset : set α) = s := set.ext $ λ _, mem_to_finset @[simp] theorem to_finset_inj {s t : set α} [fintype s] [fintype t] : s.to_finset = t.to_finset ↔ s = t := ⟨λ h, by rw [← s.coe_to_finset, h, t.coe_to_finset], λ h, by simp [h]; congr⟩ end set lemma finset.card_univ [fintype α] : (finset.univ : finset α).card = fintype.card α := rfl lemma finset.eq_univ_of_card [fintype α] (s : finset α) (hs : s.card = fintype.card α) : s = univ := eq_of_subset_of_card_le (subset_univ _) $ by rw [hs, finset.card_univ] lemma finset.card_le_univ [fintype α] (s : finset α) : s.card ≤ fintype.card α := card_le_of_subset (subset_univ s) lemma finset.card_univ_diff [decidable_eq α] [fintype α] (s : finset α) : (finset.univ \ s).card = fintype.card α - s.card := finset.card_sdiff (subset_univ s) lemma finset.card_compl [decidable_eq α] [fintype α] (s : finset α) : sᶜ.card = fintype.card α - s.card := finset.card_univ_diff s instance (n : ℕ) : fintype (fin n) := ⟨finset.fin_range n, finset.mem_fin_range⟩ lemma fin.univ_def (n : ℕ) : (univ : finset (fin n)) = finset.fin_range n := rfl @[simp] theorem fintype.card_fin (n : ℕ) : fintype.card (fin n) = n := list.length_fin_range n @[simp] lemma finset.card_fin (n : ℕ) : finset.card (finset.univ : finset (fin n)) = n := by rw [finset.card_univ, fintype.card_fin] lemma fin.equiv_iff_eq {m n : ℕ} : nonempty (fin m ≃ fin n) ↔ m = n := ⟨λ ⟨h⟩, by simpa using fintype.card_congr h, λ h, ⟨equiv.cast $ h ▸ rfl ⟩ ⟩ /-- Embed `fin n` into `fin (n + 1)` by prepending zero to the `univ` -/ lemma fin.univ_succ (n : ℕ) : (univ : finset (fin (n + 1))) = insert 0 (univ.image fin.succ) := begin ext m, simp only [mem_univ, mem_insert, true_iff, mem_image, exists_prop], exact fin.cases (or.inl rfl) (λ i, or.inr ⟨i, trivial, rfl⟩) m end /-- Embed `fin n` into `fin (n + 1)` by appending a new `fin.last n` to the `univ` -/ lemma fin.univ_cast_succ (n : ℕ) : (univ : finset (fin (n + 1))) = insert (fin.last n) (univ.image fin.cast_succ) := begin ext m, simp only [mem_univ, mem_insert, true_iff, mem_image, exists_prop, true_and], by_cases h : m.val < n, { right, use fin.cast_lt m h, rw fin.cast_succ_cast_lt }, { left, exact fin.eq_last_of_not_lt h } end /-- Embed `fin n` into `fin (n + 1)` by inserting around a specified pivot `p : fin (n + 1)` into the `univ` -/ lemma fin.univ_succ_above (n : ℕ) (p : fin (n + 1)) : (univ : finset (fin (n + 1))) = insert p (univ.image (fin.succ_above p)) := begin rcases lt_or_eq_of_le (fin.le_last p) with hl|rfl, { ext m, simp only [finset.mem_univ, finset.mem_insert, true_iff, finset.mem_image, exists_prop], refine or_iff_not_imp_left.mpr _, { intro h, use p.pred_above m h, simp only [eq_self_iff_true, fin.succ_above_pred_above, and_self] } }, { rw fin.succ_above_last, exact fin.univ_cast_succ n } end @[instance, priority 10] def unique.fintype {α : Type*} [unique α] : fintype α := fintype.of_subsingleton (default α) @[simp] lemma univ_unique {α : Type*} [unique α] [f : fintype α] : @finset.univ α _ = {default α} := by rw [subsingleton.elim f (@unique.fintype α _)]; refl instance : fintype empty := ⟨∅, empty.rec _⟩ @[simp] theorem fintype.univ_empty : @univ empty _ = ∅ := rfl @[simp] theorem fintype.card_empty : fintype.card empty = 0 := rfl instance : fintype pempty := ⟨∅, pempty.rec _⟩ @[simp] theorem fintype.univ_pempty : @univ pempty _ = ∅ := rfl @[simp] theorem fintype.card_pempty : fintype.card pempty = 0 := rfl instance : fintype unit := fintype.of_subsingleton () theorem fintype.univ_unit : @univ unit _ = {()} := rfl theorem fintype.card_unit : fintype.card unit = 1 := rfl instance : fintype punit := fintype.of_subsingleton punit.star @[simp] theorem fintype.univ_punit : @univ punit _ = {punit.star} := rfl @[simp] theorem fintype.card_punit : fintype.card punit = 1 := rfl instance : fintype bool := ⟨⟨tt ::ₘ ff ::ₘ 0, by simp⟩, λ x, by cases x; simp⟩ @[simp] theorem fintype.univ_bool : @univ bool _ = {tt, ff} := rfl instance units_int.fintype : fintype (units ℤ) := ⟨{1, -1}, λ x, by cases int.units_eq_one_or x; simp *⟩ instance additive.fintype : Π [fintype α], fintype (additive α) := id instance multiplicative.fintype : Π [fintype α], fintype (multiplicative α) := id @[simp] theorem fintype.card_units_int : fintype.card (units ℤ) = 2 := rfl noncomputable instance [monoid α] [fintype α] : fintype (units α) := by classical; exact fintype.of_injective units.val units.ext @[simp] theorem fintype.card_bool : fintype.card bool = 2 := rfl /-- Given a finset on `α`, lift it to being a finset on `option α` using `option.some` and then insert `option.none`. -/ def finset.insert_none (s : finset α) : finset (option α) := ⟨none ::ₘ s.1.map some, multiset.nodup_cons.2 ⟨by simp, multiset.nodup_map (λ a b, option.some.inj) s.2⟩⟩ @[simp] theorem finset.mem_insert_none {s : finset α} : ∀ {o : option α}, o ∈ s.insert_none ↔ ∀ a ∈ o, a ∈ s | none := iff_of_true (multiset.mem_cons_self _ _) (λ a h, by cases h) | (some a) := multiset.mem_cons.trans $ by simp; refl theorem finset.some_mem_insert_none {s : finset α} {a : α} : some a ∈ s.insert_none ↔ a ∈ s := by simp instance {α : Type*} [fintype α] : fintype (option α) := ⟨univ.insert_none, λ a, by simp⟩ @[simp] theorem fintype.card_option {α : Type*} [fintype α] : fintype.card (option α) = fintype.card α + 1 := (multiset.card_cons _ _).trans (by rw multiset.card_map; refl) instance {α : Type*} (β : α → Type*) [fintype α] [∀ a, fintype (β a)] : fintype (sigma β) := ⟨univ.sigma (λ _, univ), λ ⟨a, b⟩, by simp⟩ @[simp] lemma finset.univ_sigma_univ {α : Type*} {β : α → Type*} [fintype α] [∀ a, fintype (β a)] : (univ : finset α).sigma (λ a, (univ : finset (β a))) = univ := rfl instance (α β : Type*) [fintype α] [fintype β] : fintype (α × β) := ⟨univ.product univ, λ ⟨a, b⟩, by simp⟩ @[simp] lemma finset.univ_product_univ {α β : Type*} [fintype α] [fintype β] : (univ : finset α).product (univ : finset β) = univ := rfl @[simp] theorem fintype.card_prod (α β : Type*) [fintype α] [fintype β] : fintype.card (α × β) = fintype.card α * fintype.card β := card_product _ _ /-- Given that `α × β` is a fintype, `α` is also a fintype. -/ def fintype.fintype_prod_left {α β} [decidable_eq α] [fintype (α × β)] [nonempty β] : fintype α := ⟨(fintype.elems (α × β)).image prod.fst, assume a, let ⟨b⟩ := ‹nonempty β› in by simp; exact ⟨b, fintype.complete _⟩⟩ /-- Given that `α × β` is a fintype, `β` is also a fintype. -/ def fintype.fintype_prod_right {α β} [decidable_eq β] [fintype (α × β)] [nonempty α] : fintype β := ⟨(fintype.elems (α × β)).image prod.snd, assume b, let ⟨a⟩ := ‹nonempty α› in by simp; exact ⟨a, fintype.complete _⟩⟩ instance (α : Type*) [fintype α] : fintype (ulift α) := fintype.of_equiv _ equiv.ulift.symm @[simp] theorem fintype.card_ulift (α : Type*) [fintype α] : fintype.card (ulift α) = fintype.card α := fintype.of_equiv_card _ instance (α : Type u) (β : Type v) [fintype α] [fintype β] : fintype (α ⊕ β) := @fintype.of_equiv _ _ (@sigma.fintype _ (λ b, cond b (ulift α) (ulift.{(max u v) v} β)) _ (λ b, by cases b; apply ulift.fintype)) ((equiv.sum_equiv_sigma_bool _ _).symm.trans (equiv.sum_congr equiv.ulift equiv.ulift)) namespace fintype variables [fintype α] [fintype β] lemma card_le_of_injective (f : α → β) (hf : function.injective f) : card α ≤ card β := finset.card_le_card_of_inj_on f (λ _ _, finset.mem_univ _) (λ _ _ _ _ h, hf h) /-- The pigeonhole principle for finitely many pigeons and pigeonholes. This is the `fintype` version of `finset.exists_ne_map_eq_of_card_lt_of_maps_to`. -/ lemma exists_ne_map_eq_of_card_lt (f : α → β) (h : fintype.card β < fintype.card α) : ∃ x y, x ≠ y ∧ f x = f y := let ⟨x, _, y, _, h⟩ := finset.exists_ne_map_eq_of_card_lt_of_maps_to h (λ x _, mem_univ (f x)) in ⟨x, y, h⟩ lemma card_eq_one_iff : card α = 1 ↔ (∃ x : α, ∀ y, y = x) := by rw [← card_unit, card_eq]; exact ⟨λ ⟨a⟩, ⟨a.symm (), λ y, a.injective (subsingleton.elim _ _)⟩, λ ⟨x, hx⟩, ⟨⟨λ _, (), λ _, x, λ _, (hx _).trans (hx _).symm, λ _, subsingleton.elim _ _⟩⟩⟩ lemma card_eq_zero_iff : card α = 0 ↔ (α → false) := ⟨λ h a, have e : α ≃ empty := classical.choice (card_eq.1 (by simp [h])), (e a).elim, λ h, have e : α ≃ empty := ⟨λ a, (h a).elim, λ a, a.elim, λ a, (h a).elim, λ a, a.elim⟩, by simp [card_congr e]⟩ /-- A `fintype` with cardinality zero is (constructively) equivalent to `pempty`. -/ def card_eq_zero_equiv_equiv_pempty : card α = 0 ≃ (α ≃ pempty.{v+1}) := { to_fun := λ h, { to_fun := λ a, false.elim (card_eq_zero_iff.1 h a), inv_fun := λ a, pempty.elim a, left_inv := λ a, false.elim (card_eq_zero_iff.1 h a), right_inv := λ a, pempty.elim a, }, inv_fun := λ e, by { simp only [←of_equiv_card e], convert card_pempty, }, left_inv := λ h, rfl, right_inv := λ e, by { ext x, cases e x, } } lemma card_pos_iff : 0 < card α ↔ nonempty α := ⟨λ h, classical.by_contradiction (λ h₁, have card α = 0 := card_eq_zero_iff.2 (λ a, h₁ ⟨a⟩), lt_irrefl 0 $ by rwa this at h), λ ⟨a⟩, nat.pos_of_ne_zero (mt card_eq_zero_iff.1 (λ h, h a))⟩ lemma card_le_one_iff : card α ≤ 1 ↔ (∀ a b : α, a = b) := let n := card α in have hn : n = card α := rfl, match n, hn with | 0 := λ ha, ⟨λ h, λ a, (card_eq_zero_iff.1 ha.symm a).elim, λ _, ha ▸ nat.le_succ _⟩ | 1 := λ ha, ⟨λ h, λ a b, let ⟨x, hx⟩ := card_eq_one_iff.1 ha.symm in by rw [hx a, hx b], λ _, ha ▸ le_refl _⟩ | (n+2) := λ ha, ⟨λ h, by rw ← ha at h; exact absurd h dec_trivial, (λ h, card_unit ▸ card_le_of_injective (λ _, ()) (λ _ _ _, h _ _))⟩ end lemma card_le_one_iff_subsingleton : card α ≤ 1 ↔ subsingleton α := iff.trans card_le_one_iff subsingleton_iff.symm lemma one_lt_card_iff_nontrivial : 1 < card α ↔ nontrivial α := begin classical, rw ← not_iff_not, push_neg, rw [not_nontrivial_iff_subsingleton, card_le_one_iff_subsingleton] end lemma exists_ne_of_one_lt_card (h : 1 < card α) (a : α) : ∃ b : α, b ≠ a := by { haveI : nontrivial α := one_lt_card_iff_nontrivial.1 h, exact exists_ne a } lemma exists_pair_of_one_lt_card (h : 1 < card α) : ∃ (a b : α), a ≠ b := by { haveI : nontrivial α := one_lt_card_iff_nontrivial.1 h, exact exists_pair_ne α } lemma injective_iff_surjective {f : α → α} : injective f ↔ surjective f := by haveI := classical.prop_decidable; exact have ∀ {f : α → α}, injective f → surjective f, from λ f hinj x, have h₁ : image f univ = univ := eq_of_subset_of_card_le (subset_univ _) ((card_image_of_injective univ hinj).symm ▸ le_refl _), have h₂ : x ∈ image f univ := h₁.symm ▸ mem_univ _, exists_of_bex (mem_image.1 h₂), ⟨this, λ hsurj, has_left_inverse.injective ⟨surj_inv hsurj, left_inverse_of_surjective_of_right_inverse (this (injective_surj_inv _)) (right_inverse_surj_inv _)⟩⟩ lemma injective_iff_bijective {f : α → α} : injective f ↔ bijective f := by simp [bijective, injective_iff_surjective] lemma surjective_iff_bijective {f : α → α} : surjective f ↔ bijective f := by simp [bijective, injective_iff_surjective] lemma injective_iff_surjective_of_equiv {β : Type*} {f : α → β} (e : α ≃ β) : injective f ↔ surjective f := have injective (e.symm ∘ f) ↔ surjective (e.symm ∘ f), from injective_iff_surjective, ⟨λ hinj, by simpa [function.comp] using e.surjective.comp (this.1 (e.symm.injective.comp hinj)), λ hsurj, by simpa [function.comp] using e.injective.comp (this.2 (e.symm.surjective.comp hsurj))⟩ lemma nonempty_equiv_of_card_eq (h : card α = card β) : nonempty (α ≃ β) := begin obtain ⟨m, ⟨f⟩⟩ := exists_equiv_fin α, obtain ⟨n, ⟨g⟩⟩ := exists_equiv_fin β, suffices : m = n, { subst this, exact ⟨f.trans g.symm⟩ }, calc m = card (fin m) : (card_fin m).symm ... = card α : card_congr f.symm ... = card β : h ... = card (fin n) : card_congr g ... = n : card_fin n end lemma bijective_iff_injective_and_card (f : α → β) : bijective f ↔ injective f ∧ card α = card β := begin split, { intro h, exact ⟨h.1, card_congr (equiv.of_bijective f h)⟩ }, { rintro ⟨hf, h⟩, refine ⟨hf, _⟩, obtain ⟨e⟩ : nonempty (α ≃ β) := nonempty_equiv_of_card_eq h, rwa ← injective_iff_surjective_of_equiv e } end lemma bijective_iff_surjective_and_card (f : α → β) : bijective f ↔ surjective f ∧ card α = card β := begin split, { intro h, exact ⟨h.2, card_congr (equiv.of_bijective f h)⟩, }, { rintro ⟨hf, h⟩, refine ⟨_, hf⟩, obtain ⟨e⟩ : nonempty (α ≃ β) := nonempty_equiv_of_card_eq h, rwa injective_iff_surjective_of_equiv e } end end fintype lemma fintype.coe_image_univ [fintype α] [decidable_eq β] {f : α → β} : ↑(finset.image f finset.univ) = set.range f := by { ext x, simp } instance list.subtype.fintype [decidable_eq α] (l : list α) : fintype {x // x ∈ l} := fintype.of_list l.attach l.mem_attach instance multiset.subtype.fintype [decidable_eq α] (s : multiset α) : fintype {x // x ∈ s} := fintype.of_multiset s.attach s.mem_attach instance finset.subtype.fintype (s : finset α) : fintype {x // x ∈ s} := ⟨s.attach, s.mem_attach⟩ instance finset_coe.fintype (s : finset α) : fintype (↑s : set α) := finset.subtype.fintype s @[simp] lemma fintype.card_coe (s : finset α) : fintype.card (↑s : set α) = s.card := card_attach lemma finset.attach_eq_univ {s : finset α} : s.attach = finset.univ := rfl lemma finset.card_le_one_iff {s : finset α} : s.card ≤ 1 ↔ ∀ {x y}, x ∈ s → y ∈ s → x = y := begin let t : set α := ↑s, letI : fintype t := finset_coe.fintype s, have : fintype.card t = s.card := fintype.card_coe s, rw [← this, fintype.card_le_one_iff], split, { assume H x y hx hy, exact subtype.mk.inj (H ⟨x, hx⟩ ⟨y, hy⟩) }, { assume H x y, exact subtype.eq (H x.2 y.2) } end /-- A `finset` of a subsingleton type has cardinality at most one. -/ lemma finset.card_le_one_of_subsingleton [subsingleton α] (s : finset α) : s.card ≤ 1 := finset.card_le_one_iff.2 $ λ _ _ _ _, subsingleton.elim _ _ lemma finset.one_lt_card_iff {s : finset α} : 1 < s.card ↔ ∃ x y, (x ∈ s) ∧ (y ∈ s) ∧ x ≠ y := begin classical, rw ← not_iff_not, push_neg, simpa [or_iff_not_imp_left] using finset.card_le_one_iff end instance plift.fintype (p : Prop) [decidable p] : fintype (plift p) := ⟨if h : p then {⟨h⟩} else ∅, λ ⟨h⟩, by simp [h]⟩ instance Prop.fintype : fintype Prop := ⟨⟨true ::ₘ false ::ₘ 0, by simp [true_ne_false]⟩, classical.cases (by simp) (by simp)⟩ instance subtype.fintype (p : α → Prop) [decidable_pred p] [fintype α] : fintype {x // p x} := fintype.subtype (univ.filter p) (by simp) /-- A set on a fintype, when coerced to a type, is a fintype. -/ def set_fintype {α} [fintype α] (s : set α) [decidable_pred s] : fintype s := subtype.fintype (λ x, x ∈ s) namespace function.embedding /-- An embedding from a `fintype` to itself can be promoted to an equivalence. -/ noncomputable def equiv_of_fintype_self_embedding {α : Type*} [fintype α] (e : α ↪ α) : α ≃ α := equiv.of_bijective e (fintype.injective_iff_bijective.1 e.2) @[simp] lemma equiv_of_fintype_self_embedding_to_embedding {α : Type*} [fintype α] (e : α ↪ α) : e.equiv_of_fintype_self_embedding.to_embedding = e := by { ext, refl, } end function.embedding @[simp] lemma finset.univ_map_embedding {α : Type*} [fintype α] (e : α ↪ α) : univ.map e = univ := by rw [← e.equiv_of_fintype_self_embedding_to_embedding, univ_map_equiv_to_embedding] namespace fintype variables [decidable_eq α] [fintype α] {δ : α → Type*} /-- Given for all `a : α` a finset `t a` of `δ a`, then one can define the finset `fintype.pi_finset t` of all functions taking values in `t a` for all `a`. This is the analogue of `finset.pi` where the base finset is `univ` (but formally they are not the same, as there is an additional condition `i ∈ finset.univ` in the `finset.pi` definition). -/ def pi_finset (t : Πa, finset (δ a)) : finset (Πa, δ a) := (finset.univ.pi t).map ⟨λ f a, f a (mem_univ a), λ _ _, by simp [function.funext_iff]⟩ @[simp] lemma mem_pi_finset {t : Πa, finset (δ a)} {f : Πa, δ a} : f ∈ pi_finset t ↔ (∀a, f a ∈ t a) := begin split, { simp only [pi_finset, mem_map, and_imp, forall_prop_of_true, exists_prop, mem_univ, exists_imp_distrib, mem_pi], assume g hg hgf a, rw ← hgf, exact hg a }, { simp only [pi_finset, mem_map, forall_prop_of_true, exists_prop, mem_univ, mem_pi], assume hf, exact ⟨λ a ha, f a, hf, rfl⟩ } end lemma pi_finset_subset (t₁ t₂ : Πa, finset (δ a)) (h : ∀ a, t₁ a ⊆ t₂ a) : pi_finset t₁ ⊆ pi_finset t₂ := λ g hg, mem_pi_finset.2 $ λ a, h a $ mem_pi_finset.1 hg a lemma pi_finset_disjoint_of_disjoint [∀ a, decidable_eq (δ a)] (t₁ t₂ : Πa, finset (δ a)) {a : α} (h : disjoint (t₁ a) (t₂ a)) : disjoint (pi_finset t₁) (pi_finset t₂) := disjoint_iff_ne.2 $ λ f₁ hf₁ f₂ hf₂ eq₁₂, disjoint_iff_ne.1 h (f₁ a) (mem_pi_finset.1 hf₁ a) (f₂ a) (mem_pi_finset.1 hf₂ a) (congr_fun eq₁₂ a) end fintype /-! ### pi -/ /-- A dependent product of fintypes, indexed by a fintype, is a fintype. -/ instance pi.fintype {α : Type*} {β : α → Type*} [decidable_eq α] [fintype α] [∀a, fintype (β a)] : fintype (Πa, β a) := ⟨fintype.pi_finset (λ _, univ), by simp⟩ @[simp] lemma fintype.pi_finset_univ {α : Type*} {β : α → Type*} [decidable_eq α] [fintype α] [∀a, fintype (β a)] : fintype.pi_finset (λ a : α, (finset.univ : finset (β a))) = (finset.univ : finset (Π a, β a)) := rfl instance d_array.fintype {n : ℕ} {α : fin n → Type*} [∀n, fintype (α n)] : fintype (d_array n α) := fintype.of_equiv _ (equiv.d_array_equiv_fin _).symm instance array.fintype {n : ℕ} {α : Type*} [fintype α] : fintype (array n α) := d_array.fintype instance vector.fintype {α : Type*} [fintype α] {n : ℕ} : fintype (vector α n) := fintype.of_equiv _ (equiv.vector_equiv_fin _ _).symm instance quotient.fintype [fintype α] (s : setoid α) [decidable_rel ((≈) : α → α → Prop)] : fintype (quotient s) := fintype.of_surjective quotient.mk (λ x, quotient.induction_on x (λ x, ⟨x, rfl⟩)) instance finset.fintype [fintype α] : fintype (finset α) := ⟨univ.powerset, λ x, finset.mem_powerset.2 (finset.subset_univ _)⟩ @[simp] lemma fintype.card_finset [fintype α] : fintype.card (finset α) = 2 ^ (fintype.card α) := finset.card_powerset finset.univ @[simp] lemma set.to_finset_univ [fintype α] : (set.univ : set α).to_finset = finset.univ := by { ext, simp only [set.mem_univ, mem_univ, set.mem_to_finset] } @[simp] lemma set.to_finset_empty [fintype α] : (∅ : set α).to_finset = ∅ := by { ext, simp only [set.mem_empty_eq, set.mem_to_finset, not_mem_empty] } theorem fintype.card_subtype_le [fintype α] (p : α → Prop) [decidable_pred p] : fintype.card {x // p x} ≤ fintype.card α := by rw fintype.subtype_card; exact card_le_of_subset (subset_univ _) theorem fintype.card_subtype_lt [fintype α] {p : α → Prop} [decidable_pred p] {x : α} (hx : ¬ p x) : fintype.card {x // p x} < fintype.card α := by rw [fintype.subtype_card]; exact finset.card_lt_card ⟨subset_univ _, not_forall.2 ⟨x, by simp [hx]⟩⟩ instance psigma.fintype {α : Type*} {β : α → Type*} [fintype α] [∀ a, fintype (β a)] : fintype (Σ' a, β a) := fintype.of_equiv _ (equiv.psigma_equiv_sigma _).symm instance psigma.fintype_prop_left {α : Prop} {β : α → Type*} [decidable α] [∀ a, fintype (β a)] : fintype (Σ' a, β a) := if h : α then fintype.of_equiv (β h) ⟨λ x, ⟨h, x⟩, psigma.snd, λ _, rfl, λ ⟨_, _⟩, rfl⟩ else ⟨∅, λ x, h x.1⟩ instance psigma.fintype_prop_right {α : Type*} {β : α → Prop} [∀ a, decidable (β a)] [fintype α] : fintype (Σ' a, β a) := fintype.of_equiv {a // β a} ⟨λ ⟨x, y⟩, ⟨x, y⟩, λ ⟨x, y⟩, ⟨x, y⟩, λ ⟨x, y⟩, rfl, λ ⟨x, y⟩, rfl⟩ instance psigma.fintype_prop_prop {α : Prop} {β : α → Prop} [decidable α] [∀ a, decidable (β a)] : fintype (Σ' a, β a) := if h : ∃ a, β a then ⟨{⟨h.fst, h.snd⟩}, λ ⟨_, _⟩, by simp⟩ else ⟨∅, λ ⟨x, y⟩, h ⟨x, y⟩⟩ instance set.fintype [fintype α] : fintype (set α) := ⟨(@finset.univ α _).powerset.map ⟨coe, coe_injective⟩, λ s, begin classical, refine mem_map.2 ⟨finset.univ.filter s, mem_powerset.2 (subset_univ _), _⟩, apply (coe_filter _ _).trans, rw [coe_univ, set.sep_univ], refl end⟩ instance pfun_fintype (p : Prop) [decidable p] (α : p → Type*) [Π hp, fintype (α hp)] : fintype (Π hp : p, α hp) := if hp : p then fintype.of_equiv (α hp) ⟨λ a _, a, λ f, f hp, λ _, rfl, λ _, rfl⟩ else ⟨singleton (λ h, (hp h).elim), by simp [hp, function.funext_iff]⟩ @[simp] lemma finset.univ_pi_univ {α : Type*} {β : α → Type*} [decidable_eq α] [fintype α] [∀a, fintype (β a)] : finset.univ.pi (λ a : α, (finset.univ : finset (β a))) = finset.univ := by { ext, simp } lemma mem_image_univ_iff_mem_range {α β : Type*} [fintype α] [decidable_eq β] {f : α → β} {b : β} : b ∈ univ.image f ↔ b ∈ set.range f := by simp lemma card_lt_card_of_injective_of_not_mem {α β : Type*} [fintype α] [fintype β] (f : α → β) (h : function.injective f) {b : β} (w : b ∉ set.range f) : fintype.card α < fintype.card β := begin classical, calc fintype.card α = (univ : finset α).card : rfl ... = (image f univ).card : (card_image_of_injective univ h).symm ... < (insert b (image f univ)).card : card_lt_card (ssubset_insert (mt mem_image_univ_iff_mem_range.mp w)) ... ≤ (univ : finset β).card : card_le_of_subset (subset_univ _) ... = fintype.card β : rfl end /-- An auxiliary function for `quotient.fin_choice`. Given a collection of setoids indexed by a type `ι`, a (finite) list `l` of indices, and a function that for each `i ∈ l` gives a term of the corresponding quotient type, then there is a corresponding term in the quotient of the product of the setoids indexed by `l`. -/ def quotient.fin_choice_aux {ι : Type*} [decidable_eq ι] {α : ι → Type*} [S : ∀ i, setoid (α i)] : Π (l : list ι), (Π i ∈ l, quotient (S i)) → @quotient (Π i ∈ l, α i) (by apply_instance) | [] f := ⟦λ i, false.elim⟧ | (i::l) f := begin refine quotient.lift_on₂ (f i (list.mem_cons_self _ _)) (quotient.fin_choice_aux l (λ j h, f j (list.mem_cons_of_mem _ h))) _ _, exact λ a l, ⟦λ j h, if e : j = i then by rw e; exact a else l _ (h.resolve_left e)⟧, refine λ a₁ l₁ a₂ l₂ h₁ h₂, quotient.sound (λ j h, _), by_cases e : j = i; simp [e], { subst j, exact h₁ }, { exact h₂ _ _ } end theorem quotient.fin_choice_aux_eq {ι : Type*} [decidable_eq ι] {α : ι → Type*} [S : ∀ i, setoid (α i)] : ∀ (l : list ι) (f : Π i ∈ l, α i), quotient.fin_choice_aux l (λ i h, ⟦f i h⟧) = ⟦f⟧ | [] f := quotient.sound (λ i h, h.elim) | (i::l) f := begin simp [quotient.fin_choice_aux, quotient.fin_choice_aux_eq l], refine quotient.sound (λ j h, _), by_cases e : j = i; simp [e], subst j, refl end /-- Given a collection of setoids indexed by a fintype `ι` and a function that for each `i : ι` gives a term of the corresponding quotient type, then there is corresponding term in the quotient of the product of the setoids. -/ def quotient.fin_choice {ι : Type*} [decidable_eq ι] [fintype ι] {α : ι → Type*} [S : ∀ i, setoid (α i)] (f : Π i, quotient (S i)) : @quotient (Π i, α i) (by apply_instance) := quotient.lift_on (@quotient.rec_on _ _ (λ l : multiset ι, @quotient (Π i ∈ l, α i) (by apply_instance)) finset.univ.1 (λ l, quotient.fin_choice_aux l (λ i _, f i)) (λ a b h, begin have := λ a, quotient.fin_choice_aux_eq a (λ i h, quotient.out (f i)), simp [quotient.out_eq] at this, simp [this], let g := λ a:multiset ι, ⟦λ (i : ι) (h : i ∈ a), quotient.out (f i)⟧, refine eq_of_heq ((eq_rec_heq _ _).trans (_ : g a == g b)), congr' 1, exact quotient.sound h, end)) (λ f, ⟦λ i, f i (finset.mem_univ _)⟧) (λ a b h, quotient.sound $ λ i, h _ _) theorem quotient.fin_choice_eq {ι : Type*} [decidable_eq ι] [fintype ι] {α : ι → Type*} [∀ i, setoid (α i)] (f : Π i, α i) : quotient.fin_choice (λ i, ⟦f i⟧) = ⟦f⟧ := begin let q, swap, change quotient.lift_on q _ _ = _, have : q = ⟦λ i h, f i⟧, { dsimp [q], exact quotient.induction_on (@finset.univ ι _).1 (λ l, quotient.fin_choice_aux_eq _ _) }, simp [this], exact setoid.refl _ end section equiv open list equiv equiv.perm variables [decidable_eq α] [decidable_eq β] /-- Given a list, produce a list of all permutations of its elements. -/ def perms_of_list : list α → list (perm α) | [] := [1] | (a :: l) := perms_of_list l ++ l.bind (λ b, (perms_of_list l).map (λ f, swap a b * f)) lemma length_perms_of_list : ∀ l : list α, length (perms_of_list l) = l.length! | [] := rfl | (a :: l) := begin rw [length_cons, nat.factorial_succ], simp [perms_of_list, length_bind, length_perms_of_list, function.comp, nat.succ_mul], cc end lemma mem_perms_of_list_of_mem {l : list α} {f : perm α} (h : ∀ x, f x ≠ x → x ∈ l) : f ∈ perms_of_list l := begin induction l with a l IH generalizing f h, { exact list.mem_singleton.2 (equiv.ext $ λ x, decidable.by_contradiction $ h _) }, by_cases hfa : f a = a, { refine mem_append_left _ (IH (λ x hx, mem_of_ne_of_mem _ (h x hx))), rintro rfl, exact hx hfa }, { have hfa' : f (f a) ≠ f a := mt (λ h, f.injective h) hfa, have : ∀ (x : α), (swap a (f a) * f) x ≠ x → x ∈ l, { intros x hx, have hxa : x ≠ a, { rintro rfl, apply hx, simp only [mul_apply, swap_apply_right] }, refine list.mem_of_ne_of_mem hxa (h x (λ h, _)), simp only [h, mul_apply, swap_apply_def, mul_apply, ne.def, apply_eq_iff_eq] at hx; split_ifs at hx, exacts [hxa (h.symm.trans h_1), hx h] }, suffices : f ∈ perms_of_list l ∨ ∃ (b ∈ l) (g ∈ perms_of_list l), swap a b * g = f, { simpa only [perms_of_list, exists_prop, list.mem_map, mem_append, list.mem_bind] }, refine or_iff_not_imp_left.2 (λ hfl, ⟨f a, _, swap a (f a) * f, IH this, _⟩), { by_cases hffa : f (f a) = a, { exact mem_of_ne_of_mem hfa (h _ (mt (λ h, f.injective h) hfa)) }, { apply this, simp only [mul_apply, swap_apply_def, mul_apply, ne.def, apply_eq_iff_eq], split_ifs; cc } }, { rw [← mul_assoc, mul_def (swap a (f a)) (swap a (f a)), swap_swap, ← equiv.perm.one_def, one_mul] } } end lemma mem_of_mem_perms_of_list : ∀ {l : list α} {f : perm α}, f ∈ perms_of_list l → ∀ {x}, f x ≠ x → x ∈ l | [] f h := have f = 1 := by simpa [perms_of_list] using h, by rw this; simp | (a::l) f h := (mem_append.1 h).elim (λ h x hx, mem_cons_of_mem _ (mem_of_mem_perms_of_list h hx)) (λ h x hx, let ⟨y, hy, hy'⟩ := list.mem_bind.1 h in let ⟨g, hg₁, hg₂⟩ := list.mem_map.1 hy' in if hxa : x = a then by simp [hxa] else if hxy : x = y then mem_cons_of_mem _ $ by rwa hxy else mem_cons_of_mem _ $ mem_of_mem_perms_of_list hg₁ $ by rw [eq_inv_mul_iff_mul_eq.2 hg₂, mul_apply, swap_inv, swap_apply_def]; split_ifs; cc) lemma mem_perms_of_list_iff {l : list α} {f : perm α} : f ∈ perms_of_list l ↔ ∀ {x}, f x ≠ x → x ∈ l := ⟨mem_of_mem_perms_of_list, mem_perms_of_list_of_mem⟩ lemma nodup_perms_of_list : ∀ {l : list α} (hl : l.nodup), (perms_of_list l).nodup | [] hl := by simp [perms_of_list] | (a::l) hl := have hl' : l.nodup, from nodup_of_nodup_cons hl, have hln' : (perms_of_list l).nodup, from nodup_perms_of_list hl', have hmeml : ∀ {f : perm α}, f ∈ perms_of_list l → f a = a, from λ f hf, not_not.1 (mt (mem_of_mem_perms_of_list hf) (nodup_cons.1 hl).1), by rw [perms_of_list, list.nodup_append, list.nodup_bind, pairwise_iff_nth_le]; exact ⟨hln', ⟨λ _ _, nodup_map (λ _ _, mul_left_cancel) hln', λ i j hj hij x hx₁ hx₂, let ⟨f, hf⟩ := list.mem_map.1 hx₁ in let ⟨g, hg⟩ := list.mem_map.1 hx₂ in have hix : x a = nth_le l i (lt_trans hij hj), by rw [← hf.2, mul_apply, hmeml hf.1, swap_apply_left], have hiy : x a = nth_le l j hj, by rw [← hg.2, mul_apply, hmeml hg.1, swap_apply_left], absurd (hf.2.trans (hg.2.symm)) $ λ h, ne_of_lt hij $ nodup_iff_nth_le_inj.1 hl' i j (lt_trans hij hj) hj $ by rw [← hix, hiy]⟩, λ f hf₁ hf₂, let ⟨x, hx, hx'⟩ := list.mem_bind.1 hf₂ in let ⟨g, hg⟩ := list.mem_map.1 hx' in have hgxa : g⁻¹ x = a, from f.injective $ by rw [hmeml hf₁, ← hg.2]; simp, have hxa : x ≠ a, from λ h, (list.nodup_cons.1 hl).1 (h ▸ hx), (list.nodup_cons.1 hl).1 $ hgxa ▸ mem_of_mem_perms_of_list hg.1 (by rwa [apply_inv_self, hgxa])⟩ /-- Given a finset, produce the finset of all permutations of its elements. -/ def perms_of_finset (s : finset α) : finset (perm α) := quotient.hrec_on s.1 (λ l hl, ⟨perms_of_list l, nodup_perms_of_list hl⟩) (λ a b hab, hfunext (congr_arg _ (quotient.sound hab)) (λ ha hb _, heq_of_eq $ finset.ext $ by simp [mem_perms_of_list_iff, hab.mem_iff])) s.2 lemma mem_perms_of_finset_iff : ∀ {s : finset α} {f : perm α}, f ∈ perms_of_finset s ↔ ∀ {x}, f x ≠ x → x ∈ s := by rintros ⟨⟨l⟩, hs⟩ f; exact mem_perms_of_list_iff lemma card_perms_of_finset : ∀ (s : finset α), (perms_of_finset s).card = s.card! := by rintros ⟨⟨l⟩, hs⟩; exact length_perms_of_list l /-- The collection of permutations of a fintype is a fintype. -/ def fintype_perm [fintype α] : fintype (perm α) := ⟨perms_of_finset (@finset.univ α _), by simp [mem_perms_of_finset_iff]⟩ instance [fintype α] [fintype β] : fintype (α ≃ β) := if h : fintype.card β = fintype.card α then trunc.rec_on_subsingleton (fintype.equiv_fin α) (λ eα, trunc.rec_on_subsingleton (fintype.equiv_fin β) (λ eβ, @fintype.of_equiv _ (perm α) fintype_perm (equiv_congr (equiv.refl α) (eα.trans (eq.rec_on h eβ.symm)) : (α ≃ α) ≃ (α ≃ β)))) else ⟨∅, λ x, false.elim (h (fintype.card_eq.2 ⟨x.symm⟩))⟩ lemma fintype.card_perm [fintype α] : fintype.card (perm α) = (fintype.card α)! := subsingleton.elim (@fintype_perm α _ _) (@equiv.fintype α α _ _ _ _) ▸ card_perms_of_finset _ lemma fintype.card_equiv [fintype α] [fintype β] (e : α ≃ β) : fintype.card (α ≃ β) = (fintype.card α)! := fintype.card_congr (equiv_congr (equiv.refl α) e) ▸ fintype.card_perm lemma univ_eq_singleton_of_card_one {α} [fintype α] (x : α) (h : fintype.card α = 1) : (univ : finset α) = {x} := begin apply symm, apply eq_of_subset_of_card_le (subset_univ ({x})), apply le_of_eq, simp [h, finset.card_univ] end end equiv namespace fintype section choose open fintype open equiv variables [fintype α] (p : α → Prop) [decidable_pred p] /-- Given a fintype `α` and a predicate `p`, associate to a proof that there is a unique element of `α` satisfying `p` this unique element, as an element of the corresponding subtype. -/ def choose_x (hp : ∃! a : α, p a) : {a // p a} := ⟨finset.choose p univ (by simp; exact hp), finset.choose_property _ _ _⟩ /-- Given a fintype `α` and a predicate `p`, associate to a proof that there is a unique element of `α` satisfying `p` this unique element, as an element of `α`. -/ def choose (hp : ∃! a, p a) : α := choose_x p hp lemma choose_spec (hp : ∃! a, p a) : p (choose p hp) := (choose_x p hp).property end choose section bijection_inverse open function variables [fintype α] variables [decidable_eq β] variables {f : α → β} /-- ` `bij_inv f` is the unique inverse to a bijection `f`. This acts as a computable alternative to `function.inv_fun`. -/ def bij_inv (f_bij : bijective f) (b : β) : α := fintype.choose (λ a, f a = b) begin rcases f_bij.right b with ⟨a', fa_eq_b⟩, rw ← fa_eq_b, exact ⟨a', ⟨rfl, (λ a h, f_bij.left h)⟩⟩ end lemma left_inverse_bij_inv (f_bij : bijective f) : left_inverse (bij_inv f_bij) f := λ a, f_bij.left (choose_spec (λ a', f a' = f a) _) lemma right_inverse_bij_inv (f_bij : bijective f) : right_inverse (bij_inv f_bij) f := λ b, choose_spec (λ a', f a' = b) _ lemma bijective_bij_inv (f_bij : bijective f) : bijective (bij_inv f_bij) := ⟨(right_inverse_bij_inv _).injective, (left_inverse_bij_inv _).surjective⟩ end bijection_inverse lemma well_founded_of_trans_of_irrefl [fintype α] (r : α → α → Prop) [is_trans α r] [is_irrefl α r] : well_founded r := by classical; exact have ∀ x y, r x y → (univ.filter (λ z, r z x)).card < (univ.filter (λ z, r z y)).card, from λ x y hxy, finset.card_lt_card $ by simp only [finset.lt_iff_ssubset.symm, lt_iff_le_not_le, finset.le_iff_subset, finset.subset_iff, mem_filter, true_and, mem_univ, hxy]; exact ⟨λ z hzx, trans hzx hxy, not_forall_of_exists_not ⟨x, not_imp.2 ⟨hxy, irrefl x⟩⟩⟩, subrelation.wf this (measure_wf _) lemma preorder.well_founded [fintype α] [preorder α] : well_founded ((<) : α → α → Prop) := well_founded_of_trans_of_irrefl _ @[instance, priority 10] lemma linear_order.is_well_order [fintype α] [linear_order α] : is_well_order α (<) := { wf := preorder.well_founded } end fintype /-- A type is said to be infinite if it has no fintype instance. -/ class infinite (α : Type*) : Prop := (not_fintype : fintype α → false) @[simp] lemma not_nonempty_fintype {α : Type*} : ¬nonempty (fintype α) ↔ infinite α := ⟨λf, ⟨λ x, f ⟨x⟩⟩, λ⟨f⟩ ⟨x⟩, f x⟩ lemma finset.exists_minimal {α : Type*} [preorder α] (s : finset α) (h : s.nonempty) : ∃ m ∈ s, ∀ x ∈ s, ¬ (x < m) := begin obtain ⟨c, hcs : c ∈ s⟩ := h, have : well_founded (@has_lt.lt {x // x ∈ s} _) := fintype.well_founded_of_trans_of_irrefl _, obtain ⟨⟨m, hms : m ∈ s⟩, -, H⟩ := this.has_min set.univ ⟨⟨c, hcs⟩, trivial⟩, exact ⟨m, hms, λ x hx hxm, H ⟨x, hx⟩ trivial hxm⟩, end lemma finset.exists_maximal {α : Type*} [preorder α] (s : finset α) (h : s.nonempty) : ∃ m ∈ s, ∀ x ∈ s, ¬ (m < x) := @finset.exists_minimal (order_dual α) _ s h namespace infinite lemma exists_not_mem_finset [infinite α] (s : finset α) : ∃ x, x ∉ s := not_forall.1 $ λ h, not_fintype ⟨s, h⟩ @[priority 100] -- see Note [lower instance priority] instance (α : Type*) [H : infinite α] : nontrivial α := ⟨let ⟨x, hx⟩ := exists_not_mem_finset (∅ : finset α) in let ⟨y, hy⟩ := exists_not_mem_finset ({x} : finset α) in ⟨y, x, by simpa only [mem_singleton] using hy⟩⟩ lemma nonempty (α : Type*) [infinite α] : nonempty α := by apply_instance lemma of_injective [infinite β] (f : β → α) (hf : injective f) : infinite α := ⟨λ I, by exactI not_fintype (fintype.of_injective f hf)⟩ lemma of_surjective [infinite β] (f : α → β) (hf : surjective f) : infinite α := ⟨λ I, by classical; exactI not_fintype (fintype.of_surjective f hf)⟩ private noncomputable def nat_embedding_aux (α : Type*) [infinite α] : ℕ → α | n := by letI := classical.dec_eq α; exact classical.some (exists_not_mem_finset ((multiset.range n).pmap (λ m (hm : m < n), nat_embedding_aux m) (λ _, multiset.mem_range.1)).to_finset) private lemma nat_embedding_aux_injective (α : Type*) [infinite α] : function.injective (nat_embedding_aux α) := begin assume m n h, letI := classical.dec_eq α, wlog hmlen : m ≤ n using m n, by_contradiction hmn, have hmn : m < n, from lt_of_le_of_ne hmlen hmn, refine (classical.some_spec (exists_not_mem_finset ((multiset.range n).pmap (λ m (hm : m < n), nat_embedding_aux α m) (λ _, multiset.mem_range.1)).to_finset)) _, refine multiset.mem_to_finset.2 (multiset.mem_pmap.2 ⟨m, multiset.mem_range.2 hmn, _⟩), rw [h, nat_embedding_aux] end /-- Embedding of `ℕ` into an infinite type. -/ noncomputable def nat_embedding (α : Type*) [infinite α] : ℕ ↪ α := ⟨_, nat_embedding_aux_injective α⟩ lemma exists_subset_card_eq (α : Type*) [infinite α] (n : ℕ) : ∃ s : finset α, s.card = n := ⟨(range n).map (nat_embedding α), by rw [card_map, card_range]⟩ end infinite lemma not_injective_infinite_fintype [infinite α] [fintype β] (f : α → β) : ¬ injective f := assume (hf : injective f), have H : fintype α := fintype.of_injective f hf, infinite.not_fintype H /-- The pigeonhole principle for infinitely many pigeons in finitely many pigeonholes. If there are infinitely many pigeons in finitely many pigeonholes, then there are at least two pigeons in the same pigeonhole. See also: `fintype.exists_ne_map_eq_of_card_lt`, `fintype.exists_infinite_fiber`. -/ lemma fintype.exists_ne_map_eq_of_infinite [infinite α] [fintype β] (f : α → β) : ∃ x y : α, x ≠ y ∧ f x = f y := begin classical, by_contra hf, push_neg at hf, apply not_injective_infinite_fintype f, intros x y, contrapose, apply hf, end /-- The strong pigeonhole principle for infinitely many pigeons in finitely many pigeonholes. If there are infinitely many pigeons in finitely many pigeonholes, then there is a pigeonhole with infinitely many pigeons. See also: `fintype.exists_ne_map_eq_of_infinite` -/ lemma fintype.exists_infinite_fiber [infinite α] [fintype β] (f : α → β) : ∃ y : β, infinite (f ⁻¹' {y}) := begin classical, by_contra hf, push_neg at hf, haveI h' : ∀ (y : β), fintype (f ⁻¹' {y}) := begin intro y, specialize hf y, rw [←not_nonempty_fintype, not_not] at hf, exact classical.choice hf, end, let key : fintype α := { elems := univ.bind (λ (y : β), (f ⁻¹' {y}).to_finset), complete := by simp }, exact infinite.not_fintype key, end lemma not_surjective_fintype_infinite [fintype α] [infinite β] (f : α → β) : ¬ surjective f := assume (hf : surjective f), have H : infinite α := infinite.of_surjective f hf, @infinite.not_fintype _ H infer_instance instance nat.infinite : infinite ℕ := ⟨λ ⟨s, hs⟩, finset.not_mem_range_self $ s.subset_range_sup_succ (hs _)⟩ instance int.infinite : infinite ℤ := infinite.of_injective int.of_nat (λ _ _, int.of_nat.inj) section trunc /-- For `s : multiset α`, we can lift the existential statement that `∃ x, x ∈ s` to a `trunc α`. -/ def trunc_of_multiset_exists_mem {α} (s : multiset α) : (∃ x, x ∈ s) → trunc α := quotient.rec_on_subsingleton s $ λ l h, match l, h with | [], _ := false.elim (by tauto) | (a :: _), _ := trunc.mk a end /-- A `nonempty` `fintype` constructively contains an element. -/ def trunc_of_nonempty_fintype (α) [nonempty α] [fintype α] : trunc α := trunc_of_multiset_exists_mem finset.univ.val (by simp) /-- A `fintype` with positive cardinality constructively contains an element. -/ def trunc_of_card_pos {α} [fintype α] (h : 0 < fintype.card α) : trunc α := by { letI := (fintype.card_pos_iff.mp h), exact trunc_of_nonempty_fintype α } /-- By iterating over the elements of a fintype, we can lift an existential statement `∃ a, P a` to `trunc (Σ' a, P a)`, containing data. -/ def trunc_sigma_of_exists {α} [fintype α] {P : α → Prop} [decidable_pred P] (h : ∃ a, P a) : trunc (Σ' a, P a) := @trunc_of_nonempty_fintype (Σ' a, P a) (exists.elim h $ λ a ha, ⟨⟨a, ha⟩⟩) _ end trunc
86c3b7e3b65bfedb7a5a51fe8c97c89c2fd7452c
4a092885406df4e441e9bb9065d9405dacb94cd8
/src/for_mathlib/function.lean
0ea72b0346f235d89ae228cda4ea495d36e9883f
[ "Apache-2.0" ]
permissive
semorrison/lean-perfectoid-spaces
78c1572cedbfae9c3e460d8aaf91de38616904d8
bb4311dff45791170bcb1b6a983e2591bee88a19
refs/heads/master
1,588,841,765,494
1,554,805,620,000
1,554,805,620,000
180,353,546
0
1
null
1,554,809,880,000
1,554,809,880,000
null
UTF-8
Lean
false
false
375
lean
variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} def function.comp₂ (f : α → β → γ) (g : γ → δ) : α → β → δ := λ x y, g (f x y) notation g `∘₂` f := function.comp₂ f g lemma function.uncurry_comp₂ (f : α → β → γ) (g : γ → δ) : function.uncurry (g ∘₂ f) = (g ∘ function.uncurry f) := funext $ λ ⟨p, q⟩, rfl
1acdd7dd6da71b08d95bc80220ff4b274fee1da2
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/parity.lean
135a011afaed870e24c5c5b92b6be802e05480a3
[ "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
680
lean
import data.nat open nat algebra namespace foo inductive Parity : nat → Type := | even : ∀ n : nat, Parity (2 * n) | odd : ∀ n : nat, Parity (2 * n + 1) open Parity definition parity : Π (n : nat), Parity n | parity 0 := even 0 | parity (n+1) := begin have aux : Parity n, from parity n, cases aux with [k, k], begin apply (Parity.odd k) end, begin change (Parity (2*k + 2*1)), rewrite -left_distrib, apply (Parity.even (k+1)) end end print definition parity definition half (n : nat) : nat := match ⟨n, parity n⟩ with | ⟨⌞2 * k⌟, even k⟩ := k | ⟨⌞2 * k + 1⌟, odd k⟩ := k end end foo
04a1243616f7ec9bb99d164c7834472aa2e23c13
d1a52c3f208fa42c41df8278c3d280f075eb020c
/src/Lean/Elab/Match.lean
09310d752c7e697255a6e705b51372523b4ceb89
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
cipher1024/lean4
6e1f98bb58e7a92b28f5364eb38a14c8d0aae393
69114d3b50806264ef35b57394391c3e738a9822
refs/heads/master
1,642,227,983,603
1,642,011,696,000
1,642,011,696,000
228,607,691
0
0
Apache-2.0
1,576,584,269,000
1,576,584,268,000
null
UTF-8
Lean
false
false
46,199
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Util.CollectFVars import Lean.Meta.Match.MatchPatternAttr import Lean.Meta.Match.Match import Lean.Meta.SortLocalDecls import Lean.Meta.GeneralizeVars import Lean.Elab.SyntheticMVars import Lean.Elab.Arg import Lean.Parser.Term import Lean.Elab.PatternVar namespace Lean.Elab.Term open Meta open Lean.Parser.Term private def expandSimpleMatch (stx discr lhsVar rhs : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do let newStx ← `(let $lhsVar := $discr; $rhs) withMacroExpansion stx newStx <| elabTerm newStx expectedType? private def mkUserNameFor (e : Expr) : TermElabM Name := do match e with /- Remark: we use `mkFreshUserName` to make sure we don't add a variable to the local context that can be resolved to `e`. -/ | Expr.fvar fvarId _ => mkFreshUserName ((← getLocalDecl fvarId).userName) | _ => mkFreshBinderName /-- Return true iff `n` is an auxiliary variable created by `expandNonAtomicDiscrs?` -/ def isAuxDiscrName (n : Name) : Bool := n.hasMacroScopes && n.eraseMacroScopes == `_discr /-- We treat `@x` as atomic to avoid unnecessary extra local declarations from being inserted into the local context. Recall that `expandMatchAltsIntoMatch` uses `@` modifier. Thus this is kind of discriminant is quite common. Remark: if the discriminat is `Systax.missing`, we abort the elaboration of the `match`-expression. This can happen due to error recovery. Example ``` example : (p ∨ p) → p := fun h => match ``` If we don't abort, the elaborator loops because we will keep trying to expand ``` match ``` into ``` let d := <Syntax.missing>; match ``` Recall that `Syntax.setArg stx i arg` is a no-op when `i` is out-of-bounds. -/ def isAtomicDiscr? (discr : Syntax) : TermElabM (Option Expr) := do match discr with | `($x:ident) => isLocalIdent? x | `(@$x:ident) => isLocalIdent? x | _ => if discr.isMissing then throwAbortTerm else return none -- See expandNonAtomicDiscrs? private def elabAtomicDiscr (discr : Syntax) : TermElabM Expr := do let term := discr[1] match (← isAtomicDiscr? term) with | some e@(Expr.fvar fvarId _) => let localDecl ← getLocalDecl fvarId if !isAuxDiscrName localDecl.userName then addTermInfo discr e return e -- it is not an auxiliary local created by `expandNonAtomicDiscrs?` else instantiateMVars localDecl.value | _ => throwErrorAt discr "unexpected discriminant" structure ElabMatchTypeAndDiscrsResult where discrs : Array Expr matchType : Expr /- `true` when performing dependent elimination. We use this to decide whether we optimize the "match unit" case. See `isMatchUnit?`. -/ isDep : Bool alts : Array MatchAltView private partial def elabMatchTypeAndDiscrs (discrStxs : Array Syntax) (matchOptType : Syntax) (matchAltViews : Array MatchAltView) (expectedType : Expr) : TermElabM ElabMatchTypeAndDiscrsResult := do let numDiscrs := discrStxs.size if matchOptType.isNone then elabDiscrs 0 #[] else let matchTypeStx := matchOptType[0][1] let matchType ← elabType matchTypeStx let (discrs, isDep) ← elabDiscrsWitMatchType matchType expectedType return { discrs := discrs, matchType := matchType, isDep := isDep, alts := matchAltViews } where /- Easy case: elaborate discriminant when the match-type has been explicitly provided by the user. -/ elabDiscrsWitMatchType (matchType : Expr) (expectedType : Expr) : TermElabM (Array Expr × Bool) := do let mut discrs := #[] let mut i := 0 let mut matchType := matchType let mut isDep := false for discrStx in discrStxs do i := i + 1 matchType ← whnf matchType match matchType with | Expr.forallE _ d b _ => let discr ← fullApproxDefEq <| elabTermEnsuringType discrStx[1] d trace[Elab.match] "discr #{i} {discr} : {d}" if b.hasLooseBVars then isDep := true matchType ← b.instantiate1 discr discrs := discrs.push discr | _ => throwError "invalid type provided to match-expression, function type with arity #{discrStxs.size} expected" return (discrs, isDep) markIsDep (r : ElabMatchTypeAndDiscrsResult) := { r with isDep := true } /- Elaborate discriminants inferring the match-type -/ elabDiscrs (i : Nat) (discrs : Array Expr) : TermElabM ElabMatchTypeAndDiscrsResult := do if h : i < discrStxs.size then let discrStx := discrStxs.get ⟨i, h⟩ let discr ← elabAtomicDiscr discrStx let discr ← instantiateMVars discr let discrType ← inferType discr let discrType ← instantiateMVars discrType let discrs := discrs.push discr let userName ← mkUserNameFor discr if discrStx[0].isNone then let mut result ← elabDiscrs (i + 1) discrs let matchTypeBody ← kabstract result.matchType discr if matchTypeBody.hasLooseBVars then result := markIsDep result return { result with matchType := Lean.mkForall userName BinderInfo.default discrType matchTypeBody } else let discrs := discrs.push (← mkEqRefl discr) let result ← elabDiscrs (i + 1) discrs let result := markIsDep result let identStx := discrStx[0][0] withLocalDeclD userName discrType fun x => do let eqType ← mkEq discr x withLocalDeclD identStx.getId eqType fun h => do let matchTypeBody ← kabstract result.matchType discr let matchTypeBody := matchTypeBody.instantiate1 x let matchType ← mkForallFVars #[x, h] matchTypeBody return { result with matchType := matchType alts := result.alts.map fun altView => if i+1 > altView.patterns.size then -- Unexpected number of patterns. The input is invalid, but we want to process whatever to provide info to users. altView else { altView with patterns := altView.patterns.insertAt (i+1) identStx } } else return { discrs, alts := matchAltViews, isDep := false, matchType := expectedType } def expandMacrosInPatterns (matchAlts : Array MatchAltView) : MacroM (Array MatchAltView) := do matchAlts.mapM fun matchAlt => do let patterns ← matchAlt.patterns.mapM expandMacros pure { matchAlt with patterns := patterns } private def getMatchGeneralizing? : Syntax → Option Bool | `(match (generalizing := true) $discrs,* $[: $ty?]? with $alts:matchAlt*) => some true | `(match (generalizing := false) $discrs,* $[: $ty?]? with $alts:matchAlt*) => some false | _ => none /- Given `stx` a match-expression, return its alternatives. -/ private def getMatchAlts : Syntax → Array MatchAltView | `(match $[$gen]? $discrs,* $[: $ty?]? with $alts:matchAlt*) => alts.filterMap fun alt => match alt with | `(matchAltExpr| | $patterns,* => $rhs) => some { ref := alt, patterns := patterns, rhs := rhs } | _ => none | _ => #[] builtin_initialize Parser.registerBuiltinNodeKind `MVarWithIdKind /-- The elaboration function for `Syntax` created using `mkMVarSyntax`. It just converts the metavariable id wrapped by the Syntax into an `Expr`. -/ @[builtinTermElab MVarWithIdKind] def elabMVarWithIdKind : TermElab := fun stx expectedType? => return mkInaccessible <| mkMVar (getMVarSyntaxMVarId stx) @[builtinTermElab inaccessible] def elabInaccessible : TermElab := fun stx expectedType? => do let e ← elabTerm stx[1] expectedType? return mkInaccessible e open Lean.Elab.Term.Quotation in @[builtinQuotPrecheck Lean.Parser.Term.match] def precheckMatch : Precheck | `(match $[$discrs:term],* with $[| $[$patss],* => $rhss]*) => do discrs.forM precheck for (pats, rhs) in patss.zip rhss do let vars ← try getPatternsVars pats catch | _ => return -- can happen in case of pattern antiquotations Quotation.withNewLocals (getPatternVarNames vars) <| precheck rhs | _ => throwUnsupportedSyntax /- We convert the collected `PatternVar`s intro `PatternVarDecl` -/ inductive PatternVarDecl where /- For `anonymousVar`, we create both a metavariable and a free variable. The free variable is used as an assignment for the metavariable when it is not assigned during pattern elaboration. -/ | anonymousVar (mvarId : MVarId) (fvarId : FVarId) | localVar (fvarId : FVarId) private partial def withPatternVars {α} (pVars : Array PatternVar) (k : Array PatternVarDecl → TermElabM α) : TermElabM α := let rec loop (i : Nat) (decls : Array PatternVarDecl) := do if h : i < pVars.size then match pVars.get ⟨i, h⟩ with | PatternVar.anonymousVar mvarId => let type ← mkFreshTypeMVar let userName ← mkFreshBinderName withLocalDecl userName BinderInfo.default type fun x => loop (i+1) (decls.push (PatternVarDecl.anonymousVar mvarId x.fvarId!)) | PatternVar.localVar userName => let type ← mkFreshTypeMVar withLocalDecl userName BinderInfo.default type fun x => loop (i+1) (decls.push (PatternVarDecl.localVar x.fvarId!)) else /- We must create the metavariables for `PatternVar.anonymousVar` AFTER we create the new local decls using `withLocalDecl`. Reason: their scope must include the new local decls since some of them are assigned by typing constraints. -/ decls.forM fun decl => match decl with | PatternVarDecl.anonymousVar mvarId fvarId => do let type ← inferType (mkFVar fvarId) discard <| mkFreshExprMVarWithId mvarId type | _ => pure () k decls loop 0 #[] /- Remark: when performing dependent pattern matching, we often had to write code such as ```lean def Vec.map' (f : α → β) (xs : Vec α n) : Vec β n := match n, xs with | _, nil => nil | _, cons a as => cons (f a) (map' f as) ``` We had to include `n` and the `_`s because the type of `xs` depends on `n`. Moreover, `nil` and `cons a as` have different types. This was quite tedious. So, we have implemented an automatic "discriminant refinement procedure". The procedure is based on the observation that we get a type error whenenver we forget to include `_`s and the indices a discriminant depends on. So, we catch the exception, check whether the type of the discriminant is an indexed family, and add their indices as new discriminants. The current implementation, adds indices as they are found, and does not try to "sort" the new discriminants. If the refinement process fails, we report the original error message. -/ /- Auxiliary structure for storing an type mismatch exception when processing the pattern #`idx` of some alternative. -/ structure PatternElabException where ex : Exception patternIdx : Nat -- Discriminant that sh pathToIndex : List Nat -- Path to the problematic inductive type index that produced the type mismatch /-- This method is part of the "discriminant refinement" procedure. It in invoked when the type of the `pattern` does not match the expected type. The expected type is based on the motive computed using the `match` discriminants. It tries to compute a path to an index of the discriminant type. For example, suppose the user has written ``` inductive Mem (a : α) : List α → Prop where | head {as} : Mem a (a::as) | tail {as} : Mem a as → Mem a (a'::as) infix:50 " ∈ " => Mem example (a b : Nat) (h : a ∈ [b]) : b = a := match h with | Mem.head => rfl ``` The motive for the match is `a ∈ [b] → b = a`, and get a type mismatch between the type of `Mem.head` and `a ∈ [b]`. This procedure return the path `[2, 1]` to the index `b`. We use it to produce the following refinement ``` example (a b : Nat) (h : a ∈ [b]) : b = a := match b, h with | _, Mem.head => rfl ``` which produces the new motive `(x : Nat) → a ∈ [x] → x = a` After this refinement step, the `match` is elaborated successfully. This method relies on the fact that the dependent pattern matcher compiler solves equations between indices of indexed inductive families. The following kinds of equations are supported by this compiler: - `x = t` - `t = x` - `ctor ... = ctor ...` where `x` is a free variable, `t` is an arbitrary term, and `ctor` is constructor. Our procedure ensures that "information" is not lost, and will *not* succeed in an example such as ``` example (a b : Nat) (f : Nat → Nat) (h : f a ∈ [f b]) : f b = f a := match h with | Mem.head => rfl ``` and will not add `f b` as a new discriminant. We may add an option in the future to enable this more liberal form of refinement. -/ private partial def findDiscrRefinementPath (pattern : Expr) (expected : Expr) : OptionT MetaM (List Nat) := do goType (← instantiateMVars (← inferType pattern)) expected where checkCompatibleApps (t d : Expr) : OptionT MetaM Unit := do guard d.isApp guard <| t.getAppNumArgs == d.getAppNumArgs let tFn := t.getAppFn let dFn := d.getAppFn guard <| tFn.isConst && dFn.isConst guard (← isDefEq tFn dFn) -- Visitor for inductive types goType (t d : Expr) : OptionT MetaM (List Nat) := do trace[Meta.debug] "type {t} =?= {d}" let t ← whnf t let d ← whnf d checkCompatibleApps t d matchConstInduct t.getAppFn (fun _ => failure) fun info _ => do let tArgs := t.getAppArgs let dArgs := d.getAppArgs for i in [:info.numParams] do let tArg := tArgs[i] let dArg := dArgs[i] unless (← isDefEq tArg dArg) do return i :: (← goType tArg dArg) for i in [info.numParams : tArgs.size] do let tArg := tArgs[i] let dArg := dArgs[i] unless (← isDefEq tArg dArg) do return i :: (← goIndex tArg dArg) failure -- Visitor for indexed families goIndex (t d : Expr) : OptionT MetaM (List Nat) := do let t ← whnfD t let d ← whnfD d if t.isFVar || d.isFVar then return [] -- Found refinement path else trace[Meta.debug] "index {t} =?= {d}" checkCompatibleApps t d matchConstCtor t.getAppFn (fun _ => failure) fun info _ => do let tArgs := t.getAppArgs let dArgs := d.getAppArgs for i in [:info.numParams] do let tArg := tArgs[i] let dArg := dArgs[i] unless (← isDefEq tArg dArg) do failure for i in [info.numParams : tArgs.size] do let tArg := tArgs[i] let dArg := dArgs[i] unless (← isDefEq tArg dArg) do return i :: (← goIndex tArg dArg) failure private partial def eraseIndices (type : Expr) : MetaM Expr := do let type' ← whnfD type matchConstInduct type'.getAppFn (fun _ => return type) fun info _ => do let args := type'.getAppArgs let params ← args[:info.numParams].toArray.mapM eraseIndices let result := mkAppN type'.getAppFn params let resultType ← inferType result let (newIndices, _, _) ← forallMetaTelescopeReducing resultType (some (args.size - info.numParams)) return mkAppN result newIndices private def elabPatterns (patternStxs : Array Syntax) (matchType : Expr) : ExceptT PatternElabException TermElabM (Array Expr × Expr) := withReader (fun ctx => { ctx with implicitLambda := false }) do let mut patterns := #[] let mut matchType := matchType for idx in [:patternStxs.size] do let patternStx := patternStxs[idx] matchType ← whnf matchType match matchType with | Expr.forallE _ d b _ => let pattern ← do let s ← saveState try liftM <| withSynthesize <| withoutErrToSorry <| elabTermEnsuringType patternStx d catch ex : Exception => restoreState s match (← liftM <| commitIfNoErrors? <| withoutErrToSorry do elabTermAndSynthesize patternStx (← eraseIndices d)) with | some pattern => match (← findDiscrRefinementPath pattern d |>.run) with | some path => trace[Meta.debug] "refinement path: {path}" restoreState s -- Wrap the type mismatch exception for the "discriminant refinement" feature. throwThe PatternElabException { ex := ex, patternIdx := idx, pathToIndex := path } | none => restoreState s; throw ex | none => throw ex matchType := b.instantiate1 pattern patterns := patterns.push pattern | _ => throwError "unexpected match type" return (patterns, matchType) def finalizePatternDecls (patternVarDecls : Array PatternVarDecl) : TermElabM (Array LocalDecl) := do let mut decls := #[] for pdecl in patternVarDecls do match pdecl with | PatternVarDecl.localVar fvarId => let decl ← getLocalDecl fvarId let decl ← instantiateLocalDeclMVars decl decls := decls.push decl | PatternVarDecl.anonymousVar mvarId fvarId => let e ← instantiateMVars (mkMVar mvarId); trace[Elab.match] "finalizePatternDecls: mvarId: {mvarId.name} := {e}, fvar: {mkFVar fvarId}" match e with | Expr.mvar newMVarId _ => /- Metavariable was not assigned, or assigned to another metavariable. So, we assign to the auxiliary free variable we created at `withPatternVars` to `newMVarId`. -/ assignExprMVar newMVarId (mkFVar fvarId) trace[Elab.match] "finalizePatternDecls: {mkMVar newMVarId} := {mkFVar fvarId}" let decl ← getLocalDecl fvarId let decl ← instantiateLocalDeclMVars decl decls := decls.push decl | _ => pure () /- We perform a topological sort (dependecies) on `decls` because the pattern elaboration process may produce a sequence where a declaration d₁ may occur after d₂ when d₂ depends on d₁. -/ sortLocalDecls decls open Meta.Match (Pattern Pattern.var Pattern.inaccessible Pattern.ctor Pattern.as Pattern.val Pattern.arrayLit AltLHS MatcherResult) namespace ToDepElimPattern structure State where found : FVarIdSet := {} localDecls : Array LocalDecl newLocals : FVarIdSet := {} abbrev M := StateRefT State TermElabM private def alreadyVisited (fvarId : FVarId) : M Bool := do let s ← get return s.found.contains fvarId private def markAsVisited (fvarId : FVarId) : M Unit := modify fun s => { s with found := s.found.insert fvarId } private def throwInvalidPattern {α} (e : Expr) : M α := throwError "invalid pattern {indentExpr e}" /- Create a new LocalDecl `x` for the metavariable `mvar`, and return `Pattern.var x` -/ private def mkLocalDeclFor (mvar : Expr) : M Pattern := do let mvarId := mvar.mvarId! let s ← get match (← getExprMVarAssignment? mvarId) with | some val => return Pattern.inaccessible val | none => let fvarId ← mkFreshFVarId let type ← inferType mvar /- HACK: `fvarId` is not in the scope of `mvarId` If this generates problems in the future, we should update the metavariable declarations. -/ assignExprMVar mvarId (mkFVar fvarId) let userName ← mkFreshBinderName let newDecl := LocalDecl.cdecl arbitrary fvarId userName type BinderInfo.default; modify fun s => { s with newLocals := s.newLocals.insert fvarId, localDecls := match s.localDecls.findIdx? fun decl => mvar.occurs decl.type with | none => s.localDecls.push newDecl -- None of the existing declarations depend on `mvar` | some i => s.localDecls.insertAt i newDecl } return Pattern.var fvarId partial def main (e : Expr) : M Pattern := do let isLocalDecl (fvarId : FVarId) : M Bool := do return (← get).localDecls.any fun d => d.fvarId == fvarId let mkPatternVar (fvarId : FVarId) (e : Expr) : M Pattern := do if (← alreadyVisited fvarId) then return Pattern.inaccessible e else markAsVisited fvarId return Pattern.var e.fvarId! let mkInaccessible (e : Expr) : M Pattern := do match e with | Expr.fvar fvarId _ => if (← isLocalDecl fvarId) then mkPatternVar fvarId e else return Pattern.inaccessible e | _ => return Pattern.inaccessible e match inaccessible? e with | some t => mkInaccessible t | none => match e.arrayLit? with | some (α, lits) => return Pattern.arrayLit α (← lits.mapM main) | none => if e.isAppOfArity `namedPattern 3 then let p ← main <| e.getArg! 2 match e.getArg! 1 with | Expr.fvar fvarId _ => return Pattern.as fvarId p | _ => throwError "unexpected occurrence of auxiliary declaration 'namedPattern'" else if isMatchValue e then return Pattern.val e else if e.isFVar then let fvarId := e.fvarId! unless (← isLocalDecl fvarId) do throwInvalidPattern e mkPatternVar fvarId e else if e.isMVar then mkLocalDeclFor e else let newE ← whnf e if newE != e then main newE else matchConstCtor e.getAppFn (fun _ => do if (← isProof e) then /- We mark nested proofs as inaccessible. This is fine due to proof irrelevance. We need this feature to be able to elaborate definitions such as: ``` def f : Fin 2 → Nat | 0 => 5 | 1 => 45 ``` -/ return Pattern.inaccessible e else throwInvalidPattern e) (fun v us => do let args := e.getAppArgs unless args.size == v.numParams + v.numFields do throwInvalidPattern e let params := args.extract 0 v.numParams let fields := args.extract v.numParams args.size let fields ← fields.mapM main return Pattern.ctor v.name us params.toList fields.toList) end ToDepElimPattern def withDepElimPatterns {α} (localDecls : Array LocalDecl) (ps : Array Expr) (k : Array LocalDecl → Array Pattern → TermElabM α) : TermElabM α := do let (patterns, s) ← (ps.mapM ToDepElimPattern.main).run { localDecls := localDecls } let localDecls ← s.localDecls.mapM fun d => instantiateLocalDeclMVars d /- toDepElimPatterns may have added new localDecls. Thus, we must update the local context before we execute `k` -/ let lctx ← getLCtx let lctx := localDecls.foldl (fun (lctx : LocalContext) d => lctx.erase d.fvarId) lctx let lctx := localDecls.foldl (fun (lctx : LocalContext) d => lctx.addDecl d) lctx withTheReader Meta.Context (fun ctx => { ctx with lctx := lctx }) do k localDecls patterns private def withElaboratedLHS {α} (ref : Syntax) (patternVarDecls : Array PatternVarDecl) (patternStxs : Array Syntax) (matchType : Expr) (k : AltLHS → Expr → TermElabM α) : ExceptT PatternElabException TermElabM α := do let (patterns, matchType) ← withSynthesize <| elabPatterns patternStxs matchType id (α := TermElabM α) do let localDecls ← finalizePatternDecls patternVarDecls let patterns ← patterns.mapM (instantiateMVars ·) withDepElimPatterns localDecls patterns fun localDecls patterns => k { ref := ref, fvarDecls := localDecls.toList, patterns := patterns.toList } matchType private def elabMatchAltView (alt : MatchAltView) (matchType : Expr) : ExceptT PatternElabException TermElabM (AltLHS × Expr) := withRef alt.ref do let (patternVars, alt) ← collectPatternVars alt trace[Elab.match] "patternVars: {patternVars}" withPatternVars patternVars fun patternVarDecls => do withElaboratedLHS alt.ref patternVarDecls alt.patterns matchType fun altLHS matchType => do let rhs ← elabTermEnsuringType alt.rhs matchType let xs := altLHS.fvarDecls.toArray.map LocalDecl.toExpr let rhs ← if xs.isEmpty then pure <| mkSimpleThunk rhs else mkLambdaFVars xs rhs trace[Elab.match] "rhs: {rhs}" return (altLHS, rhs) /-- Collect problematic index for the "discriminant refinement feature". This method is invoked when we detect a type mismatch at a pattern #`idx` of some alternative. -/ private partial def getIndexToInclude? (discr : Expr) (pathToIndex : List Nat) : TermElabM (Option Expr) := do go (← inferType discr) pathToIndex |>.run where go (e : Expr) (path : List Nat) : OptionT MetaM Expr := do match path with | [] => return e | i::path => let e ← whnfD e guard <| e.isApp && i < e.getAppNumArgs go (e.getArg! i) path /-- "Generalize" variables that depend on the discriminants. Remarks and limitations: - If `matchType` is a proposition, then we generalize even when the user did not provide `(generalizing := true)`. Motivation: users should have control about the actual `match`-expressions in their programs. - We currently do not generalize let-decls. - We abort generalization if the new `matchType` is type incorrect. - Only discriminants that are free variables are considered during specialization. - We "generalize" by adding new discriminants and pattern variables. We do not "clear" the generalized variables, but they become inaccessible since they are shadowed by the patterns variables. We assume this is ok since this is the exact behavior users would get if they had written it by hand. Recall there is no `clear` in term mode. -/ private def generalize (discrs : Array Expr) (matchType : Expr) (altViews : Array MatchAltView) (generalizing? : Option Bool) : TermElabM (Array Expr × Expr × Array MatchAltView × Bool) := do let gen ← match generalizing? with | some g => pure g | _ => isProp matchType if !gen then return (discrs, matchType, altViews, false) else let ysFVarIds ← getFVarsToGeneralize discrs /- let-decls are currently being ignored by the generalizer. -/ let ysFVarIds ← ysFVarIds.filterM fun fvarId => return !(← getLocalDecl fvarId).isLet if ysFVarIds.isEmpty then return (discrs, matchType, altViews, false) else let ys := ysFVarIds.map mkFVar -- trace[Meta.debug] "ys: {ys}, discrs: {discrs}" let matchType' ← forallBoundedTelescope matchType discrs.size fun ds type => do let type ← mkForallFVars ys type let (discrs', ds') := Array.unzip <| Array.zip discrs ds |>.filter fun (di, d) => di.isFVar let type := type.replaceFVars discrs' ds' mkForallFVars ds type -- trace[Meta.debug] "matchType': {matchType'}" if (← isTypeCorrect matchType') then let discrs := discrs ++ ys let altViews ← altViews.mapM fun altView => do let patternVars ← getPatternsVars altView.patterns -- We traverse backwards because we want to keep the most recent names. -- For example, if `ys` contains `#[h, h]`, we want to make sure `mkFreshUsername is applied to the first `h`, -- since it is already shadowed by the second. let ysUserNames ← ys.foldrM (init := #[]) fun ys ysUserNames => do let yDecl ← getLocalDecl ys.fvarId! let mut yUserName := yDecl.userName if ysUserNames.contains yUserName then yUserName ← mkFreshUserName yUserName -- Explicitly provided pattern variables shadow `y` else if patternVars.any fun | PatternVar.localVar x => x == yUserName | _ => false then yUserName ← mkFreshUserName yUserName return ysUserNames.push yUserName let ysIds ← ysUserNames.reverse.mapM fun n => return mkIdentFrom (← getRef) n return { altView with patterns := altView.patterns ++ ysIds } return (discrs, matchType', altViews, true) else return (discrs, matchType, altViews, true) private partial def elabMatchAltViews (generalizing? : Option Bool) (discrs : Array Expr) (matchType : Expr) (altViews : Array MatchAltView) : TermElabM (Array Expr × Expr × Array (AltLHS × Expr) × Bool) := do loop discrs matchType altViews none where /- "Discriminant refinement" main loop. `first?` contains the first error message we found before updated the `discrs`. -/ loop (discrs : Array Expr) (matchType : Expr) (altViews : Array MatchAltView) (first? : Option (SavedState × Exception)) : TermElabM (Array Expr × Expr × Array (AltLHS × Expr) × Bool) := do let s ← saveState let (discrs', matchType', altViews', refined) ← generalize discrs matchType altViews generalizing? match (← altViews'.mapM (fun altView => elabMatchAltView altView matchType') |>.run) with | Except.ok alts => return (discrs', matchType', alts, first?.isSome || refined) | Except.error { patternIdx := patternIdx, pathToIndex := pathToIndex, ex := ex } => trace[Meta.debug] "pathToIndex: {toString pathToIndex}" let some index ← getIndexToInclude? discrs[patternIdx] pathToIndex | throwEx (← updateFirst first? ex) trace[Meta.debug] "index: {index}" if (← discrs.anyM fun discr => isDefEq discr index) then throwEx (← updateFirst first? ex) let first ← updateFirst first? ex s.restore let indices ← collectDeps #[index] discrs let matchType ← try updateMatchType indices matchType catch ex => throwEx first let altViews ← addWildcardPatterns indices.size altViews let discrs := indices ++ discrs loop discrs matchType altViews first throwEx {α} (p : SavedState × Exception) : TermElabM α := do p.1.restore; throw p.2 updateFirst (first? : Option (SavedState × Exception)) (ex : Exception) : TermElabM (SavedState × Exception) := do match first? with | none => return (← saveState, ex) | some first => return first containsFVar (es : Array Expr) (fvarId : FVarId) : Bool := es.any fun e => e.isFVar && e.fvarId! == fvarId /- Update `indices` by including any free variable `x` s.t. - Type of some `discr` depends on `x`. - Type of `x` depends on some free variable in `indices`. If we don't include these extra variables in indices, then `updateMatchType` will generate a type incorrect term. For example, suppose `discr` contains `h : @HEq α a α b`, and `indices` is `#[α, b]`, and `matchType` is `@HEq α a α b → B`. `updateMatchType indices matchType` produces the type `(α' : Type) → (b : α') → @HEq α' a α' b → B` which is type incorrect because we have `a : α`. The method `collectDeps` will include `a` into `indices`. This method does not handle dependencies among non-free variables. We rely on the type checking method `check` at `updateMatchType`. Remark: `indices : Array Expr` does not need to be an array anymore. We should cleanup this code, and use `index : Expr` instead. -/ collectDeps (indices : Array Expr) (discrs : Array Expr) : TermElabM (Array Expr) := do let mut s : CollectFVars.State := {} for discr in discrs do s := collectFVars s (← instantiateMVars (← inferType discr)) let (indicesFVar, indicesNonFVar) := indices.split Expr.isFVar let indicesFVar := indicesFVar.map Expr.fvarId! let mut toAdd := #[] for fvarId in s.fvarSet.toList do unless containsFVar discrs fvarId || containsFVar indices fvarId do let localDecl ← getLocalDecl fvarId let mctx ← getMCtx for indexFVarId in indicesFVar do if mctx.localDeclDependsOn localDecl indexFVarId then toAdd := toAdd.push fvarId let indicesFVar ← sortFVarIds (indicesFVar ++ toAdd) return indicesFVar.map mkFVar ++ indicesNonFVar updateMatchType (indices : Array Expr) (matchType : Expr) : TermElabM Expr := do let matchType ← indices.foldrM (init := matchType) fun index matchType => do let indexType ← inferType index let matchTypeBody ← kabstract matchType index let userName ← mkUserNameFor index return Lean.mkForall userName BinderInfo.default indexType matchTypeBody check matchType return matchType addWildcardPatterns (num : Nat) (altViews : Array MatchAltView) : TermElabM (Array MatchAltView) := do let hole := mkHole (← getRef) let wildcards := mkArray num hole return altViews.map fun altView => { altView with patterns := wildcards ++ altView.patterns } def mkMatcher (input : Meta.Match.MkMatcherInput) : TermElabM MatcherResult := Meta.Match.mkMatcher input register_builtin_option match.ignoreUnusedAlts : Bool := { defValue := false descr := "if true, do not generate error if an alternative is not used" } def reportMatcherResultErrors (altLHSS : List AltLHS) (result : MatcherResult) : TermElabM Unit := do unless result.counterExamples.isEmpty do withHeadRefOnly <| logError m!"missing cases:\n{Meta.Match.counterExamplesToMessageData result.counterExamples}" unless match.ignoreUnusedAlts.get (← getOptions) || result.unusedAltIdxs.isEmpty do let mut i := 0 for alt in altLHSS do if result.unusedAltIdxs.contains i then withRef alt.ref do logError "redundant alternative" i := i + 1 /-- If `altLHSS + rhss` is encoding `| PUnit.unit => rhs[0]`, return `rhs[0]` Otherwise, return none. -/ private def isMatchUnit? (altLHSS : List Match.AltLHS) (rhss : Array Expr) : MetaM (Option Expr) := do assert! altLHSS.length == rhss.size match altLHSS with | [ { fvarDecls := [], patterns := [ Pattern.ctor `PUnit.unit .. ], .. } ] => /- Recall that for alternatives of the form `| PUnit.unit => rhs`, `rhss[0]` is of the form `fun _ : Unit => b`. -/ match rhss[0] with | Expr.lam _ _ b _ => return if b.hasLooseBVars then none else b | _ => return none | _ => return none private def elabMatchAux (generalizing? : Option Bool) (discrStxs : Array Syntax) (altViews : Array MatchAltView) (matchOptType : Syntax) (expectedType : Expr) : TermElabM Expr := do let mut generalizing? := generalizing? if !matchOptType.isNone then if generalizing? == some true then throwError "the '(generalizing := true)' parameter is not supported when the 'match' type is explicitly provided" generalizing? := some false let (discrs, matchType, altLHSS, isDep, rhss) ← commitIfDidNotPostpone do let ⟨discrs, matchType, isDep, altViews⟩ ← elabMatchTypeAndDiscrs discrStxs matchOptType altViews expectedType let matchAlts ← liftMacroM <| expandMacrosInPatterns altViews trace[Elab.match] "matchType: {matchType}" let (discrs, matchType, alts, refined) ← elabMatchAltViews generalizing? discrs matchType matchAlts let isDep := isDep || refined /- We should not use `synthesizeSyntheticMVarsNoPostponing` here. Otherwise, we will not be able to elaborate examples such as: ``` def f (x : Nat) : Option Nat := none def g (xs : List (Nat × Nat)) : IO Unit := xs.forM fun x => match f x.fst with | _ => pure () ``` If `synthesizeSyntheticMVarsNoPostponing`, the example above fails at `x.fst` because the type of `x` is only available after we proces the last argument of `List.forM`. We apply pending default types to make sure we can process examples such as ``` let (a, b) := (0, 0) ``` -/ synthesizeSyntheticMVarsUsingDefault let rhss := alts.map Prod.snd let matchType ← instantiateMVars matchType let altLHSS ← alts.toList.mapM fun alt => do let altLHS ← Match.instantiateAltLHSMVars alt.1 /- Remark: we try to postpone before throwing an error. The combinator `commitIfDidNotPostpone` ensures we backtrack any updates that have been performed. The quick-check `waitExpectedTypeAndDiscrs` minimizes the number of scenarios where we have to postpone here. Here is an example that passes the `waitExpectedTypeAndDiscrs` test, but postpones here. ``` def bad (ps : Array (Nat × Nat)) : Array (Nat × Nat) := (ps.filter fun (p : Prod _ _) => match p with | (x, y) => x == 0) ++ ps ``` When we try to elaborate `fun (p : Prod _ _) => ...` for the first time, we haven't propagated the type of `ps` yet because `Array.filter` has type `{α : Type u_1} → (α → Bool) → (as : Array α) → optParam Nat 0 → optParam Nat (Array.size as) → Array α` However, the partial type annotation `(p : Prod _ _)` makes sure we succeed at the quick-check `waitExpectedTypeAndDiscrs`. -/ withRef altLHS.ref do for d in altLHS.fvarDecls do if d.hasExprMVar then withExistingLocalDecls altLHS.fvarDecls do tryPostpone throwMVarError m!"invalid match-expression, type of pattern variable '{d.toExpr}' contains metavariables{indentExpr d.type}" for p in altLHS.patterns do if p.hasExprMVar then withExistingLocalDecls altLHS.fvarDecls do tryPostpone throwMVarError m!"invalid match-expression, pattern contains metavariables{indentExpr (← p.toExpr)}" pure altLHS return (discrs, matchType, altLHSS, isDep, rhss) if let some r ← if isDep then pure none else isMatchUnit? altLHSS rhss then return r else let numDiscrs := discrs.size let matcherName ← mkAuxName `match let matcherResult ← mkMatcher { matcherName, matchType, numDiscrs, lhss := altLHSS } matcherResult.addMatcher let motive ← forallBoundedTelescope matchType numDiscrs fun xs matchType => mkLambdaFVars xs matchType reportMatcherResultErrors altLHSS matcherResult let r := mkApp matcherResult.matcher motive let r := mkAppN r discrs let r := mkAppN r rhss trace[Elab.match] "result: {r}" return r private def getDiscrs (matchStx : Syntax) : Array Syntax := matchStx[2].getSepArgs private def getMatchOptType (matchStx : Syntax) : Syntax := matchStx[3] private def expandNonAtomicDiscrs? (matchStx : Syntax) : TermElabM (Option Syntax) := let matchOptType := getMatchOptType matchStx; if matchOptType.isNone then do let discrs := getDiscrs matchStx; let allLocal ← discrs.allM fun discr => Option.isSome <$> isAtomicDiscr? discr[1] if allLocal then return none else -- We use `foundFVars` to make sure the discriminants are distinct variables. -- See: code for computing "matchType" at `elabMatchTypeAndDiscrs` let rec loop (discrs : List Syntax) (discrsNew : Array Syntax) (foundFVars : FVarIdSet) := do match discrs with | [] => let discrs := Syntax.mkSep discrsNew (mkAtomFrom matchStx ", "); pure (matchStx.setArg 2 discrs) | discr :: discrs => -- Recall that -- matchDiscr := leading_parser optional (ident >> ":") >> termParser let term := discr[1] let addAux : TermElabM Syntax := withFreshMacroScope do let d ← `(_discr); unless isAuxDiscrName d.getId do -- Use assertion? throwError "unexpected internal auxiliary discriminant name" let discrNew := discr.setArg 1 d; let r ← loop discrs (discrsNew.push discrNew) foundFVars `(let _discr := $term; $r) match (← isAtomicDiscr? term) with | some x => if x.isFVar then loop discrs (discrsNew.push discr) (foundFVars.insert x.fvarId!) else addAux | none => addAux return some (← loop discrs.toList #[] {}) else -- We do not pull non atomic discriminants when match type is provided explicitly by the user return none private def waitExpectedType (expectedType? : Option Expr) : TermElabM Expr := do tryPostponeIfNoneOrMVar expectedType? match expectedType? with | some expectedType => pure expectedType | none => mkFreshTypeMVar private def tryPostponeIfDiscrTypeIsMVar (matchStx : Syntax) : TermElabM Unit := do -- We don't wait for the discriminants types when match type is provided by user if getMatchOptType matchStx |>.isNone then let discrs := getDiscrs matchStx for discr in discrs do let term := discr[1] match (← isAtomicDiscr? term) with | none => throwErrorAt discr "unexpected discriminant" -- see `expandNonAtomicDiscrs? | some d => let dType ← inferType d trace[Elab.match] "discr {d} : {dType}" tryPostponeIfMVar dType /- We (try to) elaborate a `match` only when the expected type is available. If the `matchType` has not been provided by the user, we also try to postpone elaboration if the type of a discriminant is not available. That is, it is of the form `(?m ...)`. We use `expandNonAtomicDiscrs?` to make sure all discriminants are local variables. This is a standard trick we use in the elaborator, and it is also used to elaborate structure instances. Suppose, we are trying to elaborate ``` match g x with | ... => ... ``` `expandNonAtomicDiscrs?` converts it intro ``` let _discr := g x match _discr with | ... => ... ``` Thus, at `tryPostponeIfDiscrTypeIsMVar` we only need to check whether the type of `_discr` is not of the form `(?m ...)`. Note that, the auxiliary variable `_discr` is expanded at `elabAtomicDiscr`. This elaboration technique is needed to elaborate terms such as: ```lean xs.filter fun (a, b) => a > b ``` which are syntax sugar for ```lean List.filter (fun p => match p with | (a, b) => a > b) xs ``` When we visit `match p with | (a, b) => a > b`, we don't know the type of `p` yet. -/ private def waitExpectedTypeAndDiscrs (matchStx : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do tryPostponeIfNoneOrMVar expectedType? tryPostponeIfDiscrTypeIsMVar matchStx match expectedType? with | some expectedType => return expectedType | none => mkFreshTypeMVar /- ``` leading_parser:leadPrec "match " >> sepBy1 matchDiscr ", " >> optType >> " with " >> matchAlts ``` Remark the `optIdent` must be `none` at `matchDiscr`. They are expanded by `expandMatchDiscr?`. -/ private def elabMatchCore (stx : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do let expectedType ← waitExpectedTypeAndDiscrs stx expectedType? let discrStxs := (getDiscrs stx).map fun d => d let gen? := getMatchGeneralizing? stx let altViews := getMatchAlts stx let matchOptType := getMatchOptType stx elabMatchAux gen? discrStxs altViews matchOptType expectedType private def isPatternVar (stx : Syntax) : TermElabM Bool := do match (← resolveId? stx "pattern") with | none => isAtomicIdent stx | some f => match f with | Expr.const fName _ _ => match (← getEnv).find? fName with | some (ConstantInfo.ctorInfo _) => return false | some _ => return !hasMatchPatternAttribute (← getEnv) fName | _ => isAtomicIdent stx | _ => isAtomicIdent stx where isAtomicIdent (stx : Syntax) : Bool := stx.isIdent && stx.getId.eraseMacroScopes.isAtomic -- leading_parser "match " >> sepBy1 termParser ", " >> optType >> " with " >> matchAlts /-- Pattern matching. `match e, ... with | p, ... => f | ...` matches each given term `e` against each pattern `p` of a match alternative. When all patterns of an alternative match, the `match` term evaluates to the value of the corresponding right-hand side `f` with the pattern variables bound to the respective matched values. When not constructing a proof, `match` does not automatically substitute variables matched on in dependent variables' types. Use `match (generalizing := true) ...` to enforce this. -/ @[builtinTermElab «match»] def elabMatch : TermElab := fun stx expectedType? => do match stx with | `(match $discr:term with | $y:ident => $rhs:term) => if (← isPatternVar y) then expandSimpleMatch stx discr y rhs expectedType? else elabMatchDefault stx expectedType? | _ => elabMatchDefault stx expectedType? where elabMatchDefault (stx : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do match (← expandNonAtomicDiscrs? stx) with | some stxNew => withMacroExpansion stx stxNew <| elabTerm stxNew expectedType? | none => let discrs := getDiscrs stx; let matchOptType := getMatchOptType stx; if !matchOptType.isNone && discrs.any fun d => !d[0].isNone then throwErrorAt matchOptType "match expected type should not be provided when discriminants with equality proofs are used" elabMatchCore stx expectedType? builtin_initialize registerTraceClass `Elab.match -- leading_parser:leadPrec "nomatch " >> termParser /-- Empty match/ex falso. `nomatch e` is of arbitrary type `α : Sort u` if Lean can show that an empty set of patterns is exhaustive given `e`'s type, e.g. because it has no constructors. -/ @[builtinTermElab «nomatch»] def elabNoMatch : TermElab := fun stx expectedType? => do match stx with | `(nomatch $discrExpr) => match (← isLocalIdent? discrExpr) with | some _ => let expectedType ← waitExpectedType expectedType? let discr := mkNode ``Lean.Parser.Term.matchDiscr #[mkNullNode, discrExpr] elabMatchAux none #[discr] #[] mkNullNode expectedType | _ => let stxNew ← `(let _discr := $discrExpr; nomatch _discr) withMacroExpansion stx stxNew <| elabTerm stxNew expectedType? | _ => throwUnsupportedSyntax end Lean.Elab.Term
767032e17b752672ca872361f35f30ef930e43e5
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/ring_theory/witt_vector/structure_polynomial.lean
247f386090e2841567bdc112d9c2e0d187b60f24
[ "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
18,599
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Robert Y. Lewis -/ import data.matrix.notation import field_theory.mv_polynomial import field_theory.finite.polynomial import number_theory.basic import ring_theory.witt_vector.witt_polynomial /-! # Witt structure polynomials In this file we prove the main theorem that makes the whole theory of Witt vectors work. Briefly, consider a polynomial `Φ : mv_polynomial idx ℤ` over the integers, with polynomials variables indexed by an arbitrary type `idx`. Then there exists a unique family of polynomials `φ : ℕ → mv_polynomial (idx × ℕ) Φ` such that for all `n : ℕ` we have (`witt_structure_int_exists_unique`) ``` bind₁ φ (witt_polynomial p ℤ n) = bind₁ (λ i, (rename (prod.mk i) (witt_polynomial p ℤ n))) Φ ``` In other words: evaluating the `n`-th Witt polynomial on the family `φ` is the same as evaluating `Φ` on the (appropriately renamed) `n`-th Witt polynomials. N.b.: As far as we know, these polynomials do not have a name in the literature, so we have decided to call them the “Witt structure polynomials”. See `witt_structure_int`. ## Special cases With the main result of this file in place, we apply it to certain special polynomials. For example, by taking `Φ = X tt + X ff` resp. `Φ = X tt * X ff` we obtain families of polynomials `witt_add` resp. `witt_mul` (with type `ℕ → mv_polynomial (bool × ℕ) ℤ`) that will be used in later files to define the addition and multiplication on the ring of Witt vectors. ## Outline of the proof The proof of `witt_structure_int_exists_unique` is rather technical, and takes up most of this file. We start by proving the analogous version for polynomials with rational coefficients, instead of integer coefficients. In this case, the solution is rather easy, since the Witt polynomials form a faithful change of coordinates in the polynomial ring `mv_polynomial ℕ ℚ`. We therefore obtain a family of polynomials `witt_structure_rat Φ` for every `Φ : mv_polynomial idx ℚ`. If `Φ` has integer coefficients, then the polynomials `witt_structure_rat Φ n` do so as well. Proving this claim is the essential core of this file, and culminates in `map_witt_structure_int`, which proves that upon mapping the coefficients of `witt_structure_int Φ n` from the integers to the rationals, one obtains `witt_structure_rat Φ n`. Ultimately, the proof of `map_witt_structure_int` relies on ``` dvd_sub_pow_of_dvd_sub {R : Type*} [comm_ring R] {p : ℕ} {a b : R} : (p : R) ∣ a - b → ∀ (k : ℕ), (p : R) ^ (k + 1) ∣ a ^ p ^ k - b ^ p ^ k ``` ## Main results * `witt_structure_rat Φ`: the family of polynomials `ℕ → mv_polynomial (idx × ℕ) ℚ` associated with `Φ : mv_polynomial idx ℚ` and satisfying the property explained above. * `witt_structure_rat_prop`: the proof that `witt_structure_rat` indeed satisfies the property. * `witt_structure_int Φ`: the family of polynomials `ℕ → mv_polynomial (idx × ℕ) ℤ` associated with `Φ : mv_polynomial idx ℤ` and satisfying the property explained above. * `map_witt_structure_int`: the proof that the integral polynomials `with_structure_int Φ` are equal to `witt_structure_rat Φ` when mapped to polynomials with rational coefficients. * `witt_structure_int_prop`: the proof that `witt_structure_int` indeed satisfies the property. * Five families of polynomials that will be used to define the ring structure on the ring of Witt vectors: - `witt_vector.witt_zero` - `witt_vector.witt_one` - `witt_vector.witt_add` - `witt_vector.witt_mul` - `witt_vector.witt_neg` (We also define `witt_vector.witt_sub`, and later we will prove that it describes subtraction, which is defined as `λ a b, a + -b`. See `witt_vector.sub_coeff` for this proof.) ## References * [Hazewinkel, *Witt Vectors*][Haze09] * [Commelin and Lewis, *Formalizing the Ring of Witt Vectors*][CL21] -/ open mv_polynomial open set open finset (range) open finsupp (single) -- This lemma reduces a bundled morphism to a "mere" function, -- and consequently the simplifier cannot use a lot of powerful simp-lemmas. -- We disable this locally, and probably it should be disabled globally in mathlib. local attribute [-simp] coe_eval₂_hom variables {p : ℕ} {R : Type*} {idx : Type*} [comm_ring R] open_locale witt open_locale big_operators section p_prime variables (p) [hp : fact p.prime] include hp /-- `witt_structure_rat Φ` is a family of polynomials `ℕ → mv_polynomial (idx × ℕ) ℚ` that are uniquely characterised by the property that ``` bind₁ (witt_structure_rat p Φ) (witt_polynomial p ℚ n) = bind₁ (λ i, (rename (prod.mk i) (witt_polynomial p ℚ n))) Φ ``` In other words: evaluating the `n`-th Witt polynomial on the family `witt_structure_rat Φ` is the same as evaluating `Φ` on the (appropriately renamed) `n`-th Witt polynomials. See `witt_structure_rat_prop` for this property, and `witt_structure_rat_exists_unique` for the fact that `witt_structure_rat` gives the unique family of polynomials with this property. These polynomials turn out to have integral coefficients, but it requires some effort to show this. See `witt_structure_int` for the version with integral coefficients, and `map_witt_structure_int` for the fact that it is equal to `witt_structure_rat` when mapped to polynomials over the rationals. -/ noncomputable def witt_structure_rat (Φ : mv_polynomial idx ℚ) (n : ℕ) : mv_polynomial (idx × ℕ) ℚ := bind₁ (λ k, bind₁ (λ i, rename (prod.mk i) (W_ ℚ k)) Φ) (X_in_terms_of_W p ℚ n) theorem witt_structure_rat_prop (Φ : mv_polynomial idx ℚ) (n : ℕ) : bind₁ (witt_structure_rat p Φ) (W_ ℚ n) = bind₁ (λ i, (rename (prod.mk i) (W_ ℚ n))) Φ := calc bind₁ (witt_structure_rat p Φ) (W_ ℚ n) = bind₁ (λ k, bind₁ (λ i, (rename (prod.mk i)) (W_ ℚ k)) Φ) (bind₁ (X_in_terms_of_W p ℚ) (W_ ℚ n)) : by { rw bind₁_bind₁, apply eval₂_hom_congr (ring_hom.ext_rat _ _) rfl rfl } ... = bind₁ (λ i, (rename (prod.mk i) (W_ ℚ n))) Φ : by rw [bind₁_X_in_terms_of_W_witt_polynomial p _ n, bind₁_X_right] theorem witt_structure_rat_exists_unique (Φ : mv_polynomial idx ℚ) : ∃! (φ : ℕ → mv_polynomial (idx × ℕ) ℚ), ∀ (n : ℕ), bind₁ φ (W_ ℚ n) = bind₁ (λ i, (rename (prod.mk i) (W_ ℚ n))) Φ := begin refine ⟨witt_structure_rat p Φ, _, _⟩, { intro n, apply witt_structure_rat_prop }, { intros φ H, funext n, rw show φ n = bind₁ φ (bind₁ (W_ ℚ) (X_in_terms_of_W p ℚ n)), { rw [bind₁_witt_polynomial_X_in_terms_of_W p, bind₁_X_right] }, rw [bind₁_bind₁], exact eval₂_hom_congr (ring_hom.ext_rat _ _) (funext H) rfl }, end lemma witt_structure_rat_rec_aux (Φ : mv_polynomial idx ℚ) (n : ℕ) : witt_structure_rat p Φ n * C (p ^ n : ℚ) = bind₁ (λ b, rename (λ i, (b, i)) (W_ ℚ n)) Φ - ∑ i in range n, C (p ^ i : ℚ) * (witt_structure_rat p Φ i) ^ p ^ (n - i) := begin have := X_in_terms_of_W_aux p ℚ n, replace := congr_arg (bind₁ (λ k : ℕ, bind₁ (λ i, rename (prod.mk i) (W_ ℚ k)) Φ)) this, rw [alg_hom.map_mul, bind₁_C_right] at this, rw [witt_structure_rat, this], clear this, conv_lhs { simp only [alg_hom.map_sub, bind₁_X_right] }, rw sub_right_inj, simp only [alg_hom.map_sum, alg_hom.map_mul, bind₁_C_right, alg_hom.map_pow], refl end /-- Write `witt_structure_rat p φ n` in terms of `witt_structure_rat p φ i` for `i < n`. -/ lemma witt_structure_rat_rec (Φ : mv_polynomial idx ℚ) (n : ℕ) : (witt_structure_rat p Φ n) = C (1 / p ^ n : ℚ) * (bind₁ (λ b, (rename (λ i, (b, i)) (W_ ℚ n))) Φ - ∑ i in range n, C (p ^ i : ℚ) * (witt_structure_rat p Φ i) ^ p ^ (n - i)) := begin calc witt_structure_rat p Φ n = C (1 / p ^ n : ℚ) * (witt_structure_rat p Φ n * C (p ^ n : ℚ)) : _ ... = _ : by rw witt_structure_rat_rec_aux, rw [mul_left_comm, ← C_mul, div_mul_cancel, C_1, mul_one], exact pow_ne_zero _ (nat.cast_ne_zero.2 hp.1.ne_zero), end /-- `witt_structure_int Φ` is a family of polynomials `ℕ → mv_polynomial (idx × ℕ) ℚ` that are uniquely characterised by the property that ``` bind₁ (witt_structure_int p Φ) (witt_polynomial p ℚ n) = bind₁ (λ i, (rename (prod.mk i) (witt_polynomial p ℚ n))) Φ ``` In other words: evaluating the `n`-th Witt polynomial on the family `witt_structure_int Φ` is the same as evaluating `Φ` on the (appropriately renamed) `n`-th Witt polynomials. See `witt_structure_int_prop` for this property, and `witt_structure_int_exists_unique` for the fact that `witt_structure_int` gives the unique family of polynomials with this property. -/ noncomputable def witt_structure_int (Φ : mv_polynomial idx ℤ) (n : ℕ) : mv_polynomial (idx × ℕ) ℤ := finsupp.map_range rat.num (rat.coe_int_num 0) (witt_structure_rat p (map (int.cast_ring_hom ℚ) Φ) n) variable {p} lemma bind₁_rename_expand_witt_polynomial (Φ : mv_polynomial idx ℤ) (n : ℕ) (IH : ∀ m : ℕ, m < (n + 1) → map (int.cast_ring_hom ℚ) (witt_structure_int p Φ m) = witt_structure_rat p (map (int.cast_ring_hom ℚ) Φ) m) : bind₁ (λ b, rename (λ i, (b, i)) (expand p (W_ ℤ n))) Φ = bind₁ (λ i, expand p (witt_structure_int p Φ i)) (W_ ℤ n) := begin apply mv_polynomial.map_injective (int.cast_ring_hom ℚ) int.cast_injective, simp only [map_bind₁, map_rename, map_expand, rename_expand, map_witt_polynomial], have key := (witt_structure_rat_prop p (map (int.cast_ring_hom ℚ) Φ) n).symm, apply_fun expand p at key, simp only [expand_bind₁] at key, rw key, clear key, apply eval₂_hom_congr' rfl _ rfl, rintro i hi -, rw [witt_polynomial_vars, finset.mem_range] at hi, simp only [IH i hi], end lemma C_p_pow_dvd_bind₁_rename_witt_polynomial_sub_sum (Φ : mv_polynomial idx ℤ) (n : ℕ) (IH : ∀ m : ℕ, m < n → map (int.cast_ring_hom ℚ) (witt_structure_int p Φ m) = witt_structure_rat p (map (int.cast_ring_hom ℚ) Φ) m) : C ↑(p ^ n) ∣ (bind₁ (λ (b : idx), rename (λ i, (b, i)) (witt_polynomial p ℤ n)) Φ - ∑ i in range n, C (↑p ^ i) * witt_structure_int p Φ i ^ p ^ (n - i)) := begin cases n, { simp only [is_unit_one, int.coe_nat_zero, int.coe_nat_succ, zero_add, pow_zero, C_1, is_unit.dvd] }, -- prepare a useful equation for rewriting have key := bind₁_rename_expand_witt_polynomial Φ n IH, apply_fun (map (int.cast_ring_hom (zmod (p ^ (n + 1))))) at key, conv_lhs at key { simp only [map_bind₁, map_rename, map_expand, map_witt_polynomial] }, -- clean up and massage rw [nat.succ_eq_add_one, C_dvd_iff_zmod, ring_hom.map_sub, sub_eq_zero, map_bind₁], simp only [map_rename, map_witt_polynomial, witt_polynomial_zmod_self], rw key, clear key IH, rw [bind₁, aeval_witt_polynomial, ring_hom.map_sum, ring_hom.map_sum, finset.sum_congr rfl], intros k hk, rw [finset.mem_range, nat.lt_succ_iff] at hk, simp only [← sub_eq_zero, ← ring_hom.map_sub, ← C_dvd_iff_zmod, C_eq_coe_nat, ← mul_sub, ← int.nat_cast_eq_coe_nat, ← nat.cast_pow], rw show p ^ (n + 1) = p ^ k * p ^ (n - k + 1), { rw [← pow_add, ←add_assoc], congr' 2, rw [add_comm, ←nat.sub_eq_iff_eq_add hk] }, rw [nat.cast_mul, nat.cast_pow, nat.cast_pow], apply mul_dvd_mul_left, rw show p ^ (n + 1 - k) = p * p ^ (n - k), { rw [← pow_succ, nat.sub_add_comm hk] }, rw [pow_mul], -- the machine! apply dvd_sub_pow_of_dvd_sub, rw [← C_eq_coe_nat, int.nat_cast_eq_coe_nat, C_dvd_iff_zmod, ring_hom.map_sub, sub_eq_zero, map_expand, ring_hom.map_pow, mv_polynomial.expand_zmod], end variables (p) @[simp] lemma map_witt_structure_int (Φ : mv_polynomial idx ℤ) (n : ℕ) : map (int.cast_ring_hom ℚ) (witt_structure_int p Φ n) = witt_structure_rat p (map (int.cast_ring_hom ℚ) Φ) n := begin apply nat.strong_induction_on n, clear n, intros n IH, rw [witt_structure_int, map_map_range_eq_iff, int.coe_cast_ring_hom], intro c, rw [witt_structure_rat_rec, coeff_C_mul, mul_comm, mul_div_assoc', mul_one], have sum_induction_steps : map (int.cast_ring_hom ℚ) (∑ i in range n, C (p ^ i : ℤ) * (witt_structure_int p Φ i) ^ p ^ (n - i)) = ∑ i in range n, C (p ^ i : ℚ) * (witt_structure_rat p (map (int.cast_ring_hom ℚ) Φ) i) ^ p ^ (n - i), { rw [ring_hom.map_sum], apply finset.sum_congr rfl, intros i hi, rw finset.mem_range at hi, simp only [IH i hi, ring_hom.map_mul, ring_hom.map_pow, map_C], refl }, simp only [← sum_induction_steps, ← map_witt_polynomial p (int.cast_ring_hom ℚ), ← map_rename, ← map_bind₁, ← ring_hom.map_sub, coeff_map], rw show (p : ℚ)^n = ((p^n : ℕ) : ℤ), by norm_cast, rw [← rat.denom_eq_one_iff, ring_hom.eq_int_cast, rat.denom_div_cast_eq_one_iff], swap, { exact_mod_cast pow_ne_zero n hp.1.ne_zero }, revert c, rw [← C_dvd_iff_dvd_coeff], exact C_p_pow_dvd_bind₁_rename_witt_polynomial_sub_sum Φ n IH, end variables (p) theorem witt_structure_int_prop (Φ : mv_polynomial idx ℤ) (n) : bind₁ (witt_structure_int p Φ) (witt_polynomial p ℤ n) = bind₁ (λ i, rename (prod.mk i) (W_ ℤ n)) Φ := begin apply mv_polynomial.map_injective (int.cast_ring_hom ℚ) int.cast_injective, have := witt_structure_rat_prop p (map (int.cast_ring_hom ℚ) Φ) n, simpa only [map_bind₁, ← eval₂_hom_map_hom, eval₂_hom_C_left, map_rename, map_witt_polynomial, alg_hom.coe_to_ring_hom, map_witt_structure_int], end lemma eq_witt_structure_int (Φ : mv_polynomial idx ℤ) (φ : ℕ → mv_polynomial (idx × ℕ) ℤ) (h : ∀ n, bind₁ φ (witt_polynomial p ℤ n) = bind₁ (λ i, rename (prod.mk i) (W_ ℤ n)) Φ) : φ = witt_structure_int p Φ := begin funext k, apply mv_polynomial.map_injective (int.cast_ring_hom ℚ) int.cast_injective, rw map_witt_structure_int, refine congr_fun _ k, apply unique_of_exists_unique (witt_structure_rat_exists_unique p (map (int.cast_ring_hom ℚ) Φ)), { intro n, specialize h n, apply_fun map (int.cast_ring_hom ℚ) at h, simpa only [map_bind₁, ← eval₂_hom_map_hom, eval₂_hom_C_left, map_rename, map_witt_polynomial, alg_hom.coe_to_ring_hom] using h, }, { intro n, apply witt_structure_rat_prop } end theorem witt_structure_int_exists_unique (Φ : mv_polynomial idx ℤ) : ∃! (φ : ℕ → mv_polynomial (idx × ℕ) ℤ), ∀ (n : ℕ), bind₁ φ (witt_polynomial p ℤ n) = bind₁ (λ i : idx, (rename (prod.mk i) (W_ ℤ n))) Φ := ⟨witt_structure_int p Φ, witt_structure_int_prop _ _, eq_witt_structure_int _ _⟩ theorem witt_structure_prop (Φ : mv_polynomial idx ℤ) (n) : aeval (λ i, map (int.cast_ring_hom R) (witt_structure_int p Φ i)) (witt_polynomial p ℤ n) = aeval (λ i, rename (prod.mk i) (W n)) Φ := begin convert congr_arg (map (int.cast_ring_hom R)) (witt_structure_int_prop p Φ n) using 1; rw hom_bind₁; apply eval₂_hom_congr (ring_hom.ext_int _ _) _ rfl, { refl }, { simp only [map_rename, map_witt_polynomial] } end lemma witt_structure_int_rename {σ : Type*} (Φ : mv_polynomial idx ℤ) (f : idx → σ) (n : ℕ) : witt_structure_int p (rename f Φ) n = rename (prod.map f id) (witt_structure_int p Φ n) := begin apply mv_polynomial.map_injective (int.cast_ring_hom ℚ) int.cast_injective, simp only [map_rename, map_witt_structure_int, witt_structure_rat, rename_bind₁, rename_rename, bind₁_rename], refl end @[simp] lemma constant_coeff_witt_structure_rat_zero (Φ : mv_polynomial idx ℚ) : constant_coeff (witt_structure_rat p Φ 0) = constant_coeff Φ := by simp only [witt_structure_rat, bind₁, map_aeval, X_in_terms_of_W_zero, constant_coeff_rename, constant_coeff_witt_polynomial, aeval_X, constant_coeff_comp_algebra_map, eval₂_hom_zero', ring_hom.id_apply] lemma constant_coeff_witt_structure_rat (Φ : mv_polynomial idx ℚ) (h : constant_coeff Φ = 0) (n : ℕ) : constant_coeff (witt_structure_rat p Φ n) = 0 := by simp only [witt_structure_rat, eval₂_hom_zero', h, bind₁, map_aeval, constant_coeff_rename, constant_coeff_witt_polynomial, constant_coeff_comp_algebra_map, ring_hom.id_apply, constant_coeff_X_in_terms_of_W] @[simp] lemma constant_coeff_witt_structure_int_zero (Φ : mv_polynomial idx ℤ) : constant_coeff (witt_structure_int p Φ 0) = constant_coeff Φ := begin have inj : function.injective (int.cast_ring_hom ℚ), { intros m n, exact int.cast_inj.mp, }, apply inj, rw [← constant_coeff_map, map_witt_structure_int, constant_coeff_witt_structure_rat_zero, constant_coeff_map], end lemma constant_coeff_witt_structure_int (Φ : mv_polynomial idx ℤ) (h : constant_coeff Φ = 0) (n : ℕ) : constant_coeff (witt_structure_int p Φ n) = 0 := begin have inj : function.injective (int.cast_ring_hom ℚ), { intros m n, exact int.cast_inj.mp, }, apply inj, rw [← constant_coeff_map, map_witt_structure_int, constant_coeff_witt_structure_rat, ring_hom.map_zero], rw [constant_coeff_map, h, ring_hom.map_zero], end variable (R) -- we could relax the fintype on `idx`, but then we need to cast from finset to set. -- for our applications `idx` is always finite. lemma witt_structure_rat_vars [fintype idx] (Φ : mv_polynomial idx ℚ) (n : ℕ) : (witt_structure_rat p Φ n).vars ⊆ finset.univ.product (finset.range (n + 1)) := begin rw witt_structure_rat, intros x hx, simp only [finset.mem_product, true_and, finset.mem_univ, finset.mem_range], obtain ⟨k, hk, hx'⟩ := mem_vars_bind₁ _ _ hx, obtain ⟨i, -, hx''⟩ := mem_vars_bind₁ _ _ hx', obtain ⟨j, hj, rfl⟩ := mem_vars_rename _ _ hx'', rw [witt_polynomial_vars, finset.mem_range] at hj, replace hk := X_in_terms_of_W_vars_subset p _ hk, rw finset.mem_range at hk, exact lt_of_lt_of_le hj hk, end -- we could relax the fintype on `idx`, but then we need to cast from finset to set. -- for our applications `idx` is always finite. lemma witt_structure_int_vars [fintype idx] (Φ : mv_polynomial idx ℤ) (n : ℕ) : (witt_structure_int p Φ n).vars ⊆ finset.univ.product (finset.range (n + 1)) := begin have : function.injective (int.cast_ring_hom ℚ) := int.cast_injective, rw [← vars_map_of_injective _ this, map_witt_structure_int], apply witt_structure_rat_vars, end end p_prime
66c2dc19b648e946dc51eca37f95efdd2b8d598a
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Elab/PreDefinition/Structural/FindRecArg.lean
b6d4033412ccf6a4156a212fc7c3885b86bcc8f1
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
6,641
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Elab.PreDefinition.Structural.Basic namespace Lean.Elab.Structural open Meta private def getIndexMinPos (xs : Array Expr) (indices : Array Expr) : Nat := Id.run do let mut minPos := xs.size for index in indices do match xs.indexOf? index with | some pos => if pos.val < minPos then minPos := pos.val | _ => pure () return minPos -- Indices can only depend on other indices private def hasBadIndexDep? (ys : Array Expr) (indices : Array Expr) : MetaM (Option (Expr × Expr)) := do for index in indices do let indexType ← inferType index for y in ys do if !indices.contains y && (← dependsOn indexType y.fvarId!) then return some (index, y) return none -- Inductive datatype parameters cannot depend on ys private def hasBadParamDep? (ys : Array Expr) (indParams : Array Expr) : MetaM (Option (Expr × Expr)) := do for p in indParams do let pType ← inferType p for y in ys do if ← dependsOn pType y.fvarId! then return some (p, y) return none private def throwStructuralFailed : MetaM α := throwError "structural recursion cannot be used" private def orelse' (x y : M α) : M α := do let saveState ← get orelseMergeErrors x (do set saveState; y) /-- Try to find an argument that is structurally smaller in every recursive application. We use this argument to justify termination using the auxiliary `brecOn` construction. We give preference for arguments that are *not* indices of inductive types of other arguments. See issue #837 for an example where we can show termination using the index of an inductive family, but we don't get the desired definitional equalities. We perform two passes. In the first-pass, we only consider arguments that are not indices. In the second pass, we consider them. TODO: explore whether there are better solutions, and whether there are other ways to break the heuristic used for creating the smart unfolding auxiliary definition. -/ partial def findRecArg (numFixed : Nat) (xs : Array Expr) (k : RecArgInfo → M α) : M α := do /- Collect arguments that are indices. See comment above. -/ let indicesRef : IO.Ref FVarIdSet ← IO.mkRef {} for x in xs do let xType ← inferType x /- Traverse all sub-expressions in the type of `x` -/ forEachExpr xType fun e => /- If `e` is an inductive family, we store in `indicesRef` all variables in `xs` that occur in "index positions". -/ matchConstInduct e.getAppFn (fun _ => pure ()) fun info _ => do if info.numIndices > 0 && info.numParams + info.numIndices == e.getAppNumArgs then for arg in e.getAppArgs[info.numParams:] do forEachExpr arg fun e => do if e.isFVar && xs.any (· == e) then indicesRef.modify fun indices => indices.insert e.fvarId! let indices ← indicesRef.get /- We perform two passes. See comment above. -/ let rec go (i : Nat) (firstPass : Bool) : M α := do if h : i < xs.size then let x := xs.get ⟨i, h⟩ trace[Elab.definition.structural] "findRecArg x: {x}, firstPass: {firstPass}" let localDecl ← getFVarLocalDecl x if localDecl.isLet then throwStructuralFailed else if firstPass == indices.contains localDecl.fvarId then go (i+1) firstPass else let xType ← whnfD localDecl.type matchConstInduct xType.getAppFn (fun _ => go (i+1) firstPass) fun indInfo us => do if !(← hasConst (mkBRecOnName indInfo.name)) then go (i+1) firstPass else if indInfo.isReflexive && !(← hasConst (mkBInductionOnName indInfo.name)) && !(← isInductivePredicate indInfo.name) then go (i+1) firstPass else let indArgs := xType.getAppArgs let indParams := indArgs.extract 0 indInfo.numParams let indIndices := indArgs.extract indInfo.numParams indArgs.size if !indIndices.all Expr.isFVar then orelse' (throwError "argument #{i+1} was not used because its type is an inductive family and indices are not variables{indentExpr xType}") (go (i+1) firstPass) else if !indIndices.allDiff then orelse' (throwError "argument #{i+1} was not used because its type is an inductive family and indices are not pairwise distinct{indentExpr xType}") (go (i+1) firstPass) else let indexMinPos := getIndexMinPos xs indIndices let numFixed := if indexMinPos < numFixed then indexMinPos else numFixed let fixedParams := xs.extract 0 numFixed let ys := xs.extract numFixed xs.size match (← hasBadIndexDep? ys indIndices) with | some (index, y) => orelse' (throwError "argument #{i+1} was not used because its type is an inductive family{indentExpr xType}\nand index{indentExpr index}\ndepends on the non index{indentExpr y}") (go (i+1) firstPass) | none => match (← hasBadParamDep? ys indParams) with | some (indParam, y) => orelse' (throwError "argument #{i+1} was not used because its type is an inductive datatype{indentExpr xType}\nand parameter{indentExpr indParam}\ndepends on{indentExpr y}") (go (i+1) firstPass) | none => let indicesPos := indIndices.map fun index => match ys.indexOf? index with | some i => i.val | none => unreachable! orelse' (mapError (k { fixedParams := fixedParams ys := ys pos := i - fixedParams.size indicesPos := indicesPos indName := indInfo.name indLevels := us indParams := indParams indIndices := indIndices reflexive := indInfo.isReflexive indPred := ←isInductivePredicate indInfo.name }) (fun msg => m!"argument #{i+1} was not used for structural recursion{indentD msg}")) (go (i+1) firstPass) else if firstPass then go (i := numFixed) (firstPass := false) else throwStructuralFailed go (i := numFixed) (firstPass := true) end Lean.Elab.Structural
cf057295700e897146ffe231e892e49d48761767
48eee836fdb5c613d9a20741c17db44c8e12e61c
/src/algebra/theories/bounded_lattice.lean
1f859e162d2fd692b6b26968293f40259cb9d405
[ "Apache-2.0" ]
permissive
fgdorais/lean-universal
06430443a4abe51e303e602684c2977d1f5c0834
9259b0f7fb3aa83a9e0a7a3eaa44c262e42cc9b1
refs/heads/master
1,592,479,744,136
1,589,473,399,000
1,589,473,399,000
196,287,552
1
1
null
null
null
null
UTF-8
Lean
false
false
4,110
lean
-- Copyright © 2019 François G. Dorais. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. import .basic import .lattice import .semiring namespace algebra signature bounded_lattice (α : Type*) := (join : α → α → α) (meet : α → α → α) (bot : α) (top : α) namespace bounded_lattice_sig variables {α : Type*} (s : bounded_lattice_sig α) @[signature_instance] definition to_lattice : lattice_sig α := { join := s.join , meet := s.meet } @[signature_instance] definition to_bounded_join_semilattice : bounded_semilattice_sig α := { op := s.join , id := s.bot } @[signature_instance] definition to_bounded_meet_semilattice : bounded_semilattice_sig α := { op := s.meet , id := s.top } @[signature_instance] definition to_join_meet_semiring : semiring_sig α := { add := s.join , zero := s.bot , mul := s.meet , one := s.top } @[signature_instance] definition to_meet_join_semiring : semiring_sig α := { add := s.meet , zero := s.top , mul := s.join , one := s.bot } end bounded_lattice_sig variables {α : Type*} (s : bounded_lattice_sig α) local infix ∪ := s.join local infix ∩ := s.meet local notation `𝟙` := s.top local notation `𝟘` := s.bot @[theory] class bounded_lattice : Prop := intro :: (join_associative : identity.op_associative s.join) (join_commutative : identity.op_commutative s.join) (join_right_absorptive : identity.op_right_absorptive s.join s.meet) (join_right_identity : identity.op_right_identity s.join s.bot) (meet_associative : identity.op_associative s.meet) (meet_commutative : identity.op_commutative s.meet) (meet_right_absorptive : identity.op_right_absorptive s.meet s.join) (meet_right_identity : identity.op_right_identity s.meet s.top) namespace bounded_lattice variable [i : bounded_lattice s] include i instance to_lattice : lattice s.to_lattice := lattice.infer _ @[identity_instance] theorem join_idempotent : identity.op_idempotent s.join := λ x, op_idempotent s.join x @[identity_instance] theorem meet_idempotent : identity.op_idempotent s.meet := λ x, op_idempotent s.meet x instance to_bounded_join_semilattice : bounded_semilattice s.to_bounded_join_semilattice := bounded_semilattice.infer _ instance to_bounded_meet_semilattice : bounded_semilattice s.to_bounded_meet_semilattice := bounded_semilattice.infer _ @[identity_instance] theorem join_right_null : identity.op_right_fixpoint s.join s.top := λ x, calc x ∪ 𝟙 = (x ∩ 𝟙) ∪ 𝟙 : by rw op_right_identity s.meet ... = 𝟙 : by rw op_left_absorptive s.join @[identity_instance] theorem meet_right_null : identity.op_right_fixpoint s.meet s.bot := λ x, calc x ∩ 𝟘 = (x ∪ 𝟘) ∩ 𝟘 : by rw op_right_identity s.join ... = 𝟘 : by rw op_left_absorptive s.meet end bounded_lattice @[theory] class bounded_distributive_lattice : Prop := intro :: (join_associative : identity.op_associative s.join) (join_commutative : identity.op_commutative s.join) (join_right_absorptive : identity.op_right_absorptive s.join s.meet) (join_right_identity : identity.op_right_identity s.join s.bot) (meet_associative : identity.op_associative s.meet) (meet_commutative : identity.op_commutative s.meet) (meet_right_absorptive : identity.op_right_absorptive s.meet s.join) (meet_right_identity : identity.op_right_identity s.meet s.top) (meet_join_right_distributive : identity.op_right_distributive s.meet s.join) namespace bounded_distributive_lattice variable [i : bounded_distributive_lattice s] include i instance to_bounded_lattice : bounded_lattice s := bounded_lattice.infer _ instance to_distributive_lattice : distributive_lattice s.to_lattice := distributive_lattice.infer _ instance to_join_meet_semiring : comm_semiring s.to_join_meet_semiring := comm_semiring.infer _ /- help to_meet_join_semiring inference -/ @[identity_instance] theorem join_meet_right_distributive : identity.op_right_distributive s.join s.meet := op_right_distributive _ _ instance to_meet_join_semiring : comm_semiring s.to_meet_join_semiring := comm_semiring.infer _ end bounded_distributive_lattice end algebra
3f1373c735f098b31367ab83a7f26bc2f9788001
4f643cce24b2d005aeeb5004c2316a8d6cc7f3b1
/src/o_minimal/dunlo.lean
e01de4c54f67a9ce5f0e5a45c57d3845954a589e
[]
no_license
rwbarton/lean-omin
da209ed061d64db65a8f7f71f198064986f30eb9
fd733c6d95ef6f4743aae97de5e15df79877c00e
refs/heads/master
1,674,408,673,325
1,607,343,535,000
1,607,343,535,000
285,150,399
9
0
null
null
null
null
UTF-8
Lean
false
false
2,639
lean
import order.basic import data.finset.lattice import data.rat namespace o_minimal set_option old_structure_cmd true /-- A DUNLO is a dense unbounded nonempty linear order. This is the setting in which we can talk about o-minimal structures. See [vdD], §1.3, first italicized paragraph. -/ class DUNLO (R : Type*) extends linear_order R := [dense : densely_ordered R] [unbounded_below : no_bot_order R] [unbounded_above : no_top_order R] [nonempty : nonempty R] -- These classes are all `Prop`s so these instances should be harmless. attribute [instance] DUNLO.dense DUNLO.unbounded_below DUNLO.unbounded_above DUNLO.nonempty instance : DUNLO ℚ := { .. show linear_order ℚ, by apply_instance } -- TODO: for_mathlib /-- In a DUNLO, a system of constraints Lᵢ < x, x < Uⱼ is solvable if and only if Lᵢ < Uⱼ for every i and j. Here i and j range over possibly empty finite sets I and J respectively. (In fact, this property characterizes DUNLOs.) -/ lemma order_constraints_feasible_iff {R : Type*} [DUNLO R] (lower upper : finset R) : (∃ x, (∀ g ∈ lower, g < x) ∧ (∀ h ∈ upper, x < h)) ↔ ∀ (g ∈ lower) (h ∈ upper), g < h := begin split, { rintro ⟨x, hx₁, hx₂⟩ g Hg h Hh, exact lt_trans (hx₁ g Hg) (hx₂ h Hh) }, { -- TODO: maybe reformulate all this into a useful lemma: -- (s : finset R) : s = ∅ ∨ ∃ max ∈ s, ∀ i ∈ s, i ≤ max -- Pretty similar to `exists_max_image`. cases hlower : lower.max with lmax; [{ rw finset.max_eq_none at hlower, subst lower }, { have le_lmax : ∀ g ∈ lower, g ≤ lmax, { intros g H, apply finset.le_max_of_mem H hlower } }], all_goals { -- TODO: can't we write it using `;`? cases hupper : upper.min with umin; [{ rw finset.min_eq_none at hupper, subst upper }, { have umin_le : ∀ h ∈ upper, umin ≤ h, { intros h H, apply finset.min_le_of_mem H hupper } }] }, { simp }, { suffices : ∃ (x : R), ∀ (h : R), h ∈ upper → x < h, { simpa }, obtain ⟨x, hx⟩ := no_bot umin, exact ⟨x, λ h H, lt_of_lt_of_le hx (umin_le h H)⟩ }, { suffices : ∃ (x : R), ∀ (g : R), g ∈ lower → g < x, { simpa }, obtain ⟨x, hx⟩ := no_top lmax, exact ⟨x, λ g H, lt_of_le_of_lt (le_lmax g H) hx⟩ }, { intro Hgh, specialize Hgh lmax (finset.mem_of_max hlower) umin (finset.mem_of_min hupper), obtain ⟨x, hx₁, hx₂⟩ := exists_between Hgh, exact ⟨x, λ g H, lt_of_le_of_lt (le_lmax g H) hx₁, λ h H, lt_of_lt_of_le hx₂ (umin_le h H)⟩ } } end end o_minimal
cb2c3f185762f80cf09d22e9fa72981e5060d90a
59b654f4ee2fef898a3487dc03554a569051b63a
/src/old/utils.lean
b006d9c26d70cb4e4bd23cc6566a95c28ea7b922
[]
no_license
gunpinyo/twisted_cube_formalisation
180c9157478b66ec2b11ca47c8ff998a3e978a88
f78206ac495e84bd43a9b820fa10b6c94722e0ec
refs/heads/master
1,624,501,222,992
1,607,081,624,000
1,607,081,624,000
166,885,106
0
0
null
null
null
null
UTF-8
Lean
false
false
2,876
lean
import data.bitvec import data.vector2 -- def function.comp_n_times {α : Type*} (f : α → α) : ℕ → α → α -- | 0 := id -- | (n +1) := f ∘ (function.comp_n_times n) def bxor_bxor_id (a b : bool) : bxor a (bxor a b) = b := begin cases a, simp, simp, end def bxor_comm (a b : bool) : bxor a b = bxor b a := begin cases a, simp, simp, end def bnot_self {a : bool} : ¬ (bnot a = a) := begin intro p, cases a, all_goals {contradiction}, end -- def nat.add_le_add {n m l : ℕ} : n + l ≤ m + l → n ≤ m := -- begin intro p, induction l with l IH, {assumption,}, simp at p, assumption end section variable {n : ℕ} def fin.zero : fin (n +1) := ⟨0, nat.zero_lt_succ n⟩ @[simp] def fin.mk_from_succ (i : ℕ) (p_succ_i : i +1 < n +1) : fin n := ⟨i, nat.pred_le_pred p_succ_i⟩ def fin.succ_injection {i i' : fin n} : i.succ = i'.succ → i = i' := begin cases i, cases i', intro p, simp [fin.succ] at p |-, assumption, end def fin.to_zero {p : 0 < n +1} : (⟨0, p⟩ : fin (n +1)) = fin.zero := rfl def fin.to_succ {i : ℕ} {p : i +1 < n +1} : (⟨i +1, p⟩ : fin (n +1)) = (fin.mk_from_succ i p).succ := rfl def fin.elim_out_of_bound {α : Sort*} {i m : ℕ} (p : i + m < m) : α := begin exfalso, induction m with m IH, {simp at p, exact nat.not_lt_zero i p,}, have : i + nat.succ m = nat.succ (i + m), {refl,}, rw this at p, exact IH (nat.le_of_succ_le_succ p), end end @[simp] def fin.maybe_pred_rec {n : ℕ} {α : Type*} (a : α) (f : fin n → α) : fin (n +1) → α | ⟨0, _⟩ := a | ⟨i +1, succ_i_lt_succ_n⟩ := f ⟨i, nat.pred_le_pred succ_i_lt_succ_n⟩ def hetero_to_homo_eq {α β : Type} {x : α} {y : β} : Π p : x == y, (eq.rec_on (type_eq_of_heq (p : x == y)) x : β) = y := assume h, by cases h; refl section variables {α : Type*} {n : ℕ} {a : α} variables {v : vector α n} {sv sv' : vector α (n +1)} def vector.cons_injection : sv = sv' → sv.head = sv'.head ∧ sv.tail = sv'.tail := begin rw [←sv.cons_head_tail, ←sv'.cons_head_tail], rw [vector.head_cons, vector.tail_cons, vector.head_cons, vector.tail_cons], cases vector.tail sv with l p, cases vector.tail sv' with l' p', simp [vector.cons], exact λ x y, ⟨x, y⟩, end def vector.insert_nth_zero : v.insert_nth a fin.zero = a :: v := begin cases v with l p, simp [fin.zero, vector.insert_nth, vector.cons, list.insert_nth], end def vector.insert_nth_succ {i : fin (n +1)} : sv.insert_nth a i.succ = sv.head :: (sv.tail).insert_nth a i := begin rw [←sv.cons_head_tail, vector.head_cons, vector.tail_cons], cases sv.tail with l p, cases i with i_val i_lt, unfold fin.succ, apply vector.eq, simp [vector.insert_nth, list.insert_nth, vector.cons], end end
846cf9b2ab09c190c97db7967a581e93cb76894e
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/analysis/calculus/darboux.lean
9f81e949926d7e31f9a199a39a7d3a0b551c1768
[ "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
4,782
lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import analysis.calculus.mean_value /-! # Darboux's theorem In this file we prove that the derivative of a differentiable function on an interval takes all intermediate values. The proof is based on the [Wikipedia](https://en.wikipedia.org/wiki/Darboux%27s_theorem_(analysis)) page about this theorem. -/ open filter set open_locale topological_space classical variables {a b : ℝ} {f f' : ℝ → ℝ} /-- Darboux's theorem: if `a ≤ b` and `f' a < m < f' b`, then `f' c = m` for some `c ∈ [a, b]`. -/ theorem exists_has_deriv_within_at_eq_of_gt_of_lt (hab : a ≤ b) (hf : ∀ x ∈ (Icc a b), has_deriv_within_at f (f' x) (Icc a b) x) {m : ℝ} (hma : f' a < m) (hmb : m < f' b) : m ∈ f' '' (Icc a b) := begin have hab' : a < b, { refine lt_of_le_of_ne hab (λ hab', _), subst b, exact lt_asymm hma hmb }, set g : ℝ → ℝ := λ x, f x - m * x, have hg : ∀ x ∈ Icc a b, has_deriv_within_at g (f' x - m) (Icc a b) x, { intros x hx, simpa using (hf x hx).sub ((has_deriv_within_at_id x _).const_mul m) }, obtain ⟨c, cmem, hc⟩ : ∃ c ∈ Icc a b, is_min_on g (Icc a b) c, from compact_Icc.exists_forall_le (nonempty_Icc.2 $ hab) (λ x hx, (hg x hx).continuous_within_at), have cmem' : c ∈ Ioo a b, { cases eq_or_lt_of_le cmem.1 with hac hac, -- Show that `c` can't be equal to `a` { subst c, refine absurd (sub_nonneg.1 $ nonneg_of_mul_nonneg_left _ (sub_pos.2 hab')) (not_le_of_lt hma), have : b - a ∈ pos_tangent_cone_at (Icc a b) a, from mem_pos_tangent_cone_at_of_segment_subset (segment_eq_Icc hab ▸ subset.refl _), simpa [-sub_nonneg, -continuous_linear_map.map_sub] using hc.localize.has_fderiv_within_at_nonneg (hg a (left_mem_Icc.2 hab)) this }, cases eq_or_lt_of_le cmem.2 with hbc hbc, -- Show that `c` can't be equal to `a` { subst c, refine absurd (sub_nonpos.1 $ nonpos_of_mul_nonneg_right _ (sub_lt_zero.2 hab')) (not_le_of_lt hmb), have : a - b ∈ pos_tangent_cone_at (Icc a b) b, from mem_pos_tangent_cone_at_of_segment_subset (by rw [segment_symm, segment_eq_Icc hab]), simpa [-sub_nonneg, -continuous_linear_map.map_sub] using hc.localize.has_fderiv_within_at_nonneg (hg b (right_mem_Icc.2 hab)) this }, exact ⟨hac, hbc⟩ }, use [c, cmem], rw [← sub_eq_zero], have : Icc a b ∈ 𝓝 c, by rwa [← mem_interior_iff_mem_nhds, interior_Icc], exact (hc.is_local_min this).has_deriv_at_eq_zero ((hg c cmem).has_deriv_at this) end /-- Darboux's theorem: if `a ≤ b` and `f' a > m > f' b`, then `f' c = m` for some `c ∈ [a, b]`. -/ theorem exists_has_deriv_within_at_eq_of_lt_of_gt (hab : a ≤ b) (hf : ∀ x ∈ (Icc a b), has_deriv_within_at f (f' x) (Icc a b) x) {m : ℝ} (hma : m < f' a) (hmb : f' b < m) : m ∈ f' '' (Icc a b) := let ⟨c, cmem, hc⟩ := exists_has_deriv_within_at_eq_of_gt_of_lt hab (λ x hx, (hf x hx).neg) (neg_lt_neg hma) (neg_lt_neg hmb) in ⟨c, cmem, neg_injective hc⟩ /-- Darboux's theorem: the image of a convex set under `f'` is a convex set. -/ theorem convex_image_has_deriv_at {s : set ℝ} (hs : convex s) (hf : ∀ x ∈ s, has_deriv_at f (f' x) x) : convex (f' '' s) := begin refine convex_real_iff.2 _, rintros _ _ ⟨a, ha, rfl⟩ ⟨b, hb, rfl⟩ m ⟨hma, hmb⟩, cases eq_or_lt_of_le hma with hma hma, by exact hma ▸ mem_image_of_mem f' ha, cases eq_or_lt_of_le hmb with hmb hmb, by exact hmb.symm ▸ mem_image_of_mem f' hb, cases le_total a b with hab hab, { have : Icc a b ⊆ s, from convex_real_iff.1 hs ha hb, rcases exists_has_deriv_within_at_eq_of_gt_of_lt hab (λ x hx, (hf x $ this hx).has_deriv_within_at) hma hmb with ⟨c, cmem, hc⟩, exact ⟨c, this cmem, hc⟩ }, { have : Icc b a ⊆ s, from convex_real_iff.1 hs hb ha, rcases exists_has_deriv_within_at_eq_of_lt_of_gt hab (λ x hx, (hf x $ this hx).has_deriv_within_at) hmb hma with ⟨c, cmem, hc⟩, exact ⟨c, this cmem, hc⟩ } end /-- If the derivative of a function is never equal to `m`, then either it is always greater than `m`, or it is always less than `m`. -/ theorem deriv_forall_lt_or_forall_gt_of_forall_ne {s : set ℝ} (hs : convex s) (hf : ∀ x ∈ s, has_deriv_at f (f' x) x) {m : ℝ} (hf' : ∀ x ∈ s, f' x ≠ m) : (∀ x ∈ s, f' x < m) ∨ (∀ x ∈ s, m < f' x) := begin contrapose! hf', rcases hf' with ⟨⟨b, hb, hmb⟩, ⟨a, ha, hma⟩⟩, exact convex_real_iff.1 (convex_image_has_deriv_at hs hf) (mem_image_of_mem f' ha) (mem_image_of_mem f' hb) ⟨hma, hmb⟩ end
2db589872e8c61410c8c563bf11a641757bd15a3
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/tactic/unfold_cases.lean
4693a943bada6214277dd871fb6a5a2d60f011d5
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
6,292
lean
/- Copyright (c) 2020 Dany Fabian. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Dany Fabian -/ import tactic.split_ifs /-! # Unfold cases tactic In Lean, pattern matching expressions are not atomic parts of the syntax, but rather they are compiled down into simpler terms that are later checked by the kernel. This allows Lean to have a minimalistic kernel but can occasionally lead an explosion of cases that need to be considered. What looks like one case in the `match` expression can in fact be compiled into many different cases that all need to proved by case analysis. This tactic automates the process by allowing us to write down an equation `f x = y` where we know that `f x = y` is provably true, but does not hold definitionally. In that case the `unfold_cases` tactic will continue unfolding `f` and introducing `cases` where necessary until the left hand side becomes definitionally equal to the right hand side. Consider a definition as follows: ```lean def myand : bool → bool → bool | ff _ := ff | _ ff := ff | _ _ := tt ``` The equation compiler generates 4 equation lemmas for us: ```lean myand ff ff = ff myand ff tt = ff myand tt ff = ff myand tt tt = tt ``` This is not in line with what one might expect looking at the definition. Whilst it is provably true, that `∀ x, myand ff x = ff` and `∀ x, myand x ff = ff`, we do not get these stronger lemmas from the compiler for free but must in fact prove them using `cases` or some other local reasoning. In other words, the following does not constitute a proof that lean accepts. ```lean example : ∀ x, myand ff x = ff := begin intros, refl end ``` However, you can use `unfold_cases { refl }` to prove `∀ x, myand ff x = ff` and `∀ x, myand x ff = ff`. For definitions with many cases, the savings can be very significant. The term that gets generated for the above definition looks like this: ```lean λ (a a_1 : bool), a.cases_on (a_1.cases_on (id_rhs bool ff) (id_rhs bool ff)) (a_1.cases_on (id_rhs bool ff) (id_rhs bool tt)) ``` When the tactic tries to prove the goal `∀ x, myand ff x = ff`, it starts by `intros`, followed by unfolding the definition: ```lean ⊢ ff.cases_on (x.cases_on (id_rhs bool ff) (id_rhs bool ff)) (x.cases_on (id_rhs bool ff) (id_rhs bool tt)) = ff ``` At this point, it can make progress using `dsimp`. But then it gets stuck: ```lean ⊢ bool.rec (id_rhs bool ff) (id_rhs bool ff) x = ff ``` Next, it can introduce a case split on `x`. At this point, it has to prove two goals: ```lean ⊢ bool.rec (id_rhs bool ff) (id_rhs bool ff) ff = ff ⊢ bool.rec (id_rhs bool ff) (id_rhs bool ff) tt = ff ``` Now, however, both goals can be discharged using `refl`. -/ namespace tactic open expr namespace unfold_cases /-- Given an equation `f x = y`, this tactic tries to infer an expression that can be used to do distinction by cases on to make progress. Pre-condition: assumes that the outer-most application cannot be beta-reduced (e.g. `whnf` or `dsimp`). -/ meta def find_splitting_expr : expr → tactic expr | `(@ite _ %%cond %%dec_inst _ _ = _) := pure `(@decidable.em %%cond %%dec_inst) | `(%%(app x y) = _) := pure y | e := fail!"expected an expression of the form: f x = y. Got:\n{e}" /-- Tries to finish the current goal using the `inner` tactic. If the tactic fails, it tries to find an expression on which to do a distinction by cases and calls itself recursively. The order of operations is significant. Because the unfolding can potentially be infinite, it is important to apply the `inner` tactic at every step. Notice, that if the `inner` tactic succeeds, the recursive unfolding is stopped. -/ meta def unfold_cases_core (inner : interactive.itactic) : tactic unit := inner <|> (do split_ifs [], all_goals unfold_cases_core, skip) <|> do tgt ← target, e ← find_splitting_expr tgt, focus1 $ do cases e, all_goals $ (dsimp_target >> unfold_cases_core) <|> skip, skip /-- Given a target of the form `⊢ f x₁ ... xₙ = y`, unfolds `f` using a delta reduction. -/ meta def unfold_tgt : expr → tactic unit | `(%%l@(app _ _) = %%r) := match l.get_app_fn with | const n ls := delta_target [n] | e := fail!"couldn't unfold:\n{e}" end | e := fail!"expected an expression of the form: f x = y. Got:\n{e}" end unfold_cases namespace interactive open unfold_cases /-- This tactic unfolds the definition of a function or `match` expression. Then it recursively introduces a distinction by cases. The decision what expression to do the distinction on is driven by the pattern matching expression. A typical use case is using `unfold_cases { refl }` to collapse cases that need to be considered in a pattern matching. ```lean have h : foo x = y, by unfold_cases { refl }, rw h, ``` The tactic expects a goal in the form of an equation, possibly universally quantified. We can prove a theorem, even if the various case do not directly correspond to the function definition. Here is an example application of the tactic: ```lean def foo : ℕ → ℕ → ℕ | 0 0 := 17 | (n+2) 17 := 17 | 1 0 := 23 | 0 (n+18) := 15 | 0 17 := 17 | 1 17 := 17 | _ (n+18) := 27 | _ _ := 15 example : ∀ x, foo x 17 = 17 := begin unfold_cases { refl }, end ``` The compiler generates 57 cases for `foo`. However, when we look at the definition, we see that whenever the function is applied to `17` in the second argument, it returns `17`. Proving this property consists of merely considering all the cases, eliminating invalid ones and applying `refl` on the ones which remain. Further examples can be found in `test/unfold_cases.lean`. -/ meta def unfold_cases (inner : itactic) : tactic unit := focus1 $ do tactic.intros, tgt ← target, unfold_tgt tgt, try dsimp_target, unfold_cases_core inner add_tactic_doc { name := "unfold_cases", category := doc_category.tactic, decl_names := [`tactic.interactive.unfold_cases], tags := ["induction", "case bashing"] } end interactive end tactic
4941289f4d4d57b12f2ce780b8097f1681a944d3
4727251e0cd73359b15b664c3170e5d754078599
/src/algebra/order/field.lean
7fb60ecc547d235a080940e779ebbbf40ffd5a7d
[ "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
30,385
lean
/- Copyright (c) 2014 Robert Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Lewis, Leonardo de Moura, Mario Carneiro, Floris van Doorn -/ import algebra.field.basic import algebra.group_power.order import algebra.order.ring import order.bounds import tactic.monotonicity.basic /-! # Linear ordered fields A linear ordered field is a field equipped with a linear order such that * addition respects the order: `a ≤ b → c + a ≤ c + b`; * multiplication of positives is positive: `0 < a → 0 < b → 0 < a * b`; * `0 < 1`. ## Main Definitions * `linear_ordered_field`: the class of linear ordered fields. -/ set_option old_structure_cmd true variable {α : Type*} /-- A linear ordered field is a field with a linear order respecting the operations. -/ @[protect_proj] class linear_ordered_field (α : Type*) extends linear_ordered_comm_ring α, field α section linear_ordered_field variables [linear_ordered_field α] {a b c d e : α} section /-- `equiv.mul_left₀` as an order_iso. -/ @[simps {simp_rhs := tt}] def order_iso.mul_left₀ (a : α) (ha : 0 < a) : α ≃o α := { map_rel_iff' := λ _ _, mul_le_mul_left ha, ..equiv.mul_left₀ a ha.ne' } /-- `equiv.mul_right₀` as an order_iso. -/ @[simps {simp_rhs := tt}] def order_iso.mul_right₀ (a : α) (ha : 0 < a) : α ≃o α := { map_rel_iff' := λ _ _, mul_le_mul_right ha, ..equiv.mul_right₀ a ha.ne' } end /-! ### Lemmas about pos, nonneg, nonpos, neg -/ @[simp] lemma inv_pos : 0 < a⁻¹ ↔ 0 < a := suffices ∀ a : α, 0 < a → 0 < a⁻¹, from ⟨λ h, inv_inv a ▸ this _ h, this a⟩, assume a ha, flip lt_of_mul_lt_mul_left ha.le $ by simp [ne_of_gt ha, zero_lt_one] @[simp] lemma inv_nonneg : 0 ≤ a⁻¹ ↔ 0 ≤ a := by simp only [le_iff_eq_or_lt, inv_pos, zero_eq_inv] @[simp] lemma inv_lt_zero : a⁻¹ < 0 ↔ a < 0 := by simp only [← not_le, inv_nonneg] @[simp] lemma inv_nonpos : a⁻¹ ≤ 0 ↔ a ≤ 0 := by simp only [← not_lt, inv_pos] lemma one_div_pos : 0 < 1 / a ↔ 0 < a := inv_eq_one_div a ▸ inv_pos lemma one_div_neg : 1 / a < 0 ↔ a < 0 := inv_eq_one_div a ▸ inv_lt_zero lemma one_div_nonneg : 0 ≤ 1 / a ↔ 0 ≤ a := inv_eq_one_div a ▸ inv_nonneg lemma one_div_nonpos : 1 / a ≤ 0 ↔ a ≤ 0 := inv_eq_one_div a ▸ inv_nonpos lemma div_pos_iff : 0 < a / b ↔ 0 < a ∧ 0 < b ∨ a < 0 ∧ b < 0 := by simp [division_def, mul_pos_iff] lemma div_neg_iff : a / b < 0 ↔ 0 < a ∧ b < 0 ∨ a < 0 ∧ 0 < b := by simp [division_def, mul_neg_iff] lemma div_nonneg_iff : 0 ≤ a / b ↔ 0 ≤ a ∧ 0 ≤ b ∨ a ≤ 0 ∧ b ≤ 0 := by simp [division_def, mul_nonneg_iff] lemma div_nonpos_iff : a / b ≤ 0 ↔ 0 ≤ a ∧ b ≤ 0 ∨ a ≤ 0 ∧ 0 ≤ b := by simp [division_def, mul_nonpos_iff] lemma div_pos (ha : 0 < a) (hb : 0 < b) : 0 < a / b := div_pos_iff.2 $ or.inl ⟨ha, hb⟩ lemma div_pos_of_neg_of_neg (ha : a < 0) (hb : b < 0) : 0 < a / b := div_pos_iff.2 $ or.inr ⟨ha, hb⟩ lemma div_neg_of_neg_of_pos (ha : a < 0) (hb : 0 < b) : a / b < 0 := div_neg_iff.2 $ or.inr ⟨ha, hb⟩ lemma div_neg_of_pos_of_neg (ha : 0 < a) (hb : b < 0) : a / b < 0 := div_neg_iff.2 $ or.inl ⟨ha, hb⟩ lemma div_nonneg (ha : 0 ≤ a) (hb : 0 ≤ b) : 0 ≤ a / b := div_nonneg_iff.2 $ or.inl ⟨ha, hb⟩ lemma div_nonneg_of_nonpos (ha : a ≤ 0) (hb : b ≤ 0) : 0 ≤ a / b := div_nonneg_iff.2 $ or.inr ⟨ha, hb⟩ lemma div_nonpos_of_nonpos_of_nonneg (ha : a ≤ 0) (hb : 0 ≤ b) : a / b ≤ 0 := div_nonpos_iff.2 $ or.inr ⟨ha, hb⟩ lemma div_nonpos_of_nonneg_of_nonpos (ha : 0 ≤ a) (hb : b ≤ 0) : a / b ≤ 0 := div_nonpos_iff.2 $ or.inl ⟨ha, hb⟩ /-! ### Relating one division with another term. -/ lemma le_div_iff (hc : 0 < c) : a ≤ b / c ↔ a * c ≤ b := ⟨λ h, div_mul_cancel b (ne_of_lt hc).symm ▸ mul_le_mul_of_nonneg_right h hc.le, λ h, calc a = a * c * (1 / c) : mul_mul_div a (ne_of_lt hc).symm ... ≤ b * (1 / c) : mul_le_mul_of_nonneg_right h (one_div_pos.2 hc).le ... = b / c : (div_eq_mul_one_div b c).symm⟩ lemma le_div_iff' (hc : 0 < c) : a ≤ b / c ↔ c * a ≤ b := by rw [mul_comm, le_div_iff hc] lemma div_le_iff (hb : 0 < b) : a / b ≤ c ↔ a ≤ c * b := ⟨λ h, calc a = a / b * b : by rw (div_mul_cancel _ (ne_of_lt hb).symm) ... ≤ c * b : mul_le_mul_of_nonneg_right h hb.le, λ h, calc a / b = a * (1 / b) : div_eq_mul_one_div a b ... ≤ (c * b) * (1 / b) : mul_le_mul_of_nonneg_right h (one_div_pos.2 hb).le ... = (c * b) / b : (div_eq_mul_one_div (c * b) b).symm ... = c : by refine (div_eq_iff (ne_of_gt hb)).mpr rfl⟩ lemma div_le_iff' (hb : 0 < b) : a / b ≤ c ↔ a ≤ b * c := by rw [mul_comm, div_le_iff hb] lemma lt_div_iff (hc : 0 < c) : a < b / c ↔ a * c < b := lt_iff_lt_of_le_iff_le $ div_le_iff hc lemma lt_div_iff' (hc : 0 < c) : a < b / c ↔ c * a < b := by rw [mul_comm, lt_div_iff hc] lemma div_lt_iff (hc : 0 < c) : b / c < a ↔ b < a * c := lt_iff_lt_of_le_iff_le (le_div_iff hc) lemma div_lt_iff' (hc : 0 < c) : b / c < a ↔ b < c * a := by rw [mul_comm, div_lt_iff hc] lemma inv_mul_le_iff (h : 0 < b) : b⁻¹ * a ≤ c ↔ a ≤ b * c := begin rw [inv_eq_one_div, mul_comm, ← div_eq_mul_one_div], exact div_le_iff' h, end lemma inv_mul_le_iff' (h : 0 < b) : b⁻¹ * a ≤ c ↔ a ≤ c * b := by rw [inv_mul_le_iff h, mul_comm] lemma mul_inv_le_iff (h : 0 < b) : a * b⁻¹ ≤ c ↔ a ≤ b * c := by rw [mul_comm, inv_mul_le_iff h] lemma mul_inv_le_iff' (h : 0 < b) : a * b⁻¹ ≤ c ↔ a ≤ c * b := by rw [mul_comm, inv_mul_le_iff' h] lemma div_self_le_one (a : α) : a / a ≤ 1 := if h : a = 0 then by simp [h] else by simp [h] lemma inv_mul_lt_iff (h : 0 < b) : b⁻¹ * a < c ↔ a < b * c := begin rw [inv_eq_one_div, mul_comm, ← div_eq_mul_one_div], exact div_lt_iff' h, end lemma inv_mul_lt_iff' (h : 0 < b) : b⁻¹ * a < c ↔ a < c * b := by rw [inv_mul_lt_iff h, mul_comm] lemma mul_inv_lt_iff (h : 0 < b) : a * b⁻¹ < c ↔ a < b * c := by rw [mul_comm, inv_mul_lt_iff h] lemma mul_inv_lt_iff' (h : 0 < b) : a * b⁻¹ < c ↔ a < c * b := by rw [mul_comm, inv_mul_lt_iff' h] lemma inv_pos_le_iff_one_le_mul (ha : 0 < a) : a⁻¹ ≤ b ↔ 1 ≤ b * a := by { rw [inv_eq_one_div], exact div_le_iff ha } lemma inv_pos_le_iff_one_le_mul' (ha : 0 < a) : a⁻¹ ≤ b ↔ 1 ≤ a * b := by { rw [inv_eq_one_div], exact div_le_iff' ha } lemma inv_pos_lt_iff_one_lt_mul (ha : 0 < a) : a⁻¹ < b ↔ 1 < b * a := by { rw [inv_eq_one_div], exact div_lt_iff ha } lemma inv_pos_lt_iff_one_lt_mul' (ha : 0 < a) : a⁻¹ < b ↔ 1 < a * b := by { rw [inv_eq_one_div], exact div_lt_iff' ha } lemma div_le_iff_of_neg (hc : c < 0) : b / c ≤ a ↔ a * c ≤ b := ⟨λ h, div_mul_cancel b (ne_of_lt hc) ▸ mul_le_mul_of_nonpos_right h hc.le, λ h, calc a = a * c * (1 / c) : mul_mul_div a (ne_of_lt hc) ... ≥ b * (1 / c) : mul_le_mul_of_nonpos_right h (one_div_neg.2 hc).le ... = b / c : (div_eq_mul_one_div b c).symm⟩ lemma div_le_iff_of_neg' (hc : c < 0) : b / c ≤ a ↔ c * a ≤ b := by rw [mul_comm, div_le_iff_of_neg hc] lemma le_div_iff_of_neg (hc : c < 0) : a ≤ b / c ↔ b ≤ a * c := by rw [← neg_neg c, mul_neg, div_neg, le_neg, div_le_iff (neg_pos.2 hc), neg_mul] lemma le_div_iff_of_neg' (hc : c < 0) : a ≤ b / c ↔ b ≤ c * a := by rw [mul_comm, le_div_iff_of_neg hc] lemma div_lt_iff_of_neg (hc : c < 0) : b / c < a ↔ a * c < b := lt_iff_lt_of_le_iff_le $ le_div_iff_of_neg hc lemma div_lt_iff_of_neg' (hc : c < 0) : b / c < a ↔ c * a < b := by rw [mul_comm, div_lt_iff_of_neg hc] lemma lt_div_iff_of_neg (hc : c < 0) : a < b / c ↔ b < a * c := lt_iff_lt_of_le_iff_le $ div_le_iff_of_neg hc lemma lt_div_iff_of_neg' (hc : c < 0) : a < b / c ↔ b < c * a := by rw [mul_comm, lt_div_iff_of_neg hc] /-- One direction of `div_le_iff` where `b` is allowed to be `0` (but `c` must be nonnegative) -/ lemma div_le_of_nonneg_of_le_mul (hb : 0 ≤ b) (hc : 0 ≤ c) (h : a ≤ c * b) : a / b ≤ c := by { rcases eq_or_lt_of_le hb with rfl|hb', simp [hc], rwa [div_le_iff hb'] } lemma div_le_one_of_le (h : a ≤ b) (hb : 0 ≤ b) : a / b ≤ 1 := div_le_of_nonneg_of_le_mul hb zero_le_one $ by rwa one_mul /-! ### Bi-implications of inequalities using inversions -/ lemma inv_le_inv_of_le (ha : 0 < a) (h : a ≤ b) : b⁻¹ ≤ a⁻¹ := by rwa [← one_div a, le_div_iff' ha, ← div_eq_mul_inv, div_le_iff (ha.trans_le h), one_mul] /-- See `inv_le_inv_of_le` for the implication from right-to-left with one fewer assumption. -/ lemma inv_le_inv (ha : 0 < a) (hb : 0 < b) : a⁻¹ ≤ b⁻¹ ↔ b ≤ a := by rw [← one_div, div_le_iff ha, ← div_eq_inv_mul, le_div_iff hb, one_mul] /-- In a linear ordered field, for positive `a` and `b` we have `a⁻¹ ≤ b ↔ b⁻¹ ≤ a`. See also `inv_le_of_inv_le` for a one-sided implication with one fewer assumption. -/ lemma inv_le (ha : 0 < a) (hb : 0 < b) : a⁻¹ ≤ b ↔ b⁻¹ ≤ a := by rw [← inv_le_inv hb (inv_pos.2 ha), inv_inv] lemma inv_le_of_inv_le (ha : 0 < a) (h : a⁻¹ ≤ b) : b⁻¹ ≤ a := (inv_le ha ((inv_pos.2 ha).trans_le h)).1 h lemma le_inv (ha : 0 < a) (hb : 0 < b) : a ≤ b⁻¹ ↔ b ≤ a⁻¹ := by rw [← inv_le_inv (inv_pos.2 hb) ha, inv_inv] lemma inv_lt_inv (ha : 0 < a) (hb : 0 < b) : a⁻¹ < b⁻¹ ↔ b < a := lt_iff_lt_of_le_iff_le (inv_le_inv hb ha) /-- In a linear ordered field, for positive `a` and `b` we have `a⁻¹ < b ↔ b⁻¹ < a`. See also `inv_lt_of_inv_lt` for a one-sided implication with one fewer assumption. -/ lemma inv_lt (ha : 0 < a) (hb : 0 < b) : a⁻¹ < b ↔ b⁻¹ < a := lt_iff_lt_of_le_iff_le (le_inv hb ha) lemma inv_lt_of_inv_lt (ha : 0 < a) (h : a⁻¹ < b) : b⁻¹ < a := (inv_lt ha ((inv_pos.2 ha).trans h)).1 h lemma lt_inv (ha : 0 < a) (hb : 0 < b) : a < b⁻¹ ↔ b < a⁻¹ := lt_iff_lt_of_le_iff_le (inv_le hb ha) lemma inv_le_inv_of_neg (ha : a < 0) (hb : b < 0) : a⁻¹ ≤ b⁻¹ ↔ b ≤ a := by rw [← one_div, div_le_iff_of_neg ha, ← div_eq_inv_mul, div_le_iff_of_neg hb, one_mul] lemma inv_le_of_neg (ha : a < 0) (hb : b < 0) : a⁻¹ ≤ b ↔ b⁻¹ ≤ a := by rw [← inv_le_inv_of_neg hb (inv_lt_zero.2 ha), inv_inv] lemma le_inv_of_neg (ha : a < 0) (hb : b < 0) : a ≤ b⁻¹ ↔ b ≤ a⁻¹ := by rw [← inv_le_inv_of_neg (inv_lt_zero.2 hb) ha, inv_inv] lemma inv_lt_inv_of_neg (ha : a < 0) (hb : b < 0) : a⁻¹ < b⁻¹ ↔ b < a := lt_iff_lt_of_le_iff_le (inv_le_inv_of_neg hb ha) lemma inv_lt_of_neg (ha : a < 0) (hb : b < 0) : a⁻¹ < b ↔ b⁻¹ < a := lt_iff_lt_of_le_iff_le (le_inv_of_neg hb ha) lemma lt_inv_of_neg (ha : a < 0) (hb : b < 0) : a < b⁻¹ ↔ b < a⁻¹ := lt_iff_lt_of_le_iff_le (inv_le_of_neg hb ha) lemma inv_lt_one (ha : 1 < a) : a⁻¹ < 1 := by rwa [inv_lt ((@zero_lt_one α _ _).trans ha) zero_lt_one, inv_one] lemma one_lt_inv (h₁ : 0 < a) (h₂ : a < 1) : 1 < a⁻¹ := by rwa [lt_inv (@zero_lt_one α _ _) h₁, inv_one] lemma inv_le_one (ha : 1 ≤ a) : a⁻¹ ≤ 1 := by rwa [inv_le ((@zero_lt_one α _ _).trans_le ha) zero_lt_one, inv_one] lemma one_le_inv (h₁ : 0 < a) (h₂ : a ≤ 1) : 1 ≤ a⁻¹ := by rwa [le_inv (@zero_lt_one α _ _) h₁, inv_one] lemma inv_lt_one_iff_of_pos (h₀ : 0 < a) : a⁻¹ < 1 ↔ 1 < a := ⟨λ h₁, inv_inv a ▸ one_lt_inv (inv_pos.2 h₀) h₁, inv_lt_one⟩ lemma inv_lt_one_iff : a⁻¹ < 1 ↔ a ≤ 0 ∨ 1 < a := begin cases le_or_lt a 0 with ha ha, { simp [ha, (inv_nonpos.2 ha).trans_lt zero_lt_one] }, { simp only [ha.not_le, false_or, inv_lt_one_iff_of_pos ha] } end lemma one_lt_inv_iff : 1 < a⁻¹ ↔ 0 < a ∧ a < 1 := ⟨λ h, ⟨inv_pos.1 (zero_lt_one.trans h), inv_inv a ▸ inv_lt_one h⟩, and_imp.2 one_lt_inv⟩ lemma inv_le_one_iff : a⁻¹ ≤ 1 ↔ a ≤ 0 ∨ 1 ≤ a := begin rcases em (a = 1) with (rfl|ha), { simp [le_rfl] }, { simp only [ne.le_iff_lt (ne.symm ha), ne.le_iff_lt (mt inv_eq_one.1 ha), inv_lt_one_iff] } end lemma one_le_inv_iff : 1 ≤ a⁻¹ ↔ 0 < a ∧ a ≤ 1 := ⟨λ h, ⟨inv_pos.1 (zero_lt_one.trans_le h), inv_inv a ▸ inv_le_one h⟩, and_imp.2 one_le_inv⟩ /-! ### Relating two divisions. -/ @[mono] lemma div_le_div_of_le (hc : 0 ≤ c) (h : a ≤ b) : a / c ≤ b / c := begin rw [div_eq_mul_one_div a c, div_eq_mul_one_div b c], exact mul_le_mul_of_nonneg_right h (one_div_nonneg.2 hc) end -- Not a `mono` lemma b/c `div_le_div` is strictly more general lemma div_le_div_of_le_left (ha : 0 ≤ a) (hc : 0 < c) (h : c ≤ b) : a / b ≤ a / c := begin rw [div_eq_mul_inv, div_eq_mul_inv], exact mul_le_mul_of_nonneg_left ((inv_le_inv (hc.trans_le h) hc).mpr h) ha end lemma div_le_div_of_le_of_nonneg (hab : a ≤ b) (hc : 0 ≤ c) : a / c ≤ b / c := div_le_div_of_le hc hab lemma div_le_div_of_nonpos_of_le (hc : c ≤ 0) (h : b ≤ a) : a / c ≤ b / c := begin rw [div_eq_mul_one_div a c, div_eq_mul_one_div b c], exact mul_le_mul_of_nonpos_right h (one_div_nonpos.2 hc) end lemma div_lt_div_of_lt (hc : 0 < c) (h : a < b) : a / c < b / c := begin rw [div_eq_mul_one_div a c, div_eq_mul_one_div b c], exact mul_lt_mul_of_pos_right h (one_div_pos.2 hc) end lemma div_lt_div_of_neg_of_lt (hc : c < 0) (h : b < a) : a / c < b / c := begin rw [div_eq_mul_one_div a c, div_eq_mul_one_div b c], exact mul_lt_mul_of_neg_right h (one_div_neg.2 hc) end lemma div_le_div_right (hc : 0 < c) : a / c ≤ b / c ↔ a ≤ b := ⟨le_imp_le_of_lt_imp_lt $ div_lt_div_of_lt hc, div_le_div_of_le $ hc.le⟩ lemma div_le_div_right_of_neg (hc : c < 0) : a / c ≤ b / c ↔ b ≤ a := ⟨le_imp_le_of_lt_imp_lt $ div_lt_div_of_neg_of_lt hc, div_le_div_of_nonpos_of_le $ hc.le⟩ lemma div_lt_div_right (hc : 0 < c) : a / c < b / c ↔ a < b := lt_iff_lt_of_le_iff_le $ div_le_div_right hc lemma div_lt_div_right_of_neg (hc : c < 0) : a / c < b / c ↔ b < a := lt_iff_lt_of_le_iff_le $ div_le_div_right_of_neg hc lemma div_lt_div_left (ha : 0 < a) (hb : 0 < b) (hc : 0 < c) : a / b < a / c ↔ c < b := by simp only [div_eq_mul_inv, mul_lt_mul_left ha, inv_lt_inv hb hc] lemma div_le_div_left (ha : 0 < a) (hb : 0 < b) (hc : 0 < c) : a / b ≤ a / c ↔ c ≤ b := le_iff_le_iff_lt_iff_lt.2 (div_lt_div_left ha hc hb) lemma div_lt_div_iff (b0 : 0 < b) (d0 : 0 < d) : a / b < c / d ↔ a * d < c * b := by rw [lt_div_iff d0, div_mul_eq_mul_div, div_lt_iff b0] lemma div_le_div_iff (b0 : 0 < b) (d0 : 0 < d) : a / b ≤ c / d ↔ a * d ≤ c * b := by rw [le_div_iff d0, div_mul_eq_mul_div, div_le_iff b0] @[mono] lemma div_le_div (hc : 0 ≤ c) (hac : a ≤ c) (hd : 0 < d) (hbd : d ≤ b) : a / b ≤ c / d := by { rw div_le_div_iff (hd.trans_le hbd) hd, exact mul_le_mul hac hbd hd.le hc } lemma div_lt_div (hac : a < c) (hbd : d ≤ b) (c0 : 0 ≤ c) (d0 : 0 < d) : a / b < c / d := (div_lt_div_iff (d0.trans_le hbd) d0).2 (mul_lt_mul hac hbd d0 c0) lemma div_lt_div' (hac : a ≤ c) (hbd : d < b) (c0 : 0 < c) (d0 : 0 < d) : a / b < c / d := (div_lt_div_iff (d0.trans hbd) d0).2 (mul_lt_mul' hac hbd d0.le c0) lemma div_lt_div_of_lt_left (hc : 0 < c) (hb : 0 < b) (h : b < a) : c / a < c / b := (div_lt_div_left hc (hb.trans h) hb).mpr h /-! ### Relating one division and involving `1` -/ lemma div_le_self (ha : 0 ≤ a) (hb : 1 ≤ b) : a / b ≤ a := by simpa only [div_one] using div_le_div_of_le_left ha zero_lt_one hb lemma div_lt_self (ha : 0 < a) (hb : 1 < b) : a / b < a := by simpa only [div_one] using div_lt_div_of_lt_left ha zero_lt_one hb lemma le_div_self (ha : 0 ≤ a) (hb₀ : 0 < b) (hb₁ : b ≤ 1) : a ≤ a / b := by simpa only [div_one] using div_le_div_of_le_left ha hb₀ hb₁ lemma one_le_div (hb : 0 < b) : 1 ≤ a / b ↔ b ≤ a := by rw [le_div_iff hb, one_mul] lemma div_le_one (hb : 0 < b) : a / b ≤ 1 ↔ a ≤ b := by rw [div_le_iff hb, one_mul] lemma one_lt_div (hb : 0 < b) : 1 < a / b ↔ b < a := by rw [lt_div_iff hb, one_mul] lemma div_lt_one (hb : 0 < b) : a / b < 1 ↔ a < b := by rw [div_lt_iff hb, one_mul] lemma one_le_div_of_neg (hb : b < 0) : 1 ≤ a / b ↔ a ≤ b := by rw [le_div_iff_of_neg hb, one_mul] lemma div_le_one_of_neg (hb : b < 0) : a / b ≤ 1 ↔ b ≤ a := by rw [div_le_iff_of_neg hb, one_mul] lemma one_lt_div_of_neg (hb : b < 0) : 1 < a / b ↔ a < b := by rw [lt_div_iff_of_neg hb, one_mul] lemma div_lt_one_of_neg (hb : b < 0) : a / b < 1 ↔ b < a := by rw [div_lt_iff_of_neg hb, one_mul] lemma one_div_le (ha : 0 < a) (hb : 0 < b) : 1 / a ≤ b ↔ 1 / b ≤ a := by simpa using inv_le ha hb lemma one_div_lt (ha : 0 < a) (hb : 0 < b) : 1 / a < b ↔ 1 / b < a := by simpa using inv_lt ha hb lemma le_one_div (ha : 0 < a) (hb : 0 < b) : a ≤ 1 / b ↔ b ≤ 1 / a := by simpa using le_inv ha hb lemma lt_one_div (ha : 0 < a) (hb : 0 < b) : a < 1 / b ↔ b < 1 / a := by simpa using lt_inv ha hb lemma one_div_le_of_neg (ha : a < 0) (hb : b < 0) : 1 / a ≤ b ↔ 1 / b ≤ a := by simpa using inv_le_of_neg ha hb lemma one_div_lt_of_neg (ha : a < 0) (hb : b < 0) : 1 / a < b ↔ 1 / b < a := by simpa using inv_lt_of_neg ha hb lemma le_one_div_of_neg (ha : a < 0) (hb : b < 0) : a ≤ 1 / b ↔ b ≤ 1 / a := by simpa using le_inv_of_neg ha hb lemma lt_one_div_of_neg (ha : a < 0) (hb : b < 0) : a < 1 / b ↔ b < 1 / a := by simpa using lt_inv_of_neg ha hb lemma one_lt_div_iff : 1 < a / b ↔ 0 < b ∧ b < a ∨ b < 0 ∧ a < b := begin rcases lt_trichotomy b 0 with (hb|rfl|hb), { simp [hb, hb.not_lt, one_lt_div_of_neg] }, { simp [lt_irrefl, zero_le_one] }, { simp [hb, hb.not_lt, one_lt_div] } end lemma one_le_div_iff : 1 ≤ a / b ↔ 0 < b ∧ b ≤ a ∨ b < 0 ∧ a ≤ b := begin rcases lt_trichotomy b 0 with (hb|rfl|hb), { simp [hb, hb.not_lt, one_le_div_of_neg] }, { simp [lt_irrefl, zero_lt_one.not_le, zero_lt_one] }, { simp [hb, hb.not_lt, one_le_div] } end lemma div_lt_one_iff : a / b < 1 ↔ 0 < b ∧ a < b ∨ b = 0 ∨ b < 0 ∧ b < a := begin rcases lt_trichotomy b 0 with (hb|rfl|hb), { simp [hb, hb.not_lt, hb.ne, div_lt_one_of_neg] }, { simp [zero_lt_one], }, { simp [hb, hb.not_lt, div_lt_one, hb.ne.symm] } end lemma div_le_one_iff : a / b ≤ 1 ↔ 0 < b ∧ a ≤ b ∨ b = 0 ∨ b < 0 ∧ b ≤ a := begin rcases lt_trichotomy b 0 with (hb|rfl|hb), { simp [hb, hb.not_lt, hb.ne, div_le_one_of_neg] }, { simp [zero_le_one], }, { simp [hb, hb.not_lt, div_le_one, hb.ne.symm] } end /-! ### Relating two divisions, involving `1` -/ lemma one_div_le_one_div_of_le (ha : 0 < a) (h : a ≤ b) : 1 / b ≤ 1 / a := by simpa using inv_le_inv_of_le ha h lemma one_div_lt_one_div_of_lt (ha : 0 < a) (h : a < b) : 1 / b < 1 / a := by rwa [lt_div_iff' ha, ← div_eq_mul_one_div, div_lt_one (ha.trans h)] lemma one_div_le_one_div_of_neg_of_le (hb : b < 0) (h : a ≤ b) : 1 / b ≤ 1 / a := by rwa [div_le_iff_of_neg' hb, ← div_eq_mul_one_div, div_le_one_of_neg (h.trans_lt hb)] lemma one_div_lt_one_div_of_neg_of_lt (hb : b < 0) (h : a < b) : 1 / b < 1 / a := by rwa [div_lt_iff_of_neg' hb, ← div_eq_mul_one_div, div_lt_one_of_neg (h.trans hb)] lemma le_of_one_div_le_one_div (ha : 0 < a) (h : 1 / a ≤ 1 / b) : b ≤ a := le_imp_le_of_lt_imp_lt (one_div_lt_one_div_of_lt ha) h lemma lt_of_one_div_lt_one_div (ha : 0 < a) (h : 1 / a < 1 / b) : b < a := lt_imp_lt_of_le_imp_le (one_div_le_one_div_of_le ha) h lemma le_of_neg_of_one_div_le_one_div (hb : b < 0) (h : 1 / a ≤ 1 / b) : b ≤ a := le_imp_le_of_lt_imp_lt (one_div_lt_one_div_of_neg_of_lt hb) h lemma lt_of_neg_of_one_div_lt_one_div (hb : b < 0) (h : 1 / a < 1 / b) : b < a := lt_imp_lt_of_le_imp_le (one_div_le_one_div_of_neg_of_le hb) h /-- For the single implications with fewer assumptions, see `one_div_le_one_div_of_le` and `le_of_one_div_le_one_div` -/ lemma one_div_le_one_div (ha : 0 < a) (hb : 0 < b) : 1 / a ≤ 1 / b ↔ b ≤ a := div_le_div_left zero_lt_one ha hb /-- For the single implications with fewer assumptions, see `one_div_lt_one_div_of_lt` and `lt_of_one_div_lt_one_div` -/ lemma one_div_lt_one_div (ha : 0 < a) (hb : 0 < b) : 1 / a < 1 / b ↔ b < a := div_lt_div_left zero_lt_one ha hb /-- For the single implications with fewer assumptions, see `one_div_lt_one_div_of_neg_of_lt` and `lt_of_one_div_lt_one_div` -/ lemma one_div_le_one_div_of_neg (ha : a < 0) (hb : b < 0) : 1 / a ≤ 1 / b ↔ b ≤ a := by simpa [one_div] using inv_le_inv_of_neg ha hb /-- For the single implications with fewer assumptions, see `one_div_lt_one_div_of_lt` and `lt_of_one_div_lt_one_div` -/ lemma one_div_lt_one_div_of_neg (ha : a < 0) (hb : b < 0) : 1 / a < 1 / b ↔ b < a := lt_iff_lt_of_le_iff_le (one_div_le_one_div_of_neg hb ha) lemma one_lt_one_div (h1 : 0 < a) (h2 : a < 1) : 1 < 1 / a := by rwa [lt_one_div (@zero_lt_one α _ _) h1, one_div_one] lemma one_le_one_div (h1 : 0 < a) (h2 : a ≤ 1) : 1 ≤ 1 / a := by rwa [le_one_div (@zero_lt_one α _ _) h1, one_div_one] lemma one_div_lt_neg_one (h1 : a < 0) (h2 : -1 < a) : 1 / a < -1 := suffices 1 / a < 1 / -1, by rwa one_div_neg_one_eq_neg_one at this, one_div_lt_one_div_of_neg_of_lt h1 h2 lemma one_div_le_neg_one (h1 : a < 0) (h2 : -1 ≤ a) : 1 / a ≤ -1 := suffices 1 / a ≤ 1 / -1, by rwa one_div_neg_one_eq_neg_one at this, one_div_le_one_div_of_neg_of_le h1 h2 /-! ### Results about halving. The equalities also hold in fields of characteristic `0`. -/ lemma add_halves (a : α) : a / 2 + a / 2 = a := by rw [div_add_div_same, ← two_mul, mul_div_cancel_left a two_ne_zero] lemma sub_self_div_two (a : α) : a - a / 2 = a / 2 := suffices a / 2 + a / 2 - a / 2 = a / 2, by rwa add_halves at this, by rw [add_sub_cancel] lemma div_two_sub_self (a : α) : a / 2 - a = - (a / 2) := suffices a / 2 - (a / 2 + a / 2) = - (a / 2), by rwa add_halves at this, by rw [sub_add_eq_sub_sub, sub_self, zero_sub] lemma add_self_div_two (a : α) : (a + a) / 2 = a := by rw [← mul_two, mul_div_cancel a two_ne_zero] lemma half_pos (h : 0 < a) : 0 < a / 2 := div_pos h zero_lt_two lemma one_half_pos : (0:α) < 1 / 2 := half_pos zero_lt_one lemma div_two_lt_of_pos (h : 0 < a) : a / 2 < a := by { rw [div_lt_iff (@zero_lt_two α _ _)], exact lt_mul_of_one_lt_right h one_lt_two } lemma half_lt_self : 0 < a → a / 2 < a := div_two_lt_of_pos lemma half_le_self (ha_nonneg : 0 ≤ a) : a / 2 ≤ a := begin by_cases h0 : a = 0, { simp [h0], }, { rw ← ne.def at h0, exact (half_lt_self (lt_of_le_of_ne ha_nonneg h0.symm)).le, }, end lemma one_half_lt_one : (1 / 2 : α) < 1 := half_lt_self zero_lt_one lemma add_sub_div_two_lt (h : a < b) : a + (b - a) / 2 < b := begin rwa [← div_sub_div_same, sub_eq_add_neg, add_comm (b/2), ← add_assoc, ← sub_eq_add_neg, ← lt_sub_iff_add_lt, sub_self_div_two, sub_self_div_two, div_lt_div_right (@zero_lt_two α _ _)] end lemma left_lt_add_div_two : a < (a + b) / 2 ↔ a < b := by simp [lt_div_iff, mul_two] lemma add_div_two_lt_right : (a + b) / 2 < b ↔ a < b := by simp [div_lt_iff, mul_two] /-- An inequality involving `2`. -/ lemma sub_one_div_inv_le_two (a2 : 2 ≤ a) : (1 - 1 / a)⁻¹ ≤ 2 := begin -- Take inverses on both sides to obtain `2⁻¹ ≤ 1 - 1 / a` refine trans (inv_le_inv_of_le (inv_pos.mpr zero_lt_two) _) (inv_inv (2 : α)).le, -- move `1 / a` to the left and `1 - 1 / 2 = 1 / 2` to the right to obtain `1 / a ≤ ⅟ 2` refine trans ((le_sub_iff_add_le.mpr ((_ : _ + 2⁻¹ = _ ).le))) ((sub_le_sub_iff_left 1).mpr _), { -- show 2⁻¹ + 2⁻¹ = 1 exact trans (two_mul _).symm (mul_inv_cancel two_ne_zero) }, { -- take inverses on both sides and use the assumption `2 ≤ a`. exact (one_div a).le.trans (inv_le_inv_of_le zero_lt_two a2) } end /-! ### Miscellaneous lemmas -/ /-- Pullback a `linear_ordered_field` under an injective map. See note [reducible non-instances]. -/ @[reducible] def function.injective.linear_ordered_field {β : Type*} [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] [has_sub β] [has_inv β] [has_div β] [has_scalar ℕ β] [has_scalar ℤ β] [has_pow β ℕ] [has_pow β ℤ] (f : β → α) (hf : function.injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (-x) = -f x) (sub : ∀ x y, f (x - y) = f x - f y) (inv : ∀ x, f (x⁻¹) = (f x)⁻¹) (div : ∀ x y, f (x / y) = f x / f y) (nsmul : ∀ x (n : ℕ), f (n • x) = n • f x) (zsmul : ∀ x (n : ℤ), f (n • x) = n • f x) (npow : ∀ x (n : ℕ), f (x ^ n) = f x ^ n) (zpow : ∀ x (n : ℤ), f (x ^ n) = f x ^ n): linear_ordered_field β := { ..hf.linear_ordered_ring f zero one add mul neg sub nsmul zsmul npow, ..hf.field f zero one add mul neg sub inv div nsmul zsmul npow zpow} lemma mul_sub_mul_div_mul_neg_iff (hc : c ≠ 0) (hd : d ≠ 0) : (a * d - b * c) / (c * d) < 0 ↔ a / c < b / d := by rw [mul_comm b c, ← div_sub_div _ _ hc hd, sub_lt_zero] alias mul_sub_mul_div_mul_neg_iff ↔ div_lt_div_of_mul_sub_mul_div_neg mul_sub_mul_div_mul_neg lemma mul_sub_mul_div_mul_nonpos_iff (hc : c ≠ 0) (hd : d ≠ 0) : (a * d - b * c) / (c * d) ≤ 0 ↔ a / c ≤ b / d := by rw [mul_comm b c, ← div_sub_div _ _ hc hd, sub_nonpos] alias mul_sub_mul_div_mul_nonpos_iff ↔ div_le_div_of_mul_sub_mul_div_nonpos mul_sub_mul_div_mul_nonpos lemma mul_le_mul_of_mul_div_le (h : a * (b / c) ≤ d) (hc : 0 < c) : b * a ≤ d * c := begin rw [← mul_div_assoc] at h, rwa [mul_comm b, ← div_le_iff hc], end lemma div_mul_le_div_mul_of_div_le_div (h : a / b ≤ c / d) (he : 0 ≤ e) : a / (b * e) ≤ c / (d * e) := begin rw [div_mul_eq_div_mul_one_div, div_mul_eq_div_mul_one_div], exact mul_le_mul_of_nonneg_right h (one_div_nonneg.2 he) end lemma exists_add_lt_and_pos_of_lt (h : b < a) : ∃ c : α, b + c < a ∧ 0 < c := ⟨(a - b) / 2, add_sub_div_two_lt h, div_pos (sub_pos_of_lt h) zero_lt_two⟩ lemma exists_pos_mul_lt {a : α} (h : 0 < a) (b : α) : ∃ c : α, 0 < c ∧ b * c < a := begin have : 0 < a / max (b + 1) 1, from div_pos h (lt_max_iff.2 (or.inr zero_lt_one)), refine ⟨a / max (b + 1) 1, this, _⟩, rw [← lt_div_iff this, div_div_cancel' h.ne'], exact lt_max_iff.2 (or.inl $ lt_add_one _) end lemma le_of_forall_sub_le (h : ∀ ε > 0, b - ε ≤ a) : b ≤ a := begin contrapose! h, simpa only [and_comm ((0 : α) < _), lt_sub_iff_add_lt, gt_iff_lt] using exists_add_lt_and_pos_of_lt h, end lemma monotone.div_const {β : Type*} [preorder β] {f : β → α} (hf : monotone f) {c : α} (hc : 0 ≤ c) : monotone (λ x, (f x) / c) := by simpa only [div_eq_mul_inv] using hf.mul_const (inv_nonneg.2 hc) lemma strict_mono.div_const {β : Type*} [preorder β] {f : β → α} (hf : strict_mono f) {c : α} (hc : 0 < c) : strict_mono (λ x, (f x) / c) := by simpa only [div_eq_mul_inv] using hf.mul_const (inv_pos.2 hc) @[priority 100] -- see Note [lower instance priority] instance linear_ordered_field.to_densely_ordered : densely_ordered α := { dense := λ a₁ a₂ h, ⟨(a₁ + a₂) / 2, calc a₁ = (a₁ + a₁) / 2 : (add_self_div_two a₁).symm ... < (a₁ + a₂) / 2 : div_lt_div_of_lt zero_lt_two (add_lt_add_left h _), calc (a₁ + a₂) / 2 < (a₂ + a₂) / 2 : div_lt_div_of_lt zero_lt_two (add_lt_add_right h _) ... = a₂ : add_self_div_two a₂⟩ } lemma mul_self_inj_of_nonneg (a0 : 0 ≤ a) (b0 : 0 ≤ b) : a * a = b * b ↔ a = b := mul_self_eq_mul_self_iff.trans $ or_iff_left_of_imp $ λ h, by { subst a, have : b = 0 := le_antisymm (neg_nonneg.1 a0) b0, rw [this, neg_zero] } lemma min_div_div_right {c : α} (hc : 0 ≤ c) (a b : α) : min (a / c) (b / c) = (min a b) / c := eq.symm $ monotone.map_min (λ x y, div_le_div_of_le hc) lemma max_div_div_right {c : α} (hc : 0 ≤ c) (a b : α) : max (a / c) (b / c) = (max a b) / c := eq.symm $ monotone.map_max (λ x y, div_le_div_of_le hc) lemma min_div_div_right_of_nonpos {c : α} (hc : c ≤ 0) (a b : α) : min (a / c) (b / c) = (max a b) / c := eq.symm $ antitone.map_max $ λ x y, div_le_div_of_nonpos_of_le hc lemma max_div_div_right_of_nonpos {c : α} (hc : c ≤ 0) (a b : α) : max (a / c) (b / c) = (min a b) / c := eq.symm $ antitone.map_min $ λ x y, div_le_div_of_nonpos_of_le hc lemma abs_div (a b : α) : |a / b| = |a| / |b| := (abs_hom : α →*₀ α).map_div a b lemma abs_one_div (a : α) : |1 / a| = 1 / |a| := by rw [abs_div, abs_one] lemma abs_inv (a : α) : |a⁻¹| = (|a|)⁻¹ := (abs_hom : α →*₀ α).map_inv a -- TODO: add lemmas with `a⁻¹`. lemma one_div_strict_anti_on : strict_anti_on (λ x : α, 1 / x) (set.Ioi 0) := λ x x1 y y1 xy, (one_div_lt_one_div (set.mem_Ioi.mp y1) (set.mem_Ioi.mp x1)).mpr xy lemma one_div_pow_le_one_div_pow_of_le (a1 : 1 ≤ a) {m n : ℕ} (mn : m ≤ n) : 1 / a ^ n ≤ 1 / a ^ m := by refine (one_div_le_one_div _ _).mpr (pow_le_pow a1 mn); exact pow_pos (zero_lt_one.trans_le a1) _ lemma one_div_pow_lt_one_div_pow_of_lt (a1 : 1 < a) {m n : ℕ} (mn : m < n) : 1 / a ^ n < 1 / a ^ m := by refine (one_div_lt_one_div _ _).mpr (pow_lt_pow a1 mn); exact pow_pos (trans zero_lt_one a1) _ lemma one_div_pow_anti (a1 : 1 ≤ a) : antitone (λ n : ℕ, 1 / a ^ n) := λ m n, one_div_pow_le_one_div_pow_of_le a1 lemma one_div_pow_strict_anti (a1 : 1 < a) : strict_anti (λ n : ℕ, 1 / a ^ n) := λ m n, one_div_pow_lt_one_div_pow_of_lt a1 /-! ### Results about `is_lub` and `is_glb` -/ lemma is_lub.mul_left {s : set α} (ha : 0 ≤ a) (hs : is_lub s b) : is_lub ((λ b, a * b) '' s) (a * b) := begin rcases lt_or_eq_of_le ha with ha | rfl, { exact (order_iso.mul_left₀ _ ha).is_lub_image'.2 hs, }, { simp_rw zero_mul, rw hs.nonempty.image_const, exact is_lub_singleton }, end lemma is_lub.mul_right {s : set α} (ha : 0 ≤ a) (hs : is_lub s b) : is_lub ((λ b, b * a) '' s) (b * a) := by simpa [mul_comm] using hs.mul_left ha lemma is_glb.mul_left {s : set α} (ha : 0 ≤ a) (hs : is_glb s b) : is_glb ((λ b, a * b) '' s) (a * b) := begin rcases lt_or_eq_of_le ha with ha | rfl, { exact (order_iso.mul_left₀ _ ha).is_glb_image'.2 hs, }, { simp_rw zero_mul, rw hs.nonempty.image_const, exact is_glb_singleton }, end lemma is_glb.mul_right {s : set α} (ha : 0 ≤ a) (hs : is_glb s b) : is_glb ((λ b, b * a) '' s) (b * a) := by simpa [mul_comm] using hs.mul_left ha end linear_ordered_field
474193b802da6585ffdae84a66849b0997c17c73
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/topology/category/Top/limits/konig.lean
992e9c8e6ed501c17334e1f4928d767b2a4683e5
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
5,409
lean
/- Copyright (c) 2017 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Scott Morrison, Mario Carneiro, Andrew Yang -/ import topology.category.Top.limits.basic /-! # Topological Kőnig's lemma > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. A topological version of Kőnig's lemma is that the inverse limit of nonempty compact Hausdorff spaces is nonempty. (Note: this can be generalized further to inverse limits of nonempty compact T0 spaces, where all the maps are closed maps; see [Stone1979] --- however there is an erratum for Theorem 4 that the element in the inverse limit can have cofinally many components that are not closed points.) We give this in a more general form, which is that cofiltered limits of nonempty compact Hausdorff spaces are nonempty (`nonempty_limit_cone_of_compact_t2_cofiltered_system`). This also applies to inverse limits, where `{J : Type u} [preorder J] [is_directed J (≤)]` and `F : Jᵒᵖ ⥤ Top`. The theorem is specialized to nonempty finite types (which are compact Hausdorff with the discrete topology) in lemmas `nonempty_sections_of_finite_cofiltered_system` and `nonempty_sections_of_finite_inverse_system` in the file `category_theory.cofiltered_system`. (See <https://stacks.math.columbia.edu/tag/086J> for the Set version.) -/ open category_theory open category_theory.limits universes u v w noncomputable theory namespace Top section topological_konig variables {J : Type u} [small_category J] variables (F : J ⥤ Top.{u}) private abbreviation finite_diagram_arrow {J : Type u} [small_category J] (G : finset J) := Σ' (X Y : J) (mX : X ∈ G) (mY : Y ∈ G), X ⟶ Y private abbreviation finite_diagram (J : Type u) [small_category J] := Σ (G : finset J), finset (finite_diagram_arrow G) /-- Partial sections of a cofiltered limit are sections when restricted to a finite subset of objects and morphisms of `J`. -/ def partial_sections {J : Type u} [small_category J] (F : J ⥤ Top.{u}) {G : finset J} (H : finset (finite_diagram_arrow G)) : set (Π j, F.obj j) := { u | ∀ {f : finite_diagram_arrow G} (hf : f ∈ H), F.map f.2.2.2.2 (u f.1) = u f.2.1 } lemma partial_sections.nonempty [is_cofiltered_or_empty J] [h : Π (j : J), nonempty (F.obj j)] {G : finset J} (H : finset (finite_diagram_arrow G)) : (partial_sections F H).nonempty := begin classical, casesI is_empty_or_nonempty J, { exact ⟨is_empty_elim, λ j, is_empty.elim' infer_instance j.1⟩ }, haveI : is_cofiltered J := ⟨⟩, use λ (j : J), if hj : j ∈ G then F.map (is_cofiltered.inf_to G H hj) (h (is_cofiltered.inf G H)).some else (h _).some, rintros ⟨X, Y, hX, hY, f⟩ hf, dsimp only, rwa [dif_pos hX, dif_pos hY, ←comp_app, ←F.map_comp, @is_cofiltered.inf_to_commutes _ _ _ G H], end lemma partial_sections.directed : directed superset (λ (G : finite_diagram J), partial_sections F G.2) := begin classical, intros A B, let ιA : finite_diagram_arrow A.1 → finite_diagram_arrow (A.1 ⊔ B.1) := λ f, ⟨f.1, f.2.1, finset.mem_union_left _ f.2.2.1, finset.mem_union_left _ f.2.2.2.1, f.2.2.2.2⟩, let ιB : finite_diagram_arrow B.1 → finite_diagram_arrow (A.1 ⊔ B.1) := λ f, ⟨f.1, f.2.1, finset.mem_union_right _ f.2.2.1, finset.mem_union_right _ f.2.2.2.1, f.2.2.2.2⟩, refine ⟨⟨A.1 ⊔ B.1, A.2.image ιA ⊔ B.2.image ιB⟩, _, _⟩, { rintro u hu f hf, have : ιA f ∈ A.2.image ιA ⊔ B.2.image ιB, { apply finset.mem_union_left, rw finset.mem_image, refine ⟨f, hf, rfl⟩ }, exact hu this }, { rintro u hu f hf, have : ιB f ∈ A.2.image ιA ⊔ B.2.image ιB, { apply finset.mem_union_right, rw finset.mem_image, refine ⟨f, hf, rfl⟩ }, exact hu this } end lemma partial_sections.closed [Π (j : J), t2_space (F.obj j)] {G : finset J} (H : finset (finite_diagram_arrow G)) : is_closed (partial_sections F H) := begin have : partial_sections F H = ⋂ {f : finite_diagram_arrow G} (hf : f ∈ H), { u | F.map f.2.2.2.2 (u f.1) = u f.2.1 }, { ext1, simp only [set.mem_Inter, set.mem_set_of_eq], refl, }, rw this, apply is_closed_bInter, intros f hf, apply is_closed_eq, continuity, end /-- Cofiltered limits of nonempty compact Hausdorff spaces are nonempty topological spaces. -/ lemma nonempty_limit_cone_of_compact_t2_cofiltered_system [is_cofiltered_or_empty J] [Π (j : J), nonempty (F.obj j)] [Π (j : J), compact_space (F.obj j)] [Π (j : J), t2_space (F.obj j)] : nonempty (Top.limit_cone.{u} F).X := begin classical, obtain ⟨u, hu⟩ := is_compact.nonempty_Inter_of_directed_nonempty_compact_closed (λ G, partial_sections F _) (partial_sections.directed F) (λ G, partial_sections.nonempty F _) (λ G, is_closed.is_compact (partial_sections.closed F _)) (λ G, partial_sections.closed F _), use u, intros X Y f, let G : finite_diagram J := ⟨{X, Y}, {⟨X, Y, by simp only [true_or, eq_self_iff_true, finset.mem_insert], by simp only [eq_self_iff_true, or_true, finset.mem_insert, finset.mem_singleton], f⟩}⟩, exact hu _ ⟨G, rfl⟩ (finset.mem_singleton_self _), end end topological_konig end Top
e7e391d47b4834210243b6deb5ad6da8a4411152
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/algebra/group/units_hom.lean
29f90787d31745791473fc6efbe00be645b0a6ed
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
4,983
lean
/- Copyright (c) 2018 Johan Commelin All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Chris Hughes, Kevin Buzzard -/ import algebra.group.hom /-! # Lift monoid homomorphisms to group homomorphisms of their units subgroups. -/ universes u v w namespace units variables {M : Type u} {N : Type v} {P : Type w} [monoid M] [monoid N] [monoid P] /-- The group homomorphism on units induced by a `monoid_hom`. -/ @[to_additive "The `add_group` homomorphism on `add_unit`s induced by an `add_monoid_hom`."] def map (f : M →* N) : Mˣ →* Nˣ := monoid_hom.mk' (λ u, ⟨f u.val, f u.inv, by rw [← f.map_mul, u.val_inv, f.map_one], by rw [← f.map_mul, u.inv_val, f.map_one]⟩) (λ x y, ext (f.map_mul x y)) @[simp, to_additive] lemma coe_map (f : M →* N) (x : Mˣ) : ↑(map f x) = f x := rfl @[simp, to_additive] lemma coe_map_inv (f : M →* N) (u : Mˣ) : ↑(map f u)⁻¹ = f ↑u⁻¹ := rfl @[simp, to_additive] lemma map_comp (f : M →* N) (g : N →* P) : map (g.comp f) = (map g).comp (map f) := rfl variables (M) @[simp, to_additive] lemma map_id : map (monoid_hom.id M) = monoid_hom.id Mˣ := by ext; refl /-- Coercion `Mˣ → M` as a monoid homomorphism. -/ @[to_additive "Coercion `add_units M → M` as an add_monoid homomorphism."] def coe_hom : Mˣ →* M := ⟨coe, coe_one, coe_mul⟩ variable {M} @[simp, to_additive] lemma coe_hom_apply (x : Mˣ) : coe_hom M x = ↑x := rfl /-- If a map `g : M → Nˣ` agrees with a homomorphism `f : M →* N`, then this map is a monoid homomorphism too. -/ @[to_additive "If a map `g : M → add_units N` agrees with a homomorphism `f : M →+ N`, then this map is an add_monoid homomorphism too."] def lift_right (f : M →* N) (g : M → Nˣ) (h : ∀ x, ↑(g x) = f x) : M →* Nˣ := { to_fun := g, map_one' := units.ext $ (h 1).symm ▸ f.map_one, map_mul' := λ x y, units.ext $ by simp only [h, coe_mul, f.map_mul] } @[simp, to_additive] lemma coe_lift_right {f : M →* N} {g : M → Nˣ} (h : ∀ x, ↑(g x) = f x) (x) : (lift_right f g h x : N) = f x := h x @[simp, to_additive] lemma mul_lift_right_inv {f : M →* N} {g : M → Nˣ} (h : ∀ x, ↑(g x) = f x) (x) : f x * ↑(lift_right f g h x)⁻¹ = 1 := by rw [units.mul_inv_eq_iff_eq_mul, one_mul, coe_lift_right] @[simp, to_additive] lemma lift_right_inv_mul {f : M →* N} {g : M → Nˣ} (h : ∀ x, ↑(g x) = f x) (x) : ↑(lift_right f g h x)⁻¹ * f x = 1 := by rw [units.inv_mul_eq_iff_eq_mul, mul_one, coe_lift_right] end units namespace monoid_hom /-- If `f` is a homomorphism from a group `G` to a monoid `M`, then its image lies in the units of `M`, and `f.to_hom_units` is the corresponding monoid homomorphism from `G` to `Mˣ`. -/ @[to_additive "If `f` is a homomorphism from an additive group `G` to an additive monoid `M`, then its image lies in the `add_units` of `M`, and `f.to_hom_units` is the corresponding homomorphism from `G` to `add_units M`."] def to_hom_units {G M : Type*} [group G] [monoid M] (f : G →* M) : G →* Mˣ := { to_fun := λ g, ⟨f g, f (g⁻¹), by rw [← f.map_mul, mul_inv_self, f.map_one], by rw [← f.map_mul, inv_mul_self, f.map_one]⟩, map_one' := units.ext (f.map_one), map_mul' := λ _ _, units.ext (f.map_mul _ _) } @[simp] lemma coe_to_hom_units {G M : Type*} [group G] [monoid M] (f : G →* M) (g : G): (f.to_hom_units g : M) = f g := rfl end monoid_hom section is_unit variables {M : Type*} {N : Type*} @[to_additive] lemma is_unit.map [monoid M] [monoid N] (f : M →* N) {x : M} (h : is_unit x) : is_unit (f x) := by rcases h with ⟨y, rfl⟩; exact (units.map f y).is_unit /-- If a homomorphism `f : M →* N` sends each element to an `is_unit`, then it can be lifted to `f : M →* Nˣ`. See also `units.lift_right` for a computable version. -/ @[to_additive "If a homomorphism `f : M →+ N` sends each element to an `is_add_unit`, then it can be lifted to `f : M →+ add_units N`. See also `add_units.lift_right` for a computable version."] noncomputable def is_unit.lift_right [monoid M] [monoid N] (f : M →* N) (hf : ∀ x, is_unit (f x)) : M →* Nˣ := units.lift_right f (λ x, classical.some (hf x)) $ λ x, classical.some_spec (hf x) @[to_additive] lemma is_unit.coe_lift_right [monoid M] [monoid N] (f : M →* N) (hf : ∀ x, is_unit (f x)) (x) : (is_unit.lift_right f hf x : N) = f x := units.coe_lift_right _ x @[simp, to_additive] lemma is_unit.mul_lift_right_inv [monoid M] [monoid N] (f : M →* N) (h : ∀ x, is_unit (f x)) (x) : f x * ↑(is_unit.lift_right f h x)⁻¹ = 1 := units.mul_lift_right_inv (λ y, classical.some_spec $ h y) x @[simp, to_additive] lemma is_unit.lift_right_inv_mul [monoid M] [monoid N] (f : M →* N) (h : ∀ x, is_unit (f x)) (x) : ↑(is_unit.lift_right f h x)⁻¹ * f x = 1 := units.lift_right_inv_mul (λ y, classical.some_spec $ h y) x end is_unit
9801a97cdc396b4dd6ec555414c602f4c153f51f
9b9a16fa2cb737daee6b2785474678b6fa91d6d4
/test/fin_cases.lean
9e1311e38228544d6cf831289979f65cd86d496f
[ "Apache-2.0" ]
permissive
johoelzl/mathlib
253f46daa30b644d011e8e119025b01ad69735c4
592e3c7a2dfbd5826919b4605559d35d4d75938f
refs/heads/master
1,625,657,216,488
1,551,374,946,000
1,551,374,946,000
98,915,829
0
0
Apache-2.0
1,522,917,267,000
1,501,524,499,000
Lean
UTF-8
Lean
false
false
393
lean
import tactic.fin_cases example (f : ℕ → Prop) (p : fin 3) (h0 : f 0) (h1 : f 1) (h2 : f 2) : f p.val := begin fin_cases *, all_goals { assumption } end example (x2 : fin 2) (x3 : fin 3) (n : nat) (y : fin n) : x2.val * x3.val = x3.val * x2.val := begin fin_cases x2; fin_cases x3, success_if_fail { fin_cases * }, success_if_fail { fin_cases y }, all_goals { simp }, end
153e2814da037b8d00f7b5d62a1f56f195fdc815
4727251e0cd73359b15b664c3170e5d754078599
/src/category_theory/functor/left_derived.lean
26a2216d37c93f2e1d1e91e8ea3ee2a3d3f71b13
[ "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
7,677
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 category_theory.preadditive.projective_resolution /-! # Left-derived functors We define the left-derived functors `F.left_derived n : C ⥤ D` for any additive functor `F` out of a category with projective resolutions. The definition is ``` projective_resolutions C ⋙ F.map_homotopy_category _ ⋙ homotopy_category.homology_functor D _ n ``` that is, we pick a projective resolution (thought of as an object of the homotopy category), we apply `F` objectwise, and compute `n`-th homology. We show that these left-derived functors can be calculated on objects using any choice of projective resolution, and on morphisms by any choice of lift to a chain map between chosen projective resolutions. Similarly we define natural transformations between left-derived functors coming from natural transformations between the original additive functors, and show how to compute the components. ## Implementation We don't assume the categories involved are abelian (just preadditive, and have equalizers, cokernels, and image maps), or that the functors are right exact. None of these assumptions are needed yet. It is often convenient, of course, to work with `[abelian C] [enough_projectives C] [abelian D]` which (assuming the results from `category_theory.abelian.projective`) are enough to provide all the typeclass hypotheses assumed here. -/ noncomputable theory open category_theory open category_theory.limits universes v u namespace category_theory variables {C : Type u} [category.{v} C] {D : Type*} [category D] -- Importing `category_theory.abelian.projective` and assuming -- `[abelian C] [enough_projectives C] [abelian D]` suffices to acquire all the following: variables [preadditive C] [has_zero_object C] [has_equalizers C] [has_images C] [has_projective_resolutions C] variables [preadditive D] [has_zero_object D] [has_equalizers D] [has_cokernels D] [has_images D] [has_image_maps D] /-- The left derived functors of an additive functor. -/ def functor.left_derived (F : C ⥤ D) [F.additive] (n : ℕ) : C ⥤ D := projective_resolutions C ⋙ F.map_homotopy_category _ ⋙ homotopy_category.homology_functor D _ n -- TODO the left derived functors are additive (and linear when `F` is linear) /-- We can compute a left derived functor using a chosen projective resolution. -/ @[simps] def functor.left_derived_obj_iso (F : C ⥤ D) [F.additive] (n : ℕ) {X : C} (P : ProjectiveResolution X) : (F.left_derived n).obj X ≅ (homology_functor D _ n).obj ((F.map_homological_complex _).obj P.complex) := (homotopy_category.homology_functor D _ n).map_iso (homotopy_category.iso_of_homotopy_equiv (F.map_homotopy_equiv (ProjectiveResolution.homotopy_equiv _ P))) ≪≫ (homotopy_category.homology_factors D _ n).app _ /-- The 0-th derived functor of `F` on a projective object `X` is just `F.obj X`. -/ @[simps] def functor.left_derived_obj_projective_zero (F : C ⥤ D) [F.additive] (X : C) [projective X] : (F.left_derived 0).obj X ≅ F.obj X := F.left_derived_obj_iso 0 (ProjectiveResolution.self X) ≪≫ (homology_functor _ _ _).map_iso ((chain_complex.single₀_map_homological_complex F).app X) ≪≫ (chain_complex.homology_functor_0_single₀ D).app (F.obj X) open_locale zero_object /-- The higher derived functors vanish on projective objects. -/ @[simps] def functor.left_derived_obj_projective_succ (F : C ⥤ D) [F.additive] (n : ℕ) (X : C) [projective X] : (F.left_derived (n+1)).obj X ≅ 0 := F.left_derived_obj_iso (n+1) (ProjectiveResolution.self X) ≪≫ (homology_functor _ _ _).map_iso ((chain_complex.single₀_map_homological_complex F).app X) ≪≫ (chain_complex.homology_functor_succ_single₀ D n).app (F.obj X) ≪≫ (functor.zero_obj _).iso_zero /-- We can compute a left derived functor on a morphism using a lift of that morphism to a chain map between chosen projective resolutions. -/ lemma functor.left_derived_map_eq (F : C ⥤ D) [F.additive] (n : ℕ) {X Y : C} (f : X ⟶ Y) {P : ProjectiveResolution X} {Q : ProjectiveResolution Y} (g : P.complex ⟶ Q.complex) (w : g ≫ Q.π = P.π ≫ (chain_complex.single₀ C).map f) : (F.left_derived n).map f = (F.left_derived_obj_iso n P).hom ≫ (homology_functor D _ n).map ((F.map_homological_complex _).map g) ≫ (F.left_derived_obj_iso n Q).inv := begin dsimp only [functor.left_derived, functor.left_derived_obj_iso], dsimp, simp only [category.comp_id, category.id_comp], rw [←homology_functor_map, homotopy_category.homology_functor_map_factors], simp only [←functor.map_comp], congr' 1, apply homotopy_category.eq_of_homotopy, apply functor.map_homotopy, apply homotopy.trans, exact homotopy_category.homotopy_out_map _, apply ProjectiveResolution.lift_homotopy f, { simp, }, { simp [w], }, end /-- The natural transformation between left-derived functors induced by a natural transformation. -/ @[simps] def nat_trans.left_derived {F G : C ⥤ D} [F.additive] [G.additive] (α : F ⟶ G) (n : ℕ) : F.left_derived n ⟶ G.left_derived n := whisker_left (projective_resolutions C) (whisker_right (nat_trans.map_homotopy_category α _) (homotopy_category.homology_functor D _ n)) @[simp] lemma nat_trans.left_derived_id (F : C ⥤ D) [F.additive] (n : ℕ) : nat_trans.left_derived (𝟙 F) n = 𝟙 (F.left_derived n) := by { simp [nat_trans.left_derived], refl, } -- The `simp_nf` linter times out here, so we disable it. @[simp, nolint simp_nf] lemma nat_trans.left_derived_comp {F G H : C ⥤ D} [F.additive] [G.additive] [H.additive] (α : F ⟶ G) (β : G ⟶ H) (n : ℕ) : nat_trans.left_derived (α ≫ β) n = nat_trans.left_derived α n ≫ nat_trans.left_derived β n := by simp [nat_trans.left_derived] /-- A component of the natural transformation between left-derived functors can be computed using a chosen projective resolution. -/ lemma nat_trans.left_derived_eq {F G : C ⥤ D} [F.additive] [G.additive] (α : F ⟶ G) (n : ℕ) {X : C} (P : ProjectiveResolution X) : (nat_trans.left_derived α n).app X = (F.left_derived_obj_iso n P).hom ≫ (homology_functor D _ n).map ((nat_trans.map_homological_complex α _).app P.complex) ≫ (G.left_derived_obj_iso n P).inv := begin symmetry, dsimp [nat_trans.left_derived, functor.left_derived_obj_iso], simp only [category.comp_id, category.id_comp], rw [←homology_functor_map, homotopy_category.homology_functor_map_factors], simp only [←functor.map_comp], congr' 1, apply homotopy_category.eq_of_homotopy, simp only [nat_trans.map_homological_complex_naturality_assoc, ←functor.map_comp], apply homotopy.comp_left_id, rw [←functor.map_id], apply functor.map_homotopy, apply homotopy_equiv.homotopy_hom_inv_id, end -- TODO: -- lemma nat_trans.left_derived_projective_zero {F G : C ⥤ D} [F.additive] [G.additive] (α : F ⟶ G) -- (X : C) [projective X] : -- (nat_trans.left_derived α 0).app X = -- (F.left_derived_obj_projective_zero X).hom ≫ -- α.app X ≫ -- (G.left_derived_obj_projective_zero X).inv := sorry -- TODO: -- lemma nat_trans.left_derived_projective_succ {F G : C ⥤ D} [F.additive] [G.additive] (α : F ⟶ G) -- (n : ℕ) (X : C) [projective X] : -- (nat_trans.left_derived α (n+1)).app X = 0 := sorry -- TODO left-derived functors of the identity functor are the identity -- (requires we assume `abelian`?) -- PROJECT left-derived functors of a composition (Grothendieck sequence) end category_theory
14a9c1729f6e4df4616b09ec5ed8600bd60b2ce8
ba4794a0deca1d2aaa68914cd285d77880907b5c
/src/game/world4/level8.lean
6e18d6a7c1bd17fda3cb189b194e93bdd4000769
[ "Apache-2.0" ]
permissive
ChrisHughes24/natural_number_game
c7c00aa1f6a95004286fd456ed13cf6e113159ce
9d09925424da9f6275e6cfe427c8bcf12bb0944f
refs/heads/master
1,600,715,773,528
1,573,910,462,000
1,573,910,462,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,765
lean
import game.world4.level7 -- hide -- incantation for importing ring into framework -- hide import tactic.ring -- hide meta def less_leaky.interactive.ring := tactic.interactive.ring -- hide namespace mynat -- hide def two_eq_succ_one : (2 : mynat) = succ 1 := rfl -- hide /- # Power World -/ instance : comm_semiring mynat := by structure_helper -- you just levelled up /- ## Level 8: `add_squared` [final boss music] You see something written on the stone dungeon wall: ``` begin rw two_eq_succ_one, rw one_eq_succ_zero, repeat {rw pow_succ}, ... ``` and you can't make out the last two lines because there's a kind of thing in the way that will magically disappear but only when you've beaten the boss. -/ /- Theorem For all naturals $a$ and $b$, we have $$(a+b)^2=a^2+b^2+2ab.$$ -/ lemma add_squared (a b : mynat) : (a + b) ^ (2 : mynat) = a ^ (2 : mynat) + b ^ (2 : mynat) + 2 * a * b := begin [less_leaky] rw two_eq_succ_one, rw one_eq_succ_zero, repeat {rw pow_succ}, repeat {rw pow_zero}, ring, end /- As the boss lies smouldering, you notice on the dungeon wall that <a href="https://twitter.com/XenaProject/status/1190453646904958976?s=20/" target="blank"> two more lines of code are now visible under the first three...</a> (Twitter.com) I just beat this level with 27 rewrites followed by a `refl`. Can you do any better? If you beat it then well done. Do you fancy doing $(a+b)^3$ now? You might want to read <a href="https://xenaproject.wordpress.com/2018/06/13/ab3/" target="blank"> this Xena Project blog post</a> before you start though. -/ /- If you got this far -- very well done! If you only learnt the three tactics `rw`, `induction` and `refl` then there are now more tactics to learn; go back to the main menu and choose Function World. The main thing we really want to impress upon people is that we believe that *all of pure mathematics* can be done in this new way. A system called Coq (which is very like Lean) has <a href="https://hal.inria.fr/hal-00816699" target="blank"> checked the proof of the Feit-Thompson theorem</a> (hundreds of pages of group theory) and Lean has a <a href="https://leanprover-community.github.io/lean-perfectoid-spaces/" target="blank"> definition of perfectoid spaces</a> (a very complex modern mathematical structure). I believe that these systems will one day cause a paradigm shift in the way mathematics is done, but first we need to build what we know, or at least build enough to state what we mathematicians believe. If you want to get involved, come and join us at the <a href="https://leanprover.zulipchat.com" target="blank">Zulip Lean chat</a>. The #new members stream is a great place to start asking questions. -/ end mynat -- hide
c95a33ec806c10ef823109cfec4b5bcab3a685a9
67dc347ff8e6eaa780fd69518f3e69b2fa5eef96
/src/smt2/default.lean
f08292e836eddb0abe722a749cc8b81b3e4736c0
[ "Apache-2.0" ]
permissive
Kha/smt2_interface
74589568b30d32a500fb3a9abb299a28f19d75e9
d92be33fbf4d56e3745e255ab423ba8da7d7695b
refs/heads/master
1,619,785,421,091
1,518,453,826,000
1,518,453,826,000
121,273,425
0
0
null
1,518,453,882,000
1,518,453,882,000
null
UTF-8
Lean
false
false
12,888
lean
import system.io import .solvers.z3 import .syntax import .builder import .tactic import .attributes import .lol import init.data.option.basic declare_trace smt2 open tactic open smt2.builder open native meta structure smt2_state : Type := (ctxt : lol.context) (type_map : rb_map expr lol.type) meta def smt2_state.initial : smt2_state := ⟨ lol.context.empty, rb_map.mk _ _ ⟩ @[reducible] meta def smt2_m (α : Type) := state_t smt2_state tactic α meta instance tactic_to_smt2_m (α : Type) : has_coe (tactic α) (smt2_m α) := ⟨ fun tc, fun s, do res ← tc, return (res, s) ⟩ namespace smt2 meta def trace_smt2 (msg : string) : smt2_m unit := tactic.when_tracing `smt2 (tactic.trace msg) meta def fail {α : Type} (msg : string) : smt2_m α := tactic.fail $ "smt2_tactic: " ++ msg meta def mangle_name (n : name) : string := "lean_" ++ n^.to_string_with_sep "-" meta def insert_type (n : string) (ty : expr) (lty : lol.type) : smt2_m unit := do st ← state_t.read, state_t.write ⟨ st.ctxt.declare_type n lty, st.type_map.insert ty lty ⟩ meta def fn_type : expr → (list expr × expr) | (expr.pi _ _ ty rest) := let (args, rt) := fn_type rest in (ty :: args, rt) | rt := ([], rt) -- Currently we only support first order fn types meta def compile_arrow_type (ty : expr) (cb : expr → smt2_m lol.type) : smt2_m lol.type := let (args, rt) := fn_type ty in lol.type.fn <$> monad.mapm cb args <*> cb rt meta def compile_type : expr → smt2_m lol.type := fun ty, do st ← state_t.read, match st.type_map.find ty with | some lty := return lty | none := do lty ← match ty with | `(int) := pure $ lol.type.int | `(nat) := pure $ lol.type.refinement lol.type.int (fun x, lol.term.lte (lol.term.int 0) (lol.term.var x)) | `(Prop) := pure $ lol.type.bool | _ := if ty.is_arrow then compile_arrow_type ty compile_type else if ty.is_constant then do insert_type (mangle_name ty.const_name) ty (lol.type.fn [] (lol.type.var $ mangle_name ty.const_name)), return $ (lol.type.fn [] (lol.type.var $ mangle_name ty.const_name)) else fail $ "unsupported type: " ++ to_string ty end, -- insert_type ty lty, return lty end meta def add_decl (n : name) (ty : expr) : smt2_m unit := do st ← state_t.read, ct ← compile_type ty, let d := lol.decl.fn (mangle_name n) ct none, state_t.write { st with ctxt := st.ctxt.declare d } -- meta def ensure_constant (e : expr) (n : name) : smt2_m lol.decl := -- do ty ← infer_type e, -- let (arg_tys, ret_ty) := fn_type ty, -- let mangled_name := mangle_name n, -- arg_sorts ← monad.mapm compile_type arg_tys, -- ret_sort ← compile_type ret_ty, -- -- ensure_constant_core e (return $ (mangled_name, arg_sorts, ret_sort)), -- return $ lol.decl.fn mangled_name arg_sorts ret_sort -- meta def formula_type_from_arrow (n : name) (e : expr) : smt2_m formula_type := -- do (lol.decl.fn _ arg_sorts ret_sort) ← ensure_constant e n, -- return $ formula_type.fn n arg_sorts ret_sort -- /-- The goal of this function is to categorize the set of formulas in the hypotheses, -- and goal. We want to narrow down from the full term language of Lean to a fragment -- of formula's we suppose. The below code makes some assumptions: -- A local constant of the form `(P : Prop)`, must be reflected as declaration -- in SMT2 that is `(declare-const P Bool)`. -- An occurence of a proof of `P`, `(p : P)`, must be transformed into -- `(assert P)`. If P is a formula, not an atom, we must transform P into a corresponding -- SMT2 formula and `(assert P)`. -- -/ meta def extract_coe_args (args : list expr) : smt2_m (expr × expr × expr) := match args with | (source :: target :: inst :: e :: []) := return (source, target, e) | _ := fail "internal tactic error expected `coe` to have exactly 4 arguments" end meta def reflect_coercion (source target e : expr) (callback : expr → smt2_m lol.term) : smt2_m lol.term := if source = `(nat) ∧ target = `(int) then callback e else fail $ "unsupported coercion between " ++ "`" ++ to_string source ++ "` and `" ++ to_string target ++ "`" meta def reflect_application (fn : expr) (args : list expr) (callback : expr → smt2_m lol.term) : smt2_m lol.term := if fn.is_constant then if fn.const_name = `coe then do (source, target, e) ← extract_coe_args args, reflect_coercion source target e callback else do ty ← infer_type fn, let mangled := (mangle_name fn.const_name), add_decl fn.const_name ty, lol.term.apply mangled <$> monad.mapm callback args else if fn.is_local_constant then lol.term.apply (mangle_name fn.local_uniq_name) <$> monad.mapm callback args else fail $ "unsupported head symbol `" ++ to_string fn ++ "`" -- meta def is_supported_head_symbol (e : expr) : bool := true meta def is_supported_numeric_ty (ty : expr) : bool := (ty = `(int) ∨ ty = `(nat)) -- /-- This function is the meat of the tactic, it takes a propositional formula in Lean, and transforms -- it into a corresponding term in SMT2. -/ meta def reflect_arith_formula (reflect_base : expr → smt2_m lol.term) : expr → smt2_m lol.term | `(%%a + %%b) := lol.term.add <$> reflect_arith_formula a <*> reflect_arith_formula b | `(%%a - %%b) := lol.term.sub <$> reflect_arith_formula a <*> reflect_arith_formula b | `(%%a * %%b) := lol.term.mul <$> reflect_arith_formula a <*> reflect_arith_formula b | `(%%a / %%b) := lol.term.div <$> reflect_arith_formula a <*> reflect_arith_formula b | `(%%a % %%b) := lol.term.mod <$> reflect_arith_formula a <*> reflect_arith_formula b | `(- %%a) := lol.term.neg <$> reflect_arith_formula a -- /- Constants -/ | `(has_zero.zero _) := lol.term.int <$> eval_expr int `(has_zero.zero int) | `(has_one.one _) := lol.term.int <$> eval_expr int `(has_one.one int) | `(bit0 %%Bits) := do ty ← infer_type Bits, if is_supported_numeric_ty ty then lol.term.int <$> eval_expr int `(bit0 %%Bits : int) else if (ty = `(nat)) then lol.term.int <$> int.of_nat <$> eval_expr nat `(bit0 %%Bits : nat) else fail $ "unknown numeric literal: " ++ (to_string ```(bit0 %%Bits : int)) | `(bit1 %%Bits) := do ty ← infer_type Bits, if is_supported_numeric_ty ty then lol.term.int <$> eval_expr int `(bit1 %%Bits : int) else if (ty = `(nat)) then lol.term.int <$> (int.of_nat <$> eval_expr nat `(bit1 %%Bits : nat)) else fail $ "unknown numeric literal: " ++ (to_string `(bit1 %%Bits : int)) | a := if a.is_local_constant then return $ lol.term.var (mangle_name a.local_uniq_name) else if a.is_constant then return $ lol.term.var (mangle_name a.const_name) else if a.is_app then reflect_application (a.get_app_fn) (a.get_app_args) reflect_base else fail $ "unsupported arithmetic formula: " ++ to_string a -- /-- Check if the type is an `int` or logically a subtype of an `int` like nat. -/ meta def is_int (e : expr) : tactic bool := do ty ← infer_type e, return $ (ty = `(int)) || (ty = `(nat)) meta def unsupported_ordering_on {α : Type} (elem : expr) : tactic α := do ty ← infer_type elem, tactic.fail $ "unable to translate orderings for values of type: " ++ to_string ty meta def reflect_ordering (reflect_arith : expr → smt2_m lol.term) (R : lol.term → lol.term → lol.term) (P Q : expr) : smt2_m lol.term := do is ← is_int P, -- NB: P and Q should have the same type. if is then R <$> (reflect_arith P) <*> (reflect_arith Q) else unsupported_ordering_on P meta def supported_pi_binder (ty : expr) : bool := match ty with | `(int) := tt | `(nat) := tt | `(Prop) := tt | _ := if ty.is_constant then tt else ff end meta def add_assertion (t : lol.term) : smt2_m unit := do st ← state_t.read, state_t.write { st with ctxt := st.ctxt.assert t } meta def compile_pi (e : expr) (cb : expr → smt2_m lol.term) : smt2_m lol.term := if supported_pi_binder e.binding_domain then do loc ← tactic.mk_local' e.binding_name e.binding_info e.binding_domain, lol.term.forallq (mangle_name $ loc.local_uniq_name) <$> (compile_type $ e.binding_domain) <*> (cb (expr.instantiate_var (e.binding_body) loc)) else fail $ "arbitrary Π types are not supported, unable to translate term: `" ++ to_string e ++ "`" meta def reflect_prop_formula' : expr → smt2_m lol.term | `(¬ %%P) := lol.term.not <$> (reflect_prop_formula' P) | `(%%P = %% Q) := lol.term.equals <$> (reflect_prop_formula' P) <*> (reflect_prop_formula' Q) | `(%%P ∧ %%Q) := lol.term.and <$> (reflect_prop_formula' P) <*> (reflect_prop_formula' Q) | `(%%P ∨ %%Q) := lol.term.or <$> (reflect_prop_formula' P) <*> (reflect_prop_formula' Q) | `(%%P ↔ %%Q) := lol.term.iff <$> (reflect_prop_formula' P) <*> (reflect_prop_formula' Q) | `(%%P < %%Q) := reflect_ordering (reflect_arith_formula reflect_prop_formula') lol.term.lt P Q | `(%%P <= %%Q) := reflect_ordering (reflect_arith_formula reflect_prop_formula') lol.term.lte P Q | `(%%P > %%Q) := reflect_ordering (reflect_arith_formula reflect_prop_formula') lol.term.gt P Q | `(%%P >= %%Q) := reflect_ordering (reflect_arith_formula reflect_prop_formula') lol.term.gte P Q | `(true) := return $ lol.term.true | `(false) := return $ lol.term.false | e := do ty ← infer_type e, if e.is_local_constant then pure $ lol.term.var (mangle_name e.local_uniq_name) else if e.is_arrow then lol.term.implies <$> (reflect_prop_formula' e.binding_domain) <*> (reflect_prop_formula' e.binding_body ) else if e.is_pi then compile_pi e reflect_prop_formula' else if is_supported_numeric_ty ty then reflect_arith_formula reflect_prop_formula' e else if e.is_app then reflect_application (e.get_app_fn) (e.get_app_args) reflect_prop_formula' else tactic.fail $ "unsupported propositional formula : " ++ to_string e meta def reflect_prop_formula (e : expr) : smt2_m unit := reflect_prop_formula' e >>= add_assertion -- meta def warn_unable_to_trans_local (e : expr) : smt2_m (builder unit) := do -- trace_smt2 $ "unable to translate local variable: " ++ to_string e, -- return $ return () meta def is_builtin_type : expr → bool | `(int) := tt | `(Prop) := tt | `(nat) := tt | _ := ff meta def unsupported_formula (e : expr) : smt2_m unit := fail $ "unsupported formula: " ++ to_string e meta def compile_local (e : expr) : smt2_m unit := do ty ← infer_type e, prop_sorted ← is_prop ty, if e.is_local_constant then if is_builtin_type ty then add_decl e.local_uniq_name ty else if ty.is_arrow then add_decl e.local_uniq_name ty else if prop_sorted then reflect_prop_formula ty else unsupported_formula ty else if e.is_constant then if is_builtin_type ty ∨ ty.is_arrow then add_decl e.const_name ty else if prop_sorted then reflect_prop_formula ty else unsupported_formula ty else if (ty = `(Prop)) then reflect_prop_formula e else unsupported_formula e meta def reflect_attr_decl (n : name) : smt2_m unit := do exp ← mk_const n, compile_local exp /- Reflect the environment consisting of declarations with the `smt2` attribute. -/ meta def reflect_environment : smt2_m unit := do decls ← attribute.get_instances `smt2, bs ← monad.mapm reflect_attr_decl decls.reverse, return () meta def reflect_context : smt2_m unit := do ls ← local_context, bs ← monad.mapm (fun e, compile_local e) ls, return () meta def reflect_goal : smt2_m unit := do tgt ← target, -- SMT solvers are looking for satisfiabiltiy, so we must negate to check validity. reflect_prop_formula `(_root_.not %%tgt), return () meta def reflect : smt2_m (builder unit) := do reflect_environment, reflect_context, reflect_goal, st ← state_t.read, return $ (lol.to_builder (lol.smt2_compiler_state.mk (rb_map.mk _ _) st.ctxt []) lol.compile >> check_sat) end smt2 universe u @[smt2] lemma int_of_nat_is_pos : forall (n : nat), 0 <= int.of_nat n := begin intros, trivial end axiom proof_by_z3 (A : Sort u) : A meta def z3 (log_file : option string := none) : tactic unit := do (builder, _) ← smt2.reflect smt2_state.initial, resp ← unsafe_run_io (smt2 builder log_file), match resp with | smt2.response.sat := fail "z3 was unable to prove the goal" | smt2.response.unknown := fail "z3 was unable to prove the goal" | smt2.response.other str := fail $ "z3 communication error, unexpected response:\n\n" ++ str ++ "\n" | smt2.response.unsat := do tgt ← target, sry ← to_expr $ ``(proof_by_z3 %%tgt), exact sry end