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
ff60bf12e4419a48cc821b9a599af77668ec5e32
7cef822f3b952965621309e88eadf618da0c8ae9
/src/category_theory/limits/shapes/binary_products.lean
5832170464cea80c3a8e671582d90810631939d6
[ "Apache-2.0" ]
permissive
rmitta/mathlib
8d90aee30b4db2b013e01f62c33f297d7e64a43d
883d974b608845bad30ae19e27e33c285200bf84
refs/heads/master
1,585,776,832,544
1,576,874,096,000
1,576,874,096,000
153,663,165
0
2
Apache-2.0
1,544,806,490,000
1,539,884,365,000
Lean
UTF-8
Lean
false
false
9,224
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.limits.shapes.finite_products import category_theory.limits.shapes.terminal import category_theory.discrete_category /-! # Binary (co)products We define a category `walking_pair`, which is the index category for a binary (co)product diagram. A convenience method `pair X Y` constructs the functor from the walking pair, hitting the given objects. We define `prod X Y` and `coprod X Y` as limits and colimits of such functors. Typeclasses `has_binary_products` and `has_binary_coproducts` assert the existence of (co)limits shaped as walking pairs. -/ universes v u open category_theory namespace category_theory.limits /-- The type of objects for the diagram indexing a binary (co)product. -/ @[derive decidable_eq] inductive walking_pair : Type v | left | right instance fintype_walking_pair : fintype walking_pair := { elems := [walking_pair.left, walking_pair.right].to_finset, complete := λ x, by { cases x; simp } } def pair_function {C : Type u} (X Y : C) : walking_pair → C | walking_pair.left := X | walking_pair.right := Y variables {C : Type u} [𝒞 : category.{v} C] include 𝒞 def pair (X Y : C) : discrete walking_pair ⥤ C := functor.of_function (pair_function X Y) @[simp] lemma pair_obj_left (X Y : C) : (pair X Y).obj walking_pair.left = X := rfl @[simp] lemma pair_obj_right (X Y : C) : (pair X Y).obj walking_pair.right = Y := rfl def map_pair {W X Y Z : C} (f : W ⟶ Y) (g : X ⟶ Z) : pair W X ⟶ pair Y Z := { app := λ j, match j with | walking_pair.left := f | walking_pair.right := g end } @[simp] lemma map_pair_left {W X Y Z : C} (f : W ⟶ Y) (g : X ⟶ Z) : (map_pair f g).app walking_pair.left = f := rfl @[simp] lemma map_pair_right {W X Y Z : C} (f : W ⟶ Y) (g : X ⟶ Z) : (map_pair f g).app walking_pair.right = g := rfl abbreviation binary_fan (X Y : C) := cone (pair X Y) abbreviation binary_cofan (X Y : C) := cocone (pair X Y) variables {X Y : C} def binary_fan.mk {P : C} (π₁ : P ⟶ X) (π₂ : P ⟶ Y) : binary_fan X Y := { X := P, π := { app := λ j, walking_pair.cases_on j π₁ π₂ }} def binary_cofan.mk {P : C} (ι₁ : X ⟶ P) (ι₂ : Y ⟶ P) : binary_cofan X Y := { X := P, ι := { app := λ j, walking_pair.cases_on j ι₁ ι₂ }} @[simp] lemma binary_fan.mk_π_app_left {P : C} (π₁ : P ⟶ X) (π₂ : P ⟶ Y) : (binary_fan.mk π₁ π₂).π.app walking_pair.left = π₁ := rfl @[simp] lemma binary_fan.mk_π_app_right {P : C} (π₁ : P ⟶ X) (π₂ : P ⟶ Y) : (binary_fan.mk π₁ π₂).π.app walking_pair.right = π₂ := rfl @[simp] lemma binary_cofan.mk_π_app_left {P : C} (ι₁ : X ⟶ P) (ι₂ : Y ⟶ P) : (binary_cofan.mk ι₁ ι₂).ι.app walking_pair.left = ι₁ := rfl @[simp] lemma binary_cofan.mk_π_app_right {P : C} (ι₁ : X ⟶ P) (ι₂ : Y ⟶ P) : (binary_cofan.mk ι₁ ι₂).ι.app walking_pair.right = ι₂ := rfl abbreviation prod (X Y : C) [has_limit (pair X Y)] := limit (pair X Y) abbreviation coprod (X Y : C) [has_colimit (pair X Y)] := colimit (pair X Y) notation X `⨯`:20 Y:20 := prod X Y notation X `⨿`:20 Y:20 := coprod X Y abbreviation prod.fst {X Y : C} [has_limit (pair X Y)] : X ⨯ Y ⟶ X := limit.π (pair X Y) walking_pair.left abbreviation prod.snd {X Y : C} [has_limit (pair X Y)] : X ⨯ Y ⟶ Y := limit.π (pair X Y) walking_pair.right abbreviation coprod.inl {X Y : C} [has_colimit (pair X Y)] : X ⟶ X ⨿ Y := colimit.ι (pair X Y) walking_pair.left abbreviation coprod.inr {X Y : C} [has_colimit (pair X Y)] : Y ⟶ X ⨿ Y := colimit.ι (pair X Y) walking_pair.right abbreviation prod.lift {W X Y : C} [has_limit (pair X Y)] (f : W ⟶ X) (g : W ⟶ Y) : W ⟶ X ⨯ Y := limit.lift _ (binary_fan.mk f g) abbreviation coprod.desc {W X Y : C} [has_colimit (pair X Y)] (f : X ⟶ W) (g : Y ⟶ W) : X ⨿ Y ⟶ W := colimit.desc _ (binary_cofan.mk f g) abbreviation prod.map {W X Y Z : C} [has_limits_of_shape.{v} (discrete walking_pair) C] (f : W ⟶ Y) (g : X ⟶ Z) : W ⨯ X ⟶ Y ⨯ Z := lim.map (map_pair f g) abbreviation coprod.map {W X Y Z : C} [has_colimits_of_shape.{v} (discrete walking_pair) C] (f : W ⟶ Y) (g : X ⟶ Z) : W ⨿ X ⟶ Y ⨿ Z := colim.map (map_pair f g) variables (C) class has_binary_products := (has_limits_of_shape : has_limits_of_shape.{v} (discrete walking_pair) C) class has_binary_coproducts := (has_colimits_of_shape : has_colimits_of_shape.{v} (discrete walking_pair) C) attribute [instance] has_binary_products.has_limits_of_shape has_binary_coproducts.has_colimits_of_shape @[priority 100] -- see Note [lower instance priority] instance [has_finite_products.{v} C] : has_binary_products.{v} C := { has_limits_of_shape := by apply_instance } @[priority 100] -- see Note [lower instance priority] instance [has_finite_coproducts.{v} C] : has_binary_coproducts.{v} C := { has_colimits_of_shape := by apply_instance } section variables {C} [has_binary_products.{v} C] local attribute [tidy] tactic.case_bash /-- The braiding isomorphism which swaps a binary product. -/ @[simps] def prod.braiding (P Q : C) : P ⨯ Q ≅ Q ⨯ P := { hom := prod.lift prod.snd prod.fst, inv := prod.lift prod.snd prod.fst } /-- The braiding isomorphism is symmetric. -/ @[simp] lemma prod.symmetry (P Q : C) : (prod.braiding P Q).hom ≫ (prod.braiding Q P).hom = 𝟙 _ := by tidy /-- The associator isomorphism for binary products. -/ @[simps] def prod.associator (P Q R : C) : (P ⨯ Q) ⨯ R ≅ P ⨯ (Q ⨯ R) := { hom := prod.lift (prod.fst ≫ prod.fst) (prod.lift (prod.fst ≫ prod.snd) prod.snd), inv := prod.lift (prod.lift prod.fst (prod.snd ≫ prod.fst)) (prod.snd ≫ prod.snd) } lemma prod.pentagon (W X Y Z : C) : prod.map ((prod.associator W X Y).hom) (𝟙 Z) ≫ (prod.associator W (X ⨯ Y) Z).hom ≫ prod.map (𝟙 W) ((prod.associator X Y Z).hom) = (prod.associator (W ⨯ X) Y Z).hom ≫ (prod.associator W X (Y⨯Z)).hom := by tidy lemma prod.associator_naturality {X₁ X₂ X₃ Y₁ Y₂ Y₃ : C} (f₁ : X₁ ⟶ Y₁) (f₂ : X₂ ⟶ Y₂) (f₃ : X₃ ⟶ Y₃) : prod.map (prod.map f₁ f₂) f₃ ≫ (prod.associator Y₁ Y₂ Y₃).hom = (prod.associator X₁ X₂ X₃).hom ≫ prod.map f₁ (prod.map f₂ f₃) := by tidy variables [has_terminal.{v} C] /-- The left unitor isomorphism for binary products with the terminal object. -/ @[simps] def prod.left_unitor (P : C) : ⊤_ C ⨯ P ≅ P := { hom := prod.snd, inv := prod.lift (terminal.from P) (𝟙 _) } /-- The right unitor isomorphism for binary products with the terminal object. -/ @[simps] def prod.right_unitor (P : C) : P ⨯ ⊤_ C ≅ P := { hom := prod.fst, inv := prod.lift (𝟙 _) (terminal.from P) } lemma prod.triangle (X Y : C) : (prod.associator X (⊤_ C) Y).hom ≫ prod.map (𝟙 X) ((prod.left_unitor Y).hom) = prod.map ((prod.right_unitor X).hom) (𝟙 Y) := by tidy end section variables {C} [has_binary_coproducts.{v} C] local attribute [tidy] tactic.case_bash /-- The braiding isomorphism which swaps a binary coproduct. -/ @[simps] def coprod.braiding (P Q : C) : P ⨿ Q ≅ Q ⨿ P := { hom := coprod.desc coprod.inr coprod.inl, inv := coprod.desc coprod.inr coprod.inl } /-- The braiding isomorphism is symmetric. -/ @[simp] lemma coprod.symmetry (P Q : C) : (coprod.braiding P Q).hom ≫ (coprod.braiding Q P).hom = 𝟙 _ := by tidy /-- The associator isomorphism for binary coproducts. -/ @[simps] def coprod.associator (P Q R : C) : (P ⨿ Q) ⨿ R ≅ P ⨿ (Q ⨿ R) := { hom := coprod.desc (coprod.desc coprod.inl (coprod.inl ≫ coprod.inr)) (coprod.inr ≫ coprod.inr), inv := coprod.desc (coprod.inl ≫ coprod.inl) (coprod.desc (coprod.inr ≫ coprod.inl) coprod.inr) } lemma coprod.pentagon (W X Y Z : C) : coprod.map ((coprod.associator W X Y).hom) (𝟙 Z) ≫ (coprod.associator W (X⨿Y) Z).hom ≫ coprod.map (𝟙 W) ((coprod.associator X Y Z).hom) = (coprod.associator (W⨿X) Y Z).hom ≫ (coprod.associator W X (Y⨿Z)).hom := by tidy lemma coprod.associator_naturality {X₁ X₂ X₃ Y₁ Y₂ Y₃ : C} (f₁ : X₁ ⟶ Y₁) (f₂ : X₂ ⟶ Y₂) (f₃ : X₃ ⟶ Y₃) : coprod.map (coprod.map f₁ f₂) f₃ ≫ (coprod.associator Y₁ Y₂ Y₃).hom = (coprod.associator X₁ X₂ X₃).hom ≫ coprod.map f₁ (coprod.map f₂ f₃) := by tidy variables [has_initial.{v} C] /-- The left unitor isomorphism for binary coproducts with the initial object. -/ @[simps] def coprod.left_unitor (P : C) : ⊥_ C ⨿ P ≅ P := { hom := coprod.desc (initial.to P) (𝟙 _), inv := coprod.inr } /-- The right unitor isomorphism for binary coproducts with the initial object. -/ @[simps] def coprod.right_unitor (P : C) : P ⨿ ⊥_ C ≅ P := { hom := coprod.desc (𝟙 _) (initial.to P), inv := coprod.inl } lemma coprod.triangle (X Y : C) : (coprod.associator X (⊥_ C) Y).hom ≫ coprod.map (𝟙 X) ((coprod.left_unitor Y).hom) = coprod.map ((coprod.right_unitor X).hom) (𝟙 Y) := by tidy end end category_theory.limits
ce545743bf56dff90c792f1822f8d753c4a54b84
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/analysis/normed_space/real_inner_product.lean
2b665cc5176c7d4dc331dbbc01761070386bc752
[ "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
52,845
lean
/- Copyright (c) 2019 Zhouhang Zhou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Zhouhang Zhou, Sébastien Gouëzel -/ import algebra.quadratic_discriminant import linear_algebra.bilinear_form import tactic.apply_fun import tactic.monotonicity import topology.metric_space.pi_Lp /-! # Inner Product Space This file defines real inner product space and proves its basic properties. An inner product space is a vector space endowed with an inner product. It generalizes the notion of dot product in `ℝ^n` and provides the means of defining the length of a vector and the angle between two vectors. In particular vectors `x` and `y` are orthogonal if their inner product equals zero. ## Main statements Existence of orthogonal projection onto nonempty complete subspace: Let `u` be a point in an inner product space, and let `K` be a nonempty complete subspace. Then there exists a unique `v` in `K` that minimizes the distance `∥u - v∥` to `u`. The point `v` is usually called the orthogonal projection of `u` onto `K`. ## Implementation notes We decide to develop the theory of real inner product spaces and that of complex inner product spaces separately. ## Tags inner product space, norm, orthogonal projection ## References * [Clément & Martin, *The Lax-Milgram Theorem. A detailed proof to be formalized in Coq*] * [Clément & Martin, *A Coq formal proof of the Lax–Milgram theorem*] The Coq code is available at the following address: <http://www.lri.fr/~sboldo/elfic/index.html> -/ noncomputable theory open real set open_locale big_operators open_locale classical open_locale topological_space universes u v w variables {α : Type u} {F : Type v} {G : Type w} /-- Syntactic typeclass for types endowed with an inner product -/ class has_inner (α : Type*) := (inner : α → α → ℝ) export has_inner (inner) -- the norm is embedded in the inner product space structure -- to avoid definitional equality issues. See Note [forgetful inheritance]. /-- An inner product space is a real vector space with an additional operation called inner product. Inner product spaces over complex vector space will be defined in another file. The norm could be derived from the inner product, instead we require the existence of a norm and the fact that it is equal to `sqrt (inner x x)` to be able to put instances on `ℝ` or product spaces. To construct a norm from an inner product, see `inner_product_space.of_core`. -/ class inner_product_space (α : Type*) extends normed_group α, normed_space ℝ α, has_inner α := (norm_eq_sqrt_inner : ∀ (x : α), ∥x∥ = sqrt (inner x x)) (comm : ∀ x y, inner x y = inner y x) (add_left : ∀ x y z, inner (x + y) z = inner x z + inner y z) (smul_left : ∀ x y r, inner (r • x) y = r * inner x y) /-! ### Constructing a normed space structure from a scalar product In the definition of an inner product space, we require the existence of a norm, which is equal (but maybe not defeq) to the square root of the scalar product. This makes it possible to put an inner product space structure on spaces with a preexisting norm (for instance `ℝ`), with good properties. However, sometimes, one would like to define the norm starting only from a well-behaved scalar product. This is what we implement in this paragraph, starting from a structure `inner_product_space.core` stating that we have a nice scalar product. Our goal here is not to develop a whole theory with all the supporting API, as this will be done below for `inner_product_space`. Instead, we implement the bare minimum to go as directly as possible to the construction of the norm and the proof of the triangular inequality. -/ /-- A structure requiring that a scalar product is positive definite and symmetric, from which one can construct an `inner_product_space` instance in `inner_product_space.of_core`. -/ @[nolint has_inhabited_instance] structure inner_product_space.core (F : Type*) [add_comm_group F] [semimodule ℝ F] := (inner : F → F → ℝ) (comm : ∀ x y, inner x y = inner y x) (nonneg : ∀ x, 0 ≤ inner x x) (definite : ∀ x, inner x x = 0 → x = 0) (add_left : ∀ x y z, inner (x + y) z = inner x z + inner y z) (smul_left : ∀ x y r, inner (r • x) y = r * inner x y) /- We set `inner_product_space.core` to be a class as we will use it as such in the construction of the normed space structure that it produces. However, all the instances we will use will be local to this proof. -/ attribute [class] inner_product_space.core namespace inner_product_space.of_core variables [add_comm_group F] [semimodule ℝ F] [c : inner_product_space.core F] include c /-- Inner product constructed from an `inner_product_space.core` structure -/ def to_has_inner : has_inner F := { inner := c.inner } local attribute [instance] to_has_inner lemma inner_comm (x y : F) : inner x y = inner y x := c.comm x y lemma inner_add_left (x y z : F) : inner (x + y) z = inner x z + inner y z := c.add_left _ _ _ lemma inner_add_right (x y z : F) : inner x (y + z) = inner x y + inner x z := by { rw [inner_comm, inner_add_left], simp [inner_comm] } lemma inner_smul_left (x y : F) (r : ℝ) : inner (r • x) y = r * inner x y := c.smul_left _ _ _ lemma inner_smul_right (x y : F) (r : ℝ) : inner x (r • y) = r * inner x y := by { rw [inner_comm, inner_smul_left, inner_comm] } /-- Norm constructed from an `inner_product_space.core` structure, defined to be the square root of the scalar product. -/ def to_has_norm : has_norm F := { norm := λ x, sqrt (inner x x) } local attribute [instance] to_has_norm lemma norm_eq_sqrt_inner (x : F) : ∥x∥ = sqrt (inner x x) := rfl lemma inner_self_eq_norm_square (x : F) : inner x x = ∥x∥ * ∥x∥ := (mul_self_sqrt (c.nonneg _)).symm /-- Expand `inner (x + y) (x + y)` -/ lemma inner_add_add_self (x y : F) : inner (x + y) (x + y) = inner x x + 2 * inner x y + inner y y := by simpa [inner_add_left, inner_add_right, two_mul, add_assoc] using inner_comm _ _ /-- Cauchy–Schwarz inequality -/ lemma inner_mul_inner_self_le (x y : F) : inner x y * inner x y ≤ inner x x * inner y y := begin have : ∀ t, 0 ≤ inner y y * t * t + 2 * inner x y * t + inner x x, from assume t, calc 0 ≤ inner (x+t•y) (x+t•y) : c.nonneg _ ... = inner y y * t * t + 2 * inner x y * t + inner x x : by { simp only [inner_add_add_self, inner_smul_right, inner_smul_left], ring }, have := discriminant_le_zero this, rw discrim at this, have h : (2 * inner x y)^2 - 4 * inner y y * inner x x = 4 * (inner x y * inner x y - inner x x * inner y y) := by ring, rw h at this, linarith end /-- Cauchy–Schwarz inequality with norm -/ lemma abs_inner_le_norm (x y : F) : abs (inner x y) ≤ ∥x∥ * ∥y∥ := nonneg_le_nonneg_of_squares_le (mul_nonneg (sqrt_nonneg _) (sqrt_nonneg _)) begin rw abs_mul_abs_self, have : ∥x∥ * ∥y∥ * (∥x∥ * ∥y∥) = inner x x * inner y y, simp only [inner_self_eq_norm_square], ring, rw this, exact inner_mul_inner_self_le _ _ end /-- Normed group structure constructed from an `inner_product_space.core` structure. -/ def to_normed_group : normed_group F := normed_group.of_core F { norm_eq_zero_iff := assume x, begin split, { assume h, rw [norm_eq_sqrt_inner, sqrt_eq_zero] at h, { exact c.definite x h }, { exact c.nonneg x } }, { rintros rfl, have : inner ((0 : ℝ) • (0 : F)) 0 = 0 * inner (0 : F) 0 := inner_smul_left _ _ _, simp at this, simp [norm, this] } end, norm_neg := assume x, begin have A : (- (1 : ℝ)) • x = -x, by simp, rw [norm_eq_sqrt_inner, norm_eq_sqrt_inner, ← A, inner_smul_left, inner_smul_right], simp, end, triangle := assume x y, begin have := calc ∥x + y∥ * ∥x + y∥ = inner (x + y) (x + y) : by rw inner_self_eq_norm_square ... = inner x x + 2 * inner x y + inner y y : inner_add_add_self _ _ ... ≤ inner x x + 2 * (∥x∥ * ∥y∥) + inner y y : by linarith [abs_inner_le_norm x y, le_abs_self (inner x y)] ... = (∥x∥ + ∥y∥) * (∥x∥ + ∥y∥) : by { simp only [inner_self_eq_norm_square], ring }, exact nonneg_le_nonneg_of_squares_le (add_nonneg (sqrt_nonneg _) (sqrt_nonneg _)) this end } local attribute [instance] to_normed_group /-- Normed space structure constructed from an `inner_product_space.core` structure. -/ def to_normed_space : normed_space ℝ F := { norm_smul_le := assume r x, le_of_eq $ begin have A : 0 ≤ ∥r∥ * ∥x∥ := mul_nonneg (abs_nonneg _) (sqrt_nonneg _), rw [norm_eq_sqrt_inner, sqrt_eq_iff_mul_self_eq _ A, inner_smul_left, inner_smul_right, inner_self_eq_norm_square], { calc abs(r) * ∥x∥ * (abs(r) * ∥x∥) = (abs(r) * abs(r)) * (∥x∥ * ∥x∥) : by ring ... = r * (r * (∥x∥ * ∥x∥)) : by { rw abs_mul_abs_self, ring } }, { exact c.nonneg _ } end } end inner_product_space.of_core /-- Given an `inner_product_space.core` structure on a space, one can use it to turn the space into an inner product space, constructing the norm out of the inner product. -/ def inner_product_space.of_core [add_comm_group F] [semimodule ℝ F] (c : inner_product_space.core F) : inner_product_space F := begin letI : normed_group F := @inner_product_space.of_core.to_normed_group F _ _ c, letI : normed_space ℝ F := @inner_product_space.of_core.to_normed_space F _ _ c, exact { norm_eq_sqrt_inner := λ x, rfl, .. c } end /-! ### Properties of inner product spaces -/ variables [inner_product_space α] export inner_product_space (norm_eq_sqrt_inner) section basic_properties lemma inner_comm (x y : α) : inner x y = inner y x := inner_product_space.comm x y lemma inner_add_left {x y z : α} : inner (x + y) z = inner x z + inner y z := inner_product_space.add_left _ _ _ lemma inner_add_right {x y z : α} : inner x (y + z) = inner x y + inner x z := by { rw [inner_comm, inner_add_left], simp [inner_comm] } lemma inner_smul_left {x y : α} {r : ℝ} : inner (r • x) y = r * inner x y := inner_product_space.smul_left _ _ _ lemma inner_smul_right {x y : α} {r : ℝ} : inner x (r • y) = r * inner x y := by { rw [inner_comm, inner_smul_left, inner_comm] } variables (α) /-- The inner product as a bilinear form. -/ def bilin_form_of_inner : bilin_form ℝ α := { bilin := inner, bilin_add_left := λ x y z, inner_add_left, bilin_smul_left := λ a x y, inner_smul_left, bilin_add_right := λ x y z, inner_add_right, bilin_smul_right := λ a x y, inner_smul_right } variables {α} /-- An inner product with a sum on the left. -/ lemma sum_inner {ι : Type*} (s : finset ι) (f : ι → α) (x : α) : inner (∑ i in s, f i) x = ∑ i in s, inner (f i) x := bilin_form.map_sum_left (bilin_form_of_inner α) _ _ _ /-- An inner product with a sum on the right. -/ lemma inner_sum {ι : Type*} (s : finset ι) (f : ι → α) (x : α) : inner x (∑ i in s, f i) = ∑ i in s, inner x (f i) := bilin_form.map_sum_right (bilin_form_of_inner α) _ _ _ @[simp] lemma inner_zero_left {x : α} : inner 0 x = 0 := by { rw [← zero_smul ℝ (0:α), inner_smul_left, zero_mul] } @[simp] lemma inner_zero_right {x : α} : inner x 0 = 0 := by { rw [inner_comm, inner_zero_left] } @[simp] lemma inner_self_eq_zero {x : α} : inner x x = 0 ↔ x = 0 := ⟨λ h, by simpa [h] using norm_eq_sqrt_inner x, λ h, by simp [h]⟩ lemma inner_self_nonneg {x : α} : 0 ≤ inner x x := begin classical, by_cases h : x = 0, { simp [h] }, { have : 0 < sqrt (inner x x), { rw ← norm_eq_sqrt_inner, exact norm_pos_iff.mpr h }, exact le_of_lt (sqrt_pos.1 this) } end @[simp] lemma inner_self_nonpos {x : α} : inner x x ≤ 0 ↔ x = 0 := ⟨λ h, inner_self_eq_zero.1 (le_antisymm h inner_self_nonneg), λ h, h.symm ▸ le_of_eq inner_zero_left⟩ @[simp] lemma inner_neg_left {x y : α} : inner (-x) y = -inner x y := by { rw [← neg_one_smul ℝ x, inner_smul_left], simp } @[simp] lemma inner_neg_right {x y : α} : inner x (-y) = -inner x y := by { rw [inner_comm, inner_neg_left, inner_comm] } @[simp] lemma inner_neg_neg {x y : α} : inner (-x) (-y) = inner x y := by simp lemma inner_sub_left {x y z : α} : inner (x - y) z = inner x z - inner y z := by { simp [sub_eq_add_neg, inner_add_left] } lemma inner_sub_right {x y z : α} : inner x (y - z) = inner x y - inner x z := by { simp [sub_eq_add_neg, inner_add_right] } /-- Expand `inner (x + y) (x + y)` -/ lemma inner_add_add_self {x y : α} : inner (x + y) (x + y) = inner x x + 2 * inner x y + inner y y := by simpa [inner_add_left, inner_add_right, two_mul, add_assoc] using inner_comm _ _ /-- Expand `inner (x - y) (x - y)` -/ lemma inner_sub_sub_self {x y : α} : inner (x - y) (x - y) = inner x x - 2 * inner x y + inner y y := begin simp only [inner_sub_left, inner_sub_right, two_mul], simpa [sub_eq_add_neg, add_comm, add_left_comm] using inner_comm _ _ end /-- Parallelogram law -/ lemma parallelogram_law {x y : α} : inner (x + y) (x + y) + inner (x - y) (x - y) = 2 * (inner x x + inner y y) := by simp [inner_add_add_self, inner_sub_sub_self, two_mul, sub_eq_add_neg, add_comm, add_left_comm] /-- Cauchy–Schwarz inequality -/ lemma inner_mul_inner_self_le (x y : α) : inner x y * inner x y ≤ inner x x * inner y y := begin have : ∀ t, 0 ≤ inner y y * t * t + 2 * inner x y * t + inner x x, from assume t, calc 0 ≤ inner (x+t•y) (x+t•y) : inner_self_nonneg ... = inner y y * t * t + 2 * inner x y * t + inner x x : by { simp only [inner_add_add_self, inner_smul_right, inner_smul_left], ring }, have := discriminant_le_zero this, rw discrim at this, have h : (2 * inner x y)^2 - 4 * inner y y * inner x x = 4 * (inner x y * inner x y - inner x x * inner y y) := by ring, rw h at this, linarith end /-- A family of vectors is linearly independent if they are nonzero and orthogonal. -/ lemma linear_independent_of_ne_zero_of_inner_eq_zero {ι : Type*} {v : ι → α} (hz : ∀ i, v i ≠ 0) (ho : ∀ i j, i ≠ j → inner (v i) (v j) = 0) : linear_independent ℝ v := begin rw linear_independent_iff', intros s g hg i hi, have h' : g i * inner (v i) (v i) = inner (∑ j in s, g j • v j) (v i), { rw sum_inner, symmetry, convert finset.sum_eq_single i _ _, { rw inner_smul_left }, { intros j hj hji, rw [inner_smul_left, ho j i hji, mul_zero] }, { exact λ h, false.elim (h hi) } }, simpa [hg, hz] using h' end end basic_properties section norm lemma inner_self_eq_norm_square (x : α) : inner x x = ∥x∥ * ∥x∥ := by { rw norm_eq_sqrt_inner, exact (mul_self_sqrt inner_self_nonneg).symm } /-- Expand the square -/ lemma norm_add_pow_two {x y : α} : ∥x + y∥^2 = ∥x∥^2 + 2 * inner x y + ∥y∥^2 := by { repeat {rw [pow_two, ← inner_self_eq_norm_square]}, exact inner_add_add_self } /-- Same lemma as above but in a different form -/ lemma norm_add_mul_self {x y : α} : ∥x + y∥ * ∥x + y∥ = ∥x∥ * ∥x∥ + 2 * inner x y + ∥y∥ * ∥y∥ := by { repeat {rw [← pow_two]}, exact norm_add_pow_two } /-- Expand the square -/ lemma norm_sub_pow_two {x y : α} : ∥x - y∥^2 = ∥x∥^2 - 2 * inner x y + ∥y∥^2 := by { repeat {rw [pow_two, ← inner_self_eq_norm_square]}, exact inner_sub_sub_self } /-- Same lemma as above but in a different form -/ lemma norm_sub_mul_self {x y : α} : ∥x - y∥ * ∥x - y∥ = ∥x∥ * ∥x∥ - 2 * inner x y + ∥y∥ * ∥y∥ := by { repeat {rw [← pow_two]}, exact norm_sub_pow_two } /-- Cauchy–Schwarz inequality with norm -/ lemma abs_inner_le_norm (x y : α) : abs (inner x y) ≤ ∥x∥ * ∥y∥ := nonneg_le_nonneg_of_squares_le (mul_nonneg (norm_nonneg _) (norm_nonneg _)) begin rw abs_mul_abs_self, have : ∥x∥ * ∥y∥ * (∥x∥ * ∥y∥) = inner x x * inner y y, simp only [inner_self_eq_norm_square], ring, rw this, exact inner_mul_inner_self_le _ _ end lemma parallelogram_law_with_norm {x y : α} : ∥x + y∥ * ∥x + y∥ + ∥x - y∥ * ∥x - y∥ = 2 * (∥x∥ * ∥x∥ + ∥y∥ * ∥y∥) := by { simp only [(inner_self_eq_norm_square _).symm], exact parallelogram_law } /-- The inner product, in terms of the norm. -/ lemma inner_eq_norm_add_mul_self_sub_norm_mul_self_sub_norm_mul_self_div_two (x y : α) : inner x y = (∥x + y∥ * ∥x + y∥ - ∥x∥ * ∥x∥ - ∥y∥ * ∥y∥) / 2 := begin rw norm_add_mul_self, ring end /-- The inner product, in terms of the norm. -/ lemma inner_eq_norm_mul_self_add_norm_mul_self_sub_norm_sub_mul_self_div_two (x y : α) : inner x y = (∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ - ∥x - y∥ * ∥x - y∥) / 2 := begin rw norm_sub_mul_self, ring end /-- The inner product, in terms of the norm. -/ lemma inner_eq_norm_add_mul_self_sub_norm_sub_mul_self_div_four (x y : α) : inner x y = (∥x + y∥ * ∥x + y∥ - ∥x - y∥ * ∥x - y∥) / 4 := begin rw [norm_add_mul_self, norm_sub_mul_self], ring end /-- Pythagorean theorem, if-and-only-if vector inner product form. -/ lemma norm_add_square_eq_norm_square_add_norm_square_iff_inner_eq_zero (x y : α) : ∥x + y∥ * ∥x + y∥ = ∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ ↔ inner x y = 0 := begin rw [norm_add_mul_self, add_right_cancel_iff, add_right_eq_self, mul_eq_zero], norm_num end /-- Pythagorean theorem, vector inner product form. -/ lemma norm_add_square_eq_norm_square_add_norm_square {x y : α} (h : inner x y = 0) : ∥x + y∥ * ∥x + y∥ = ∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ := (norm_add_square_eq_norm_square_add_norm_square_iff_inner_eq_zero x y).2 h /-- Pythagorean theorem, subtracting vectors, if-and-only-if vector inner product form. -/ lemma norm_sub_square_eq_norm_square_add_norm_square_iff_inner_eq_zero (x y : α) : ∥x - y∥ * ∥x - y∥ = ∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ ↔ inner x y = 0 := begin rw [norm_sub_mul_self, add_right_cancel_iff, sub_eq_add_neg, add_right_eq_self, neg_eq_zero, mul_eq_zero], norm_num end /-- Pythagorean theorem, subtracting vectors, vector inner product form. -/ lemma norm_sub_square_eq_norm_square_add_norm_square {x y : α} (h : inner x y = 0) : ∥x - y∥ * ∥x - y∥ = ∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ := (norm_sub_square_eq_norm_square_add_norm_square_iff_inner_eq_zero x y).2 h /-- The sum and difference of two vectors are orthogonal if and only if they have the same norm. -/ lemma inner_add_sub_eq_zero_iff (x y : α) : inner (x + y) (x - y) = 0 ↔ ∥x∥ = ∥y∥ := begin conv_rhs { rw ←mul_self_inj_of_nonneg (norm_nonneg _) (norm_nonneg _) }, simp [←inner_self_eq_norm_square, inner_add_left, inner_sub_right, inner_comm y x, sub_eq_zero, add_comm (inner x y)] end /-- The inner product of two vectors, divided by the product of their norms, has absolute value at most 1. -/ lemma abs_inner_div_norm_mul_norm_le_one (x y : α) : abs (inner x y / (∥x∥ * ∥y∥)) ≤ 1 := begin rw abs_div, by_cases h : 0 = abs (∥x∥ * ∥y∥), { rw [←h, div_zero], norm_num }, { rw div_le_iff' (lt_of_le_of_ne (ge_iff_le.mp (abs_nonneg (∥x∥ * ∥y∥))) h), convert abs_inner_le_norm x y using 1, rw [abs_mul, abs_of_nonneg (norm_nonneg x), abs_of_nonneg (norm_nonneg y), mul_one] } end /-- The inner product of a vector with a multiple of itself. -/ lemma inner_smul_self_left (x : α) (r : ℝ) : inner (r • x) x = r * (∥x∥ * ∥x∥) := by rw [inner_smul_left, ←inner_self_eq_norm_square] /-- The inner product of a vector with a multiple of itself. -/ lemma inner_smul_self_right (x : α) (r : ℝ) : inner x (r • x) = r * (∥x∥ * ∥x∥) := by rw [inner_smul_right, ←inner_self_eq_norm_square] /-- The inner product of a nonzero vector with a nonzero multiple of itself, divided by the product of their norms, has absolute value 1. -/ lemma abs_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_ne_zero_mul {x : α} {r : ℝ} (hx : x ≠ 0) (hr : r ≠ 0) : abs (inner x (r • x) / (∥x∥ * ∥r • x∥)) = 1 := begin rw [inner_smul_self_right, norm_smul, real.norm_eq_abs, ←mul_assoc ∥x∥, mul_comm _ (abs r), mul_assoc, abs_div, abs_mul r, abs_mul (abs r), abs_abs, div_self], exact mul_ne_zero (λ h, hr (eq_zero_of_abs_eq_zero h)) (λ h, hx (norm_eq_zero.1 (eq_zero_of_mul_self_eq_zero (eq_zero_of_abs_eq_zero h)))) end /-- The inner product of a nonzero vector with a positive multiple of itself, divided by the product of their norms, has value 1. -/ lemma inner_div_norm_mul_norm_eq_one_of_ne_zero_of_pos_mul {x : α} {r : ℝ} (hx : x ≠ 0) (hr : 0 < r) : inner x (r • x) / (∥x∥ * ∥r • x∥) = 1 := begin rw [inner_smul_self_right, norm_smul, real.norm_eq_abs, ←mul_assoc ∥x∥, mul_comm _ (abs r), mul_assoc, abs_of_nonneg (le_of_lt hr), div_self], exact mul_ne_zero (ne_of_gt hr) (λ h, hx (norm_eq_zero.1 (eq_zero_of_mul_self_eq_zero h))) end /-- The inner product of a nonzero vector with a negative multiple of itself, divided by the product of their norms, has value -1. -/ lemma inner_div_norm_mul_norm_eq_neg_one_of_ne_zero_of_neg_mul {x : α} {r : ℝ} (hx : x ≠ 0) (hr : r < 0) : inner x (r • x) / (∥x∥ * ∥r • x∥) = -1 := begin rw [inner_smul_self_right, norm_smul, real.norm_eq_abs, ←mul_assoc ∥x∥, mul_comm _ (abs r), mul_assoc, abs_of_neg hr, ←neg_mul_eq_neg_mul, div_neg_eq_neg_div, div_self], exact mul_ne_zero (ne_of_lt hr) (λ h, hx (norm_eq_zero.1 (eq_zero_of_mul_self_eq_zero h))) end /-- The inner product of two vectors, divided by the product of their norms, has absolute value 1 if and only if they are nonzero and one is a multiple of the other. One form of equality case for Cauchy-Schwarz. -/ lemma abs_inner_div_norm_mul_norm_eq_one_iff (x y : α) : abs (inner x y / (∥x∥ * ∥y∥)) = 1 ↔ (x ≠ 0 ∧ ∃ (r : ℝ), r ≠ 0 ∧ y = r • x) := begin split, { intro h, have hx0 : x ≠ 0, { intro hx0, rw [hx0, inner_zero_left, zero_div] at h, norm_num at h, exact h }, refine and.intro hx0 _, set r := inner x y / (∥x∥ * ∥x∥) with hr, use r, set t := y - r • x with ht, have ht0 : inner x t = 0, { rw [ht, inner_sub_right, inner_smul_right, hr, ←inner_self_eq_norm_square, div_mul_cancel _ (λ h, hx0 (inner_self_eq_zero.1 h)), sub_self] }, rw [←sub_add_cancel y (r • x), ←ht, inner_add_right, ht0, zero_add, inner_smul_right, inner_self_eq_norm_square, ←mul_assoc, mul_comm, mul_div_mul_left _ _ (λ h, hx0 (norm_eq_zero.1 h)), abs_div, abs_mul, abs_of_nonneg (norm_nonneg _), abs_of_nonneg (norm_nonneg _), ←real.norm_eq_abs, ←norm_smul] at h, have hr0 : r ≠ 0, { intro hr0, rw [hr0, zero_smul, norm_zero, zero_div] at h, norm_num at h }, refine and.intro hr0 _, have h2 : ∥r • x∥ ^ 2 = ∥t + r • x∥ ^ 2, { rw [eq_of_div_eq_one h] }, rw [pow_two, pow_two, ←inner_self_eq_norm_square, ←inner_self_eq_norm_square, inner_add_add_self] at h2, conv_rhs at h2 { congr, congr, skip, rw [inner_smul_right, inner_comm, ht0, mul_zero, mul_zero] }, symmetry' at h2, rw [add_zero, add_left_eq_self, inner_self_eq_zero] at h2, rw h2 at ht, exact eq_of_sub_eq_zero ht.symm }, { intro h, rcases h with ⟨hx, ⟨r, ⟨hr, hy⟩⟩⟩, rw hy, exact abs_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_ne_zero_mul hx hr } end /-- The inner product of two vectors, divided by the product of their norms, has value 1 if and only if they are nonzero and one is a positive multiple of the other. -/ lemma inner_div_norm_mul_norm_eq_one_iff (x y : α) : inner x y / (∥x∥ * ∥y∥) = 1 ↔ (x ≠ 0 ∧ ∃ (r : ℝ), 0 < r ∧ y = r • x) := begin split, { intro h, have ha := h, apply_fun abs at ha, norm_num at ha, rcases (abs_inner_div_norm_mul_norm_eq_one_iff x y).1 ha with ⟨hx, ⟨r, ⟨hr, hy⟩⟩⟩, use [hx, r], refine and.intro _ hy, by_contradiction hrneg, rw hy at h, rw inner_div_norm_mul_norm_eq_neg_one_of_ne_zero_of_neg_mul hx (lt_of_le_of_ne (le_of_not_lt hrneg) hr) at h, norm_num at h }, { intro h, rcases h with ⟨hx, ⟨r, ⟨hr, hy⟩⟩⟩, rw hy, exact inner_div_norm_mul_norm_eq_one_of_ne_zero_of_pos_mul hx hr } end /-- The inner product of two vectors, divided by the product of their norms, has value -1 if and only if they are nonzero and one is a negative multiple of the other. -/ lemma inner_div_norm_mul_norm_eq_neg_one_iff (x y : α) : inner x y / (∥x∥ * ∥y∥) = -1 ↔ (x ≠ 0 ∧ ∃ (r : ℝ), r < 0 ∧ y = r • x) := begin split, { intro h, have ha := h, apply_fun abs at ha, norm_num at ha, rcases (abs_inner_div_norm_mul_norm_eq_one_iff x y).1 ha with ⟨hx, ⟨r, ⟨hr, hy⟩⟩⟩, use [hx, r], refine and.intro _ hy, by_contradiction hrpos, rw hy at h, rw inner_div_norm_mul_norm_eq_one_of_ne_zero_of_pos_mul hx (lt_of_le_of_ne (le_of_not_lt hrpos) hr.symm) at h, norm_num at h }, { intro h, rcases h with ⟨hx, ⟨r, ⟨hr, hy⟩⟩⟩, rw hy, exact inner_div_norm_mul_norm_eq_neg_one_of_ne_zero_of_neg_mul hx hr } end /-- The inner product of two weighted sums, where the weights in each sum add to 0, in terms of the norms of pairwise differences. -/ lemma inner_sum_smul_sum_smul_of_sum_eq_zero {ι₁ : Type*} {s₁ : finset ι₁} {w₁ : ι₁ → ℝ} (v₁ : ι₁ → α) (h₁ : ∑ i in s₁, w₁ i = 0) {ι₂ : Type*} {s₂ : finset ι₂} {w₂ : ι₂ → ℝ} (v₂ : ι₂ → α) (h₂ : ∑ i in s₂, w₂ i = 0) : inner (∑ i₁ in s₁, w₁ i₁ • v₁ i₁) (∑ i₂ in s₂, w₂ i₂ • v₂ i₂) = (-∑ i₁ in s₁, ∑ i₂ in s₂, w₁ i₁ * w₂ i₂ * (∥v₁ i₁ - v₂ i₂∥ * ∥v₁ i₁ - v₂ i₂∥)) / 2 := by simp_rw [sum_inner, inner_sum, inner_smul_left, inner_smul_right, inner_eq_norm_mul_self_add_norm_mul_self_sub_norm_sub_mul_self_div_two, ←div_sub_div_same, ←div_add_div_same, mul_sub_left_distrib, left_distrib, finset.sum_sub_distrib, finset.sum_add_distrib, ←finset.mul_sum, ←finset.sum_mul, h₁, h₂, zero_mul, mul_zero, finset.sum_const_zero, zero_add, zero_sub, finset.mul_sum, neg_div, finset.sum_div, mul_div_assoc, mul_assoc] end norm /-! ### Inner product space structure on product spaces -/ -- TODO [Lean 3.15]: drop some of these `show`s /-- If `ι` is a finite type and each space `f i`, `i : ι`, is an inner product space, then `Π i, f i` is an inner product space as well. Since `Π i, f i` is endowed with the sup norm, we use instead `pi_Lp 2 one_le_two f` for the product space, which is endowed with the `L^2` norm. -/ instance pi_Lp.inner_product_space (ι : Type*) [fintype ι] (f : ι → Type*) [Π i, inner_product_space (f i)] : inner_product_space (pi_Lp 2 one_le_two f) := { inner := λ x y, ∑ i, inner (x i) (y i), norm_eq_sqrt_inner := begin assume x, have : (2 : ℝ)⁻¹ * 2 = 1, by norm_num, simp [inner, pi_Lp.norm_eq, norm_eq_sqrt_inner, sqrt_eq_rpow, ← rpow_mul (inner_self_nonneg), this], end, comm := λ x y, finset.sum_congr rfl $ λ i hi, inner_comm (x i) (y i), add_left := λ x y z, show ∑ i, inner (x i + y i) (z i) = ∑ i, inner (x i) (z i) + ∑ i, inner (y i) (z i), by simp only [inner_add_left, finset.sum_add_distrib], smul_left := λ x y r, show ∑ (i : ι), inner (r • x i) (y i) = r * ∑ i, inner (x i) (y i), by simp only [finset.mul_sum, inner_smul_left] } /-- The type of real numbers is an inner product space. -/ instance real.inner_product_space : inner_product_space ℝ := { inner := (*), norm_eq_sqrt_inner := λ x, by simp [inner, norm_eq_abs, sqrt_mul_self_eq_abs], comm := mul_comm, add_left := add_mul, smul_left := λ _ _ _, mul_assoc _ _ _ } /-- The standard Euclidean space, functions on a finite type. For an `n`-dimensional space use `euclidean_space (fin n)`. -/ @[reducible, nolint unused_arguments] def euclidean_space (n : Type*) [fintype n] : Type* := pi_Lp 2 one_le_two (λ (i : n), ℝ) section pi_Lp local attribute [reducible] pi_Lp variables (n : Type*) [fintype n] instance : finite_dimensional ℝ (euclidean_space n) := by apply_instance @[simp] lemma findim_euclidean_space : finite_dimensional.findim ℝ (euclidean_space n) = fintype.card n := by simp lemma findim_euclidean_space_fin {n : ℕ} : finite_dimensional.findim ℝ (euclidean_space (fin n)) = n := by simp end pi_Lp /-! ### Orthogonal projection in inner product spaces -/ section orthogonal open filter /-- Existence of minimizers Let `u` be a point in an inner product space, and let `K` be a nonempty complete convex subset. Then there exists a unique `v` in `K` that minimizes the distance `∥u - v∥` to `u`. -/ -- FIXME this monolithic proof causes a deterministic timeout with `-T50000` -- It should be broken in a sequence of more manageable pieces, -- perhaps with individual statements for the three steps below. theorem exists_norm_eq_infi_of_complete_convex {K : set α} (ne : K.nonempty) (h₁ : is_complete K) (h₂ : convex K) : ∀ u : α, ∃ v ∈ K, ∥u - v∥ = ⨅ w : K, ∥u - w∥ := assume u, begin let δ := ⨅ w : K, ∥u - w∥, letI : nonempty K := ne.to_subtype, have zero_le_δ : 0 ≤ δ := le_cinfi (λ _, norm_nonneg _), have δ_le : ∀ w : K, δ ≤ ∥u - w∥, from cinfi_le ⟨0, forall_range_iff.2 $ λ _, norm_nonneg _⟩, have δ_le' : ∀ w ∈ K, δ ≤ ∥u - w∥ := assume w hw, δ_le ⟨w, hw⟩, -- Step 1: since `δ` is the infimum, can find a sequence `w : ℕ → K` in `K` -- such that `∥u - w n∥ < δ + 1 / (n + 1)` (which implies `∥u - w n∥ --> δ`); -- maybe this should be a separate lemma have exists_seq : ∃ w : ℕ → K, ∀ n, ∥u - w n∥ < δ + 1 / (n + 1), { have hδ : ∀n:ℕ, δ < δ + 1 / (n + 1), from λ n, lt_add_of_le_of_pos (le_refl _) nat.one_div_pos_of_nat, have h := λ n, exists_lt_of_cinfi_lt (hδ n), let w : ℕ → K := λ n, classical.some (h n), exact ⟨w, λ n, classical.some_spec (h n)⟩ }, rcases exists_seq with ⟨w, hw⟩, have norm_tendsto : tendsto (λ n, ∥u - w n∥) at_top (𝓝 δ), { have h : tendsto (λ n:ℕ, δ) at_top (𝓝 δ) := tendsto_const_nhds, have h' : tendsto (λ n:ℕ, δ + 1 / (n + 1)) at_top (𝓝 δ), { convert h.add tendsto_one_div_add_at_top_nhds_0_nat, simp only [add_zero] }, exact tendsto_of_tendsto_of_tendsto_of_le_of_le h h' (λ x, δ_le _) (λ x, le_of_lt (hw _)) }, -- Step 2: Prove that the sequence `w : ℕ → K` is a Cauchy sequence have seq_is_cauchy : cauchy_seq (λ n, ((w n):α)), { rw cauchy_seq_iff_le_tendsto_0, -- splits into three goals let b := λ n:ℕ, (8 * δ * (1/(n+1)) + 4 * (1/(n+1)) * (1/(n+1))), use (λn, sqrt (b n)), split, -- first goal : `∀ (n : ℕ), 0 ≤ sqrt (b n)` assume n, exact sqrt_nonneg _, split, -- second goal : `∀ (n m N : ℕ), N ≤ n → N ≤ m → dist ↑(w n) ↑(w m) ≤ sqrt (b N)` assume p q N hp hq, let wp := ((w p):α), let wq := ((w q):α), let a := u - wq, let b := u - wp, let half := 1 / (2:ℝ), let div := 1 / ((N:ℝ) + 1), have : 4 * ∥u - half • (wq + wp)∥ * ∥u - half • (wq + wp)∥ + ∥wp - wq∥ * ∥wp - wq∥ = 2 * (∥a∥ * ∥a∥ + ∥b∥ * ∥b∥) := calc 4 * ∥u - half•(wq + wp)∥ * ∥u - half•(wq + wp)∥ + ∥wp - wq∥ * ∥wp - wq∥ = (2*∥u - half•(wq + wp)∥) * (2 * ∥u - half•(wq + wp)∥) + ∥wp-wq∥*∥wp-wq∥ : by ring ... = (abs((2:ℝ)) * ∥u - half•(wq + wp)∥) * (abs((2:ℝ)) * ∥u - half•(wq+wp)∥) + ∥wp-wq∥*∥wp-wq∥ : by { rw abs_of_nonneg, exact add_nonneg zero_le_one zero_le_one } ... = ∥(2:ℝ) • (u - half • (wq + wp))∥ * ∥(2:ℝ) • (u - half • (wq + wp))∥ + ∥wp-wq∥ * ∥wp-wq∥ : by { rw [norm_smul], refl } ... = ∥a + b∥ * ∥a + b∥ + ∥a - b∥ * ∥a - b∥ : begin rw [smul_sub, smul_smul, mul_one_div_cancel (two_ne_zero : (2 : ℝ) ≠ 0), ← one_add_one_eq_two, add_smul], simp only [one_smul], have eq₁ : wp - wq = a - b, show wp - wq = (u - wq) - (u - wp), abel, have eq₂ : u + u - (wq + wp) = a + b, show u + u - (wq + wp) = (u - wq) + (u - wp), abel, rw [eq₁, eq₂], end ... = 2 * (∥a∥ * ∥a∥ + ∥b∥ * ∥b∥) : parallelogram_law_with_norm, have eq : δ ≤ ∥u - half • (wq + wp)∥, { rw smul_add, apply δ_le', apply h₂, repeat {exact subtype.mem _}, repeat {exact le_of_lt one_half_pos}, exact add_halves 1 }, have eq₁ : 4 * δ * δ ≤ 4 * ∥u - half • (wq + wp)∥ * ∥u - half • (wq + wp)∥, { mono, mono, norm_num, apply mul_nonneg, norm_num, exact norm_nonneg _ }, have eq₂ : ∥a∥ * ∥a∥ ≤ (δ + div) * (δ + div) := mul_self_le_mul_self (norm_nonneg _) (le_trans (le_of_lt $ hw q) (add_le_add_left (nat.one_div_le_one_div hq) _)), have eq₂' : ∥b∥ * ∥b∥ ≤ (δ + div) * (δ + div) := mul_self_le_mul_self (norm_nonneg _) (le_trans (le_of_lt $ hw p) (add_le_add_left (nat.one_div_le_one_div hp) _)), rw dist_eq_norm, apply nonneg_le_nonneg_of_squares_le, { exact sqrt_nonneg _ }, rw mul_self_sqrt, exact calc ∥wp - wq∥ * ∥wp - wq∥ = 2 * (∥a∥*∥a∥ + ∥b∥*∥b∥) - 4 * ∥u - half • (wq+wp)∥ * ∥u - half • (wq+wp)∥ : by { rw ← this, simp } ... ≤ 2 * (∥a∥ * ∥a∥ + ∥b∥ * ∥b∥) - 4 * δ * δ : sub_le_sub_left eq₁ _ ... ≤ 2 * ((δ + div) * (δ + div) + (δ + div) * (δ + div)) - 4 * δ * δ : sub_le_sub_right (mul_le_mul_of_nonneg_left (add_le_add eq₂ eq₂') (by norm_num)) _ ... = 8 * δ * div + 4 * div * div : by ring, exact add_nonneg (mul_nonneg (mul_nonneg (by norm_num) zero_le_δ) (le_of_lt nat.one_div_pos_of_nat)) (mul_nonneg (mul_nonneg (by norm_num) (le_of_lt nat.one_div_pos_of_nat)) (le_of_lt nat.one_div_pos_of_nat)), -- third goal : `tendsto (λ (n : ℕ), sqrt (b n)) at_top (𝓝 0)` apply tendsto.comp, { convert continuous_sqrt.continuous_at, exact sqrt_zero.symm }, have eq₁ : tendsto (λ (n : ℕ), 8 * δ * (1 / (n + 1))) at_top (𝓝 (0:ℝ)), { convert (@tendsto_const_nhds _ _ _ (8 * δ) _).mul tendsto_one_div_add_at_top_nhds_0_nat, simp only [mul_zero] }, have : tendsto (λ (n : ℕ), (4:ℝ) * (1 / (n + 1))) at_top (𝓝 (0:ℝ)), { convert (@tendsto_const_nhds _ _ _ (4:ℝ) _).mul tendsto_one_div_add_at_top_nhds_0_nat, simp only [mul_zero] }, have eq₂ : tendsto (λ (n : ℕ), (4:ℝ) * (1 / (n + 1)) * (1 / (n + 1))) at_top (𝓝 (0:ℝ)), { convert this.mul tendsto_one_div_add_at_top_nhds_0_nat, simp only [mul_zero] }, convert eq₁.add eq₂, simp only [add_zero] }, -- Step 3: By completeness of `K`, let `w : ℕ → K` converge to some `v : K`. -- Prove that it satisfies all requirements. rcases cauchy_seq_tendsto_of_is_complete h₁ (λ n, _) seq_is_cauchy with ⟨v, hv, w_tendsto⟩, use v, use hv, have h_cont : continuous (λ v, ∥u - v∥) := continuous.comp continuous_norm (continuous.sub continuous_const continuous_id), have : tendsto (λ n, ∥u - w n∥) at_top (𝓝 ∥u - v∥), convert (tendsto.comp h_cont.continuous_at w_tendsto), exact tendsto_nhds_unique this norm_tendsto, exact subtype.mem _ end /-- Characterization of minimizers in the above theorem -/ theorem norm_eq_infi_iff_inner_le_zero {K : set α} (h : convex K) {u : α} {v : α} (hv : v ∈ K) : ∥u - v∥ = (⨅ w : K, ∥u - w∥) ↔ ∀ w ∈ K, inner (u - v) (w - v) ≤ 0 := iff.intro begin assume eq w hw, let δ := ⨅ w : K, ∥u - w∥, let p := inner (u - v) (w - v), let q := ∥w - v∥^2, letI : nonempty K := ⟨⟨v, hv⟩⟩, have zero_le_δ : 0 ≤ δ, apply le_cinfi, intro, exact norm_nonneg _, have δ_le : ∀ w : K, δ ≤ ∥u - w∥, assume w, apply cinfi_le, use (0:ℝ), rintros _ ⟨_, rfl⟩, exact norm_nonneg _, have δ_le' : ∀ w ∈ K, δ ≤ ∥u - w∥ := assume w hw, δ_le ⟨w, hw⟩, have : ∀θ:ℝ, 0 < θ → θ ≤ 1 → 2 * p ≤ θ * q, assume θ hθ₁ hθ₂, have : ∥u - v∥^2 ≤ ∥u - v∥^2 - 2 * θ * inner (u - v) (w - v) + θ*θ*∥w - v∥^2 := calc ∥u - v∥^2 ≤ ∥u - (θ•w + (1-θ)•v)∥^2 : begin simp only [pow_two], apply mul_self_le_mul_self (norm_nonneg _), rw [eq], apply δ_le', apply h hw hv, exacts [le_of_lt hθ₁, sub_nonneg.2 hθ₂, add_sub_cancel'_right _ _], end ... = ∥(u - v) - θ • (w - v)∥^2 : begin have : u - (θ•w + (1-θ)•v) = (u - v) - θ • (w - v), { rw [smul_sub, sub_smul, one_smul], simp only [sub_eq_add_neg, add_comm, add_left_comm, add_assoc, neg_add_rev] }, rw this end ... = ∥u - v∥^2 - 2 * θ * inner (u - v) (w - v) + θ*θ*∥w - v∥^2 : begin rw [norm_sub_pow_two, inner_smul_right, norm_smul], simp only [pow_two], show ∥u-v∥*∥u-v∥-2*(θ*inner(u-v)(w-v))+abs(θ)*∥w-v∥*(abs(θ)*∥w-v∥)= ∥u-v∥*∥u-v∥-2*θ*inner(u-v)(w-v)+θ*θ*(∥w-v∥*∥w-v∥), rw abs_of_pos hθ₁, ring end, have eq₁ : ∥u-v∥^2-2*θ*inner(u-v)(w-v)+θ*θ*∥w-v∥^2=∥u-v∥^2+(θ*θ*∥w-v∥^2-2*θ*inner(u-v)(w-v)), abel, rw [eq₁, le_add_iff_nonneg_right] at this, have eq₂ : θ*θ*∥w-v∥^2-2*θ*inner(u-v)(w-v)=θ*(θ*∥w-v∥^2-2*inner(u-v)(w-v)), ring, rw eq₂ at this, have := le_of_sub_nonneg (nonneg_of_mul_nonneg_left this hθ₁), exact this, by_cases hq : q = 0, { rw hq at this, have : p ≤ 0, have := this (1:ℝ) (by norm_num) (by norm_num), linarith, exact this }, { have q_pos : 0 < q, apply lt_of_le_of_ne, exact pow_two_nonneg _, intro h, exact hq h.symm, by_contradiction hp, rw not_le at hp, let θ := min (1:ℝ) (p / q), have eq₁ : θ*q ≤ p := calc θ*q ≤ (p/q) * q : mul_le_mul_of_nonneg_right (min_le_right _ _) (pow_two_nonneg _) ... = p : div_mul_cancel _ hq, have : 2 * p ≤ p := calc 2 * p ≤ θ*q : by { refine this θ (lt_min (by norm_num) (div_pos hp q_pos)) (by norm_num) } ... ≤ p : eq₁, linarith } end begin assume h, letI : nonempty K := ⟨⟨v, hv⟩⟩, apply le_antisymm, { apply le_cinfi, assume w, apply nonneg_le_nonneg_of_squares_le (norm_nonneg _), have := h w w.2, exact calc ∥u - v∥ * ∥u - v∥ ≤ ∥u - v∥ * ∥u - v∥ - 2 * inner (u - v) ((w:α) - v) : by linarith ... ≤ ∥u - v∥^2 - 2 * inner (u - v) ((w:α) - v) + ∥(w:α) - v∥^2 : by { rw pow_two, refine le_add_of_nonneg_right _, exact pow_two_nonneg _ } ... = ∥(u - v) - (w - v)∥^2 : norm_sub_pow_two.symm ... = ∥u - w∥ * ∥u - w∥ : by { have : (u - v) - (w - v) = u - w, abel, rw [this, pow_two] } }, { show (⨅ (w : K), ∥u - w∥) ≤ (λw:K, ∥u - w∥) ⟨v, hv⟩, apply cinfi_le, use 0, rintros y ⟨z, rfl⟩, exact norm_nonneg _ } end /-- Existence of minimizers. Let `u` be a point in an inner product space, and let `K` be a nonempty complete subspace. Then there exists a unique `v` in `K` that minimizes the distance `∥u - v∥` to `u`. This point `v` is usually called the orthogonal projection of `u` onto `K`. -/ theorem exists_norm_eq_infi_of_complete_subspace (K : subspace ℝ α) (h : is_complete (↑K : set α)) : ∀ u : α, ∃ v ∈ K, ∥u - v∥ = ⨅ w : (↑K : set α), ∥u - w∥ := exists_norm_eq_infi_of_complete_convex ⟨0, K.zero_mem⟩ h K.convex /-- Characterization of minimizers in the above theorem. Let `u` be a point in an inner product space, and let `K` be a nonempty subspace. Then point `v` minimizes the distance `∥u - v∥` if and only if for all `w ∈ K`, `inner (u - v) w = 0` (i.e., `u - v` is orthogonal to the subspace `K`) -/ theorem norm_eq_infi_iff_inner_eq_zero (K : subspace ℝ α) {u : α} {v : α} (hv : v ∈ K) : ∥u - v∥ = (⨅ w : (↑K : set α), ∥u - w∥) ↔ ∀ w ∈ K, inner (u - v) w = 0 := iff.intro begin assume h, have h : ∀ w ∈ K, inner (u - v) (w - v) ≤ 0, { rwa [norm_eq_infi_iff_inner_le_zero] at h, exacts [K.convex, hv] }, assume w hw, have le : inner (u - v) w ≤ 0, let w' := w + v, have : w' ∈ K := submodule.add_mem _ hw hv, have h₁ := h w' this, have h₂ : w' - v = w, simp only [add_neg_cancel_right, sub_eq_add_neg], rw h₂ at h₁, exact h₁, have ge : inner (u - v) w ≥ 0, let w'' := -w + v, have : w'' ∈ K := submodule.add_mem _ (submodule.neg_mem _ hw) hv, have h₁ := h w'' this, have h₂ : w'' - v = -w, simp only [neg_inj, add_neg_cancel_right, sub_eq_add_neg], rw [h₂, inner_neg_right] at h₁, linarith, exact le_antisymm le ge end begin assume h, have : ∀ w ∈ K, inner (u - v) (w - v) ≤ 0, assume w hw, let w' := w - v, have : w' ∈ K := submodule.sub_mem _ hw hv, have h₁ := h w' this, exact le_of_eq h₁, rwa norm_eq_infi_iff_inner_le_zero, exacts [submodule.convex _, hv] end /-- The orthogonal projection onto a complete subspace, as an unbundled function. This definition is only intended for use in setting up the bundled version `orthogonal_projection` and should not be used once that is defined. -/ def orthogonal_projection_fn {K : submodule ℝ α} (h : is_complete (K : set α)) (v : α) := (exists_norm_eq_infi_of_complete_subspace K h v).some /-- The unbundled orthogonal projection is in the given subspace. This lemma is only intended for use in setting up the bundled version and should not be used once that is defined. -/ lemma orthogonal_projection_fn_mem {K : submodule ℝ α} (h : is_complete (K : set α)) (v : α) : orthogonal_projection_fn h v ∈ K := (exists_norm_eq_infi_of_complete_subspace K h v).some_spec.some /-- The characterization of the unbundled orthogonal projection. This lemma is only intended for use in setting up the bundled version and should not be used once that is defined. -/ lemma orthogonal_projection_fn_inner_eq_zero {K : submodule ℝ α} (h : is_complete (K : set α)) (v : α) : ∀ w ∈ K, inner (v - orthogonal_projection_fn h v) w = 0 := begin rw ←norm_eq_infi_iff_inner_eq_zero K (orthogonal_projection_fn_mem h v), exact (exists_norm_eq_infi_of_complete_subspace K h v).some_spec.some_spec end /-- The unbundled orthogonal projection is the unique point in `K` with the orthogonality property. This lemma is only intended for use in setting up the bundled version and should not be used once that is defined. -/ lemma eq_orthogonal_projection_fn_of_mem_of_inner_eq_zero {K : submodule ℝ α} (h : is_complete (K : set α)) {u v : α} (hvm : v ∈ K) (hvo : ∀ w ∈ K, inner (u - v) w = 0) : v = orthogonal_projection_fn h u := begin rw [←sub_eq_zero, ←inner_self_eq_zero], have hvs : v - orthogonal_projection_fn h u ∈ K := submodule.sub_mem K hvm (orthogonal_projection_fn_mem h u), have huo : inner (u - orthogonal_projection_fn h u) (v - orthogonal_projection_fn h u) = 0 := orthogonal_projection_fn_inner_eq_zero h u _ hvs, have huv : inner (u - v) (v - orthogonal_projection_fn h u) = 0 := hvo _ hvs, have houv : inner ((u - orthogonal_projection_fn h u) - (u - v)) (v - orthogonal_projection_fn h u) = 0, { rw [inner_sub_left, huo, huv, sub_zero] }, rwa sub_sub_sub_cancel_left at houv end /-- The orthogonal projection onto a complete subspace. For most purposes, `orthogonal_projection`, which removes the `is_complete` hypothesis and is the identity map when the subspace is not complete, should be used instead. -/ def orthogonal_projection_of_complete {K : submodule ℝ α} (h : is_complete (K : set α)) : linear_map ℝ α α := { to_fun := orthogonal_projection_fn h, map_add' := λ x y, begin have hm : orthogonal_projection_fn h x + orthogonal_projection_fn h y ∈ K := submodule.add_mem K (orthogonal_projection_fn_mem h x) (orthogonal_projection_fn_mem h y), have ho : ∀ w ∈ K, inner (x + y - (orthogonal_projection_fn h x + orthogonal_projection_fn h y)) w = 0, { intros w hw, rw [add_sub_comm, inner_add_left, orthogonal_projection_fn_inner_eq_zero h _ w hw, orthogonal_projection_fn_inner_eq_zero h _ w hw, add_zero] }, rw eq_orthogonal_projection_fn_of_mem_of_inner_eq_zero h hm ho end, map_smul' := λ c x, begin have hm : c • orthogonal_projection_fn h x ∈ K := submodule.smul_mem K _ (orthogonal_projection_fn_mem h x), have ho : ∀ w ∈ K, inner (c • x - c • orthogonal_projection_fn h x) w = 0, { intros w hw, rw [←smul_sub, inner_smul_left, orthogonal_projection_fn_inner_eq_zero h _ w hw, mul_zero] }, rw eq_orthogonal_projection_fn_of_mem_of_inner_eq_zero h hm ho end } /-- The orthogonal projection onto a subspace, which is expected to be complete. If the subspace is not complete, this uses the identity map instead. -/ def orthogonal_projection (K : submodule ℝ α) : linear_map ℝ α α := if h : is_complete (K : set α) then orthogonal_projection_of_complete h else linear_map.id /-- The definition of `orthogonal_projection` using `if`. -/ lemma orthogonal_projection_def (K : submodule ℝ α) : orthogonal_projection K = if h : is_complete (K : set α) then orthogonal_projection_of_complete h else linear_map.id := rfl @[simp] lemma orthogonal_projection_fn_eq {K : submodule ℝ α} (h : is_complete (K : set α)) (v : α) : orthogonal_projection_fn h v = orthogonal_projection K v := by { rw [orthogonal_projection_def, dif_pos h], refl } /-- The orthogonal projection is in the given subspace. -/ lemma orthogonal_projection_mem {K : submodule ℝ α} (h : is_complete (K : set α)) (v : α) : orthogonal_projection K v ∈ K := begin rw ←orthogonal_projection_fn_eq h, exact orthogonal_projection_fn_mem h v end /-- The characterization of the orthogonal projection. -/ @[simp] lemma orthogonal_projection_inner_eq_zero (K : submodule ℝ α) (v : α) : ∀ w ∈ K, inner (v - orthogonal_projection K v) w = 0 := begin simp_rw orthogonal_projection_def, split_ifs, { exact orthogonal_projection_fn_inner_eq_zero h v }, { simp }, end /-- The orthogonal projection is the unique point in `K` with the orthogonality property. -/ lemma eq_orthogonal_projection_of_mem_of_inner_eq_zero {K : submodule ℝ α} (h : is_complete (K : set α)) {u v : α} (hvm : v ∈ K) (hvo : ∀ w ∈ K, inner (u - v) w = 0) : v = orthogonal_projection K u := begin rw ←orthogonal_projection_fn_eq h, exact eq_orthogonal_projection_fn_of_mem_of_inner_eq_zero h hvm hvo end /-- The subspace of vectors orthogonal to a given subspace. -/ def submodule.orthogonal (K : submodule ℝ α) : submodule ℝ α := { carrier := {v | ∀ u ∈ K, inner u v = 0}, zero_mem' := λ _ _, inner_zero_right, add_mem' := λ x y hx hy u hu, by rw [inner_add_right, hx u hu, hy u hu, add_zero], smul_mem' := λ c x hx u hu, by rw [inner_smul_right, hx u hu, mul_zero] } /-- When a vector is in `K.orthogonal`. -/ lemma submodule.mem_orthogonal (K : submodule ℝ α) (v : α) : v ∈ K.orthogonal ↔ ∀ u ∈ K, inner u v = 0 := iff.rfl /-- When a vector is in `K.orthogonal`, with the inner product the other way round. -/ lemma submodule.mem_orthogonal' (K : submodule ℝ α) (v : α) : v ∈ K.orthogonal ↔ ∀ u ∈ K, inner v u = 0 := by simp_rw [submodule.mem_orthogonal, inner_comm] /-- A vector in `K` is orthogonal to one in `K.orthogonal`. -/ lemma submodule.inner_right_of_mem_orthogonal {u v : α} {K : submodule ℝ α} (hu : u ∈ K) (hv : v ∈ K.orthogonal) : inner u v = 0 := (K.mem_orthogonal v).1 hv u hu /-- A vector in `K.orthogonal` is orthogonal to one in `K`. -/ lemma submodule.inner_left_of_mem_orthogonal {u v : α} {K : submodule ℝ α} (hu : u ∈ K) (hv : v ∈ K.orthogonal) : inner v u = 0 := inner_comm u v ▸ submodule.inner_right_of_mem_orthogonal hu hv /-- `K` and `K.orthogonal` have trivial intersection. -/ lemma submodule.orthogonal_disjoint (K : submodule ℝ α) : disjoint K K.orthogonal := begin simp_rw [submodule.disjoint_def, submodule.mem_orthogonal], exact λ x hx ho, inner_self_eq_zero.1 (ho x hx) end variables (α) /-- `submodule.orthogonal` gives a `galois_connection` between `submodule ℝ α` and its `order_dual`. -/ lemma submodule.orthogonal_gc : @galois_connection (submodule ℝ α) (order_dual $ submodule ℝ α) _ _ submodule.orthogonal submodule.orthogonal := λ K₁ K₂, ⟨λ h v hv u hu, submodule.inner_left_of_mem_orthogonal hv (h hu), λ h v hv u hu, submodule.inner_left_of_mem_orthogonal hv (h hu)⟩ variables {α} /-- `submodule.orthogonal` reverses the `≤` ordering of two subspaces. -/ lemma submodule.orthogonal_le {K₁ K₂ : submodule ℝ α} (h : K₁ ≤ K₂) : K₂.orthogonal ≤ K₁.orthogonal := (submodule.orthogonal_gc α).monotone_l h /-- `K` is contained in `K.orthogonal.orthogonal`. -/ lemma submodule.le_orthogonal_orthogonal (K : submodule ℝ α) : K ≤ K.orthogonal.orthogonal := (submodule.orthogonal_gc α).le_u_l _ /-- The inf of two orthogonal subspaces equals the subspace orthogonal to the sup. -/ lemma submodule.inf_orthogonal (K₁ K₂ : submodule ℝ α) : K₁.orthogonal ⊓ K₂.orthogonal = (K₁ ⊔ K₂).orthogonal := (submodule.orthogonal_gc α).l_sup.symm /-- The inf of an indexed family of orthogonal subspaces equals the subspace orthogonal to the sup. -/ lemma submodule.infi_orthogonal {ι : Type*} (K : ι → submodule ℝ α) : (⨅ i, (K i).orthogonal) = (supr K).orthogonal := (submodule.orthogonal_gc α).l_supr.symm /-- The inf of a set of orthogonal subspaces equals the subspace orthogonal to the sup. -/ lemma submodule.Inf_orthogonal (s : set $ submodule ℝ α) : (⨅ K ∈ s, submodule.orthogonal K) = (Sup s).orthogonal := (submodule.orthogonal_gc α).l_Sup.symm /-- If `K₁` is complete and contained in `K₂`, `K₁` and `K₁.orthogonal ⊓ K₂` span `K₂`. -/ lemma submodule.sup_orthogonal_inf_of_is_complete {K₁ K₂ : submodule ℝ α} (h : K₁ ≤ K₂) (hc : is_complete (K₁ : set α)) : K₁ ⊔ (K₁.orthogonal ⊓ K₂) = K₂ := begin ext x, rw submodule.mem_sup, rcases exists_norm_eq_infi_of_complete_subspace K₁ hc x with ⟨v, hv, hvm⟩, rw norm_eq_infi_iff_inner_eq_zero K₁ hv at hvm, split, { rintro ⟨y, hy, z, hz, rfl⟩, exact K₂.add_mem (h hy) hz.2 }, { exact λ hx, ⟨v, hv, x - v, ⟨(K₁.mem_orthogonal' _).2 hvm, K₂.sub_mem hx (h hv)⟩, add_sub_cancel'_right _ _⟩ } end /-- If `K` is complete, `K` and `K.orthogonal` span the whole space. -/ lemma submodule.sup_orthogonal_of_is_complete {K : submodule ℝ α} (h : is_complete (K : set α)) : K ⊔ K.orthogonal = ⊤ := begin convert submodule.sup_orthogonal_inf_of_is_complete (le_top : K ≤ ⊤) h, simp end /-- If `K` is complete, `K` and `K.orthogonal` are complements of each other. -/ lemma submodule.is_compl_orthogonal_of_is_complete {K : submodule ℝ α} (h : is_complete (K : set α)) : is_compl K K.orthogonal := ⟨K.orthogonal_disjoint, le_of_eq (submodule.sup_orthogonal_of_is_complete h).symm⟩ open finite_dimensional /-- Given a finite-dimensional subspace `K₂`, and a subspace `K₁` containined in it, the dimensions of `K₁` and the intersection of its orthogonal subspace with `K₂` add to that of `K₂`. -/ lemma submodule.findim_add_inf_findim_orthogonal {K₁ K₂ : submodule ℝ α} [finite_dimensional ℝ K₂] (h : K₁ ≤ K₂) : findim ℝ K₁ + findim ℝ (K₁.orthogonal ⊓ K₂ : submodule ℝ α) = findim ℝ K₂ := begin haveI := submodule.finite_dimensional_of_le h, have hd := submodule.dim_sup_add_dim_inf_eq K₁ (K₁.orthogonal ⊓ K₂), rw [←inf_assoc, (submodule.orthogonal_disjoint K₁).eq_bot, bot_inf_eq, findim_bot, submodule.sup_orthogonal_inf_of_is_complete h (submodule.complete_of_finite_dimensional _)] at hd, rw add_zero at hd, exact hd.symm end end orthogonal
6028072b833b1aa9c173a306cecbbaf0d7615db6
63abd62053d479eae5abf4951554e1064a4c45b4
/src/order/complete_lattice.lean
7044dbdd520c2c84003d09473502617078b0ead9
[ "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
38,167
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import order.bounds /-! # Theory of complete lattices ## Main definitions * `Sup` and `Inf` are the supremum and the infimum of a set; * `supr (f : ι → α)` and `infi (f : ι → α)` are indexed supremum and infimum of a function, defined as `Sup` and `Inf` of the range of this function; * `class complete_lattice`: a bounded lattice such that `Sup s` is always the least upper boundary of `s` and `Inf s` is always the greatest lower boundary of `s`; * `class complete_linear_order`: a linear ordered complete lattice. ## Naming conventions We use `Sup`/`Inf`/`supr`/`infi` for the corresponding functions in the statement. Sometimes we also use `bsupr`/`binfi` for "bounded` supremum or infimum, i.e. one of `⨆ i ∈ s, f i`, `⨆ i (hi : p i), f i`, or more generally `⨆ i (hi : p i), f i hi`. ## Notation * `⨆ i, f i` : `supr f`, the supremum of the range of `f`; * `⨅ i, f i` : `infi f`, the infimum of the range of `f`. -/ set_option old_structure_cmd true open set variables {α β β₂ : Type*} {ι ι₂ : Sort*} /-- class for the `Sup` operator -/ class has_Sup (α : Type*) := (Sup : set α → α) /-- class for the `Inf` operator -/ class has_Inf (α : Type*) := (Inf : set α → α) export has_Sup (Sup) has_Inf (Inf) /-- Supremum of a set -/ add_decl_doc has_Sup.Sup /-- Infimum of a set -/ add_decl_doc has_Inf.Inf /-- Indexed supremum -/ def supr [has_Sup α] {ι} (s : ι → α) : α := Sup (range s) /-- Indexed infimum -/ def infi [has_Inf α] {ι} (s : ι → α) : α := Inf (range s) @[priority 50] instance has_Inf_to_nonempty (α) [has_Inf α] : nonempty α := ⟨Inf ∅⟩ @[priority 50] instance has_Sup_to_nonempty (α) [has_Sup α] : nonempty α := ⟨Sup ∅⟩ notation `⨆` binders `, ` r:(scoped f, supr f) := r notation `⨅` binders `, ` r:(scoped f, infi f) := r instance (α) [has_Inf α] : has_Sup (order_dual α) := ⟨(Inf : set α → α)⟩ instance (α) [has_Sup α] : has_Inf (order_dual α) := ⟨(Sup : set α → α)⟩ /-- A complete lattice is a bounded lattice which has suprema and infima for every subset. -/ class complete_lattice (α : Type*) extends bounded_lattice α, has_Sup α, has_Inf α := (le_Sup : ∀s, ∀a∈s, a ≤ Sup s) (Sup_le : ∀s a, (∀b∈s, b ≤ a) → Sup s ≤ a) (Inf_le : ∀s, ∀a∈s, Inf s ≤ a) (le_Inf : ∀s a, (∀b∈s, a ≤ b) → a ≤ Inf s) /-- Create a `complete_lattice` from a `partial_order` and `Inf` function that returns the greatest lower bound of a set. Usually this constructor provides poor definitional equalities, so it should be used with `.. complete_lattice_of_Inf α _`. -/ def complete_lattice_of_Inf (α : Type*) [H1 : partial_order α] [H2 : has_Inf α] (is_glb_Inf : ∀ s : set α, is_glb s (Inf s)) : complete_lattice α := { bot := Inf univ, bot_le := λ x, (is_glb_Inf univ).1 trivial, top := Inf ∅, le_top := λ a, (is_glb_Inf ∅).2 $ by simp, sup := λ a b, Inf {x | a ≤ x ∧ b ≤ x}, inf := λ a b, Inf {a, b}, le_inf := λ a b c hab hac, by { apply (is_glb_Inf _).2, simp [*] }, inf_le_right := λ a b, (is_glb_Inf _).1 $ mem_insert_of_mem _ $ mem_singleton _, inf_le_left := λ a b, (is_glb_Inf _).1 $ mem_insert _ _, sup_le := λ a b c hac hbc, (is_glb_Inf _).1 $ by simp [*], le_sup_left := λ a b, (is_glb_Inf _).2 $ λ x, and.left, le_sup_right := λ a b, (is_glb_Inf _).2 $ λ x, and.right, le_Inf := λ s a ha, (is_glb_Inf s).2 ha, Inf_le := λ s a ha, (is_glb_Inf s).1 ha, Sup := λ s, Inf (upper_bounds s), le_Sup := λ s a ha, (is_glb_Inf (upper_bounds s)).2 $ λ b hb, hb ha, Sup_le := λ s a ha, (is_glb_Inf (upper_bounds s)).1 ha, .. H1, .. H2 } /-- Create a `complete_lattice` from a `partial_order` and `Sup` function that returns the least upper bound of a set. Usually this constructor provides poor definitional equalities, so it should be used with `.. complete_lattice_of_Sup α _`. -/ def complete_lattice_of_Sup (α : Type*) [H1 : partial_order α] [H2 : has_Sup α] (is_lub_Sup : ∀ s : set α, is_lub s (Sup s)) : complete_lattice α := { top := Sup univ, le_top := λ x, (is_lub_Sup univ).1 trivial, bot := Sup ∅, bot_le := λ x, (is_lub_Sup ∅).2 $ by simp, sup := λ a b, Sup {a, b}, sup_le := λ a b c hac hbc, (is_lub_Sup _).2 (by simp [*]), le_sup_left := λ a b, (is_lub_Sup _).1 $ mem_insert _ _, le_sup_right := λ a b, (is_lub_Sup _).1 $ mem_insert_of_mem _ $ mem_singleton _, inf := λ a b, Sup {x | x ≤ a ∧ x ≤ b}, le_inf := λ a b c hab hac, (is_lub_Sup _).1 $ by simp [*], inf_le_left := λ a b, (is_lub_Sup _).2 (λ x, and.left), inf_le_right := λ a b, (is_lub_Sup _).2 (λ x, and.right), Inf := λ s, Sup (lower_bounds s), Sup_le := λ s a ha, (is_lub_Sup s).2 ha, le_Sup := λ s a ha, (is_lub_Sup s).1 ha, Inf_le := λ s a ha, (is_lub_Sup (lower_bounds s)).2 (λ b hb, hb ha), le_Inf := λ s a ha, (is_lub_Sup (lower_bounds s)).1 ha, .. H1, .. H2 } /-- A complete linear order is a linear order whose lattice structure is complete. -/ class complete_linear_order (α : Type*) extends complete_lattice α, linear_order α namespace order_dual variable (α) instance [complete_lattice α] : complete_lattice (order_dual α) := { le_Sup := @complete_lattice.Inf_le α _, Sup_le := @complete_lattice.le_Inf α _, Inf_le := @complete_lattice.le_Sup α _, le_Inf := @complete_lattice.Sup_le α _, .. order_dual.bounded_lattice α, ..order_dual.has_Sup α, ..order_dual.has_Inf α } instance [complete_linear_order α] : complete_linear_order (order_dual α) := { .. order_dual.complete_lattice α, .. order_dual.linear_order α } end order_dual section variables [complete_lattice α] {s t : set α} {a b : α} @[ematch] theorem le_Sup : a ∈ s → a ≤ Sup s := complete_lattice.le_Sup s a theorem Sup_le : (∀b∈s, b ≤ a) → Sup s ≤ a := complete_lattice.Sup_le s a @[ematch] theorem Inf_le : a ∈ s → Inf s ≤ a := complete_lattice.Inf_le s a theorem le_Inf : (∀b∈s, a ≤ b) → a ≤ Inf s := complete_lattice.le_Inf s a lemma is_lub_Sup (s : set α) : is_lub s (Sup s) := ⟨assume x, le_Sup, assume x, Sup_le⟩ lemma is_lub.Sup_eq (h : is_lub s a) : Sup s = a := (is_lub_Sup s).unique h lemma is_glb_Inf (s : set α) : is_glb s (Inf s) := ⟨assume a, Inf_le, assume a, le_Inf⟩ lemma is_glb.Inf_eq (h : is_glb s a) : Inf s = a := (is_glb_Inf s).unique h theorem le_Sup_of_le (hb : b ∈ s) (h : a ≤ b) : a ≤ Sup s := le_trans h (le_Sup hb) theorem Inf_le_of_le (hb : b ∈ s) (h : b ≤ a) : Inf s ≤ a := le_trans (Inf_le hb) h theorem Sup_le_Sup (h : s ⊆ t) : Sup s ≤ Sup t := (is_lub_Sup s).mono (is_lub_Sup t) h theorem Inf_le_Inf (h : s ⊆ t) : Inf t ≤ Inf s := (is_glb_Inf s).mono (is_glb_Inf t) h @[simp] theorem Sup_le_iff : Sup s ≤ a ↔ (∀b ∈ s, b ≤ a) := is_lub_le_iff (is_lub_Sup s) @[simp] theorem le_Inf_iff : a ≤ Inf s ↔ (∀b ∈ s, a ≤ b) := le_is_glb_iff (is_glb_Inf s) theorem Sup_le_Sup_of_forall_exists_le (h : ∀ x ∈ s, ∃ y ∈ t, x ≤ y) : Sup s ≤ Sup t := le_of_forall_le' (by simp only [Sup_le_iff]; introv h₀ h₁; rcases h _ h₁ with ⟨y,hy,hy'⟩; solve_by_elim [le_trans hy']) theorem Inf_le_Inf_of_forall_exists_le (h : ∀ x ∈ s, ∃ y ∈ t, y ≤ x) : Inf t ≤ Inf s := le_of_forall_le (by simp only [le_Inf_iff]; introv h₀ h₁; rcases h _ h₁ with ⟨y,hy,hy'⟩; solve_by_elim [le_trans _ hy']) theorem Inf_le_Sup (hs : s.nonempty) : Inf s ≤ Sup s := is_glb_le_is_lub (is_glb_Inf s) (is_lub_Sup s) hs -- TODO: it is weird that we have to add union_def theorem Sup_union {s t : set α} : Sup (s ∪ t) = Sup s ⊔ Sup t := ((is_lub_Sup s).union (is_lub_Sup t)).Sup_eq theorem Sup_inter_le {s t : set α} : Sup (s ∩ t) ≤ Sup s ⊓ Sup t := by finish /- Sup_le (assume a ⟨a_s, a_t⟩, le_inf (le_Sup a_s) (le_Sup a_t)) -/ theorem Inf_union {s t : set α} : Inf (s ∪ t) = Inf s ⊓ Inf t := ((is_glb_Inf s).union (is_glb_Inf t)).Inf_eq theorem le_Inf_inter {s t : set α} : Inf s ⊔ Inf t ≤ Inf (s ∩ t) := @Sup_inter_le (order_dual α) _ _ _ @[simp] theorem Sup_empty : Sup ∅ = (⊥ : α) := is_lub_empty.Sup_eq @[simp] theorem Inf_empty : Inf ∅ = (⊤ : α) := (@is_glb_empty α _).Inf_eq @[simp] theorem Sup_univ : Sup univ = (⊤ : α) := (@is_lub_univ α _).Sup_eq @[simp] theorem Inf_univ : Inf univ = (⊥ : α) := is_glb_univ.Inf_eq -- TODO(Jeremy): get this automatically @[simp] theorem Sup_insert {a : α} {s : set α} : Sup (insert a s) = a ⊔ Sup s := ((is_lub_Sup s).insert a).Sup_eq @[simp] theorem Inf_insert {a : α} {s : set α} : Inf (insert a s) = a ⊓ Inf s := ((is_glb_Inf s).insert a).Inf_eq theorem Sup_le_Sup_of_subset_instert_bot (h : s ⊆ insert ⊥ t) : Sup s ≤ Sup t := le_trans (Sup_le_Sup h) (le_of_eq (trans Sup_insert bot_sup_eq)) theorem Inf_le_Inf_of_subset_insert_top (h : s ⊆ insert ⊤ t) : Inf t ≤ Inf s := le_trans (le_of_eq (trans top_inf_eq.symm Inf_insert.symm)) (Inf_le_Inf h) -- We will generalize this to conditionally complete lattices in `cSup_singleton`. theorem Sup_singleton {a : α} : Sup {a} = a := is_lub_singleton.Sup_eq -- We will generalize this to conditionally complete lattices in `cInf_singleton`. theorem Inf_singleton {a : α} : Inf {a} = a := is_glb_singleton.Inf_eq theorem Sup_pair {a b : α} : Sup {a, b} = a ⊔ b := (@is_lub_pair α _ a b).Sup_eq theorem Inf_pair {a b : α} : Inf {a, b} = a ⊓ b := (@is_glb_pair α _ a b).Inf_eq @[simp] theorem Inf_eq_top : Inf s = ⊤ ↔ (∀a∈s, a = ⊤) := iff.intro (assume h a ha, top_unique $ h ▸ Inf_le ha) (assume h, top_unique $ le_Inf $ assume a ha, top_le_iff.2 $ h a ha) @[simp] theorem Sup_eq_bot : Sup s = ⊥ ↔ (∀a∈s, a = ⊥) := @Inf_eq_top (order_dual α) _ _ end section complete_linear_order variables [complete_linear_order α] {s t : set α} {a b : α} lemma Inf_lt_iff : Inf s < b ↔ (∃a∈s, a < b) := is_glb_lt_iff (is_glb_Inf s) lemma lt_Sup_iff : b < Sup s ↔ (∃a∈s, b < a) := lt_is_lub_iff (is_lub_Sup s) lemma Sup_eq_top : Sup s = ⊤ ↔ (∀b<⊤, ∃a∈s, b < a) := iff.intro (assume (h : Sup s = ⊤) b hb, by rwa [←h, lt_Sup_iff] at hb) (assume h, top_unique $ le_of_not_gt $ assume h', let ⟨a, ha, h⟩ := h _ h' in lt_irrefl a $ lt_of_le_of_lt (le_Sup ha) h) lemma Inf_eq_bot : Inf s = ⊥ ↔ (∀b>⊥, ∃a∈s, a < b) := @Sup_eq_top (order_dual α) _ _ lemma lt_supr_iff {f : ι → α} : a < supr f ↔ (∃i, a < f i) := lt_Sup_iff.trans exists_range_iff lemma infi_lt_iff {f : ι → α} : infi f < a ↔ (∃i, f i < a) := Inf_lt_iff.trans exists_range_iff end complete_linear_order /- ### supr & infi -/ section variables [complete_lattice α] {s t : ι → α} {a b : α} -- TODO: this declaration gives error when starting smt state --@[ematch] theorem le_supr (s : ι → α) (i : ι) : s i ≤ supr s := le_Sup ⟨i, rfl⟩ @[ematch] theorem le_supr' (s : ι → α) (i : ι) : (: s i ≤ supr s :) := le_Sup ⟨i, rfl⟩ /- TODO: this version would be more powerful, but, alas, the pattern matcher doesn't accept it. @[ematch] theorem le_supr' (s : ι → α) (i : ι) : (: s i :) ≤ (: supr s :) := le_Sup ⟨i, rfl⟩ -/ lemma is_lub_supr : is_lub (range s) (⨆j, s j) := is_lub_Sup _ lemma is_lub.supr_eq (h : is_lub (range s) a) : (⨆j, s j) = a := h.Sup_eq lemma is_glb_infi : is_glb (range s) (⨅j, s j) := is_glb_Inf _ lemma is_glb.infi_eq (h : is_glb (range s) a) : (⨅j, s j) = a := h.Inf_eq theorem le_supr_of_le (i : ι) (h : a ≤ s i) : a ≤ supr s := le_trans h (le_supr _ i) theorem le_bsupr {p : ι → Prop} {f : Π i (h : p i), α} (i : ι) (hi : p i) : f i hi ≤ ⨆ i hi, f i hi := le_supr_of_le i $ le_supr (f i) hi theorem supr_le (h : ∀i, s i ≤ a) : supr s ≤ a := Sup_le $ assume b ⟨i, eq⟩, eq ▸ h i theorem bsupr_le {p : ι → Prop} {f : Π i (h : p i), α} (h : ∀ i hi, f i hi ≤ a) : (⨆ i (hi : p i), f i hi) ≤ a := supr_le $ λ i, supr_le $ h i theorem bsupr_le_supr (p : ι → Prop) (f : ι → α) : (⨆ i (H : p i), f i) ≤ ⨆ i, f i := bsupr_le (λ i hi, le_supr f i) theorem supr_le_supr (h : ∀i, s i ≤ t i) : supr s ≤ supr t := supr_le $ assume i, le_supr_of_le i (h i) theorem supr_le_supr2 {t : ι₂ → α} (h : ∀i, ∃j, s i ≤ t j) : supr s ≤ supr t := supr_le $ assume j, exists.elim (h j) le_supr_of_le theorem bsupr_le_bsupr {p : ι → Prop} {f g : Π i (hi : p i), α} (h : ∀ i hi, f i hi ≤ g i hi) : (⨆ i hi, f i hi) ≤ ⨆ i hi, g i hi := bsupr_le $ λ i hi, le_trans (h i hi) (le_bsupr i hi) theorem supr_le_supr_const (h : ι → ι₂) : (⨆ i:ι, a) ≤ (⨆ j:ι₂, a) := supr_le $ le_supr _ ∘ h @[simp] theorem supr_le_iff : supr s ≤ a ↔ (∀i, s i ≤ a) := (is_lub_le_iff is_lub_supr).trans forall_range_iff theorem Sup_eq_supr {s : set α} : Sup s = (⨆a ∈ s, a) := le_antisymm (Sup_le $ assume b h, le_supr_of_le b $ le_supr _ h) (supr_le $ assume b, supr_le $ assume h, le_Sup h) lemma le_supr_iff : (a ≤ supr s) ↔ (∀ b, (∀ i, s i ≤ b) → a ≤ b) := ⟨λ h b hb, le_trans h (supr_le hb), λ h, h _ $ λ i, le_supr s i⟩ lemma monotone.le_map_supr [complete_lattice β] {f : α → β} (hf : monotone f) : (⨆ i, f (s i)) ≤ f (supr s) := supr_le $ λ i, hf $ le_supr _ _ lemma monotone.le_map_supr2 [complete_lattice β] {f : α → β} (hf : monotone f) {ι' : ι → Sort*} (s : Π i, ι' i → α) : (⨆ i (h : ι' i), f (s i h)) ≤ f (⨆ i (h : ι' i), s i h) := calc (⨆ i h, f (s i h)) ≤ (⨆ i, f (⨆ h, s i h)) : supr_le_supr $ λ i, hf.le_map_supr ... ≤ f (⨆ i (h : ι' i), s i h) : hf.le_map_supr lemma monotone.le_map_Sup [complete_lattice β] {s : set α} {f : α → β} (hf : monotone f) : (⨆a∈s, f a) ≤ f (Sup s) := by rw [Sup_eq_supr]; exact hf.le_map_supr2 _ lemma supr_comp_le {ι' : Sort*} (f : ι' → α) (g : ι → ι') : (⨆ x, f (g x)) ≤ ⨆ y, f y := supr_le_supr2 $ λ x, ⟨_, le_refl _⟩ lemma monotone.supr_comp_eq [preorder β] {f : β → α} (hf : monotone f) {s : ι → β} (hs : ∀ x, ∃ i, x ≤ s i) : (⨆ x, f (s x)) = ⨆ y, f y := le_antisymm (supr_comp_le _ _) (supr_le_supr2 $ λ x, (hs x).imp $ λ i hi, hf hi) lemma function.surjective.supr_comp {α : Type*} [has_Sup α] {f : ι → ι₂} (hf : function.surjective f) (g : ι₂ → α) : (⨆ x, g (f x)) = ⨆ y, g y := by simp only [supr, hf.range_comp] lemma supr_congr {α : Type*} [has_Sup α] {f : ι → α} {g : ι₂ → α} (h : ι → ι₂) (h1 : function.surjective h) (h2 : ∀ x, g (h x) = f x) : (⨆ x, f x) = ⨆ y, g y := by { convert h1.supr_comp g, exact (funext h2).symm } -- TODO: finish doesn't do well here. @[congr] theorem supr_congr_Prop {α : Type*} [has_Sup α] {p q : Prop} {f₁ : p → α} {f₂ : q → α} (pq : p ↔ q) (f : ∀x, f₁ (pq.mpr x) = f₂ x) : supr f₁ = supr f₂ := begin have : f₁ ∘ pq.mpr = f₂ := funext f, rw [← this], refine (function.surjective.supr_comp (λ h, ⟨pq.1 h, _⟩) f₁).symm, refl end theorem infi_le (s : ι → α) (i : ι) : infi s ≤ s i := Inf_le ⟨i, rfl⟩ @[ematch] theorem infi_le' (s : ι → α) (i : ι) : (: infi s ≤ s i :) := Inf_le ⟨i, rfl⟩ theorem infi_le_of_le (i : ι) (h : s i ≤ a) : infi s ≤ a := le_trans (infi_le _ i) h theorem binfi_le {p : ι → Prop} {f : Π i (hi : p i), α} (i : ι) (hi : p i) : (⨅ i hi, f i hi) ≤ f i hi := infi_le_of_le i $ infi_le (f i) hi theorem le_infi (h : ∀i, a ≤ s i) : a ≤ infi s := le_Inf $ assume b ⟨i, eq⟩, eq ▸ h i theorem le_binfi {p : ι → Prop} {f : Π i (h : p i), α} (h : ∀ i hi, a ≤ f i hi) : a ≤ ⨅ i hi, f i hi := le_infi $ λ i, le_infi $ h i theorem infi_le_binfi (p : ι → Prop) (f : ι → α) : (⨅ i, f i) ≤ ⨅ i (H : p i), f i := le_binfi (λ i hi, infi_le f i) theorem infi_le_infi (h : ∀i, s i ≤ t i) : infi s ≤ infi t := le_infi $ assume i, infi_le_of_le i (h i) theorem infi_le_infi2 {t : ι₂ → α} (h : ∀j, ∃i, s i ≤ t j) : infi s ≤ infi t := le_infi $ assume j, exists.elim (h j) infi_le_of_le theorem binfi_le_binfi {p : ι → Prop} {f g : Π i (h : p i), α} (h : ∀ i hi, f i hi ≤ g i hi) : (⨅ i hi, f i hi) ≤ ⨅ i hi, g i hi := le_binfi $ λ i hi, le_trans (binfi_le i hi) (h i hi) theorem infi_le_infi_const (h : ι₂ → ι) : (⨅ i:ι, a) ≤ (⨅ j:ι₂, a) := le_infi $ infi_le _ ∘ h @[simp] theorem le_infi_iff : a ≤ infi s ↔ (∀i, a ≤ s i) := ⟨assume : a ≤ infi s, assume i, le_trans this (infi_le _ _), le_infi⟩ theorem Inf_eq_infi {s : set α} : Inf s = (⨅a ∈ s, a) := @Sup_eq_supr (order_dual α) _ _ lemma monotone.map_infi_le [complete_lattice β] {f : α → β} (hf : monotone f) : f (infi s) ≤ (⨅ i, f (s i)) := le_infi $ λ i, hf $ infi_le _ _ lemma monotone.map_infi2_le [complete_lattice β] {f : α → β} (hf : monotone f) {ι' : ι → Sort*} (s : Π i, ι' i → α) : f (⨅ i (h : ι' i), s i h) ≤ (⨅ i (h : ι' i), f (s i h)) := @monotone.le_map_supr2 (order_dual α) (order_dual β) _ _ _ f hf.order_dual _ _ lemma monotone.map_Inf_le [complete_lattice β] {s : set α} {f : α → β} (hf : monotone f) : f (Inf s) ≤ ⨅ a∈s, f a := by rw [Inf_eq_infi]; exact hf.map_infi2_le _ lemma le_infi_comp {ι' : Sort*} (f : ι' → α) (g : ι → ι') : (⨅ y, f y) ≤ ⨅ x, f (g x) := infi_le_infi2 $ λ x, ⟨_, le_refl _⟩ lemma monotone.infi_comp_eq [preorder β] {f : β → α} (hf : monotone f) {s : ι → β} (hs : ∀ x, ∃ i, s i ≤ x) : (⨅ x, f (s x)) = ⨅ y, f y := le_antisymm (infi_le_infi2 $ λ x, (hs x).imp $ λ i hi, hf hi) (le_infi_comp _ _) lemma function.surjective.infi_comp {α : Type*} [has_Inf α] {f : ι → ι₂} (hf : function.surjective f) (g : ι₂ → α) : (⨅ x, g (f x)) = ⨅ y, g y := @function.surjective.supr_comp _ _ (order_dual α) _ f hf g lemma infi_congr {α : Type*} [has_Inf α] {f : ι → α} {g : ι₂ → α} (h : ι → ι₂) (h1 : function.surjective h) (h2 : ∀ x, g (h x) = f x) : (⨅ x, f x) = ⨅ y, g y := @supr_congr _ _ (order_dual α) _ _ _ h h1 h2 @[congr] theorem infi_congr_Prop {α : Type*} [has_Inf α] {p q : Prop} {f₁ : p → α} {f₂ : q → α} (pq : p ↔ q) (f : ∀x, f₁ (pq.mpr x) = f₂ x) : infi f₁ = infi f₂ := @supr_congr_Prop (order_dual α) _ p q f₁ f₂ pq f -- We will generalize this to conditionally complete lattices in `cinfi_const`. theorem infi_const [nonempty ι] {a : α} : (⨅ b:ι, a) = a := by rw [infi, range_const, Inf_singleton] -- We will generalize this to conditionally complete lattices in `csupr_const`. theorem supr_const [nonempty ι] {a : α} : (⨆ b:ι, a) = a := @infi_const (order_dual α) _ _ _ _ @[simp] lemma infi_top : (⨅i:ι, ⊤ : α) = ⊤ := top_unique $ le_infi $ assume i, le_refl _ @[simp] lemma supr_bot : (⨆i:ι, ⊥ : α) = ⊥ := @infi_top (order_dual α) _ _ @[simp] lemma infi_eq_top : infi s = ⊤ ↔ (∀i, s i = ⊤) := Inf_eq_top.trans forall_range_iff @[simp] lemma supr_eq_bot : supr s = ⊥ ↔ (∀i, s i = ⊥) := Sup_eq_bot.trans forall_range_iff @[simp] lemma infi_pos {p : Prop} {f : p → α} (hp : p) : (⨅ h : p, f h) = f hp := le_antisymm (infi_le _ _) (le_infi $ assume h, le_refl _) @[simp] lemma infi_neg {p : Prop} {f : p → α} (hp : ¬ p) : (⨅ h : p, f h) = ⊤ := le_antisymm le_top $ le_infi $ assume h, (hp h).elim @[simp] lemma supr_pos {p : Prop} {f : p → α} (hp : p) : (⨆ h : p, f h) = f hp := le_antisymm (supr_le $ assume h, le_refl _) (le_supr _ _) @[simp] lemma supr_neg {p : Prop} {f : p → α} (hp : ¬ p) : (⨆ h : p, f h) = ⊥ := le_antisymm (supr_le $ assume h, (hp h).elim) bot_le lemma supr_eq_dif {p : Prop} [decidable p] (a : p → α) : (⨆h:p, a h) = (if h : p then a h else ⊥) := by by_cases p; simp [h] lemma supr_eq_if {p : Prop} [decidable p] (a : α) : (⨆h:p, a) = (if p then a else ⊥) := supr_eq_dif (λ _, a) lemma infi_eq_dif {p : Prop} [decidable p] (a : p → α) : (⨅h:p, a h) = (if h : p then a h else ⊤) := @supr_eq_dif (order_dual α) _ _ _ _ lemma infi_eq_if {p : Prop} [decidable p] (a : α) : (⨅h:p, a) = (if p then a else ⊤) := infi_eq_dif (λ _, a) -- TODO: should this be @[simp]? theorem infi_comm {f : ι → ι₂ → α} : (⨅i, ⨅j, f i j) = (⨅j, ⨅i, f i j) := le_antisymm (le_infi $ assume i, le_infi $ assume j, infi_le_of_le j $ infi_le _ i) (le_infi $ assume j, le_infi $ assume i, infi_le_of_le i $ infi_le _ j) /- TODO: this is strange. In the proof below, we get exactly the desired among the equalities, but close does not get it. begin apply @le_antisymm, simp, intros, begin [smt] ematch, ematch, ematch, trace_state, have := le_refl (f i_1 i), trace_state, close end end -/ -- TODO: should this be @[simp]? theorem supr_comm {f : ι → ι₂ → α} : (⨆i, ⨆j, f i j) = (⨆j, ⨆i, f i j) := @infi_comm (order_dual α) _ _ _ _ @[simp] theorem infi_infi_eq_left {b : β} {f : Πx:β, x = b → α} : (⨅x, ⨅h:x = b, f x h) = f b rfl := le_antisymm (infi_le_of_le b $ infi_le _ rfl) (le_infi $ assume b', le_infi $ assume eq, match b', eq with ._, rfl := le_refl _ end) @[simp] theorem infi_infi_eq_right {b : β} {f : Πx:β, b = x → α} : (⨅x, ⨅h:b = x, f x h) = f b rfl := le_antisymm (infi_le_of_le b $ infi_le _ rfl) (le_infi $ assume b', le_infi $ assume eq, match b', eq with ._, rfl := le_refl _ end) @[simp] theorem supr_supr_eq_left {b : β} {f : Πx:β, x = b → α} : (⨆x, ⨆h : x = b, f x h) = f b rfl := @infi_infi_eq_left (order_dual α) _ _ _ _ @[simp] theorem supr_supr_eq_right {b : β} {f : Πx:β, b = x → α} : (⨆x, ⨆h : b = x, f x h) = f b rfl := @infi_infi_eq_right (order_dual α) _ _ _ _ attribute [ematch] le_refl theorem infi_subtype {p : ι → Prop} {f : subtype p → α} : (⨅ x, f x) = (⨅ i (h:p i), f ⟨i, h⟩) := le_antisymm (le_infi $ assume i, le_infi $ assume : p i, infi_le _ _) (le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _) lemma infi_subtype' {p : ι → Prop} {f : ∀ i, p i → α} : (⨅ i (h : p i), f i h) = (⨅ x : subtype p, f x x.property) := (@infi_subtype _ _ _ p (λ x, f x.val x.property)).symm lemma infi_subtype'' {ι} (s : set ι) (f : ι → α) : (⨅ i : s, f i) = ⨅ (t : ι) (H : t ∈ s), f t := infi_subtype theorem infi_inf_eq {f g : ι → α} : (⨅ x, f x ⊓ g x) = (⨅ x, f x) ⊓ (⨅ x, g x) := le_antisymm (le_inf (le_infi $ assume i, infi_le_of_le i inf_le_left) (le_infi $ assume i, infi_le_of_le i inf_le_right)) (le_infi $ assume i, le_inf (inf_le_left_of_le $ infi_le _ _) (inf_le_right_of_le $ infi_le _ _)) /- TODO: here is another example where more flexible pattern matching might help. begin apply @le_antisymm, safe, pose h := f a ⊓ g a, begin [smt] ematch, ematch end end -/ lemma infi_inf [h : nonempty ι] {f : ι → α} {a : α} : (⨅x, f x) ⊓ a = (⨅ x, f x ⊓ a) := by rw [infi_inf_eq, infi_const] lemma inf_infi [nonempty ι] {f : ι → α} {a : α} : a ⊓ (⨅x, f x) = (⨅ x, a ⊓ f x) := by rw [inf_comm, infi_inf]; simp [inf_comm] lemma binfi_inf {p : ι → Prop} {f : Π i (hi : p i), α} {a : α} (h : ∃ i, p i) : (⨅i (h : p i), f i h) ⊓ a = (⨅ i (h : p i), f i h ⊓ a) := by haveI : nonempty {i // p i} := (let ⟨i, hi⟩ := h in ⟨⟨i, hi⟩⟩); rw [infi_subtype', infi_subtype', infi_inf] theorem supr_sup_eq {f g : β → α} : (⨆ x, f x ⊔ g x) = (⨆ x, f x) ⊔ (⨆ x, g x) := @infi_inf_eq (order_dual α) β _ _ _ /- supr and infi under Prop -/ @[simp] theorem infi_false {s : false → α} : infi s = ⊤ := le_antisymm le_top (le_infi $ assume i, false.elim i) @[simp] theorem supr_false {s : false → α} : supr s = ⊥ := le_antisymm (supr_le $ assume i, false.elim i) bot_le @[simp] theorem infi_true {s : true → α} : infi s = s trivial := le_antisymm (infi_le _ _) (le_infi $ assume ⟨⟩, le_refl _) @[simp] theorem supr_true {s : true → α} : supr s = s trivial := le_antisymm (supr_le $ assume ⟨⟩, le_refl _) (le_supr _ _) @[simp] theorem infi_exists {p : ι → Prop} {f : Exists p → α} : (⨅ x, f x) = (⨅ i, ⨅ h:p i, f ⟨i, h⟩) := le_antisymm (le_infi $ assume i, le_infi $ assume : p i, infi_le _ _) (le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _) @[simp] theorem supr_exists {p : ι → Prop} {f : Exists p → α} : (⨆ x, f x) = (⨆ i, ⨆ h:p i, f ⟨i, h⟩) := @infi_exists (order_dual α) _ _ _ _ theorem infi_and {p q : Prop} {s : p ∧ q → α} : infi s = (⨅ h₁ h₂, s ⟨h₁, h₂⟩) := le_antisymm (le_infi $ assume i, le_infi $ assume j, infi_le _ _) (le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _) /-- The symmetric case of `infi_and`, useful for rewriting into a infimum over a conjunction -/ lemma infi_and' {p q : Prop} {s : p → q → α} : (⨅ (h₁ : p) (h₂ : q), s h₁ h₂) = ⨅ (h : p ∧ q), s h.1 h.2 := by { symmetry, exact infi_and } theorem supr_and {p q : Prop} {s : p ∧ q → α} : supr s = (⨆ h₁ h₂, s ⟨h₁, h₂⟩) := @infi_and (order_dual α) _ _ _ _ /-- The symmetric case of `supr_and`, useful for rewriting into a supremum over a conjunction -/ lemma supr_and' {p q : Prop} {s : p → q → α} : (⨆ (h₁ : p) (h₂ : q), s h₁ h₂) = ⨆ (h : p ∧ q), s h.1 h.2 := by { symmetry, exact supr_and } theorem infi_or {p q : Prop} {s : p ∨ q → α} : infi s = (⨅ h : p, s (or.inl h)) ⊓ (⨅ h : q, s (or.inr h)) := le_antisymm (le_inf (infi_le_infi2 $ assume j, ⟨_, le_refl _⟩) (infi_le_infi2 $ assume j, ⟨_, le_refl _⟩)) (le_infi $ assume i, match i with | or.inl i := inf_le_left_of_le $ infi_le _ _ | or.inr j := inf_le_right_of_le $ infi_le _ _ end) theorem supr_or {p q : Prop} {s : p ∨ q → α} : (⨆ x, s x) = (⨆ i, s (or.inl i)) ⊔ (⨆ j, s (or.inr j)) := @infi_or (order_dual α) _ _ _ _ lemma Sup_range {α : Type*} [has_Sup α] {f : ι → α} : Sup (range f) = supr f := rfl lemma Inf_range {α : Type*} [has_Inf α] {f : ι → α} : Inf (range f) = infi f := rfl lemma supr_range {g : β → α} {f : ι → β} : (⨆b∈range f, g b) = (⨆i, g (f i)) := le_antisymm (supr_le $ assume b, supr_le $ assume ⟨i, (h : f i = b)⟩, h ▸ le_supr _ i) (supr_le $ assume i, le_supr_of_le (f i) $ le_supr (λp, g (f i)) (mem_range_self _)) lemma infi_range {g : β → α} {f : ι → β} : (⨅b∈range f, g b) = (⨅i, g (f i)) := @supr_range (order_dual α) _ _ _ _ _ theorem Inf_image {s : set β} {f : β → α} : Inf (f '' s) = (⨅ a ∈ s, f a) := by rw [← infi_subtype'', infi, range_comp, subtype.range_coe] theorem Sup_image {s : set β} {f : β → α} : Sup (f '' s) = (⨆ a ∈ s, f a) := @Inf_image (order_dual α) _ _ _ _ /- ### supr and infi under set constructions -/ theorem infi_emptyset {f : β → α} : (⨅ x ∈ (∅ : set β), f x) = ⊤ := by simp theorem supr_emptyset {f : β → α} : (⨆ x ∈ (∅ : set β), f x) = ⊥ := by simp theorem infi_univ {f : β → α} : (⨅ x ∈ (univ : set β), f x) = (⨅ x, f x) := by simp theorem supr_univ {f : β → α} : (⨆ x ∈ (univ : set β), f x) = (⨆ x, f x) := by simp theorem infi_union {f : β → α} {s t : set β} : (⨅ x ∈ s ∪ t, f x) = (⨅x∈s, f x) ⊓ (⨅x∈t, f x) := by simp only [← infi_inf_eq, infi_or] lemma infi_split (f : β → α) (p : β → Prop) : (⨅ i, f i) = (⨅ i (h : p i), f i) ⊓ (⨅ i (h : ¬ p i), f i) := by simpa [classical.em] using @infi_union _ _ _ f {i | p i} {i | ¬ p i} lemma infi_split_single (f : β → α) (i₀ : β) : (⨅ i, f i) = f i₀ ⊓ (⨅ i (h : i ≠ i₀), f i) := by convert infi_split _ _; simp theorem infi_le_infi_of_subset {f : β → α} {s t : set β} (h : s ⊆ t) : (⨅ x ∈ t, f x) ≤ (⨅ x ∈ s, f x) := by rw [(union_eq_self_of_subset_left h).symm, infi_union]; exact inf_le_left theorem supr_union {f : β → α} {s t : set β} : (⨆ x ∈ s ∪ t, f x) = (⨆x∈s, f x) ⊔ (⨆x∈t, f x) := @infi_union (order_dual α) _ _ _ _ _ lemma supr_split (f : β → α) (p : β → Prop) : (⨆ i, f i) = (⨆ i (h : p i), f i) ⊔ (⨆ i (h : ¬ p i), f i) := @infi_split (order_dual α) _ _ _ _ lemma supr_split_single (f : β → α) (i₀ : β) : (⨆ i, f i) = f i₀ ⊔ (⨆ i (h : i ≠ i₀), f i) := @infi_split_single (order_dual α) _ _ _ _ theorem supr_le_supr_of_subset {f : β → α} {s t : set β} (h : s ⊆ t) : (⨆ x ∈ s, f x) ≤ (⨆ x ∈ t, f x) := @infi_le_infi_of_subset (order_dual α) _ _ _ _ _ h theorem infi_insert {f : β → α} {s : set β} {b : β} : (⨅ x ∈ insert b s, f x) = f b ⊓ (⨅x∈s, f x) := eq.trans infi_union $ congr_arg (λx:α, x ⊓ (⨅x∈s, f x)) infi_infi_eq_left theorem supr_insert {f : β → α} {s : set β} {b : β} : (⨆ x ∈ insert b s, f x) = f b ⊔ (⨆x∈s, f x) := eq.trans supr_union $ congr_arg (λx:α, x ⊔ (⨆x∈s, f x)) supr_supr_eq_left theorem infi_singleton {f : β → α} {b : β} : (⨅ x ∈ (singleton b : set β), f x) = f b := by simp theorem infi_pair {f : β → α} {a b : β} : (⨅ x ∈ ({a, b} : set β), f x) = f a ⊓ f b := by rw [infi_insert, infi_singleton] theorem supr_singleton {f : β → α} {b : β} : (⨆ x ∈ (singleton b : set β), f x) = f b := @infi_singleton (order_dual α) _ _ _ _ theorem supr_pair {f : β → α} {a b : β} : (⨆ x ∈ ({a, b} : set β), f x) = f a ⊔ f b := by rw [supr_insert, supr_singleton] lemma infi_image {γ} {f : β → γ} {g : γ → α} {t : set β} : (⨅ c ∈ f '' t, g c) = (⨅ b ∈ t, g (f b)) := by rw [← Inf_image, ← Inf_image, ← image_comp] lemma supr_image {γ} {f : β → γ} {g : γ → α} {t : set β} : (⨆ c ∈ f '' t, g c) = (⨆ b ∈ t, g (f b)) := @infi_image (order_dual α) _ _ _ _ _ _ /-! ### `supr` and `infi` under `Type` -/ theorem infi_of_empty' (h : ι → false) {s : ι → α} : infi s = ⊤ := top_unique (le_infi $ assume i, (h i).elim) theorem supr_of_empty' (h : ι → false) {s : ι → α} : supr s = ⊥ := bot_unique (supr_le $ assume i, (h i).elim) theorem infi_of_empty (h : ¬nonempty ι) {s : ι → α} : infi s = ⊤ := infi_of_empty' (λ i, h ⟨i⟩) theorem supr_of_empty (h : ¬nonempty ι) {s : ι → α} : supr s = ⊥ := supr_of_empty' (λ i, h ⟨i⟩) @[simp] theorem infi_empty {s : empty → α} : infi s = ⊤ := infi_of_empty nonempty_empty @[simp] theorem supr_empty {s : empty → α} : supr s = ⊥ := supr_of_empty nonempty_empty @[simp] theorem infi_unit {f : unit → α} : (⨅ x, f x) = f () := le_antisymm (infi_le _ _) (le_infi $ assume ⟨⟩, le_refl _) @[simp] theorem supr_unit {f : unit → α} : (⨆ x, f x) = f () := le_antisymm (supr_le $ assume ⟨⟩, le_refl _) (le_supr _ _) lemma supr_bool_eq {f : bool → α} : (⨆b:bool, f b) = f tt ⊔ f ff := le_antisymm (supr_le $ assume b, match b with tt := le_sup_left | ff := le_sup_right end) (sup_le (le_supr _ _) (le_supr _ _)) lemma infi_bool_eq {f : bool → α} : (⨅b:bool, f b) = f tt ⊓ f ff := @supr_bool_eq (order_dual α) _ _ lemma is_glb_binfi {s : set β} {f : β → α} : is_glb (f '' s) (⨅ x ∈ s, f x) := by simpa only [range_comp, subtype.range_coe, infi_subtype'] using @is_glb_infi α s _ (f ∘ coe) theorem supr_subtype {p : ι → Prop} {f : subtype p → α} : (⨆ x, f x) = (⨆ i (h:p i), f ⟨i, h⟩) := @infi_subtype (order_dual α) _ _ _ _ lemma supr_subtype' {p : ι → Prop} {f : ∀ i, p i → α} : (⨆ i (h : p i), f i h) = (⨆ x : subtype p, f x x.property) := (@supr_subtype _ _ _ p (λ x, f x.val x.property)).symm lemma Sup_eq_supr' {s : set α} : Sup s = ⨆ x : s, (x : α) := by rw [Sup_eq_supr, supr_subtype']; refl lemma is_lub_bsupr {s : set β} {f : β → α} : is_lub (f '' s) (⨆ x ∈ s, f x) := by simpa only [range_comp, subtype.range_coe, supr_subtype'] using @is_lub_supr α s _ (f ∘ coe) theorem infi_sigma {p : β → Type*} {f : sigma p → α} : (⨅ x, f x) = (⨅ i (h:p i), f ⟨i, h⟩) := le_antisymm (le_infi $ assume i, le_infi $ assume : p i, infi_le _ _) (le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _) theorem supr_sigma {p : β → Type*} {f : sigma p → α} : (⨆ x, f x) = (⨆ i (h:p i), f ⟨i, h⟩) := @infi_sigma (order_dual α) _ _ _ _ theorem infi_prod {γ : Type*} {f : β × γ → α} : (⨅ x, f x) = (⨅ i j, f (i, j)) := le_antisymm (le_infi $ assume i, le_infi $ assume j, infi_le _ _) (le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _) theorem supr_prod {γ : Type*} {f : β × γ → α} : (⨆ x, f x) = (⨆ i j, f (i, j)) := @infi_prod (order_dual α) _ _ _ _ theorem infi_sum {γ : Type*} {f : β ⊕ γ → α} : (⨅ x, f x) = (⨅ i, f (sum.inl i)) ⊓ (⨅ j, f (sum.inr j)) := le_antisymm (le_inf (infi_le_infi2 $ assume i, ⟨_, le_refl _⟩) (infi_le_infi2 $ assume j, ⟨_, le_refl _⟩)) (le_infi $ assume s, match s with | sum.inl i := inf_le_left_of_le $ infi_le _ _ | sum.inr j := inf_le_right_of_le $ infi_le _ _ end) theorem supr_sum {γ : Type*} {f : β ⊕ γ → α} : (⨆ x, f x) = (⨆ i, f (sum.inl i)) ⊔ (⨆ j, f (sum.inr j)) := @infi_sum (order_dual α) _ _ _ _ /-! ### `supr` and `infi` under `ℕ` -/ lemma supr_ge_eq_supr_nat_add {u : ℕ → α} (n : ℕ) : (⨆ i ≥ n, u i) = ⨆ i, u (i + n) := begin apply le_antisymm; simp only [supr_le_iff], { exact λ i hi, le_Sup ⟨i - n, by { dsimp only, rw nat.sub_add_cancel hi }⟩ }, { exact λ i, le_Sup ⟨i + n, supr_pos (nat.le_add_left _ _)⟩ } end lemma infi_ge_eq_infi_nat_add {u : ℕ → α} (n : ℕ) : (⨅ i ≥ n, u i) = ⨅ i, u (i + n) := @supr_ge_eq_supr_nat_add (order_dual α) _ _ _ end section complete_linear_order variables [complete_linear_order α] lemma supr_eq_top (f : ι → α) : supr f = ⊤ ↔ (∀b<⊤, ∃i, b < f i) := by simp only [← Sup_range, Sup_eq_top, set.exists_range_iff] lemma infi_eq_bot (f : ι → α) : infi f = ⊥ ↔ (∀b>⊥, ∃i, f i < b) := by simp only [← Inf_range, Inf_eq_bot, set.exists_range_iff] end complete_linear_order /-! ### Instances -/ instance complete_lattice_Prop : complete_lattice Prop := { Sup := λs, ∃a∈s, a, le_Sup := assume s a h p, ⟨a, h, p⟩, Sup_le := assume s a h ⟨b, h', p⟩, h b h' p, Inf := λs, ∀a:Prop, a∈s → a, Inf_le := assume s a h p, p a h, le_Inf := assume s a h p b hb, h b hb p, .. bounded_distrib_lattice_Prop } lemma Inf_Prop_eq {s : set Prop} : Inf s = (∀p ∈ s, p) := rfl lemma Sup_Prop_eq {s : set Prop} : Sup s = (∃p ∈ s, p) := rfl lemma infi_Prop_eq {ι : Sort*} {p : ι → Prop} : (⨅i, p i) = (∀i, p i) := le_antisymm (assume h i, h _ ⟨i, rfl⟩ ) (assume h p ⟨i, eq⟩, eq ▸ h i) lemma supr_Prop_eq {ι : Sort*} {p : ι → Prop} : (⨆i, p i) = (∃i, p i) := le_antisymm (λ ⟨q, ⟨i, (eq : p i = q)⟩, hq⟩, ⟨i, eq.symm ▸ hq⟩) (λ ⟨i, hi⟩, ⟨p i, ⟨i, rfl⟩, hi⟩) instance pi.has_Sup {α : Type*} {β : α → Type*} [Π i, has_Sup (β i)] : has_Sup (Π i, β i) := ⟨λ s i, ⨆ f : s, (f : Π i, β i) i⟩ instance pi.has_Inf {α : Type*} {β : α → Type*} [Π i, has_Inf (β i)] : has_Inf (Π i, β i) := ⟨λ s i, ⨅ f : s, (f : Π i, β i) i⟩ instance pi.complete_lattice {α : Type*} {β : α → Type*} [∀ i, complete_lattice (β i)] : complete_lattice (Π i, β i) := { Sup := Sup, Inf := Inf, le_Sup := λ s f hf i, le_supr (λ f : s, (f : Π i, β i) i) ⟨f, hf⟩, Inf_le := λ s f hf i, infi_le (λ f : s, (f : Π i, β i) i) ⟨f, hf⟩, Sup_le := λ s f hf i, supr_le $ λ g, hf g g.2 i, le_Inf := λ s f hf i, le_infi $ λ g, hf g g.2 i, .. pi.bounded_lattice } lemma Inf_apply {α : Type*} {β : α → Type*} [Π i, has_Inf (β i)] {s : set (Πa, β a)} {a : α} : (Inf s) a = (⨅ f : s, (f : Πa, β a) a) := rfl lemma infi_apply {α : Type*} {β : α → Type*} {ι : Sort*} [Π i, has_Inf (β i)] {f : ι → Πa, β a} {a : α} : (⨅i, f i) a = (⨅i, f i a) := by rw [infi, Inf_apply, infi, infi, ← image_eq_range (λ f : Π i, β i, f a) (range f), ← range_comp] lemma Sup_apply {α : Type*} {β : α → Type*} [Π i, has_Sup (β i)] {s : set (Πa, β a)} {a : α} : (Sup s) a = (⨆f:s, (f : Πa, β a) a) := rfl lemma supr_apply {α : Type*} {β : α → Type*} {ι : Sort*} [Π i, has_Sup (β i)] {f : ι → Πa, β a} {a : α} : (⨆i, f i) a = (⨆i, f i a) := @infi_apply α (λ i, order_dual (β i)) _ _ f a section complete_lattice variables [preorder α] [complete_lattice β] theorem monotone_Sup_of_monotone {s : set (α → β)} (m_s : ∀f∈s, monotone f) : monotone (Sup s) := assume x y h, supr_le $ λ f, le_supr_of_le f $ m_s f f.2 h theorem monotone_Inf_of_monotone {s : set (α → β)} (m_s : ∀f∈s, monotone f) : monotone (Inf s) := assume x y h, le_infi $ λ f, infi_le_of_le f $ m_s f f.2 h end complete_lattice namespace prod variables (α β) instance [has_Inf α] [has_Inf β] : has_Inf (α × β) := ⟨λs, (Inf (prod.fst '' s), Inf (prod.snd '' s))⟩ instance [has_Sup α] [has_Sup β] : has_Sup (α × β) := ⟨λs, (Sup (prod.fst '' s), Sup (prod.snd '' s))⟩ instance [complete_lattice α] [complete_lattice β] : complete_lattice (α × β) := { le_Sup := assume s p hab, ⟨le_Sup $ mem_image_of_mem _ hab, le_Sup $ mem_image_of_mem _ hab⟩, Sup_le := assume s p h, ⟨ Sup_le $ ball_image_of_ball $ assume p hp, (h p hp).1, Sup_le $ ball_image_of_ball $ assume p hp, (h p hp).2⟩, Inf_le := assume s p hab, ⟨Inf_le $ mem_image_of_mem _ hab, Inf_le $ mem_image_of_mem _ hab⟩, le_Inf := assume s p h, ⟨ le_Inf $ ball_image_of_ball $ assume p hp, (h p hp).1, le_Inf $ ball_image_of_ball $ assume p hp, (h p hp).2⟩, .. prod.bounded_lattice α β, .. prod.has_Sup α β, .. prod.has_Inf α β } end prod
734d60a5d5a7bf5e6dfdfc9003ff615b4d395897
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/rw_inst_mvars.lean
eff45a55f5324da0ef0633c0059499c24ac46e13
[ "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
171
lean
example (p : Nat → Prop) (h : ∀ n, p (n+1) = p n) : (p m ↔ p 0) := by induction m case succ ih => rw [h, ih] exact Iff.rfl case zero => exact Iff.rfl
ec86ab4bcd9564205fedc40fbf75393b26069350
4a092885406df4e441e9bb9065d9405dacb94cd8
/src/power_bounded.lean
9fa794b8b723cd82da1eb775c65cafbe0b6d5c35
[ "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
10,507
lean
import topology.basic import topology.algebra.ring import algebra.group_power import ring_theory.subring import tactic.ring import for_mathlib.submonoid import for_mathlib.topological_rings import for_mathlib.nonarchimedean.basic local attribute [instance] set.pointwise_mul_semiring /- The theory of topologically nilpotent, bounded, and power-bounded elements and subsets of topological rings. -/ variables {R : Type*} [comm_ring R] [topological_space R] [topological_ring R] /-- Wedhorn Definition 5.25 page 36 -/ definition is_topologically_nilpotent (r : R) : Prop := ∀ U ∈ (nhds (0 : R)), ∃ N : ℕ, ∀ n : ℕ, n > N → r^n ∈ U -- def monoid.set_pow {R : Type*} [monoid R] (T : set R) : ℕ → set R -- | 0 := {1} -- | (n + 1) := ((*) <$> monoid.set_pow n <*> T) def is_topologically_nilpotent_subset (T : set R) : Prop := ∀ U ∈ (nhds (0 : R)), ∃ n : ℕ, T ^ n ⊆ U namespace topologically_nilpotent -- don't know what to prove end topologically_nilpotent /-- Wedhorn Definition 5.27 page 36 -/ definition is_bounded (B : set R) : Prop := ∀ U ∈ nhds (0 : R), ∃ V ∈ nhds (0 : R), ∀ v ∈ V, ∀ b ∈ B, v*b ∈ U lemma is_bounded_iff (B : set R) : is_bounded B ↔ ∀ U ∈ nhds (0 : R), ∃ V ∈ nhds (0 : R), V * B ⊆ U := forall_congr $ λ U, imp_congr iff.rfl $ exists_congr $ λ V, exists_congr $ λ hV, begin split, { rintros H _ ⟨v, hv, b, hb, rfl⟩, exact H v hv b hb }, { intros H v hv b hb, exact H ⟨v, hv, b, hb, rfl⟩ } end section open submodule topological_add_group set_option class.instance_max_depth 80 lemma is_bounded_add_subgroup_iff (hR : nonarchimedean R) (B : set R) [is_add_subgroup B] : is_bounded B ↔ ∀ U ∈ nhds (0:R), ∃ V : open_add_subgroup R, (↑((V : set R) • span ℤ B) : set R) ⊆ U := begin split, { rintros H U hU, cases hR U hU with W hW, rw is_bounded_iff at H, rcases H _ W.mem_nhds_zero with ⟨V', hV', H'⟩, cases hR V' hV' with V hV, use V, refine set.subset.trans _ hW, change ↑(span _ _ * span _ _) ⊆ _, rw [span_mul_span, ← add_group_closure_eq_spanℤ, add_group.closure_subset_iff], exact set.subset.trans (set.mul_le_mul hV (set.subset.refl B)) H' }, { intros H, rw is_bounded_iff, intros U hU, cases H U hU with V hV, use [V, V.mem_nhds_zero], refine set.subset.trans _ hV, rintros _ ⟨v, hv, b, hb, rfl⟩, exact mul_mem_mul (subset_span hv) (subset_span hb) } end end namespace bounded open topological_add_group lemma subset {B C : set R} (h : B ⊆ C) (hC : is_bounded C) : is_bounded B := λ U hU, exists.elim (hC U hU) $ λ V ⟨hV, hC⟩, ⟨V, hV, λ v hv b hb, hC v hv b $ h hb⟩ -- TODO : this is PR 809 to mathlib, remove when it hits lemma is_add_submonoid.mem_nhds_zero {G : Type*} [topological_space G] [add_monoid G] [topological_add_monoid G] (H : set G) [is_add_submonoid H] (hH : is_open H) : H ∈ nhds (0 : G) := begin rw mem_nhds_sets_iff, use H, use (by refl), split, use hH, exact is_add_submonoid.zero_mem _, end lemma add_group.closure (hR : nonarchimedean R) (T : set R) (hT : is_bounded T) : is_bounded (add_group.closure T) := begin intros U hU, -- find subgroup U' in U rcases hR U hU with ⟨U', hU'⟩, -- U' still a nhd -- Use boundedness hypo for T with U' to get V rcases hT (U' : set R) U'.mem_nhds_zero with ⟨V, hV, hB⟩, -- find subgroup V' in V rcases hR V hV with ⟨V', hV'⟩, -- V' works for our proof use [V', V'.mem_nhds_zero], intros v hv b hb, -- Suffices to prove we're in U' apply hU', -- Prove the result by induction apply add_group.in_closure.rec_on hb, { intros t ht, exact hB v (hV' hv) t ht }, { rw mul_zero, exact U'.zero_mem }, { intros a Ha Hv, rwa [←neg_mul_comm, neg_mul_eq_neg_mul_symm, is_add_subgroup.neg_mem_iff] }, { intros a b ha hb Ha Hb, rw [mul_add], exact U'.add_mem Ha Hb } end end bounded definition is_power_bounded (r : R) : Prop := is_bounded (powers r) definition is_power_bounded_subset (T : set R) : Prop := is_bounded (monoid.closure T) namespace power_bounded open topological_add_group lemma zero : is_power_bounded (0 : R) := λ U hU, ⟨U, begin split, {exact hU}, intros v hv b H, induction H with n H, induction n ; { simp [H.symm, pow_succ, mem_of_nhds hU], try {assumption} } end⟩ lemma one : is_power_bounded (1 : R) := λ U hU, ⟨U, begin split, {exact hU}, intros v hv b H, cases H with n H, simpa [H.symm] end⟩ lemma singleton (r : R) : is_power_bounded r ↔ is_power_bounded_subset ({r} : set R) := begin unfold is_power_bounded, unfold is_power_bounded_subset, rw monoid.closure_singleton, end lemma subset {B C : set R} (h : B ⊆ C) (hC : is_power_bounded_subset C) : is_power_bounded_subset B := λ U hU, exists.elim (hC U hU) $ λ V ⟨hV, hC⟩, ⟨V, hV, λ v hv b hb, hC v hv b $ monoid.closure_mono h hb⟩ lemma union {S T : set R} (hS : is_power_bounded_subset S) (hT : is_power_bounded_subset T) : is_power_bounded_subset (S ∪ T) := begin intros U hU, rcases hT U hU with ⟨V, hV, hVU⟩, rcases hS V hV with ⟨W, hW, hWV⟩, use W, use hW, -- this is wrong intros v hv b hb, rw monoid.mem_closure_union_iff at hb, rcases hb with ⟨y, hy, z, hz, hyz⟩, rw [←hyz, ←mul_assoc], apply hVU _ _ _ hz, exact hWV _ hv _ hy, end lemma mul (a b : R) (ha : is_power_bounded a) (hb : is_power_bounded b) : is_power_bounded (a * b) := λ U U_nhd, begin rcases hb U U_nhd with ⟨Vb, Vb_nhd, hVb⟩, rcases ha Vb Vb_nhd with ⟨Va, Va_nhd, hVa⟩, clear ha hb, use Va, split, {exact Va_nhd}, { intros v hv x H, cases H with n hx, rw [← hx, mul_pow, ← mul_assoc], apply hVb (v * a^n) _ _ _, apply hVa v hv _ _, repeat { dsimp [powers], existsi n, refl } } end lemma add_group.closure (hR : nonarchimedean R) {T : set R} (hT : is_power_bounded_subset T) : is_power_bounded_subset (add_group.closure T) := begin refine bounded.subset _ (bounded.add_group.closure hR _ hT), intros a ha, apply monoid.in_closure.rec_on ha, { apply add_group.closure_mono, exact monoid.subset_closure }, { apply add_group.mem_closure, exact monoid.in_closure.one _ }, { intros a b ha hb Ha Hb, haveI : is_subring (add_group.closure (monoid.closure T)) := ring.is_subring, exact is_submonoid.mul_mem Ha Hb, } end lemma monoid.closure (hR : nonarchimedean R) {T : set R} (hT : is_power_bounded_subset T) : is_power_bounded_subset (monoid.closure T) := begin refine bounded.subset _ hT, apply monoid.closure_subset, refl, end lemma ring.closure (hR : nonarchimedean R) (T : set R) (hT : is_power_bounded_subset T) : is_power_bounded_subset (ring.closure T) := add_group.closure hR $ monoid.closure hR hT lemma ring.closure' (hR : nonarchimedean R) (T : set R) (hT : is_power_bounded_subset T) : is_bounded (_root_.ring.closure T) := bounded.subset monoid.subset_closure (ring.closure hR _ hT) lemma add (hR : nonarchimedean R) (a b : R) (ha : is_power_bounded a) (hb : is_power_bounded b) : is_power_bounded (a + b) := begin rw singleton at ha hb ⊢, have hab := add_group.closure hR (union ha hb), refine subset _ hab, rw set.singleton_subset_iff, apply is_add_submonoid.add_mem; apply add_group.subset_closure; simp end end power_bounded variable (R) -- definition makes sense for all R, but it's only a subring for certain -- rings e.g. non-archimedean rings. definition power_bounded_subring := {r : R | is_power_bounded r} variable {R} namespace power_bounded_subring open topological_add_group instance : has_coe (power_bounded_subring R) R := ⟨subtype.val⟩ lemma zero_mem : (0 : R) ∈ power_bounded_subring R := power_bounded.zero lemma one_mem : (1 : R) ∈ power_bounded_subring R := power_bounded.one lemma add_mem (h : nonarchimedean R) ⦃a b : R⦄ (ha : a ∈ power_bounded_subring R) (hb : b ∈ power_bounded_subring R) : a + b ∈ power_bounded_subring R := power_bounded.add h a b ha hb lemma mul_mem : ∀ ⦃a b : R⦄, a ∈ power_bounded_subring R → b ∈ power_bounded_subring R → a * b ∈ power_bounded_subring R := power_bounded.mul lemma neg_mem : ∀ ⦃a : R⦄, a ∈ power_bounded_subring R → -a ∈ power_bounded_subring R := λ a ha U hU, begin let Usymm := U ∩ {u | -u ∈ U}, let hUsymm : Usymm ∈ (nhds (0 : R)) := begin apply filter.inter_mem_sets hU, apply continuous.tendsto (topological_add_group.continuous_neg R) 0, simpa end, rcases ha Usymm hUsymm with ⟨V, ⟨V_nhd, hV⟩⟩, clear hUsymm, existsi V, split, {exact V_nhd}, intros v hv b H, cases H with n hb, rw ← hb, rw show v * (-a)^n = ((-1)^n * v) * a^n, begin rw [neg_eq_neg_one_mul, mul_pow], ring, end, have H := hV v hv (a^n) _, suffices : (-1)^n * v * a^n ∈ Usymm, { exact this.1 }, { simp, cases (@neg_one_pow_eq_or R _ n) with h h; { dsimp [Usymm] at H, simp [h, H.1, H.2] } }, { dsimp [powers], existsi n, refl } end instance : is_submonoid (power_bounded_subring R) := { one_mem := one_mem, mul_mem := mul_mem } instance (hR : nonarchimedean R) : is_add_subgroup (power_bounded_subring R) := { zero_mem := zero_mem, add_mem := add_mem hR, neg_mem := neg_mem } instance (hR : nonarchimedean R) : is_subring (power_bounded_subring R) := { ..power_bounded_subring.is_submonoid, ..power_bounded_subring.is_add_subgroup hR } variable (R) definition is_uniform : Prop := is_bounded (power_bounded_subring R) end power_bounded_subring section open set lemma is_adic.is_bounded (h : is_adic R) : is_bounded (univ : set R) := begin intros U hU, rw mem_nhds_sets_iff at hU, rcases hU with ⟨V, hV₁, ⟨hV₂, h0⟩⟩, tactic.unfreeze_local_instances, rcases h with ⟨J, hJ⟩, rw is_ideal_adic_iff at hJ, have H : (∃ (n : ℕ), (J^n).carrier ⊆ V) := begin apply hJ.2, exact mem_nhds_sets hV₂ h0, end, rcases H with ⟨n, hn⟩, use (J^n).carrier, -- the key step split, { exact mem_nhds_sets (hJ.1 n) (J^n).zero_mem }, { rintros a ha b hb, apply hV₁, exact hn ((J^n).mul_mem_right ha), } end lemma is_bounded_subset (S₁ S₂ : set R) (h : S₁ ⊆ S₂) (H : is_bounded S₂) : is_bounded S₁ := begin intros U hU, rcases H U hU with ⟨V, hV₁, hV₂⟩, use [V, hV₁], intros v hv b hb, exact hV₂ _ hv _ (h hb), end end
b8aea3faffd7a4cb07829b016aa71ff056480f75
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebra/lie/abelian.lean
0b9c476b61cee76778af4db715962ffd6cff8def
[ "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
11,644
lean
/- Copyright (c) 2021 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import algebra.lie.of_associative import algebra.lie.ideal_operations /-! # Trivial Lie modules and Abelian Lie algebras The action of a Lie algebra `L` on a module `M` is trivial if `⁅x, m⁆ = 0` for all `x ∈ L` and `m ∈ M`. In the special case that `M = L` with the adjoint action, triviality corresponds to the concept of an Abelian Lie algebra. In this file we define these concepts and provide some related definitions and results. ## Main definitions * `lie_module.is_trivial` * `is_lie_abelian` * `commutative_ring_iff_abelian_lie_ring` * `lie_module.ker` * `lie_module.max_triv_submodule` * `lie_algebra.center` ## Tags lie algebra, abelian, commutative, center -/ universes u v w w₁ w₂ /-- A Lie (ring) module is trivial iff all brackets vanish. -/ class lie_module.is_trivial (L : Type v) (M : Type w) [has_bracket L M] [has_zero M] : Prop := (trivial : ∀ (x : L) (m : M), ⁅x, m⁆ = 0) @[simp] lemma trivial_lie_zero (L : Type v) (M : Type w) [has_bracket L M] [has_zero M] [lie_module.is_trivial L M] (x : L) (m : M) : ⁅x, m⁆ = 0 := lie_module.is_trivial.trivial x m /-- A Lie algebra is Abelian iff it is trivial as a Lie module over itself. -/ abbreviation is_lie_abelian (L : Type v) [has_bracket L L] [has_zero L] : Prop := lie_module.is_trivial L L instance lie_ideal.is_lie_abelian_of_trivial (R : Type u) (L : Type v) [comm_ring R] [lie_ring L] [lie_algebra R L] (I : lie_ideal R L) [h : lie_module.is_trivial L I] : is_lie_abelian I := { trivial := λ x y, by apply h.trivial } lemma function.injective.is_lie_abelian {R : Type u} {L₁ : Type v} {L₂ : Type w} [comm_ring R] [lie_ring L₁] [lie_ring L₂] [lie_algebra R L₁] [lie_algebra R L₂] {f : L₁ →ₗ⁅R⁆ L₂} (h₁ : function.injective f) (h₂ : is_lie_abelian L₂) : is_lie_abelian L₁ := { trivial := λ x y, h₁ $ calc f ⁅x,y⁆ = ⁅f x, f y⁆ : lie_hom.map_lie f x y ... = 0 : trivial_lie_zero _ _ _ _ ... = f 0 : f.map_zero.symm } lemma function.surjective.is_lie_abelian {R : Type u} {L₁ : Type v} {L₂ : Type w} [comm_ring R] [lie_ring L₁] [lie_ring L₂] [lie_algebra R L₁] [lie_algebra R L₂] {f : L₁ →ₗ⁅R⁆ L₂} (h₁ : function.surjective f) (h₂ : is_lie_abelian L₁) : is_lie_abelian L₂ := { trivial := λ x y, begin obtain ⟨u, rfl⟩ := h₁ x, obtain ⟨v, rfl⟩ := h₁ y, rw [← lie_hom.map_lie, trivial_lie_zero, lie_hom.map_zero], end } lemma lie_abelian_iff_equiv_lie_abelian {R : Type u} {L₁ : Type v} {L₂ : Type w} [comm_ring R] [lie_ring L₁] [lie_ring L₂] [lie_algebra R L₁] [lie_algebra R L₂] (e : L₁ ≃ₗ⁅R⁆ L₂) : is_lie_abelian L₁ ↔ is_lie_abelian L₂ := ⟨e.symm.injective.is_lie_abelian, e.injective.is_lie_abelian⟩ lemma commutative_ring_iff_abelian_lie_ring {A : Type v} [ring A] : is_commutative A (*) ↔ is_lie_abelian A := have h₁ : is_commutative A (*) ↔ ∀ (a b : A), a * b = b * a := ⟨λ h, h.1, λ h, ⟨h⟩⟩, have h₂ : is_lie_abelian A ↔ ∀ (a b : A), ⁅a, b⁆ = 0 := ⟨λ h, h.1, λ h, ⟨h⟩⟩, by simp only [h₁, h₂, lie_ring.of_associative_ring_bracket, sub_eq_zero] lemma lie_algebra.is_lie_abelian_bot (R : Type u) (L : Type v) [comm_ring R] [lie_ring L] [lie_algebra R L] : is_lie_abelian (⊥ : lie_ideal R L) := ⟨λ ⟨x, hx⟩ _, by convert zero_lie _⟩ section center variables (R : Type u) (L : Type v) (M : Type w) (N : Type w₁) variables [comm_ring R] [lie_ring L] [lie_algebra R L] variables [add_comm_group M] [module R M] [lie_ring_module L M] [lie_module R L M] variables [add_comm_group N] [module R N] [lie_ring_module L N] [lie_module R L N] namespace lie_module /-- The kernel of the action of a Lie algebra `L` on a Lie module `M` as a Lie ideal in `L`. -/ protected def ker : lie_ideal R L := (to_endomorphism R L M).ker @[simp] protected lemma mem_ker (x : L) : x ∈ lie_module.ker R L M ↔ ∀ (m : M), ⁅x, m⁆ = 0 := by simp only [lie_module.ker, lie_hom.mem_ker, linear_map.ext_iff, linear_map.zero_apply, to_endomorphism_apply_apply] /-- The largest submodule of a Lie module `M` on which the Lie algebra `L` acts trivially. -/ def max_triv_submodule : lie_submodule R L M := { carrier := { m | ∀ (x : L), ⁅x, m⁆ = 0 }, zero_mem' := λ x, lie_zero x, add_mem' := λ x y hx hy z, by rw [lie_add, hx, hy, add_zero], smul_mem' := λ c x hx y, by rw [lie_smul, hx, smul_zero], lie_mem := λ x m hm y, by rw [hm, lie_zero], } @[simp] lemma mem_max_triv_submodule (m : M) : m ∈ max_triv_submodule R L M ↔ ∀ (x : L), ⁅x, m⁆ = 0 := iff.rfl instance : is_trivial L (max_triv_submodule R L M) := { trivial := λ x m, subtype.ext (m.property x), } @[simp] lemma ideal_oper_max_triv_submodule_eq_bot (I : lie_ideal R L) : ⁅I, max_triv_submodule R L M⁆ = ⊥ := begin rw [← lie_submodule.coe_to_submodule_eq_iff, lie_submodule.lie_ideal_oper_eq_linear_span, lie_submodule.bot_coe_submodule, submodule.span_eq_bot], rintros m ⟨⟨x, hx⟩, ⟨⟨m, hm⟩, rfl⟩⟩, exact hm x, end lemma le_max_triv_iff_bracket_eq_bot {N : lie_submodule R L M} : N ≤ max_triv_submodule R L M ↔ ⁅(⊤ : lie_ideal R L), N⁆ = ⊥ := begin refine ⟨λ h, _, λ h m hm, _⟩, { rw [← le_bot_iff, ← ideal_oper_max_triv_submodule_eq_bot R L M ⊤], exact lie_submodule.mono_lie_right _ _ ⊤ h, }, { rw mem_max_triv_submodule, rw lie_submodule.lie_eq_bot_iff at h, exact λ x, h x (lie_submodule.mem_top x) m hm, }, end lemma trivial_iff_le_maximal_trivial (N : lie_submodule R L M) : is_trivial L N ↔ N ≤ max_triv_submodule R L M := ⟨ λ h m hm x, is_trivial.dcases_on h (λ h, subtype.ext_iff.mp (h x ⟨m, hm⟩)), λ h, { trivial := λ x m, subtype.ext (h m.2 x) }⟩ lemma is_trivial_iff_max_triv_eq_top : is_trivial L M ↔ max_triv_submodule R L M = ⊤ := begin split, { rintros ⟨h⟩, ext, simp only [mem_max_triv_submodule, h, forall_const, true_iff, eq_self_iff_true], }, { intros h, constructor, intros x m, revert x, rw [← mem_max_triv_submodule R L M, h], exact lie_submodule.mem_top m, }, end variables {R L M N} /-- `max_triv_submodule` is functorial. -/ def max_triv_hom (f : M →ₗ⁅R,L⁆ N) : max_triv_submodule R L M →ₗ⁅R,L⁆ max_triv_submodule R L N := { to_fun := λ m, ⟨f m, λ x, (lie_module_hom.map_lie _ _ _).symm.trans $ (congr_arg f (m.property x)).trans (lie_module_hom.map_zero _)⟩, map_add' := λ m n, by simpa, map_smul' := λ t m, by simpa, map_lie' := λ x m, by simp, } @[norm_cast, simp] lemma coe_max_triv_hom_apply (f : M →ₗ⁅R,L⁆ N) (m : max_triv_submodule R L M) : (max_triv_hom f m : N) = f m := rfl /-- The maximal trivial submodules of Lie-equivalent Lie modules are Lie-equivalent. -/ def max_triv_equiv (e : M ≃ₗ⁅R,L⁆ N) : max_triv_submodule R L M ≃ₗ⁅R,L⁆ max_triv_submodule R L N := { to_fun := max_triv_hom (e : M →ₗ⁅R,L⁆ N), inv_fun := max_triv_hom (e.symm : N →ₗ⁅R,L⁆ M), left_inv := λ m, by { ext, simp, }, right_inv := λ n, by { ext, simp, }, .. max_triv_hom (e : M →ₗ⁅R,L⁆ N), } @[norm_cast, simp] lemma coe_max_triv_equiv_apply (e : M ≃ₗ⁅R,L⁆ N) (m : max_triv_submodule R L M) : (max_triv_equiv e m : N) = e ↑m := rfl @[simp] lemma max_triv_equiv_of_refl_eq_refl : max_triv_equiv (lie_module_equiv.refl : M ≃ₗ⁅R,L⁆ M) = lie_module_equiv.refl := by { ext, simp only [coe_max_triv_equiv_apply, lie_module_equiv.refl_apply], } @[simp] lemma max_triv_equiv_of_equiv_symm_eq_symm (e : M ≃ₗ⁅R,L⁆ N) : (max_triv_equiv e).symm = max_triv_equiv e.symm := rfl /-- A linear map between two Lie modules is a morphism of Lie modules iff the Lie algebra action on it is trivial. -/ def max_triv_linear_map_equiv_lie_module_hom : (max_triv_submodule R L (M →ₗ[R] N)) ≃ₗ[R] (M →ₗ⁅R,L⁆ N) := { to_fun := λ f, { to_linear_map := f.val, map_lie' := λ x m, by { have hf : ⁅x, f.val⁆ m = 0, { rw [f.property x, linear_map.zero_apply], }, rw [lie_hom.lie_apply, sub_eq_zero, ← linear_map.to_fun_eq_coe] at hf, exact hf.symm, }, }, map_add' := λ f g, by { ext, simp, }, map_smul' := λ F G, by { ext, simp, }, inv_fun := λ F, ⟨F, λ x, by { ext, simp, }⟩, left_inv := λ f, by simp, right_inv := λ F, by simp, } @[simp] lemma coe_max_triv_linear_map_equiv_lie_module_hom (f : max_triv_submodule R L (M →ₗ[R] N)) : ((max_triv_linear_map_equiv_lie_module_hom f) : M → N) = f := by { ext, refl, } @[simp] lemma coe_max_triv_linear_map_equiv_lie_module_hom_symm (f : M →ₗ⁅R,L⁆ N) : ((max_triv_linear_map_equiv_lie_module_hom.symm f) : M → N) = f := rfl @[simp] lemma coe_linear_map_max_triv_linear_map_equiv_lie_module_hom (f : max_triv_submodule R L (M →ₗ[R] N)) : ((max_triv_linear_map_equiv_lie_module_hom f) : M →ₗ[R] N) = (f : M →ₗ[R] N) := by { ext, refl, } @[simp] lemma coe_linear_map_max_triv_linear_map_equiv_lie_module_hom_symm (f : M →ₗ⁅R,L⁆ N) : ((max_triv_linear_map_equiv_lie_module_hom.symm f) : M →ₗ[R] N) = (f : M →ₗ[R] N) := rfl end lie_module namespace lie_algebra /-- The center of a Lie algebra is the set of elements that commute with everything. It can be viewed as the maximal trivial submodule of the Lie algebra as a Lie module over itself via the adjoint representation. -/ abbreviation center : lie_ideal R L := lie_module.max_triv_submodule R L L instance : is_lie_abelian (center R L) := infer_instance @[simp] lemma ad_ker_eq_self_module_ker : (ad R L).ker = lie_module.ker R L L := rfl @[simp] lemma self_module_ker_eq_center : lie_module.ker R L L = center R L := begin ext y, simp only [lie_module.mem_max_triv_submodule, lie_module.mem_ker, ← lie_skew _ y, neg_eq_zero], end lemma abelian_of_le_center (I : lie_ideal R L) (h : I ≤ center R L) : is_lie_abelian I := begin haveI : lie_module.is_trivial L I := (lie_module.trivial_iff_le_maximal_trivial R L L I).mpr h, exact lie_ideal.is_lie_abelian_of_trivial R L I, end lemma is_lie_abelian_iff_center_eq_top : is_lie_abelian L ↔ center R L = ⊤ := lie_module.is_trivial_iff_max_triv_eq_top R L L end lie_algebra end center section ideal_operations open lie_submodule lie_subalgebra variables {R : Type u} {L : Type v} {M : Type w} variables [comm_ring R] [lie_ring L] [lie_algebra R L] [add_comm_group M] [module R M] variables [lie_ring_module L M] [lie_module R L M] variables (N N' : lie_submodule R L M) (I J : lie_ideal R L) @[simp] lemma lie_submodule.trivial_lie_oper_zero [lie_module.is_trivial L M] : ⁅I, N⁆ = ⊥ := begin suffices : ⁅I, N⁆ ≤ ⊥, from le_bot_iff.mp this, rw [lie_ideal_oper_eq_span, lie_submodule.lie_span_le], rintros m ⟨x, n, h⟩, rw trivial_lie_zero at h, simp [← h], end lemma lie_submodule.lie_abelian_iff_lie_self_eq_bot : is_lie_abelian I ↔ ⁅I, I⁆ = ⊥ := begin simp only [_root_.eq_bot_iff, lie_ideal_oper_eq_span, lie_submodule.lie_span_le, lie_submodule.bot_coe, set.subset_singleton_iff, set.mem_set_of_eq, exists_imp_distrib], refine ⟨λ h z x y hz, hz.symm.trans (((I : lie_subalgebra R L).coe_bracket x y).symm.trans ((coe_zero_iff_zero _ _).mpr (by apply h.trivial))), λ h, ⟨λ x y, ((I : lie_subalgebra R L).coe_zero_iff_zero _).mp (h _ x y rfl)⟩⟩, end end ideal_operations
a862a9f6a75b7d8dd17fb883b7c8adb8d3f43064
e00ea76a720126cf9f6d732ad6216b5b824d20a7
/src/data/num/lemmas.lean
8426746516c85ea26ebf8e74a2fb493219148da0
[ "Apache-2.0" ]
permissive
vaibhavkarve/mathlib
a574aaf68c0a431a47fa82ce0637f0f769826bfe
17f8340912468f49bdc30acdb9a9fa02eeb0473a
refs/heads/master
1,621,263,802,637
1,585,399,588,000
1,585,399,588,000
250,833,447
0
0
Apache-2.0
1,585,410,341,000
1,585,410,341,000
null
UTF-8
Lean
false
false
49,700
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro Properties of the binary representation of integers. -/ import data.num.basic data.num.bitwise algebra.ordered_ring tactic.interactive data.int.basic data.nat.gcd namespace pos_num variables {α : Type*} @[simp] theorem cast_one [has_zero α] [has_one α] [has_add α] : ((1 : pos_num) : α) = 1 := rfl @[simp] theorem cast_one' [has_zero α] [has_one α] [has_add α] : (pos_num.one : α) = 1 := rfl @[simp] theorem cast_bit0 [has_zero α] [has_one α] [has_add α] (n : pos_num) : (n.bit0 : α) = _root_.bit0 n := rfl @[simp] theorem cast_bit1 [has_zero α] [has_one α] [has_add α] (n : pos_num) : (n.bit1 : α) = _root_.bit1 n := rfl @[simp] theorem cast_to_nat [add_monoid α] [has_one α] : ∀ n : pos_num, ((n : ℕ) : α) = n | 1 := nat.cast_one | (bit0 p) := (nat.cast_bit0 _).trans $ congr_arg _root_.bit0 p.cast_to_nat | (bit1 p) := (nat.cast_bit1 _).trans $ congr_arg _root_.bit1 p.cast_to_nat @[simp] theorem to_nat_to_int (n : pos_num) : ((n : ℕ) : ℤ) = n := by rw [← int.nat_cast_eq_coe_nat, cast_to_nat] @[simp] theorem cast_to_int [add_group α] [has_one α] (n : pos_num) : ((n : ℤ) : α) = n := by rw [← to_nat_to_int, int.cast_coe_nat, cast_to_nat] theorem succ_to_nat : ∀ n, (succ n : ℕ) = n + 1 | 1 := rfl | (bit0 p) := rfl | (bit1 p) := (congr_arg _root_.bit0 (succ_to_nat p)).trans $ show ↑p + 1 + ↑p + 1 = ↑p + ↑p + 1 + 1, by simp [add_left_comm] theorem one_add (n : pos_num) : 1 + n = succ n := by cases n; refl theorem add_one (n : pos_num) : n + 1 = succ n := by cases n; refl theorem add_to_nat : ∀ m n, ((m + n : pos_num) : ℕ) = m + n | 1 b := by rw [one_add b, succ_to_nat, add_comm]; refl | a 1 := by rw [add_one a, succ_to_nat]; refl | (bit0 a) (bit0 b) := (congr_arg _root_.bit0 (add_to_nat a b)).trans $ show ((a + b) + (a + b) : ℕ) = (a + a) + (b + b), by simp [add_left_comm] | (bit0 a) (bit1 b) := (congr_arg _root_.bit1 (add_to_nat a b)).trans $ show ((a + b) + (a + b) + 1 : ℕ) = (a + a) + (b + b + 1), by simp [add_left_comm] | (bit1 a) (bit0 b) := (congr_arg _root_.bit1 (add_to_nat a b)).trans $ show ((a + b) + (a + b) + 1 : ℕ) = (a + a + 1) + (b + b), by simp [add_comm, add_left_comm] | (bit1 a) (bit1 b) := show (succ (a + b) + succ (a + b) : ℕ) = (a + a + 1) + (b + b + 1), by rw [succ_to_nat, add_to_nat]; simp [add_left_comm] theorem add_succ : ∀ (m n : pos_num), m + succ n = succ (m + n) | 1 b := by simp [one_add] | (bit0 a) 1 := congr_arg bit0 (add_one a) | (bit1 a) 1 := congr_arg bit1 (add_one a) | (bit0 a) (bit0 b) := rfl | (bit0 a) (bit1 b) := congr_arg bit0 (add_succ a b) | (bit1 a) (bit0 b) := rfl | (bit1 a) (bit1 b) := congr_arg bit1 (add_succ a b) theorem bit0_of_bit0 : Π n, _root_.bit0 n = bit0 n | 1 := rfl | (bit0 p) := congr_arg bit0 (bit0_of_bit0 p) | (bit1 p) := show bit0 (succ (_root_.bit0 p)) = _, by rw bit0_of_bit0; refl theorem bit1_of_bit1 (n : pos_num) : _root_.bit1 n = bit1 n := show _root_.bit0 n + 1 = bit1 n, by rw [add_one, bit0_of_bit0]; refl theorem mul_to_nat (m) : ∀ n, ((m * n : pos_num) : ℕ) = m * n | 1 := (mul_one _).symm | (bit0 p) := show (↑(m * p) + ↑(m * p) : ℕ) = ↑m * (p + p), by rw [mul_to_nat, left_distrib] | (bit1 p) := (add_to_nat (bit0 (m * p)) m).trans $ show (↑(m * p) + ↑(m * p) + ↑m : ℕ) = ↑m * (p + p) + m, by rw [mul_to_nat, left_distrib] theorem to_nat_pos : ∀ n : pos_num, 0 < (n : ℕ) | 1 := zero_lt_one | (bit0 p) := let h := to_nat_pos p in add_pos h h | (bit1 p) := nat.succ_pos _ theorem cmp_to_nat_lemma {m n : pos_num} : (m:ℕ) < n → (bit1 m : ℕ) < bit0 n := show (m:ℕ) < n → (m + m + 1 + 1 : ℕ) ≤ n + n, by intro h; rw [nat.add_right_comm m m 1, add_assoc]; exact add_le_add h h theorem cmp_swap (m) : ∀n, (cmp m n).swap = cmp n m := by induction m with m IH m IH; intro n; cases n with n n; try {unfold cmp}; try {refl}; rw ←IH; cases cmp m n; refl theorem cmp_to_nat : ∀ (m n), (ordering.cases_on (cmp m n) ((m:ℕ) < n) (m = n) ((m:ℕ) > n) : Prop) | 1 1 := rfl | (bit0 a) 1 := let h : (1:ℕ) ≤ a := to_nat_pos a in add_le_add h h | (bit1 a) 1 := nat.succ_lt_succ $ to_nat_pos $ bit0 a | 1 (bit0 b) := let h : (1:ℕ) ≤ b := to_nat_pos b in add_le_add h h | 1 (bit1 b) := nat.succ_lt_succ $ to_nat_pos $ bit0 b | (bit0 a) (bit0 b) := begin have := cmp_to_nat a b, revert this, cases cmp a b; dsimp; intro, { exact add_lt_add this this }, { rw this }, { exact add_lt_add this this } end | (bit0 a) (bit1 b) := begin dsimp [cmp], have := cmp_to_nat a b, revert this, cases cmp a b; dsimp; intro, { exact nat.le_succ_of_le (add_lt_add this this) }, { rw this, apply nat.lt_succ_self }, { exact cmp_to_nat_lemma this } end | (bit1 a) (bit0 b) := begin dsimp [cmp], have := cmp_to_nat a b, revert this, cases cmp a b; dsimp; intro, { exact cmp_to_nat_lemma this }, { rw this, apply nat.lt_succ_self }, { exact nat.le_succ_of_le (add_lt_add this this) }, end | (bit1 a) (bit1 b) := begin have := cmp_to_nat a b, revert this, cases cmp a b; dsimp; intro, { exact nat.succ_lt_succ (add_lt_add this this) }, { rw this }, { exact nat.succ_lt_succ (add_lt_add this this) } end theorem lt_to_nat {m n : pos_num} : (m:ℕ) < n ↔ m < n := show (m:ℕ) < n ↔ cmp m n = ordering.lt, from match cmp m n, cmp_to_nat m n with | ordering.lt, h := by simp at h; simp [h] | ordering.eq, h := by simp at h; simp [h, lt_irrefl]; exact dec_trivial | ordering.gt, h := by simp [not_lt_of_gt h]; exact dec_trivial end theorem le_to_nat {m n : pos_num} : (m:ℕ) ≤ n ↔ m ≤ n := by rw ← not_lt; exact not_congr lt_to_nat end pos_num namespace num variables {α : Type*} open pos_num theorem add_zero (n : num) : n + 0 = n := by cases n; refl theorem zero_add (n : num) : 0 + n = n := by cases n; refl theorem add_one : ∀ n : num, n + 1 = succ n | 0 := rfl | (pos p) := by cases p; refl theorem add_succ : ∀ (m n : num), m + succ n = succ (m + n) | 0 n := by simp [zero_add] | (pos p) 0 := show pos (p + 1) = succ (pos p + 0), by rw [pos_num.add_one, add_zero]; refl | (pos p) (pos q) := congr_arg pos (pos_num.add_succ _ _) @[simp] theorem add_of_nat (m) : ∀ n, ((m + n : ℕ) : num) = m + n | 0 := (add_zero _).symm | (n+1) := show ((m + n : ℕ) + 1 : num) = m + (↑ n + 1), by rw [add_one, add_one, add_succ, add_of_nat] theorem bit0_of_bit0 : ∀ n : num, bit0 n = n.bit0 | 0 := rfl | (pos p) := congr_arg pos p.bit0_of_bit0 theorem bit1_of_bit1 : ∀ n : num, bit1 n = n.bit1 | 0 := rfl | (pos p) := congr_arg pos p.bit1_of_bit1 @[simp] theorem cast_zero [has_zero α] [has_one α] [has_add α] : ((0 : num) : α) = 0 := rfl @[simp] theorem cast_zero' [has_zero α] [has_one α] [has_add α] : (num.zero : α) = 0 := rfl @[simp] theorem cast_one [has_zero α] [has_one α] [has_add α] : ((1 : num) : α) = 1 := rfl @[simp] theorem cast_pos [has_zero α] [has_one α] [has_add α] (n : pos_num) : (num.pos n : α) = n := rfl theorem succ'_to_nat : ∀ n, (succ' n : ℕ) = n + 1 | 0 := (_root_.zero_add _).symm | (pos p) := pos_num.succ_to_nat _ theorem succ_to_nat (n) : (succ n : ℕ) = n + 1 := succ'_to_nat n @[simp] theorem cast_to_nat [add_monoid α] [has_one α] : ∀ n : num, ((n : ℕ) : α) = n | 0 := nat.cast_zero | (pos p) := p.cast_to_nat @[simp] theorem to_nat_to_int (n : num) : ((n : ℕ) : ℤ) = n := by rw [← int.nat_cast_eq_coe_nat, cast_to_nat] @[simp] theorem cast_to_int [add_group α] [has_one α] (n : num) : ((n : ℤ) : α) = n := by rw [← to_nat_to_int, int.cast_coe_nat, cast_to_nat] theorem to_of_nat : Π (n : ℕ), ((n : num) : ℕ) = n | 0 := rfl | (n+1) := by rw [nat.cast_add_one, add_one, succ_to_nat, to_of_nat] @[simp, move_cast] theorem of_nat_cast [add_monoid α] [has_one α] (n : ℕ) : ((n : num) : α) = n := by rw [← cast_to_nat, to_of_nat] theorem of_nat_inj {m n : ℕ} : (m : num) = n ↔ m = n := ⟨λ h, function.injective_of_left_inverse to_of_nat h, congr_arg _⟩ theorem add_to_nat : ∀ m n, ((m + n : num) : ℕ) = m + n | 0 0 := rfl | 0 (pos q) := (_root_.zero_add _).symm | (pos p) 0 := rfl | (pos p) (pos q) := pos_num.add_to_nat _ _ theorem mul_to_nat : ∀ m n, ((m * n : num) : ℕ) = m * n | 0 0 := rfl | 0 (pos q) := (zero_mul _).symm | (pos p) 0 := rfl | (pos p) (pos q) := pos_num.mul_to_nat _ _ theorem cmp_to_nat : ∀ (m n), (ordering.cases_on (cmp m n) ((m:ℕ) < n) (m = n) ((m:ℕ) > n) : Prop) | 0 0 := rfl | 0 (pos b) := to_nat_pos _ | (pos a) 0 := to_nat_pos _ | (pos a) (pos b) := by { have := pos_num.cmp_to_nat a b; revert this; dsimp [cmp]; cases pos_num.cmp a b, exacts [id, congr_arg pos, id] } theorem lt_to_nat {m n : num} : (m:ℕ) < n ↔ m < n := show (m:ℕ) < n ↔ cmp m n = ordering.lt, from match cmp m n, cmp_to_nat m n with | ordering.lt, h := by simp at h; simp [h] | ordering.eq, h := by simp at h; simp [h, lt_irrefl]; exact dec_trivial | ordering.gt, h := by simp [not_lt_of_gt h]; exact dec_trivial end theorem le_to_nat {m n : num} : (m:ℕ) ≤ n ↔ m ≤ n := by rw ← not_lt; exact not_congr lt_to_nat end num namespace pos_num @[simp] theorem of_to_nat : Π (n : pos_num), ((n : ℕ) : num) = num.pos n | 1 := rfl | (bit0 p) := show ↑(p + p : ℕ) = num.pos p.bit0, by rw [num.add_of_nat, of_to_nat]; exact congr_arg num.pos p.bit0_of_bit0 | (bit1 p) := show ((p + p : ℕ) : num) + 1 = num.pos p.bit1, by rw [num.add_of_nat, of_to_nat]; exact congr_arg num.pos p.bit1_of_bit1 end pos_num namespace num @[simp] theorem of_to_nat : Π (n : num), ((n : ℕ) : num) = n | 0 := rfl | (pos p) := p.of_to_nat theorem to_nat_inj {m n : num} : (m : ℕ) = n ↔ m = n := ⟨λ h, function.injective_of_left_inverse of_to_nat h, congr_arg _⟩ meta def transfer_rw : tactic unit := `[repeat {rw ← to_nat_inj <|> rw ← lt_to_nat <|> rw ← le_to_nat}, repeat {rw add_to_nat <|> rw mul_to_nat <|> rw cast_one <|> rw cast_zero}] meta def transfer : tactic unit := `[intros, transfer_rw, try {simp}] instance : comm_semiring num := by refine { add := (+), zero := 0, zero_add := zero_add, add_zero := add_zero, mul := (*), one := 1, .. }; try {transfer}; simp [mul_add, mul_left_comm, mul_comm, add_comm] instance : ordered_cancel_comm_monoid num := { add_left_cancel := by {intros a b c, transfer_rw, apply add_left_cancel}, add_right_cancel := by {intros a b c, transfer_rw, apply add_right_cancel}, lt := (<), lt_iff_le_not_le := by {intros a b, transfer_rw, apply lt_iff_le_not_le}, le := (≤), le_refl := by transfer, le_trans := by {intros a b c, transfer_rw, apply le_trans}, le_antisymm := by {intros a b, transfer_rw, apply le_antisymm}, add_le_add_left := by {intros a b h c, revert h, transfer_rw, exact λ h, add_le_add_left h c}, le_of_add_le_add_left := by {intros a b c, transfer_rw, apply le_of_add_le_add_left}, ..num.comm_semiring } instance : decidable_linear_ordered_semiring num := { le_total := by {intros a b, transfer_rw, apply le_total}, zero_lt_one := dec_trivial, mul_le_mul_of_nonneg_left := by {intros a b c, transfer_rw, apply mul_le_mul_of_nonneg_left}, mul_le_mul_of_nonneg_right := by {intros a b c, transfer_rw, apply mul_le_mul_of_nonneg_right}, mul_lt_mul_of_pos_left := by {intros a b c, transfer_rw, apply mul_lt_mul_of_pos_left}, mul_lt_mul_of_pos_right := by {intros a b c, transfer_rw, apply mul_lt_mul_of_pos_right}, decidable_lt := num.decidable_lt, decidable_le := num.decidable_le, decidable_eq := num.decidable_eq, ..num.comm_semiring, ..num.ordered_cancel_comm_monoid } theorem dvd_to_nat (m n : num) : (m : ℕ) ∣ n ↔ m ∣ n := ⟨λ ⟨k, e⟩, ⟨k, by rw [← of_to_nat n, e]; simp⟩, λ ⟨k, e⟩, ⟨k, by simp [e, mul_to_nat]⟩⟩ end num namespace pos_num variables {α : Type*} open num theorem to_nat_inj {m n : pos_num} : (m : ℕ) = n ↔ m = n := ⟨λ h, num.pos.inj $ by rw [← pos_num.of_to_nat, ← pos_num.of_to_nat, h], congr_arg _⟩ theorem pred'_to_nat : ∀ n, (pred' n : ℕ) = nat.pred n | 1 := rfl | (bit0 n) := have nat.succ ↑(pred' n) = ↑n, by rw [pred'_to_nat n, nat.succ_pred_eq_of_pos (to_nat_pos n)], match pred' n, this : ∀ k : num, nat.succ ↑k = ↑n → ↑(num.cases_on k 1 bit1 : pos_num) = nat.pred (_root_.bit0 n) with | 0, (h : ((1:num):ℕ) = n) := by rw ← to_nat_inj.1 h; refl | num.pos p, (h : nat.succ ↑p = n) := by rw ← h; exact (nat.succ_add p p).symm end | (bit1 n) := rfl @[simp] theorem pred'_succ' (n) : pred' (succ' n) = n := num.to_nat_inj.1 $ by rw [pred'_to_nat, succ'_to_nat, nat.add_one, nat.pred_succ] @[simp] theorem succ'_pred' (n) : succ' (pred' n) = n := to_nat_inj.1 $ by rw [succ'_to_nat, pred'_to_nat, nat.add_one, nat.succ_pred_eq_of_pos (to_nat_pos _)] theorem size_to_nat : ∀ n, (size n : ℕ) = nat.size n | 1 := nat.size_one.symm | (bit0 n) := by rw [size, succ_to_nat, size_to_nat, cast_bit0, nat.size_bit0 $ ne_of_gt $ to_nat_pos n] | (bit1 n) := by rw [size, succ_to_nat, size_to_nat, cast_bit1, nat.size_bit1] theorem size_eq_nat_size : ∀ n, (size n : ℕ) = nat_size n | 1 := rfl | (bit0 n) := by rw [size, succ_to_nat, nat_size, size_eq_nat_size] | (bit1 n) := by rw [size, succ_to_nat, nat_size, size_eq_nat_size] theorem nat_size_to_nat (n) : nat_size n = nat.size n := by rw [← size_eq_nat_size, size_to_nat] theorem nat_size_pos (n) : 0 < nat_size n := by cases n; apply nat.succ_pos meta def transfer_rw : tactic unit := `[repeat {rw ← to_nat_inj <|> rw ← lt_to_nat <|> rw ← le_to_nat}, repeat {rw add_to_nat <|> rw mul_to_nat <|> rw cast_one <|> rw cast_zero}] meta def transfer : tactic unit := `[intros, transfer_rw, try {simp [add_comm, add_left_comm, mul_comm, mul_left_comm]}] instance : add_comm_semigroup pos_num := by refine {add := (+), ..}; transfer instance : comm_monoid pos_num := by refine {mul := (*), one := 1, ..}; transfer instance : distrib pos_num := by refine {add := (+), mul := (*), ..}; {transfer, simp [mul_add, mul_comm]} instance : decidable_linear_order pos_num := { lt := (<), lt_iff_le_not_le := by {intros a b, transfer_rw, apply lt_iff_le_not_le}, le := (≤), le_refl := by transfer, le_trans := by {intros a b c, transfer_rw, apply le_trans}, le_antisymm := by {intros a b, transfer_rw, apply le_antisymm}, le_total := by {intros a b, transfer_rw, apply le_total}, decidable_lt := by apply_instance, decidable_le := by apply_instance, decidable_eq := by apply_instance } @[simp] theorem cast_to_num (n : pos_num) : ↑n = num.pos n := by rw [← cast_to_nat, ← of_to_nat n] @[simp, elim_cast] theorem bit_to_nat (b n) : (bit b n : ℕ) = nat.bit b n := by cases b; refl @[simp, move_cast] theorem cast_add [add_monoid α] [has_one α] (m n) : ((m + n : pos_num) : α) = m + n := by rw [← cast_to_nat, add_to_nat, nat.cast_add, cast_to_nat, cast_to_nat] @[simp, move_cast] theorem cast_succ [add_monoid α] [has_one α] (n : pos_num) : (succ n : α) = n + 1 := by rw [← add_one, cast_add, cast_one] @[simp, elim_cast] theorem cast_inj [add_monoid α] [has_one α] [char_zero α] {m n : pos_num} : (m:α) = n ↔ m = n := by rw [← cast_to_nat m, ← cast_to_nat n, nat.cast_inj, to_nat_inj] @[simp] theorem one_le_cast [linear_ordered_semiring α] (n : pos_num) : (1 : α) ≤ n := by rw [← cast_to_nat, ← nat.cast_one, nat.cast_le]; apply to_nat_pos @[simp] theorem cast_pos [linear_ordered_semiring α] (n : pos_num) : 0 < (n : α) := lt_of_lt_of_le zero_lt_one (one_le_cast n) @[simp, move_cast] theorem cast_mul [semiring α] (m n) : ((m * n : pos_num) : α) = m * n := by rw [← cast_to_nat, mul_to_nat, nat.cast_mul, cast_to_nat, cast_to_nat] @[simp] theorem cmp_eq (m n) : cmp m n = ordering.eq ↔ m = n := begin have := cmp_to_nat m n, cases cmp m n; simp at this ⊢; try {exact this}; { simp [show m ≠ n, from λ e, by rw e at this; exact lt_irrefl _ this] } end @[simp, elim_cast] theorem cast_lt [linear_ordered_semiring α] {m n : pos_num} : (m:α) < n ↔ m < n := by rw [← cast_to_nat m, ← cast_to_nat n, nat.cast_lt, lt_to_nat] @[simp, elim_cast] theorem cast_le [linear_ordered_semiring α] {m n : pos_num} : (m:α) ≤ n ↔ m ≤ n := by rw ← not_lt; exact not_congr cast_lt end pos_num namespace num variables {α : Type*} open pos_num theorem bit_to_nat (b n) : (bit b n : ℕ) = nat.bit b n := by cases b; cases n; refl theorem cast_succ' [add_monoid α] [has_one α] (n) : (succ' n : α) = n + 1 := by rw [← pos_num.cast_to_nat, succ'_to_nat, nat.cast_add_one, cast_to_nat] theorem cast_succ [add_monoid α] [has_one α] (n) : (succ n : α) = n + 1 := cast_succ' n @[simp] theorem cast_add [semiring α] (m n) : ((m + n : num) : α) = m + n := by rw [← cast_to_nat, add_to_nat, nat.cast_add, cast_to_nat, cast_to_nat] @[simp] theorem cast_bit0 [semiring α] (n : num) : (n.bit0 : α) = _root_.bit0 n := by rw [← bit0_of_bit0, _root_.bit0, cast_add]; refl @[simp] theorem cast_bit1 [semiring α] (n : num) : (n.bit1 : α) = _root_.bit1 n := by rw [← bit1_of_bit1, _root_.bit1, bit0_of_bit0, cast_add, cast_bit0]; refl @[simp] theorem cast_mul [semiring α] : ∀ m n, ((m * n : num) : α) = m * n | 0 0 := (zero_mul _).symm | 0 (pos q) := (zero_mul _).symm | (pos p) 0 := (mul_zero _).symm | (pos p) (pos q) := pos_num.cast_mul _ _ theorem size_to_nat : ∀ n, (size n : ℕ) = nat.size n | 0 := nat.size_zero.symm | (pos p) := p.size_to_nat theorem size_eq_nat_size : ∀ n, (size n : ℕ) = nat_size n | 0 := rfl | (pos p) := p.size_eq_nat_size theorem nat_size_to_nat (n) : nat_size n = nat.size n := by rw [← size_eq_nat_size, size_to_nat] @[simp] theorem of_nat'_eq : ∀ n, num.of_nat' n = n := nat.binary_rec rfl $ λ b n IH, begin rw of_nat' at IH ⊢, rw [nat.binary_rec_eq, IH], { cases b; simp [nat.bit, bit0_of_bit0, bit1_of_bit1] }, { refl } end theorem zneg_to_znum (n : num) : -n.to_znum = n.to_znum_neg := by cases n; refl theorem zneg_to_znum_neg (n : num) : -n.to_znum_neg = n.to_znum := by cases n; refl theorem to_znum_inj {m n : num} : m.to_znum = n.to_znum ↔ m = n := ⟨λ h, by cases m; cases n; cases h; refl, congr_arg _⟩ @[simp] theorem cast_to_znum [has_zero α] [has_one α] [has_add α] [has_neg α] : ∀ n : num, (n.to_znum : α) = n | 0 := rfl | (num.pos p) := rfl @[simp] theorem cast_to_znum_neg [add_group α] [has_one α] : ∀ n : num, (n.to_znum_neg : α) = -n | 0 := neg_zero.symm | (num.pos p) := rfl @[simp] theorem add_to_znum (m n : num) : num.to_znum (m + n) = m.to_znum + n.to_znum := by cases m; cases n; refl end num namespace pos_num open num theorem pred_to_nat {n : pos_num} (h : n > 1) : (pred n : ℕ) = nat.pred n := begin unfold pred, have := pred'_to_nat n, cases e : pred' n, { have : (1:ℕ) ≤ nat.pred n := nat.pred_le_pred ((@cast_lt ℕ _ _ _).2 h), rw [← pred'_to_nat, e] at this, exact absurd this dec_trivial }, { rw [← pred'_to_nat, e], refl } end theorem sub'_one (a : pos_num) : sub' a 1 = (pred' a).to_znum := by cases a; refl theorem one_sub' (a : pos_num) : sub' 1 a = (pred' a).to_znum_neg := by cases a; refl theorem lt_iff_cmp {m n} : m < n ↔ cmp m n = ordering.lt := iff.rfl theorem le_iff_cmp {m n} : m ≤ n ↔ cmp m n ≠ ordering.gt := not_congr $ lt_iff_cmp.trans $ by rw ← cmp_swap; cases cmp m n; exact dec_trivial end pos_num namespace num variables {α : Type*} open pos_num theorem pred_to_nat : ∀ (n : num), (pred n : ℕ) = nat.pred n | 0 := rfl | (pos p) := by rw [pred, pos_num.pred'_to_nat]; refl theorem ppred_to_nat : ∀ (n : num), coe <$> ppred n = nat.ppred n | 0 := rfl | (pos p) := by rw [ppred, option.map_some, nat.ppred_eq_some.2]; rw [pos_num.pred'_to_nat, nat.succ_pred_eq_of_pos (pos_num.to_nat_pos _)]; refl theorem cmp_swap (m n) : (cmp m n).swap = cmp n m := by cases m; cases n; try {unfold cmp}; try {refl}; apply pos_num.cmp_swap theorem cmp_eq (m n) : cmp m n = ordering.eq ↔ m = n := begin have := cmp_to_nat m n, cases cmp m n; simp at this ⊢; try {exact this}; { simp [show m ≠ n, from λ e, by rw e at this; exact lt_irrefl _ this] } end @[simp, elim_cast] theorem cast_lt [linear_ordered_semiring α] {m n : num} : (m:α) < n ↔ m < n := by rw [← cast_to_nat m, ← cast_to_nat n, nat.cast_lt, lt_to_nat] @[simp, elim_cast] theorem cast_le [linear_ordered_semiring α] {m n : num} : (m:α) ≤ n ↔ m ≤ n := by rw ← not_lt; exact not_congr cast_lt @[simp, elim_cast] theorem cast_inj [linear_ordered_semiring α] {m n : num} : (m:α) = n ↔ m = n := by rw [← cast_to_nat m, ← cast_to_nat n, nat.cast_inj, to_nat_inj] theorem lt_iff_cmp {m n} : m < n ↔ cmp m n = ordering.lt := iff.rfl theorem le_iff_cmp {m n} : m ≤ n ↔ cmp m n ≠ ordering.gt := not_congr $ lt_iff_cmp.trans $ by rw ← cmp_swap; cases cmp m n; exact dec_trivial theorem bitwise_to_nat {f : num → num → num} {g : bool → bool → bool} (p : pos_num → pos_num → num) (gff : g ff ff = ff) (f00 : f 0 0 = 0) (f0n : ∀ n, f 0 (pos n) = cond (g ff tt) (pos n) 0) (fn0 : ∀ n, f (pos n) 0 = cond (g tt ff) (pos n) 0) (fnn : ∀ m n, f (pos m) (pos n) = p m n) (p11 : p 1 1 = cond (g tt tt) 1 0) (p1b : ∀ b n, p 1 (pos_num.bit b n) = bit (g tt b) (cond (g ff tt) (pos n) 0)) (pb1 : ∀ a m, p (pos_num.bit a m) 1 = bit (g a tt) (cond (g tt ff) (pos m) 0)) (pbb : ∀ a b m n, p (pos_num.bit a m) (pos_num.bit b n) = bit (g a b) (p m n)) : ∀ m n : num, (f m n : ℕ) = nat.bitwise g m n := begin intros, cases m with m; cases n with n; try { change zero with 0 }; try { change ((0:num):ℕ) with 0 }, { rw [f00, nat.bitwise_zero]; refl }, { unfold nat.bitwise, rw [f0n, nat.binary_rec_zero], cases g ff tt; refl }, { unfold nat.bitwise, generalize h : (pos m : ℕ) = m', revert h, apply nat.bit_cases_on m' _, intros b m' h, rw [fn0, nat.binary_rec_eq, nat.binary_rec_zero, ←h], cases g tt ff; refl, apply nat.bitwise_bit_aux gff }, { rw fnn, have : ∀b (n : pos_num), (cond b ↑n 0 : ℕ) = ↑(cond b (pos n) 0 : num) := by intros; cases b; refl, induction m with m IH m IH generalizing n; cases n with n n, any_goals { change one with 1 }, any_goals { change pos 1 with 1 }, any_goals { change pos_num.bit0 with pos_num.bit ff }, any_goals { change pos_num.bit1 with pos_num.bit tt }, any_goals { change ((1:num):ℕ) with nat.bit tt 0 }, all_goals { repeat { rw show ∀ b n, (pos (pos_num.bit b n) : ℕ) = nat.bit b ↑n, by intros; cases b; refl }, rw nat.bitwise_bit }, any_goals { assumption }, any_goals { rw [nat.bitwise_zero, p11], cases g tt tt; refl }, any_goals { rw [nat.bitwise_zero_left, this, ← bit_to_nat, p1b] }, any_goals { rw [nat.bitwise_zero_right _ gff, this, ← bit_to_nat, pb1] }, all_goals { rw [← show ∀ n, ↑(p m n) = nat.bitwise g ↑m ↑n, from IH], rw [← bit_to_nat, pbb] } } end @[simp, move_cast] theorem lor_to_nat : ∀ m n, (lor m n : ℕ) = nat.lor m n := by apply bitwise_to_nat (λx y, pos (pos_num.lor x y)); intros; try {cases a}; try {cases b}; refl @[simp, move_cast] theorem land_to_nat : ∀ m n, (land m n : ℕ) = nat.land m n := by apply bitwise_to_nat pos_num.land; intros; try {cases a}; try {cases b}; refl @[simp, move_cast] theorem ldiff_to_nat : ∀ m n, (ldiff m n : ℕ) = nat.ldiff m n := by apply bitwise_to_nat pos_num.ldiff; intros; try {cases a}; try {cases b}; refl @[simp, move_cast] theorem lxor_to_nat : ∀ m n, (lxor m n : ℕ) = nat.lxor m n := by apply bitwise_to_nat pos_num.lxor; intros; try {cases a}; try {cases b}; refl @[simp, move_cast] theorem shiftl_to_nat (m n) : (shiftl m n : ℕ) = nat.shiftl m n := begin cases m; dunfold shiftl, {symmetry, apply nat.zero_shiftl}, simp, induction n with n IH, {refl}, simp [pos_num.shiftl, nat.shiftl_succ], rw ←IH end @[simp, move_cast] theorem shiftr_to_nat (m n) : (shiftr m n : ℕ) = nat.shiftr m n := begin cases m with m; dunfold shiftr, {symmetry, apply nat.zero_shiftr}, induction n with n IH generalizing m, {cases m; refl}, cases m with m m; dunfold pos_num.shiftr, { rw [nat.shiftr_eq_div_pow], symmetry, apply nat.div_eq_of_lt, exact @nat.pow_lt_pow_of_lt_right 2 dec_trivial 0 (n+1) (nat.succ_pos _) }, { transitivity, apply IH, change nat.shiftr m n = nat.shiftr (bit1 m) (n+1), rw [add_comm n 1, nat.shiftr_add], apply congr_arg (λx, nat.shiftr x n), unfold nat.shiftr, change (bit1 ↑m : ℕ) with nat.bit tt m, rw nat.div2_bit }, { transitivity, apply IH, change nat.shiftr m n = nat.shiftr (bit0 m) (n + 1), rw [add_comm n 1, nat.shiftr_add], apply congr_arg (λx, nat.shiftr x n), unfold nat.shiftr, change (bit0 ↑m : ℕ) with nat.bit ff m, rw nat.div2_bit } end @[simp] theorem test_bit_to_nat (m n) : test_bit m n = nat.test_bit m n := begin cases m with m; unfold test_bit nat.test_bit, { change (zero : nat) with 0, rw nat.zero_shiftr, refl }, induction n with n IH generalizing m; cases m; dunfold pos_num.test_bit, {refl}, { exact (nat.bodd_bit _ _).symm }, { exact (nat.bodd_bit _ _).symm }, { change ff = nat.bodd (nat.shiftr 1 (n + 1)), rw [add_comm, nat.shiftr_add], change nat.shiftr 1 1 with 0, rw nat.zero_shiftr; refl }, { change pos_num.test_bit m n = nat.bodd (nat.shiftr (nat.bit tt m) (n + 1)), rw [add_comm, nat.shiftr_add], unfold nat.shiftr, rw nat.div2_bit, apply IH }, { change pos_num.test_bit m n = nat.bodd (nat.shiftr (nat.bit ff m) (n + 1)), rw [add_comm, nat.shiftr_add], unfold nat.shiftr, rw nat.div2_bit, apply IH }, end end num namespace znum variables {α : Type*} open pos_num @[simp] theorem cast_zero [has_zero α] [has_one α] [has_add α] [has_neg α] : ((0 : znum) : α) = 0 := rfl @[simp] theorem cast_zero' [has_zero α] [has_one α] [has_add α] [has_neg α] : (znum.zero : α) = 0 := rfl @[simp] theorem cast_one [has_zero α] [has_one α] [has_add α] [has_neg α] : ((1 : znum) : α) = 1 := rfl @[simp] theorem cast_pos [has_zero α] [has_one α] [has_add α] [has_neg α] (n : pos_num) : (pos n : α) = n := rfl @[simp] theorem cast_neg [has_zero α] [has_one α] [has_add α] [has_neg α] (n : pos_num) : (neg n : α) = -n := rfl @[simp] theorem cast_zneg [add_group α] [has_one α] : ∀ n, ((-n : znum) : α) = -n | 0 := neg_zero.symm | (pos p) := rfl | (neg p) := (neg_neg _).symm theorem neg_zero : (-0 : znum) = 0 := rfl theorem zneg_pos (n : pos_num) : -pos n = neg n := rfl theorem zneg_neg (n : pos_num) : -neg n = pos n := rfl theorem zneg_zneg (n : znum) : - -n = n := by cases n; refl theorem zneg_bit1 (n : znum) : -n.bit1 = (-n).bitm1 := by cases n; refl theorem zneg_bitm1 (n : znum) : -n.bitm1 = (-n).bit1 := by cases n; refl theorem zneg_succ (n : znum) : -n.succ = (-n).pred := by cases n; try {refl}; rw [succ, num.zneg_to_znum_neg]; refl theorem zneg_pred (n : znum) : -n.pred = (-n).succ := by rw [← zneg_zneg (succ (-n)), zneg_succ, zneg_zneg] @[simp] theorem neg_of_int : ∀ n, ((-n : ℤ) : znum) = -n | (n+1:ℕ) := rfl | 0 := rfl | -[1+n] := (zneg_zneg _).symm @[simp] theorem abs_to_nat : ∀ n, (abs n : ℕ) = int.nat_abs n | 0 := rfl | (pos p) := congr_arg int.nat_abs p.to_nat_to_int | (neg p) := show int.nat_abs ((p:ℕ):ℤ) = int.nat_abs (- p), by rw [p.to_nat_to_int, int.nat_abs_neg] @[simp] theorem abs_to_znum : ∀ n : num, abs n.to_znum = n | 0 := rfl | (num.pos p) := rfl @[simp] theorem cast_to_int [add_group α] [has_one α] : ∀ n : znum, ((n : ℤ) : α) = n | 0 := rfl | (pos p) := by rw [cast_pos, cast_pos, pos_num.cast_to_int] | (neg p) := by rw [cast_neg, cast_neg, int.cast_neg, pos_num.cast_to_int] theorem bit0_of_bit0 : ∀ n : znum, _root_.bit0 n = n.bit0 | 0 := rfl | (pos a) := congr_arg pos a.bit0_of_bit0 | (neg a) := congr_arg neg a.bit0_of_bit0 theorem bit1_of_bit1 : ∀ n : znum, _root_.bit1 n = n.bit1 | 0 := rfl | (pos a) := congr_arg pos a.bit1_of_bit1 | (neg a) := show pos_num.sub' 1 (_root_.bit0 a) = _, by rw [pos_num.one_sub', a.bit0_of_bit0]; refl @[simp] theorem cast_bit0 [add_group α] [has_one α] : ∀ n : znum, (n.bit0 : α) = bit0 n | 0 := (add_zero _).symm | (pos p) := by rw [znum.bit0, cast_pos, cast_pos]; refl | (neg p) := by rw [znum.bit0, cast_neg, cast_neg, pos_num.cast_bit0, _root_.bit0, _root_.bit0, neg_add_rev] @[simp] theorem cast_bit1 [add_group α] [has_one α] : ∀ n : znum, (n.bit1 : α) = bit1 n | 0 := by simp [znum.bit1, _root_.bit1, _root_.bit0] | (pos p) := by rw [znum.bit1, cast_pos, cast_pos]; refl | (neg p) := begin rw [znum.bit1, cast_neg, cast_neg], cases e : pred' p; have : p = _ := (succ'_pred' p).symm.trans (congr_arg num.succ' e), { change p=1 at this, subst p, simp [_root_.bit1, _root_.bit0] }, { rw [num.succ'] at this, subst p, have : (↑(-↑a:ℤ) : α) = -1 + ↑(-↑a + 1 : ℤ), {simp [add_comm]}, simpa [_root_.bit1, _root_.bit0, -add_comm] }, end @[simp] theorem cast_bitm1 [add_group α] [has_one α] (n : znum) : (n.bitm1 : α) = bit0 n - 1 := begin conv { to_lhs, rw ← zneg_zneg n }, rw [← zneg_bit1, cast_zneg, cast_bit1], have : ((-1 + n + n : ℤ) : α) = (n + n + -1 : ℤ), {simp [add_comm, add_left_comm]}, simpa [_root_.bit1, _root_.bit0, sub_eq_add_neg] end theorem add_zero (n : znum) : n + 0 = n := by cases n; refl theorem zero_add (n : znum) : 0 + n = n := by cases n; refl theorem add_one : ∀ n : znum, n + 1 = succ n | 0 := rfl | (pos p) := congr_arg pos p.add_one | (neg p) := by cases p; refl end znum namespace pos_num variables {α : Type*} theorem cast_to_znum : ∀ n : pos_num, (n : znum) = znum.pos n | 1 := rfl | (bit0 p) := (znum.bit0_of_bit0 p).trans $ congr_arg _ (cast_to_znum p) | (bit1 p) := (znum.bit1_of_bit1 p).trans $ congr_arg _ (cast_to_znum p) theorem cast_sub' [add_group α] [has_one α] : ∀ m n : pos_num, (sub' m n : α) = m - n | a 1 := by rw [sub'_one, num.cast_to_znum, ← num.cast_to_nat, pred'_to_nat, ← nat.sub_one]; simp [pos_num.cast_pos] | 1 b := by rw [one_sub', num.cast_to_znum_neg, ← neg_sub, neg_inj', ← num.cast_to_nat, pred'_to_nat, ← nat.sub_one]; simp [pos_num.cast_pos] | (bit0 a) (bit0 b) := begin rw [sub', znum.cast_bit0, cast_sub'], have : ((a + -b + (a + -b) : ℤ) : α) = a + a + (-b + -b), {simp [add_left_comm]}, simpa [_root_.bit0, sub_eq_add_neg] end | (bit0 a) (bit1 b) := begin rw [sub', znum.cast_bitm1, cast_sub'], have : ((-b + (a + (-b + -1)) : ℤ) : α) = (a + -1 + (-b + -b):ℤ), { simp [add_comm, add_left_comm] }, simpa [_root_.bit1, _root_.bit0, sub_eq_add_neg] end | (bit1 a) (bit0 b) := begin rw [sub', znum.cast_bit1, cast_sub'], have : ((-b + (a + (-b + 1)) : ℤ) : α) = (a + 1 + (-b + -b):ℤ), { simp [add_comm, add_left_comm] }, simpa [_root_.bit1, _root_.bit0, sub_eq_add_neg] end | (bit1 a) (bit1 b) := begin rw [sub', znum.cast_bit0, cast_sub'], have : ((-b + (a + -b) : ℤ) : α) = a + (-b + -b), {simp [add_left_comm]}, simpa [_root_.bit1, _root_.bit0, sub_eq_add_neg] end theorem to_nat_eq_succ_pred (n : pos_num) : (n:ℕ) = n.pred' + 1 := by rw [← num.succ'_to_nat, n.succ'_pred'] theorem to_int_eq_succ_pred (n : pos_num) : (n:ℤ) = (n.pred' : ℕ) + 1 := by rw [← n.to_nat_to_int, to_nat_eq_succ_pred]; refl end pos_num namespace num variables {α : Type*} @[simp] theorem cast_sub' [add_group α] [has_one α] : ∀ m n : num, (sub' m n : α) = m - n | 0 0 := (sub_zero _).symm | (pos a) 0 := (sub_zero _).symm | 0 (pos b) := (zero_sub _).symm | (pos a) (pos b) := pos_num.cast_sub' _ _ @[simp] theorem of_nat_to_znum : ∀ n : ℕ, to_znum n = n | 0 := rfl | (n+1) := by rw [nat.cast_add_one, nat.cast_add_one, znum.add_one, add_one, ← of_nat_to_znum]; cases (n:num); refl @[simp] theorem of_nat_to_znum_neg (n : ℕ) : to_znum_neg n = -n := by rw [← of_nat_to_znum, zneg_to_znum] theorem mem_of_znum' : ∀ {m : num} {n : znum}, m ∈ of_znum' n ↔ n = to_znum m | 0 0 := ⟨λ _, rfl, λ _, rfl⟩ | (pos m) 0 := ⟨λ h, by cases h, λ h, by cases h⟩ | m (znum.pos p) := option.some_inj.trans $ by cases m; split; intro h; try {cases h}; refl | m (znum.neg p) := ⟨λ h, by cases h, λ h, by cases m; cases h⟩ theorem of_znum'_to_nat : ∀ (n : znum), coe <$> of_znum' n = int.to_nat' n | 0 := rfl | (znum.pos p) := show _ = int.to_nat' p, by rw [← pos_num.to_nat_to_int p]; refl | (znum.neg p) := congr_arg (λ x, int.to_nat' (-x)) $ show ((p.pred' + 1 : ℕ) : ℤ) = p, by rw ← succ'_to_nat; simp @[simp] theorem of_znum_to_nat : ∀ (n : znum), (of_znum n : ℕ) = int.to_nat n | 0 := rfl | (znum.pos p) := show _ = int.to_nat p, by rw [← pos_num.to_nat_to_int p]; refl | (znum.neg p) := congr_arg (λ x, int.to_nat (-x)) $ show ((p.pred' + 1 : ℕ) : ℤ) = p, by rw ← succ'_to_nat; simp @[simp] theorem cast_of_znum [add_group α] [has_one α] (n : znum) : (of_znum n : α) = int.to_nat n := by rw [← cast_to_nat, of_znum_to_nat] @[simp] theorem sub_to_nat (m n) : ((m - n : num) : ℕ) = m - n := show (of_znum _ : ℕ) = _, by rw [of_znum_to_nat, cast_sub', ← to_nat_to_int, ← to_nat_to_int, int.to_nat_sub] end num namespace znum variables {α : Type*} @[simp] theorem cast_add [add_group α] [has_one α] : ∀ m n, ((m + n : znum) : α) = m + n | 0 a := by cases a; exact (_root_.zero_add _).symm | b 0 := by cases b; exact (_root_.add_zero _).symm | (pos a) (pos b) := pos_num.cast_add _ _ | (pos a) (neg b) := pos_num.cast_sub' _ _ | (neg a) (pos b) := (pos_num.cast_sub' _ _).trans $ show ↑b + -↑a = -↑a + ↑b, by rw [← pos_num.cast_to_int a, ← pos_num.cast_to_int b, ← int.cast_neg, ← int.cast_add (-a)]; simp [add_comm] | (neg a) (neg b) := show -(↑(a + b) : α) = -a + -b, by rw [ pos_num.cast_add, neg_eq_iff_neg_eq, neg_add_rev, neg_neg, neg_neg, ← pos_num.cast_to_int a, ← pos_num.cast_to_int b, ← int.cast_add]; simp [add_comm] @[simp] theorem cast_succ [add_group α] [has_one α] (n) : ((succ n : znum) : α) = n + 1 := by rw [← add_one, cast_add, cast_one] @[simp] theorem mul_to_int : ∀ m n, ((m * n : znum) : ℤ) = m * n | 0 a := by cases a; exact (_root_.zero_mul _).symm | b 0 := by cases b; exact (_root_.mul_zero _).symm | (pos a) (pos b) := pos_num.cast_mul a b | (pos a) (neg b) := show -↑(a * b) = ↑a * -↑b, by rw [pos_num.cast_mul, neg_mul_eq_mul_neg] | (neg a) (pos b) := show -↑(a * b) = -↑a * ↑b, by rw [pos_num.cast_mul, neg_mul_eq_neg_mul] | (neg a) (neg b) := show ↑(a * b) = -↑a * -↑b, by rw [pos_num.cast_mul, neg_mul_neg] theorem cast_mul [ring α] (m n) : ((m * n : znum) : α) = m * n := by rw [← cast_to_int, mul_to_int, int.cast_mul, cast_to_int, cast_to_int] @[simp] theorem of_to_int : Π (n : znum), ((n : ℤ) : znum) = n | 0 := rfl | (pos a) := by rw [cast_pos, ← pos_num.cast_to_nat, int.cast_coe_nat', ← num.of_nat_to_znum, pos_num.of_to_nat]; refl | (neg a) := by rw [cast_neg, neg_of_int, ← pos_num.cast_to_nat, int.cast_coe_nat', ← num.of_nat_to_znum_neg, pos_num.of_to_nat]; refl theorem to_of_int : Π (n : ℤ), ((n : znum) : ℤ) = n | (n : ℕ) := by rw [int.cast_coe_nat, ← num.of_nat_to_znum, num.cast_to_znum, ← num.cast_to_nat, int.nat_cast_eq_coe_nat, num.to_of_nat] | -[1+ n] := by rw [int.cast_neg_succ_of_nat, cast_zneg, add_one, cast_succ, int.neg_succ_of_nat_eq, ← num.of_nat_to_znum, num.cast_to_znum, ← num.cast_to_nat, int.nat_cast_eq_coe_nat, num.to_of_nat] theorem to_int_inj {m n : znum} : (m : ℤ) = n ↔ m = n := ⟨λ h, function.injective_of_left_inverse of_to_int h, congr_arg _⟩ @[simp] theorem of_int_cast [add_group α] [has_one α] (n : ℤ) : ((n : znum) : α) = n := by rw [← cast_to_int, to_of_int] @[simp] theorem of_nat_cast [add_group α] [has_one α] (n : ℕ) : ((n : znum) : α) = n := of_int_cast n @[simp] theorem of_int'_eq : ∀ n, znum.of_int' n = n | (n : ℕ) := to_int_inj.1 $ by simp [znum.of_int'] | -[1+ n] := to_int_inj.1 $ by simp [znum.of_int'] theorem cmp_to_int : ∀ (m n), (ordering.cases_on (cmp m n) ((m:ℤ) < n) (m = n) ((m:ℤ) > n) : Prop) | 0 0 := rfl | (pos a) (pos b) := begin have := pos_num.cmp_to_nat a b; revert this; dsimp [cmp]; cases pos_num.cmp a b; dsimp; [simp, exact congr_arg pos, simp [gt]] end | (neg a) (neg b) := begin have := pos_num.cmp_to_nat b a; revert this; dsimp [cmp]; cases pos_num.cmp b a; dsimp; [simp, simp {contextual := tt}, simp [gt]] end | (pos a) 0 := pos_num.cast_pos _ | (pos a) (neg b) := lt_trans (neg_lt_zero.2 $ pos_num.cast_pos _) (pos_num.cast_pos _) | 0 (neg b) := neg_lt_zero.2 $ pos_num.cast_pos _ | (neg a) 0 := neg_lt_zero.2 $ pos_num.cast_pos _ | (neg a) (pos b) := lt_trans (neg_lt_zero.2 $ pos_num.cast_pos _) (pos_num.cast_pos _) | 0 (pos b) := pos_num.cast_pos _ theorem lt_to_int {m n : znum} : (m:ℤ) < n ↔ m < n := show (m:ℤ) < n ↔ cmp m n = ordering.lt, from match cmp m n, cmp_to_int m n with | ordering.lt, h := by simp at h; simp [h] | ordering.eq, h := by simp at h; simp [h, lt_irrefl]; exact dec_trivial | ordering.gt, h := by simp [not_lt_of_gt h]; exact dec_trivial end theorem le_to_int {m n : znum} : (m:ℤ) ≤ n ↔ m ≤ n := by rw ← not_lt; exact not_congr lt_to_int @[simp, elim_cast] theorem cast_lt [linear_ordered_ring α] {m n : znum} : (m:α) < n ↔ m < n := by rw [← cast_to_int m, ← cast_to_int n, int.cast_lt, lt_to_int] @[simp, elim_cast] theorem cast_le [linear_ordered_ring α] {m n : znum} : (m:α) ≤ n ↔ m ≤ n := by rw ← not_lt; exact not_congr cast_lt @[simp, elim_cast] theorem cast_inj [linear_ordered_ring α] {m n : znum} : (m:α) = n ↔ m = n := by rw [← cast_to_int m, ← cast_to_int n, int.cast_inj, to_int_inj] meta def transfer_rw : tactic unit := `[repeat {rw ← to_int_inj <|> rw ← lt_to_int <|> rw ← le_to_int}, repeat {rw cast_add <|> rw mul_to_int <|> rw cast_one <|> rw cast_zero}] meta def transfer : tactic unit := `[intros, transfer_rw, try {simp [add_comm, add_left_comm, mul_comm, mul_left_comm]}] instance : decidable_linear_order znum := { lt := (<), lt_iff_le_not_le := by {intros a b, transfer_rw, apply lt_iff_le_not_le}, le := (≤), le_refl := by transfer, le_trans := by {intros a b c, transfer_rw, apply le_trans}, le_antisymm := by {intros a b, transfer_rw, apply le_antisymm}, le_total := by {intros a b, transfer_rw, apply le_total}, decidable_eq := znum.decidable_eq, decidable_le := znum.decidable_le, decidable_lt := znum.decidable_lt } instance : add_comm_group znum := { add := (+), add_assoc := by transfer, zero := 0, zero_add := zero_add, add_zero := add_zero, add_comm := by transfer, neg := has_neg.neg, add_left_neg := by transfer } instance : decidable_linear_ordered_comm_ring znum := { mul := (*), mul_assoc := by transfer, one := 1, one_mul := by transfer, mul_one := by transfer, left_distrib := by {transfer, simp [mul_add]}, right_distrib := by {transfer, simp [mul_add, mul_comm]}, mul_comm := by transfer, zero_ne_one := dec_trivial, add_le_add_left := by {intros a b h c, revert h, transfer_rw, exact λ h, add_le_add_left h c}, add_lt_add_left := by {intros a b h c, revert h, transfer_rw, exact λ h, add_lt_add_left h c}, mul_pos := by {intros a b, transfer_rw, apply mul_pos}, mul_nonneg := by {intros x y, change 0 ≤ x → 0 ≤ y → 0 ≤ x * y, transfer_rw, apply mul_nonneg}, zero_lt_one := dec_trivial, ..znum.decidable_linear_order, ..znum.add_comm_group } @[simp] theorem dvd_to_int (m n : znum) : (m : ℤ) ∣ n ↔ m ∣ n := ⟨λ ⟨k, e⟩, ⟨k, by rw [← of_to_int n, e]; simp⟩, λ ⟨k, e⟩, ⟨k, by simp [e]⟩⟩ end znum namespace pos_num theorem divmod_to_nat_aux {n d : pos_num} {q r : num} (h₁ : (r:ℕ) + d * _root_.bit0 q = n) (h₂ : (r:ℕ) < 2 * d) : ((divmod_aux d q r).2 + d * (divmod_aux d q r).1 : ℕ) = ↑n ∧ ((divmod_aux d q r).2 : ℕ) < d := begin unfold divmod_aux, have : ∀ {r₂}, num.of_znum' (num.sub' r (num.pos d)) = some r₂ ↔ (r : ℕ) = r₂ + d, { intro r₂, apply num.mem_of_znum'.trans, rw [← znum.to_int_inj, num.cast_to_znum, num.cast_sub', sub_eq_iff_eq_add, ← int.coe_nat_inj'], simp }, cases e : num.of_znum' (num.sub' r (num.pos d)) with r₂; simp [divmod_aux], { refine ⟨h₁, lt_of_not_ge (λ h, _)⟩, cases nat.le.dest h with r₂ e', rw [← num.to_of_nat r₂, add_comm] at e', cases e.symm.trans (this.2 e'.symm) }, { have := this.1 e, split, { rwa [_root_.bit1, add_comm _ 1, mul_add, mul_one, ← add_assoc, ← this] }, { rwa [this, two_mul, add_lt_add_iff_right] at h₂ } } end theorem divmod_to_nat (d n : pos_num) : (n / d : ℕ) = (divmod d n).1 ∧ (n % d : ℕ) = (divmod d n).2 := begin rw nat.div_mod_unique (pos_num.cast_pos _), induction n with n IH n IH, { exact divmod_to_nat_aux (by simp; refl) (nat.mul_le_mul_left 2 (pos_num.cast_pos d : (0 : ℕ) < d)) }, { unfold divmod, cases divmod d n with q r, simp only [divmod] at IH ⊢, apply divmod_to_nat_aux; simp, { rw [_root_.bit1, _root_.bit1, add_right_comm, bit0_eq_two_mul ↑n, ← IH.1, mul_add, ← bit0_eq_two_mul, mul_left_comm, ← bit0_eq_two_mul] }, { rw ← bit0_eq_two_mul, exact nat.bit1_lt_bit0 IH.2 } }, { unfold divmod, cases divmod d n with q r, simp only [divmod] at IH ⊢, apply divmod_to_nat_aux; simp, { rw [bit0_eq_two_mul ↑n, ← IH.1, mul_add, ← bit0_eq_two_mul, mul_left_comm, ← bit0_eq_two_mul] }, { rw ← bit0_eq_two_mul, exact nat.bit0_lt IH.2 } } end @[simp] theorem div'_to_nat (n d) : (div' n d : ℕ) = n / d := (divmod_to_nat _ _).1.symm @[simp] theorem mod'_to_nat (n d) : (mod' n d : ℕ) = n % d := (divmod_to_nat _ _).2.symm end pos_num namespace num @[simp] theorem div_to_nat : ∀ n d, ((n / d : num) : ℕ) = n / d | 0 0 := rfl | 0 (pos d) := (nat.zero_div _).symm | (pos n) 0 := (nat.div_zero _).symm | (pos n) (pos d) := pos_num.div'_to_nat _ _ @[simp] theorem mod_to_nat : ∀ n d, ((n % d : num) : ℕ) = n % d | 0 0 := rfl | 0 (pos d) := (nat.zero_mod _).symm | (pos n) 0 := (nat.mod_zero _).symm | (pos n) (pos d) := pos_num.mod'_to_nat _ _ theorem gcd_to_nat_aux : ∀ {n} {a b : num}, a ≤ b → (a * b).nat_size ≤ n → (gcd_aux n a b : ℕ) = nat.gcd a b | 0 0 b ab h := (nat.gcd_zero_left _).symm | 0 (pos a) 0 ab h := (not_lt_of_ge ab).elim rfl | 0 (pos a) (pos b) ab h := (not_lt_of_le h).elim $ pos_num.nat_size_pos _ | (nat.succ n) 0 b ab h := (nat.gcd_zero_left _).symm | (nat.succ n) (pos a) b ab h := begin simp [gcd_aux], rw [nat.gcd_rec, gcd_to_nat_aux, mod_to_nat], {refl}, { rw [← le_to_nat, mod_to_nat], exact le_of_lt (nat.mod_lt _ (pos_num.cast_pos _)) }, rw [nat_size_to_nat, mul_to_nat, nat.size_le] at h ⊢, rw [mod_to_nat, mul_comm], rw [nat.pow_succ, ← nat.mod_add_div b (pos a)] at h, refine lt_of_mul_lt_mul_right (lt_of_le_of_lt _ h) (nat.zero_le 2), rw [mul_two, mul_add], refine add_le_add_left (nat.mul_le_mul_left _ (le_trans (le_of_lt (nat.mod_lt _ (pos_num.cast_pos _))) _)) _, suffices : 1 ≤ _, simpa using nat.mul_le_mul_left (pos a) this, rw [nat.le_div_iff_mul_le _ _ a.cast_pos, one_mul], exact le_to_nat.2 ab end @[simp] theorem gcd_to_nat : ∀ a b, (gcd a b : ℕ) = nat.gcd a b := have ∀ a b : num, (a * b).nat_size ≤ a.nat_size + b.nat_size, begin intros, simp [nat_size_to_nat], rw [nat.size_le, nat.pow_add], exact mul_lt_mul'' (nat.lt_size_self _) (nat.lt_size_self _) (nat.zero_le _) (nat.zero_le _) end, begin intros, unfold gcd, split_ifs, { exact gcd_to_nat_aux h (this _ _) }, { rw nat.gcd_comm, exact gcd_to_nat_aux (le_of_not_le h) (this _ _) } end theorem dvd_iff_mod_eq_zero {m n : num} : m ∣ n ↔ n % m = 0 := by rw [← dvd_to_nat, nat.dvd_iff_mod_eq_zero, ← to_nat_inj, mod_to_nat]; refl instance : decidable_rel ((∣) : num → num → Prop) | a b := decidable_of_iff' _ dvd_iff_mod_eq_zero end num namespace znum @[simp] theorem div_to_int : ∀ n d, ((n / d : znum) : ℤ) = n / d | 0 0 := rfl | 0 (pos d) := (int.zero_div _).symm | 0 (neg d) := (int.zero_div _).symm | (pos n) 0 := (int.div_zero _).symm | (neg n) 0 := (int.div_zero _).symm | (pos n) (pos d) := (num.cast_to_znum _).trans $ by rw ← num.to_nat_to_int; simp | (pos n) (neg d) := (num.cast_to_znum_neg _).trans $ by rw ← num.to_nat_to_int; simp | (neg n) (pos d) := show - _ = (-_/↑d), begin rw [n.to_int_eq_succ_pred, d.to_int_eq_succ_pred, ← pos_num.to_nat_to_int, num.succ'_to_nat, num.div_to_nat], change -[1+ n.pred' / ↑d] = -[1+ n.pred' / (d.pred' + 1)], rw d.to_nat_eq_succ_pred end | (neg n) (neg d) := show ↑(pos_num.pred' n / num.pos d).succ' = (-_ / -↑d), begin rw [n.to_int_eq_succ_pred, d.to_int_eq_succ_pred, ← pos_num.to_nat_to_int, num.succ'_to_nat, num.div_to_nat], change (nat.succ (_/d) : ℤ) = nat.succ (n.pred'/(d.pred' + 1)), rw d.to_nat_eq_succ_pred end @[simp] theorem mod_to_int : ∀ n d, ((n % d : znum) : ℤ) = n % d | 0 d := (int.zero_mod _).symm | (pos n) d := (num.cast_to_znum _).trans $ by rw [← num.to_nat_to_int, cast_pos, num.mod_to_nat, ← pos_num.to_nat_to_int, abs_to_nat]; refl | (neg n) d := (num.cast_sub' _ _).trans $ by rw [← num.to_nat_to_int, cast_neg, ← num.to_nat_to_int, num.succ_to_nat, num.mod_to_nat, abs_to_nat, ← int.sub_nat_nat_eq_coe, n.to_int_eq_succ_pred]; refl @[simp] theorem gcd_to_nat (a b) : (gcd a b : ℕ) = int.gcd a b := (num.gcd_to_nat _ _).trans $ by simpa theorem dvd_iff_mod_eq_zero {m n : znum} : m ∣ n ↔ n % m = 0 := by rw [← dvd_to_int, int.dvd_iff_mod_eq_zero, ← to_int_inj, mod_to_int]; refl instance : decidable_rel ((∣) : znum → znum → Prop) | a b := decidable_of_iff' _ dvd_iff_mod_eq_zero end znum
75da229fab4a43c6004b249af3d58724c2b80d83
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/sec_param_pp2.lean
a16e2df1088e4e101b5687c7bf3b9ba65d80e56c
[ "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
230
lean
section parameters {A : Type} (a : A) section parameters {B : Type} (b : B) variable f : A → B → A definition id2 := f a b check id2 set_option pp.universes true check id2 end check id2 end check id2
9295bcfa8e5f10dcc7aa6d04afbcbce4c2c590e7
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/group_theory/monoid_localization.lean
0e11e1016203912abd047b41b3969fd640aae556
[ "Apache-2.0" ]
permissive
ilitzroth/mathlib
ea647e67f1fdfd19a0f7bdc5504e8acec6180011
5254ef14e3465f6504306132fe3ba9cec9ffff16
refs/heads/master
1,680,086,661,182
1,617,715,647,000
1,617,715,647,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
54,949
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 group_theory.congruence import group_theory.submonoid import algebra.group.units import algebra.punit_instances /-! # Localizations of commutative monoids Localizing a commutative ring at one of its submonoids does not rely on the ring's addition, so we can generalize localizations to commutative monoids. We characterize the localization of a commutative monoid `M` at a submonoid `S` up to isomorphism; that is, a commutative monoid `N` is the localization of `M` at `S` iff we can find a monoid homomorphism `f : M →* N` satisfying 3 properties: 1. For all `y ∈ S`, `f y` is a unit; 2. For all `z : N`, there exists `(x, y) : M × S` such that `z * f y = f x`; 3. For all `x, y : M`, `f x = f y` iff there exists `c ∈ S` such that `x * c = y * c`. Given such a localization map `f : M →* N`, we can define the surjection `localization_map.mk'` sending `(x, y) : M × S` to `f x * (f y)⁻¹`, and `localization_map.lift`, the homomorphism from `N` induced by a homomorphism from `M` which maps elements of `S` to invertible elements of the codomain. Similarly, given commutative monoids `P, Q`, a submonoid `T` of `P` and a localization map for `T` from `P` to `Q`, then a homomorphism `g : M →* P` such that `g(S) ⊆ T` induces a homomorphism of localizations, `localization_map.map`, from `N` to `Q`. We treat the special case of localizing away from an element in the sections `away_map` and `away`. We also define the quotient of `M × S` by the unique congruence relation (equivalence relation preserving a binary operation) `r` such that for any other congruence relation `s` on `M × S` satisfying '`∀ y ∈ S`, `(1, 1) ∼ (y, y)` under `s`', we have that `(x₁, y₁) ∼ (x₂, y₂)` by `s` whenever `(x₁, y₁) ∼ (x₂, y₂)` by `r`. We show this relation is equivalent to the standard localization relation. This defines the localization as a quotient type, `localization`, but the majority of subsequent lemmas in the file are given in terms of localizations up to isomorphism, using maps which satisfy the characteristic predicate. ## Implementation notes In maths it is natural to reason up to isomorphism, but in Lean we cannot naturally `rewrite` one structure with an isomorphic one; one way around this is to isolate a predicate characterizing a structure up to isomorphism, and reason about things that satisfy the predicate. The infimum form of the localization congruence relation is chosen as 'canonical' here, since it shortens some proofs. To apply a localization map `f` as a function, we use `f.to_map`, as coercions don't work well for this structure. To reason about the localization as a quotient type, use `mk_eq_monoid_of_mk'` and associated lemmas. These show the quotient map `mk : M → S → localization S` equals the surjection `localization_map.mk'` induced by the map `monoid_of : localization_map S (localization S)` (where `of` establishes the localization as a quotient type satisfies the characteristic predicate). The lemma `mk_eq_monoid_of_mk'` hence gives you access to the results in the rest of the file, which are about the `localization_map.mk'` induced by any localization map. ## Tags localization, monoid localization, quotient monoid, congruence relation, characteristic predicate, commutative monoid -/ set_option old_structure_cmd true namespace add_submonoid variables {M : Type*} [add_comm_monoid M] (S : add_submonoid M) (N : Type*) [add_comm_monoid N] /-- The type of add_monoid homomorphisms satisfying the characteristic predicate: if `f : M →+ N` satisfies this predicate, then `N` is isomorphic to the localization of `M` at `S`. -/ @[nolint has_inhabited_instance] structure localization_map extends add_monoid_hom M N := (map_add_units' : ∀ y : S, is_add_unit (to_fun y)) (surj' : ∀ z : N, ∃ x : M × S, z + to_fun x.2 = to_fun x.1) (eq_iff_exists' : ∀ x y, to_fun x = to_fun y ↔ ∃ c : S, x + c = y + c) /-- The add_monoid hom underlying a `localization_map` of `add_comm_monoid`s. -/ add_decl_doc localization_map.to_add_monoid_hom end add_submonoid variables {M : Type*} [comm_monoid M] (S : submonoid M) (N : Type*) [comm_monoid N] {P : Type*} [comm_monoid P] namespace submonoid /-- The type of monoid homomorphisms satisfying the characteristic predicate: if `f : M →* N` satisfies this predicate, then `N` is isomorphic to the localization of `M` at `S`. -/ @[nolint has_inhabited_instance] structure localization_map extends monoid_hom M N := (map_units' : ∀ y : S, is_unit (to_fun y)) (surj' : ∀ z : N, ∃ x : M × S, z * to_fun x.2 = to_fun x.1) (eq_iff_exists' : ∀ x y, to_fun x = to_fun y ↔ ∃ c : S, x * c = y * c) attribute [to_additive add_submonoid.localization_map] submonoid.localization_map attribute [to_additive add_submonoid.localization_map.to_add_monoid_hom] submonoid.localization_map.to_monoid_hom /-- The monoid hom underlying a `localization_map`. -/ add_decl_doc localization_map.to_monoid_hom end submonoid namespace localization run_cmd to_additive.map_namespace `localization `add_localization /-- The congruence relation on `M × S`, `M` a `comm_monoid` and `S` a submonoid of `M`, whose quotient is the localization of `M` at `S`, defined as the unique congruence relation on `M × S` such that for any other congruence relation `s` on `M × S` where for all `y ∈ S`, `(1, 1) ∼ (y, y)` under `s`, we have that `(x₁, y₁) ∼ (x₂, y₂)` by `r` implies `(x₁, y₁) ∼ (x₂, y₂)` by `s`. -/ @[to_additive "The congruence relation on `M × S`, `M` an `add_comm_monoid` and `S` an `add_submonoid` of `M`, whose quotient is the localization of `M` at `S`, defined as the unique congruence relation on `M × S` such that for any other congruence relation `s` on `M × S` where for all `y ∈ S`, `(0, 0) ∼ (y, y)` under `s`, we have that `(x₁, y₁) ∼ (x₂, y₂)` by `r` implies `(x₁, y₁) ∼ (x₂, y₂)` by `s`."] def r (S : submonoid M) : con (M × S) := Inf {c | ∀ y : S, c 1 (y, y)} /-- An alternate form of the congruence relation on `M × S`, `M` a `comm_monoid` and `S` a submonoid of `M`, whose quotient is the localization of `M` at `S`. -/ @[to_additive "An alternate form of the congruence relation on `M × S`, `M` a `comm_monoid` and `S` a submonoid of `M`, whose quotient is the localization of `M` at `S`."] def r' : con (M × S) := begin refine { r := λ a b : M × S, ∃ c : S, a.1 * b.2 * c = b.1 * a.2 * c, iseqv := ⟨λ a, ⟨1, rfl⟩, λ a b ⟨c, hc⟩, ⟨c, hc.symm⟩, _⟩, .. }, { rintros a b c ⟨t₁, ht₁⟩ ⟨t₂, ht₂⟩, use b.2 * t₁ * t₂, simp only [submonoid.coe_mul], calc a.1 * c.2 * (b.2 * t₁ * t₂) = a.1 * b.2 * t₁ * c.2 * t₂ : by ac_refl ... = b.1 * c.2 * t₂ * a.2 * t₁ : by { rw ht₁, ac_refl } ... = c.1 * a.2 * (b.2 * t₁ * t₂) : by { rw ht₂, ac_refl } }, { rintros a b c d ⟨t₁, ht₁⟩ ⟨t₂, ht₂⟩, use t₁ * t₂, calc (a.1 * c.1) * (b.2 * d.2) * (t₁ * t₂) = (a.1 * b.2 * t₁) * (c.1 * d.2 * t₂) : by ac_refl ... = (b.1 * d.1) * (a.2 * c.2) * (t₁ * t₂) : by { rw [ht₁, ht₂], ac_refl } } end /-- The congruence relation used to localize a `comm_monoid` at a submonoid can be expressed equivalently as an infimum (see `localization.r`) or explicitly (see `localization.r'`). -/ @[to_additive "The additive congruence relation used to localize an `add_comm_monoid` at a submonoid can be expressed equivalently as an infimum (see `add_localization.r`) or explicitly (see `add_localization.r'`)."] theorem r_eq_r' : r S = r' S := le_antisymm (Inf_le $ λ _, ⟨1, by simp⟩) $ le_Inf $ λ b H ⟨p, q⟩ y ⟨t, ht⟩, begin rw [← mul_one (p, q), ← mul_one y], refine b.trans (b.mul (b.refl _) (H (y.2 * t))) _, convert b.symm (b.mul (b.refl y) (H (q * t))) using 1, rw [prod.mk_mul_mk, submonoid.coe_mul, ← mul_assoc, ht, mul_left_comm, mul_assoc], refl end variables {S} @[to_additive] lemma r_iff_exists {x y : M × S} : r S x y ↔ ∃ c : S, x.1 * y.2 * c = y.1 * x.2 * c := by rw r_eq_r' S; refl end localization /-- The localization of a `comm_monoid` at one of its submonoids (as a quotient type). -/ @[to_additive add_localization "The localization of an `add_comm_monoid` at one of its submonoids (as a quotient type)."] def localization := (localization.r S).quotient namespace localization @[to_additive] instance inhabited : inhabited (localization S) := con.quotient.inhabited @[to_additive] instance : comm_monoid (localization S) := (r S).comm_monoid variables {S} /-- Given a `comm_monoid` `M` and submonoid `S`, `mk` sends `x : M`, `y ∈ S` to the equivalence class of `(x, y)` in the localization of `M` at `S`. -/ @[to_additive "Given an `add_comm_monoid` `M` and submonoid `S`, `mk` sends `x : M`, `y ∈ S` to the equivalence class of `(x, y)` in the localization of `M` at `S`."] def mk (x : M) (y : S) : localization S := (r S).mk' (x, y) @[elab_as_eliminator, to_additive] theorem ind {p : localization S → Prop} (H : ∀ (y : M × S), p (mk y.1 y.2)) (x) : p x := by rcases x; convert H x; exact prod.mk.eta.symm @[elab_as_eliminator, to_additive] theorem induction_on {p : localization S → Prop} (x) (H : ∀ (y : M × S), p (mk y.1 y.2)) : p x := ind H x @[elab_as_eliminator, to_additive] theorem induction_on₂ {p : localization S → localization S → Prop} (x y) (H : ∀ (x y : M × S), p (mk x.1 x.2) (mk y.1 y.2)) : p x y := induction_on x $ λ x, induction_on y $ H x @[elab_as_eliminator, to_additive] theorem induction_on₃ {p : localization S → localization S → localization S → Prop} (x y z) (H : ∀ (x y z : M × S), p (mk x.1 x.2) (mk y.1 y.2) (mk z.1 z.2)) : p x y z := induction_on₂ x y $ λ x y, induction_on z $ H x y @[to_additive] lemma one_rel (y : S) : r S 1 (y, y) := λ b hb, hb y @[to_additive] theorem r_of_eq {x y : M × S} (h : y.1 * x.2 = x.1 * y.2) : r S x y := r_iff_exists.2 ⟨1, by rw h⟩ end localization variables {S N} namespace monoid_hom /-- Makes a localization map from a `comm_monoid` hom satisfying the characteristic predicate. -/ @[to_additive "Makes a localization map from an `add_comm_monoid` hom satisfying the characteristic predicate."] def to_localization_map (f : M →* N) (H1 : ∀ y : S, is_unit (f y)) (H2 : ∀ z, ∃ x : M × S, z * f x.2 = f x.1) (H3 : ∀ x y, f x = f y ↔ ∃ c : S, x * c = y * c) : submonoid.localization_map S N := { map_units' := H1, surj' := H2, eq_iff_exists' := H3, .. f } end monoid_hom namespace submonoid namespace localization_map /-- Short for `to_monoid_hom`; used to apply a localization map as a function. -/ @[to_additive "Short for `to_add_monoid_hom`; used to apply a localization map as a function."] abbreviation to_map (f : localization_map S N) := f.to_monoid_hom @[to_additive, ext] lemma ext {f g : localization_map S N} (h : ∀ x, f.to_map x = g.to_map x) : f = g := by cases f; cases g; simp only; exact funext h attribute [ext] add_submonoid.localization_map.ext @[to_additive] lemma ext_iff {f g : localization_map S N} : f = g ↔ ∀ x, f.to_map x = g.to_map x := ⟨λ h x, h ▸ rfl, ext⟩ @[to_additive] lemma to_map_injective : function.injective (@localization_map.to_map _ _ S N _) := λ _ _ h, ext $ monoid_hom.ext_iff.1 h @[to_additive] lemma map_units (f : localization_map S N) (y : S) : is_unit (f.to_map y) := f.4 y @[to_additive] lemma surj (f : localization_map S N) (z : N) : ∃ x : M × S, z * f.to_map x.2 = f.to_map x.1 := f.5 z @[to_additive] lemma eq_iff_exists (f : localization_map S N) {x y} : f.to_map x = f.to_map y ↔ ∃ c : S, x * c = y * c := f.6 x y /-- Given a localization map `f : M →* N`, a section function sending `z : N` to some `(x, y) : M × S` such that `f x * (f y)⁻¹ = z`. -/ @[to_additive "Given a localization map `f : M →+ N`, a section function sending `z : N` to some `(x, y) : M × S` such that `f x - f y = z`."] noncomputable def sec (f : localization_map S N) (z : N) : M × S := classical.some $ f.surj z @[to_additive] lemma sec_spec {f : localization_map S N} (z : N) : z * f.to_map (f.sec z).2 = f.to_map (f.sec z).1 := classical.some_spec $ f.surj z @[to_additive] lemma sec_spec' {f : localization_map S N} (z : N) : f.to_map (f.sec z).1 = f.to_map (f.sec z).2 * z := by rw [mul_comm, sec_spec] /-- Given a monoid hom `f : M →* N` and submonoid `S ⊆ M` such that `f(S) ⊆ units N`, for all `w : M, z : N` and `y ∈ S`, we have `w * (f y)⁻¹ = z ↔ w = f y * z`. -/ @[to_additive "Given an add_monoid hom `f : M →+ N` and submonoid `S ⊆ M` such that `f(S) ⊆ add_units N`, for all `w : M, z : N` and `y ∈ S`, we have `w - f y = z ↔ w = f y + z`."] lemma mul_inv_left {f : M →* N} (h : ∀ y : S, is_unit (f y)) (y : S) (w z) : w * ↑(is_unit.lift_right (f.mrestrict S) h y)⁻¹ = z ↔ w = f y * z := by rw mul_comm; convert units.inv_mul_eq_iff_eq_mul _; exact (is_unit.coe_lift_right (f.mrestrict S) h _).symm /-- Given a monoid hom `f : M →* N` and submonoid `S ⊆ M` such that `f(S) ⊆ units N`, for all `w : M, z : N` and `y ∈ S`, we have `z = w * (f y)⁻¹ ↔ z * f y = w`. -/ @[to_additive "Given an add_monoid hom `f : M →+ N` and submonoid `S ⊆ M` such that `f(S) ⊆ add_units N`, for all `w : M, z : N` and `y ∈ S`, we have `z = w - f y ↔ z + f y = w`."] lemma mul_inv_right {f : M →* N} (h : ∀ y : S, is_unit (f y)) (y : S) (w z) : z = w * ↑(is_unit.lift_right (f.mrestrict S) h y)⁻¹ ↔ z * f y = w := by rw [eq_comm, mul_inv_left h, mul_comm, eq_comm] /-- Given a monoid hom `f : M →* N` and submonoid `S ⊆ M` such that `f(S) ⊆ units N`, for all `x₁ x₂ : M` and `y₁, y₂ ∈ S`, we have `f x₁ * (f y₁)⁻¹ = f x₂ * (f y₂)⁻¹ ↔ f (x₁ * y₂) = f (x₂ * y₁)`. -/ @[simp, to_additive "Given an add_monoid hom `f : M →+ N` and submonoid `S ⊆ M` such that `f(S) ⊆ add_units N`, for all `x₁ x₂ : M` and `y₁, y₂ ∈ S`, we have `f x₁ - f y₁ = f x₂ - f y₂ ↔ f (x₁ + y₂) = f (x₂ + y₁)`."] lemma mul_inv {f : M →* N} (h : ∀ y : S, is_unit (f y)) {x₁ x₂} {y₁ y₂ : S} : f x₁ * ↑(is_unit.lift_right (f.mrestrict S) h y₁)⁻¹ = f x₂ * ↑(is_unit.lift_right (f.mrestrict S) h y₂)⁻¹ ↔ f (x₁ * y₂) = f (x₂ * y₁) := by rw [mul_inv_right h, mul_assoc, mul_comm _ (f y₂), ←mul_assoc, mul_inv_left h, mul_comm x₂, f.map_mul, f.map_mul] /-- Given a monoid hom `f : M →* N` and submonoid `S ⊆ M` such that `f(S) ⊆ units N`, for all `y, z ∈ S`, we have `(f y)⁻¹ = (f z)⁻¹ → f y = f z`. -/ @[to_additive "Given an add_monoid hom `f : M →+ N` and submonoid `S ⊆ M` such that `f(S) ⊆ add_units N`, for all `y, z ∈ S`, we have `- (f y) = - (f z) → f y = f z`."] lemma inv_inj {f : M →* N} (hf : ∀ y : S, is_unit (f y)) {y z} (h : (is_unit.lift_right (f.mrestrict S) hf y)⁻¹ = (is_unit.lift_right (f.mrestrict S) hf z)⁻¹) : f y = f z := by rw [←mul_one (f y), eq_comm, ←mul_inv_left hf y (f z) 1, h]; convert units.inv_mul _; exact (is_unit.coe_lift_right (f.mrestrict S) hf _).symm /-- Given a monoid hom `f : M →* N` and submonoid `S ⊆ M` such that `f(S) ⊆ units N`, for all `y ∈ S`, `(f y)⁻¹` is unique. -/ @[to_additive "Given an add_monoid hom `f : M →+ N` and submonoid `S ⊆ M` such that `f(S) ⊆ add_units N`, for all `y ∈ S`, `- (f y)` is unique."] lemma inv_unique {f : M →* N} (h : ∀ y : S, is_unit (f y)) {y : S} {z} (H : f y * z = 1) : ↑(is_unit.lift_right (f.mrestrict S) h y)⁻¹ = z := by rw [←one_mul ↑(_)⁻¹, mul_inv_left, ←H] variables (f : localization_map S N) @[to_additive] lemma map_right_cancel {x y} {c : S} (h : f.to_map (c * x) = f.to_map (c * y)) : f.to_map x = f.to_map y := begin rw [f.to_map.map_mul, f.to_map.map_mul] at h, cases f.map_units c with u hu, rw ←hu at h, exact (units.mul_right_inj u).1 h, end @[to_additive] lemma map_left_cancel {x y} {c : S} (h : f.to_map (x * c) = f.to_map (y * c)) : f.to_map x = f.to_map y := f.map_right_cancel $ by rw [mul_comm _ x, mul_comm _ y, h] /-- Given a localization map `f : M →* N`, the surjection sending `(x, y) : M × S` to `f x * (f y)⁻¹`. -/ @[to_additive "Given a localization map `f : M →+ N`, the surjection sending `(x, y) : M × S` to `f x - f y`."] noncomputable def mk' (f : localization_map S N) (x : M) (y : S) : N := f.to_map x * ↑(is_unit.lift_right (f.to_map.mrestrict S) f.map_units y)⁻¹ @[to_additive] lemma mk'_mul (x₁ x₂ : M) (y₁ y₂ : S) : f.mk' (x₁ * x₂) (y₁ * y₂) = f.mk' x₁ y₁ * f.mk' x₂ y₂ := (mul_inv_left f.map_units _ _ _).2 $ show _ = _ * (_ * _ * (_ * _)), by rw [←mul_assoc, ←mul_assoc, mul_inv_right f.map_units, mul_assoc, mul_assoc, mul_comm _ (f.to_map x₂), ←mul_assoc, ←mul_assoc, mul_inv_right f.map_units, submonoid.coe_mul, f.to_map.map_mul, f.to_map.map_mul]; ac_refl @[to_additive] lemma mk'_one (x) : f.mk' x (1 : S) = f.to_map x := by rw [mk', monoid_hom.map_one]; exact mul_one _ /-- Given a localization map `f : M →* N` for a submonoid `S ⊆ M`, for all `z : N` we have that if `x : M, y ∈ S` are such that `z * f y = f x`, then `f x * (f y)⁻¹ = z`. -/ @[simp, to_additive "Given a localization map `f : M →+ N` for a submonoid `S ⊆ M`, for all `z : N` we have that if `x : M, y ∈ S` are such that `z + f y = f x`, then `f x - f y = z`."] lemma mk'_sec (z : N) : f.mk' (f.sec z).1 (f.sec z).2 = z := show _ * _ = _, by rw [←sec_spec, mul_inv_left, mul_comm] @[to_additive] lemma mk'_surjective (z : N) : ∃ x (y : S), f.mk' x y = z := ⟨(f.sec z).1, (f.sec z).2, f.mk'_sec z⟩ @[to_additive] lemma mk'_spec (x) (y : S) : f.mk' x y * f.to_map y = f.to_map x := show _ * _ * _ = _, by rw [mul_assoc, mul_comm _ (f.to_map y), ←mul_assoc, mul_inv_left, mul_comm] @[to_additive] lemma mk'_spec' (x) (y : S) : f.to_map y * f.mk' x y = f.to_map x := by rw [mul_comm, mk'_spec] @[to_additive] theorem eq_mk'_iff_mul_eq {x} {y : S} {z} : z = f.mk' x y ↔ z * f.to_map y = f.to_map x := ⟨λ H, by rw [H, mk'_spec], λ H, by erw [mul_inv_right, H]; refl⟩ @[to_additive] theorem mk'_eq_iff_eq_mul {x} {y : S} {z} : f.mk' x y = z ↔ f.to_map x = z * f.to_map y := by rw [eq_comm, eq_mk'_iff_mul_eq, eq_comm] @[to_additive] lemma mk'_eq_iff_eq {x₁ x₂} {y₁ y₂ : S} : f.mk' x₁ y₁ = f.mk' x₂ y₂ ↔ f.to_map (x₁ * y₂) = f.to_map (x₂ * y₁) := ⟨λ H, by rw [f.to_map.map_mul, f.mk'_eq_iff_eq_mul.1 H, mul_assoc, mul_comm (f.to_map _), ←mul_assoc, mk'_spec, f.to_map.map_mul], λ H, by rw [mk'_eq_iff_eq_mul, mk', mul_assoc, mul_comm _ (f.to_map y₁), ←mul_assoc, ←f.to_map.map_mul, ←H, f.to_map.map_mul, mul_inv_right f.map_units]⟩ @[to_additive] protected lemma eq {a₁ b₁} {a₂ b₂ : S} : f.mk' a₁ a₂ = f.mk' b₁ b₂ ↔ ∃ c : S, a₁ * b₂ * c = b₁ * a₂ * c := f.mk'_eq_iff_eq.trans $ f.eq_iff_exists @[to_additive] protected lemma eq' {a₁ b₁} {a₂ b₂ : S} : f.mk' a₁ a₂ = f.mk' b₁ b₂ ↔ localization.r S (a₁, a₂) (b₁, b₂) := by rw [f.eq, localization.r_iff_exists] @[to_additive] lemma eq_iff_eq (g : localization_map S P) {x y} : f.to_map x = f.to_map y ↔ g.to_map x = g.to_map y := f.eq_iff_exists.trans g.eq_iff_exists.symm @[to_additive] lemma mk'_eq_iff_mk'_eq (g : localization_map S P) {x₁ x₂} {y₁ y₂ : S} : f.mk' x₁ y₁ = f.mk' x₂ y₂ ↔ g.mk' x₁ y₁ = g.mk' x₂ y₂ := f.eq'.trans g.eq'.symm /-- Given a localization map `f : M →* N` for a submonoid `S ⊆ M`, for all `x₁ : M` and `y₁ ∈ S`, if `x₂ : M, y₂ ∈ S` are such that `f x₁ * (f y₁)⁻¹ * f y₂ = f x₂`, then there exists `c ∈ S` such that `x₁ * y₂ * c = x₂ * y₁ * c`. -/ @[to_additive "Given a localization map `f : M →+ N` for a submonoid `S ⊆ M`, for all `x₁ : M` and `y₁ ∈ S`, if `x₂ : M, y₂ ∈ S` are such that `(f x₁ - f y₁) + f y₂ = f x₂`, then there exists `c ∈ S` such that `x₁ + y₂ + c = x₂ + y₁ + c`."] lemma exists_of_sec_mk' (x) (y : S) : ∃ c : S, x * (f.sec $ f.mk' x y).2 * c = (f.sec $ f.mk' x y).1 * y * c := f.eq_iff_exists.1 $ f.mk'_eq_iff_eq.1 $ (mk'_sec _ _).symm @[to_additive] lemma mk'_eq_of_eq {a₁ b₁ : M} {a₂ b₂ : S} (H : b₁ * a₂ = a₁ * b₂) : f.mk' a₁ a₂ = f.mk' b₁ b₂ := f.mk'_eq_iff_eq.2 $ H ▸ rfl @[simp, to_additive] lemma mk'_self' (y : S) : f.mk' (y : M) y = 1 := show _ * _ = _, by rw [mul_inv_left, mul_one] @[simp, to_additive] lemma mk'_self (x) (H : x ∈ S) : f.mk' x ⟨x, H⟩ = 1 := by convert mk'_self' _ _; refl @[to_additive] lemma mul_mk'_eq_mk'_of_mul (x₁ x₂) (y : S) : f.to_map x₁ * f.mk' x₂ y = f.mk' (x₁ * x₂) y := by rw [←mk'_one, ←mk'_mul, one_mul] @[to_additive] lemma mk'_mul_eq_mk'_of_mul (x₁ x₂) (y : S) : f.mk' x₂ y * f.to_map x₁ = f.mk' (x₁ * x₂) y := by rw [mul_comm, mul_mk'_eq_mk'_of_mul] @[to_additive] lemma mul_mk'_one_eq_mk' (x) (y : S) : f.to_map x * f.mk' 1 y = f.mk' x y := by rw [mul_mk'_eq_mk'_of_mul, mul_one] @[simp, to_additive] lemma mk'_mul_cancel_right (x : M) (y : S) : f.mk' (x * y) y = f.to_map x := by rw [←mul_mk'_one_eq_mk', f.to_map.map_mul, mul_assoc, mul_mk'_one_eq_mk', mk'_self', mul_one] @[to_additive] lemma mk'_mul_cancel_left (x) (y : S) : f.mk' ((y : M) * x) y = f.to_map x := by rw [mul_comm, mk'_mul_cancel_right] @[to_additive] lemma is_unit_comp (j : N →* P) (y : S) : is_unit (j.comp f.to_map y) := ⟨units.map j $ is_unit.lift_right (f.to_map.mrestrict S) f.map_units y, show j _ = j _, from congr_arg j $ (is_unit.coe_lift_right (f.to_map.mrestrict S) f.map_units _)⟩ variables {g : M →* P} /-- Given a localization map `f : M →* N` for a submonoid `S ⊆ M` and a map of `comm_monoid`s `g : M →* P` such that `g(S) ⊆ units P`, `f x = f y → g x = g y` for all `x y : M`. -/ @[to_additive "Given a localization map `f : M →+ N` for a submonoid `S ⊆ M` and a map of `add_comm_monoid`s `g : M →+ P` such that `g(S) ⊆ add_units P`, `f x = f y → g x = g y` for all `x y : M`."] lemma eq_of_eq (hg : ∀ y : S, is_unit (g y)) {x y} (h : f.to_map x = f.to_map y) : g x = g y := begin obtain ⟨c, hc⟩ := f.eq_iff_exists.1 h, rw [←mul_one (g x), ←is_unit.mul_lift_right_inv (g.mrestrict S) hg c], show _ * (g c * _) = _, rw [←mul_assoc, ←g.map_mul, hc, mul_inv_left hg, g.map_mul, mul_comm], end /-- Given `comm_monoid`s `M, P`, localization maps `f : M →* N, k : P →* Q` for submonoids `S, T` respectively, and `g : M →* P` such that `g(S) ⊆ T`, `f x = f y` implies `k (g x) = k (g y)`. -/ @[to_additive "Given `add_comm_monoid`s `M, P`, localization maps `f : M →+ N, k : P →+ Q` for submonoids `S, T` respectively, and `g : M →+ P` such that `g(S) ⊆ T`, `f x = f y` implies `k (g x) = k (g y)`."] lemma comp_eq_of_eq {T : submonoid P} {Q : Type*} [comm_monoid Q] (hg : ∀ y : S, g y ∈ T) (k : localization_map T Q) {x y} (h : f.to_map x = f.to_map y) : k.to_map (g x) = k.to_map (g y) := f.eq_of_eq (λ y : S, show is_unit (k.to_map.comp g y), from k.map_units ⟨g y, hg y⟩) h variables (hg : ∀ y : S, is_unit (g y)) /-- Given a localization map `f : M →* N` for a submonoid `S ⊆ M` and a map of `comm_monoid`s `g : M →* P` such that `g y` is invertible for all `y : S`, the homomorphism induced from `N` to `P` sending `z : N` to `g x * (g y)⁻¹`, where `(x, y) : M × S` are such that `z = f x * (f y)⁻¹`. -/ @[to_additive "Given a localization map `f : M →+ N` for a submonoid `S ⊆ M` and a map of `add_comm_monoid`s `g : M →+ P` such that `g y` is invertible for all `y : S`, the homomorphism induced from `N` to `P` sending `z : N` to `g x - g y`, where `(x, y) : M × S` are such that `z = f x - f y`."] noncomputable def lift : N →* P := { to_fun := λ z, g (f.sec z).1 * ↑(is_unit.lift_right (g.mrestrict S) hg (f.sec z).2)⁻¹, map_one' := by rw [mul_inv_left, mul_one]; exact f.eq_of_eq hg (by rw [←sec_spec, one_mul]), map_mul' := λ x y, begin rw [mul_inv_left hg, ←mul_assoc, ←mul_assoc, mul_inv_right hg, mul_comm _ (g (f.sec y).1), ←mul_assoc, ←mul_assoc, mul_inv_right hg], repeat { rw ←g.map_mul }, exact f.eq_of_eq hg (by repeat { rw f.to_map.map_mul <|> rw sec_spec' }; ac_refl) end } variables {S g} /-- Given a localization map `f : M →* N` for a submonoid `S ⊆ M` and a map of `comm_monoid`s `g : M →* P` such that `g y` is invertible for all `y : S`, the homomorphism induced from `N` to `P` maps `f x * (f y)⁻¹` to `g x * (g y)⁻¹` for all `x : M, y ∈ S`. -/ @[to_additive "Given a localization map `f : M →+ N` for a submonoid `S ⊆ M` and a map of `add_comm_monoid`s `g : M →+ P` such that `g y` is invertible for all `y : S`, the homomorphism induced from `N` to `P` maps `f x - f y` to `g x - g y` for all `x : M, y ∈ S`."] lemma lift_mk' (x y) : f.lift hg (f.mk' x y) = g x * ↑(is_unit.lift_right (g.mrestrict S) hg y)⁻¹ := (mul_inv hg).2 $ f.eq_of_eq hg $ by rw [f.to_map.map_mul, f.to_map.map_mul, sec_spec', mul_assoc, f.mk'_spec, mul_comm] /-- Given a localization map `f : M →* N` for a submonoid `S ⊆ M`, if a `comm_monoid` map `g : M →* P` induces a map `f.lift hg : N →* P` then for all `z : N, v : P`, we have `f.lift hg z = v ↔ g x = g y * v`, where `x : M, y ∈ S` are such that `z * f y = f x`. -/ @[to_additive "Given a localization map `f : M →+ N` for a submonoid `S ⊆ M`, if an `add_comm_monoid` map `g : M →+ P` induces a map `f.lift hg : N →+ P` then for all `z : N, v : P`, we have `f.lift hg z = v ↔ g x = g y + v`, where `x : M, y ∈ S` are such that `z + f y = f x`."] lemma lift_spec (z v) : f.lift hg z = v ↔ g (f.sec z).1 = g (f.sec z).2 * v := mul_inv_left hg _ _ v /-- Given a localization map `f : M →* N` for a submonoid `S ⊆ M`, if a `comm_monoid` map `g : M →* P` induces a map `f.lift hg : N →* P` then for all `z : N, v w : P`, we have `f.lift hg z * w = v ↔ g x * w = g y * v`, where `x : M, y ∈ S` are such that `z * f y = f x`. -/ @[to_additive "Given a localization map `f : M →+ N` for a submonoid `S ⊆ M`, if an `add_comm_monoid` map `g : M →+ P` induces a map `f.lift hg : N →+ P` then for all `z : N, v w : P`, we have `f.lift hg z + w = v ↔ g x + w = g y + v`, where `x : M, y ∈ S` are such that `z + f y = f x`."] lemma lift_spec_mul (z w v) : f.lift hg z * w = v ↔ g (f.sec z).1 * w = g (f.sec z).2 * v := begin rw mul_comm, show _ * (_ * _) = _ ↔ _, rw [←mul_assoc, mul_inv_left hg, mul_comm], end @[to_additive] lemma lift_mk'_spec (x v) (y : S) : f.lift hg (f.mk' x y) = v ↔ g x = g y * v := by rw f.lift_mk' hg; exact mul_inv_left hg _ _ _ /-- Given a localization map `f : M →* N` for a submonoid `S ⊆ M`, if a `comm_monoid` map `g : M →* P` induces a map `f.lift hg : N →* P` then for all `z : N`, we have `f.lift hg z * g y = g x`, where `x : M, y ∈ S` are such that `z * f y = f x`. -/ @[to_additive "Given a localization map `f : M →+ N` for a submonoid `S ⊆ M`, if an `add_comm_monoid` map `g : M →+ P` induces a map `f.lift hg : N →+ P` then for all `z : N`, we have `f.lift hg z + g y = g x`, where `x : M, y ∈ S` are such that `z + f y = f x`."] lemma lift_mul_right (z) : f.lift hg z * g (f.sec z).2 = g (f.sec z).1 := show _ * _ * _ = _, by erw [mul_assoc, is_unit.lift_right_inv_mul, mul_one] /-- Given a localization map `f : M →* N` for a submonoid `S ⊆ M`, if a `comm_monoid` map `g : M →* P` induces a map `f.lift hg : N →* P` then for all `z : N`, we have `g y * f.lift hg z = g x`, where `x : M, y ∈ S` are such that `z * f y = f x`. -/ @[to_additive "Given a localization map `f : M →+ N` for a submonoid `S ⊆ M`, if an `add_comm_monoid` map `g : M →+ P` induces a map `f.lift hg : N →+ P` then for all `z : N`, we have `g y + f.lift hg z = g x`, where `x : M, y ∈ S` are such that `z + f y = f x`."] lemma lift_mul_left (z) : g (f.sec z).2 * f.lift hg z = g (f.sec z).1 := by rw [mul_comm, lift_mul_right] @[simp, to_additive] lemma lift_eq (x : M) : f.lift hg (f.to_map x) = g x := by rw [lift_spec, ←g.map_mul]; exact f.eq_of_eq hg (by rw [sec_spec', f.to_map.map_mul]) @[to_additive] lemma lift_eq_iff {x y : M × S} : f.lift hg (f.mk' x.1 x.2) = f.lift hg (f.mk' y.1 y.2) ↔ g (x.1 * y.2) = g (y.1 * x.2) := by rw [lift_mk', lift_mk', mul_inv hg] @[simp, to_additive] lemma lift_comp : (f.lift hg).comp f.to_map = g := by ext; exact f.lift_eq hg _ @[simp, to_additive] lemma lift_of_comp (j : N →* P) : f.lift (f.is_unit_comp j) = j := begin ext, rw lift_spec, show j _ = j _ * _, erw [←j.map_mul, sec_spec'], end @[to_additive] lemma epic_of_localization_map {j k : N →* P} (h : ∀ a, j.comp f.to_map a = k.comp f.to_map a) : j = k := begin rw [←f.lift_of_comp j, ←f.lift_of_comp k], congr' 1 with x, exact h x, end @[to_additive] lemma lift_unique {j : N →* P} (hj : ∀ x, j (f.to_map x) = g x) : f.lift hg = j := begin ext, rw [lift_spec, ←hj, ←hj, ←j.map_mul], apply congr_arg, rw ←sec_spec', end @[simp, to_additive] lemma lift_id (x) : f.lift f.map_units x = x := monoid_hom.ext_iff.1 (f.lift_of_comp $ monoid_hom.id N) x /-- Given two localization maps `f : M →* N, k : M →* P` for a submonoid `S ⊆ M`, the hom from `P` to `N` induced by `f` is left inverse to the hom from `N` to `P` induced by `k`. -/ @[simp, to_additive] lemma lift_left_inverse {k : localization_map S P} (z : N) : k.lift f.map_units (f.lift k.map_units z) = z := begin rw lift_spec, cases f.surj z with x hx, conv_rhs {congr, skip, rw f.eq_mk'_iff_mul_eq.2 hx}, rw [mk', ←mul_assoc, mul_inv_right f.map_units, ←f.to_map.map_mul, ←f.to_map.map_mul], apply k.eq_of_eq f.map_units, rw [k.to_map.map_mul, k.to_map.map_mul, ←sec_spec, mul_assoc, lift_spec_mul], repeat { rw ←k.to_map.map_mul }, apply f.eq_of_eq k.map_units, repeat { rw f.to_map.map_mul }, rw [sec_spec', ←hx], ac_refl, end @[to_additive] lemma lift_surjective_iff : function.surjective (f.lift hg) ↔ ∀ v : P, ∃ x : M × S, v * g x.2 = g x.1 := begin split, { intros H v, obtain ⟨z, hz⟩ := H v, obtain ⟨x, hx⟩ := f.surj z, use x, rw [←hz, f.eq_mk'_iff_mul_eq.2 hx, lift_mk', mul_assoc, mul_comm _ (g ↑x.2)], erw [is_unit.mul_lift_right_inv (g.mrestrict S) hg, mul_one] }, { intros H v, obtain ⟨x, hx⟩ := H v, use f.mk' x.1 x.2, rw [lift_mk', mul_inv_left hg, mul_comm, ←hx] } end @[to_additive] lemma lift_injective_iff : function.injective (f.lift hg) ↔ ∀ x y, f.to_map x = f.to_map y ↔ g x = g y := begin split, { intros H x y, split, { exact f.eq_of_eq hg }, { intro h, rw [←f.lift_eq hg, ←f.lift_eq hg] at h, exact H h }}, { intros H z w h, obtain ⟨x, hx⟩ := f.surj z, obtain ⟨y, hy⟩ := f.surj w, rw [←f.mk'_sec z, ←f.mk'_sec w], exact (mul_inv f.map_units).2 ((H _ _).2 $ (mul_inv hg).1 h) } end variables {T : submonoid P} (hy : ∀ y : S, g y ∈ T) {Q : Type*} [comm_monoid Q] (k : localization_map T Q) /-- Given a `comm_monoid` homomorphism `g : M →* P` where for submonoids `S ⊆ M, T ⊆ P` we have `g(S) ⊆ T`, the induced monoid homomorphism from the localization of `M` at `S` to the localization of `P` at `T`: if `f : M →* N` and `k : P →* Q` are localization maps for `S` and `T` respectively, we send `z : N` to `k (g x) * (k (g y))⁻¹`, where `(x, y) : M × S` are such that `z = f x * (f y)⁻¹`. -/ @[to_additive "Given a `add_comm_monoid` homomorphism `g : M →+ P` where for submonoids `S ⊆ M, T ⊆ P` we have `g(S) ⊆ T`, the induced add_monoid homomorphism from the localization of `M` at `S` to the localization of `P` at `T`: if `f : M →+ N` and `k : P →+ Q` are localization maps for `S` and `T` respectively, we send `z : N` to `k (g x) - k (g y)`, where `(x, y) : M × S` are such that `z = f x - f y`."] noncomputable def map : N →* Q := @lift _ _ _ _ _ _ _ f (k.to_map.comp g) $ λ y, k.map_units ⟨g y, hy y⟩ variables {k} @[to_additive] lemma map_eq (x) : f.map hy k (f.to_map x) = k.to_map (g x) := f.lift_eq (λ y, k.map_units ⟨g y, hy y⟩) x @[simp, to_additive] lemma map_comp : (f.map hy k).comp f.to_map = k.to_map.comp g := f.lift_comp $ λ y, k.map_units ⟨g y, hy y⟩ @[to_additive] lemma map_mk' (x) (y : S) : f.map hy k (f.mk' x y) = k.mk' (g x) ⟨g y, hy y⟩ := begin rw [map, lift_mk', mul_inv_left], { show k.to_map (g x) = k.to_map (g y) * _, rw mul_mk'_eq_mk'_of_mul, exact (k.mk'_mul_cancel_left (g x) ⟨(g y), hy y⟩).symm }, end /-- Given localization maps `f : M →* N, k : P →* Q` for submonoids `S, T` respectively, if a `comm_monoid` homomorphism `g : M →* P` induces a `f.map hy k : N →* Q`, then for all `z : N`, `u : Q`, we have `f.map hy k z = u ↔ k (g x) = k (g y) * u` where `x : M, y ∈ S` are such that `z * f y = f x`. -/ @[to_additive "Given localization maps `f : M →+ N, k : P →+ Q` for submonoids `S, T` respectively, if an `add_comm_monoid` homomorphism `g : M →+ P` induces a `f.map hy k : N →+ Q`, then for all `z : N`, `u : Q`, we have `f.map hy k z = u ↔ k (g x) = k (g y) + u` where `x : M, y ∈ S` are such that `z + f y = f x`."] lemma map_spec (z u) : f.map hy k z = u ↔ k.to_map (g (f.sec z).1) = k.to_map (g (f.sec z).2) * u := f.lift_spec (λ y, k.map_units ⟨g y, hy y⟩) _ _ /-- Given localization maps `f : M →* N, k : P →* Q` for submonoids `S, T` respectively, if a `comm_monoid` homomorphism `g : M →* P` induces a `f.map hy k : N →* Q`, then for all `z : N`, we have `f.map hy k z * k (g y) = k (g x)` where `x : M, y ∈ S` are such that `z * f y = f x`. -/ @[to_additive "Given localization maps `f : M →+ N, k : P →+ Q` for submonoids `S, T` respectively, if an `add_comm_monoid` homomorphism `g : M →+ P` induces a `f.map hy k : N →+ Q`, then for all `z : N`, we have `f.map hy k z + k (g y) = k (g x)` where `x : M, y ∈ S` are such that `z + f y = f x`."] lemma map_mul_right (z) : f.map hy k z * (k.to_map (g (f.sec z).2)) = k.to_map (g (f.sec z).1) := f.lift_mul_right (λ y, k.map_units ⟨g y, hy y⟩) _ /-- Given localization maps `f : M →* N, k : P →* Q` for submonoids `S, T` respectively, if a `comm_monoid` homomorphism `g : M →* P` induces a `f.map hy k : N →* Q`, then for all `z : N`, we have `k (g y) * f.map hy k z = k (g x)` where `x : M, y ∈ S` are such that `z * f y = f x`. -/ @[to_additive "Given localization maps `f : M →+ N, k : P →+ Q` for submonoids `S, T` respectively, if an `add_comm_monoid` homomorphism `g : M →+ P` induces a `f.map hy k : N →+ Q`, then for all `z : N`, we have `k (g y) + f.map hy k z = k (g x)` where `x : M, y ∈ S` are such that `z + f y = f x`."] lemma map_mul_left (z) : k.to_map (g (f.sec z).2) * f.map hy k z = k.to_map (g (f.sec z).1) := by rw [mul_comm, f.map_mul_right] @[simp, to_additive] lemma map_id (z : N) : f.map (λ y, show monoid_hom.id M y ∈ S, from y.2) f z = z := f.lift_id z /-- If `comm_monoid` homs `g : M →* P, l : P →* A` induce maps of localizations, the composition of the induced maps equals the map of localizations induced by `l ∘ g`. -/ @[to_additive "If `add_comm_monoid` homs `g : M →+ P, l : P →+ A` induce maps of localizations, the composition of the induced maps equals the map of localizations induced by `l ∘ g`."] lemma map_comp_map {A : Type*} [comm_monoid A] {U : submonoid A} {R} [comm_monoid R] (j : localization_map U R) {l : P →* A} (hl : ∀ w : T, l w ∈ U) : (k.map hl j).comp (f.map hy k) = f.map (λ x, show l.comp g x ∈ U, from hl ⟨g x, hy x⟩) j := begin ext z, show j.to_map _ * _ = j.to_map (l _) * _, { rw [mul_inv_left, ←mul_assoc, mul_inv_right], show j.to_map _ * j.to_map (l (g _)) = j.to_map (l _) * _, rw [←j.to_map.map_mul, ←j.to_map.map_mul, ←l.map_mul, ←l.map_mul], exact k.comp_eq_of_eq hl j (by rw [k.to_map.map_mul, k.to_map.map_mul, sec_spec', mul_assoc, map_mul_right]) }, end /-- If `comm_monoid` homs `g : M →* P, l : P →* A` induce maps of localizations, the composition of the induced maps equals the map of localizations induced by `l ∘ g`. -/ @[to_additive "If `add_comm_monoid` homs `g : M →+ P, l : P →+ A` induce maps of localizations, the composition of the induced maps equals the map of localizations induced by `l ∘ g`."] lemma map_map {A : Type*} [comm_monoid A] {U : submonoid A} {R} [comm_monoid R] (j : localization_map U R) {l : P →* A} (hl : ∀ w : T, l w ∈ U) (x) : k.map hl j (f.map hy k x) = f.map (λ x, show l.comp g x ∈ U, from hl ⟨g x, hy x⟩) j x := by rw ←f.map_comp_map hy j hl; refl section away_map variables (x : M) /-- Given `x : M`, the type of `comm_monoid` homomorphisms `f : M →* N` such that `N` is isomorphic to the localization of `M` at the submonoid generated by `x`. -/ @[reducible, to_additive "Given `x : M`, the type of `add_comm_monoid` homomorphisms `f : M →+ N` such that `N` is isomorphic to the localization of `M` at the submonoid generated by `x`."] def away_map (N' : Type*) [comm_monoid N'] := localization_map (powers x) N' variables (F : away_map x N) /-- Given `x : M` and a localization map `F : M →* N` away from `x`, `inv_self` is `(F x)⁻¹`. -/ noncomputable def away_map.inv_self : N := F.mk' 1 ⟨x, mem_powers _⟩ /-- Given `x : M`, a localization map `F : M →* N` away from `x`, and a map of `comm_monoid`s `g : M →* P` such that `g x` is invertible, the homomorphism induced from `N` to `P` sending `z : N` to `g y * (g x)⁻ⁿ`, where `y : M, n : ℕ` are such that `z = F y * (F x)⁻ⁿ`. -/ noncomputable def away_map.lift (hg : is_unit (g x)) : N →* P := F.lift $ λ y, show is_unit (g y.1), begin obtain ⟨n, hn⟩ := y.2, rw [←hn, g.map_pow], exact is_unit.map (monoid_hom.of $ ((^ n) : P → P)) hg, end @[simp] lemma away_map.lift_eq (hg : is_unit (g x)) (a : M) : F.lift x hg (F.to_map a) = g a := lift_eq _ _ _ @[simp] lemma away_map.lift_comp (hg : is_unit (g x)) : (F.lift x hg).comp F.to_map = g := lift_comp _ _ /-- Given `x y : M` and localization maps `F : M →* N, G : M →* P` away from `x` and `x * y` respectively, the homomorphism induced from `N` to `P`. -/ noncomputable def away_to_away_right (y : M) (G : away_map (x * y) P) : N →* P := F.lift x $ show is_unit (G.to_map x), from is_unit_of_mul_eq_one (G.to_map x) (G.mk' y ⟨x * y, mem_powers _⟩) $ by rw [mul_mk'_eq_mk'_of_mul, mk'_self] end away_map end localization_map end submonoid namespace add_submonoid namespace localization_map section away_map variables {A : Type*} [add_comm_monoid A] (x : A) {B : Type*} [add_comm_monoid B] (F : away_map x B) {C : Type*} [add_comm_monoid C] {g : A →+ C} /-- Given `x : A` and a localization map `F : A →+ B` away from `x`, `neg_self` is `- (F x)`. -/ noncomputable def away_map.neg_self : B := F.mk' 0 ⟨x, mem_multiples _⟩ /-- Given `x : A`, a localization map `F : A →+ B` away from `x`, and a map of `add_comm_monoid`s `g : A →+ C` such that `g x` is invertible, the homomorphism induced from `B` to `C` sending `z : B` to `g y - n • g x`, where `y : A, n : ℕ` are such that `z = F y - n • F x`. -/ noncomputable def away_map.lift (hg : is_add_unit (g x)) : B →+ C := F.lift $ λ y, show is_add_unit (g y.1), begin obtain ⟨n, hn⟩ := y.2, rw [←hn, g.map_nsmul], exact is_add_unit.map (add_monoid_hom.of $ (λ x, n •ℕ x)) hg, end @[simp] lemma away_map.lift_eq (hg : is_add_unit (g x)) (a : A) : F.lift x hg (F.to_map a) = g a := lift_eq _ _ _ @[simp] lemma away_map.lift_comp (hg : is_add_unit (g x)) : (F.lift x hg).comp F.to_map = g := lift_comp _ _ /-- Given `x y : A` and localization maps `F : A →+ B, G : A →+ C` away from `x` and `x + y` respectively, the homomorphism induced from `B` to `C`. -/ noncomputable def away_to_away_right (y : A) (G : away_map (x + y) C) : B →+ C := F.lift x $ show is_add_unit (G.to_map x), from is_add_unit_of_add_eq_zero (G.to_map x) (G.mk' y ⟨x + y, mem_multiples _⟩) $ by rw [add_mk'_eq_mk'_of_add, mk'_self] end away_map end localization_map end add_submonoid namespace submonoid namespace localization_map variables (f : S.localization_map N) {g : M →* P} (hg : ∀ (y : S), is_unit (g y)) {T : submonoid P} {Q : Type*} [comm_monoid Q] /-- If `f : M →* N` and `k : M →* P` are localization maps for a submonoid `S`, we get an isomorphism of `N` and `P`. -/ @[to_additive "If `f : M →+ N` and `k : M →+ R` are localization maps for a submonoid `S`, we get an isomorphism of `N` and `R`."] noncomputable def mul_equiv_of_localizations (k : localization_map S P) : N ≃* P := ⟨f.lift k.map_units, k.lift f.map_units, f.lift_left_inverse, k.lift_left_inverse, monoid_hom.map_mul _⟩ @[simp, to_additive] lemma mul_equiv_of_localizations_apply {k : localization_map S P} {x} : f.mul_equiv_of_localizations k x = f.lift k.map_units x := rfl @[simp, to_additive] lemma mul_equiv_of_localizations_symm_apply {k : localization_map S P} {x} : (f.mul_equiv_of_localizations k).symm x = k.lift f.map_units x := rfl @[to_additive] lemma mul_equiv_of_localizations_symm_eq_mul_equiv_of_localizations {k : localization_map S P} : (k.mul_equiv_of_localizations f).symm = f.mul_equiv_of_localizations k := rfl /-- If `f : M →* N` is a localization map for a submonoid `S` and `k : N ≃* P` is an isomorphism of `comm_monoid`s, `k ∘ f` is a localization map for `M` at `S`. -/ @[to_additive "If `f : M →+ N` is a localization map for a submonoid `S` and `k : N ≃+ P` is an isomorphism of `add_comm_monoid`s, `k ∘ f` is a localization map for `M` at `S`."] def of_mul_equiv_of_localizations (k : N ≃* P) : localization_map S P := (k.to_monoid_hom.comp f.to_map).to_localization_map (λ y, is_unit_comp f k.to_monoid_hom y) (λ v, let ⟨z, hz⟩ := k.to_equiv.surjective v in let ⟨x, hx⟩ := f.surj z in ⟨x, show v * k _ = k _, by rw [←hx, k.map_mul, ←hz]; refl⟩) (λ x y, k.apply_eq_iff_eq.trans f.eq_iff_exists) @[simp, to_additive] lemma of_mul_equiv_of_localizations_apply {k : N ≃* P} (x) : (f.of_mul_equiv_of_localizations k).to_map x = k (f.to_map x) := rfl @[to_additive] lemma of_mul_equiv_of_localizations_eq {k : N ≃* P} : (f.of_mul_equiv_of_localizations k).to_map = k.to_monoid_hom.comp f.to_map := rfl @[to_additive] lemma symm_comp_of_mul_equiv_of_localizations_apply {k : N ≃* P} (x) : k.symm ((f.of_mul_equiv_of_localizations k).to_map x) = f.to_map x := k.symm_apply_apply (f.to_map x) @[to_additive] lemma symm_comp_of_mul_equiv_of_localizations_apply' {k : P ≃* N} (x) : k ((f.of_mul_equiv_of_localizations k.symm).to_map x) = f.to_map x := k.apply_symm_apply (f.to_map x) @[to_additive] lemma of_mul_equiv_of_localizations_eq_iff_eq {k : N ≃* P} {x y} : (f.of_mul_equiv_of_localizations k).to_map x = y ↔ f.to_map x = k.symm y := k.to_equiv.eq_symm_apply.symm @[to_additive add_equiv_of_localizations_right_inv] lemma mul_equiv_of_localizations_right_inv (k : localization_map S P) : f.of_mul_equiv_of_localizations (f.mul_equiv_of_localizations k) = k := to_map_injective $ f.lift_comp k.map_units @[to_additive add_equiv_of_localizations_right_inv_apply, simp] lemma mul_equiv_of_localizations_right_inv_apply {k : localization_map S P} {x} : (f.of_mul_equiv_of_localizations (f.mul_equiv_of_localizations k)).to_map x = k.to_map x := ext_iff.1 (f.mul_equiv_of_localizations_right_inv k) x @[to_additive] lemma mul_equiv_of_localizations_left_inv (k : N ≃* P) : f.mul_equiv_of_localizations (f.of_mul_equiv_of_localizations k) = k := mul_equiv.ext $ monoid_hom.ext_iff.1 $ f.lift_of_comp k.to_monoid_hom @[simp, to_additive] lemma mul_equiv_of_localizations_left_inv_apply {k : N ≃* P} (x) : f.mul_equiv_of_localizations (f.of_mul_equiv_of_localizations k) x = k x := by rw mul_equiv_of_localizations_left_inv @[simp, to_additive] lemma of_mul_equiv_of_localizations_id : f.of_mul_equiv_of_localizations (mul_equiv.refl N) = f := by ext; refl @[to_additive] lemma of_mul_equiv_of_localizations_comp {k : N ≃* P} {j : P ≃* Q} : (f.of_mul_equiv_of_localizations (k.trans j)).to_map = j.to_monoid_hom.comp (f.of_mul_equiv_of_localizations k).to_map := by ext; refl /-- Given `comm_monoid`s `M, P` and submonoids `S ⊆ M, T ⊆ P`, if `f : M →* N` is a localization map for `S` and `k : P ≃* M` is an isomorphism of `comm_monoid`s such that `k(T) = S`, `f ∘ k` is a localization map for `T`. -/ @[to_additive "Given `comm_monoid`s `M, P` and submonoids `S ⊆ M, T ⊆ P`, if `f : M →* N` is a localization map for `S` and `k : P ≃* M` is an isomorphism of `comm_monoid`s such that `k(T) = S`, `f ∘ k` is a localization map for `T`."] def of_mul_equiv_of_dom {k : P ≃* M} (H : T.map k.to_monoid_hom = S) : localization_map T N := let H' : S.comap k.to_monoid_hom = T := H ▸ (set_like.coe_injective $ T.1.preimage_image_eq k.to_equiv.injective) in (f.to_map.comp k.to_monoid_hom).to_localization_map (λ y, let ⟨z, hz⟩ := f.map_units ⟨k y, H ▸ set.mem_image_of_mem k y.2⟩ in ⟨z, hz⟩) (λ z, let ⟨x, hx⟩ := f.surj z in let ⟨v, hv⟩ := k.to_equiv.surjective x.1 in let ⟨w, hw⟩ := k.to_equiv.surjective x.2 in ⟨(v, ⟨w, H' ▸ show k w ∈ S, from hw.symm ▸ x.2.2⟩), show z * f.to_map (k.to_equiv w) = f.to_map (k.to_equiv v), by erw [hv, hw, hx]; refl⟩) (λ x y, show f.to_map _ = f.to_map _ ↔ _, by erw f.eq_iff_exists; exact ⟨λ ⟨c, hc⟩, let ⟨d, hd⟩ := k.to_equiv.surjective c in ⟨⟨d, H' ▸ show k d ∈ S, from hd.symm ▸ c.2⟩, by erw [←hd, ←k.map_mul, ←k.map_mul] at hc; exact k.to_equiv.injective hc⟩, λ ⟨c, hc⟩, ⟨⟨k c, H ▸ set.mem_image_of_mem k c.2⟩, by erw ←k.map_mul; rw [hc, k.map_mul]; refl⟩⟩) @[simp, to_additive] lemma of_mul_equiv_of_dom_apply {k : P ≃* M} (H : T.map k.to_monoid_hom = S) (x) : (f.of_mul_equiv_of_dom H).to_map x = f.to_map (k x) := rfl @[to_additive] lemma of_mul_equiv_of_dom_eq {k : P ≃* M} (H : T.map k.to_monoid_hom = S) : (f.of_mul_equiv_of_dom H).to_map = f.to_map.comp k.to_monoid_hom := rfl @[to_additive] lemma of_mul_equiv_of_dom_comp_symm {k : P ≃* M} (H : T.map k.to_monoid_hom = S) (x) : (f.of_mul_equiv_of_dom H).to_map (k.symm x) = f.to_map x := congr_arg f.to_map $ k.apply_symm_apply x @[to_additive] lemma of_mul_equiv_of_dom_comp {k : M ≃* P} (H : T.map k.symm.to_monoid_hom = S) (x) : (f.of_mul_equiv_of_dom H).to_map (k x) = f.to_map x := congr_arg f.to_map $ k.symm_apply_apply x /-- A special case of `f ∘ id = f`, `f` a localization map. -/ @[simp, to_additive "A special case of `f ∘ id = f`, `f` a localization map."] lemma of_mul_equiv_of_dom_id : f.of_mul_equiv_of_dom (show S.map (mul_equiv.refl M).to_monoid_hom = S, from submonoid.ext $ λ x, ⟨λ ⟨y, hy, h⟩, h ▸ hy, λ h, ⟨x, h, rfl⟩⟩) = f := by ext; refl /-- Given localization maps `f : M →* N, k : P →* U` for submonoids `S, T` respectively, an isomorphism `j : M ≃* P` such that `j(S) = T` induces an isomorphism of localizations `N ≃* U`. -/ @[to_additive "Given localization maps `f : M →+ N, k : P →+ U` for submonoids `S, T` respectively, an isomorphism `j : M ≃+ P` such that `j(S) = T` induces an isomorphism of localizations `N ≃+ U`."] noncomputable def mul_equiv_of_mul_equiv (k : localization_map T Q) {j : M ≃* P} (H : S.map j.to_monoid_hom = T) : N ≃* Q := f.mul_equiv_of_localizations $ k.of_mul_equiv_of_dom H @[simp, to_additive] lemma mul_equiv_of_mul_equiv_eq_map_apply {k : localization_map T Q} {j : M ≃* P} (H : S.map j.to_monoid_hom = T) (x) : f.mul_equiv_of_mul_equiv k H x = f.map (λ y : S, show j.to_monoid_hom y ∈ T, from H ▸ set.mem_image_of_mem j y.2) k x := rfl @[to_additive] lemma mul_equiv_of_mul_equiv_eq_map {k : localization_map T Q} {j : M ≃* P} (H : S.map j.to_monoid_hom = T) : (f.mul_equiv_of_mul_equiv k H).to_monoid_hom = f.map (λ y : S, show j.to_monoid_hom y ∈ T, from H ▸ set.mem_image_of_mem j y.2) k := rfl @[simp, to_additive] lemma mul_equiv_of_mul_equiv_eq {k : localization_map T Q} {j : M ≃* P} (H : S.map j.to_monoid_hom = T) (x) : f.mul_equiv_of_mul_equiv k H (f.to_map x) = k.to_map (j x) := f.map_eq (λ y : S, H ▸ set.mem_image_of_mem j y.2) _ @[simp, to_additive] lemma mul_equiv_of_mul_equiv_mk' {k : localization_map T Q} {j : M ≃* P} (H : S.map j.to_monoid_hom = T) (x y) : f.mul_equiv_of_mul_equiv k H (f.mk' x y) = k.mk' (j x) ⟨j y, H ▸ set.mem_image_of_mem j y.2⟩ := f.map_mk' (λ y : S, H ▸ set.mem_image_of_mem j y.2) _ _ @[simp, to_additive] lemma of_mul_equiv_of_mul_equiv_apply {k : localization_map T Q} {j : M ≃* P} (H : S.map j.to_monoid_hom = T) (x) : (f.of_mul_equiv_of_localizations (f.mul_equiv_of_mul_equiv k H)).to_map x = k.to_map (j x) := ext_iff.1 (f.mul_equiv_of_localizations_right_inv (k.of_mul_equiv_of_dom H)) x @[to_additive] lemma of_mul_equiv_of_mul_equiv {k : localization_map T Q} {j : M ≃* P} (H : S.map j.to_monoid_hom = T) : (f.of_mul_equiv_of_localizations (f.mul_equiv_of_mul_equiv k H)).to_map = k.to_map.comp j.to_monoid_hom := monoid_hom.ext $ f.of_mul_equiv_of_mul_equiv_apply H end localization_map end submonoid namespace localization variables (S) /-- Natural hom sending `x : M`, `M` a `comm_monoid`, to the equivalence class of `(x, 1)` in the localization of `M` at a submonoid. -/ @[to_additive "Natural homomorphism sending `x : M`, `M` an `add_comm_monoid`, to the equivalence class of `(x, 0)` in the localization of `M` at a submonoid."] def monoid_of : submonoid.localization_map S (localization S) := { map_units' := λ y, is_unit_iff_exists_inv.2 ⟨mk 1 y, (r S).eq.2 $ show r S (_, 1 * y) 1, by simpa using (r S).symm (one_rel y)⟩, surj' := λ z, induction_on z $ λ x, ⟨x, (r S).eq.2 $ show r S (x.1 * x.2, x.2 * 1) (x.1, 1), by rw [mul_comm x.2, ←mul_one (x.1, (1 : S))]; exact (r S).mul ((r S).refl (x.1, 1)) ((r S).symm $ one_rel x.2)⟩, eq_iff_exists' := λ x y, (r S).eq.trans $ r_iff_exists.trans $ show (∃ (c : S), x * 1 * c = y * 1 * c) ↔ _, by rw [mul_one, mul_one], ..(r S).mk'.comp $ monoid_hom.inl M S } variables {S} @[to_additive] lemma mk_one_eq_monoid_of_mk (x) : mk x 1 = (monoid_of S).to_map x := rfl @[to_additive] lemma mk_eq_monoid_of_mk'_apply (x y) : mk x y = (monoid_of S).mk' x y := show _ = _ * _, from (submonoid.localization_map.mul_inv_right (monoid_of S).map_units _ _ _).2 $ begin rw [←mk_one_eq_monoid_of_mk, ←mk_one_eq_monoid_of_mk, show mk x y * mk y 1 = mk (x * y) (1 * y), by rw mul_comm 1 y; refl, show mk x 1 = mk (x * 1) ((1 : S) * 1), by rw [mul_one, mul_one]], exact (con.eq _).2 (con.symm _ $ (localization.r S).mul (con.refl _ (x, 1)) $ one_rel _), end @[simp, to_additive] lemma mk_eq_monoid_of_mk' : mk = (monoid_of S).mk' := funext $ λ _, funext $ λ _, mk_eq_monoid_of_mk'_apply _ _ variables (f : submonoid.localization_map S N) /-- Given a localization map `f : M →* N` for a submonoid `S`, we get an isomorphism between the localization of `M` at `S` as a quotient type and `N`. -/ @[to_additive "Given a localization map `f : M →+ N` for a submonoid `S`, we get an isomorphism between the localization of `M` at `S` as a quotient type and `N`."] noncomputable def mul_equiv_of_quotient (f : submonoid.localization_map S N) : localization S ≃* N := (monoid_of S).mul_equiv_of_localizations f variables {f} @[simp, to_additive] lemma mul_equiv_of_quotient_apply (x) : mul_equiv_of_quotient f x = (monoid_of S).lift f.map_units x := rfl @[simp, to_additive] lemma mul_equiv_of_quotient_mk' (x y) : mul_equiv_of_quotient f ((monoid_of S).mk' x y) = f.mk' x y := (monoid_of S).lift_mk' _ _ _ @[to_additive] lemma mul_equiv_of_quotient_mk (x y) : mul_equiv_of_quotient f (mk x y) = f.mk' x y := by rw mk_eq_monoid_of_mk'_apply; exact mul_equiv_of_quotient_mk' _ _ @[simp, to_additive] lemma mul_equiv_of_quotient_monoid_of (x) : mul_equiv_of_quotient f ((monoid_of S).to_map x) = f.to_map x := (monoid_of S).lift_eq _ _ @[simp, to_additive] lemma mul_equiv_of_quotient_symm_mk' (x y) : (mul_equiv_of_quotient f).symm (f.mk' x y) = (monoid_of S).mk' x y := f.lift_mk' _ _ _ @[to_additive] lemma mul_equiv_of_quotient_symm_mk (x y) : (mul_equiv_of_quotient f).symm (f.mk' x y) = mk x y := by rw mk_eq_monoid_of_mk'_apply; exact mul_equiv_of_quotient_symm_mk' _ _ @[simp, to_additive] lemma mul_equiv_of_quotient_symm_monoid_of (x) : (mul_equiv_of_quotient f).symm (f.to_map x) = (monoid_of S).to_map x := f.lift_eq _ _ section away variables (x : M) /-- Given `x : M`, the localization of `M` at the submonoid generated by `x`, as a quotient. -/ @[reducible, to_additive "Given `x : M`, the localization of `M` at the submonoid generated by `x`, as a quotient."] def away := localization (submonoid.powers x) /-- Given `x : M`, `inv_self` is `x⁻¹` in the localization (as a quotient type) of `M` at the submonoid generated by `x`. -/ @[to_additive "Given `x : M`, `neg_self` is `-x` in the localization (as a quotient type) of `M` at the submonoid generated by `x`."] def away.inv_self : away x := mk 1 ⟨x, submonoid.mem_powers _⟩ /-- Given `x : M`, the natural hom sending `y : M`, `M` a `comm_monoid`, to the equivalence class of `(y, 1)` in the localization of `M` at the submonoid generated by `x`. -/ @[reducible, to_additive "Given `x : M`, the natural hom sending `y : M`, `M` an `add_comm_monoid`, to the equivalence class of `(y, 0)` in the localization of `M` at the submonoid generated by `x`."] def away.monoid_of : submonoid.localization_map.away_map x (away x) := monoid_of (submonoid.powers x) @[simp, to_additive] lemma away.mk_eq_monoid_of_mk' : mk = (away.monoid_of x).mk' := mk_eq_monoid_of_mk' /-- Given `x : M` and a localization map `f : M →* N` away from `x`, we get an isomorphism between the localization of `M` at the submonoid generated by `x` as a quotient type and `N`. -/ @[to_additive "Given `x : M` and a localization map `f : M →+ N` away from `x`, we get an isomorphism between the localization of `M` at the submonoid generated by `x` as a quotient type and `N`."] noncomputable def away.mul_equiv_of_quotient (f : submonoid.localization_map.away_map x N) : away x ≃* N := mul_equiv_of_quotient f end away end localization
72f850d379a5fbd0a2c1ec48ed415aee491d61f9
94e33a31faa76775069b071adea97e86e218a8ee
/src/topology/continuous_function/algebra.lean
a742ae95c8dd82d7b584060cb05c8c66c9688a75
[ "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
33,481
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Nicolò Cavalleri -/ import topology.algebra.module.basic import topology.continuous_function.ordered import topology.algebra.uniform_group import topology.uniform_space.compact_convergence import topology.algebra.star import algebra.algebra.subalgebra.basic import tactic.field_simp /-! # Algebraic structures over continuous functions In this file we define instances of algebraic structures over the type `continuous_map α β` (denoted `C(α, β)`) of **bundled** continuous maps from `α` to `β`. For example, `C(α, β)` is a group when `β` is a group, a ring when `β` is a ring, etc. For each type of algebraic structure, we also define an appropriate subobject of `α → β` with carrier `{ f : α → β | continuous f }`. For example, when `β` is a group, a subgroup `continuous_subgroup α β` of `α → β` is constructed with carrier `{ f : α → β | continuous f }`. Note that, rather than using the derived algebraic structures on these subobjects (for example, when `β` is a group, the derived group structure on `continuous_subgroup α β`), one should use `C(α, β)` with the appropriate instance of the structure. -/ local attribute [elab_simple] continuous.comp namespace continuous_functions variables {α : Type*} {β : Type*} [topological_space α] [topological_space β] variables {f g : {f : α → β | continuous f }} instance : has_coe_to_fun {f : α → β | continuous f} (λ _, α → β) := ⟨subtype.val⟩ end continuous_functions namespace continuous_map variables {α : Type*} {β : Type*} {γ : Type*} variables [topological_space α] [topological_space β] [topological_space γ] @[to_additive] instance has_mul [has_mul β] [has_continuous_mul β] : has_mul C(α, β) := ⟨λ f g, ⟨f * g, continuous_mul.comp (f.continuous.prod_mk g.continuous : _)⟩⟩ @[simp, norm_cast, to_additive] lemma coe_mul [has_mul β] [has_continuous_mul β] (f g : C(α, β)) : ⇑(f * g) = f * g := rfl @[simp, to_additive] lemma mul_comp [has_mul γ] [has_continuous_mul γ] (f₁ f₂ : C(β, γ)) (g : C(α, β)) : (f₁ * f₂).comp g = f₁.comp g * f₂.comp g := rfl @[to_additive] instance [has_one β] : has_one C(α, β) := ⟨const α 1⟩ @[simp, norm_cast, to_additive] lemma coe_one [has_one β] : ⇑(1 : C(α, β)) = 1 := rfl @[simp, to_additive] lemma one_comp [has_one γ] (g : C(α, β)) : (1 : C(β, γ)).comp g = 1 := rfl instance [has_nat_cast β] : has_nat_cast C(α, β) := ⟨λ n, continuous_map.const _ n⟩ @[simp, norm_cast] lemma coe_nat_cast [has_nat_cast β] (n : ℕ) : ((n : C(α, β)) : α → β) = n := rfl instance [has_int_cast β] : has_int_cast C(α, β) := ⟨λ n, continuous_map.const _ n⟩ @[simp, norm_cast] lemma coe_int_cast [has_int_cast β] (n : ℤ) : ((n : C(α, β)) : α → β) = n := rfl instance has_nsmul [add_monoid β] [has_continuous_add β] : has_smul ℕ C(α, β) := ⟨λ n f, ⟨n • f, f.continuous.nsmul n⟩⟩ @[to_additive] instance has_pow [monoid β] [has_continuous_mul β] : has_pow C(α, β) ℕ := ⟨λ f n, ⟨f ^ n, f.continuous.pow n⟩⟩ @[norm_cast, to_additive] lemma coe_pow [monoid β] [has_continuous_mul β] (f : C(α, β)) (n : ℕ) : ⇑(f ^ n) = f ^ n := rfl -- don't make `coe_nsmul` simp as the linter complains it's redundant WRT `coe_smul` attribute [simp] coe_pow @[to_additive] lemma pow_comp [monoid γ] [has_continuous_mul γ] (f : C(β, γ)) (n : ℕ) (g : C(α, β)) : (f^n).comp g = (f.comp g)^n := rfl -- don't make `nsmul_comp` simp as the linter complains it's redundant WRT `smul_comp` attribute [simp] pow_comp @[to_additive] instance [group β] [topological_group β] : has_inv C(α, β) := { inv := λ f, ⟨f⁻¹, f.continuous.inv⟩ } @[simp, norm_cast, to_additive] lemma coe_inv [group β] [topological_group β] (f : C(α, β)) : ⇑(f⁻¹) = f⁻¹ := rfl @[simp, to_additive] lemma inv_comp [group γ] [topological_group γ] (f : C(β, γ)) (g : C(α, β)) : (f⁻¹).comp g = (f.comp g)⁻¹ := rfl @[to_additive] instance [has_div β] [has_continuous_div β] : has_div C(α, β) := { div := λ f g, ⟨f / g, f.continuous.div' g.continuous⟩ } @[simp, norm_cast, to_additive] lemma coe_div [has_div β] [has_continuous_div β] (f g : C(α, β)) : ⇑(f / g) = f / g := rfl @[simp, to_additive] lemma div_comp [has_div γ] [has_continuous_div γ] (f g : C(β, γ)) (h : C(α, β)) : (f / g).comp h = (f.comp h) / (g.comp h) := rfl instance has_zsmul [add_group β] [topological_add_group β] : has_smul ℤ C(α, β) := { smul := λ z f, ⟨z • f, f.continuous.zsmul z⟩ } @[to_additive] instance has_zpow [group β] [topological_group β] : has_pow C(α, β) ℤ := { pow := λ f z, ⟨f ^ z, f.continuous.zpow z⟩ } @[norm_cast, to_additive] lemma coe_zpow [group β] [topological_group β] (f : C(α, β)) (z : ℤ) : ⇑(f ^ z) = f ^ z := rfl -- don't make `coe_zsmul` simp as the linter complains it's redundant WRT `coe_smul` attribute [simp] coe_zpow @[to_additive] lemma zpow_comp [group γ] [topological_group γ] (f : C(β, γ)) (z : ℤ) (g : C(α, β)) : (f^z).comp g = (f.comp g)^z := rfl -- don't make `zsmul_comp` simp as the linter complains it's redundant WRT `smul_comp` attribute [simp] zpow_comp end continuous_map section group_structure /-! ### Group stucture In this section we show that continuous functions valued in a topological group inherit the structure of a group. -/ section subtype /-- The `submonoid` of continuous maps `α → β`. -/ @[to_additive "The `add_submonoid` of continuous maps `α → β`. "] def continuous_submonoid (α : Type*) (β : Type*) [topological_space α] [topological_space β] [monoid β] [has_continuous_mul β] : submonoid (α → β) := { carrier := { f : α → β | continuous f }, one_mem' := @continuous_const _ _ _ _ 1, mul_mem' := λ f g fc gc, continuous.comp has_continuous_mul.continuous_mul (continuous.prod_mk fc gc : _) } /-- The subgroup of continuous maps `α → β`. -/ @[to_additive "The `add_subgroup` of continuous maps `α → β`. "] def continuous_subgroup (α : Type*) (β : Type*) [topological_space α] [topological_space β] [group β] [topological_group β] : subgroup (α → β) := { inv_mem' := λ f fc, continuous.inv fc, ..continuous_submonoid α β, }. end subtype namespace continuous_map @[to_additive] instance {α : Type*} {β : Type*} [topological_space α] [topological_space β] [semigroup β] [has_continuous_mul β] : semigroup C(α, β) := coe_injective.semigroup _ coe_mul @[to_additive] instance {α : Type*} {β : Type*} [topological_space α] [topological_space β] [comm_semigroup β] [has_continuous_mul β] : comm_semigroup C(α, β) := coe_injective.comm_semigroup _ coe_mul @[to_additive] instance {α : Type*} {β : Type*} [topological_space α] [topological_space β] [mul_one_class β] [has_continuous_mul β] : mul_one_class C(α, β) := coe_injective.mul_one_class _ coe_one coe_mul instance {α : Type*} {β : Type*} [topological_space α] [topological_space β] [mul_zero_class β] [has_continuous_mul β] : mul_zero_class C(α, β) := coe_injective.mul_zero_class _ coe_zero coe_mul instance {α : Type*} {β : Type*} [topological_space α] [topological_space β] [semigroup_with_zero β] [has_continuous_mul β] : semigroup_with_zero C(α, β) := coe_injective.semigroup_with_zero _ coe_zero coe_mul @[to_additive] instance {α : Type*} {β : Type*} [topological_space α] [topological_space β] [monoid β] [has_continuous_mul β] : monoid C(α, β) := coe_injective.monoid _ coe_one coe_mul coe_pow instance {α : Type*} {β : Type*} [topological_space α] [topological_space β] [monoid_with_zero β] [has_continuous_mul β] : monoid_with_zero C(α, β) := coe_injective.monoid_with_zero _ coe_zero coe_one coe_mul coe_pow @[to_additive] instance {α : Type*} {β : Type*} [topological_space α] [topological_space β] [comm_monoid β] [has_continuous_mul β] : comm_monoid C(α, β) := coe_injective.comm_monoid _ coe_one coe_mul coe_pow instance {α : Type*} {β : Type*} [topological_space α] [topological_space β] [comm_monoid_with_zero β] [has_continuous_mul β] : comm_monoid_with_zero C(α, β) := coe_injective.comm_monoid_with_zero _ coe_zero coe_one coe_mul coe_pow @[to_additive] instance {α : Type*} {β : Type*} [topological_space α] [locally_compact_space α] [topological_space β] [has_mul β] [has_continuous_mul β] : has_continuous_mul C(α, β) := ⟨begin refine continuous_of_continuous_uncurry _ _, have h1 : continuous (λ x : (C(α, β) × C(α, β)) × α, x.fst.fst x.snd) := continuous_eval'.comp (continuous_fst.prod_map continuous_id), have h2 : continuous (λ x : (C(α, β) × C(α, β)) × α, x.fst.snd x.snd) := continuous_eval'.comp (continuous_snd.prod_map continuous_id), exact h1.mul h2, end⟩ /-- Coercion to a function as an `monoid_hom`. Similar to `monoid_hom.coe_fn`. -/ @[to_additive "Coercion to a function as an `add_monoid_hom`. Similar to `add_monoid_hom.coe_fn`.", simps] def coe_fn_monoid_hom {α : Type*} {β : Type*} [topological_space α] [topological_space β] [monoid β] [has_continuous_mul β] : C(α, β) →* (α → β) := { to_fun := coe_fn, map_one' := coe_one, map_mul' := coe_mul } /-- Composition on the left by a (continuous) homomorphism of topological monoids, as a `monoid_hom`. Similar to `monoid_hom.comp_left`. -/ @[to_additive "Composition on the left by a (continuous) homomorphism of topological `add_monoid`s, as an `add_monoid_hom`. Similar to `add_monoid_hom.comp_left`.", simps] protected def _root_.monoid_hom.comp_left_continuous (α : Type*) {β : Type*} {γ : Type*} [topological_space α] [topological_space β] [monoid β] [has_continuous_mul β] [topological_space γ] [monoid γ] [has_continuous_mul γ] (g : β →* γ) (hg : continuous g) : C(α, β) →* C(α, γ) := { to_fun := λ f, (⟨g, hg⟩ : C(β, γ)).comp f, map_one' := ext $ λ x, g.map_one, map_mul' := λ f₁ f₂, ext $ λ x, g.map_mul _ _ } /-- Composition on the right as a `monoid_hom`. Similar to `monoid_hom.comp_hom'`. -/ @[to_additive "Composition on the right as an `add_monoid_hom`. Similar to `add_monoid_hom.comp_hom'`.", simps] def comp_monoid_hom' {α : Type*} {β : Type*} {γ : Type*} [topological_space α] [topological_space β] [topological_space γ] [mul_one_class γ] [has_continuous_mul γ] (g : C(α, β)) : C(β, γ) →* C(α, γ) := { to_fun := λ f, f.comp g, map_one' := one_comp g, map_mul' := λ f₁ f₂, mul_comp f₁ f₂ g } open_locale big_operators @[simp, to_additive] lemma coe_prod {α : Type*} {β : Type*} [comm_monoid β] [topological_space α] [topological_space β] [has_continuous_mul β] {ι : Type*} (s : finset ι) (f : ι → C(α, β)) : ⇑(∏ i in s, f i) = (∏ i in s, (f i : α → β)) := (coe_fn_monoid_hom : C(α, β) →* _).map_prod f s @[to_additive] lemma prod_apply {α : Type*} {β : Type*} [comm_monoid β] [topological_space α] [topological_space β] [has_continuous_mul β] {ι : Type*} (s : finset ι) (f : ι → C(α, β)) (a : α) : (∏ i in s, f i) a = (∏ i in s, f i a) := by simp @[to_additive] instance {α : Type*} {β : Type*} [topological_space α] [topological_space β] [group β] [topological_group β] : group C(α, β) := coe_injective.group _ coe_one coe_mul coe_inv coe_div coe_pow coe_zpow @[to_additive] instance {α : Type*} {β : Type*} [topological_space α] [topological_space β] [comm_group β] [topological_group β] : comm_group C(α, β) := coe_injective.comm_group _ coe_one coe_mul coe_inv coe_div coe_pow coe_zpow @[to_additive] instance {α : Type*} {β : Type*} [topological_space α] [topological_space β] [comm_group β] [topological_group β] : topological_group C(α, β) := { continuous_mul := by { letI : uniform_space β := topological_group.to_uniform_space β, have : uniform_group β := topological_group_is_uniform, rw continuous_iff_continuous_at, rintros ⟨f, g⟩, rw [continuous_at, tendsto_iff_forall_compact_tendsto_uniformly_on, nhds_prod_eq], exactI λ K hK, uniform_continuous_mul.comp_tendsto_uniformly_on ((tendsto_iff_forall_compact_tendsto_uniformly_on.mp filter.tendsto_id K hK).prod (tendsto_iff_forall_compact_tendsto_uniformly_on.mp filter.tendsto_id K hK)), }, continuous_inv := by { letI : uniform_space β := topological_group.to_uniform_space β, have : uniform_group β := topological_group_is_uniform, rw continuous_iff_continuous_at, intro f, rw [continuous_at, tendsto_iff_forall_compact_tendsto_uniformly_on], exactI λ K hK, uniform_continuous_inv.comp_tendsto_uniformly_on (tendsto_iff_forall_compact_tendsto_uniformly_on.mp filter.tendsto_id K hK), } } end continuous_map end group_structure section ring_structure /-! ### Ring stucture In this section we show that continuous functions valued in a topological semiring `R` inherit the structure of a ring. -/ section subtype /-- The subsemiring of continuous maps `α → β`. -/ def continuous_subsemiring (α : Type*) (R : Type*) [topological_space α] [topological_space R] [semiring R] [topological_semiring R] : subsemiring (α → R) := { ..continuous_add_submonoid α R, ..continuous_submonoid α R } /-- The subring of continuous maps `α → β`. -/ def continuous_subring (α : Type*) (R : Type*) [topological_space α] [topological_space R] [ring R] [topological_ring R] : subring (α → R) := { ..continuous_subsemiring α R, ..continuous_add_subgroup α R } end subtype namespace continuous_map instance {α : Type*} {β : Type*} [topological_space α] [topological_space β] [non_unital_non_assoc_semiring β] [topological_semiring β] : non_unital_non_assoc_semiring C(α, β) := coe_injective.non_unital_non_assoc_semiring _ coe_zero coe_add coe_mul coe_nsmul instance {α : Type*} {β : Type*} [topological_space α] [topological_space β] [non_unital_semiring β] [topological_semiring β] : non_unital_semiring C(α, β) := coe_injective.non_unital_semiring _ coe_zero coe_add coe_mul coe_nsmul instance {α : Type*} {β : Type*} [topological_space α] [topological_space β] [add_monoid_with_one β] [has_continuous_add β] : add_monoid_with_one C(α, β) := coe_injective.add_monoid_with_one _ coe_zero coe_one coe_add coe_nsmul coe_nat_cast instance {α : Type*} {β : Type*} [topological_space α] [topological_space β] [non_assoc_semiring β] [topological_semiring β] : non_assoc_semiring C(α, β) := coe_injective.non_assoc_semiring _ coe_zero coe_one coe_add coe_mul coe_nsmul coe_nat_cast instance {α : Type*} {β : Type*} [topological_space α] [topological_space β] [semiring β] [topological_semiring β] : semiring C(α, β) := coe_injective.semiring _ coe_zero coe_one coe_add coe_mul coe_nsmul coe_pow coe_nat_cast instance {α : Type*} {β : Type*} [topological_space α] [topological_space β] [non_unital_non_assoc_ring β] [topological_ring β] : non_unital_non_assoc_ring C(α, β) := coe_injective.non_unital_non_assoc_ring _ coe_zero coe_add coe_mul coe_neg coe_sub coe_nsmul coe_zsmul instance {α : Type*} {β : Type*} [topological_space α] [topological_space β] [non_unital_ring β] [topological_ring β] : non_unital_ring C(α, β) := coe_injective.non_unital_ring _ coe_zero coe_add coe_mul coe_neg coe_sub coe_nsmul coe_zsmul instance {α : Type*} {β : Type*} [topological_space α] [topological_space β] [non_assoc_ring β] [topological_ring β] : non_assoc_ring C(α, β) := coe_injective.non_assoc_ring _ coe_zero coe_one coe_add coe_mul coe_neg coe_sub coe_nsmul coe_zsmul coe_nat_cast coe_int_cast instance {α : Type*} {β : Type*} [topological_space α] [topological_space β] [ring β] [topological_ring β] : ring C(α, β) := coe_injective.ring _ coe_zero coe_one coe_add coe_mul coe_neg coe_sub coe_nsmul coe_zsmul coe_pow coe_nat_cast coe_int_cast instance {α : Type*} {β : Type*} [topological_space α] [topological_space β] [non_unital_comm_semiring β] [topological_semiring β] : non_unital_comm_semiring C(α, β) := coe_injective.non_unital_comm_semiring _ coe_zero coe_add coe_mul coe_nsmul instance {α : Type*} {β : Type*} [topological_space α] [topological_space β] [comm_semiring β] [topological_semiring β] : comm_semiring C(α, β) := coe_injective.comm_semiring _ coe_zero coe_one coe_add coe_mul coe_nsmul coe_pow coe_nat_cast instance {α : Type*} {β : Type*} [topological_space α] [topological_space β] [non_unital_comm_ring β] [topological_ring β] : non_unital_comm_ring C(α, β) := coe_injective.non_unital_comm_ring _ coe_zero coe_add coe_mul coe_neg coe_sub coe_nsmul coe_zsmul instance {α : Type*} {β : Type*} [topological_space α] [topological_space β] [comm_ring β] [topological_ring β] : comm_ring C(α, β) := coe_injective.comm_ring _ coe_zero coe_one coe_add coe_mul coe_neg coe_sub coe_nsmul coe_zsmul coe_pow coe_nat_cast coe_int_cast /-- Composition on the left by a (continuous) homomorphism of topological semirings, as a `ring_hom`. Similar to `ring_hom.comp_left`. -/ @[simps] protected def _root_.ring_hom.comp_left_continuous (α : Type*) {β : Type*} {γ : Type*} [topological_space α] [topological_space β] [semiring β] [topological_semiring β] [topological_space γ] [semiring γ] [topological_semiring γ] (g : β →+* γ) (hg : continuous g) : C(α, β) →+* C(α, γ) := { .. g.to_monoid_hom.comp_left_continuous α hg, .. g.to_add_monoid_hom.comp_left_continuous α hg } /-- Coercion to a function as a `ring_hom`. -/ @[simps] def coe_fn_ring_hom {α : Type*} {β : Type*} [topological_space α] [topological_space β] [ring β] [topological_ring β] : C(α, β) →+* (α → β) := { to_fun := coe_fn, ..(coe_fn_monoid_hom : C(α, β) →* _), ..(coe_fn_add_monoid_hom : C(α, β) →+ _) } end continuous_map end ring_structure local attribute [ext] subtype.eq section module_structure /-! ### Semiodule stucture In this section we show that continuous functions valued in a topological module `M` over a topological semiring `R` inherit the structure of a module. -/ section subtype variables (α : Type*) [topological_space α] variables (R : Type*) [semiring R] variables (M : Type*) [topological_space M] [add_comm_group M] variables [module R M] [has_continuous_const_smul R M] [topological_add_group M] /-- The `R`-submodule of continuous maps `α → M`. -/ def continuous_submodule : submodule R (α → M) := { carrier := { f : α → M | continuous f }, smul_mem' := λ c f hf, hf.const_smul c, ..continuous_add_subgroup α M } end subtype namespace continuous_map variables {α β : Type*} [topological_space α] [topological_space β] {R R₁ : Type*} {M : Type*} [topological_space M] {M₂ : Type*} [topological_space M₂] @[to_additive continuous_map.has_vadd] instance [has_smul R M] [has_continuous_const_smul R M] : has_smul R C(α, M) := ⟨λ r f, ⟨r • f, f.continuous.const_smul r⟩⟩ @[to_additive] instance [locally_compact_space α] [has_smul R M] [has_continuous_const_smul R M] : has_continuous_const_smul R C(α, M) := ⟨λ γ, continuous_of_continuous_uncurry _ (continuous_eval'.const_smul γ)⟩ @[to_additive] instance [locally_compact_space α] [topological_space R] [has_smul R M] [has_continuous_smul R M] : has_continuous_smul R C(α, M) := ⟨begin refine continuous_of_continuous_uncurry _ _, have h : continuous (λ x : (R × C(α, M)) × α, x.fst.snd x.snd) := continuous_eval'.comp (continuous_snd.prod_map continuous_id), exact (continuous_fst.comp continuous_fst).smul h, end⟩ @[simp, to_additive, norm_cast] lemma coe_smul [has_smul R M] [has_continuous_const_smul R M] (c : R) (f : C(α, M)) : ⇑(c • f) = c • f := rfl @[to_additive] lemma smul_apply [has_smul R M] [has_continuous_const_smul R M] (c : R) (f : C(α, M)) (a : α) : (c • f) a = c • (f a) := rfl @[simp, to_additive] lemma smul_comp [has_smul R M] [has_continuous_const_smul R M] (r : R) (f : C(β, M)) (g : C(α, β)) : (r • f).comp g = r • (f.comp g) := rfl @[to_additive] instance [has_smul R M] [has_continuous_const_smul R M] [has_smul R₁ M] [has_continuous_const_smul R₁ M] [smul_comm_class R R₁ M] : smul_comm_class R R₁ C(α, M) := { smul_comm := λ _ _ _, ext $ λ _, smul_comm _ _ _ } instance [has_smul R M] [has_continuous_const_smul R M] [has_smul R₁ M] [has_continuous_const_smul R₁ M] [has_smul R R₁] [is_scalar_tower R R₁ M] : is_scalar_tower R R₁ C(α, M) := { smul_assoc := λ _ _ _, ext $ λ _, smul_assoc _ _ _ } instance [has_smul R M] [has_smul Rᵐᵒᵖ M] [has_continuous_const_smul R M] [is_central_scalar R M] : is_central_scalar R C(α, M) := { op_smul_eq_smul := λ _ _, ext $ λ _, op_smul_eq_smul _ _ } instance [monoid R] [mul_action R M] [has_continuous_const_smul R M] : mul_action R C(α, M) := function.injective.mul_action _ coe_injective coe_smul instance [monoid R] [add_monoid M] [distrib_mul_action R M] [has_continuous_add M] [has_continuous_const_smul R M] : distrib_mul_action R C(α, M) := function.injective.distrib_mul_action coe_fn_add_monoid_hom coe_injective coe_smul variables [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] variables [has_continuous_add M] [module R M] [has_continuous_const_smul R M] variables [has_continuous_add M₂] [module R M₂] [has_continuous_const_smul R M₂] instance module : module R C(α, M) := function.injective.module R coe_fn_add_monoid_hom coe_injective coe_smul variables (R) /-- Composition on the left by a continuous linear map, as a `linear_map`. Similar to `linear_map.comp_left`. -/ @[simps] protected def _root_.continuous_linear_map.comp_left_continuous (α : Type*) [topological_space α] (g : M →L[R] M₂) : C(α, M) →ₗ[R] C(α, M₂) := { map_smul' := λ c f, ext $ λ x, g.map_smul' c _, .. g.to_linear_map.to_add_monoid_hom.comp_left_continuous α g.continuous } /-- Coercion to a function as a `linear_map`. -/ @[simps] def coe_fn_linear_map : C(α, M) →ₗ[R] (α → M) := { to_fun := coe_fn, map_smul' := coe_smul, ..(coe_fn_add_monoid_hom : C(α, M) →+ _) } end continuous_map end module_structure section algebra_structure /-! ### Algebra structure In this section we show that continuous functions valued in a topological algebra `A` over a ring `R` inherit the structure of an algebra. Note that the hypothesis that `A` is a topological algebra is obtained by requiring that `A` be both a `has_continuous_smul` and a `topological_semiring`.-/ section subtype variables {α : Type*} [topological_space α] {R : Type*} [comm_semiring R] {A : Type*} [topological_space A] [semiring A] [algebra R A] [topological_semiring A] /-- The `R`-subalgebra of continuous maps `α → A`. -/ def continuous_subalgebra : subalgebra R (α → A) := { carrier := { f : α → A | continuous f }, algebra_map_mem' := λ r, (continuous_const : continuous $ λ (x : α), algebra_map R A r), ..continuous_subsemiring α A } end subtype section continuous_map variables {α : Type*} [topological_space α] {R : Type*} [comm_semiring R] {A : Type*} [topological_space A] [semiring A] [algebra R A] [topological_semiring A] {A₂ : Type*} [topological_space A₂] [semiring A₂] [algebra R A₂] [topological_semiring A₂] /-- Continuous constant functions as a `ring_hom`. -/ def continuous_map.C : R →+* C(α, A) := { to_fun := λ c : R, ⟨λ x: α, ((algebra_map R A) c), continuous_const⟩, map_one' := by ext x; exact (algebra_map R A).map_one, map_mul' := λ c₁ c₂, by ext x; exact (algebra_map R A).map_mul _ _, map_zero' := by ext x; exact (algebra_map R A).map_zero, map_add' := λ c₁ c₂, by ext x; exact (algebra_map R A).map_add _ _ } @[simp] lemma continuous_map.C_apply (r : R) (a : α) : continuous_map.C r a = algebra_map R A r := rfl variables [has_continuous_const_smul R A] [has_continuous_const_smul R A₂] instance continuous_map.algebra : algebra R C(α, A) := { to_ring_hom := continuous_map.C, commutes' := λ c f, by ext x; exact algebra.commutes' _ _, smul_def' := λ c f, by ext x; exact algebra.smul_def' _ _, } variables (R) /-- Composition on the left by a (continuous) homomorphism of topological `R`-algebras, as an `alg_hom`. Similar to `alg_hom.comp_left`. -/ @[simps] protected def alg_hom.comp_left_continuous {α : Type*} [topological_space α] (g : A →ₐ[R] A₂) (hg : continuous g) : C(α, A) →ₐ[R] C(α, A₂) := { commutes' := λ c, continuous_map.ext $ λ _, g.commutes' _, .. g.to_ring_hom.comp_left_continuous α hg } /-- Coercion to a function as an `alg_hom`. -/ @[simps] def continuous_map.coe_fn_alg_hom : C(α, A) →ₐ[R] (α → A) := { to_fun := coe_fn, commutes' := λ r, rfl, -- `..(continuous_map.coe_fn_ring_hom : C(α, A) →+* _)` times out for some reason map_zero' := continuous_map.coe_zero, map_one' := continuous_map.coe_one, map_add' := continuous_map.coe_add, map_mul' := continuous_map.coe_mul } variables {R} /-- A version of `separates_points` for subalgebras of the continuous functions, used for stating the Stone-Weierstrass theorem. -/ abbreviation subalgebra.separates_points (s : subalgebra R C(α, A)) : Prop := set.separates_points ((λ f : C(α, A), (f : α → A)) '' (s : set C(α, A))) lemma subalgebra.separates_points_monotone : monotone (λ s : subalgebra R C(α, A), s.separates_points) := λ s s' r h x y n, begin obtain ⟨f, m, w⟩ := h n, rcases m with ⟨f, ⟨m, rfl⟩⟩, exact ⟨_, ⟨f, ⟨r m, rfl⟩⟩, w⟩, end @[simp] lemma algebra_map_apply (k : R) (a : α) : algebra_map R C(α, A) k a = k • 1 := by { rw algebra.algebra_map_eq_smul_one, refl, } variables {𝕜 : Type*} [topological_space 𝕜] /-- A set of continuous maps "separates points strongly" if for each pair of distinct points there is a function with specified values on them. We give a slightly unusual formulation, where the specified values are given by some function `v`, and we ask `f x = v x ∧ f y = v y`. This avoids needing a hypothesis `x ≠ y`. In fact, this definition would work perfectly well for a set of non-continuous functions, but as the only current use case is in the Stone-Weierstrass theorem, writing it this way avoids having to deal with casts inside the set. (This may need to change if we do Stone-Weierstrass on non-compact spaces, where the functions would be continuous functions vanishing at infinity.) -/ def set.separates_points_strongly (s : set C(α, 𝕜)) : Prop := ∀ (v : α → 𝕜) (x y : α), ∃ f : s, (f x : 𝕜) = v x ∧ f y = v y variables [field 𝕜] [topological_ring 𝕜] /-- Working in continuous functions into a topological field, a subalgebra of functions that separates points also separates points strongly. By the hypothesis, we can find a function `f` so `f x ≠ f y`. By an affine transformation in the field we can arrange so that `f x = a` and `f x = b`. -/ lemma subalgebra.separates_points.strongly {s : subalgebra 𝕜 C(α, 𝕜)} (h : s.separates_points) : (s : set C(α, 𝕜)).separates_points_strongly := λ v x y, begin by_cases n : x = y, { subst n, use ((v x) • 1 : C(α, 𝕜)), { apply s.smul_mem, apply s.one_mem, }, { simp [coe_fn_coe_base'] }, }, obtain ⟨f, ⟨f, ⟨m, rfl⟩⟩, w⟩ := h n, replace w : f x - f y ≠ 0 := sub_ne_zero_of_ne w, let a := v x, let b := v y, let f' := ((b - a) * (f x - f y)⁻¹) • (continuous_map.C (f x) - f) + continuous_map.C a, refine ⟨⟨f', _⟩, _, _⟩, { simp only [f', set_like.mem_coe, subalgebra.mem_to_submodule], -- TODO should there be a tactic for this? -- We could add an attribute `@[subobject_mem]`, and a tactic -- ``def subobject_mem := `[solve_by_elim with subobject_mem { max_depth := 10 }]`` solve_by_elim [subalgebra.add_mem, subalgebra.smul_mem, subalgebra.sub_mem, subalgebra.algebra_map_mem] { max_depth := 6 }, }, { simp [f', coe_fn_coe_base'], }, { simp [f', coe_fn_coe_base', inv_mul_cancel_right₀ w], }, end end continuous_map -- TODO[gh-6025]: make this an instance once safe to do so lemma continuous_map.subsingleton_subalgebra (α : Type*) [topological_space α] (R : Type*) [comm_semiring R] [topological_space R] [topological_semiring R] [subsingleton α] : subsingleton (subalgebra R C(α, R)) := begin fsplit, intros s₁ s₂, by_cases n : nonempty α, { obtain ⟨x⟩ := n, ext f, have h : f = algebra_map R C(α, R) (f x), { ext x', simp only [mul_one, algebra.id.smul_eq_mul, algebra_map_apply], congr, }, rw h, simp only [subalgebra.algebra_map_mem], }, { ext f, have h : f = 0, { ext x', exact false.elim (n ⟨x'⟩), }, subst h, simp only [subalgebra.zero_mem], }, end end algebra_structure section module_over_continuous_functions /-! ### Structure as module over scalar functions If `M` is a module over `R`, then we show that the space of continuous functions from `α` to `M` is naturally a module over the ring of continuous functions from `α` to `R`. -/ namespace continuous_map instance has_smul' {α : Type*} [topological_space α] {R : Type*} [semiring R] [topological_space R] {M : Type*} [topological_space M] [add_comm_monoid M] [module R M] [has_continuous_smul R M] : has_smul C(α, R) C(α, M) := ⟨λ f g, ⟨λ x, (f x) • (g x), (continuous.smul f.2 g.2)⟩⟩ instance module' {α : Type*} [topological_space α] (R : Type*) [ring R] [topological_space R] [topological_ring R] (M : Type*) [topological_space M] [add_comm_monoid M] [has_continuous_add M] [module R M] [has_continuous_smul R M] : module C(α, R) C(α, M) := { smul := (•), smul_add := λ c f g, by ext x; exact smul_add (c x) (f x) (g x), add_smul := λ c₁ c₂ f, by ext x; exact add_smul (c₁ x) (c₂ x) (f x), mul_smul := λ c₁ c₂ f, by ext x; exact mul_smul (c₁ x) (c₂ x) (f x), one_smul := λ f, by ext x; exact one_smul R (f x), zero_smul := λ f, by ext x; exact zero_smul _ _, smul_zero := λ r, by ext x; exact smul_zero _, } end continuous_map end module_over_continuous_functions /-! We now provide formulas for `f ⊓ g` and `f ⊔ g`, where `f g : C(α, β)`, in terms of `continuous_map.abs`. -/ section variables {R : Type*} [linear_ordered_field R] -- TODO: -- This lemma (and the next) could go all the way back in `algebra.order.field`, -- except that it is tedious to prove without tactics. -- Rather than stranding it at some intermediate location, -- it's here, immediately prior to the point of use. lemma min_eq_half_add_sub_abs_sub {x y : R} : min x y = 2⁻¹ * (x + y - |x - y|) := by cases le_total x y with h h; field_simp [h, abs_of_nonneg, abs_of_nonpos, mul_two]; abel lemma max_eq_half_add_add_abs_sub {x y : R} : max x y = 2⁻¹ * (x + y + |x - y|) := by cases le_total x y with h h; field_simp [h, abs_of_nonneg, abs_of_nonpos, mul_two]; abel end namespace continuous_map section lattice variables {α : Type*} [topological_space α] variables {β : Type*} [linear_ordered_field β] [topological_space β] [order_topology β] [topological_ring β] lemma inf_eq (f g : C(α, β)) : f ⊓ g = (2⁻¹ : β) • (f + g - |f - g|) := ext (λ x, by simpa using min_eq_half_add_sub_abs_sub) -- Not sure why this is grosser than `inf_eq`: lemma sup_eq (f g : C(α, β)) : f ⊔ g = (2⁻¹ : β) • (f + g + |f - g|) := ext (λ x, by simpa [mul_add] using @max_eq_half_add_add_abs_sub _ _ (f x) (g x)) end lattice /-! ### Star structure If `β` has a continuous star operation, we put a star structure on `C(α, β)` by using the star operation pointwise. If `β` is a ⋆-ring, then `C(α, β)` inherits a ⋆-ring structure. If `β` is a ⋆-ring and a ⋆-module over `R`, then the space of continuous functions from `α` to `β` is a ⋆-module over `R`. -/ section star_structure variables {R α β : Type*} variables [topological_space α] [topological_space β] section has_star variables [has_star β] [has_continuous_star β] instance : has_star C(α, β) := { star := λ f, star_continuous_map.comp f } @[simp] lemma coe_star (f : C(α, β)) : ⇑(star f) = star f := rfl @[simp] lemma star_apply (f : C(α, β)) (x : α) : star f x = star (f x) := rfl end has_star instance [has_involutive_star β] [has_continuous_star β] : has_involutive_star C(α, β) := { star_involutive := λ f, ext $ λ x, star_star _ } instance [add_monoid β] [has_continuous_add β] [star_add_monoid β] [has_continuous_star β] : star_add_monoid C(α, β) := { star_add := λ f g, ext $ λ x, star_add _ _ } instance [semigroup β] [has_continuous_mul β] [star_semigroup β] [has_continuous_star β] : star_semigroup C(α, β) := { star_mul := λ f g, ext $ λ x, star_mul _ _ } instance [non_unital_semiring β] [topological_semiring β] [star_ring β] [has_continuous_star β] : star_ring C(α, β) := { ..continuous_map.star_add_monoid } instance [has_star R] [has_star β] [has_smul R β] [star_module R β] [has_continuous_star β] [has_continuous_const_smul R β] : star_module R C(α, β) := { star_smul := λ k f, ext $ λ x, star_smul _ _ } end star_structure end continuous_map
c16b5a2a263a208774b20010ca4a083fefcec794
592ee40978ac7604005a4e0d35bbc4b467389241
/Library/generated/mathscheme-lean/InvolutiveAddMagmaSig.lean
3b330f0e9b33f7d574a0e09727bce46048e8de11
[]
no_license
ysharoda/Deriving-Definitions
3e149e6641fae440badd35ac110a0bd705a49ad2
dfecb27572022de3d4aa702cae8db19957523a59
refs/heads/master
1,679,127,857,700
1,615,939,007,000
1,615,939,007,000
229,785,731
4
0
null
null
null
null
UTF-8
Lean
false
false
8,580
lean
import init.data.nat.basic import init.data.fin.basic import data.vector import .Prelude open Staged open nat open fin open vector section InvolutiveAddMagmaSig structure InvolutiveAddMagmaSig (A : Type) : Type := (plus : (A → (A → A))) (prim : (A → A)) open InvolutiveAddMagmaSig structure Sig (AS : Type) : Type := (plusS : (AS → (AS → AS))) (primS : (AS → AS)) structure Product (A : Type) : Type := (plusP : ((Prod A A) → ((Prod A A) → (Prod A A)))) (primP : ((Prod A A) → (Prod A A))) structure Hom {A1 : Type} {A2 : Type} (In1 : (InvolutiveAddMagmaSig A1)) (In2 : (InvolutiveAddMagmaSig A2)) : Type := (hom : (A1 → A2)) (pres_plus : (∀ {x1 x2 : A1} , (hom ((plus In1) x1 x2)) = ((plus In2) (hom x1) (hom x2)))) (pres_prim : (∀ {x1 : A1} , (hom ((prim In1) x1)) = ((prim In2) (hom x1)))) structure RelInterp {A1 : Type} {A2 : Type} (In1 : (InvolutiveAddMagmaSig A1)) (In2 : (InvolutiveAddMagmaSig A2)) : Type 1 := (interp : (A1 → (A2 → Type))) (interp_plus : (∀ {x1 x2 : A1} {y1 y2 : A2} , ((interp x1 y1) → ((interp x2 y2) → (interp ((plus In1) x1 x2) ((plus In2) y1 y2)))))) (interp_prim : (∀ {x1 : A1} {y1 : A2} , ((interp x1 y1) → (interp ((prim In1) x1) ((prim In2) y1))))) inductive InvolutiveAddMagmaSigTerm : Type | plusL : (InvolutiveAddMagmaSigTerm → (InvolutiveAddMagmaSigTerm → InvolutiveAddMagmaSigTerm)) | primL : (InvolutiveAddMagmaSigTerm → InvolutiveAddMagmaSigTerm) open InvolutiveAddMagmaSigTerm inductive ClInvolutiveAddMagmaSigTerm (A : Type) : Type | sing : (A → ClInvolutiveAddMagmaSigTerm) | plusCl : (ClInvolutiveAddMagmaSigTerm → (ClInvolutiveAddMagmaSigTerm → ClInvolutiveAddMagmaSigTerm)) | primCl : (ClInvolutiveAddMagmaSigTerm → ClInvolutiveAddMagmaSigTerm) open ClInvolutiveAddMagmaSigTerm inductive OpInvolutiveAddMagmaSigTerm (n : ℕ) : Type | v : ((fin n) → OpInvolutiveAddMagmaSigTerm) | plusOL : (OpInvolutiveAddMagmaSigTerm → (OpInvolutiveAddMagmaSigTerm → OpInvolutiveAddMagmaSigTerm)) | primOL : (OpInvolutiveAddMagmaSigTerm → OpInvolutiveAddMagmaSigTerm) open OpInvolutiveAddMagmaSigTerm inductive OpInvolutiveAddMagmaSigTerm2 (n : ℕ) (A : Type) : Type | v2 : ((fin n) → OpInvolutiveAddMagmaSigTerm2) | sing2 : (A → OpInvolutiveAddMagmaSigTerm2) | plusOL2 : (OpInvolutiveAddMagmaSigTerm2 → (OpInvolutiveAddMagmaSigTerm2 → OpInvolutiveAddMagmaSigTerm2)) | primOL2 : (OpInvolutiveAddMagmaSigTerm2 → OpInvolutiveAddMagmaSigTerm2) open OpInvolutiveAddMagmaSigTerm2 def simplifyCl {A : Type} : ((ClInvolutiveAddMagmaSigTerm A) → (ClInvolutiveAddMagmaSigTerm A)) | (plusCl x1 x2) := (plusCl (simplifyCl x1) (simplifyCl x2)) | (primCl x1) := (primCl (simplifyCl x1)) | (sing x1) := (sing x1) def simplifyOpB {n : ℕ} : ((OpInvolutiveAddMagmaSigTerm n) → (OpInvolutiveAddMagmaSigTerm n)) | (plusOL x1 x2) := (plusOL (simplifyOpB x1) (simplifyOpB x2)) | (primOL x1) := (primOL (simplifyOpB x1)) | (v x1) := (v x1) def simplifyOp {n : ℕ} {A : Type} : ((OpInvolutiveAddMagmaSigTerm2 n A) → (OpInvolutiveAddMagmaSigTerm2 n A)) | (plusOL2 x1 x2) := (plusOL2 (simplifyOp x1) (simplifyOp x2)) | (primOL2 x1) := (primOL2 (simplifyOp x1)) | (v2 x1) := (v2 x1) | (sing2 x1) := (sing2 x1) def evalB {A : Type} : ((InvolutiveAddMagmaSig A) → (InvolutiveAddMagmaSigTerm → A)) | In (plusL x1 x2) := ((plus In) (evalB In x1) (evalB In x2)) | In (primL x1) := ((prim In) (evalB In x1)) def evalCl {A : Type} : ((InvolutiveAddMagmaSig A) → ((ClInvolutiveAddMagmaSigTerm A) → A)) | In (sing x1) := x1 | In (plusCl x1 x2) := ((plus In) (evalCl In x1) (evalCl In x2)) | In (primCl x1) := ((prim In) (evalCl In x1)) def evalOpB {A : Type} {n : ℕ} : ((InvolutiveAddMagmaSig A) → ((vector A n) → ((OpInvolutiveAddMagmaSigTerm n) → A))) | In vars (v x1) := (nth vars x1) | In vars (plusOL x1 x2) := ((plus In) (evalOpB In vars x1) (evalOpB In vars x2)) | In vars (primOL x1) := ((prim In) (evalOpB In vars x1)) def evalOp {A : Type} {n : ℕ} : ((InvolutiveAddMagmaSig A) → ((vector A n) → ((OpInvolutiveAddMagmaSigTerm2 n A) → A))) | In vars (v2 x1) := (nth vars x1) | In vars (sing2 x1) := x1 | In vars (plusOL2 x1 x2) := ((plus In) (evalOp In vars x1) (evalOp In vars x2)) | In vars (primOL2 x1) := ((prim In) (evalOp In vars x1)) def inductionB {P : (InvolutiveAddMagmaSigTerm → Type)} : ((∀ (x1 x2 : InvolutiveAddMagmaSigTerm) , ((P x1) → ((P x2) → (P (plusL x1 x2))))) → ((∀ (x1 : InvolutiveAddMagmaSigTerm) , ((P x1) → (P (primL x1)))) → (∀ (x : InvolutiveAddMagmaSigTerm) , (P x)))) | pplusl ppriml (plusL x1 x2) := (pplusl _ _ (inductionB pplusl ppriml x1) (inductionB pplusl ppriml x2)) | pplusl ppriml (primL x1) := (ppriml _ (inductionB pplusl ppriml x1)) def inductionCl {A : Type} {P : ((ClInvolutiveAddMagmaSigTerm A) → Type)} : ((∀ (x1 : A) , (P (sing x1))) → ((∀ (x1 x2 : (ClInvolutiveAddMagmaSigTerm A)) , ((P x1) → ((P x2) → (P (plusCl x1 x2))))) → ((∀ (x1 : (ClInvolutiveAddMagmaSigTerm A)) , ((P x1) → (P (primCl x1)))) → (∀ (x : (ClInvolutiveAddMagmaSigTerm A)) , (P x))))) | psing ppluscl pprimcl (sing x1) := (psing x1) | psing ppluscl pprimcl (plusCl x1 x2) := (ppluscl _ _ (inductionCl psing ppluscl pprimcl x1) (inductionCl psing ppluscl pprimcl x2)) | psing ppluscl pprimcl (primCl x1) := (pprimcl _ (inductionCl psing ppluscl pprimcl x1)) def inductionOpB {n : ℕ} {P : ((OpInvolutiveAddMagmaSigTerm n) → Type)} : ((∀ (fin : (fin n)) , (P (v fin))) → ((∀ (x1 x2 : (OpInvolutiveAddMagmaSigTerm n)) , ((P x1) → ((P x2) → (P (plusOL x1 x2))))) → ((∀ (x1 : (OpInvolutiveAddMagmaSigTerm n)) , ((P x1) → (P (primOL x1)))) → (∀ (x : (OpInvolutiveAddMagmaSigTerm n)) , (P x))))) | pv pplusol pprimol (v x1) := (pv x1) | pv pplusol pprimol (plusOL x1 x2) := (pplusol _ _ (inductionOpB pv pplusol pprimol x1) (inductionOpB pv pplusol pprimol x2)) | pv pplusol pprimol (primOL x1) := (pprimol _ (inductionOpB pv pplusol pprimol x1)) def inductionOp {n : ℕ} {A : Type} {P : ((OpInvolutiveAddMagmaSigTerm2 n A) → Type)} : ((∀ (fin : (fin n)) , (P (v2 fin))) → ((∀ (x1 : A) , (P (sing2 x1))) → ((∀ (x1 x2 : (OpInvolutiveAddMagmaSigTerm2 n A)) , ((P x1) → ((P x2) → (P (plusOL2 x1 x2))))) → ((∀ (x1 : (OpInvolutiveAddMagmaSigTerm2 n A)) , ((P x1) → (P (primOL2 x1)))) → (∀ (x : (OpInvolutiveAddMagmaSigTerm2 n A)) , (P x)))))) | pv2 psing2 pplusol2 pprimol2 (v2 x1) := (pv2 x1) | pv2 psing2 pplusol2 pprimol2 (sing2 x1) := (psing2 x1) | pv2 psing2 pplusol2 pprimol2 (plusOL2 x1 x2) := (pplusol2 _ _ (inductionOp pv2 psing2 pplusol2 pprimol2 x1) (inductionOp pv2 psing2 pplusol2 pprimol2 x2)) | pv2 psing2 pplusol2 pprimol2 (primOL2 x1) := (pprimol2 _ (inductionOp pv2 psing2 pplusol2 pprimol2 x1)) def stageB : (InvolutiveAddMagmaSigTerm → (Staged InvolutiveAddMagmaSigTerm)) | (plusL x1 x2) := (stage2 plusL (codeLift2 plusL) (stageB x1) (stageB x2)) | (primL x1) := (stage1 primL (codeLift1 primL) (stageB x1)) def stageCl {A : Type} : ((ClInvolutiveAddMagmaSigTerm A) → (Staged (ClInvolutiveAddMagmaSigTerm A))) | (sing x1) := (Now (sing x1)) | (plusCl x1 x2) := (stage2 plusCl (codeLift2 plusCl) (stageCl x1) (stageCl x2)) | (primCl x1) := (stage1 primCl (codeLift1 primCl) (stageCl x1)) def stageOpB {n : ℕ} : ((OpInvolutiveAddMagmaSigTerm n) → (Staged (OpInvolutiveAddMagmaSigTerm n))) | (v x1) := (const (code (v x1))) | (plusOL x1 x2) := (stage2 plusOL (codeLift2 plusOL) (stageOpB x1) (stageOpB x2)) | (primOL x1) := (stage1 primOL (codeLift1 primOL) (stageOpB x1)) def stageOp {n : ℕ} {A : Type} : ((OpInvolutiveAddMagmaSigTerm2 n A) → (Staged (OpInvolutiveAddMagmaSigTerm2 n A))) | (sing2 x1) := (Now (sing2 x1)) | (v2 x1) := (const (code (v2 x1))) | (plusOL2 x1 x2) := (stage2 plusOL2 (codeLift2 plusOL2) (stageOp x1) (stageOp x2)) | (primOL2 x1) := (stage1 primOL2 (codeLift1 primOL2) (stageOp x1)) structure StagedRepr (A : Type) (Repr : (Type → Type)) : Type := (plusT : ((Repr A) → ((Repr A) → (Repr A)))) (primT : ((Repr A) → (Repr A))) end InvolutiveAddMagmaSig
134890e61e06d86626963b8c4acbccdf4652d765
6ccb5ca9e90a0387f7fd4ee6150c04fa815186c5
/Lie_theory/src/Algebra/tangent_bundle_derivation.lean
ad8df0c62d7a7290983aa84008a5441b38002d72
[]
no_license
AnthonyBordg/Geometry_in_Lean
a2d034aed2bc37041eff4bd5f3b0213f08b57e44
b0f11164e9f695097b5c0e404a0dc429cdc24bb8
refs/heads/master
1,677,197,927,686
1,612,521,636,000
1,612,521,636,000
235,324,945
0
0
null
1,610,621,725,000
1,579,605,620,000
Lean
UTF-8
Lean
false
false
8,139
lean
import geometry.manifold.algebra.smooth_functions import ring_theory.derivation import geometry.manifold.temporary_to_be_removed variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {H : Type*} [topological_space H] (I : model_with_corners 𝕜 E H) (M : Type*) [topological_space M] [charted_space H M] [smooth_manifold_with_corners I M] open_locale manifold def module_point_derivation (x : M) : module C∞(I, M; 𝕜) 𝕜 := { smul := λ f k, f x * k, one_smul := λ k, one_mul k, mul_smul := λ f g k, mul_assoc _ _ _, smul_add := λ f g k, mul_add _ _ _, smul_zero := λ f, mul_zero _, add_smul := λ f g k, add_mul _ _ _, zero_smul := λ f, zero_mul _ } def compatible_semimodule_tangent_space (x : M) : @compatible_semimodule 𝕜 C∞(I, M; 𝕜) _ _ _ 𝕜 _ (module_point_derivation I M x) _ := { compatible_smul := λ h k, rfl, } @[reducible] def point_derivation (x : M) := @derivation 𝕜 C∞(I, M; 𝕜) _ _ _ 𝕜 _ (module_point_derivation I M x) _ (compatible_semimodule_tangent_space I M x) def tangent_bundle_derivation := Σ x : M, point_derivation I M x /-instance : has_add (tangent_bundle_derivation I M) := { add := λ v w, sigma.mk v.1 (v.2 + w.2) }-/ variables {I M} def tangent_space_inclusion {x : M} (v : point_derivation I M x) : tangent_bundle_derivation I M := sigma.mk x v /- Something weird is happening. Does not find the instance of smooth manifolds with corners. Moreover if I define it as a reducible def .eval does not work... It also takes very long time to typecheck -/ section namespace point_derivation variables {I} {M} {x y : M} {v w : point_derivation I M x} (f g : C∞(I, M; 𝕜)) (r : 𝕜) lemma coe_injective (h : ⇑v = w) : v = w := @derivation.coe_injective 𝕜 _ C∞(I, M; 𝕜) _ _ 𝕜 _ (module_point_derivation I M x) _ (compatible_semimodule_tangent_space I M x) v w h @[ext] theorem ext (h : ∀ f, v f = w f) : v = w := coe_injective $ funext h variables {u : point_derivation I M y} theorem hext (h1 : x = y) (h2 : ∀ f, v f = u f) : v == u := begin cases h1, rw heq_iff_eq at *, ext, exact h2 f, end end point_derivation end section variables {I} {M} {X Y : vector_field_derivation I M} (f g : C∞(I, M; 𝕜)) (r : 𝕜) namespace vector_field_derivation instance : has_coe_to_fun (vector_field_derivation I M) := ⟨_, λ X, X.to_linear_map.to_fun⟩ instance has_coe_to_derivation : has_coe (vector_field_derivation I M) (derivation 𝕜 C∞(I, M; 𝕜) C∞(I, M; 𝕜)) := ⟨to_derivation⟩ instance has_coe_to_linear_map : has_coe (vector_field_derivation I M) (C∞(I, M; 𝕜) →ₗ[𝕜] C∞(I, M; 𝕜)) := ⟨λ X, X.to_linear_map⟩ @[simp] lemma to_fun_eq_coe : X.to_fun = ⇑X := rfl @[simp, norm_cast] lemma coe_linear_map (X : vector_field_derivation I M) : ⇑(X : C∞(I, M; 𝕜) →ₗ[𝕜] C∞(I, M; 𝕜)) = X := rfl lemma coe_injective (h : ⇑X = Y) : X = Y := by { cases X, cases Y, congr', exact derivation.coe_injective h } @[ext] theorem ext (h : ∀ f, X f = Y f) : X = Y := coe_injective $ funext h variables (X Y) @[simp] lemma map_add : X (f + g) = X f + X g := derivation.map_add _ _ _ @[simp] lemma map_zero : X 0 = 0 := derivation.map_zero _ @[simp] lemma map_smul : X (r • f) = r • X f := derivation.map_smul _ _ _ @[simp] lemma leibniz : X (f * g) = f • X g + g • X f := derivation.leibniz _ _ _ @[simp] lemma map_one_eq_zero : X 1 = 0 := derivation.map_one_eq_zero _ @[simp] lemma map_neg : X (-f) = -X f := derivation.map_neg _ _ @[simp] lemma map_sub : X (f - g) = X f - X g := derivation.map_sub _ _ _ instance : has_zero (vector_field_derivation I M) := ⟨⟨(0 : derivation 𝕜 C∞(I, M; 𝕜) C∞(I, M; 𝕜))⟩⟩ instance : inhabited (vector_field_derivation I M) := ⟨0⟩ instance : add_comm_group (vector_field_derivation I M) := { add := λ X Y, ⟨X + Y⟩, add_assoc := λ X Y Z, ext $ λ a, add_assoc _ _ _, zero_add := λ X, ext $ λ a, zero_add _, add_zero := λ X, ext $ λ a, add_zero _, add_comm := λ X Y, ext $ λ a, add_comm _ _, neg := λ X, ⟨-X⟩, add_left_neg := λ X, ext $ λ a, add_left_neg _, ..vector_field_derivation.has_zero } @[simp] lemma add_apply : (X + Y) f = X f + Y f := rfl @[simp] lemma zero_apply : (0 : vector_field_derivation I M) f = 0 := rfl instance : has_bracket (vector_field_derivation I M) := { bracket := λ X Y, ⟨⁅X, Y⁆⟩ } @[simp] lemma commutator_to_derivation_coe : ⁅X, Y⁆.to_derivation = ⁅X, Y⁆ := rfl @[simp] lemma commutator_coe_derivation : ⇑⁅X, Y⁆ = (⁅X, Y⁆ : derivation 𝕜 C∞(I, M; 𝕜) C∞(I, M; 𝕜)) := rfl @[simp] lemma commutator_apply : ⁅X, Y⁆ f = X (Y f) - Y (X f) := by rw [commutator_coe_derivation, derivation.commutator_apply]; refl instance : lie_ring (vector_field_derivation I M) := { add_lie := λ X Y Z, by { ext1 f, simp only [commutator_apply, add_apply, map_add], ring, }, lie_add := λ X Y Z, by { ext1 f, simp only [commutator_apply, add_apply, map_add], ring }, lie_self := λ X, by { ext1 f, simp only [commutator_apply, zero_apply, sub_self] }, jacobi := λ X Y Z, by { ext1 f, simp only [commutator_apply, add_apply, map_sub, zero_apply], ring }, } instance : has_scalar 𝕜 (vector_field_derivation I M) := { smul := λ k X, ⟨k • X⟩ } instance kmodule : module 𝕜 (vector_field_derivation I M) := semimodule.of_core $ { mul_smul := λ r s X, ext $ λ b, mul_smul _ _ _, one_smul := λ X, ext $ λ b, one_smul 𝕜 _, smul_add := λ r X Y, ext $ λ b, smul_add _ _ _, add_smul := λ r s X, ext $ λ b, add_smul _ _ _, ..vector_field_derivation.has_scalar } @[simp] lemma smul_apply : (r • X) f = r • X f := rfl instance : lie_algebra 𝕜 (vector_field_derivation I M) := { lie_smul := λ X Y Z, by { ext1 f, simp only [commutator_apply, smul_apply, map_smul, smul_sub] }, ..vector_field_derivation.kmodule, } def eval (X : vector_field_derivation I M) (x : M) : point_derivation I M x := { to_fun := λ f, (X f) x, map_add' := λ f g, by { rw map_add, refl }, map_smul' := λ f g, by { rw [map_smul, algebra.id.smul_eq_mul], refl }, leibniz' := λ h k, by { dsimp only [], rw [leibniz, algebra.id.smul_eq_mul], refl } } @[simp] lemma eval_apply (x : M) : X.eval x f = (X f) x := rfl @[simp] lemma eval_add (x : M) : (X + Y).eval x = X.eval x + Y.eval x := by ext f; simp only [derivation.add_apply, add_apply, eval_apply, smooth_map.add_apply] /- to be moved -/ @[simp] lemma ring_commutator.apply {α : Type*} {R : Type*} [ring R] (f g : α → R) (a : α) : ⁅f, g⁆ a = ⁅f a, g a⁆ := by simp only [ring_commutator.commutator, pi.mul_apply, pi.sub_apply] /- instance : has_coe_to_fun (vector_field_derivation I M) := ⟨_, λ X, eval X⟩ polymorphysm of coercions to functions is not possible? -/ end vector_field_derivation variables {E' : Type*} [normed_group E'] [normed_space 𝕜 E'] {H' : Type*} [topological_space H'] {I' : model_with_corners 𝕜 E' H'} {M' : Type*} [topological_space M'] [charted_space H' M'] [smooth_manifold_with_corners I' M'] def fdifferential (f : C∞(I, M; I', M')) (x : M) (v : point_derivation I M x) : (point_derivation I' M' (f x)) := { to_fun := λ g, v (g.comp f), map_add' := λ g h, by { rw smooth_map.add_comp, }, map_smul' := λ k g, by { rw smooth_map.smul_comp, }, leibniz' := λ f g, by {dsimp only [], sorry}, } /-TODO: change it so that it is a linear map -/ localized "notation `fd` := fdifferential" in manifold lemma apply_fdifferential (f : C∞(I, M; I', M')) (x : M) (v : point_derivation I M x) (g : C∞(I', M'; 𝕜)) : fd f x v g = v (g.comp f) := rfl variables {E'' : Type*} [normed_group E''] [normed_space 𝕜 E''] {H'' : Type*} [topological_space H''] {I'' : model_with_corners 𝕜 E'' H''} {M'' : Type*} [topological_space M''] [charted_space H'' M''] [smooth_manifold_with_corners I'' M''] @[simp] lemma fdifferential_comp (g : C∞(I', M'; I'', M'')) (f : C∞(I, M; I', M')) (x : M) : (fd g (f x)) ∘ (fd f x) = fd (g.comp f) x := by { ext, simp only [apply_fdifferential], refl } end
09873c285d3fe1fe0bd4d3cb1b1be2d75a522b8f
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/ring_theory/localization.lean
c7ef5d24c233bf936946d0baa620ef8048dafd7a
[ "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
24,603
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Mario Carneiro, Johan Commelin -/ import tactic.ring data.quot data.equiv.algebra ring_theory.ideal_operations group_theory.submonoid universes u v namespace localization variables (α : Type u) [comm_ring α] (S : set α) [is_submonoid S] def r (x y : α × S) : Prop := ∃ t ∈ S, ((x.2 : α) * y.1 - y.2 * x.1) * t = 0 local infix ≈ := r α S section variables {α S} theorem r_of_eq {a₀ a₁ : α × S} (h : (a₀.2 : α) * a₁.1 = a₁.2 * a₀.1) : a₀ ≈ a₁ := ⟨1, is_submonoid.one_mem S, by rw [h, sub_self, mul_one]⟩ end theorem refl (x : α × S) : x ≈ x := r_of_eq rfl theorem symm (x y : α × S) : x ≈ y → y ≈ x := λ ⟨t, hts, ht⟩, ⟨t, hts, by rw [← neg_sub, ← neg_mul_eq_neg_mul, ht, neg_zero]⟩ theorem trans : ∀ (x y z : α × S), x ≈ y → y ≈ z → x ≈ z := λ ⟨r₁, s₁, hs₁⟩ ⟨r₂, s₂, hs₂⟩ ⟨r₃, s₃, hs₃⟩ ⟨t, hts, ht⟩ ⟨t', hts', ht'⟩, ⟨s₂ * t' * t, is_submonoid.mul_mem (is_submonoid.mul_mem hs₂ hts') hts, calc (s₁ * r₃ - s₃ * r₁) * (s₂ * t' * t) = t' * s₃ * ((s₁ * r₂ - s₂ * r₁) * t) + t * s₁ * ((s₂ * r₃ - s₃ * r₂) * t') : by simp [mul_left_comm, mul_add, mul_comm] ... = 0 : by simp only [subtype.coe_mk] at ht ht'; rw [ht, ht']; simp⟩ instance : setoid (α × S) := ⟨r α S, refl α S, symm α S, trans α S⟩ end localization /-- The localization of a ring at a submonoid: the elements of the submonoid become invertible in the localization.-/ def localization (α : Type u) [comm_ring α] (S : set α) [is_submonoid S] := quotient $ localization.setoid α S namespace localization variables (α : Type u) [comm_ring α] (S : set α) [is_submonoid S] instance : has_add (localization α S) := ⟨quotient.lift₂ (λ x y : α × S, (⟦⟨x.2 * y.1 + y.2 * x.1, x.2 * y.2⟩⟧ : localization α S)) $ λ ⟨r₁, s₁, hs₁⟩ ⟨r₂, s₂, hs₂⟩ ⟨r₃, s₃, hs₃⟩ ⟨r₄, s₄, hs₄⟩ ⟨t₅, hts₅, ht₅⟩ ⟨t₆, hts₆, ht₆⟩, quotient.sound ⟨t₆ * t₅, is_submonoid.mul_mem hts₆ hts₅, calc (s₁ * s₂ * (s₃ * r₄ + s₄ * r₃) - s₃ * s₄ * (s₁ * r₂ + s₂ * r₁)) * (t₆ * t₅) = s₁ * s₃ * ((s₂ * r₄ - s₄ * r₂) * t₆) * t₅ + s₂ * s₄ * ((s₁ * r₃ - s₃ * r₁) * t₅) * t₆ : by ring ... = 0 : by simp only [subtype.coe_mk] at ht₅ ht₆; rw [ht₆, ht₅]; simp⟩⟩ instance : has_neg (localization α S) := ⟨quotient.lift (λ x : α × S, (⟦⟨-x.1, x.2⟩⟧ : localization α S)) $ λ ⟨r₁, s₁, hs₁⟩ ⟨r₂, s₂, hs₂⟩ ⟨t, hts, ht⟩, quotient.sound ⟨t, hts, calc (s₁ * -r₂ - s₂ * -r₁) * t = -((s₁ * r₂ - s₂ * r₁) * t) : by ring ... = 0 : by simp only [subtype.coe_mk] at ht; rw ht; simp⟩⟩ instance : has_mul (localization α S) := ⟨quotient.lift₂ (λ x y : α × S, (⟦⟨x.1 * y.1, x.2 * y.2⟩⟧ : localization α S)) $ λ ⟨r₁, s₁, hs₁⟩ ⟨r₂, s₂, hs₂⟩ ⟨r₃, s₃, hs₃⟩ ⟨r₄, s₄, hs₄⟩ ⟨t₅, hts₅, ht₅⟩ ⟨t₆, hts₆, ht₆⟩, quotient.sound ⟨t₆ * t₅, is_submonoid.mul_mem hts₆ hts₅, calc ((s₁ * s₂) * (r₃ * r₄) - (s₃ * s₄) * (r₁ * r₂)) * (t₆ * t₅) = t₆ * ((s₁ * r₃ - s₃ * r₁) * t₅) * r₂ * s₄ + t₅ * ((s₂ * r₄ - s₄ * r₂) * t₆) * r₃ * s₁ : by simp [mul_left_comm, mul_add, mul_comm] ... = 0 : by simp only [subtype.coe_mk] at ht₅ ht₆; rw [ht₅, ht₆]; simp⟩⟩ variables {α S} def mk (r : α) (s : S) : localization α S := ⟦(r, s)⟧ /-- The natural map from the ring to the localization.-/ def of (r : α) : localization α S := mk r 1 instance : comm_ring (localization α S) := by refine { add := has_add.add, add_assoc := λ m n k, quotient.induction_on₃ m n k _, zero := of 0, zero_add := quotient.ind _, add_zero := quotient.ind _, neg := has_neg.neg, add_left_neg := quotient.ind _, add_comm := quotient.ind₂ _, mul := has_mul.mul, mul_assoc := λ m n k, quotient.induction_on₃ m n k _, one := of 1, one_mul := quotient.ind _, mul_one := quotient.ind _, left_distrib := λ m n k, quotient.induction_on₃ m n k _, right_distrib := λ m n k, quotient.induction_on₃ m n k _, mul_comm := quotient.ind₂ _ }; { intros, try {rcases a with ⟨r₁, s₁, hs₁⟩}, try {rcases b with ⟨r₂, s₂, hs₂⟩}, try {rcases c with ⟨r₃, s₃, hs₃⟩}, refine (quotient.sound $ r_of_eq _), simp [mul_left_comm, mul_add, mul_comm] } instance of.is_ring_hom : is_ring_hom (of : α → localization α S) := { map_add := λ x y, quotient.sound $ by simp, map_mul := λ x y, quotient.sound $ by simp, map_one := rfl } variables {S} instance : has_coe α (localization α S) := ⟨of⟩ instance coe.is_ring_hom : is_ring_hom (coe : α → localization α S) := localization.of.is_ring_hom /-- The natural map from the submonoid to the unit group of the localization.-/ def to_units (s : S) : units (localization α S) := { val := s, inv := mk 1 s, val_inv := quotient.sound $ r_of_eq $ mul_assoc _ _ _, inv_val := quotient.sound $ r_of_eq $ show s.val * 1 * 1 = 1 * (1 * s.val), by simp } @[simp] lemma to_units_coe (s : S) : ((to_units s) : localization α S) = s := rfl section variables (α S) (x y : α) (n : ℕ) @[simp] lemma of_zero : (of 0 : localization α S) = 0 := rfl @[simp] lemma of_one : (of 1 : localization α S) = 1 := rfl @[simp] lemma of_add : (of (x + y) : localization α S) = of x + of y := by apply is_ring_hom.map_add @[simp] lemma of_sub : (of (x - y) : localization α S) = of x - of y := by apply is_ring_hom.map_sub @[simp] lemma of_mul : (of (x * y) : localization α S) = of x * of y := by apply is_ring_hom.map_mul @[simp] lemma of_neg : (of (-x) : localization α S) = -of x := by apply is_ring_hom.map_neg @[simp] lemma of_pow : (of (x ^ n) : localization α S) = (of x) ^ n := by apply is_semiring_hom.map_pow @[simp] lemma of_is_unit (s : S) : is_unit (of s : localization α S) := is_unit_unit $ to_units s @[simp] lemma of_is_unit' (s ∈ S) : is_unit (of s : localization α S) := is_unit_unit $ to_units ⟨s, ‹s ∈ S›⟩ @[simp] lemma coe_zero : ((0 : α) : localization α S) = 0 := rfl @[simp] lemma coe_one : ((1 : α) : localization α S) = 1 := rfl @[simp] lemma coe_add : (↑(x + y) : localization α S) = x + y := of_add _ _ _ _ @[simp] lemma coe_sub : (↑(x - y) : localization α S) = x - y := of_sub _ _ _ _ @[simp] lemma coe_mul : (↑(x * y) : localization α S) = x * y := of_mul _ _ _ _ @[simp] lemma coe_neg : (↑(-x) : localization α S) = -x := of_neg _ _ _ @[simp] lemma coe_pow : (↑(x ^ n) : localization α S) = x ^ n := of_pow _ _ _ _ @[simp] lemma coe_is_unit (s : S) : is_unit (s : localization α S) := of_is_unit _ _ _ @[simp] lemma coe_is_unit' (s ∈ S) : is_unit (s : localization α S) := of_is_unit' _ _ _ ‹s ∈ S› end @[simp] lemma mk_self {x : α} {hx : x ∈ S} : (mk x ⟨x, hx⟩ : localization α S) = 1 := quotient.sound ⟨1, is_submonoid.one_mem S, by simp only [subtype.coe_mk, is_submonoid.coe_one, mul_one, one_mul, sub_self]⟩ @[simp] lemma mk_self' {s : S} : (mk s s : localization α S) = 1 := by cases s; exact mk_self @[simp] lemma mk_self'' {s : S} : (mk s.1 s : localization α S) = 1 := mk_self' @[simp] lemma coe_mul_mk (x y : α) (s : S) : ↑x * mk y s = mk (x * y) s := quotient.sound $ r_of_eq $ by rw one_mul lemma mk_eq_mul_mk_one (r : α) (s : S) : mk r s = r * mk 1 s := by rw [coe_mul_mk, mul_one] @[simp] lemma mk_mul_mk (x y : α) (s t : S) : mk x s * mk y t = mk (x * y) (s * t) := rfl @[simp] lemma mk_mul_cancel_left (r : α) (s : S) : mk (↑s * r) s = r := by rw [mk_eq_mul_mk_one, mul_comm ↑s, coe_mul, mul_assoc, ← mk_eq_mul_mk_one, mk_self', mul_one] @[simp] lemma mk_mul_cancel_right (r : α) (s : S) : mk (r * s) s = r := by rw [mul_comm, mk_mul_cancel_left] @[simp] lemma mk_eq (r : α) (s : S) : mk r s = r * ((to_units s)⁻¹ : units _) := quotient.sound $ by simp @[elab_as_eliminator] protected theorem induction_on {C : localization α S → Prop} (x : localization α S) (ih : ∀ r s, C (mk r s : localization α S)) : C x := by rcases x with ⟨r, s⟩; exact ih r s section variables {β : Type v} [comm_ring β] {T : set β} [is_submonoid T] (f : α → β) [is_ring_hom f] @[elab_with_expected_type] def lift' (g : S → units β) (hg : ∀ s, (g s : β) = f s) (x : localization α S) : β := quotient.lift_on x (λ p, f p.1 * ((g p.2)⁻¹ : units β)) $ λ ⟨r₁, s₁⟩ ⟨r₂, s₂⟩ ⟨t, hts, ht⟩, show f r₁ * ↑(g s₁)⁻¹ = f r₂ * ↑(g s₂)⁻¹, from calc f r₁ * ↑(g s₁)⁻¹ = (f r₁ * g s₂ + ((g s₁ * f r₂ - g s₂ * f r₁) * g ⟨t, hts⟩) * ↑(g ⟨t, hts⟩)⁻¹) * ↑(g s₁)⁻¹ * ↑(g s₂)⁻¹ : by simp only [hg, subtype.coe_mk, (is_ring_hom.map_mul f).symm, (is_ring_hom.map_sub f).symm, ht, is_ring_hom.map_zero f, zero_mul, add_zero]; rw [is_ring_hom.map_mul f, ← hg, mul_right_comm, mul_assoc (f r₁), ← units.coe_mul, mul_inv_self]; rw [units.coe_one, mul_one] ... = f r₂ * ↑(g s₂)⁻¹ : by rw [mul_assoc, mul_assoc, ← units.coe_mul, mul_inv_self, units.coe_one, mul_one, mul_comm ↑(g s₂), add_sub_cancel'_right]; rw [mul_comm ↑(g s₁), ← mul_assoc, mul_assoc (f r₂), ← units.coe_mul, mul_inv_self, units.coe_one, mul_one] instance lift'.is_ring_hom (g : S → units β) (hg : ∀ s, (g s : β) = f s) : is_ring_hom (localization.lift' f g hg) := { map_one := have g 1 = 1, from units.ext (by rw hg; exact is_ring_hom.map_one f), show f 1 * ↑(g 1)⁻¹ = 1, by rw [this, one_inv, units.coe_one, mul_one, is_ring_hom.map_one f], map_mul := λ x y, localization.induction_on x $ λ r₁ s₁, localization.induction_on y $ λ r₂ s₂, have g (s₁ * s₂) = g s₁ * g s₂, from units.ext (by simp only [hg, units.coe_mul]; exact is_ring_hom.map_mul f), show _ * ↑(g (_ * _))⁻¹ = (_ * _) * (_ * _), by simp only [subtype.coe_mk, mul_one, one_mul, subtype.coe_eta, this, mul_inv_rev]; rw [is_ring_hom.map_mul f, units.coe_mul, ← mul_assoc, ← mul_assoc]; simp only [mul_right_comm], map_add := λ x y, localization.induction_on x $ λ r₁ s₁, localization.induction_on y $ λ r₂ s₂, have g (s₁ * s₂) = g s₁ * g s₂, from units.ext (by simp only [hg, units.coe_mul]; exact is_ring_hom.map_mul f), show _ * ↑(g (_ * _))⁻¹ = _ * _ + _ * _, by simp only [subtype.coe_mk, mul_one, one_mul, subtype.coe_eta, this, mul_inv_rev]; simp only [is_ring_hom.map_mul f, is_ring_hom.map_add f, add_mul, (hg _).symm]; simp only [mul_assoc, mul_comm, mul_left_comm, (units.coe_mul _ _).symm]; rw [mul_inv_cancel_left, mul_left_comm, ← mul_assoc, mul_inv_cancel_right, add_comm] } noncomputable def lift (h : ∀ s ∈ S, is_unit (f s)) : localization α S → β := localization.lift' f (λ s, classical.some $ h s.1 s.2) (λ s, by rw [← classical.some_spec (h s.1 s.2)]; refl) instance lift.is_ring_hom (h : ∀ s ∈ S, is_unit (f s)) : is_ring_hom (lift f h) := lift'.is_ring_hom _ _ _ @[simp] lemma lift'_mk (g : S → units β) (hg : ∀ s, (g s : β) = f s) (r : α) (s : S) : lift' f g hg (mk r s) = f r * ↑(g s)⁻¹ := rfl @[simp] lemma lift'_of (g : S → units β) (hg : ∀ s, (g s : β) = f s) (a : α) : lift' f g hg (of a) = f a := have g 1 = 1, from units.ext_iff.2 $ by simp [hg, is_ring_hom.map_one f], by simp [lift', quotient.lift_on_beta, of, mk, this] @[simp] lemma lift'_coe (g : S → units β) (hg : ∀ s, (g s : β) = f s) (a : α) : lift' f g hg a = f a := lift'_of _ _ _ _ @[simp] lemma lift_of (h : ∀ s ∈ S, is_unit (f s)) (a : α) : lift f h (of a) = f a := lift'_of _ _ _ _ @[simp] lemma lift_coe (h : ∀ s ∈ S, is_unit (f s)) (a : α) : lift f h a = f a := lift'_of _ _ _ _ @[simp] lemma lift'_comp_of (g : S → units β) (hg : ∀ s, (g s : β) = f s) : lift' f g hg ∘ of = f := funext $ λ a, lift'_of _ _ _ a @[simp] lemma lift_comp_of (h : ∀ s ∈ S, is_unit (f s)) : lift f h ∘ of = f := lift'_comp_of _ _ _ @[simp] lemma lift'_apply_coe (f : localization α S → β) [is_ring_hom f] (g : S → units β) (hg : ∀ s, (g s : β) = f s) : lift' (λ a : α, f a) g hg = f := have g = (λ s, units.map f (to_units s)), from funext $ λ x, units.ext_iff.2 $ (hg x).symm ▸ rfl, funext $ λ x, localization.induction_on x (λ r s, by subst this; rw [lift'_mk, ← is_group_hom.map_inv (units.map f), units.coe_map]; simp [is_ring_hom.map_mul f]) @[simp] lemma lift_apply_coe (f : localization α S → β) [is_ring_hom f] : lift (λ a : α, f a) (λ s hs, is_unit_unit (units.map f (to_units ⟨s, hs⟩))) = f := by rw [lift, lift'_apply_coe] /-- Function extensionality for localisations: two functions are equal if they agree on elements that are coercions.-/ protected lemma funext (f g : localization α S → β) [is_ring_hom f] [is_ring_hom g] (h : ∀ a : α, f a = g a) : f = g := begin rw [← lift_apply_coe f, ← lift_apply_coe g], congr' 1, exact funext h end variables {α S T} def map (hf : ∀ s ∈ S, f s ∈ T) : localization α S → localization β T := lift' (of ∘ f) (to_units ∘ subtype.map f hf) (λ s, rfl) instance map.is_ring_hom (hf : ∀ s ∈ S, f s ∈ T) : is_ring_hom (map f hf) := lift'.is_ring_hom _ _ _ @[simp] lemma map_of (hf : ∀ s ∈ S, f s ∈ T) (a : α) : map f hf (of a) = of (f a) := lift'_of _ _ _ _ @[simp] lemma map_coe (hf : ∀ s ∈ S, f s ∈ T) (a : α) : map f hf a = (f a) := lift'_of _ _ _ _ @[simp] lemma map_comp_of (hf : ∀ s ∈ S, f s ∈ T) : map f hf ∘ of = of ∘ f := funext $ λ a, map_of _ _ _ @[simp] lemma map_id : map id (λ s (hs : s ∈ S), hs) = id := localization.funext _ _ $ map_coe _ _ lemma map_comp_map {γ : Type*} [comm_ring γ] (hf : ∀ s ∈ S, f s ∈ T) (U : set γ) [is_submonoid U] (g : β → γ) [is_ring_hom g] (hg : ∀ t ∈ T, g t ∈ U) : map g hg ∘ map f hf = map (λ x, g (f x)) (λ s hs, hg _ (hf _ hs)) := localization.funext _ _ $ by simp lemma map_map {γ : Type*} [comm_ring γ] (hf : ∀ s ∈ S, f s ∈ T) (U : set γ) [is_submonoid U] (g : β → γ) [is_ring_hom g] (hg : ∀ t ∈ T, g t ∈ U) (x) : map g hg (map f hf x) = map (λ x, g (f x)) (λ s hs, hg _ (hf _ hs)) x := congr_fun (map_comp_map _ _ _ _ _) x def equiv_of_equiv (h₁ : α ≃r β) (h₂ : h₁.to_equiv '' S = T) : localization α S ≃r localization β T := { to_fun := map h₁.to_equiv $ λ s hs, by {rw ← h₂, simp [hs]}, inv_fun := map h₁.symm.to_equiv $ λ t ht, by simp [equiv.image_eq_preimage, set.preimage, set.ext_iff, *] at *, left_inv := λ _, by simp only [map_map, ring_equiv.to_equiv_symm_apply, equiv.symm_apply_apply]; erw map_id; refl, right_inv := λ _, by simp only [map_map, ring_equiv.to_equiv_symm_apply, equiv.apply_symm_apply]; erw map_id; refl, hom := map.is_ring_hom _ _ } end section away variables {β : Type v} [comm_ring β] (f : α → β) [is_ring_hom f] @[reducible] def away (x : α) := localization α (powers x) @[simp] def away.inv_self (x : α) : away x := mk 1 ⟨x, 1, pow_one x⟩ @[elab_with_expected_type] noncomputable def away.lift {x : α} (hfx : is_unit (f x)) : away x → β := localization.lift' f (λ s, classical.some hfx ^ classical.some s.2) $ λ s, by rw [units.coe_pow, ← classical.some_spec hfx, ← is_semiring_hom.map_pow f, classical.some_spec s.2]; refl instance away.lift.is_ring_hom {x : α} (hfx : is_unit (f x)) : is_ring_hom (localization.away.lift f hfx) := lift'.is_ring_hom _ _ _ @[simp] lemma away.lift_of {x : α} (hfx : is_unit (f x)) (a : α) : away.lift f hfx (of a) = f a := lift'_of _ _ _ _ @[simp] lemma away.lift_coe {x : α} (hfx : is_unit (f x)) (a : α) : away.lift f hfx a = f a := lift'_of _ _ _ _ @[simp] lemma away.lift_comp_of {x : α} (hfx : is_unit (f x)) : away.lift f hfx ∘ of = f := lift'_comp_of _ _ _ noncomputable def away_to_away_right (x y : α) : away x → away (x * y) := localization.away.lift coe $ is_unit_of_mul_one x (y * away.inv_self (x * y)) $ by rw [away.inv_self, coe_mul_mk, coe_mul_mk, mul_one, mk_self] instance away_to_away_right.is_ring_hom (x y : α) : is_ring_hom (away_to_away_right x y) := away.lift.is_ring_hom _ _ end away section at_prime variables (P : ideal α) [hp : ideal.is_prime P] include hp instance prime.is_submonoid : is_submonoid (-P : set α) := { one_mem := P.ne_top_iff_one.1 hp.1, mul_mem := λ x y hnx hny hxy, or.cases_on (hp.2 hxy) hnx hny } @[reducible] def at_prime := localization α (-P) instance at_prime.local_ring : is_local_ring (at_prime P) := local_of_nonunits_ideal (λ hze, let ⟨t, hts, ht⟩ := quotient.exact hze in hts $ have htz : t = 0, by simpa using ht, suffices (0:α) ∈ P, by rwa htz, P.zero_mem) (begin rintro ⟨⟨r₁, s₁, hs₁⟩⟩ ⟨⟨r₂, s₂, hs₂⟩⟩ hx hy hu, rcases is_unit_iff_exists_inv.1 hu with ⟨⟨⟨r₃, s₃, hs₃⟩⟩, hz⟩, rcases quotient.exact hz with ⟨t, hts, ht⟩, simp at ht, have : ∀ {r s hs}, (⟦⟨r, s, hs⟩⟧ : at_prime P) ∈ nonunits (at_prime P) → r ∈ P, { haveI := classical.dec, exact λ r s hs, not_imp_comm.1 (λ nr, is_unit_iff_exists_inv.2 ⟨⟦⟨s, r, nr⟩⟧, quotient.sound $ r_of_eq $ by simp [mul_comm]⟩) }, have hr₃ := (hp.mem_or_mem_of_mul_eq_zero ht).resolve_right hts, have := (ideal.add_mem_iff_left _ _).1 hr₃, { exact not_or (mt hp.mem_or_mem (not_or hs₁ hs₂)) hs₃ (hp.mem_or_mem this) }, { exact P.neg_mem (P.mul_mem_right (P.add_mem (P.mul_mem_left (this hy)) (P.mul_mem_left (this hx)))) } end) end at_prime variable (α) def non_zero_divisors : set α := {x | ∀ z, z * x = 0 → z = 0} instance non_zero_divisors.is_submonoid : is_submonoid (non_zero_divisors α) := { one_mem := λ z hz, by rwa mul_one at hz, mul_mem := λ x₁ x₂ hx₁ hx₂ z hz, have z * x₁ * x₂ = 0, by rwa mul_assoc, hx₁ z $ hx₂ (z * x₁) this } @[simp] lemma non_zero_divisors_one_val : (1 : non_zero_divisors α).val = 1 := rfl /-- The field of fractions of an integral domain.-/ @[reducible] def fraction_ring := localization α (non_zero_divisors α) namespace fraction_ring open function variables {β : Type u} [integral_domain β] [decidable_eq β] lemma eq_zero_of_ne_zero_of_mul_eq_zero {x y : β} : x ≠ 0 → y * x = 0 → y = 0 := λ hnx hxy, or.resolve_right (eq_zero_or_eq_zero_of_mul_eq_zero hxy) hnx lemma mem_non_zero_divisors_iff_ne_zero {x : β} : x ∈ non_zero_divisors β ↔ x ≠ 0 := ⟨λ hm hz, zero_ne_one (hm 1 $ by rw [hz, one_mul]).symm, λ hnx z, eq_zero_of_ne_zero_of_mul_eq_zero hnx⟩ variable (β) def inv_aux (x : β × (non_zero_divisors β)) : fraction_ring β := if h : x.1 = 0 then 0 else ⟦⟨x.2, x.1, mem_non_zero_divisors_iff_ne_zero.mpr h⟩⟧ instance : has_inv (fraction_ring β) := ⟨quotient.lift (inv_aux β) $ λ ⟨r₁, s₁, hs₁⟩ ⟨r₂, s₂, hs₂⟩ ⟨t, hts, ht⟩, begin have hrs : s₁ * r₂ = 0 + s₂ * r₁, from sub_eq_iff_eq_add.1 (hts _ ht), by_cases hr₁ : r₁ = 0; by_cases hr₂ : r₂ = 0; simp [hr₁, hr₂] at hrs; simp only [inv_aux, hr₁, hr₂, dif_pos, dif_neg, not_false_iff, subtype.coe_mk, quotient.eq], { exfalso, exact mem_non_zero_divisors_iff_ne_zero.mp hs₁ hrs }, { exfalso, exact mem_non_zero_divisors_iff_ne_zero.mp hs₂ hrs }, { apply r_of_eq, simpa [mul_comm] using hrs.symm } end⟩ lemma mk_inv {r s} : (mk r s : fraction_ring β)⁻¹ = if h : r = 0 then 0 else ⟦⟨s, r, mem_non_zero_divisors_iff_ne_zero.mpr h⟩⟧ := rfl lemma mk_inv' : ∀ (x : β × (non_zero_divisors β)), (⟦x⟧⁻¹ : fraction_ring β) = if h : x.1 = 0 then 0 else ⟦⟨x.2.val, x.1, mem_non_zero_divisors_iff_ne_zero.mpr h⟩⟧ | ⟨r,s,hs⟩ := rfl instance : decidable_eq (fraction_ring β) := @quotient.decidable_eq (β × non_zero_divisors β) (localization.setoid β (non_zero_divisors β)) $ λ ⟨r₁, s₁, hs₁⟩ ⟨r₂, s₂, hs₂⟩, show decidable (∃ t ∈ non_zero_divisors β, (s₁ * r₂ - s₂ * r₁) * t = 0), from decidable_of_iff (s₁ * r₂ - s₂ * r₁ = 0) ⟨λ H, ⟨1, λ y, (mul_one y).symm ▸ id, H.symm ▸ zero_mul _⟩, λ ⟨t, ht1, ht2⟩, or.resolve_right (mul_eq_zero.1 ht2) $ λ ht, one_ne_zero (ht1 1 ((one_mul t).symm ▸ ht))⟩ instance : discrete_field (fraction_ring β) := by refine { inv := has_inv.inv, zero_ne_one := λ hzo, let ⟨t, hts, ht⟩ := quotient.exact hzo in zero_ne_one (by simpa using hts _ ht : 0 = 1), mul_inv_cancel := quotient.ind _, inv_mul_cancel := quotient.ind _, has_decidable_eq := fraction_ring.decidable_eq β, inv_zero := dif_pos rfl, .. localization.comm_ring }; { intros x hnx, rcases x with ⟨x, z, hz⟩, have : x ≠ 0, from assume hx, hnx (quotient.sound $ r_of_eq $ by simp [hx]), simp only [has_inv.inv, inv_aux, quotient.lift_beta, dif_neg this], exact (quotient.sound $ r_of_eq $ by simp [mul_comm]) } @[simp] lemma mk_eq_div {r s} : (mk r s : fraction_ring β) = (r / s : fraction_ring β) := show _ = _ * dite (s.1 = 0) _ _, by rw [dif_neg (mem_non_zero_divisors_iff_ne_zero.mp s.2)]; exact localization.mk_eq_mul_mk_one _ _ variables {β} @[simp] lemma mk_eq_div' (x : β × (non_zero_divisors β)) : (⟦x⟧ : fraction_ring β) = ((x.1) / ((x.2).val) : fraction_ring β) := by erw ← mk_eq_div; cases x; refl lemma eq_zero_of (x : β) (h : (of x : fraction_ring β) = 0) : x = 0 := begin rcases quotient.exact h with ⟨t, ht, ht'⟩, simpa [mem_non_zero_divisors_iff_ne_zero.mp ht] using ht' end lemma of.injective : function.injective (of : β → fraction_ring β) := (is_add_group_hom.injective_iff _).mpr eq_zero_of section map open function is_ring_hom variables {A : Type u} [integral_domain A] [decidable_eq A] variables {B : Type v} [integral_domain B] [decidable_eq B] variables (f : A → B) [is_ring_hom f] def map (hf : injective f) : fraction_ring A → fraction_ring B := localization.map f $ λ s h, by rw [mem_non_zero_divisors_iff_ne_zero, ← map_zero f, ne.def, hf.eq_iff]; exact mem_non_zero_divisors_iff_ne_zero.1 h @[simp] lemma map_of (hf : injective f) (a : A) : map f hf (of a) = of (f a) := localization.map_of _ _ _ @[simp] lemma map_coe (hf : injective f) (a : A) : map f hf a = f a := localization.map_coe _ _ _ @[simp] lemma map_comp_of (hf : injective f) : map f hf ∘ (of : A → fraction_ring A) = (of : B → fraction_ring B) ∘ f := localization.map_comp_of _ _ instance map.is_field_hom (hf : injective f) : is_field_hom (map f hf) := localization.map.is_ring_hom _ _ def equiv_of_equiv (h : A ≃r B) : fraction_ring A ≃r fraction_ring B := localization.equiv_of_equiv h begin ext b, rw [equiv.image_eq_preimage, set.preimage, set.mem_set_of_eq, mem_non_zero_divisors_iff_ne_zero, mem_non_zero_divisors_iff_ne_zero, ne.def], exact ⟨mt (λ h, h.symm ▸ is_ring_hom.map_zero _), mt ((is_add_group_hom.injective_iff _).1 h.to_equiv.symm.injective _)⟩ end end map end fraction_ring section ideals theorem map_comap (J : ideal (localization α S)) : ideal.map coe (ideal.comap (coe : α → localization α S) J) = J := le_antisymm (ideal.map_le_iff_le_comap.2 (le_refl _)) $ λ x, localization.induction_on x $ λ r s hJ, (submodule.mem_coe _).2 $ mul_one r ▸ coe_mul_mk r 1 s ▸ (ideal.mul_mem_right _ $ ideal.mem_map_of_mem $ have _ := @ideal.mul_mem_left (localization α S) _ _ s _ hJ, by rwa [coe_coe, coe_mul_mk, mk_mul_cancel_left] at this) def le_order_embedding : ((≤) : ideal (localization α S) → ideal (localization α S) → Prop) ≼o ((≤) : ideal α → ideal α → Prop) := { to_fun := λ J, ideal.comap coe J, inj := function.injective_of_left_inverse (map_comap α), ord := λ J₁ J₂, ⟨ideal.comap_mono, λ hJ, map_comap α J₁ ▸ map_comap α J₂ ▸ ideal.map_mono hJ⟩ } end ideals end localization
4ea179a4cfbedae1cf333293aa4ad74788bc9b2f
b074a51e20fdb737b2d4c635dd292fc54685e010
/src/category_theory/monad/algebra.lean
6aaeafae3fd2aa1233757f48b2608dbbcd8bd6f8
[ "Apache-2.0" ]
permissive
minchaowu/mathlib
2daf6ffdb5a56eeca403e894af88bcaaf65aec5e
879da1cf04c2baa9eaa7bd2472100bc0335e5c73
refs/heads/master
1,609,628,676,768
1,564,310,105,000
1,564,310,105,000
99,461,307
0
0
null
null
null
null
UTF-8
Lean
false
false
3,134
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.monad.basic import category_theory.adjunction.basic namespace category_theory open category universes v₁ u₁ -- declare the `v`'s first; see `category_theory.category` for an explanation variables {C : Type u₁} [𝒞 : category.{v₁} C] include 𝒞 namespace monad structure algebra (T : C ⥤ C) [monad.{v₁} T] : Type (max u₁ v₁) := (A : C) (a : T.obj A ⟶ A) (unit' : (η_ T).app A ≫ a = 𝟙 A . obviously) (assoc' : ((μ_ T).app A ≫ a) = (T.map a ≫ a) . obviously) restate_axiom algebra.unit' restate_axiom algebra.assoc' namespace algebra variables {T : C ⥤ C} [monad.{v₁} T] structure hom (A B : algebra T) := (f : A.A ⟶ B.A) (h' : T.map f ≫ B.a = A.a ≫ f . obviously) restate_axiom hom.h' attribute [simp] hom.h namespace hom @[extensionality] lemma ext {A B : algebra T} (f g : hom A B) (w : f.f = g.f) : f = g := by { cases f, cases g, congr, assumption } def id (A : algebra T) : hom A A := { f := 𝟙 A.A } @[simp] lemma id_f (A : algebra T) : (id A).f = 𝟙 A.A := rfl def comp {P Q R : algebra T} (f : hom P Q) (g : hom Q R) : hom P R := { f := f.f ≫ g.f, h' := by rw [functor.map_comp, category.assoc, g.h, ←category.assoc, f.h, category.assoc] } @[simp] lemma comp_f {P Q R : algebra T} (f : hom P Q) (g : hom Q R) : (comp f g).f = f.f ≫ g.f := rfl end hom instance EilenbergMoore : category (algebra T) := { hom := hom, id := hom.id, comp := @hom.comp _ _ _ _ } @[simp] lemma id_f (P : algebra T) : hom.f (𝟙 P) = 𝟙 P.A := rfl @[simp] lemma comp_f {P Q R : algebra T} (f : P ⟶ Q) (g : Q ⟶ R) : (f ≫ g).f = f.f ≫ g.f := rfl end algebra variables (T : C ⥤ C) [monad.{v₁} T] def forget : algebra T ⥤ C := { obj := λ A, A.A, map := λ A B f, f.f } @[simp] lemma forget_map {X Y : algebra T} (f : X ⟶ Y) : (forget T).map f = f.f := rfl def free : C ⥤ algebra T := { obj := λ X, { A := T.obj X, a := (μ_ T).app X, assoc' := (monad.assoc T _).symm }, map := λ X Y f, { f := T.map f, h' := by erw (μ_ T).naturality } } @[simp] lemma free_obj_a (X) : ((free T).obj X).a = (μ_ T).app X := rfl @[simp] lemma free_map_f {X Y : C} (f : X ⟶ Y) : ((free T).map f).f = T.map f := rfl def adj : free T ⊣ forget T := adjunction.mk_of_hom_equiv { hom_equiv := λ X Y, { to_fun := λ f, (η_ T).app X ≫ f.f, inv_fun := λ f, { f := T.map f ≫ Y.a, h' := begin dsimp, simp, conv { to_rhs, rw [←category.assoc, ←(μ_ T).naturality, category.assoc], erw algebra.assoc }, refl, end }, left_inv := λ f, begin ext1, dsimp, simp only [free_obj_a, functor.map_comp, algebra.hom.h, category.assoc], erw [←category.assoc, monad.right_unit, id_comp], end, right_inv := λ f, begin dsimp, erw [←category.assoc, ←(η_ T).naturality, functor.id_map, category.assoc, Y.unit, comp_id], end }} end monad end category_theory
2b9f9719bc34bb94c683d42e5831a0c8334405db
7cef822f3b952965621309e88eadf618da0c8ae9
/src/data/num/lemmas.lean
b726d619aef5e46f2745549c0e33a1c7f14126bf
[ "Apache-2.0" ]
permissive
rmitta/mathlib
8d90aee30b4db2b013e01f62c33f297d7e64a43d
883d974b608845bad30ae19e27e33c285200bf84
refs/heads/master
1,585,776,832,544
1,576,874,096,000
1,576,874,096,000
153,663,165
0
2
Apache-2.0
1,544,806,490,000
1,539,884,365,000
Lean
UTF-8
Lean
false
false
49,231
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro Properties of the binary representation of integers. -/ import data.num.basic data.num.bitwise algebra.ordered_ring tactic.interactive data.int.basic data.nat.gcd namespace pos_num variables {α : Type*} @[simp] theorem cast_one [has_zero α] [has_one α] [has_add α] : ((1 : pos_num) : α) = 1 := rfl @[simp] theorem cast_one' [has_zero α] [has_one α] [has_add α] : (pos_num.one : α) = 1 := rfl @[simp] theorem cast_bit0 [has_zero α] [has_one α] [has_add α] (n : pos_num) : (n.bit0 : α) = _root_.bit0 n := rfl @[simp] theorem cast_bit1 [has_zero α] [has_one α] [has_add α] (n : pos_num) : (n.bit1 : α) = _root_.bit1 n := rfl @[simp] theorem cast_to_nat [add_monoid α] [has_one α] : ∀ n : pos_num, ((n : ℕ) : α) = n | 1 := nat.cast_one | (bit0 p) := (nat.cast_bit0 _).trans $ congr_arg _root_.bit0 p.cast_to_nat | (bit1 p) := (nat.cast_bit1 _).trans $ congr_arg _root_.bit1 p.cast_to_nat @[simp] theorem to_nat_to_int (n : pos_num) : ((n : ℕ) : ℤ) = n := by rw [← int.nat_cast_eq_coe_nat, cast_to_nat] @[simp] theorem cast_to_int [add_group α] [has_one α] (n : pos_num) : ((n : ℤ) : α) = n := by rw [← to_nat_to_int, int.cast_coe_nat, cast_to_nat] theorem succ_to_nat : ∀ n, (succ n : ℕ) = n + 1 | 1 := rfl | (bit0 p) := rfl | (bit1 p) := (congr_arg _root_.bit0 (succ_to_nat p)).trans $ show ↑p + 1 + ↑p + 1 = ↑p + ↑p + 1 + 1, by simp theorem one_add (n : pos_num) : 1 + n = succ n := by cases n; refl theorem add_one (n : pos_num) : n + 1 = succ n := by cases n; refl @[simp] theorem add_to_nat : ∀ m n, ((m + n : pos_num) : ℕ) = m + n | 1 b := by rw [one_add b, succ_to_nat, add_comm]; refl | a 1 := by rw [add_one a, succ_to_nat]; refl | (bit0 a) (bit0 b) := (congr_arg _root_.bit0 (add_to_nat a b)).trans $ show ((a + b) + (a + b) : ℕ) = (a + a) + (b + b), by simp | (bit0 a) (bit1 b) := (congr_arg _root_.bit1 (add_to_nat a b)).trans $ show ((a + b) + (a + b) + 1 : ℕ) = (a + a) + (b + b + 1), by simp | (bit1 a) (bit0 b) := (congr_arg _root_.bit1 (add_to_nat a b)).trans $ show ((a + b) + (a + b) + 1 : ℕ) = (a + a + 1) + (b + b), by simp | (bit1 a) (bit1 b) := show (succ (a + b) + succ (a + b) : ℕ) = (a + a + 1) + (b + b + 1), by rw [succ_to_nat, add_to_nat]; simp theorem add_succ : ∀ (m n : pos_num), m + succ n = succ (m + n) | 1 b := by simp [one_add] | (bit0 a) 1 := congr_arg bit0 (add_one a) | (bit1 a) 1 := congr_arg bit1 (add_one a) | (bit0 a) (bit0 b) := rfl | (bit0 a) (bit1 b) := congr_arg bit0 (add_succ a b) | (bit1 a) (bit0 b) := rfl | (bit1 a) (bit1 b) := congr_arg bit1 (add_succ a b) theorem bit0_of_bit0 : Π n, _root_.bit0 n = bit0 n | 1 := rfl | (bit0 p) := congr_arg bit0 (bit0_of_bit0 p) | (bit1 p) := show bit0 (succ (_root_.bit0 p)) = _, by rw bit0_of_bit0; refl theorem bit1_of_bit1 (n : pos_num) : _root_.bit1 n = bit1 n := show _root_.bit0 n + 1 = bit1 n, by rw [add_one, bit0_of_bit0]; refl @[simp] theorem mul_to_nat (m) : ∀ n, ((m * n : pos_num) : ℕ) = m * n | 1 := (mul_one _).symm | (bit0 p) := show (↑(m * p) + ↑(m * p) : ℕ) = ↑m * (p + p), by rw [mul_to_nat, left_distrib] | (bit1 p) := (add_to_nat (bit0 (m * p)) m).trans $ show (↑(m * p) + ↑(m * p) + ↑m : ℕ) = ↑m * (p + p) + m, by rw [mul_to_nat, left_distrib] theorem to_nat_pos : ∀ n : pos_num, 0 < (n : ℕ) | 1 := zero_lt_one | (bit0 p) := let h := to_nat_pos p in add_pos h h | (bit1 p) := nat.succ_pos _ theorem cmp_to_nat_lemma {m n : pos_num} : (m:ℕ) < n → (bit1 m : ℕ) < bit0 n := show (m:ℕ) < n → (m + m + 1 + 1 : ℕ) ≤ n + n, by intro h; rw [nat.add_right_comm m m 1, add_assoc]; exact add_le_add h h theorem cmp_swap (m) : ∀n, (cmp m n).swap = cmp n m := by induction m with m IH m IH; intro n; cases n with n n; try {unfold cmp}; try {refl}; rw ←IH; cases cmp m n; refl theorem cmp_to_nat : ∀ (m n), (ordering.cases_on (cmp m n) ((m:ℕ) < n) (m = n) ((m:ℕ) > n) : Prop) | 1 1 := rfl | (bit0 a) 1 := let h : (1:ℕ) ≤ a := to_nat_pos a in add_le_add h h | (bit1 a) 1 := nat.succ_lt_succ $ to_nat_pos $ bit0 a | 1 (bit0 b) := let h : (1:ℕ) ≤ b := to_nat_pos b in add_le_add h h | 1 (bit1 b) := nat.succ_lt_succ $ to_nat_pos $ bit0 b | (bit0 a) (bit0 b) := begin have := cmp_to_nat a b, revert this, cases cmp a b; dsimp; intro, { exact add_lt_add this this }, { rw this }, { exact add_lt_add this this } end | (bit0 a) (bit1 b) := begin dsimp [cmp], have := cmp_to_nat a b, revert this, cases cmp a b; dsimp; intro, { exact nat.le_succ_of_le (add_lt_add this this) }, { rw this, apply nat.lt_succ_self }, { exact cmp_to_nat_lemma this } end | (bit1 a) (bit0 b) := begin dsimp [cmp], have := cmp_to_nat a b, revert this, cases cmp a b; dsimp; intro, { exact cmp_to_nat_lemma this }, { rw this, apply nat.lt_succ_self }, { exact nat.le_succ_of_le (add_lt_add this this) }, end | (bit1 a) (bit1 b) := begin have := cmp_to_nat a b, revert this, cases cmp a b; dsimp; intro, { exact nat.succ_lt_succ (add_lt_add this this) }, { rw this }, { exact nat.succ_lt_succ (add_lt_add this this) } end @[simp] theorem lt_to_nat {m n : pos_num} : (m:ℕ) < n ↔ m < n := show (m:ℕ) < n ↔ cmp m n = ordering.lt, from match cmp m n, cmp_to_nat m n with | ordering.lt, h := by simp at h; simp [h] | ordering.eq, h := by simp at h; simp [h, lt_irrefl]; exact dec_trivial | ordering.gt, h := by simp [not_lt_of_gt h]; exact dec_trivial end @[simp] theorem le_to_nat {m n : pos_num} : (m:ℕ) ≤ n ↔ m ≤ n := by rw ← not_lt; exact not_congr lt_to_nat end pos_num namespace num variables {α : Type*} open pos_num theorem add_zero (n : num) : n + 0 = n := by cases n; refl theorem zero_add (n : num) : 0 + n = n := by cases n; refl theorem add_one : ∀ n : num, n + 1 = succ n | 0 := rfl | (pos p) := by cases p; refl theorem add_succ : ∀ (m n : num), m + succ n = succ (m + n) | 0 n := by simp [zero_add] | (pos p) 0 := show pos (p + 1) = succ (pos p + 0), by rw [pos_num.add_one, add_zero]; refl | (pos p) (pos q) := congr_arg pos (pos_num.add_succ _ _) @[simp] theorem add_of_nat (m) : ∀ n, ((m + n : ℕ) : num) = m + n | 0 := (add_zero _).symm | (n+1) := show ((m + n : ℕ) + 1 : num) = m + (↑ n + 1), by rw [add_one, add_one, add_succ, add_of_nat] theorem bit0_of_bit0 : ∀ n : num, bit0 n = n.bit0 | 0 := rfl | (pos p) := congr_arg pos p.bit0_of_bit0 theorem bit1_of_bit1 : ∀ n : num, bit1 n = n.bit1 | 0 := rfl | (pos p) := congr_arg pos p.bit1_of_bit1 @[simp] theorem cast_zero [has_zero α] [has_one α] [has_add α] : ((0 : num) : α) = 0 := rfl @[simp] theorem cast_zero' [has_zero α] [has_one α] [has_add α] : (num.zero : α) = 0 := rfl @[simp] theorem cast_one [has_zero α] [has_one α] [has_add α] : ((1 : num) : α) = 1 := rfl @[simp] theorem cast_pos [has_zero α] [has_one α] [has_add α] (n : pos_num) : (num.pos n : α) = n := rfl theorem succ'_to_nat : ∀ n, (succ' n : ℕ) = n + 1 | 0 := (_root_.zero_add _).symm | (pos p) := pos_num.succ_to_nat _ theorem succ_to_nat (n) : (succ n : ℕ) = n + 1 := succ'_to_nat n @[simp] theorem cast_to_nat [add_monoid α] [has_one α] : ∀ n : num, ((n : ℕ) : α) = n | 0 := nat.cast_zero | (pos p) := p.cast_to_nat @[simp] theorem to_nat_to_int (n : num) : ((n : ℕ) : ℤ) = n := by rw [← int.nat_cast_eq_coe_nat, cast_to_nat] @[simp] theorem cast_to_int [add_group α] [has_one α] (n : num) : ((n : ℤ) : α) = n := by rw [← to_nat_to_int, int.cast_coe_nat, cast_to_nat] @[simp] theorem to_of_nat : Π (n : ℕ), ((n : num) : ℕ) = n | 0 := rfl | (n+1) := by rw [nat.cast_add_one, add_one, succ_to_nat, to_of_nat] @[simp] theorem of_nat_cast [add_monoid α] [has_one α] (n : ℕ) : ((n : num) : α) = n := by rw [← cast_to_nat, to_of_nat] theorem of_nat_inj {m n : ℕ} : (m : num) = n ↔ m = n := ⟨λ h, function.injective_of_left_inverse to_of_nat h, congr_arg _⟩ @[simp] theorem add_to_nat : ∀ m n, ((m + n : num) : ℕ) = m + n | 0 0 := rfl | 0 (pos q) := (_root_.zero_add _).symm | (pos p) 0 := rfl | (pos p) (pos q) := pos_num.add_to_nat _ _ @[simp] theorem mul_to_nat : ∀ m n, ((m * n : num) : ℕ) = m * n | 0 0 := rfl | 0 (pos q) := (zero_mul _).symm | (pos p) 0 := rfl | (pos p) (pos q) := pos_num.mul_to_nat _ _ theorem cmp_to_nat : ∀ (m n), (ordering.cases_on (cmp m n) ((m:ℕ) < n) (m = n) ((m:ℕ) > n) : Prop) | 0 0 := rfl | 0 (pos b) := to_nat_pos _ | (pos a) 0 := to_nat_pos _ | (pos a) (pos b) := by { have := pos_num.cmp_to_nat a b; revert this; dsimp [cmp]; cases pos_num.cmp a b, exacts [id, congr_arg pos, id] } @[simp] theorem lt_to_nat {m n : num} : (m:ℕ) < n ↔ m < n := show (m:ℕ) < n ↔ cmp m n = ordering.lt, from match cmp m n, cmp_to_nat m n with | ordering.lt, h := by simp at h; simp [h] | ordering.eq, h := by simp at h; simp [h, lt_irrefl]; exact dec_trivial | ordering.gt, h := by simp [not_lt_of_gt h]; exact dec_trivial end @[simp] theorem le_to_nat {m n : num} : (m:ℕ) ≤ n ↔ m ≤ n := by rw ← not_lt; exact not_congr lt_to_nat end num namespace pos_num @[simp] theorem of_to_nat : Π (n : pos_num), ((n : ℕ) : num) = num.pos n | 1 := rfl | (bit0 p) := show ↑(p + p : ℕ) = num.pos p.bit0, by rw [num.add_of_nat, of_to_nat]; exact congr_arg num.pos p.bit0_of_bit0 | (bit1 p) := show ((p + p : ℕ) : num) + 1 = num.pos p.bit1, by rw [num.add_of_nat, of_to_nat]; exact congr_arg num.pos p.bit1_of_bit1 end pos_num namespace num @[simp] theorem of_to_nat : Π (n : num), ((n : ℕ) : num) = n | 0 := rfl | (pos p) := p.of_to_nat theorem to_nat_inj {m n : num} : (m : ℕ) = n ↔ m = n := ⟨λ h, function.injective_of_left_inverse of_to_nat h, congr_arg _⟩ meta def transfer_rw : tactic unit := `[repeat {rw ← to_nat_inj <|> rw ← lt_to_nat <|> rw ← le_to_nat}, repeat {rw add_to_nat <|> rw mul_to_nat <|> rw cast_one <|> rw cast_zero}] meta def transfer : tactic unit := `[intros, transfer_rw, try {simp}] instance : comm_semiring num := by refine { add := (+), zero := 0, zero_add := zero_add, add_zero := add_zero, mul := (*), one := 1, .. }; try {transfer}; simp [mul_add, mul_left_comm, mul_comm] instance : ordered_cancel_comm_monoid num := { add_left_cancel := by {intros a b c, transfer_rw, apply add_left_cancel}, add_right_cancel := by {intros a b c, transfer_rw, apply add_right_cancel}, lt := (<), lt_iff_le_not_le := by {intros a b, transfer_rw, apply lt_iff_le_not_le}, le := (≤), le_refl := by transfer, le_trans := by {intros a b c, transfer_rw, apply le_trans}, le_antisymm := by {intros a b, transfer_rw, apply le_antisymm}, add_le_add_left := by {intros a b h c, revert h, transfer_rw, exact λ h, add_le_add_left h c}, le_of_add_le_add_left := by {intros a b c, transfer_rw, apply le_of_add_le_add_left}, ..num.comm_semiring } instance : decidable_linear_ordered_semiring num := { le_total := by {intros a b, transfer_rw, apply le_total}, zero_lt_one := dec_trivial, mul_le_mul_of_nonneg_left := by {intros a b c, transfer_rw, apply mul_le_mul_of_nonneg_left}, mul_le_mul_of_nonneg_right := by {intros a b c, transfer_rw, apply mul_le_mul_of_nonneg_right}, mul_lt_mul_of_pos_left := by {intros a b c, transfer_rw, apply mul_lt_mul_of_pos_left}, mul_lt_mul_of_pos_right := by {intros a b c, transfer_rw, apply mul_lt_mul_of_pos_right}, decidable_lt := num.decidable_lt, decidable_le := num.decidable_le, decidable_eq := num.decidable_eq, ..num.comm_semiring, ..num.ordered_cancel_comm_monoid } @[simp] theorem dvd_to_nat (m n : num) : (m : ℕ) ∣ n ↔ m ∣ n := ⟨λ ⟨k, e⟩, ⟨k, by rw [← of_to_nat n, e]; simp⟩, λ ⟨k, e⟩, ⟨k, by simp [e]⟩⟩ end num namespace pos_num variables {α : Type*} open num theorem to_nat_inj {m n : pos_num} : (m : ℕ) = n ↔ m = n := ⟨λ h, num.pos.inj $ by rw [← pos_num.of_to_nat, ← pos_num.of_to_nat, h], congr_arg _⟩ theorem pred'_to_nat : ∀ n, (pred' n : ℕ) = nat.pred n | 1 := rfl | (bit0 n) := have nat.succ ↑(pred' n) = ↑n, by rw [pred'_to_nat n, nat.succ_pred_eq_of_pos (to_nat_pos n)], match pred' n, this : ∀ k : num, nat.succ ↑k = ↑n → ↑(num.cases_on k 1 bit1 : pos_num) = nat.pred (_root_.bit0 n) with | 0, (h : ((1:num):ℕ) = n) := by rw ← to_nat_inj.1 h; refl | num.pos p, (h : nat.succ ↑p = n) := by rw ← h; exact (nat.succ_add p p).symm end | (bit1 n) := rfl @[simp] theorem pred'_succ' (n) : pred' (succ' n) = n := num.to_nat_inj.1 $ by rw [pred'_to_nat, succ'_to_nat, nat.add_one, nat.pred_succ] @[simp] theorem succ'_pred' (n) : succ' (pred' n) = n := to_nat_inj.1 $ by rw [succ'_to_nat, pred'_to_nat, nat.add_one, nat.succ_pred_eq_of_pos (to_nat_pos _)] theorem size_to_nat : ∀ n, (size n : ℕ) = nat.size n | 1 := nat.size_one.symm | (bit0 n) := by rw [size, succ_to_nat, size_to_nat, cast_bit0, nat.size_bit0 $ ne_of_gt $ to_nat_pos n] | (bit1 n) := by rw [size, succ_to_nat, size_to_nat, cast_bit1, nat.size_bit1] theorem size_eq_nat_size : ∀ n, (size n : ℕ) = nat_size n | 1 := rfl | (bit0 n) := by rw [size, succ_to_nat, nat_size, size_eq_nat_size] | (bit1 n) := by rw [size, succ_to_nat, nat_size, size_eq_nat_size] theorem nat_size_to_nat (n) : nat_size n = nat.size n := by rw [← size_eq_nat_size, size_to_nat] theorem nat_size_pos (n) : 0 < nat_size n := by cases n; apply nat.succ_pos meta def transfer_rw : tactic unit := `[repeat {rw ← to_nat_inj <|> rw ← lt_to_nat <|> rw ← le_to_nat}, repeat {rw add_to_nat <|> rw mul_to_nat <|> rw cast_one <|> rw cast_zero}] meta def transfer : tactic unit := `[intros, transfer_rw, try {simp [mul_comm, mul_left_comm]}] instance : add_comm_semigroup pos_num := by refine {add := (+), ..}; transfer instance : comm_monoid pos_num := by refine {mul := (*), one := 1, ..}; transfer instance : distrib pos_num := by refine {add := (+), mul := (*), ..}; {transfer, simp [mul_add, mul_comm]} instance : decidable_linear_order pos_num := { lt := (<), lt_iff_le_not_le := by {intros a b, transfer_rw, apply lt_iff_le_not_le}, le := (≤), le_refl := by transfer, le_trans := by {intros a b c, transfer_rw, apply le_trans}, le_antisymm := by {intros a b, transfer_rw, apply le_antisymm}, le_total := by {intros a b, transfer_rw, apply le_total}, decidable_lt := by apply_instance, decidable_le := by apply_instance, decidable_eq := by apply_instance } @[simp] theorem cast_to_num (n : pos_num) : ↑n = num.pos n := by rw [← cast_to_nat, ← of_to_nat n] theorem bit_to_nat (b n) : (bit b n : ℕ) = nat.bit b n := by cases b; refl @[simp] theorem cast_add [add_monoid α] [has_one α] (m n) : ((m + n : pos_num) : α) = m + n := by rw [← cast_to_nat, add_to_nat, nat.cast_add, cast_to_nat, cast_to_nat] @[simp] theorem cast_succ [add_monoid α] [has_one α] (n : pos_num) : (succ n : α) = n + 1 := by rw [← add_one, cast_add, cast_one] @[simp] theorem cast_inj [add_monoid α] [has_one α] [char_zero α] {m n : pos_num} : (m:α) = n ↔ m = n := by rw [← cast_to_nat m, ← cast_to_nat n, nat.cast_inj, to_nat_inj] theorem one_le_cast [linear_ordered_semiring α] (n : pos_num) : (1 : α) ≤ n := by rw [← cast_to_nat, ← nat.cast_one, nat.cast_le]; apply to_nat_pos theorem cast_pos [linear_ordered_semiring α] (n : pos_num) : 0 < (n : α) := lt_of_lt_of_le zero_lt_one (one_le_cast n) @[simp] theorem cast_mul [semiring α] (m n) : ((m * n : pos_num) : α) = m * n := by rw [← cast_to_nat, mul_to_nat, nat.cast_mul, cast_to_nat, cast_to_nat] theorem cmp_eq (m n) : cmp m n = ordering.eq ↔ m = n := begin have := cmp_to_nat m n, cases cmp m n; simp at this ⊢; try {exact this}; { simp [show m ≠ n, from λ e, by rw e at this; exact lt_irrefl _ this] } end @[simp] theorem cast_lt [linear_ordered_semiring α] {m n : pos_num} : (m:α) < n ↔ m < n := by rw [← cast_to_nat m, ← cast_to_nat n, nat.cast_lt, lt_to_nat] @[simp] theorem cast_le [linear_ordered_semiring α] {m n : pos_num} : (m:α) ≤ n ↔ m ≤ n := by rw ← not_lt; exact not_congr cast_lt end pos_num namespace num variables {α : Type*} open pos_num theorem bit_to_nat (b n) : (bit b n : ℕ) = nat.bit b n := by cases b; cases n; refl theorem cast_succ' [add_monoid α] [has_one α] (n) : (succ' n : α) = n + 1 := by rw [← pos_num.cast_to_nat, succ'_to_nat, nat.cast_add_one, cast_to_nat] theorem cast_succ [add_monoid α] [has_one α] (n) : (succ n : α) = n + 1 := cast_succ' n @[simp] theorem cast_add [semiring α] (m n) : ((m + n : num) : α) = m + n := by rw [← cast_to_nat, add_to_nat, nat.cast_add, cast_to_nat, cast_to_nat] @[simp] theorem cast_bit0 [semiring α] (n : num) : (n.bit0 : α) = _root_.bit0 n := by rw [← bit0_of_bit0, _root_.bit0, cast_add]; refl @[simp] theorem cast_bit1 [semiring α] (n : num) : (n.bit1 : α) = _root_.bit1 n := by rw [← bit1_of_bit1, _root_.bit1, bit0_of_bit0, cast_add, cast_bit0]; refl @[simp] theorem cast_mul [semiring α] : ∀ m n, ((m * n : num) : α) = m * n | 0 0 := (zero_mul _).symm | 0 (pos q) := (zero_mul _).symm | (pos p) 0 := (mul_zero _).symm | (pos p) (pos q) := pos_num.cast_mul _ _ theorem size_to_nat : ∀ n, (size n : ℕ) = nat.size n | 0 := nat.size_zero.symm | (pos p) := p.size_to_nat theorem size_eq_nat_size : ∀ n, (size n : ℕ) = nat_size n | 0 := rfl | (pos p) := p.size_eq_nat_size theorem nat_size_to_nat (n) : nat_size n = nat.size n := by rw [← size_eq_nat_size, size_to_nat] @[simp] theorem of_nat'_eq : ∀ n, num.of_nat' n = n := nat.binary_rec rfl $ λ b n IH, begin rw of_nat' at IH ⊢, rw [nat.binary_rec_eq, IH], { cases b; simp [nat.bit, bit0_of_bit0, bit1_of_bit1] }, { refl } end theorem zneg_to_znum (n : num) : -n.to_znum = n.to_znum_neg := by cases n; refl theorem zneg_to_znum_neg (n : num) : -n.to_znum_neg = n.to_znum := by cases n; refl theorem to_znum_inj {m n : num} : m.to_znum = n.to_znum ↔ m = n := ⟨λ h, by cases m; cases n; cases h; refl, congr_arg _⟩ @[simp] theorem cast_to_znum [has_zero α] [has_one α] [has_add α] [has_neg α] : ∀ n : num, (n.to_znum : α) = n | 0 := rfl | (num.pos p) := rfl @[simp] theorem cast_to_znum_neg [add_group α] [has_one α] : ∀ n : num, (n.to_znum_neg : α) = -n | 0 := neg_zero.symm | (num.pos p) := rfl @[simp] theorem add_to_znum (m n : num) : num.to_znum (m + n) = m.to_znum + n.to_znum := by cases m; cases n; refl end num namespace pos_num open num theorem pred_to_nat {n : pos_num} (h : n > 1) : (pred n : ℕ) = nat.pred n := begin unfold pred, have := pred'_to_nat n, cases e : pred' n, { have : (1:ℕ) ≤ nat.pred n := nat.pred_le_pred ((@cast_lt ℕ _ _ _).2 h), rw [← pred'_to_nat, e] at this, exact absurd this dec_trivial }, { rw [← pred'_to_nat, e], refl } end theorem sub'_one (a : pos_num) : sub' a 1 = (pred' a).to_znum := by cases a; refl theorem one_sub' (a : pos_num) : sub' 1 a = (pred' a).to_znum_neg := by cases a; refl theorem lt_iff_cmp {m n} : m < n ↔ cmp m n = ordering.lt := iff.rfl theorem le_iff_cmp {m n} : m ≤ n ↔ cmp m n ≠ ordering.gt := not_congr $ lt_iff_cmp.trans $ by rw ← cmp_swap; cases cmp m n; exact dec_trivial end pos_num namespace num variables {α : Type*} open pos_num theorem pred_to_nat : ∀ (n : num), (pred n : ℕ) = nat.pred n | 0 := rfl | (pos p) := by rw [pred, pos_num.pred'_to_nat]; refl theorem ppred_to_nat : ∀ (n : num), coe <$> ppred n = nat.ppred n | 0 := rfl | (pos p) := by rw [ppred, option.map_some, nat.ppred_eq_some.2]; rw [pos_num.pred'_to_nat, nat.succ_pred_eq_of_pos (pos_num.to_nat_pos _)]; refl theorem cmp_swap (m n) : (cmp m n).swap = cmp n m := by cases m; cases n; try {unfold cmp}; try {refl}; apply pos_num.cmp_swap theorem cmp_eq (m n) : cmp m n = ordering.eq ↔ m = n := begin have := cmp_to_nat m n, cases cmp m n; simp at this ⊢; try {exact this}; { simp [show m ≠ n, from λ e, by rw e at this; exact lt_irrefl _ this] } end @[simp] theorem cast_lt [linear_ordered_semiring α] {m n : num} : (m:α) < n ↔ m < n := by rw [← cast_to_nat m, ← cast_to_nat n, nat.cast_lt, lt_to_nat] @[simp] theorem cast_le [linear_ordered_semiring α] {m n : num} : (m:α) ≤ n ↔ m ≤ n := by rw ← not_lt; exact not_congr cast_lt @[simp] theorem cast_inj [linear_ordered_semiring α] {m n : num} : (m:α) = n ↔ m = n := by rw [← cast_to_nat m, ← cast_to_nat n, nat.cast_inj, to_nat_inj] theorem lt_iff_cmp {m n} : m < n ↔ cmp m n = ordering.lt := iff.rfl theorem le_iff_cmp {m n} : m ≤ n ↔ cmp m n ≠ ordering.gt := not_congr $ lt_iff_cmp.trans $ by rw ← cmp_swap; cases cmp m n; exact dec_trivial theorem bitwise_to_nat {f : num → num → num} {g : bool → bool → bool} (p : pos_num → pos_num → num) (gff : g ff ff = ff) (f00 : f 0 0 = 0) (f0n : ∀ n, f 0 (pos n) = cond (g ff tt) (pos n) 0) (fn0 : ∀ n, f (pos n) 0 = cond (g tt ff) (pos n) 0) (fnn : ∀ m n, f (pos m) (pos n) = p m n) (p11 : p 1 1 = cond (g tt tt) 1 0) (p1b : ∀ b n, p 1 (pos_num.bit b n) = bit (g tt b) (cond (g ff tt) (pos n) 0)) (pb1 : ∀ a m, p (pos_num.bit a m) 1 = bit (g a tt) (cond (g tt ff) (pos m) 0)) (pbb : ∀ a b m n, p (pos_num.bit a m) (pos_num.bit b n) = bit (g a b) (p m n)) : ∀ m n : num, (f m n : ℕ) = nat.bitwise g m n := begin intros, cases m with m; cases n with n; try { change zero with 0 }; try { change ((0:num):ℕ) with 0 }, { rw [f00, nat.bitwise_zero]; refl }, { unfold nat.bitwise, rw [f0n, nat.binary_rec_zero], cases g ff tt; refl }, { unfold nat.bitwise, generalize h : (pos m : ℕ) = m', revert h, apply nat.bit_cases_on m' _, intros b m' h, rw [fn0, nat.binary_rec_eq, nat.binary_rec_zero, ←h], cases g tt ff; refl, apply nat.bitwise_bit_aux gff }, { rw fnn, have : ∀b (n : pos_num), (cond b ↑n 0 : ℕ) = ↑(cond b (pos n) 0 : num) := by intros; cases b; refl, induction m with m IH m IH generalizing n; cases n with n n, any_goals { change one with 1 }, any_goals { change pos 1 with 1 }, any_goals { change pos_num.bit0 with pos_num.bit ff }, any_goals { change pos_num.bit1 with pos_num.bit tt }, any_goals { change ((1:num):ℕ) with nat.bit tt 0 }, all_goals { repeat { rw show ∀ b n, (pos (pos_num.bit b n) : ℕ) = nat.bit b ↑n, by intros; cases b; refl }, rw nat.bitwise_bit }, any_goals { assumption }, any_goals { rw [nat.bitwise_zero, p11], cases g tt tt; refl }, any_goals { rw [nat.bitwise_zero_left, this, ← bit_to_nat, p1b] }, any_goals { rw [nat.bitwise_zero_right _ gff, this, ← bit_to_nat, pb1] }, all_goals { rw [← show ∀ n, ↑(p m n) = nat.bitwise g ↑m ↑n, from IH], rw [← bit_to_nat, pbb] } } end @[simp] theorem lor_to_nat : ∀ m n, (lor m n : ℕ) = nat.lor m n := by apply bitwise_to_nat (λx y, pos (pos_num.lor x y)); intros; try {cases a}; try {cases b}; refl @[simp] theorem land_to_nat : ∀ m n, (land m n : ℕ) = nat.land m n := by apply bitwise_to_nat pos_num.land; intros; try {cases a}; try {cases b}; refl @[simp] theorem ldiff_to_nat : ∀ m n, (ldiff m n : ℕ) = nat.ldiff m n := by apply bitwise_to_nat pos_num.ldiff; intros; try {cases a}; try {cases b}; refl @[simp] theorem lxor_to_nat : ∀ m n, (lxor m n : ℕ) = nat.lxor m n := by apply bitwise_to_nat pos_num.lxor; intros; try {cases a}; try {cases b}; refl @[simp] theorem shiftl_to_nat (m n) : (shiftl m n : ℕ) = nat.shiftl m n := begin cases m; dunfold shiftl, {symmetry, apply nat.zero_shiftl}, simp, induction n with n IH, {refl}, simp [pos_num.shiftl, nat.shiftl_succ], rw ←IH end @[simp] theorem shiftr_to_nat (m n) : (shiftr m n : ℕ) = nat.shiftr m n := begin cases m with m; dunfold shiftr, {symmetry, apply nat.zero_shiftr}, induction n with n IH generalizing m, {cases m; refl}, cases m with m m; dunfold pos_num.shiftr, { rw [nat.shiftr_eq_div_pow], symmetry, apply nat.div_eq_of_lt, exact @nat.pow_lt_pow_of_lt_right 2 dec_trivial 0 (n+1) (nat.succ_pos _) }, { transitivity, apply IH, change nat.shiftr m n = nat.shiftr (bit1 m) (n+1), rw [add_comm n 1, nat.shiftr_add], apply congr_arg (λx, nat.shiftr x n), unfold nat.shiftr, change (bit1 ↑m : ℕ) with nat.bit tt m, rw nat.div2_bit }, { transitivity, apply IH, change nat.shiftr m n = nat.shiftr (bit0 m) (n + 1), rw [add_comm n 1, nat.shiftr_add], apply congr_arg (λx, nat.shiftr x n), unfold nat.shiftr, change (bit0 ↑m : ℕ) with nat.bit ff m, rw nat.div2_bit } end @[simp] theorem test_bit_to_nat (m n) : test_bit m n = nat.test_bit m n := begin cases m with m; unfold test_bit nat.test_bit, { change (zero : nat) with 0, rw nat.zero_shiftr, refl }, induction n with n IH generalizing m; cases m; dunfold pos_num.test_bit, {refl}, { exact (nat.bodd_bit _ _).symm }, { exact (nat.bodd_bit _ _).symm }, { change ff = nat.bodd (nat.shiftr 1 (n + 1)), rw [add_comm, nat.shiftr_add], change nat.shiftr 1 1 with 0, rw nat.zero_shiftr; refl }, { change pos_num.test_bit m n = nat.bodd (nat.shiftr (nat.bit tt m) (n + 1)), rw [add_comm, nat.shiftr_add], unfold nat.shiftr, rw nat.div2_bit, apply IH }, { change pos_num.test_bit m n = nat.bodd (nat.shiftr (nat.bit ff m) (n + 1)), rw [add_comm, nat.shiftr_add], unfold nat.shiftr, rw nat.div2_bit, apply IH }, end end num namespace znum variables {α : Type*} open pos_num @[simp] theorem cast_zero [has_zero α] [has_one α] [has_add α] [has_neg α] : ((0 : znum) : α) = 0 := rfl @[simp] theorem cast_zero' [has_zero α] [has_one α] [has_add α] [has_neg α] : (znum.zero : α) = 0 := rfl @[simp] theorem cast_one [has_zero α] [has_one α] [has_add α] [has_neg α] : ((1 : znum) : α) = 1 := rfl @[simp] theorem cast_pos [has_zero α] [has_one α] [has_add α] [has_neg α] (n : pos_num) : (pos n : α) = n := rfl @[simp] theorem cast_neg [has_zero α] [has_one α] [has_add α] [has_neg α] (n : pos_num) : (neg n : α) = -n := rfl @[simp] theorem cast_zneg [add_group α] [has_one α] : ∀ n, ((-n : znum) : α) = -n | 0 := neg_zero.symm | (pos p) := rfl | (neg p) := (neg_neg _).symm theorem neg_zero : (-0 : znum) = 0 := rfl theorem zneg_pos (n : pos_num) : -pos n = neg n := rfl theorem zneg_neg (n : pos_num) : -neg n = pos n := rfl theorem zneg_zneg (n : znum) : - -n = n := by cases n; refl theorem zneg_bit1 (n : znum) : -n.bit1 = (-n).bitm1 := by cases n; refl theorem zneg_bitm1 (n : znum) : -n.bitm1 = (-n).bit1 := by cases n; refl theorem zneg_succ (n : znum) : -n.succ = (-n).pred := by cases n; try {refl}; rw [succ, num.zneg_to_znum_neg]; refl theorem zneg_pred (n : znum) : -n.pred = (-n).succ := by rw [← zneg_zneg (succ (-n)), zneg_succ, zneg_zneg] @[simp] theorem neg_of_int : ∀ n, ((-n : ℤ) : znum) = -n | (n+1:ℕ) := rfl | 0 := rfl | -[1+n] := (zneg_zneg _).symm @[simp] theorem abs_to_nat : ∀ n, (abs n : ℕ) = int.nat_abs n | 0 := rfl | (pos p) := congr_arg int.nat_abs p.to_nat_to_int | (neg p) := show int.nat_abs ((p:ℕ):ℤ) = int.nat_abs (- p), by rw [p.to_nat_to_int, int.nat_abs_neg] @[simp] theorem abs_to_znum : ∀ n : num, abs n.to_znum = n | 0 := rfl | (num.pos p) := rfl @[simp] theorem cast_to_int [add_group α] [has_one α] : ∀ n : znum, ((n : ℤ) : α) = n | 0 := rfl | (pos p) := by rw [cast_pos, cast_pos, pos_num.cast_to_int] | (neg p) := by rw [cast_neg, cast_neg, int.cast_neg, pos_num.cast_to_int] theorem bit0_of_bit0 : ∀ n : znum, _root_.bit0 n = n.bit0 | 0 := rfl | (pos a) := congr_arg pos a.bit0_of_bit0 | (neg a) := congr_arg neg a.bit0_of_bit0 theorem bit1_of_bit1 : ∀ n : znum, _root_.bit1 n = n.bit1 | 0 := rfl | (pos a) := congr_arg pos a.bit1_of_bit1 | (neg a) := show pos_num.sub' 1 (_root_.bit0 a) = _, by rw [pos_num.one_sub', a.bit0_of_bit0]; refl @[simp] theorem cast_bit0 [add_group α] [has_one α] : ∀ n : znum, (n.bit0 : α) = bit0 n | 0 := (add_zero _).symm | (pos p) := by rw [znum.bit0, cast_pos, cast_pos]; refl | (neg p) := by rw [znum.bit0, cast_neg, cast_neg, pos_num.cast_bit0, _root_.bit0, _root_.bit0, neg_add_rev] @[simp] theorem cast_bit1 [add_group α] [has_one α] : ∀ n : znum, (n.bit1 : α) = bit1 n | 0 := by simp [znum.bit1, _root_.bit1, _root_.bit0] | (pos p) := by rw [znum.bit1, cast_pos, cast_pos]; refl | (neg p) := begin rw [znum.bit1, cast_neg, cast_neg], cases e : pred' p; have : p = _ := (succ'_pred' p).symm.trans (congr_arg num.succ' e), { change p=1 at this, subst p, simp [_root_.bit1, _root_.bit0] }, { rw [num.succ'] at this, subst p, have : (↑(-↑a:ℤ) : α) = -1 + ↑(-↑a + 1 : ℤ), {simp}, simpa [_root_.bit1, _root_.bit0, -add_comm] }, end @[simp] theorem cast_bitm1 [add_group α] [has_one α] (n : znum) : (n.bitm1 : α) = bit0 n - 1 := begin conv { to_lhs, rw ← zneg_zneg n }, rw [← zneg_bit1, cast_zneg, cast_bit1], have : ((-1 + n + n : ℤ) : α) = (n + n + -1 : ℤ), {simp}, simpa [_root_.bit1, _root_.bit0, -add_comm] end theorem add_zero (n : znum) : n + 0 = n := by cases n; refl theorem zero_add (n : znum) : 0 + n = n := by cases n; refl theorem add_one : ∀ n : znum, n + 1 = succ n | 0 := rfl | (pos p) := congr_arg pos p.add_one | (neg p) := by cases p; refl end znum namespace pos_num variables {α : Type*} theorem cast_to_znum : ∀ n : pos_num, (n : znum) = znum.pos n | 1 := rfl | (bit0 p) := (znum.bit0_of_bit0 p).trans $ congr_arg _ (cast_to_znum p) | (bit1 p) := (znum.bit1_of_bit1 p).trans $ congr_arg _ (cast_to_znum p) theorem cast_sub' [add_group α] [has_one α] : ∀ m n : pos_num, (sub' m n : α) = m - n | a 1 := by rw [sub'_one, num.cast_to_znum, ← num.cast_to_nat, pred'_to_nat, ← nat.sub_one]; simp [pos_num.cast_pos] | 1 b := by rw [one_sub', num.cast_to_znum_neg, ← neg_sub, neg_inj', ← num.cast_to_nat, pred'_to_nat, ← nat.sub_one]; simp [pos_num.cast_pos] | (bit0 a) (bit0 b) := begin rw [sub', znum.cast_bit0, cast_sub'], have : ((a + -b + (a + -b) : ℤ) : α) = a + a + (-b + -b), {simp}, simpa [_root_.bit0, -add_left_comm] end | (bit0 a) (bit1 b) := begin rw [sub', znum.cast_bitm1, cast_sub'], have : ((-b + (a + (-b + -1)) : ℤ) : α) = (a + -1 + (-b + -b):ℤ), {simp}, simpa [_root_.bit1, _root_.bit0, -add_left_comm, -add_comm] end | (bit1 a) (bit0 b) := begin rw [sub', znum.cast_bit1, cast_sub'], have : ((-b + (a + (-b + 1)) : ℤ) : α) = (a + 1 + (-b + -b):ℤ), {simp}, simpa [_root_.bit1, _root_.bit0, -add_left_comm, -add_comm] end | (bit1 a) (bit1 b) := begin rw [sub', znum.cast_bit0, cast_sub'], have : ((-b + (a + -b) : ℤ) : α) = a + (-b + -b), {simp}, simpa [_root_.bit1, _root_.bit0, -add_left_comm, add_neg_cancel_left] end theorem to_nat_eq_succ_pred (n : pos_num) : (n:ℕ) = n.pred' + 1 := by rw [← num.succ'_to_nat, n.succ'_pred'] theorem to_int_eq_succ_pred (n : pos_num) : (n:ℤ) = (n.pred' : ℕ) + 1 := by rw [← n.to_nat_to_int, to_nat_eq_succ_pred]; refl end pos_num namespace num variables {α : Type*} @[simp] theorem cast_sub' [add_group α] [has_one α] : ∀ m n : num, (sub' m n : α) = m - n | 0 0 := (sub_zero _).symm | (pos a) 0 := (sub_zero _).symm | 0 (pos b) := (zero_sub _).symm | (pos a) (pos b) := pos_num.cast_sub' _ _ @[simp] theorem of_nat_to_znum : ∀ n : ℕ, to_znum n = n | 0 := rfl | (n+1) := by rw [nat.cast_add_one, nat.cast_add_one, znum.add_one, add_one, ← of_nat_to_znum]; cases (n:num); refl @[simp] theorem of_nat_to_znum_neg (n : ℕ) : to_znum_neg n = -n := by rw [← of_nat_to_znum, zneg_to_znum] theorem mem_of_znum' : ∀ {m : num} {n : znum}, m ∈ of_znum' n ↔ n = to_znum m | 0 0 := ⟨λ _, rfl, λ _, rfl⟩ | (pos m) 0 := ⟨λ h, by cases h, λ h, by cases h⟩ | m (znum.pos p) := option.some_inj.trans $ by cases m; split; intro h; try {cases h}; refl | m (znum.neg p) := ⟨λ h, by cases h, λ h, by cases m; cases h⟩ theorem of_znum'_to_nat : ∀ (n : znum), coe <$> of_znum' n = int.to_nat' n | 0 := rfl | (znum.pos p) := show _ = int.to_nat' p, by rw [← pos_num.to_nat_to_int p]; refl | (znum.neg p) := congr_arg (λ x, int.to_nat' (-x)) $ show ((p.pred' + 1 : ℕ) : ℤ) = p, by rw ← succ'_to_nat; simp @[simp] theorem of_znum_to_nat : ∀ (n : znum), (of_znum n : ℕ) = int.to_nat n | 0 := rfl | (znum.pos p) := show _ = int.to_nat p, by rw [← pos_num.to_nat_to_int p]; refl | (znum.neg p) := congr_arg (λ x, int.to_nat (-x)) $ show ((p.pred' + 1 : ℕ) : ℤ) = p, by rw ← succ'_to_nat; simp @[simp] theorem cast_of_znum [add_group α] [has_one α] (n : znum) : (of_znum n : α) = int.to_nat n := by rw [← cast_to_nat, of_znum_to_nat] @[simp] theorem sub_to_nat (m n) : ((m - n : num) : ℕ) = m - n := show (of_znum _ : ℕ) = _, by rw [of_znum_to_nat, cast_sub', ← to_nat_to_int, ← to_nat_to_int, int.to_nat_sub] end num namespace znum variables {α : Type*} @[simp] theorem cast_add [add_group α] [has_one α] : ∀ m n, ((m + n : znum) : α) = m + n | 0 a := by cases a; exact (_root_.zero_add _).symm | b 0 := by cases b; exact (_root_.add_zero _).symm | (pos a) (pos b) := pos_num.cast_add _ _ | (pos a) (neg b) := pos_num.cast_sub' _ _ | (neg a) (pos b) := (pos_num.cast_sub' _ _).trans $ show ↑b + -↑a = -↑a + ↑b, by rw [← pos_num.cast_to_int a, ← pos_num.cast_to_int b, ← int.cast_neg, ← int.cast_add (-a)]; simp | (neg a) (neg b) := show -(↑(a + b) : α) = -a + -b, by rw [ pos_num.cast_add, neg_eq_iff_neg_eq, neg_add_rev, neg_neg, neg_neg, ← pos_num.cast_to_int a, ← pos_num.cast_to_int b, ← int.cast_add]; simp @[simp] theorem cast_succ [add_group α] [has_one α] (n) : ((succ n : znum) : α) = n + 1 := by rw [← add_one, cast_add, cast_one] @[simp] theorem mul_to_int : ∀ m n, ((m * n : znum) : ℤ) = m * n | 0 a := by cases a; exact (_root_.zero_mul _).symm | b 0 := by cases b; exact (_root_.mul_zero _).symm | (pos a) (pos b) := pos_num.cast_mul a b | (pos a) (neg b) := show -↑(a * b) = ↑a * -↑b, by rw [pos_num.cast_mul, neg_mul_eq_mul_neg] | (neg a) (pos b) := show -↑(a * b) = -↑a * ↑b, by rw [pos_num.cast_mul, neg_mul_eq_neg_mul] | (neg a) (neg b) := show ↑(a * b) = -↑a * -↑b, by rw [pos_num.cast_mul, neg_mul_neg] theorem cast_mul [ring α] (m n) : ((m * n : znum) : α) = m * n := by rw [← cast_to_int, mul_to_int, int.cast_mul, cast_to_int, cast_to_int] @[simp] theorem of_to_int : Π (n : znum), ((n : ℤ) : znum) = n | 0 := rfl | (pos a) := by rw [cast_pos, ← pos_num.cast_to_nat, int.cast_coe_nat', ← num.of_nat_to_znum, pos_num.of_to_nat]; refl | (neg a) := by rw [cast_neg, neg_of_int, ← pos_num.cast_to_nat, int.cast_coe_nat', ← num.of_nat_to_znum_neg, pos_num.of_to_nat]; refl @[simp] theorem to_of_int : Π (n : ℤ), ((n : znum) : ℤ) = n | (n : ℕ) := by rw [int.cast_coe_nat, ← num.of_nat_to_znum, num.cast_to_znum, ← num.cast_to_nat, int.nat_cast_eq_coe_nat, num.to_of_nat] | -[1+ n] := by rw [int.cast_neg_succ_of_nat, cast_zneg, add_one, cast_succ, int.neg_succ_of_nat_eq, ← num.of_nat_to_znum, num.cast_to_znum, ← num.cast_to_nat, int.nat_cast_eq_coe_nat, num.to_of_nat] theorem to_int_inj {m n : znum} : (m : ℤ) = n ↔ m = n := ⟨λ h, function.injective_of_left_inverse of_to_int h, congr_arg _⟩ @[simp] theorem of_int_cast [add_group α] [has_one α] (n : ℤ) : ((n : znum) : α) = n := by rw [← cast_to_int, to_of_int] @[simp] theorem of_nat_cast [add_group α] [has_one α] (n : ℕ) : ((n : znum) : α) = n := of_int_cast n @[simp] theorem of_int'_eq : ∀ n, znum.of_int' n = n | (n : ℕ) := to_int_inj.1 $ by simp [znum.of_int'] | -[1+ n] := to_int_inj.1 $ by simp [znum.of_int'] theorem cmp_to_int : ∀ (m n), (ordering.cases_on (cmp m n) ((m:ℤ) < n) (m = n) ((m:ℤ) > n) : Prop) | 0 0 := rfl | (pos a) (pos b) := begin have := pos_num.cmp_to_nat a b; revert this; dsimp [cmp]; cases pos_num.cmp a b; dsimp; [simp, exact congr_arg pos, simp [gt]] end | (neg a) (neg b) := begin have := pos_num.cmp_to_nat b a; revert this; dsimp [cmp]; cases pos_num.cmp b a; dsimp; [simp, simp {contextual := tt}, simp [gt]] end | (pos a) 0 := pos_num.cast_pos _ | (pos a) (neg b) := lt_trans (neg_lt_zero.2 $ pos_num.cast_pos _) (pos_num.cast_pos _) | 0 (neg b) := neg_lt_zero.2 $ pos_num.cast_pos _ | (neg a) 0 := neg_lt_zero.2 $ pos_num.cast_pos _ | (neg a) (pos b) := lt_trans (neg_lt_zero.2 $ pos_num.cast_pos _) (pos_num.cast_pos _) | 0 (pos b) := pos_num.cast_pos _ @[simp] theorem lt_to_int {m n : znum} : (m:ℤ) < n ↔ m < n := show (m:ℤ) < n ↔ cmp m n = ordering.lt, from match cmp m n, cmp_to_int m n with | ordering.lt, h := by simp at h; simp [h] | ordering.eq, h := by simp at h; simp [h, lt_irrefl]; exact dec_trivial | ordering.gt, h := by simp [not_lt_of_gt h]; exact dec_trivial end @[simp] theorem le_to_int {m n : znum} : (m:ℤ) ≤ n ↔ m ≤ n := by rw ← not_lt; exact not_congr lt_to_int @[simp] theorem cast_lt [linear_ordered_ring α] {m n : znum} : (m:α) < n ↔ m < n := by rw [← cast_to_int m, ← cast_to_int n, int.cast_lt, lt_to_int] @[simp] theorem cast_le [linear_ordered_ring α] {m n : znum} : (m:α) ≤ n ↔ m ≤ n := by rw ← not_lt; exact not_congr cast_lt @[simp] theorem cast_inj [linear_ordered_ring α] {m n : znum} : (m:α) = n ↔ m = n := by rw [← cast_to_int m, ← cast_to_int n, int.cast_inj, to_int_inj] meta def transfer_rw : tactic unit := `[repeat {rw ← to_int_inj <|> rw ← lt_to_int <|> rw ← le_to_int}, repeat {rw cast_add <|> rw mul_to_int <|> rw cast_one <|> rw cast_zero}] meta def transfer : tactic unit := `[intros, transfer_rw, try {simp [mul_comm, mul_left_comm]}] instance : decidable_linear_order znum := { lt := (<), lt_iff_le_not_le := by {intros a b, transfer_rw, apply lt_iff_le_not_le}, le := (≤), le_refl := by transfer, le_trans := by {intros a b c, transfer_rw, apply le_trans}, le_antisymm := by {intros a b, transfer_rw, apply le_antisymm}, le_total := by {intros a b, transfer_rw, apply le_total}, decidable_eq := znum.decidable_eq, decidable_le := znum.decidable_le, decidable_lt := znum.decidable_lt } instance : add_comm_group znum := { add := (+), add_assoc := by transfer, zero := 0, zero_add := zero_add, add_zero := add_zero, add_comm := by transfer, neg := has_neg.neg, add_left_neg := by transfer } instance : decidable_linear_ordered_comm_ring znum := { mul := (*), mul_assoc := by transfer, one := 1, one_mul := by transfer, mul_one := by transfer, left_distrib := by {transfer, simp [mul_add]}, right_distrib := by {transfer, simp [mul_add, mul_comm]}, mul_comm := by transfer, zero_ne_one := dec_trivial, add_le_add_left := by {intros a b h c, revert h, transfer_rw, exact λ h, add_le_add_left h c}, add_lt_add_left := by {intros a b h c, revert h, transfer_rw, exact λ h, add_lt_add_left h c}, mul_pos := by {intros a b, transfer_rw, apply mul_pos}, mul_nonneg := by {intros x y, change 0 ≤ x → 0 ≤ y → 0 ≤ x * y, transfer_rw, apply mul_nonneg}, zero_lt_one := dec_trivial, ..znum.decidable_linear_order, ..znum.add_comm_group } @[simp] theorem dvd_to_int (m n : znum) : (m : ℤ) ∣ n ↔ m ∣ n := ⟨λ ⟨k, e⟩, ⟨k, by rw [← of_to_int n, e]; simp⟩, λ ⟨k, e⟩, ⟨k, by simp [e]⟩⟩ end znum namespace pos_num theorem divmod_to_nat_aux {n d : pos_num} {q r : num} (h₁ : (r:ℕ) + d * _root_.bit0 q = n) (h₂ : (r:ℕ) < 2 * d) : ((divmod_aux d q r).2 + d * (divmod_aux d q r).1 : ℕ) = ↑n ∧ ((divmod_aux d q r).2 : ℕ) < d := begin unfold divmod_aux, have : ∀ {r₂}, num.of_znum' (num.sub' r (num.pos d)) = some r₂ ↔ (r : ℕ) = r₂ + d, { intro r₂, apply num.mem_of_znum'.trans, rw [← znum.to_int_inj, num.cast_to_znum, num.cast_sub', sub_eq_iff_eq_add, ← int.coe_nat_inj'], simp }, cases e : num.of_znum' (num.sub' r (num.pos d)) with r₂; simp [divmod_aux], { refine ⟨h₁, lt_of_not_ge (λ h, _)⟩, cases nat.le.dest h with r₂ e', rw [← num.to_of_nat r₂, add_comm] at e', cases e.symm.trans (this.2 e'.symm) }, { have := this.1 e, split, { rwa [_root_.bit1, add_comm _ 1, mul_add, mul_one, ← add_assoc, ← this] }, { rwa [this, two_mul, add_lt_add_iff_right] at h₂ } } end theorem divmod_to_nat (d n : pos_num) : (n / d : ℕ) = (divmod d n).1 ∧ (n % d : ℕ) = (divmod d n).2 := begin rw nat.div_mod_unique (pos_num.cast_pos _), induction n with n IH n IH, { exact divmod_to_nat_aux (by simp; refl) (nat.mul_le_mul_left 2 (pos_num.cast_pos d : (0 : ℕ) < d)) }, { unfold divmod, cases divmod d n with q r, simp only [divmod] at IH ⊢, apply divmod_to_nat_aux; simp, { rw [_root_.bit1, _root_.bit1, add_right_comm, bit0_eq_two_mul ↑n, ← IH.1, mul_add, ← bit0_eq_two_mul, mul_left_comm, ← bit0_eq_two_mul] }, { rw ← bit0_eq_two_mul, exact nat.bit1_lt_bit0 IH.2 } }, { unfold divmod, cases divmod d n with q r, simp only [divmod] at IH ⊢, apply divmod_to_nat_aux; simp, { rw [bit0_eq_two_mul ↑n, ← IH.1, mul_add, ← bit0_eq_two_mul, mul_left_comm, ← bit0_eq_two_mul] }, { rw ← bit0_eq_two_mul, exact nat.bit0_lt IH.2 } } end @[simp] theorem div'_to_nat (n d) : (div' n d : ℕ) = n / d := (divmod_to_nat _ _).1.symm @[simp] theorem mod'_to_nat (n d) : (mod' n d : ℕ) = n % d := (divmod_to_nat _ _).2.symm end pos_num namespace num @[simp] theorem div_to_nat : ∀ n d, ((n / d : num) : ℕ) = n / d | 0 0 := rfl | 0 (pos d) := (nat.zero_div _).symm | (pos n) 0 := (nat.div_zero _).symm | (pos n) (pos d) := pos_num.div'_to_nat _ _ @[simp] theorem mod_to_nat : ∀ n d, ((n % d : num) : ℕ) = n % d | 0 0 := rfl | 0 (pos d) := (nat.zero_mod _).symm | (pos n) 0 := (nat.mod_zero _).symm | (pos n) (pos d) := pos_num.mod'_to_nat _ _ theorem gcd_to_nat_aux : ∀ {n} {a b : num}, a ≤ b → (a * b).nat_size ≤ n → (gcd_aux n a b : ℕ) = nat.gcd a b | 0 0 b ab h := (nat.gcd_zero_left _).symm | 0 (pos a) 0 ab h := (not_lt_of_ge ab).elim rfl | 0 (pos a) (pos b) ab h := (not_lt_of_le h).elim $ pos_num.nat_size_pos _ | (nat.succ n) 0 b ab h := (nat.gcd_zero_left _).symm | (nat.succ n) (pos a) b ab h := begin simp [gcd_aux], rw [nat.gcd_rec, gcd_to_nat_aux, mod_to_nat], {refl}, { rw [← le_to_nat, mod_to_nat], exact le_of_lt (nat.mod_lt _ (pos_num.cast_pos _)) }, rw [nat_size_to_nat, mul_to_nat, nat.size_le] at h ⊢, rw [mod_to_nat, mul_comm], rw [nat.pow_succ, ← nat.mod_add_div b (pos a)] at h, refine lt_of_mul_lt_mul_right (lt_of_le_of_lt _ h) (nat.zero_le 2), rw [mul_two, mul_add], refine add_le_add_left (nat.mul_le_mul_left _ (le_trans (le_of_lt (nat.mod_lt _ (pos_num.cast_pos _))) _)) _, suffices : 1 ≤ _, simpa using nat.mul_le_mul_left (pos a) this, rw [nat.le_div_iff_mul_le _ _ a.cast_pos, one_mul], exact le_to_nat.2 ab end @[simp] theorem gcd_to_nat : ∀ a b, (gcd a b : ℕ) = nat.gcd a b := have ∀ a b : num, (a * b).nat_size ≤ a.nat_size + b.nat_size, begin intros, simp [nat_size_to_nat], rw [nat.size_le, nat.pow_add], exact mul_lt_mul'' (nat.lt_size_self _) (nat.lt_size_self _) (nat.zero_le _) (nat.zero_le _) end, begin intros, unfold gcd, split_ifs, { exact gcd_to_nat_aux h (this _ _) }, { rw nat.gcd_comm, exact gcd_to_nat_aux (le_of_not_le h) (this _ _) } end theorem dvd_iff_mod_eq_zero {m n : num} : m ∣ n ↔ n % m = 0 := by rw [← dvd_to_nat, nat.dvd_iff_mod_eq_zero, ← to_nat_inj, mod_to_nat]; refl instance : decidable_rel ((∣) : num → num → Prop) | a b := decidable_of_iff' _ dvd_iff_mod_eq_zero end num namespace znum @[simp] theorem div_to_int : ∀ n d, ((n / d : znum) : ℤ) = n / d | 0 0 := rfl | 0 (pos d) := (int.zero_div _).symm | 0 (neg d) := (int.zero_div _).symm | (pos n) 0 := (int.div_zero _).symm | (neg n) 0 := (int.div_zero _).symm | (pos n) (pos d) := (num.cast_to_znum _).trans $ by rw ← num.to_nat_to_int; simp | (pos n) (neg d) := (num.cast_to_znum_neg _).trans $ by rw ← num.to_nat_to_int; simp | (neg n) (pos d) := show - _ = (-_/↑d), begin rw [n.to_int_eq_succ_pred, d.to_int_eq_succ_pred, ← pos_num.to_nat_to_int, num.succ'_to_nat, num.div_to_nat], change -[1+ n.pred' / ↑d] = -[1+ n.pred' / (d.pred' + 1)], rw d.to_nat_eq_succ_pred end | (neg n) (neg d) := show ↑(pos_num.pred' n / num.pos d).succ' = (-_ / -↑d), begin rw [n.to_int_eq_succ_pred, d.to_int_eq_succ_pred, ← pos_num.to_nat_to_int, num.succ'_to_nat, num.div_to_nat], change (nat.succ (_/d) : ℤ) = nat.succ (n.pred'/(d.pred' + 1)), rw d.to_nat_eq_succ_pred end @[simp] theorem mod_to_int : ∀ n d, ((n % d : znum) : ℤ) = n % d | 0 d := (int.zero_mod _).symm | (pos n) d := (num.cast_to_znum _).trans $ by rw [← num.to_nat_to_int, cast_pos, num.mod_to_nat, ← pos_num.to_nat_to_int, abs_to_nat]; refl | (neg n) d := (num.cast_sub' _ _).trans $ by rw [← num.to_nat_to_int, cast_neg, ← num.to_nat_to_int, num.succ_to_nat, num.mod_to_nat, abs_to_nat, ← int.sub_nat_nat_eq_coe, n.to_int_eq_succ_pred]; refl @[simp] theorem gcd_to_nat (a b) : (gcd a b : ℕ) = int.gcd a b := (num.gcd_to_nat _ _).trans $ by simpa theorem dvd_iff_mod_eq_zero {m n : znum} : m ∣ n ↔ n % m = 0 := by rw [← dvd_to_int, int.dvd_iff_mod_eq_zero, ← to_int_inj, mod_to_int]; refl instance : decidable_rel ((∣) : znum → znum → Prop) | a b := decidable_of_iff' _ dvd_iff_mod_eq_zero end znum
a7f83c2411cef381685f494f6a4b2934423cde2d
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/analysis/normed/group/completion.lean
c971bd88840900f6bdd8603ff70d66152532d0f1
[ "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
1,343
lean
/- Copyright (c) 2021 Heather Macbeth. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Heather Macbeth -/ import analysis.normed.group.basic import topology.algebra.group_completion import topology.metric_space.completion /-! # Completion of a normed group In this file we prove that the completion of a (semi)normed group is a normed group. ## Tags normed group, completion -/ noncomputable theory namespace uniform_space namespace completion variables (E : Type*) instance [uniform_space E] [has_norm E] : has_norm (completion E) := { norm := completion.extension has_norm.norm } @[simp] lemma norm_coe {E} [semi_normed_group E] (x : E) : ∥(x : completion E)∥ = ∥x∥ := completion.extension_coe uniform_continuous_norm x instance [semi_normed_group E] : normed_group (completion E) := { dist_eq := begin intros x y, apply completion.induction_on₂ x y; clear x y, { refine is_closed_eq (completion.uniform_continuous_extension₂ _).continuous _, exact continuous.comp completion.continuous_extension continuous_sub }, { intros x y, rw [← completion.coe_sub, norm_coe, metric.completion.dist_eq, dist_eq_norm] } end, .. uniform_space.completion.add_comm_group, .. metric.completion.metric_space } end completion end uniform_space
1cfa1d0d30658cf2707818d1e8147f05edbef45f
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/data/fintype/basic.lean
798902321c21bfa3ad1949d30f74f9140a246f34
[ "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
88,663
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.array.lemmas import data.finset.fin import data.finset.option import data.finset.pi import data.finset.powerset import data.finset.prod import data.finset.sigma import data.list.nodup_equiv_fin import data.sym.basic import data.ulift import group_theory.perm.basic import order.well_founded import tactic.wlog /-! # Finite types This file defines a typeclass to state that a type is finite. ## Main declarations * `fintype α`: Typeclass saying that a type is finite. It takes as fields a `finset` and a proof that all terms of type `α` are in it. * `finset.univ`: The finset of all elements of a fintype. * `fintype.card α`: Cardinality of a fintype. Equal to `finset.univ.card`. * `perms_of_finset s`: The finset of permutations of the finset `s`. * `fintype.trunc_equiv_fin`: A fintype `α` is computably equivalent to `fin (card α)`. The `trunc`-free, noncomputable version is `fintype.equiv_fin`. * `fintype.trunc_equiv_of_card_eq` `fintype.equiv_of_card_eq`: Two fintypes of same cardinality are equivalent. See above. * `fin.equiv_iff_eq`: `fin m ≃ fin n` iff `m = n`. * `infinite α`: Typeclass saying that a type is infinite. Defined as `fintype α → false`. * `not_fintype`: No `fintype` has an `infinite` instance. * `infinite.nat_embedding`: An embedding of `ℕ` into an infinite type. We also provide the following versions of the pigeonholes principle. * `fintype.exists_ne_map_eq_of_card_lt` and `is_empty_of_card_lt`: Finitely many pigeons and pigeonholes. Weak formulation. * `fintype.exists_ne_map_eq_of_infinite`: Infinitely many pigeons in finitely many pigeonholes. Weak formulation. * `fintype.exists_infinite_fiber`: Infinitely many pigeons in finitely many pigeonholes. Strong formulation. Some more pigeonhole-like statements can be found in `data.fintype.card_embedding`. ## Instances Among others, we provide `fintype` instances for * A `subtype` of a fintype. See `fintype.subtype`. * The `option` of a fintype. * The product of two fintypes. * The sum of two fintypes. * `Prop`. and `infinite` instances for * specific types: `ℕ`, `ℤ` * type constructors: `set α`, `finset α`, `multiset α`, `list α`, `α ⊕ β`, `α × β` along with some machinery * Types which have a surjection from/an injection to a `fintype` are themselves fintypes. See `fintype.of_injective` and `fintype.of_surjective`. * Types which have an injection from/a surjection to an `infinite` type are themselves `infinite`. See `infinite.of_injective` and `infinite.of_surjective`. -/ open_locale nat universes u v variables {α β γ : 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 lemma eq_univ_iff_forall {s : finset α} : s = univ ↔ ∀ x, x ∈ s := by simp [ext_iff] @[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_iff : (univ : finset α) = ∅ ↔ is_empty α := by rw [← not_nonempty_iff, ← univ_nonempty_iff, not_nonempty_iff_eq_empty] @[simp] lemma univ_eq_empty [is_empty α] : (univ : finset α) = ∅ := univ_eq_empty_iff.2 ‹_› @[simp] lemma univ_unique [unique α] : (univ : finset α) = {default} := finset.ext $ λ x, iff_of_true (mem_univ _) $ mem_singleton.2 $ subsingleton.elim x default @[simp] theorem subset_univ (s : finset α) : s ⊆ univ := λ a _, mem_univ a instance : order_top (finset α) := { top := univ, le_top := subset_univ } section boolean_algebra variables [decidable_eq α] {s : finset α} {a : α} instance : boolean_algebra (finset α) := { compl := λ s, univ \ s, inf_compl_le_bot := λ s x hx, by simpa using hx, top_le_sup_compl := λ s x hx, by simp, sdiff_eq := λ s t, by simp [ext_iff, compl], ..finset.order_top, ..finset.order_bot, ..finset.generalized_boolean_algebra } lemma compl_eq_univ_sdiff (s : finset α) : sᶜ = univ \ s := rfl @[simp] lemma mem_compl : a ∈ sᶜ ↔ a ∉ s := by simp [compl_eq_univ_sdiff] lemma not_mem_compl : a ∉ sᶜ ↔ a ∈ s := by rw [mem_compl, not_not] @[simp, norm_cast] lemma coe_compl (s : finset α) : ↑(sᶜ) = (↑s : set α)ᶜ := set.ext $ λ x, mem_compl @[simp] lemma compl_empty : (∅ : finset α)ᶜ = univ := compl_bot @[simp] lemma union_compl (s : finset α) : s ∪ sᶜ = univ := sup_compl_eq_top @[simp] lemma inter_compl (s : finset α) : s ∩ sᶜ = ∅ := inf_compl_eq_bot @[simp] lemma compl_union (s t : finset α) : (s ∪ t)ᶜ = sᶜ ∩ tᶜ := compl_sup @[simp] lemma compl_inter (s t : finset α) : (s ∩ t)ᶜ = sᶜ ∪ tᶜ := compl_inf @[simp] lemma compl_erase : (s.erase a)ᶜ = insert a sᶜ := by { ext, simp only [or_iff_not_imp_left, mem_insert, not_and, mem_compl, mem_erase] } @[simp] lemma compl_insert : (insert a s)ᶜ = sᶜ.erase a := by { ext, simp only [not_or_distrib, mem_insert, iff_self, mem_compl, mem_erase] } @[simp] lemma insert_compl_self (x : α) : insert x ({x}ᶜ : finset α) = univ := by rw [←compl_erase, erase_singleton, compl_empty] @[simp] lemma compl_filter (p : α → Prop) [decidable_pred p] [Π x, decidable (¬p x)] : (univ.filter p)ᶜ = univ.filter (λ x, ¬p x) := (filter_not _ _).symm lemma compl_ne_univ_iff_nonempty (s : finset α) : sᶜ ≠ univ ↔ s.nonempty := by simp [eq_univ_iff_forall, finset.nonempty] lemma compl_singleton (a : α) : ({a} : finset α)ᶜ = univ.erase a := by rw [compl_eq_univ_sdiff, sdiff_singleton_eq_erase] end boolean_algebra @[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 piecewise_compl [decidable_eq α] (s : finset α) [Π i : α, decidable (i ∈ s)] [Π i : α, decidable (i ∈ sᶜ)] {δ : α → Sort*} (f g : Π i, δ i) : sᶜ.piecewise f g = s.piecewise g f := by { ext i, simp [piecewise] } @[simp] lemma piecewise_erase_univ {δ : α → Sort*} [decidable_eq α] (a : α) (f g : Π a, δ a) : (finset.univ.erase a).piecewise f g = function.update f a (g a) := by rw [←compl_singleton, piecewise_compl, piecewise_singleton] lemma univ_map_equiv_to_embedding {α β : Type*} [fintype α] [fintype β] (e : α ≃ β) : univ.map e.to_embedding = univ := eq_univ_iff_forall.mpr (λ b, mem_map.mpr ⟨e.symm b, mem_univ _, by simp⟩) @[simp] lemma univ_filter_exists (f : α → β) [fintype β] [decidable_pred (λ y, ∃ x, f x = y)] [decidable_eq β] : finset.univ.filter (λ y, ∃ x, f x = y) = finset.univ.image f := by { ext, simp } /-- Note this is a special case of `(finset.image_preimage f univ _).symm`. -/ lemma univ_filter_mem_range (f : α → β) [fintype β] [decidable_pred (λ y, y ∈ set.range f)] [decidable_eq β] : finset.univ.filter (λ y, y ∈ set.range f) = finset.univ.image f := univ_filter_exists f /-- A special case of `finset.sup_eq_supr` that omits the useless `x ∈ univ` binder. -/ lemma sup_univ_eq_supr [complete_lattice β] (f : α → β) : finset.univ.sup f = supr f := (sup_eq_supr _ f).trans $ congr_arg _ $ funext $ λ a, supr_pos (mem_univ _) /-- A special case of `finset.inf_eq_infi` that omits the useless `x ∈ univ` binder. -/ lemma inf_univ_eq_infi [complete_lattice β] (f : α → β) : finset.univ.inf f = infi f := sup_univ_eq_supr (by exact f : α → order_dual β) @[simp] lemma fold_inf_univ [semilattice_inf α] [order_bot α] (a : α) : finset.univ.fold (⊓) a (λ x, x) = ⊥ := eq_bot_iff.2 $ ((finset.fold_op_rel_iff_and $ @_root_.le_inf_iff α _).1 le_rfl).2 ⊥ $ finset.mem_univ _ @[simp] lemma fold_sup_univ [semilattice_sup α] [order_top α] (a : α) : finset.univ.fold (⊔) a (λ x, x) = ⊤ := @fold_inf_univ (order_dual α) ‹fintype α› _ _ _ end finset open finset function namespace fintype instance decidable_pi_fintype {α} {β : α → Type*} [∀ a, decidable_eq (β a)] [fintype α] : decidable_eq (Π a, β a) := λ 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_mem_range_fintype [fintype α] [decidable_eq β] (f : α → β) : decidable_pred (∈ set.range f) := λ x, fintype.decidable_exists_fintype section bundled_homs instance decidable_eq_equiv_fintype [decidable_eq β] [fintype α] : decidable_eq (α ≃ β) := λ a b, decidable_of_iff (a.1 = b.1) equiv.coe_fn_injective.eq_iff instance decidable_eq_embedding_fintype [decidable_eq β] [fintype α] : decidable_eq (α ↪ β) := λ a b, decidable_of_iff ((a : α → β) = b) function.embedding.coe_injective.eq_iff @[to_additive] instance decidable_eq_one_hom_fintype [decidable_eq β] [fintype α] [has_one α] [has_one β]: decidable_eq (one_hom α β) := λ a b, decidable_of_iff ((a : α → β) = b) (injective.eq_iff one_hom.coe_inj) @[to_additive] instance decidable_eq_mul_hom_fintype [decidable_eq β] [fintype α] [has_mul α] [has_mul β]: decidable_eq (mul_hom α β) := λ a b, decidable_of_iff ((a : α → β) = b) (injective.eq_iff mul_hom.coe_inj) @[to_additive] instance decidable_eq_monoid_hom_fintype [decidable_eq β] [fintype α] [mul_one_class α] [mul_one_class β]: decidable_eq (α →* β) := λ a b, decidable_of_iff ((a : α → β) = b) (injective.eq_iff monoid_hom.coe_inj) instance decidable_eq_monoid_with_zero_hom_fintype [decidable_eq β] [fintype α] [mul_zero_one_class α] [mul_zero_one_class β] : decidable_eq (α →*₀ β) := λ a b, decidable_of_iff ((a : α → β) = b) (injective.eq_iff monoid_with_zero_hom.coe_inj) instance decidable_eq_ring_hom_fintype [decidable_eq β] [fintype α] [semiring α] [semiring β]: decidable_eq (α →+* β) := λ a b, decidable_of_iff ((a : α → β) = b) (injective.eq_iff ring_hom.coe_inj) end bundled_homs 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_right_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_left_inverse_fintype [decidable_eq β] [fintype β] (f : α → β) (g : β → α) : decidable (function.left_inverse f g) := show decidable (∀ x, f (g x) = x), by apply_instance lemma exists_max [fintype α] [nonempty α] {β : Type*} [linear_order β] (f : α → β) : ∃ x₀ : α, ∀ x, f x ≤ f x₀ := by simpa using exists_max_image univ f univ_nonempty lemma exists_min [fintype α] [nonempty α] {β : Type*} [linear_order β] (f : α → β) : ∃ x₀ : α, ∀ x, f x₀ ≤ f x := by simpa using exists_min_image univ f univ_nonempty /-- 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 /-- There is (computably) an equivalence between `α` and `fin (card α)`. Since it is not unique and depends on which permutation of the universe list is used, the equivalence is wrapped in `trunc` to preserve computability. See `fintype.equiv_fin` for the noncomputable version, and `fintype.trunc_equiv_fin_of_card_eq` and `fintype.equiv_fin_of_card_eq` for an equiv `α ≃ fin n` given `fintype.card α = n`. See `fintype.trunc_fin_bijection` for a version without `[decidable_eq α]`. -/ def trunc_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 (nd.nth_le_equiv_of_forall_mem_list _ h).symm) mem_univ_val univ.2 } /-- There is (noncomputably) an equivalence between `α` and `fin (card α)`. See `fintype.trunc_equiv_fin` for the computable version, and `fintype.trunc_equiv_fin_of_card_eq` and `fintype.equiv_fin_of_card_eq` for an equiv `α ≃ fin n` given `fintype.card α = n`. -/ noncomputable def equiv_fin (α) [fintype α] : α ≃ fin (card α) := by { letI := classical.dec_eq α, exact (trunc_equiv_fin α).out } /-- There is (computably) a bijection between `fin (card α)` and `α`. 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. See `fintype.trunc_equiv_fin` for a version that gives an equivalence given `[decidable_eq α]`. -/ def trunc_fin_bijection (α) [fintype α] : trunc {f : fin (card α) → α // bijective f} := by { dunfold card finset.card, exact quot.rec_on_subsingleton (@univ α _).1 (λ l (h : ∀ x : α, x ∈ l) (nd : l.nodup), trunc.mk (nd.nth_le_bijection_of_forall_mem_list _ h)) mem_univ_val univ.2 } 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 _)⟩ end fintype section inv namespace function variables [fintype α] [decidable_eq β] namespace injective variables {f : α → β} (hf : function.injective f) /-- The inverse of an `hf : injective` function `f : α → β`, of the type `↥(set.range f) → α`. This is the computable version of `function.inv_fun` that requires `fintype α` and `decidable_eq β`, or the function version of applying `(equiv.of_injective f hf).symm`. This function should not usually be used for actual computation because for most cases, an explicit inverse can be stated that has better computational properties. This function computes by checking all terms `a : α` to find the `f a = b`, so it is O(N) where `N = fintype.card α`. -/ def inv_of_mem_range : set.range f → α := λ b, finset.choose (λ a, f a = b) finset.univ ((exists_unique_congr (by simp)).mp (hf.exists_unique_of_mem_range b.property)) lemma left_inv_of_inv_of_mem_range (b : set.range f) : f (hf.inv_of_mem_range b) = b := (finset.choose_spec (λ a, f a = b) _ _).right @[simp] lemma right_inv_of_inv_of_mem_range (a : α) : hf.inv_of_mem_range (⟨f a, set.mem_range_self a⟩) = a := hf (finset.choose_spec (λ a', f a' = f a) _ _).right lemma inv_fun_restrict [nonempty α] : (set.range f).restrict (inv_fun f) = hf.inv_of_mem_range := begin ext ⟨b, h⟩, apply hf, simp [hf.left_inv_of_inv_of_mem_range, @inv_fun_eq _ _ _ f b (set.mem_range.mp h)] end lemma inv_of_mem_range_surjective : function.surjective hf.inv_of_mem_range := λ a, ⟨⟨f a, set.mem_range_self a⟩, by simp⟩ end injective namespace embedding variables (f : α ↪ β) (b : set.range f) /-- The inverse of an embedding `f : α ↪ β`, of the type `↥(set.range f) → α`. This is the computable version of `function.inv_fun` that requires `fintype α` and `decidable_eq β`, or the function version of applying `(equiv.of_injective f f.injective).symm`. This function should not usually be used for actual computation because for most cases, an explicit inverse can be stated that has better computational properties. This function computes by checking all terms `a : α` to find the `f a = b`, so it is O(N) where `N = fintype.card α`. -/ def inv_of_mem_range : α := f.injective.inv_of_mem_range b @[simp] lemma left_inv_of_inv_of_mem_range : f (f.inv_of_mem_range b) = b := f.injective.left_inv_of_inv_of_mem_range b @[simp] lemma right_inv_of_inv_of_mem_range (a : α) : f.inv_of_mem_range ⟨f a, set.mem_range_self a⟩ = a := f.injective.right_inv_of_inv_of_mem_range a lemma inv_fun_restrict [nonempty α] : (set.range f).restrict (inv_fun f) = f.inv_of_mem_range := begin ext ⟨b, h⟩, apply f.injective, simp [f.left_inv_of_inv_of_mem_range, @inv_fun_eq _ _ _ f b (set.mem_range.mp h)] end lemma inv_of_mem_range_surjective : function.surjective f.inv_of_mem_range := λ a, ⟨⟨f a, set.mem_range_self a⟩, by simp⟩ end embedding end function end inv namespace fintype /-- 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 @[congr] lemma card_congr' {α β} [fintype α] [fintype β] (h : α = β) : card α = card β := card_congr (by rw h) section variables [fintype α] [fintype β] /-- If the cardinality of `α` is `n`, there is computably a bijection between `α` and `fin n`. See `fintype.equiv_fin_of_card_eq` for the noncomputable definition, and `fintype.trunc_equiv_fin` and `fintype.equiv_fin` for the bijection `α ≃ fin (card α)`. -/ def trunc_equiv_fin_of_card_eq [decidable_eq α] {n : ℕ} (h : fintype.card α = n) : trunc (α ≃ fin n) := (trunc_equiv_fin α).map (λ e, e.trans (fin.cast h).to_equiv) /-- If the cardinality of `α` is `n`, there is noncomputably a bijection between `α` and `fin n`. See `fintype.trunc_equiv_fin_of_card_eq` for the computable definition, and `fintype.trunc_equiv_fin` and `fintype.equiv_fin` for the bijection `α ≃ fin (card α)`. -/ noncomputable def equiv_fin_of_card_eq {n : ℕ} (h : fintype.card α = n) : α ≃ fin n := by { letI := classical.dec_eq α, exact (trunc_equiv_fin_of_card_eq h).out } /-- Two `fintype`s with the same cardinality are (computably) in bijection. See `fintype.equiv_of_card_eq` for the noncomputable version, and `fintype.trunc_equiv_fin_of_card_eq` and `fintype.equiv_fin_of_card_eq` for the specialization to `fin`. -/ def trunc_equiv_of_card_eq [decidable_eq α] [decidable_eq β] (h : card α = card β) : trunc (α ≃ β) := (trunc_equiv_fin_of_card_eq h).bind (λ e, (trunc_equiv_fin β).map (λ e', e.trans e'.symm)) /-- Two `fintype`s with the same cardinality are (noncomputably) in bijection. See `fintype.trunc_equiv_of_card_eq` for the computable version, and `fintype.trunc_equiv_fin_of_card_eq` and `fintype.equiv_fin_of_card_eq` for the specialization to `fin`. -/ noncomputable def equiv_of_card_eq (h : card α = card β) : α ≃ β := by { letI := classical.dec_eq α, letI := classical.dec_eq β, exact (trunc_equiv_of_card_eq h).out } end theorem card_eq {α β} [F : fintype α] [G : fintype β] : card α = card β ↔ nonempty (α ≃ β) := ⟨λ h, by { haveI := classical.prop_decidable, exact (trunc_equiv_of_card_eq h).nonempty }, λ ⟨f⟩, card_congr f⟩ /-- Any subsingleton type with a witness is a fintype (with one term). -/ 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 /-- Note: this lemma is specifically about `fintype.of_subsingleton`. For a statement about arbitrary `fintype` instances, use either `fintype.card_le_one_iff_subsingleton` or `fintype.card_unique`. -/ @[simp] theorem card_of_subsingleton (a : α) [subsingleton α] : @fintype.card _ (of_subsingleton a) = 1 := rfl @[simp] theorem card_unique [unique α] [h : fintype α] : fintype.card α = 1 := subsingleton.elim (of_subsingleton default) h ▸ card_of_subsingleton _ @[priority 100] -- see Note [lower instance priority] instance of_is_empty [is_empty α] : fintype α := ⟨∅, is_empty_elim⟩ /-- Note: this lemma is specifically about `fintype.of_is_empty`. For a statement about arbitrary `fintype` instances, use `finset.univ_eq_empty`. -/ -- no-lint since while `finset.univ_eq_empty` can prove this, it isn't applicable for `dsimp`. @[simp, nolint simp_nf] theorem univ_of_is_empty [is_empty α] : @univ α _ = ∅ := rfl /-- Note: this lemma is specifically about `fintype.of_is_empty`. For a statement about arbitrary `fintype` instances, use `fintype.card_eq_zero_iff`. -/ @[simp] theorem card_of_is_empty [is_empty α] : fintype.card α = 0 := rfl open_locale classical variables (α) /-- Any subsingleton type is (noncomputably) a fintype (with zero or one term). -/ @[priority 5] -- see Note [lower instance priority] noncomputable instance of_subsingleton' [subsingleton α] : fintype α := if h : nonempty α then of_subsingleton (nonempty.some h) else @fintype.of_is_empty _ $ not_nonempty_iff.mp h 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⟩ @[congr] lemma to_finset_congr {s t : set α} [fintype s] [fintype t] (h : s = t) : to_finset s = to_finset t := by cc @[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⟩ @[simp, mono] theorem to_finset_mono {s t : set α} [fintype s] [fintype t] : s.to_finset ⊆ t.to_finset ↔ s ⊆ t := by simp [finset.subset_iff, set.subset_def] @[simp, mono] theorem to_finset_strict_mono {s t : set α} [fintype s] [fintype t] : s.to_finset ⊂ t.to_finset ↔ s ⊂ t := begin rw [←lt_eq_ssubset, ←finset.lt_iff_ssubset, lt_iff_le_and_ne, lt_iff_le_and_ne], simp end @[simp] theorem to_finset_disjoint_iff [decidable_eq α] {s t : set α} [fintype s] [fintype t] : disjoint s.to_finset t.to_finset ↔ disjoint s t := ⟨λ h x hx, h (by simpa using hx), λ h x hx, h (by simpa using hx)⟩ 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_eq_iff_eq_univ [fintype α] (s : finset α) : s.card = fintype.card α ↔ s = finset.univ := ⟨s.eq_univ_of_card, by { rintro rfl, exact 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_lt_univ_of_not_mem [fintype α] {s : finset α} {x : α} (hx : x ∉ s) : s.card < fintype.card α := card_lt_card ⟨subset_univ s, not_forall.2 ⟨x, λ hx', hx (hx' $ mem_univ x)⟩⟩ lemma finset.card_lt_iff_ne_univ [fintype α] (s : finset α) : s.card < fintype.card α ↔ s ≠ finset.univ := s.card_le_univ.lt_iff_ne.trans (not_iff_not_of_iff s.card_eq_iff_eq_univ) lemma finset.card_compl_lt_iff_nonempty [fintype α] [decidable_eq α] (s : finset α) : sᶜ.card < fintype.card α ↔ s.nonempty := sᶜ.card_lt_iff_ne_univ.trans s.compl_ne_univ_iff_nonempty 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] /-- `fin` as a map from `ℕ` to `Type` is injective. Note that since this is a statement about equality of types, using it should be avoided if possible. -/ lemma fin_injective : function.injective fin := λ m n h, (fintype.card_fin m).symm.trans $ (fintype.card_congr $ equiv.cast h).trans (fintype.card_fin n) /-- A reversed version of `fin.cast_eq_cast` that is easier to rewrite with. -/ theorem fin.cast_eq_cast' {n m : ℕ} (h : fin n = fin m) : cast h = ⇑(fin.cast $ fin_injective h) := (fin.cast_eq_cast _).symm /-- The cardinality of `fin (bit0 k)` is even, `fact` version. This `fact` is needed as an instance by `matrix.special_linear_group.has_neg`. -/ lemma fintype.card_fin_even {k : ℕ} : fact (even (fintype.card (fin (bit0 k)))) := ⟨by { rw [fintype.card_fin], exact even_bit0 k }⟩ lemma card_finset_fin_le {n : ℕ} (s : finset (fin n)) : s.card ≤ n := by simpa only [fintype.card_fin] using s.card_le_univ 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 ⟩ ⟩ @[simp] lemma fin.image_succ_above_univ {n : ℕ} (i : fin (n + 1)) : univ.image i.succ_above = {i}ᶜ := by { ext m, simp } @[simp] lemma fin.image_succ_univ (n : ℕ) : (univ : finset (fin n)).image fin.succ = {0}ᶜ := by rw [← fin.succ_above_zero, fin.image_succ_above_univ] @[simp] lemma fin.image_cast_succ (n : ℕ) : (univ : finset (fin n)).image fin.cast_succ = {fin.last n}ᶜ := by rw [← fin.succ_above_last, fin.image_succ_above_univ] /-- 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) := by simp /-- 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) := by simp /-- 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)) := by simp @[instance, priority 10] def unique.fintype {α : Type*} [unique α] : fintype α := fintype.of_subsingleton default /-- Short-circuit instance to decrease search for `unique.fintype`, since that relies on a subsingleton elimination for `unique`. -/ instance fintype.subtype_eq (y : α) : fintype {x // x = y} := fintype.subtype {y} (by simp) /-- Short-circuit instance to decrease search for `unique.fintype`, since that relies on a subsingleton elimination for `unique`. -/ instance fintype.subtype_eq' (y : α) : fintype {x // y = x} := fintype.subtype {y} (by simp [eq_comm]) @[simp] lemma fintype.card_subtype_eq (y : α) [fintype {x // x = y}] : fintype.card {x // x = y} = 1 := fintype.card_unique @[simp] lemma fintype.card_subtype_eq' (y : α) [fintype {x // y = x}] : fintype.card {x // y = x} = 1 := fintype.card_unique @[simp] theorem fintype.univ_empty : @univ empty _ = ∅ := rfl @[simp] theorem fintype.card_empty : fintype.card empty = 0 := rfl @[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 ℤˣ := ⟨{1, -1}, λ x, by cases int.units_eq_one_or x; simp *⟩ @[simp] lemma units_int.univ : (finset.univ : finset ℤˣ) = {1, -1} := rfl instance additive.fintype : Π [fintype α], fintype (additive α) := id instance multiplicative.fintype : Π [fintype α], fintype (multiplicative α) := id @[simp] theorem fintype.card_units_int : fintype.card ℤˣ = 2 := rfl @[simp] theorem fintype.card_bool : fintype.card bool = 2 := rfl instance {α : Type*} [fintype α] : fintype (option α) := ⟨univ.insert_none, λ a, by simp⟩ lemma univ_option (α : Type*) [fintype α] : (univ : finset (option α)) = insert_none univ := rfl @[simp] theorem fintype.card_option {α : Type*} [fintype α] : fintype.card (option α) = fintype.card α + 1 := (finset.card_cons _).trans $ congr_arg2 _ (card_map _) rfl 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.prod_left {α β} [decidable_eq α] [fintype (α × β)] [nonempty β] : fintype α := ⟨(fintype.elems (α × β)).image prod.fst, λ a, let ⟨b⟩ := ‹nonempty β› in by simp; exact ⟨b, fintype.complete _⟩⟩ /-- Given that `α × β` is a fintype, `β` is also a fintype. -/ def fintype.prod_right {α β} [decidable_eq β] [fintype (α × β)] [nonempty α] : fintype β := ⟨(fintype.elems (α × β)).image prod.snd, λ 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*) [fintype α] : fintype (plift α) := fintype.of_equiv _ equiv.plift.symm @[simp] theorem fintype.card_plift (α : Type*) [fintype α] : fintype.card (plift α) = fintype.card α := fintype.of_equiv_card _ instance (α : Type*) [fintype α] : fintype (order_dual α) := ‹fintype α› @[simp] lemma fintype.card_order_dual (α : Type*) [fintype α] : fintype.card (order_dual α) = fintype.card α := rfl instance (α : Type*) [fintype α] : fintype (lex α) := ‹fintype α› @[simp] lemma fintype.card_lex (α : Type*) [fintype α] : fintype.card (lex α) = fintype.card α := rfl lemma univ_sum_type {α β : Type*} [fintype α] [fintype β] [fintype (α ⊕ β)] [decidable_eq (α ⊕ β)] : (univ : finset (α ⊕ β)) = map function.embedding.inl univ ∪ map function.embedding.inr univ := begin rw [eq_comm, eq_univ_iff_forall], simp only [mem_union, mem_map, exists_prop, mem_univ, true_and], rintro (x|y), exacts [or.inl ⟨x, rfl⟩, or.inr ⟨y, rfl⟩] end 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)) /-- Given that `α ⊕ β` is a fintype, `α` is also a fintype. This is non-computable as it uses that `sum.inl` is an injection, but there's no clear inverse if `α` is empty. -/ noncomputable def fintype.sum_left {α β} [fintype (α ⊕ β)] : fintype α := fintype.of_injective (sum.inl : α → α ⊕ β) sum.inl_injective /-- Given that `α ⊕ β` is a fintype, `β` is also a fintype. This is non-computable as it uses that `sum.inr` is an injection, but there's no clear inverse if `β` is empty. -/ noncomputable def fintype.sum_right {α β} [fintype (α ⊕ β)] : fintype β := fintype.of_injective (sum.inr : β → α ⊕ β) sum.inr_injective @[simp] theorem fintype.card_sum [fintype α] [fintype β] : fintype.card (α ⊕ β) = fintype.card α + fintype.card β := begin classical, rw [←finset.card_univ, univ_sum_type, finset.card_union_eq], { simp [finset.card_univ] }, { intros x hx, suffices : (∃ (a : α), sum.inl a = x) ∧ ∃ (b : β), sum.inr b = x, { obtain ⟨⟨a, rfl⟩, ⟨b, hb⟩⟩ := this, simpa using hb }, simpa using hx } end /-- If the subtype of all-but-one elements is a `fintype` then the type itself is a `fintype`. -/ def fintype_of_fintype_ne (a : α) [decidable_pred (= a)] (h : fintype {b // b ≠ a}) : fintype α := fintype.of_equiv _ $ equiv.sum_compl (= a) section finset /-! ### `fintype (s : finset α)` -/ instance finset.fintype_coe_sort {α : Type u} (s : finset α) : fintype s := ⟨s.attach, s.mem_attach⟩ @[simp] lemma finset.univ_eq_attach {α : Type u} (s : finset α) : (univ : finset s) = s.attach := rfl end finset 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) lemma card_le_of_embedding (f : α ↪ β) : card α ≤ card β := card_le_of_injective f f.2 lemma card_lt_of_injective_of_not_mem (f : α → β) (h : function.injective f) {b : β} (w : b ∉ set.range f) : card α < card β := calc card α = (univ.map ⟨f, h⟩).card : (card_map _).symm ... < card β : finset.card_lt_univ_of_not_mem $ by rwa [← mem_coe, coe_map, coe_univ, set.image_univ] lemma card_lt_of_injective_not_surjective (f : α → β) (h : function.injective f) (h' : ¬function.surjective f) : card α < card β := let ⟨y, hy⟩ := not_forall.1 h' in card_lt_of_injective_of_not_mem f h hy lemma card_le_of_surjective (f : α → β) (h : function.surjective f) : card β ≤ card α := card_le_of_injective _ (function.injective_surj_inv h) lemma card_range_le {α β : Type*} (f : α → β) [fintype α] [fintype (set.range f)] : fintype.card (set.range f) ≤ fintype.card α := fintype.card_le_of_surjective (λ a, ⟨f a, by simp⟩) (λ ⟨_, a, ha⟩, ⟨a, by simpa using ha⟩) /-- 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 ↔ is_empty α := by rw [card, finset.card_eq_zero, univ_eq_empty_iff] lemma card_eq_zero [is_empty α] : card α = 0 := card_eq_zero_iff.2 ‹_› lemma card_eq_one_iff_nonempty_unique : card α = 1 ↔ nonempty (unique α) := ⟨λ h, let ⟨d, h⟩ := fintype.card_eq_one_iff.mp h in ⟨{ default := d, uniq := h}⟩, λ ⟨h⟩, by exactI fintype.card_unique⟩ /-- A `fintype` with cardinality zero is equivalent to `empty`. -/ def card_eq_zero_equiv_equiv_empty : card α = 0 ≃ (α ≃ empty) := (equiv.of_iff card_eq_zero_iff).trans (equiv.equiv_empty_equiv α).symm lemma card_pos_iff : 0 < card α ↔ nonempty α := pos_iff_ne_zero.trans $ not_iff_comm.mp $ not_nonempty_iff.trans card_eq_zero_iff.symm lemma card_pos [h : nonempty α] : 0 < card α := card_pos_iff.mpr h lemma card_ne_zero [nonempty α] : card α ≠ 0 := ne_of_gt card_pos 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).elim a, λ _, 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_rfl⟩ | (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 α := card_le_one_iff.trans 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 card_eq_one_of_forall_eq {i : α} (h : ∀ j, j = i) : card α = 1 := fintype.card_eq_one_iff.2 ⟨i,h⟩ lemma one_lt_card [h : nontrivial α] : 1 < fintype.card α := fintype.one_lt_card_iff_nontrivial.mpr h lemma one_lt_card_iff : 1 < card α ↔ ∃ a b : α, a ≠ b := one_lt_card_iff_nontrivial.trans nontrivial_iff lemma two_lt_card_iff : 2 < card α ↔ ∃ a b c : α, a ≠ b ∧ a ≠ c ∧ b ≠ c := by simp_rw [←finset.card_univ, two_lt_card_iff, mem_univ, true_and] 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_rfl), 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 card_of_bijective {f : α → β} (hf : bijective f) : card α = card β := card_congr (equiv.of_bijective f hf) lemma bijective_iff_injective_and_card (f : α → β) : bijective f ↔ injective f ∧ card α = card β := begin split, { intro h, exact ⟨h.1, card_of_bijective h⟩ }, { rintro ⟨hf, h⟩, refine ⟨hf, _⟩, rwa ←injective_iff_surjective_of_equiv (equiv_of_card_eq h) } end lemma bijective_iff_surjective_and_card (f : α → β) : bijective f ↔ surjective f ∧ card α = card β := begin split, { intro h, exact ⟨h.2, card_of_bijective h⟩ }, { rintro ⟨hf, h⟩, refine ⟨_, hf⟩, rwa injective_iff_surjective_of_equiv (equiv_of_card_eq h) } end lemma right_inverse_of_left_inverse_of_card_le {f : α → β} {g : β → α} (hfg : left_inverse f g) (hcard : card α ≤ card β) : right_inverse f g := have hsurj : surjective f, from surjective_iff_has_right_inverse.2 ⟨g, hfg⟩, right_inverse_of_injective_of_left_inverse ((bijective_iff_surjective_and_card _).2 ⟨hsurj, le_antisymm hcard (card_le_of_surjective f hsurj)⟩ ).1 hfg lemma left_inverse_of_right_inverse_of_card_le {f : α → β} {g : β → α} (hfg : right_inverse f g) (hcard : card β ≤ card α) : left_inverse f g := right_inverse_of_left_inverse_of_card_le hfg hcard 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 = s.card := card_attach lemma finset.attach_eq_univ {s : finset α} : s.attach = finset.univ := rfl instance plift.fintype_Prop (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)⟩ @[simp] lemma fintype.card_Prop : fintype.card Prop = 2 := rfl instance subtype.fintype (p : α → Prop) [decidable_pred p] [fintype α] : fintype {x // p x} := fintype.subtype (univ.filter p) (by simp) @[simp] lemma set.to_finset_univ [hu : fintype (set.univ : set α)] [fintype α] : @set.to_finset _ (set.univ : set α) hu = finset.univ := by { ext, simp only [set.mem_univ, mem_univ, set.mem_to_finset] } @[simp] lemma set.to_finset_eq_empty_iff {s : set α} [fintype s] : s.to_finset = ∅ ↔ s = ∅ := by simp [ext_iff, set.ext_iff] @[simp] lemma set.to_finset_empty : (∅ : set α).to_finset = ∅ := set.to_finset_eq_empty_iff.mpr rfl @[simp] lemma set.to_finset_range [decidable_eq α] [fintype β] (f : β → α) [fintype (set.range f)] : (set.range f).to_finset = finset.univ.image f := by simp [ext_iff] /-- 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) lemma set_fintype_card_le_univ [fintype α] (s : set α) [fintype ↥s] : fintype.card ↥s ≤ fintype.card α := fintype.card_le_of_embedding (function.embedding.subtype s) lemma set_fintype_card_eq_univ_iff [fintype α] (s : set α) [fintype ↥s] : fintype.card s = fintype.card α ↔ s = set.univ := by rw [←set.to_finset_card, finset.card_eq_iff_eq_univ, ←set.to_finset_univ, set.to_finset_inj] section variables (α) /-- The `αˣ` type is equivalent to a subtype of `α × α`. -/ @[simps] def _root_.units_equiv_prod_subtype [monoid α] : αˣ ≃ {p : α × α // p.1 * p.2 = 1 ∧ p.2 * p.1 = 1} := { to_fun := λ u, ⟨(u, ↑u⁻¹), u.val_inv, u.inv_val⟩, inv_fun := λ p, units.mk (p : α × α).1 (p : α × α).2 p.prop.1 p.prop.2, left_inv := λ u, units.ext rfl, right_inv := λ p, subtype.ext $ prod.ext rfl rfl} /-- In a `group_with_zero` `α`, the unit group `αˣ` is equivalent to the subtype of nonzero elements. -/ @[simps] def _root_.units_equiv_ne_zero [group_with_zero α] : αˣ ≃ {a : α // a ≠ 0} := ⟨λ a, ⟨a, a.ne_zero⟩, λ a, units.mk0 _ a.prop, λ _, units.ext rfl, λ _, subtype.ext rfl⟩ end instance [monoid α] [fintype α] [decidable_eq α] : fintype αˣ := fintype.of_equiv _ (units_equiv_prod_subtype α).symm lemma fintype.card_units [group_with_zero α] [fintype α] [fintype αˣ] : fintype.card αˣ = fintype.card α - 1 := begin classical, rw [eq_comm, nat.sub_eq_iff_eq_add (fintype.card_pos_iff.2 ⟨(0 : α)⟩), fintype.card_congr (units_equiv_ne_zero α)], have := fintype.card_congr (equiv.sum_compl (= (0 : α))).symm, rwa [fintype.card_sum, add_comm, fintype.card_subtype_eq] at this, end namespace function.embedding /-- An embedding from a `fintype` to itself can be promoted to an equivalence. -/ noncomputable def equiv_of_fintype_self_embedding [fintype α] (e : α ↪ α) : α ≃ α := equiv.of_bijective e (fintype.injective_iff_bijective.1 e.2) @[simp] lemma equiv_of_fintype_self_embedding_to_embedding [fintype α] (e : α ↪ α) : e.equiv_of_fintype_self_embedding.to_embedding = e := by { ext, refl, } /-- If `‖β‖ < ‖α‖` there are no embeddings `α ↪ β`. This is a formulation of the pigeonhole principle. Note this cannot be an instance as it needs `h`. -/ @[simp] lemma is_empty_of_card_lt [fintype α] [fintype β] (h : fintype.card β < fintype.card α) : is_empty (α ↪ β) := ⟨λ f, let ⟨x, y, ne, feq⟩ := fintype.exists_ne_map_eq_of_card_lt f h in ne $ f.injective feq⟩ /-- A constructive embedding of a fintype `α` in another fintype `β` when `card α ≤ card β`. -/ def trunc_of_card_le [fintype α] [fintype β] [decidable_eq α] [decidable_eq β] (h : fintype.card α ≤ fintype.card β) : trunc (α ↪ β) := (fintype.trunc_equiv_fin α).bind $ λ ea, (fintype.trunc_equiv_fin β).map $ λ eb, ea.to_embedding.trans ((fin.cast_le h).to_embedding.trans eb.symm.to_embedding) lemma nonempty_of_card_le [fintype α] [fintype β] (h : fintype.card α ≤ fintype.card β) : nonempty (α ↪ β) := by { classical, exact (trunc_of_card_le h).nonempty } lemma exists_of_card_le_finset [fintype α] {s : finset β} (h : fintype.card α ≤ s.card) : ∃ (f : α ↪ β), set.range f ⊆ s := begin rw ← fintype.card_coe at h, rcases nonempty_of_card_le h with ⟨f⟩, exact ⟨f.trans (embedding.subtype _), by simp [set.range_subset_iff]⟩ end 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 lemma card_lt_of_surjective_not_injective [fintype α] [fintype β] (f : α → β) (h : function.surjective f) (h' : ¬function.injective f) : card β < card α := card_lt_of_injective_not_surjective _ (function.injective_surj_inv h) $ λ hg, have w : function.bijective (function.surj_inv h) := ⟨function.injective_surj_inv h, hg⟩, h' $ (injective_iff_surjective_of_equiv (equiv.of_bijective _ w).symm).mpr h 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], rintro 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], exact λ hf, ⟨λ a ha, f a, hf, rfl⟩ } end @[simp] lemma coe_pi_finset (t : Π a, finset (δ a)) : (pi_finset t : set (Π a, δ a)) = set.pi set.univ (λ a, t a) := set.ext $ λ x, by { rw set.mem_univ_pi, exact fintype.mem_pi_finset } 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 _)⟩ -- irreducible due to this conversation on Zulip: -- https://leanprover.zulipchat.com/#narrow/stream/113488-general/ -- topic/.60simp.60.20ignoring.20lemmas.3F/near/241824115 @[irreducible] instance function.embedding.fintype {α β} [fintype α] [fintype β] [decidable_eq α] [decidable_eq β] : fintype (α ↪ β) := fintype.of_equiv _ (equiv.subtype_injective_equiv_embedding α β) instance [decidable_eq α] [fintype α] {n : ℕ} : fintype (sym.sym' α n) := quotient.fintype _ instance [decidable_eq α] [fintype α] {n : ℕ} : fintype (sym α n) := fintype.of_equiv _ sym.sym_equiv_sym'.symm @[simp] lemma fintype.card_finset [fintype α] : fintype.card (finset α) = 2 ^ (fintype.card α) := finset.card_powerset finset.univ lemma finset.mem_powerset_len_univ_iff [fintype α] {s : finset α} {k : ℕ} : s ∈ powerset_len k (univ : finset α) ↔ card s = k := mem_powerset_len.trans $ and_iff_right $ subset_univ _ @[simp] lemma finset.univ_filter_card_eq (α : Type*) [fintype α] (k : ℕ) : (finset.univ : finset (finset α)).filter (λ s, s.card = k) = finset.univ.powerset_len k := by { ext, simp [finset.mem_powerset_len] } @[simp] lemma fintype.card_finset_len [fintype α] (k : ℕ) : fintype.card {s : finset α // s.card = k} = nat.choose (fintype.card α) k := by simp [fintype.subtype_card, finset.card_univ] theorem fintype.card_subtype_le [fintype α] (p : α → Prop) [decidable_pred p] : fintype.card {x // p x} ≤ fintype.card α := fintype.card_le_of_embedding (function.embedding.subtype _) theorem fintype.card_subtype_lt [fintype α] {p : α → Prop} [decidable_pred p] {x : α} (hx : ¬ p x) : fintype.card {x // p x} < fintype.card α := fintype.card_lt_of_injective_of_not_mem coe subtype.coe_injective $ by rwa subtype.range_coe_subtype lemma fintype.card_subtype [fintype α] (p : α → Prop) [decidable_pred p] : fintype.card {x // p x} = ((finset.univ : finset α).filter p).card := begin refine fintype.card_of_subtype _ _, simp end lemma fintype.card_subtype_or (p q : α → Prop) [fintype {x // p x}] [fintype {x // q x}] [fintype {x // p x ∨ q x}] : fintype.card {x // p x ∨ q x} ≤ fintype.card {x // p x} + fintype.card {x // q x} := begin classical, convert fintype.card_le_of_embedding (subtype_or_left_embedding p q), rw fintype.card_sum end lemma fintype.card_subtype_or_disjoint (p q : α → Prop) (h : disjoint p q) [fintype {x // p x}] [fintype {x // q x}] [fintype {x // p x ∨ q x}] : fintype.card {x // p x ∨ q x} = fintype.card {x // p x} + fintype.card {x // q x} := begin classical, convert fintype.card_congr (subtype_or_equiv p q h), simp end theorem fintype.card_quotient_le [fintype α] (s : setoid α) [decidable_rel ((≈) : α → α → Prop)] : fintype.card (quotient s) ≤ fintype.card α := fintype.card_le_of_surjective _ (surjective_quotient_mk _) theorem fintype.card_quotient_lt [fintype α] {s : setoid α} [decidable_rel ((≈) : α → α → Prop)] {x y : α} (h1 : x ≠ y) (h2 : x ≈ y) : fintype.card (quotient s) < fintype.card α := fintype.card_lt_of_surjective_not_injective _ (surjective_quotient_mk _) $ λ w, h1 (w $ quotient.eq.mpr h2) 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⟩ @[simp] lemma fintype.card_set [fintype α] : fintype.card (set α) = 2 ^ fintype.card α := (finset.card_map _).trans (finset.card_powerset _) 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 /-- 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, _⟩), { exact mem_of_ne_of_mem hfa (h _ hfa') }, { rw [←mul_assoc, mul_def (swap a (f a)) (swap a (f a)), swap_swap, ←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.trunc_equiv_fin α) (λ eα, trunc.rec_on_subsingleton (fintype.trunc_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 symmetry, 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 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 @[simp] lemma choose_subtype_eq {α : Type*} (p : α → Prop) [fintype {a : α // p a}] [decidable_eq α] (x : {a : α // p a}) (h : ∃! (a : {a // p a}), (a : α) = x := ⟨x, rfl, λ y hy, by simpa [subtype.ext_iff] using hy⟩) : fintype.choose (λ (y : {a : α // p a}), (y : α) = x) h = x := by rw [subtype.ext_iff, fintype.choose_spec (λ (y : {a : α // p a}), (y : α) = x) _] end choose section bijection_inverse open function variables [fintype α] [decidable_eq β] {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. Note that `infinite α` is equivalent to `is_empty (fintype α)`. -/ class infinite (α : Type*) : Prop := (not_fintype : fintype α → false) lemma not_fintype (α : Type*) [h1 : infinite α] [h2 : fintype α] : false := infinite.not_fintype h2 protected lemma fintype.false {α : Type*} [infinite α] (h : fintype α) : false := not_fintype α protected lemma infinite.false {α : Type*} [fintype α] (h : infinite α) : false := not_fintype α @[simp] lemma is_empty_fintype {α : Type*} : is_empty (fintype α) ↔ infinite α := ⟨λ ⟨x⟩, ⟨x⟩, λ ⟨x⟩, ⟨x⟩⟩ /-- A non-infinite type is a fintype. -/ noncomputable def fintype_of_not_infinite {α : Type*} (h : ¬ infinite α) : fintype α := nonempty.some $ by rwa [← not_is_empty_iff, is_empty_fintype] section open_locale classical /-- Any type is (classically) either a `fintype`, or `infinite`. One can obtain the relevant typeclasses via `cases fintype_or_infinite α; resetI`. -/ noncomputable def fintype_or_infinite (α : Type*) : psum (fintype α) (infinite α) := if h : infinite α then psum.inr h else psum.inl (fintype_of_not_infinite h) end 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, fintype.false ⟨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⟩⟩ protected lemma nonempty (α : Type*) [infinite α] : nonempty α := by apply_instance lemma of_injective [infinite β] (f : β → α) (hf : injective f) : infinite α := ⟨λ I, by exactI (fintype.of_injective f hf).false⟩ lemma of_surjective [infinite β] (f : α → β) (hf : surjective f) : infinite α := ⟨λ I, by { classical, exactI (fintype.of_surjective f hf).false }⟩ instance : infinite ℕ := ⟨λ ⟨s, hs⟩, finset.not_mem_range_self $ s.subset_range_sup_succ (hs _)⟩ instance : infinite ℤ := infinite.of_injective int.of_nat (λ _ _, int.of_nat.inj) instance [infinite α] : infinite (set α) := of_injective singleton (λ a b, set.singleton_eq_singleton_iff.1) instance [infinite α] : infinite (finset α) := of_injective singleton finset.singleton_injective instance [nonempty α] : infinite (multiset α) := begin inhabit α, exact of_injective (multiset.repeat default) (multiset.repeat_injective _), end instance [nonempty α] : infinite (list α) := of_surjective (coe : list α → multiset α) (surjective_quot_mk _) instance sum_of_left [infinite α] : infinite (α ⊕ β) := of_injective sum.inl sum.inl_injective instance sum_of_right [infinite β] : infinite (α ⊕ β) := of_injective sum.inr sum.inr_injective instance prod_of_right [nonempty α] [infinite β] : infinite (α × β) := of_surjective prod.snd prod.snd_surjective instance prod_of_left [infinite α] [nonempty β] : infinite (α × β) := of_surjective prod.fst prod.fst_surjective 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 rintro 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 @[simp] lemma infinite_sum : infinite (α ⊕ β) ↔ infinite α ∨ infinite β := begin refine ⟨λ H, _, λ H, H.elim (@infinite.sum_of_left α β) (@infinite.sum_of_right α β)⟩, contrapose! H, haveI := fintype_of_not_infinite H.1, haveI := fintype_of_not_infinite H.2, exact infinite.false end @[simp] lemma infinite_prod : infinite (α × β) ↔ infinite α ∧ nonempty β ∨ nonempty α ∧ infinite β := begin refine ⟨λ H, _, λ H, H.elim (and_imp.2 $ @infinite.prod_of_left α β) (and_imp.2 $ @infinite.prod_of_right α β)⟩, rw and.comm, contrapose! H, introI H', rcases infinite.nonempty (α × β) with ⟨a, b⟩, haveI := fintype_of_not_infinite (H.1 ⟨b⟩), haveI := fintype_of_not_infinite (H.2 ⟨a⟩), exact H'.false end /-- If every finset in a type has bounded cardinality, that type is finite. -/ noncomputable def fintype_of_finset_card_le {ι : Type*} (n : ℕ) (w : ∀ s : finset ι, s.card ≤ n) : fintype ι := begin apply fintype_of_not_infinite, introI i, obtain ⟨s, c⟩ := infinite.exists_subset_card_eq ι (n+1), specialize w s, rw c at w, exact nat.not_succ_le_self n w, end lemma not_injective_infinite_fintype [infinite α] [fintype β] (f : α → β) : ¬ injective f := λ hf, (fintype.of_injective f hf).false /-- 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, apply not_injective_infinite_fintype f, intros x y, contrapose, apply hf, end -- irreducible due to this conversation on Zulip: -- https://leanprover.zulipchat.com/#narrow/stream/113488-general/ -- topic/.60simp.60.20ignoring.20lemmas.3F/near/241824115 @[irreducible] instance function.embedding.is_empty {α β} [infinite α] [fintype β] : is_empty (α ↪ β) := ⟨λ f, let ⟨x, y, ne, feq⟩ := fintype.exists_ne_map_eq_of_infinite f in ne $ f.injective feq⟩ @[priority 100] noncomputable instance function.embedding.fintype' {α β : Type*} [fintype β] : fintype (α ↪ β) := begin by_cases h : infinite α, { resetI, apply_instance }, { have := fintype_of_not_infinite h, classical, apply_instance } -- the `classical` generates `decidable_eq α/β` instances, and resets instance cache 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, haveI := λ y, fintype_of_not_infinite $ hf y, let key : fintype α := { elems := univ.bUnion (λ (y : β), (f ⁻¹' {y}).to_finset), complete := by simp }, exact key.false, end lemma not_surjective_fintype_infinite [fintype α] [infinite β] (f : α → β) : ¬ surjective f := assume (hf : surjective f), have H : infinite α := infinite.of_surjective f hf, by exactI not_fintype α 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 namespace multiset variables [fintype α] [decidable_eq α] @[simp] lemma count_univ (a : α) : count a finset.univ.val = 1 := count_eq_one_of_mem finset.univ.nodup (finset.mem_univ _) end multiset namespace fintype /-- A recursor principle for finite types, analogous to `nat.rec`. It effectively says that every `fintype` is either `empty` or `option α`, up to an `equiv`. -/ def trunc_rec_empty_option {P : Type u → Sort v} (of_equiv : ∀ {α β}, α ≃ β → P α → P β) (h_empty : P pempty) (h_option : ∀ {α} [fintype α] [decidable_eq α], P α → P (option α)) (α : Type u) [fintype α] [decidable_eq α] : trunc (P α) := begin suffices : ∀ n : ℕ, trunc (P (ulift $ fin n)), { apply trunc.bind (this (fintype.card α)), intro h, apply trunc.map _ (fintype.trunc_equiv_fin α), intro e, exact of_equiv (equiv.ulift.trans e.symm) h }, intro n, induction n with n ih, { have : card pempty = card (ulift (fin 0)), { simp only [card_fin, card_pempty, card_ulift] }, apply trunc.bind (trunc_equiv_of_card_eq this), intro e, apply trunc.mk, refine of_equiv e h_empty, }, { have : card (option (ulift (fin n))) = card (ulift (fin n.succ)), { simp only [card_fin, card_option, card_ulift] }, apply trunc.bind (trunc_equiv_of_card_eq this), intro e, apply trunc.map _ ih, intro ih, refine of_equiv e (h_option ih), }, end /-- An induction principle for finite types, analogous to `nat.rec`. It effectively says that every `fintype` is either `empty` or `option α`, up to an `equiv`. -/ @[elab_as_eliminator] lemma induction_empty_option' {P : Π (α : Type u) [fintype α], Prop} (of_equiv : ∀ α β [fintype β] (e : α ≃ β), @P α (@fintype.of_equiv α β ‹_› e.symm) → @P β ‹_›) (h_empty : P pempty) (h_option : ∀ α [fintype α], by exactI P α → P (option α)) (α : Type u) [fintype α] : P α := begin obtain ⟨p⟩ := @trunc_rec_empty_option (λ α, ∀ h, @P α h) (λ α β e hα hβ, @of_equiv α β hβ e (hα _)) (λ _i, by convert h_empty) _ α _ (classical.dec_eq α), { exact p _ }, { rintro α hα - Pα hα', resetI, convert h_option α (Pα _) } end /-- An induction principle for finite types, analogous to `nat.rec`. It effectively says that every `fintype` is either `empty` or `option α`, up to an `equiv`. -/ lemma induction_empty_option {P : Type u → Prop} (of_equiv : ∀ {α β}, α ≃ β → P α → P β) (h_empty : P pempty) (h_option : ∀ {α} [fintype α], P α → P (option α)) (α : Type u) [fintype α] : P α := begin refine induction_empty_option' _ _ _ α, exacts [λ α β _, of_equiv, h_empty, @h_option] end end fintype /-- Auxiliary definition to show `exists_seq_of_forall_finset_exists`. -/ noncomputable def seq_of_forall_finset_exists_aux {α : Type*} [decidable_eq α] (P : α → Prop) (r : α → α → Prop) (h : ∀ (s : finset α), ∃ y, (∀ x ∈ s, P x) → (P y ∧ (∀ x ∈ s, r x y))) : ℕ → α | n := classical.some (h (finset.image (λ (i : fin n), seq_of_forall_finset_exists_aux i) (finset.univ : finset (fin n)))) using_well_founded {dec_tac := `[exact i.2]} /-- Induction principle to build a sequence, by adding one point at a time satisfying a given relation with respect to all the previously chosen points. More precisely, Assume that, for any finite set `s`, one can find another point satisfying some relation `r` with respect to all the points in `s`. Then one may construct a function `f : ℕ → α` such that `r (f m) (f n)` holds whenever `m < n`. We also ensure that all constructed points satisfy a given predicate `P`. -/ lemma exists_seq_of_forall_finset_exists {α : Type*} (P : α → Prop) (r : α → α → Prop) (h : ∀ (s : finset α), (∀ x ∈ s, P x) → ∃ y, P y ∧ (∀ x ∈ s, r x y)) : ∃ (f : ℕ → α), (∀ n, P (f n)) ∧ (∀ m n, m < n → r (f m) (f n)) := begin classical, haveI : nonempty α, { rcases h ∅ (by simp) with ⟨y, hy⟩, exact ⟨y⟩ }, choose! F hF using h, have h' : ∀ (s : finset α), ∃ y, (∀ x ∈ s, P x) → (P y ∧ (∀ x ∈ s, r x y)) := λ s, ⟨F s, hF s⟩, set f := seq_of_forall_finset_exists_aux P r h' with hf, have A : ∀ (n : ℕ), P (f n), { assume n, induction n using nat.strong_induction_on with n IH, have IH' : ∀ (x : fin n), P (f x) := λ n, IH n.1 n.2, rw [hf, seq_of_forall_finset_exists_aux], exact (classical.some_spec (h' (finset.image (λ (i : fin n), f i) (finset.univ : finset (fin n)))) (by simp [IH'])).1 }, refine ⟨f, A, λ m n hmn, _⟩, nth_rewrite 1 hf, rw seq_of_forall_finset_exists_aux, apply (classical.some_spec (h' (finset.image (λ (i : fin n), f i) (finset.univ : finset (fin n)))) (by simp [A])).2, exact finset.mem_image.2 ⟨⟨m, hmn⟩, finset.mem_univ _, rfl⟩, end /-- Induction principle to build a sequence, by adding one point at a time satisfying a given symmetric relation with respect to all the previously chosen points. More precisely, Assume that, for any finite set `s`, one can find another point satisfying some relation `r` with respect to all the points in `s`. Then one may construct a function `f : ℕ → α` such that `r (f m) (f n)` holds whenever `m ≠ n`. We also ensure that all constructed points satisfy a given predicate `P`. -/ lemma exists_seq_of_forall_finset_exists' {α : Type*} (P : α → Prop) (r : α → α → Prop) [is_symm α r] (h : ∀ (s : finset α), (∀ x ∈ s, P x) → ∃ y, P y ∧ (∀ x ∈ s, r x y)) : ∃ (f : ℕ → α), (∀ n, P (f n)) ∧ (∀ m n, m ≠ n → r (f m) (f n)) := begin rcases exists_seq_of_forall_finset_exists P r h with ⟨f, hf, hf'⟩, refine ⟨f, hf, λ m n hmn, _⟩, rcases lt_trichotomy m n with h|rfl|h, { exact hf' m n h }, { exact (hmn rfl).elim }, { apply symm, exact hf' n m h } end /-- A custom induction principle for fintypes. The base case is a subsingleton type, and the induction step is for non-trivial types, and one can assume the hypothesis for smaller types (via `fintype.card`). The major premise is `fintype α`, so to use this with the `induction` tactic you have to give a name to that instance and use that name. -/ @[elab_as_eliminator] lemma fintype.induction_subsingleton_or_nontrivial {P : Π α [fintype α], Prop} (α : Type*) [fintype α] (hbase : ∀ α [fintype α] [subsingleton α], by exactI P α) (hstep : ∀ α [fintype α] [nontrivial α], by exactI ∀ (ih : ∀ β [fintype β], by exactI ∀ (h : fintype.card β < fintype.card α), P β), P α) : P α := begin obtain ⟨ n, hn ⟩ : ∃ n, fintype.card α = n := ⟨fintype.card α, rfl⟩, unfreezingI { induction n using nat.strong_induction_on with n ih generalizing α }, casesI (subsingleton_or_nontrivial α) with hsing hnontriv, { apply hbase, }, { apply hstep, introsI β _ hlt, rw hn at hlt, exact (ih (fintype.card β) hlt _ rfl), } end
ad6e45151f23b216e87a291f89b30e51367e3606
d1a52c3f208fa42c41df8278c3d280f075eb020c
/stage0/src/Lean/Util/CollectLevelParams.lean
590491592a099a68f4b9bc6c7a912e5825d670f7
[ "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
2,284
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.Expr namespace Lean namespace CollectLevelParams structure State where visitedLevel : LevelSet := {} visitedExpr : ExprSet := {} params : Array Name := #[] instance : Inhabited State := ⟨{}⟩ abbrev Visitor := State → State mutual partial def visitLevel (u : Level) : Visitor := fun s => if !u.hasParam || s.visitedLevel.contains u then s else collect u { s with visitedLevel := s.visitedLevel.insert u } partial def collect : Level → Visitor | Level.succ v _ => visitLevel v | Level.max u v _ => visitLevel v ∘ visitLevel u | Level.imax u v _ => visitLevel v ∘ visitLevel u | Level.param n _ => fun s => { s with params := s.params.push n } | _ => id end mutual partial def visitExpr (e : Expr) : Visitor := fun s => if !e.hasLevelParam then s else if s.visitedExpr.contains e then s else main e { s with visitedExpr := s.visitedExpr.insert e } partial def main : Expr → Visitor | Expr.proj _ _ s _ => visitExpr s | Expr.forallE _ d b _ => visitExpr b ∘ visitExpr d | Expr.lam _ d b _ => visitExpr b ∘ visitExpr d | Expr.letE _ t v b _ => visitExpr b ∘ visitExpr v ∘ visitExpr t | Expr.app f a _ => visitExpr a ∘ visitExpr f | Expr.mdata _ b _ => visitExpr b | Expr.const _ us _ => fun s => us.foldl (fun s u => visitLevel u s) s | Expr.sort u _ => visitLevel u | _ => id end partial def State.getUnusedLevelParam (s : CollectLevelParams.State) (pre : Name := `v) : Level := let v := mkLevelParam pre; if s.visitedLevel.contains v then let rec loop (i : Nat) := let v := mkLevelParam (pre.appendIndexAfter i); if s.visitedLevel.contains v then loop (i+1) else v loop 1 else v end CollectLevelParams def collectLevelParams (s : CollectLevelParams.State) (e : Expr) : CollectLevelParams.State := CollectLevelParams.main e s def CollectLevelParams.State.collect (s : CollectLevelParams.State) (e : Expr) : CollectLevelParams.State := collectLevelParams s e end Lean
0fd3711317330ef501b99b34485537a4918e8ebf
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/hott/types/nat/basic.hlean
565340ea98996f44dad091581ff4e2a9e7fe5a4e
[ "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
10,010
hlean
/- Copyright (c) 2014 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. (Ported from standard library) Authors: Floris van Doorn, Leonardo de Moura, Jeremy Avigad Basic operations on the natural numbers. -/ import ..num algebra.ring open prod binary eq algebra lift is_trunc namespace nat /- a variant of add, defined by recursion on the first argument -/ definition addl (x y : ℕ) : ℕ := nat.rec y (λ n r, succ r) x infix ` ⊕ `:65 := addl theorem addl_succ_right (n m : ℕ) : n ⊕ succ m = succ (n ⊕ m) := nat.rec_on n rfl (λ n₁ ih, calc succ n₁ ⊕ succ m = succ (n₁ ⊕ succ m) : rfl ... = succ (succ (n₁ ⊕ m)) : ih ... = succ (succ n₁ ⊕ m) : rfl) theorem add_eq_addl (x : ℕ) : Πy, x + y = x ⊕ y := nat.rec_on x (λ y, nat.rec_on y rfl (λ y₁ ih, calc 0 + succ y₁ = succ (0 + y₁) : rfl ... = succ (0 ⊕ y₁) : {ih} ... = 0 ⊕ (succ y₁) : rfl)) (λ x₁ ih₁ y, nat.rec_on y (calc succ x₁ + 0 = succ (x₁ + 0) : rfl ... = succ (x₁ ⊕ 0) : {ih₁ 0} ... = succ x₁ ⊕ 0 : rfl) (λ y₁ ih₂, calc succ x₁ + succ y₁ = succ (succ x₁ + y₁) : rfl ... = succ (succ x₁ ⊕ y₁) : {ih₂} ... = succ x₁ ⊕ succ y₁ : addl_succ_right)) /- successor and predecessor -/ theorem succ_ne_zero (n : ℕ) : succ n ≠ 0 := by contradiction -- add_rewrite succ_ne_zero theorem pred_zero [simp] : pred 0 = 0 := rfl theorem pred_succ [simp] (n : ℕ) : pred (succ n) = n := rfl theorem eq_zero_sum_eq_succ_pred (n : ℕ) : n = 0 ⊎ n = succ (pred n) := nat.rec_on n (sum.inl rfl) (take m IH, sum.inr (show succ m = succ (pred (succ m)), from ap succ !pred_succ⁻¹)) theorem exists_eq_succ_of_ne_zero {n : ℕ} (H : n ≠ 0) : Σk : ℕ, n = succ k := sigma.mk _ (sum_resolve_right !eq_zero_sum_eq_succ_pred H) theorem succ.inj {n m : ℕ} (H : succ n = succ m) : n = m := down (nat.no_confusion H imp.id) abbreviation eq_of_succ_eq_succ := @succ.inj theorem succ_ne_self {n : ℕ} : succ n ≠ n := nat.rec_on n (take H : 1 = 0, have ne : 1 ≠ 0, from !succ_ne_zero, absurd H ne) (take k IH H, IH (succ.inj H)) theorem discriminate {B : Type} {n : ℕ} (H1: n = 0 → B) (H2 : Πm, n = succ m → B) : B := have H : n = n → B, from nat.cases_on n H1 H2, H rfl theorem two_step_rec_on {P : ℕ → Type} (a : ℕ) (H1 : P 0) (H2 : P 1) (H3 : Π (n : ℕ) (IH1 : P n) (IH2 : P (succ n)), P (succ (succ n))) : P a := have stronger : P a × P (succ a), from nat.rec_on a (pair H1 H2) (take k IH, have IH1 : P k, from prod.pr1 IH, have IH2 : P (succ k), from prod.pr2 IH, pair IH2 (H3 k IH1 IH2)), prod.pr1 stronger theorem sub_induction {P : ℕ → ℕ → Type} (n m : ℕ) (H1 : Πm, P 0 m) (H2 : Πn, P (succ n) 0) (H3 : Πn m, P n m → P (succ n) (succ m)) : P n m := have general : Πm, P n m, from nat.rec_on n H1 (take k : ℕ, assume IH : Πm, P k m, take m : ℕ, nat.cases_on m (H2 k) (take l, (H3 k l (IH l)))), general m /- addition -/ protected definition add_zero [simp] (n : ℕ) : n + 0 = n := rfl definition add_succ [simp] (n m : ℕ) : n + succ m = succ (n + m) := rfl protected definition zero_add [simp] (n : ℕ) : 0 + n = n := begin induction n with n IH, reflexivity, exact ap succ IH end definition succ_add [simp] (n m : ℕ) : (succ n) + m = succ (n + m) := begin induction m with m IH, reflexivity, exact ap succ IH end protected definition add_comm [simp] (n m : ℕ) : n + m = m + n := begin induction n with n IH, { apply nat.zero_add}, { exact !succ_add ⬝ ap succ IH} end protected definition add_add (n l k : ℕ) : n + l + k = n + (k + l) := begin induction l with l IH, reflexivity, exact succ_add (n + l) k ⬝ ap succ IH end definition succ_add_eq_succ_add (n m : ℕ) : succ n + m = n + succ m := !succ_add protected definition add_assoc [simp] (n m k : ℕ) : (n + m) + k = n + (m + k) := begin induction k with k IH, reflexivity, exact ap succ IH end protected theorem add_left_comm : Π (n m k : ℕ), n + (m + k) = m + (n + k) := left_comm nat.add_comm nat.add_assoc protected theorem add_right_comm : Π (n m k : ℕ), n + m + k = n + k + m := right_comm nat.add_comm nat.add_assoc protected theorem add_left_cancel {n m k : ℕ} : n + m = n + k → m = k := nat.rec_on n (take H : 0 + m = 0 + k, !nat.zero_add⁻¹ ⬝ H ⬝ !nat.zero_add) (take (n : ℕ) (IH : n + m = n + k → m = k) (H : succ n + m = succ n + k), have succ (n + m) = succ (n + k), from calc succ (n + m) = succ n + m : succ_add ... = succ n + k : H ... = succ (n + k) : succ_add, have n + m = n + k, from succ.inj this, IH this) protected theorem add_right_cancel {n m k : ℕ} (H : n + m = k + m) : n = k := have H2 : m + n = m + k, from !nat.add_comm ⬝ H ⬝ !nat.add_comm, nat.add_left_cancel H2 theorem eq_zero_of_add_eq_zero_right {n m : ℕ} : n + m = 0 → n = 0 := nat.rec_on n (take (H : 0 + m = 0), rfl) (take k IH, assume H : succ k + m = 0, absurd (show succ (k + m) = 0, from calc succ (k + m) = succ k + m : succ_add ... = 0 : H) !succ_ne_zero) theorem eq_zero_of_add_eq_zero_left {n m : ℕ} (H : n + m = 0) : m = 0 := eq_zero_of_add_eq_zero_right (!nat.add_comm ⬝ H) theorem eq_zero_prod_eq_zero_of_add_eq_zero {n m : ℕ} (H : n + m = 0) : n = 0 × m = 0 := pair (eq_zero_of_add_eq_zero_right H) (eq_zero_of_add_eq_zero_left H) theorem add_one [simp] (n : ℕ) : n + 1 = succ n := rfl theorem one_add (n : ℕ) : 1 + n = succ n := !nat.zero_add ▸ !succ_add /- multiplication -/ protected theorem mul_zero [simp] (n : ℕ) : n * 0 = 0 := rfl theorem mul_succ [simp] (n m : ℕ) : n * succ m = n * m + n := rfl -- commutativity, distributivity, associativity, identity protected theorem zero_mul [simp] (n : ℕ) : 0 * n = 0 := nat.rec_on n !nat.mul_zero (take m IH, !mul_succ ⬝ !nat.add_zero ⬝ IH) theorem succ_mul [simp] (n m : ℕ) : (succ n) * m = (n * m) + m := nat.rec_on m (by rewrite nat.mul_zero) (take k IH, calc succ n * succ k = succ n * k + succ n : mul_succ ... = n * k + k + succ n : IH ... = n * k + (k + succ n) : nat.add_assoc ... = n * k + (succ n + k) : nat.add_comm ... = n * k + (n + succ k) : succ_add_eq_succ_add ... = n * k + n + succ k : nat.add_assoc ... = n * succ k + succ k : mul_succ) protected theorem mul_comm [simp] (n m : ℕ) : n * m = m * n := nat.rec_on m (!nat.mul_zero ⬝ !nat.zero_mul⁻¹) (take k IH, calc n * succ k = n * k + n : mul_succ ... = k * n + n : IH ... = (succ k) * n : succ_mul) protected theorem right_distrib (n m k : ℕ) : (n + m) * k = n * k + m * k := nat.rec_on k (calc (n + m) * 0 = 0 : nat.mul_zero ... = 0 + 0 : nat.add_zero ... = n * 0 + 0 : nat.mul_zero ... = n * 0 + m * 0 : nat.mul_zero) (take l IH, calc (n + m) * succ l = (n + m) * l + (n + m) : mul_succ ... = n * l + m * l + (n + m) : IH ... = n * l + m * l + n + m : nat.add_assoc ... = n * l + n + m * l + m : nat.add_right_comm ... = n * l + n + (m * l + m) : nat.add_assoc ... = n * succ l + (m * l + m) : mul_succ ... = n * succ l + m * succ l : mul_succ) protected theorem left_distrib (n m k : ℕ) : n * (m + k) = n * m + n * k := calc n * (m + k) = (m + k) * n : nat.mul_comm ... = m * n + k * n : nat.right_distrib ... = n * m + k * n : nat.mul_comm ... = n * m + n * k : nat.mul_comm protected theorem mul_assoc [simp] (n m k : ℕ) : (n * m) * k = n * (m * k) := nat.rec_on k (calc (n * m) * 0 = n * (m * 0) : nat.mul_zero) (take l IH, calc (n * m) * succ l = (n * m) * l + n * m : mul_succ ... = n * (m * l) + n * m : IH ... = n * (m * l + m) : nat.left_distrib ... = n * (m * succ l) : mul_succ) protected theorem mul_one [simp] (n : ℕ) : n * 1 = n := calc n * 1 = n * 0 + n : mul_succ ... = 0 + n : nat.mul_zero ... = n : nat.zero_add protected theorem one_mul [simp] (n : ℕ) : 1 * n = n := calc 1 * n = n * 1 : nat.mul_comm ... = n : nat.mul_one theorem eq_zero_sum_eq_zero_of_mul_eq_zero {n m : ℕ} : n * m = 0 → n = 0 ⊎ m = 0 := nat.cases_on n (assume H, sum.inl rfl) (take n', nat.cases_on m (assume H, sum.inr rfl) (take m', assume H : succ n' * succ m' = 0, absurd (calc 0 = succ n' * succ m' : H ... = succ n' * m' + succ n' : mul_succ ... = succ (succ n' * m' + n') : add_succ)⁻¹ !succ_ne_zero)) protected definition comm_semiring [trans_instance] : comm_semiring nat := ⦃comm_semiring, add := nat.add, add_assoc := nat.add_assoc, zero := nat.zero, zero_add := nat.zero_add, add_zero := nat.add_zero, add_comm := nat.add_comm, mul := nat.mul, mul_assoc := nat.mul_assoc, one := nat.succ nat.zero, one_mul := nat.one_mul, mul_one := nat.mul_one, left_distrib := nat.left_distrib, right_distrib := nat.right_distrib, zero_mul := nat.zero_mul, mul_zero := nat.mul_zero, mul_comm := nat.mul_comm, is_set_carrier:= _⦄ end nat section open nat definition iterate {A : Type} (op : A → A) : ℕ → A → A | 0 := λ a, a | (succ k) := λ a, op (iterate k a) notation f`^[`n`]` := iterate f n end
b9948891d1b628ceec448418fec25d9f90b04688
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/computability/NFA.lean
ab90f0f21d9384efa176d8e75929ee4eb0dca723
[ "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,887
lean
/- Copyright (c) 2020 Fox Thomson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Fox Thomson -/ import computability.DFA import data.fintype.powerset /-! # Nondeterministic Finite Automata This file contains the definition of a Nondeterministic Finite Automaton (NFA), a state machine which determines whether a string (implemented as a list over an arbitrary alphabet) is in a regular set by evaluating the string over every possible path. We show that DFA's are equivalent to NFA's however the construction from NFA to DFA uses an exponential number of states. Note that this definition allows for Automaton with infinite states, a `fintype` instance must be supplied for true NFA's. -/ open set universes u v /-- An NFA is a set of states (`σ`), a transition function from state to state labelled by the alphabet (`step`), a starting state (`start`) and a set of acceptance states (`accept`). Note the transition function sends a state to a `set` of states. These are the states that it may be sent to. -/ structure NFA (α : Type u) (σ : Type v) := (step : σ → α → set σ) (start : set σ) (accept : set σ) variables {α : Type u} {σ σ' : Type v} (M : NFA α σ) namespace NFA instance : inhabited (NFA α σ) := ⟨ NFA.mk (λ _ _, ∅) ∅ ∅ ⟩ /-- `M.step_set S a` is the union of `M.step s a` for all `s ∈ S`. -/ def step_set (S : set σ) (a : α) : set σ := ⋃ s ∈ S, M.step s a lemma mem_step_set (s : σ) (S : set σ) (a : α) : s ∈ M.step_set S a ↔ ∃ t ∈ S, s ∈ M.step t a := mem_Union₂ @[simp] lemma step_set_empty (a : α) : M.step_set ∅ a = ∅ := by simp_rw [step_set, Union_false, Union_empty] /-- `M.eval_from S x` computes all possible paths though `M` with input `x` starting at an element of `S`. -/ def eval_from (start : set σ) : list α → set σ := list.foldl M.step_set start @[simp] lemma eval_from_nil (S : set σ) : M.eval_from S [] = S := rfl @[simp] lemma eval_from_singleton (S : set σ) (a : α) : M.eval_from S [a] = M.step_set S a := rfl @[simp] lemma eval_from_append_singleton (S : set σ) (x : list α) (a : α) : M.eval_from S (x ++ [a]) = M.step_set (M.eval_from S x) a := by simp only [eval_from, list.foldl_append, list.foldl_cons, list.foldl_nil] /-- `M.eval x` computes all possible paths though `M` with input `x` starting at an element of `M.start`. -/ def eval : list α → set σ := M.eval_from M.start @[simp] lemma eval_nil : M.eval [] = M.start := rfl @[simp] lemma eval_singleton (a : α) : M.eval [a] = M.step_set M.start a := rfl @[simp] lemma eval_append_singleton (x : list α) (a : α) : M.eval (x ++ [a]) = M.step_set (M.eval x) a := eval_from_append_singleton _ _ _ _ /-- `M.accepts` is the language of `x` such that there is an accept state in `M.eval x`. -/ def accepts : language α := λ x, ∃ S ∈ M.accept, S ∈ M.eval x /-- `M.to_DFA` is an `DFA` constructed from a `NFA` `M` using the subset construction. The states is the type of `set`s of `M.state` and the step function is `M.step_set`. -/ def to_DFA : DFA α (set σ) := { step := M.step_set, start := M.start, accept := {S | ∃ s ∈ S, s ∈ M.accept} } @[simp] lemma to_DFA_correct : M.to_DFA.accepts = M.accepts := begin ext x, rw [accepts, DFA.accepts, eval, DFA.eval], change list.foldl _ _ _ ∈ {S | _} ↔ _, split; { exact λ ⟨w, h2, h3⟩, ⟨w, h3, h2⟩ }, end lemma pumping_lemma [fintype σ] {x : list α} (hx : x ∈ M.accepts) (hlen : fintype.card (set σ) ≤ list.length x) : ∃ a b c, x = a ++ b ++ c ∧ a.length + b.length ≤ fintype.card (set σ) ∧ b ≠ [] ∧ {a} * language.star {b} * {c} ≤ M.accepts := begin rw ←to_DFA_correct at hx ⊢, exact M.to_DFA.pumping_lemma hx hlen end end NFA namespace DFA /-- `M.to_NFA` is an `NFA` constructed from a `DFA` `M` by using the same start and accept states and a transition function which sends `s` with input `a` to the singleton `M.step s a`. -/ def to_NFA (M : DFA α σ') : NFA α σ' := { step := λ s a, {M.step s a}, start := {M.start}, accept := M.accept } @[simp] lemma to_NFA_eval_from_match (M : DFA α σ) (start : σ) (s : list α) : M.to_NFA.eval_from {start} s = {M.eval_from start s} := begin change list.foldl M.to_NFA.step_set {start} s = {list.foldl M.step start s}, induction s with a s ih generalizing start, { tauto }, { rw [list.foldl, list.foldl, show M.to_NFA.step_set {start} a = {M.step start a}, by simpa [NFA.step_set]], tauto } end @[simp] lemma to_NFA_correct (M : DFA α σ) : M.to_NFA.accepts = M.accepts := begin ext x, change (∃ S H, S ∈ M.to_NFA.eval_from {M.start} x) ↔ _, rw to_NFA_eval_from_match, split, { rintro ⟨ S, hS₁, hS₂ ⟩, rwa set.mem_singleton_iff.mp hS₂ at hS₁ }, { exact λ h, ⟨M.eval x, h, rfl⟩ } end end DFA
ef94683f712672e52bebb87a1e5e8d65d2a29b4f
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/category_theory/limits/shapes/kernel_pair.lean
45483383de7eeec914e6df659e0a8380d67bb49f
[ "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
9,321
lean
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import category_theory.limits.shapes.equalizers import category_theory.limits.shapes.comm_sq import category_theory.limits.shapes.regular_mono /-! # Kernel pairs This file defines what it means for a parallel pair of morphisms `a b : R ⟶ X` to be the kernel pair for a morphism `f`. Some properties of kernel pairs are given, namely allowing one to transfer between the kernel pair of `f₁ ≫ f₂` to the kernel pair of `f₁`. It is also proved that if `f` is a coequalizer of some pair, and `a`,`b` is a kernel pair for `f` then it is a coequalizer of `a`,`b`. ## Implementation The definition is essentially just a wrapper for `is_limit (pullback_cone.mk _ _ _)`, but the constructions given here are useful, yet awkward to present in that language, so a basic API is developed here. ## TODO - Internal equivalence relations (or congruences) and the fact that every kernel pair induces one, and the converse in an effective regular category (WIP by b-mehta). -/ universes v u u₂ namespace category_theory open category_theory category_theory.category category_theory.limits variables {C : Type u} [category.{v} C] variables {R X Y Z : C} (f : X ⟶ Y) (a b : R ⟶ X) /-- `is_kernel_pair f a b` expresses that `(a, b)` is a kernel pair for `f`, i.e. `a ≫ f = b ≫ f` and the square R → X ↓ ↓ X → Y is a pullback square. This is just an abbreviation for `is_pullback a b f f`. -/ abbreviation is_kernel_pair := is_pullback a b f f namespace is_kernel_pair /-- The data expressing that `(a, b)` is a kernel pair is subsingleton. -/ instance : subsingleton (is_kernel_pair f a b) := ⟨λ P Q, by { cases P, cases Q, congr, }⟩ /-- If `f` is a monomorphism, then `(𝟙 _, 𝟙 _)` is a kernel pair for `f`. -/ lemma id_of_mono [mono f] : is_kernel_pair f (𝟙 _) (𝟙 _) := ⟨⟨rfl⟩, ⟨pullback_cone.is_limit_mk_id_id _⟩⟩ instance [mono f] : inhabited (is_kernel_pair f (𝟙 _) (𝟙 _)) := ⟨id_of_mono f⟩ variables {f a b} /-- Given a pair of morphisms `p`, `q` to `X` which factor through `f`, they factor through any kernel pair of `f`. -/ noncomputable def lift' {S : C} (k : is_kernel_pair f a b) (p q : S ⟶ X) (w : p ≫ f = q ≫ f) : { t : S ⟶ R // t ≫ a = p ∧ t ≫ b = q } := pullback_cone.is_limit.lift' k.is_limit _ _ w /-- If `(a,b)` is a kernel pair for `f₁ ≫ f₂` and `a ≫ f₁ = b ≫ f₁`, then `(a,b)` is a kernel pair for just `f₁`. That is, to show that `(a,b)` is a kernel pair for `f₁` it suffices to only show the square commutes, rather than to additionally show it's a pullback. -/ lemma cancel_right {f₁ : X ⟶ Y} {f₂ : Y ⟶ Z} (comm : a ≫ f₁ = b ≫ f₁) (big_k : is_kernel_pair (f₁ ≫ f₂) a b) : is_kernel_pair f₁ a b := { w := comm, is_limit' := ⟨pullback_cone.is_limit_aux' _ $ λ s, begin let s' : pullback_cone (f₁ ≫ f₂) (f₁ ≫ f₂) := pullback_cone.mk s.fst s.snd (s.condition_assoc _), refine ⟨big_k.is_limit.lift s', big_k.is_limit.fac _ walking_cospan.left, big_k.is_limit.fac _ walking_cospan.right, λ m m₁ m₂, _⟩, apply big_k.is_limit.hom_ext, refine ((pullback_cone.mk a b _) : pullback_cone (f₁ ≫ f₂) _).equalizer_ext _ _, apply m₁.trans (big_k.is_limit.fac s' walking_cospan.left).symm, apply m₂.trans (big_k.is_limit.fac s' walking_cospan.right).symm, end⟩ } /-- If `(a,b)` is a kernel pair for `f₁ ≫ f₂` and `f₂` is mono, then `(a,b)` is a kernel pair for just `f₁`. The converse of `comp_of_mono`. -/ lemma cancel_right_of_mono {f₁ : X ⟶ Y} {f₂ : Y ⟶ Z} [mono f₂] (big_k : is_kernel_pair (f₁ ≫ f₂) a b) : is_kernel_pair f₁ a b := cancel_right (begin rw [← cancel_mono f₂, assoc, assoc, big_k.w] end) big_k /-- If `(a,b)` is a kernel pair for `f₁` and `f₂` is mono, then `(a,b)` is a kernel pair for `f₁ ≫ f₂`. The converse of `cancel_right_of_mono`. -/ lemma comp_of_mono {f₁ : X ⟶ Y} {f₂ : Y ⟶ Z} [mono f₂] (small_k : is_kernel_pair f₁ a b) : is_kernel_pair (f₁ ≫ f₂) a b := { w := by rw [small_k.w_assoc], is_limit' := ⟨pullback_cone.is_limit_aux' _ $ λ s, begin refine ⟨_, _, _, _⟩, apply (pullback_cone.is_limit.lift' small_k.is_limit s.fst s.snd _).1, rw [← cancel_mono f₂, assoc, s.condition, assoc], apply (pullback_cone.is_limit.lift' small_k.is_limit s.fst s.snd _).2.1, apply (pullback_cone.is_limit.lift' small_k.is_limit s.fst s.snd _).2.2, intros m m₁ m₂, apply small_k.is_limit.hom_ext, refine ((pullback_cone.mk a b _) : pullback_cone f₁ _).equalizer_ext _ _, { exact m₁.trans (pullback_cone.is_limit.lift' small_k.is_limit s.fst s.snd _).2.1.symm }, { exact m₂.trans (pullback_cone.is_limit.lift' small_k.is_limit s.fst s.snd _).2.2.symm }, end⟩ } /-- If `(a,b)` is the kernel pair of `f`, and `f` is a coequalizer morphism for some parallel pair, then `f` is a coequalizer morphism of `a` and `b`. -/ def to_coequalizer (k : is_kernel_pair f a b) [r : regular_epi f] : is_colimit (cofork.of_π f k.w) := begin let t := k.is_limit.lift (pullback_cone.mk _ _ r.w), have ht : t ≫ a = r.left := k.is_limit.fac _ walking_cospan.left, have kt : t ≫ b = r.right := k.is_limit.fac _ walking_cospan.right, apply cofork.is_colimit.mk _ _ _ _, { intro s, apply (cofork.is_colimit.desc' r.is_colimit s.π _).1, rw [← ht, assoc, s.condition, reassoc_of kt] }, { intro s, apply (cofork.is_colimit.desc' r.is_colimit s.π _).2 }, { intros s m w, apply r.is_colimit.hom_ext, rintro ⟨⟩, change (r.left ≫ f) ≫ m = (r.left ≫ f) ≫ _, rw [assoc, assoc], congr' 1, erw (cofork.is_colimit.desc' r.is_colimit s.π _).2, apply w, erw (cofork.is_colimit.desc' r.is_colimit s.π _).2, apply w } end /-- If `a₁ a₂ : A ⟶ Y` is a kernel pair for `g : Y ⟶ Z`, then `a₁ ×[Z] X` and `a₂ ×[Z] X` (`A ×[Z] X ⟶ Y ×[Z] X`) is a kernel pair for `Y ×[Z] X ⟶ X`. -/ protected lemma pullback {X Y Z A : C} {g : Y ⟶ Z} {a₁ a₂ : A ⟶ Y} (h : is_kernel_pair g a₁ a₂) (f : X ⟶ Z) [has_pullback f g] [has_pullback f (a₁ ≫ g)] : is_kernel_pair (pullback.fst : pullback f g ⟶ X) (pullback.map f _ f _ (𝟙 X) a₁ (𝟙 Z) (by simp) $ category.comp_id _) (pullback.map _ _ _ _ (𝟙 X) a₂ (𝟙 Z) (by simp) $ (category.comp_id _).trans h.1.1) := begin refine ⟨⟨_⟩, ⟨_⟩⟩, { rw [pullback.lift_fst, pullback.lift_fst] }, { fapply pullback_cone.is_limit_aux', intro s, refine ⟨pullback.lift (s.fst ≫ pullback.fst) (h.lift' (s.fst ≫ pullback.snd) (s.snd ≫ pullback.snd) _).1 _, _, _, _⟩, { simp_rw [category.assoc, ← pullback.condition, ← category.assoc, s.condition] }, { rw [← category.assoc, (h.lift' _ _ _).2.1, category.assoc, category.assoc, pullback.condition] }, { rw limits.pullback_cone.mk_fst, ext; simp only [category.assoc, pullback.lift_fst, pullback.lift_snd, pullback.lift_snd_assoc, category.comp_id, (h.lift' _ _ _).2.1] }, { rw limits.pullback_cone.mk_snd, ext; simp only [category.assoc, pullback.lift_fst, pullback.lift_snd, pullback.lift_snd_assoc, category.comp_id, (h.lift' _ _ _).2.2, s.condition] }, { intros m h₁ h₂, ext, { rw pullback.lift_fst, conv_rhs { rw [← h₁, category.assoc, pullback_cone.mk_fst] }, congr' 1, refine ((pullback.lift_fst _ _ _).trans $ category.comp_id _).symm }, { rw pullback.lift_snd, apply pullback_cone.is_limit.hom_ext h.is_limit; dsimp only [is_pullback.cone, comm_sq.cone]; simp only [pullback_cone.mk_fst, pullback_cone.mk_snd, category.assoc, (h.lift' _ _ _).2.1, (h.lift' _ _ _).2.2], { conv_rhs { rw [← h₁, category.assoc, pullback_cone.mk_fst, pullback.lift_snd] } }, { conv_rhs { rw [← h₂, category.assoc, pullback_cone.mk_snd, pullback.lift_snd] } } } } } end lemma mono_of_is_iso_fst (h : is_kernel_pair f a b) [is_iso a] : mono f := begin obtain ⟨l, h₁, h₂⟩ := limits.pullback_cone.is_limit.lift' h.is_limit (𝟙 _) (𝟙 _) (by simp [h.w]), rw [is_pullback.cone_fst, ← is_iso.eq_comp_inv, category.id_comp] at h₁, rw [h₁, is_iso.inv_comp_eq, category.comp_id] at h₂, constructor, intros Z g₁ g₂ e, obtain ⟨l', rfl, rfl⟩ := limits.pullback_cone.is_limit.lift' h.is_limit _ _ e, rw [is_pullback.cone_fst, h₂], end lemma is_iso_of_mono (h : is_kernel_pair f a b) [mono f] : is_iso a := begin rw ← show _ = a, from (category.comp_id _).symm.trans ((is_kernel_pair.id_of_mono f) .is_limit.cone_point_unique_up_to_iso_inv_comp h.is_limit walking_cospan.left), apply_instance, end lemma of_is_iso_of_mono [is_iso a] [mono f] : is_kernel_pair f a a := begin delta is_kernel_pair, convert_to is_pullback a (a ≫ 𝟙 X) (𝟙 X ≫ f) f, { rw category.comp_id }, { rw category.id_comp }, exact (is_pullback.of_horiz_is_iso ⟨rfl⟩).paste_vert (is_kernel_pair.id_of_mono f) end end is_kernel_pair end category_theory
21cb3f52e3f5c75484eb92786cf48514e440ce91
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/tactic/elide.lean
ff61f3a38ded8c9c4f93b28c0106e061c0274a03
[]
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
885
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Simon Hudon -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.tactic.core import Mathlib.PostPort namespace Mathlib namespace tactic namespace elide end elide namespace interactive /-- The `elide n (at ...)` tactic hides all subterms of the target goal or hypotheses beyond depth `n` by replacing them with `hidden`, which is a variant on the identity function. (Tactics should still mostly be able to see through the abbreviation, but if you want to unhide the term you can use `unelide`.) -/ /-- The `unelide (at ...)` tactic removes all `hidden` subterms in the target types (usually added by `elide`). -/ /-- The `elide n (at ...)` tactic hides all subterms of the target goal or hypotheses
6ff1ca49c01cdd9850350d031008c4d05f8809e5
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/real/pi/wallis.lean
8869286478aa2e0f771f10584e9bf48005653901
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
4,838
lean
/- Copyright (c) 2021 Hanting Zhang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Hanting Zhang -/ import analysis.special_functions.integrals /-! # The Wallis formula for Pi > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file establishes the Wallis product for `π` (`real.tendsto_prod_pi_div_two`). Our proof is largely about analyzing the behaviour of the sequence `∫ x in 0..π, sin x ^ n` as `n → ∞`. See: https://en.wikipedia.org/wiki/Wallis_product The proof can be broken down into two pieces. The first step (carried out in `analysis.special_functions.integrals`) is to use repeated integration by parts to obtain an explicit formula for this integral, which is rational if `n` is odd and a rational multiple of `π` if `n` is even. The second step, carried out here, is to estimate the ratio `∫ (x : ℝ) in 0..π, sin x ^ (2 * k + 1) / ∫ (x : ℝ) in 0..π, sin x ^ (2 * k)` and prove that it converges to one using the squeeze theorem. The final product for `π` is obtained after some algebraic manipulation. ## Main statements * `real.wallis.W`: the product of the first `k` terms in Wallis' formula for `π`. * `real.wallis.W_eq_integral_sin_pow_div_integral_sin_pow`: express `W n` as a ratio of integrals. * `real.wallis.W_le` and `real.wallis.le_W`: upper and lower bounds for `W n`. * `real.tendsto_prod_pi_div_two`: the Wallis product formula. -/ open_locale real topology big_operators nat open filter finset interval_integral namespace real namespace wallis /-- The product of the first `k` terms in Wallis' formula for `π`. -/ noncomputable def W (k : ℕ) : ℝ := ∏ i in range k, (2 * i + 2) / (2 * i + 1) * ((2 * i + 2) / (2 * i + 3)) lemma W_succ (k : ℕ) : W (k + 1) = W k * ((2 * k + 2) / (2 * k + 1) * ((2 * k + 2) / (2 * k + 3))) := prod_range_succ _ _ lemma W_pos (k : ℕ) : 0 < W k := begin induction k with k hk, { unfold W, simp }, { rw W_succ, refine mul_pos hk (mul_pos (div_pos _ _) (div_pos _ _)); positivity } end lemma W_eq_factorial_ratio (n : ℕ) : W n = (2 ^ (4 * n) * n! ^ 4) / ((2 * n)!^ 2 * (2 * n + 1)) := begin induction n with n IH, { simp only [W, prod_range_zero, nat.factorial_zero, mul_zero, pow_zero, algebra_map.coe_one, one_pow, mul_one, algebra_map.coe_zero, zero_add, div_self, ne.def, one_ne_zero, not_false_iff] }, { unfold W at ⊢ IH, rw [prod_range_succ, IH, _root_.div_mul_div_comm, _root_.div_mul_div_comm], refine (div_eq_div_iff _ _).mpr _, any_goals { exact ne_of_gt (by positivity) }, simp_rw [nat.mul_succ, nat.factorial_succ, pow_succ], push_cast, ring_nf } end lemma W_eq_integral_sin_pow_div_integral_sin_pow (k : ℕ) : (π/2)⁻¹ * W k = (∫ (x : ℝ) in 0..π, sin x ^ (2 * k + 1)) / ∫ (x : ℝ) in 0..π, sin x ^ (2 * k) := begin rw [integral_sin_pow_even, integral_sin_pow_odd, mul_div_mul_comm, ←prod_div_distrib, inv_div], simp_rw [div_div_div_comm, div_div_eq_mul_div, mul_div_assoc], refl, end lemma W_le (k : ℕ) : W k ≤ π / 2 := begin rw [←div_le_one pi_div_two_pos, div_eq_inv_mul], rw [W_eq_integral_sin_pow_div_integral_sin_pow, div_le_one (integral_sin_pow_pos _)], apply integral_sin_pow_succ_le, end lemma le_W (k : ℕ) : ((2:ℝ) * k + 1) / (2 * k + 2) * (π / 2) ≤ W k := begin rw [←le_div_iff pi_div_two_pos, div_eq_inv_mul (W k) _], rw [W_eq_integral_sin_pow_div_integral_sin_pow, le_div_iff (integral_sin_pow_pos _)], convert integral_sin_pow_succ_le (2 * k + 1), rw integral_sin_pow (2 * k), simp only [sin_zero, zero_pow', ne.def, nat.succ_ne_zero, not_false_iff, zero_mul, sin_pi, tsub_zero, nat.cast_mul, nat.cast_bit0, algebra_map.coe_one, zero_div, zero_add], end lemma tendsto_W_nhds_pi_div_two : tendsto W at_top (𝓝 $ π / 2) := begin refine tendsto_of_tendsto_of_tendsto_of_le_of_le _ tendsto_const_nhds le_W W_le, have : 𝓝 (π / 2) = 𝓝 ((1 - 0) * (π / 2)), by rw [sub_zero, one_mul], rw this, refine tendsto.mul _ tendsto_const_nhds, have h : ∀ (n:ℕ), ((2:ℝ) * n + 1) / (2 * n + 2) = 1 - 1 / (2 * n + 2), { intro n, rw [sub_div' _ _ _ (ne_of_gt (add_pos_of_nonneg_of_pos (mul_nonneg ((two_pos : 0 < (2:ℝ)).le) (nat.cast_nonneg _)) two_pos)), one_mul], congr' 1, ring }, simp_rw h, refine (tendsto_const_nhds.div_at_top _).const_sub _, refine tendsto.at_top_add _ tendsto_const_nhds, exact tendsto_coe_nat_at_top_at_top.const_mul_at_top two_pos end end wallis end real /-- Wallis' product formula for `π / 2`. -/ theorem real.tendsto_prod_pi_div_two : tendsto (λ k, ∏ i in range k, (((2:ℝ) * i + 2) / (2 * i + 1)) * ((2 * i + 2) / (2 * i + 3))) at_top (𝓝 (π/2)) := real.wallis.tendsto_W_nhds_pi_div_two
f543fdfa879402ebef926a6e595c3fc04086b456
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/topology/sheaves/sheaf.lean
e88bb67263ff130b4166a49abbe45a5061bfeaf4
[ "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
4,298
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import topology.sheaves.sheaf_condition.equalizer_products import category_theory.full_subcategory /-! # Sheaves We define sheaves on a topological space, with values in an arbitrary category with products. The sheaf condition for a `F : presheaf C X` requires that the morphism `F.obj U ⟶ ∏ F.obj (U i)` (where `U` is some open set which is the union of the `U i`) is the equalizer of the two morphisms `∏ F.obj (U i) ⟶ ∏ F.obj (U i ⊓ U j)`. We provide the instance `category (sheaf C X)` as the full subcategory of presheaves, and the fully faithful functor `sheaf.forget : sheaf C X ⥤ presheaf C X`. ## Equivalent conditions While the "official" definition is in terms of an equalizer diagram, in `src/topology/sheaves/sheaf_condition/pairwise_intersections.lean` and in `src/topology/sheaves/sheaf_condition/open_le_cover.lean` we provide two equivalent conditions (and prove they are equivalent). The first is that `F.obj U` is the limit point of the diagram consisting of all the `F.obj (U i)` and `F.obj (U i ⊓ U j)`. (That is, we explode the equalizer of two products out into its component pieces.) The second is that `F.obj U` is the limit point of the diagram constisting of all the `F.obj V`, for those `V : opens X` such that `V ≤ U i` for some `i`. (This condition is particularly easy to state, and perhaps should become the "official" definition.) -/ universes v u noncomputable theory open category_theory open category_theory.limits open topological_space open opposite open topological_space.opens namespace Top variables {C : Type u} [category.{v} C] [has_products C] variables {X : Top.{v}} (F : presheaf C X) {ι : Type v} (U : ι → opens X) namespace presheaf open sheaf_condition_equalizer_products /-- The sheaf condition for a `F : presheaf C X` requires that the morphism `F.obj U ⟶ ∏ F.obj (U i)` (where `U` is some open set which is the union of the `U i`) is the equalizer of the two morphisms `∏ F.obj (U i) ⟶ ∏ F.obj (U i) ⊓ (U j)`. -/ -- One might prefer to work with sets of opens, rather than indexed families, -- which would reduce the universe level here to `max u v`. -- However as it's a subsingleton the universe level doesn't matter much. @[derive subsingleton] def sheaf_condition (F : presheaf C X) : Type (max u (v+1)) := Π ⦃ι : Type v⦄ (U : ι → opens X), is_limit (sheaf_condition_equalizer_products.fork F U) /-- The presheaf valued in `punit` over any topological space is a sheaf. -/ def sheaf_condition_punit (F : presheaf (category_theory.discrete punit) X) : sheaf_condition F := λ ι U, punit_cone_is_limit -- Let's construct a trivial example, to keep the inhabited linter happy. instance sheaf_condition_inhabited (F : presheaf (category_theory.discrete punit) X) : inhabited (sheaf_condition F) := ⟨sheaf_condition_punit F⟩ /-- Transfer the sheaf condition across an isomorphism of presheaves. -/ def sheaf_condition_equiv_of_iso {F G : presheaf C X} (α : F ≅ G) : sheaf_condition F ≃ sheaf_condition G := equiv_of_subsingleton_of_subsingleton (λ c ι U, is_limit.of_iso_limit ((is_limit.postcompose_inv_equiv _ _).symm (c U)) (sheaf_condition_equalizer_products.fork.iso_of_iso U α.symm).symm) (λ c ι U, is_limit.of_iso_limit ((is_limit.postcompose_inv_equiv _ _).symm (c U)) (sheaf_condition_equalizer_products.fork.iso_of_iso U α).symm) end presheaf variables (C X) /-- A `sheaf C X` is a presheaf of objects from `C` over a (bundled) topological space `X`, satisfying the sheaf condition. -/ structure sheaf := (presheaf : presheaf C X) (sheaf_condition : presheaf.sheaf_condition) instance : category (sheaf C X) := induced_category.category sheaf.presheaf -- Let's construct a trivial example, to keep the inhabited linter happy. instance sheaf_inhabited : inhabited (sheaf (category_theory.discrete punit) X) := ⟨{ presheaf := functor.star _, sheaf_condition := default _ }⟩ namespace sheaf /-- The forgetful functor from sheaves to presheaves. -/ @[derive [full, faithful]] def forget : Top.sheaf C X ⥤ Top.presheaf C X := induced_functor sheaf.presheaf end sheaf end Top
85b7bdb367bae627fd9570253e6555e75597f9b2
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/control/lawful_fix_auto.lean
0aadba4aa8fc16fe12f87188c9b6bfd703379082
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
8,242
lean
/- Copyright (c) 2020 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Simon Hudon -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.tactic.apply import Mathlib.control.fix import Mathlib.order.omega_complete_partial_order import Mathlib.PostPort universes u_3 l u_1 u_2 namespace Mathlib /-! # Lawful fixed point operators This module defines the laws required of a `has_fix` instance, using the theory of omega complete partial orders (ωCPO). Proofs of the lawfulness of all `has_fix` instances in `control.fix` are provided. ## Main definition * class `lawful_fix` -/ /-- Intuitively, a fixed point operator `fix` is lawful if it satisfies `fix f = f (fix f)` for all `f`, but this is inconsistent / uninteresting in most cases due to the existence of "exotic" functions `f`, such as the function that is defined iff its argument is not, familiar from the halting problem. Instead, this requirement is limited to only functions that are `continuous` in the sense of `ω`-complete partial orders, which excludes the example because it is not monotone (making the input argument less defined can make `f` more defined). -/ class lawful_fix (α : Type u_3) [omega_complete_partial_order α] extends has_fix α where fix_eq : ∀ {f : α →ₘ α}, omega_complete_partial_order.continuous f → has_fix.fix ⇑f = coe_fn f (has_fix.fix ⇑f) theorem lawful_fix.fix_eq' {α : Type u_1} [omega_complete_partial_order α] [lawful_fix α] {f : α → α} (hf : omega_complete_partial_order.continuous' f) : has_fix.fix f = f (has_fix.fix f) := lawful_fix.fix_eq (omega_complete_partial_order.continuous.to_bundled f hf) namespace roption namespace fix theorem approx_mono' {α : Type u_1} {β : α → Type u_2} (f : ((a : α) → roption (β a)) →ₘ (a : α) → roption (β a)) {i : ℕ} : approx (⇑f) i ≤ approx (⇑f) (Nat.succ i) := sorry theorem approx_mono {α : Type u_1} {β : α → Type u_2} (f : ((a : α) → roption (β a)) →ₘ (a : α) → roption (β a)) {i : ℕ} {j : ℕ} (hij : i ≤ j) : approx (⇑f) i ≤ approx (⇑f) j := sorry theorem mem_iff {α : Type u_1} {β : α → Type u_2} (f : ((a : α) → roption (β a)) →ₘ (a : α) → roption (β a)) (a : α) (b : β a) : b ∈ roption.fix (⇑f) a ↔ ∃ (i : ℕ), b ∈ approx (⇑f) i a := sorry theorem approx_le_fix {α : Type u_1} {β : α → Type u_2} (f : ((a : α) → roption (β a)) →ₘ (a : α) → roption (β a)) (i : ℕ) : approx (⇑f) i ≤ roption.fix ⇑f := fun (a : α) (b : β a) (hh : b ∈ approx (⇑f) i a) => eq.mpr (id (Eq._oldrec (Eq.refl (b ∈ roption.fix (⇑f) a)) (propext (mem_iff f a b)))) (Exists.intro i hh) theorem exists_fix_le_approx {α : Type u_1} {β : α → Type u_2} (f : ((a : α) → roption (β a)) →ₘ (a : α) → roption (β a)) (x : α) : ∃ (i : ℕ), roption.fix (⇑f) x ≤ approx (⇑f) i x := sorry /-- The series of approximations of `fix f` (see `approx`) as a `chain` -/ def approx_chain {α : Type u_1} {β : α → Type u_2} (f : ((a : α) → roption (β a)) →ₘ (a : α) → roption (β a)) : omega_complete_partial_order.chain ((a : α) → roption (β a)) := preorder_hom.mk (approx ⇑f) sorry theorem le_f_of_mem_approx {α : Type u_1} {β : α → Type u_2} (f : ((a : α) → roption (β a)) →ₘ (a : α) → roption (β a)) {x : (a : α) → roption (β a)} (hx : x ∈ approx_chain f) : x ≤ coe_fn f x := eq.mpr (id (propext exists_imp_distrib)) (fun (i : ℕ) (hx : x = coe_fn (approx_chain f) i) => Eq._oldrec (approx_mono' f) (Eq.symm hx)) hx theorem approx_mem_approx_chain {α : Type u_1} {β : α → Type u_2} (f : ((a : α) → roption (β a)) →ₘ (a : α) → roption (β a)) {i : ℕ} : approx (⇑f) i ∈ approx_chain f := stream.mem_of_nth_eq rfl end fix theorem fix_eq_ωSup {α : Type u_1} {β : α → Type u_2} (f : ((a : α) → roption (β a)) →ₘ (a : α) → roption (β a)) : roption.fix ⇑f = omega_complete_partial_order.ωSup (fix.approx_chain f) := sorry theorem fix_le {α : Type u_1} {β : α → Type u_2} (f : ((a : α) → roption (β a)) →ₘ (a : α) → roption (β a)) {X : (a : α) → roption (β a)} (hX : coe_fn f X ≤ X) : roption.fix ⇑f ≤ X := sorry theorem fix_eq {α : Type u_1} {β : α → Type u_2} {f : ((a : α) → roption (β a)) →ₘ (a : α) → roption (β a)} (hc : omega_complete_partial_order.continuous f) : roption.fix ⇑f = coe_fn f (roption.fix ⇑f) := sorry end roption namespace roption /-- `to_unit` as a monotone function -/ def to_unit_mono {α : Type u_1} (f : roption α →ₘ roption α) : (Unit → roption α) →ₘ Unit → roption α := preorder_hom.mk (fun (x : Unit → roption α) (u : Unit) => coe_fn f (x u)) sorry theorem to_unit_cont {α : Type u_1} (f : roption α →ₘ roption α) (hc : omega_complete_partial_order.continuous f) : omega_complete_partial_order.continuous (to_unit_mono f) := sorry protected instance lawful_fix {α : Type u_1} : lawful_fix (roption α) := lawful_fix.mk sorry end roption namespace pi protected instance lawful_fix {α : Type u_1} {β : Type u_2} : lawful_fix (α → roption β) := lawful_fix.mk sorry /-- `sigma.curry` as a monotone function. -/ def monotone_curry (α : Type u_1) (β : α → Type u_2) (γ : (a : α) → β a → Type u_3) [(x : α) → (y : β x) → preorder (γ x y)] : ((x : sigma fun (a : α) => β a) → γ (sigma.fst x) (sigma.snd x)) →ₘ (a : α) → (b : β a) → γ a b := preorder_hom.mk sigma.curry sorry /-- `sigma.uncurry` as a monotone function. -/ @[simp] theorem monotone_uncurry_to_fun (α : Type u_1) (β : α → Type u_2) (γ : (a : α) → β a → Type u_3) [(x : α) → (y : β x) → preorder (γ x y)] (f : (x : α) → (y : β x) → (fun (a : α) (b : β a) => γ a b) x y) (x : sigma fun (a : α) => β a) : coe_fn (monotone_uncurry α β γ) f x = sigma.uncurry f x := Eq.refl (coe_fn (monotone_uncurry α β γ) f x) theorem continuous_curry (α : Type u_1) (β : α → Type u_2) (γ : (a : α) → β a → Type u_3) [(x : α) → (y : β x) → omega_complete_partial_order (γ x y)] : omega_complete_partial_order.continuous (monotone_curry α β γ) := sorry theorem continuous_uncurry (α : Type u_1) (β : α → Type u_2) (γ : (a : α) → β a → Type u_3) [(x : α) → (y : β x) → omega_complete_partial_order (γ x y)] : omega_complete_partial_order.continuous (monotone_uncurry α β γ) := sorry protected instance has_fix {α : Type u_1} {β : α → Type u_2} {γ : (a : α) → β a → Type u_3} [has_fix ((x : sigma β) → γ (sigma.fst x) (sigma.snd x))] : has_fix ((x : α) → (y : β x) → γ x y) := has_fix.mk fun (f : ((x : α) → (y : β x) → γ x y) → (x : α) → (y : β x) → γ x y) => sigma.curry (has_fix.fix (sigma.uncurry ∘ f ∘ sigma.curry)) theorem uncurry_curry_continuous {α : Type u_1} {β : α → Type u_2} {γ : (a : α) → β a → Type u_3} [(x : α) → (y : β x) → omega_complete_partial_order (γ x y)] {f : ((x : α) → (y : β x) → γ x y) →ₘ (x : α) → (y : β x) → γ x y} (hc : omega_complete_partial_order.continuous f) : omega_complete_partial_order.continuous (preorder_hom.comp (monotone_uncurry α β γ) (preorder_hom.comp f (monotone_curry α β γ))) := omega_complete_partial_order.continuous_comp (preorder_hom.comp f (monotone_curry α β γ)) (monotone_uncurry α β γ) (omega_complete_partial_order.continuous_comp (monotone_curry α β γ) f (continuous_curry α β γ) hc) (continuous_uncurry α β γ) protected instance pi.lawful_fix' {α : Type u_1} {β : α → Type u_2} {γ : (a : α) → β a → Type u_3} [(x : α) → (y : β x) → omega_complete_partial_order (γ x y)] [lawful_fix ((x : sigma β) → γ (sigma.fst x) (sigma.snd x))] : lawful_fix ((x : α) → (y : β x) → γ x y) := lawful_fix.mk sorry end Mathlib
bc2620bc859ebc511cc8f36b61b5baa9cacd0244
dc15192b741b5d1c22cea8d65d6eb38bce3d838d
/src/matroid.lean
46d26d1229578e84f6d2099c6e81434eac9e86cf
[]
no_license
VArtem/lean-matroids
86910241ac8d1a5ec7b35adb77c1cc9969480fb9
a8969b1cb2456820ccbdce65e2e168c48c30d9bf
refs/heads/main
1,678,556,999,525
1,614,537,008,000
1,614,537,008,000
338,915,729
0
1
null
null
null
null
UTF-8
Lean
false
false
1,884
lean
import data.fintype.basic import tactic import finset -- TODO: -- matroid constructions: subtype, contraction, direct sum, map -- dual matroid, matroid isomorphism -- base theorem, base construction -- circuit theorem, circuit construction -- rank theorem, rank construction -- closure theorem, closure construction -- examples structure matroid (α : Type*) [fintype α] [decidable_eq α] := (ind : set (finset α)) [ind_dec : decidable_pred ind] (ind_empty : ind ∅) (ind_subset : ∀ (A B), A ⊆ B → ind B → ind A) (ind_exchange : ∀ (A B : finset α), ind A → ind B → A.card < B.card → (∃ (c ∈ B), (c ∉ A) ∧ ind (insert c A))) variables {α : Type*} [fintype α] [decidable_eq α] {m : matroid α} {A B X : finset α} open finset namespace matroid @[simp] lemma ind_empty_def : m.ind ∅ := m.ind_empty @[simp] lemma ind_subset_def : A ⊆ B → m.ind B → m.ind A := m.ind_subset _ _ @[simp] lemma dep_superset {A B} : A ⊆ B → ¬m.ind A → ¬m.ind B := λ h hA hB, hA (m.ind_subset _ _ h hB) def base (m : matroid α) (A : finset α) := m.ind A ∧ ∀ x ∉ A, ¬m.ind (insert x A) def base_of (m : matroid α) (A B : finset α) := B ⊆ A ∧ m.ind B ∧ ∀ (x ∉ B), (x ∈ A) → ¬m.ind (insert x B) @[simp] lemma base_ind : m.base A → m.ind A := λ h, h.1 @[simp] lemma base_of_ind : m.base_of X A → m.ind A := λ h, h.2.1 @[simp] lemma base_of_subset : m.base_of X A → A ⊆ X := λ h, h.1 @[simp] lemma base_of_univ_iff_base {A : finset α} : m.base_of univ A ↔ m.base A := ⟨λ ⟨_, h_ind, h_ins⟩, ⟨h_ind, λ x hx, h_ins x hx (mem_univ x)⟩, λ ⟨h_ind, h_ins⟩, ⟨subset_univ A, h_ind, λ x hx _, h_ins x hx⟩⟩ def circuit (m : matroid α) (A : finset α) := ¬ m.ind A ∧ ∀ x ∈ A, m.ind (A.erase x) @[simp] lemma circuit_dep : m.circuit A → ¬ m.ind A := λ x, x.1 end matroid
febeb374b7c2c55abb7c8d53be44ad3876fdac42
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/data/finset/pi.lean
8ed9a19a57fb32c9957f363a392c6ff0bf3d6fb3
[ "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
4,477
lean
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import data.finset.basic import data.multiset.pi /-! # The cartesian product of finsets -/ namespace finset open multiset /-! ### pi -/ section pi variables {α : Type*} /-- The empty dependent product function, defined on the empty set. The assumption `a ∈ ∅` is never satisfied. -/ def pi.empty (β : α → Sort*) (a : α) (h : a ∈ (∅ : finset α)) : β a := multiset.pi.empty β a h variables {δ : α → Type*} [decidable_eq α] /-- Given a finset `s` of `α` and for all `a : α` a finset `t a` of `δ a`, then one can define the finset `s.pi t` of all functions defined on elements of `s` taking values in `t a` for `a ∈ s`. Note that the elements of `s.pi t` are only partially defined, on `s`. -/ def pi (s : finset α) (t : Πa, finset (δ a)) : finset (Πa∈s, δ a) := ⟨s.1.pi (λ a, (t a).1), nodup_pi s.2 (λ a _, (t a).2)⟩ @[simp] lemma pi_val (s : finset α) (t : Πa, finset (δ a)) : (s.pi t).1 = s.1.pi (λ a, (t a).1) := rfl @[simp] lemma mem_pi {s : finset α} {t : Πa, finset (δ a)} {f : Πa∈s, δ a} : f ∈ s.pi t ↔ (∀a (h : a ∈ s), f a h ∈ t a) := mem_pi _ _ _ /-- Given a function `f` defined on a finset `s`, define a new function on the finset `s ∪ {a}`, equal to `f` on `s` and sending `a` to a given value `b`. This function is denoted `s.pi.cons a b f`. If `a` already belongs to `s`, the new function takes the value `b` at `a` anyway. -/ def pi.cons (s : finset α) (a : α) (b : δ a) (f : Πa, a ∈ s → δ a) (a' : α) (h : a' ∈ insert a s) : δ a' := multiset.pi.cons s.1 a b f _ (multiset.mem_cons.2 $ mem_insert.symm.2 h) @[simp] lemma pi.cons_same (s : finset α) (a : α) (b : δ a) (f : Πa, a ∈ s → δ a) (h : a ∈ insert a s) : pi.cons s a b f a h = b := multiset.pi.cons_same _ lemma pi.cons_ne {s : finset α} {a a' : α} {b : δ a} {f : Πa, a ∈ s → δ a} {h : a' ∈ insert a s} (ha : a ≠ a') : pi.cons s a b f a' h = f a' ((mem_insert.1 h).resolve_left ha.symm) := multiset.pi.cons_ne _ _ lemma pi_cons_injective {a : α} {b : δ a} {s : finset α} (hs : a ∉ s) : function.injective (pi.cons s a b) := assume e₁ e₂ eq, @multiset.pi_cons_injective α _ δ a b s.1 hs _ _ $ funext $ assume e, funext $ assume h, have pi.cons s a b e₁ e (by simpa only [multiset.mem_cons, mem_insert] using h) = pi.cons s a b e₂ e (by simpa only [multiset.mem_cons, mem_insert] using h), { rw [eq] }, this @[simp] lemma pi_empty {t : Πa:α, finset (δ a)} : pi (∅ : finset α) t = singleton (pi.empty δ) := rfl @[simp] lemma pi_insert [∀a, decidable_eq (δ a)] {s : finset α} {t : Πa:α, finset (δ a)} {a : α} (ha : a ∉ s) : pi (insert a s) t = (t a).bUnion (λb, (pi s t).image (pi.cons s a b)) := begin apply eq_of_veq, rw ← multiset.erase_dup_eq_self.2 (pi (insert a s) t).2, refine (λ s' (h : s' = a ::ₘ s.1), (_ : erase_dup (multiset.pi s' (λ a, (t a).1)) = erase_dup ((t a).1.bind $ λ b, erase_dup $ (multiset.pi s.1 (λ (a : α), (t a).val)).map $ λ f a' h', multiset.pi.cons s.1 a b f a' (h ▸ h')))) _ (insert_val_of_not_mem ha), subst s', rw pi_cons, congr, funext b, rw multiset.erase_dup_eq_self.2, exact multiset.nodup_map (multiset.pi_cons_injective ha) (pi s t).2, end lemma pi_singletons {β : Type*} (s : finset α) (f : α → β) : s.pi (λ a, ({f a} : finset β)) = {λ a _, f a} := begin rw eq_singleton_iff_unique_mem, split, { simp }, intros a ha, ext i hi, rw [mem_pi] at ha, simpa using ha i hi, end lemma pi_const_singleton {β : Type*} (s : finset α) (i : β) : s.pi (λ _, ({i} : finset β)) = {λ _ _, i} := pi_singletons s (λ _, i) lemma pi_subset {s : finset α} (t₁ t₂ : Πa, finset (δ a)) (h : ∀ a ∈ s, t₁ a ⊆ t₂ a) : s.pi t₁ ⊆ s.pi t₂ := λ g hg, mem_pi.2 $ λ a ha, h a ha (mem_pi.mp hg a ha) lemma pi_disjoint_of_disjoint {δ : α → Type*} [∀a, decidable_eq (δ a)] {s : finset α} [decidable_eq (Πa∈s, δ a)] (t₁ t₂ : Πa, finset (δ a)) {a : α} (ha : a ∈ s) (h : disjoint (t₁ a) (t₂ a)) : disjoint (s.pi t₁) (s.pi t₂) := disjoint_iff_ne.2 $ λ f₁ hf₁ f₂ hf₂ eq₁₂, disjoint_iff_ne.1 h (f₁ a ha) (mem_pi.mp hf₁ a ha) (f₂ a ha) (mem_pi.mp hf₂ a ha) $ congr_fun (congr_fun eq₁₂ a) ha end pi end finset
054ca93046f143de172491acf4862bc31ebf28ae
9dc8cecdf3c4634764a18254e94d43da07142918
/src/algebra/group/units.lean
23f4851d08a2b445115105f17e4addb110463131
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
19,908
lean
/- Copyright (c) 2017 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Mario Carneiro, Johannes Hölzl, Chris Hughes, Jens Wagemaker, Jon Eugster -/ import algebra.group.basic import logic.nontrivial /-! # Units (i.e., invertible elements) of a monoid An element of a `monoid` is a unit if it has a two-sided inverse. ## Main declarations * `units M`: the group of units (i.e., invertible elements) of a monoid. * `is_unit x`: a predicate asserting that `x` is a unit (i.e., invertible element) of a monoid. For both declarations, there is an additive counterpart: `add_units` and `is_add_unit`. ## Notation We provide `Mˣ` as notation for `units M`, resembling the notation $R^{\times}$ for the units of a ring, which is common in mathematics. -/ open function universe u variable {α : Type u} /-- Units of a `monoid`, bundled version. Notation: `αˣ`. An element of a `monoid` is a unit if it has a two-sided inverse. This version bundles the inverse element so that it can be computed. For a predicate see `is_unit`. -/ structure units (α : Type u) [monoid α] := (val : α) (inv : α) (val_inv : val * inv = 1) (inv_val : inv * val = 1) postfix `ˣ`:1025 := units -- We don't provide notation for the additive version, because its use is somewhat rare. /-- Units of an `add_monoid`, bundled version. An element of an `add_monoid` is a unit if it has a two-sided additive inverse. This version bundles the inverse element so that it can be computed. For a predicate see `is_add_unit`. -/ structure add_units (α : Type u) [add_monoid α] := (val : α) (neg : α) (val_neg : val + neg = 0) (neg_val : neg + val = 0) attribute [to_additive] units section has_elem @[to_additive] lemma unique_has_one {α : Type*} [unique α] [has_one α] : default = (1 : α) := unique.default_eq 1 end has_elem namespace units variables [monoid α] @[to_additive] instance : has_coe αˣ α := ⟨val⟩ @[to_additive] instance : has_inv αˣ := ⟨λ u, ⟨u.2, u.1, u.4, u.3⟩⟩ /-- See Note [custom simps projection] -/ @[to_additive /-" See Note [custom simps projection] "-/] def simps.coe (u : αˣ) : α := u /-- See Note [custom simps projection] -/ @[to_additive /-" See Note [custom simps projection] "-/] def simps.coe_inv (u : αˣ) : α := ↑(u⁻¹) initialize_simps_projections units (val → coe as_prefix, inv → coe_inv as_prefix) initialize_simps_projections add_units (val → coe as_prefix, neg → coe_neg as_prefix) @[simp, to_additive] lemma coe_mk (a : α) (b h₁ h₂) : ↑(units.mk a b h₁ h₂) = a := rfl @[ext, to_additive] theorem ext : function.injective (coe : αˣ → α) | ⟨v, i₁, vi₁, iv₁⟩ ⟨v', i₂, vi₂, iv₂⟩ e := by change v = v' at e; subst v'; congr; simpa only [iv₂, vi₁, one_mul, mul_one] using mul_assoc i₂ v i₁ @[norm_cast, to_additive] theorem eq_iff {a b : αˣ} : (a : α) = b ↔ a = b := ext.eq_iff @[to_additive] theorem ext_iff {a b : αˣ} : a = b ↔ (a : α) = b := eq_iff.symm @[to_additive] instance [decidable_eq α] : decidable_eq αˣ := λ a b, decidable_of_iff' _ ext_iff @[simp, to_additive] theorem mk_coe (u : αˣ) (y h₁ h₂) : mk (u : α) y h₁ h₂ = u := ext rfl /-- Copy a unit, adjusting definition equalities. -/ @[to_additive /-"Copy an `add_unit`, adjusting definitional equalities."-/, simps] def copy (u : αˣ) (val : α) (hv : val = u) (inv : α) (hi : inv = ↑(u⁻¹)) : αˣ := { val := val, inv := inv, inv_val := hv.symm ▸ hi.symm ▸ u.inv_val, val_inv := hv.symm ▸ hi.symm ▸ u.val_inv } @[to_additive] lemma copy_eq (u : αˣ) (val hv inv hi) : u.copy val hv inv hi = u := ext hv @[to_additive] instance : mul_one_class αˣ := { mul := λ u₁ u₂, ⟨u₁.val * u₂.val, u₂.inv * u₁.inv, by rw [mul_assoc, ←mul_assoc u₂.val, val_inv, one_mul, val_inv], by rw [mul_assoc, ←mul_assoc u₁.inv, inv_val, one_mul, inv_val]⟩, one := ⟨1, 1, one_mul 1, one_mul 1⟩, one_mul := λ u, ext $ one_mul u, mul_one := λ u, ext $ mul_one u } /-- Units of a monoid form a group. -/ @[to_additive "Additive units of an additive monoid form an additive group."] instance : group αˣ := { mul := (*), one := 1, mul_assoc := λ u₁ u₂ u₃, ext $ mul_assoc u₁ u₂ u₃, inv := has_inv.inv, mul_left_inv := λ u, ext u.inv_val, ..units.mul_one_class } @[to_additive] instance {α} [comm_monoid α] : comm_group αˣ := { mul_comm := λ u₁ u₂, ext $ mul_comm _ _, ..units.group } @[to_additive] instance : inhabited αˣ := ⟨1⟩ @[to_additive] instance [has_repr α] : has_repr αˣ := ⟨repr ∘ val⟩ variables (a b c : αˣ) {u : αˣ} @[simp, norm_cast, to_additive] lemma coe_mul : (↑(a * b) : α) = a * b := rfl @[simp, norm_cast, to_additive] lemma coe_one : ((1 : αˣ) : α) = 1 := rfl @[simp, norm_cast, to_additive] lemma coe_eq_one {a : αˣ} : (a : α) = 1 ↔ a = 1 := by rw [←units.coe_one, eq_iff] @[simp, to_additive] lemma inv_mk (x y : α) (h₁ h₂) : (mk x y h₁ h₂)⁻¹ = mk y x h₂ h₁ := rfl @[simp, to_additive] lemma val_eq_coe : a.val = (↑a : α) := rfl @[simp, to_additive] lemma inv_eq_coe_inv : a.inv = ((a⁻¹ : αˣ) : α) := rfl @[simp, to_additive] lemma inv_mul : (↑a⁻¹ * a : α) = 1 := inv_val _ @[simp, to_additive] lemma mul_inv : (a * ↑a⁻¹ : α) = 1 := val_inv _ @[to_additive] lemma inv_mul_of_eq {a : α} (h : ↑u = a) : ↑u⁻¹ * a = 1 := by rw [←h, u.inv_mul] @[to_additive] lemma mul_inv_of_eq {a : α} (h : ↑u = a) : a * ↑u⁻¹ = 1 := by rw [←h, u.mul_inv] @[simp, to_additive] lemma mul_inv_cancel_left (a : αˣ) (b : α) : (a:α) * (↑a⁻¹ * b) = b := by rw [← mul_assoc, mul_inv, one_mul] @[simp, to_additive] lemma inv_mul_cancel_left (a : αˣ) (b : α) : (↑a⁻¹:α) * (a * b) = b := by rw [← mul_assoc, inv_mul, one_mul] @[simp, to_additive] lemma mul_inv_cancel_right (a : α) (b : αˣ) : a * b * ↑b⁻¹ = a := by rw [mul_assoc, mul_inv, mul_one] @[simp, to_additive] lemma inv_mul_cancel_right (a : α) (b : αˣ) : a * ↑b⁻¹ * b = a := by rw [mul_assoc, inv_mul, mul_one] @[simp, to_additive] theorem mul_right_inj (a : αˣ) {b c : α} : (a:α) * b = a * c ↔ b = c := ⟨λ h, by simpa only [inv_mul_cancel_left] using congr_arg ((*) ↑(a⁻¹ : αˣ)) h, congr_arg _⟩ @[simp, to_additive] theorem mul_left_inj (a : αˣ) {b c : α} : b * a = c * a ↔ b = c := ⟨λ h, by simpa only [mul_inv_cancel_right] using congr_arg (* ↑(a⁻¹ : αˣ)) h, congr_arg _⟩ @[to_additive] theorem eq_mul_inv_iff_mul_eq {a b : α} : a = b * ↑c⁻¹ ↔ a * c = b := ⟨λ h, by rw [h, inv_mul_cancel_right], λ h, by rw [← h, mul_inv_cancel_right]⟩ @[to_additive] theorem eq_inv_mul_iff_mul_eq {a c : α} : a = ↑b⁻¹ * c ↔ ↑b * a = c := ⟨λ h, by rw [h, mul_inv_cancel_left], λ h, by rw [← h, inv_mul_cancel_left]⟩ @[to_additive] theorem inv_mul_eq_iff_eq_mul {b c : α} : ↑a⁻¹ * b = c ↔ b = a * c := ⟨λ h, by rw [← h, mul_inv_cancel_left], λ h, by rw [h, inv_mul_cancel_left]⟩ @[to_additive] theorem mul_inv_eq_iff_eq_mul {a c : α} : a * ↑b⁻¹ = c ↔ a = c * b := ⟨λ h, by rw [← h, inv_mul_cancel_right], λ h, by rw [h, mul_inv_cancel_right]⟩ @[to_additive] protected lemma inv_eq_of_mul_eq_one_left {a : α} (h : a * u = 1) : ↑u⁻¹ = a := calc ↑u⁻¹ = 1 * ↑u⁻¹ : by rw one_mul ... = a : by rw [←h, mul_inv_cancel_right] @[to_additive] protected lemma inv_eq_of_mul_eq_one_right {a : α} (h : ↑u * a = 1) : ↑u⁻¹ = a := calc ↑u⁻¹ = ↑u⁻¹ * 1 : by rw mul_one ... = a : by rw [←h, inv_mul_cancel_left] @[to_additive] protected lemma eq_inv_of_mul_eq_one_left {a : α} (h : ↑u * a = 1) : a = ↑u⁻¹ := (units.inv_eq_of_mul_eq_one_right h).symm @[to_additive] protected lemma eq_inv_of_mul_eq_one_right {a : α} (h : a * u = 1) : a = ↑u⁻¹ := (units.inv_eq_of_mul_eq_one_left h).symm @[simp, to_additive] lemma mul_inv_eq_one {a : α} : a * ↑u⁻¹ = 1 ↔ a = u := ⟨inv_inv u ▸ units.eq_inv_of_mul_eq_one_right, λ h, mul_inv_of_eq h.symm⟩ @[simp, to_additive] lemma inv_mul_eq_one {a : α} : ↑u⁻¹ * a = 1 ↔ ↑u = a := ⟨inv_inv u ▸ units.inv_eq_of_mul_eq_one_right, inv_mul_of_eq⟩ @[to_additive] lemma mul_eq_one_iff_eq_inv {a : α} : a * u = 1 ↔ a = ↑u⁻¹ := by rw [←mul_inv_eq_one, inv_inv] @[to_additive] lemma mul_eq_one_iff_inv_eq {a : α} : ↑u * a = 1 ↔ ↑u⁻¹ = a := by rw [←inv_mul_eq_one, inv_inv] @[to_additive] lemma inv_unique {u₁ u₂ : αˣ} (h : (↑u₁ : α) = ↑u₂) : (↑u₁⁻¹ : α) = ↑u₂⁻¹ := units.inv_eq_of_mul_eq_one_right $ by rw [h, u₂.mul_inv] @[simp, to_additive] lemma coe_inv {M : Type*} [division_monoid M] (u : units M) : ↑u⁻¹ = (u⁻¹ : M) := eq.symm $ inv_eq_of_mul_eq_one_right u.mul_inv end units /-- For `a, b` in a `comm_monoid` such that `a * b = 1`, makes a unit out of `a`. -/ @[to_additive "For `a, b` in an `add_comm_monoid` such that `a + b = 0`, makes an add_unit out of `a`."] def units.mk_of_mul_eq_one [comm_monoid α] (a b : α) (hab : a * b = 1) : αˣ := ⟨a, b, hab, (mul_comm b a).trans hab⟩ @[simp, to_additive] lemma units.coe_mk_of_mul_eq_one [comm_monoid α] {a b : α} (h : a * b = 1) : (units.mk_of_mul_eq_one a b h : α) = a := rfl section monoid variables [monoid α] {a b c : α} /-- Partial division. It is defined when the second argument is invertible, and unlike the division operator in `division_ring` it is not totalized at zero. -/ def divp (a : α) (u) : α := a * (u⁻¹ : αˣ) infix ` /ₚ `:70 := divp @[simp] theorem divp_self (u : αˣ) : (u : α) /ₚ u = 1 := units.mul_inv _ @[simp] theorem divp_one (a : α) : a /ₚ 1 = a := mul_one _ theorem divp_assoc (a b : α) (u : αˣ) : a * b /ₚ u = a * (b /ₚ u) := mul_assoc _ _ _ /-- `field_simp` needs the reverse direction of `divp_assoc` to move all `/ₚ` to the right. -/ @[field_simps] lemma divp_assoc' (x y : α) (u : αˣ) : x * (y /ₚ u) = (x * y) /ₚ u := (divp_assoc _ _ _).symm @[simp] theorem divp_inv (u : αˣ) : a /ₚ u⁻¹ = a * u := rfl @[simp] theorem divp_mul_cancel (a : α) (u : αˣ) : a /ₚ u * u = a := (mul_assoc _ _ _).trans $ by rw [units.inv_mul, mul_one] @[simp] theorem mul_divp_cancel (a : α) (u : αˣ) : (a * u) /ₚ u = a := (mul_assoc _ _ _).trans $ by rw [units.mul_inv, mul_one] @[simp] theorem divp_left_inj (u : αˣ) {a b : α} : a /ₚ u = b /ₚ u ↔ a = b := units.mul_left_inj _ @[field_simps] theorem divp_divp_eq_divp_mul (x : α) (u₁ u₂ : αˣ) : (x /ₚ u₁) /ₚ u₂ = x /ₚ (u₂ * u₁) := by simp only [divp, mul_inv_rev, units.coe_mul, mul_assoc] @[field_simps] theorem divp_eq_iff_mul_eq {x : α} {u : αˣ} {y : α} : x /ₚ u = y ↔ y * u = x := u.mul_left_inj.symm.trans $ by rw [divp_mul_cancel]; exact ⟨eq.symm, eq.symm⟩ @[field_simps] theorem eq_divp_iff_mul_eq {x : α} {u : αˣ} {y : α} : x = y /ₚ u ↔ x * u = y := by rw [eq_comm, divp_eq_iff_mul_eq] theorem divp_eq_one_iff_eq {a : α} {u : αˣ} : a /ₚ u = 1 ↔ a = u := (units.mul_left_inj u).symm.trans $ by rw [divp_mul_cancel, one_mul] @[simp] theorem one_divp (u : αˣ) : 1 /ₚ u = ↑u⁻¹ := one_mul _ /-- Used for `field_simp` to deal with inverses of units. -/ @[field_simps] lemma inv_eq_one_divp (u : αˣ) : ↑u⁻¹ = 1 /ₚ u := by rw one_divp /-- Used for `field_simp` to deal with inverses of units. This form of the lemma is essential since `field_simp` likes to use `inv_eq_one_div` to rewrite `↑u⁻¹ = ↑(1 / u)`. -/ @[field_simps] lemma inv_eq_one_divp' (u : αˣ) : ((1 / u : αˣ) : α) = 1 /ₚ u := by rw [one_div, one_divp] /-- `field_simp` moves division inside `αˣ` to the right, and this lemma lifts the calculation to `α`. -/ @[field_simps] lemma coe_div_eq_divp (u₁ u₂ : αˣ) : ↑(u₁ / u₂) = ↑u₁ /ₚ u₂ := by rw [divp, division_def, units.coe_mul] end monoid section comm_monoid variables [comm_monoid α] @[field_simps] theorem divp_mul_eq_mul_divp (x y : α) (u : αˣ) : x /ₚ u * y = x * y /ₚ u := by simp_rw [divp, mul_assoc, mul_comm] -- Theoretically redundant as `field_simp` lemma. @[field_simps] lemma divp_eq_divp_iff {x y : α} {ux uy : αˣ} : x /ₚ ux = y /ₚ uy ↔ x * uy = y * ux := by rw [divp_eq_iff_mul_eq, divp_mul_eq_mul_divp, divp_eq_iff_mul_eq] -- Theoretically redundant as `field_simp` lemma. @[field_simps] lemma divp_mul_divp (x y : α) (ux uy : αˣ) : (x /ₚ ux) * (y /ₚ uy) = (x * y) /ₚ (ux * uy) := by rw [divp_mul_eq_mul_divp, divp_assoc', divp_divp_eq_divp_mul] end comm_monoid /-! # `is_unit` predicate In this file we define the `is_unit` predicate on a `monoid`, and prove a few basic properties. For the bundled version see `units`. See also `prime`, `associated`, and `irreducible` in `algebra/associated`. -/ section is_unit variables {M : Type*} {N : Type*} /-- An element `a : M` of a monoid is a unit if it has a two-sided inverse. The actual definition says that `a` is equal to some `u : Mˣ`, where `Mˣ` is a bundled version of `is_unit`. -/ @[to_additive "An element `a : M` of an add_monoid is an `add_unit` if it has a two-sided additive inverse. The actual definition says that `a` is equal to some `u : add_units M`, where `add_units M` is a bundled version of `is_add_unit`."] def is_unit [monoid M] (a : M) : Prop := ∃ u : Mˣ, (u : M) = a @[nontriviality, to_additive] lemma is_unit_of_subsingleton [monoid M] [subsingleton M] (a : M) : is_unit a := ⟨⟨a, a, subsingleton.elim _ _, subsingleton.elim _ _⟩, rfl⟩ attribute [nontriviality] is_add_unit_of_subsingleton @[to_additive] instance [monoid M] : can_lift M Mˣ := { coe := coe, cond := is_unit, prf := λ _, id } @[to_additive] instance [monoid M] [subsingleton M] : unique Mˣ := { default := 1, uniq := λ a, units.coe_eq_one.mp $ subsingleton.elim (a : M) 1 } @[simp, to_additive is_add_unit_add_unit] protected lemma units.is_unit [monoid M] (u : Mˣ) : is_unit (u : M) := ⟨u, rfl⟩ @[simp, to_additive] theorem is_unit_one [monoid M] : is_unit (1:M) := ⟨1, rfl⟩ @[to_additive] theorem is_unit_of_mul_eq_one [comm_monoid M] (a b : M) (h : a * b = 1) : is_unit a := ⟨units.mk_of_mul_eq_one a b h, rfl⟩ @[to_additive is_add_unit.exists_neg] theorem is_unit.exists_right_inv [monoid M] {a : M} (h : is_unit a) : ∃ b, a * b = 1 := by { rcases h with ⟨⟨a, b, hab, _⟩, rfl⟩, exact ⟨b, hab⟩ } @[to_additive is_add_unit.exists_neg'] theorem is_unit.exists_left_inv [monoid M] {a : M} (h : is_unit a) : ∃ b, b * a = 1 := by { rcases h with ⟨⟨a, b, _, hba⟩, rfl⟩, exact ⟨b, hba⟩ } @[to_additive] theorem is_unit_iff_exists_inv [comm_monoid M] {a : M} : is_unit a ↔ ∃ b, a * b = 1 := ⟨λ h, h.exists_right_inv, λ ⟨b, hab⟩, is_unit_of_mul_eq_one _ b hab⟩ @[to_additive] theorem is_unit_iff_exists_inv' [comm_monoid M] {a : M} : is_unit a ↔ ∃ b, b * a = 1 := by simp [is_unit_iff_exists_inv, mul_comm] @[to_additive] lemma is_unit.mul [monoid M] {x y : M} : is_unit x → is_unit y → is_unit (x * y) := by { rintros ⟨x, rfl⟩ ⟨y, rfl⟩, exact ⟨x * y, units.coe_mul _ _⟩ } /-- Multiplication by a `u : Mˣ` on the right doesn't affect `is_unit`. -/ @[simp, to_additive "Addition of a `u : add_units M` on the right doesn't affect `is_add_unit`."] theorem units.is_unit_mul_units [monoid M] (a : M) (u : Mˣ) : is_unit (a * u) ↔ is_unit a := iff.intro (assume ⟨v, hv⟩, have is_unit (a * ↑u * ↑u⁻¹), by existsi v * u⁻¹; rw [←hv, units.coe_mul], by rwa [mul_assoc, units.mul_inv, mul_one] at this) (λ v, v.mul u.is_unit) /-- Multiplication by a `u : Mˣ` on the left doesn't affect `is_unit`. -/ @[simp, to_additive "Addition of a `u : add_units M` on the left doesn't affect `is_add_unit`."] theorem units.is_unit_units_mul {M : Type*} [monoid M] (u : Mˣ) (a : M) : is_unit (↑u * a) ↔ is_unit a := iff.intro (assume ⟨v, hv⟩, have is_unit (↑u⁻¹ * (↑u * a)), by existsi u⁻¹ * v; rw [←hv, units.coe_mul], by rwa [←mul_assoc, units.inv_mul, one_mul] at this) u.is_unit.mul @[to_additive] theorem is_unit_of_mul_is_unit_left [comm_monoid M] {x y : M} (hu : is_unit (x * y)) : is_unit x := let ⟨z, hz⟩ := is_unit_iff_exists_inv.1 hu in is_unit_iff_exists_inv.2 ⟨y * z, by rwa ← mul_assoc⟩ @[to_additive] theorem is_unit_of_mul_is_unit_right [comm_monoid M] {x y : M} (hu : is_unit (x * y)) : is_unit y := @is_unit_of_mul_is_unit_left _ _ y x $ by rwa mul_comm namespace is_unit @[simp, to_additive] lemma mul_iff [comm_monoid M] {x y : M} : is_unit (x * y) ↔ is_unit x ∧ is_unit y := ⟨λ h, ⟨is_unit_of_mul_is_unit_left h, is_unit_of_mul_is_unit_right h⟩, λ h, is_unit.mul h.1 h.2⟩ section monoid variables [monoid M] {a b c : M} /-- The element of the group of units, corresponding to an element of a monoid which is a unit. When `α` is a `division_monoid`, use `is_unit.unit'` instead. -/ @[to_additive "The element of the additive group of additive units, corresponding to an element of an additive monoid which is an additive unit. When `α` is a `subtraction_monoid`, use `is_add_unit.add_unit'` instead."] protected noncomputable def unit (h : is_unit a) : Mˣ := (classical.some h).copy a (classical.some_spec h).symm _ rfl @[simp, to_additive] lemma unit_of_coe_units {a : Mˣ} (h : is_unit (a : M)) : h.unit = a := units.ext $ rfl @[simp, to_additive] lemma unit_spec (h : is_unit a) : ↑h.unit = a := rfl @[simp, to_additive] lemma coe_inv_mul (h : is_unit a) : ↑(h.unit)⁻¹ * a = 1 := units.mul_inv _ @[simp, to_additive] lemma mul_coe_inv (h : is_unit a) : a * ↑(h.unit)⁻¹ = 1 := by convert h.unit.mul_inv /-- `is_unit x` is decidable if we can decide if `x` comes from `Mˣ`. -/ instance (x : M) [h : decidable (∃ u : Mˣ, ↑u = x)] : decidable (is_unit x) := h @[to_additive] lemma mul_left_inj (h : is_unit a) : b * a = c * a ↔ b = c := let ⟨u, hu⟩ := h in hu ▸ u.mul_left_inj @[to_additive] lemma mul_right_inj (h : is_unit a) : a * b = a * c ↔ b = c := let ⟨u, hu⟩ := h in hu ▸ u.mul_right_inj @[to_additive] protected lemma mul_left_cancel (h : is_unit a) : a * b = a * c → b = c := h.mul_right_inj.1 @[to_additive] protected lemma mul_right_cancel (h : is_unit b) : a * b = c * b → a = c := h.mul_left_inj.1 @[to_additive] protected lemma mul_right_injective (h : is_unit a) : injective ((*) a) := λ _ _, h.mul_left_cancel @[to_additive] protected lemma mul_left_injective (h : is_unit b) : injective (* b) := λ _ _, h.mul_right_cancel end monoid variables [division_monoid M] {a : M} @[simp, to_additive] protected lemma inv_mul_cancel : is_unit a → a⁻¹ * a = 1 := by { rintro ⟨u, rfl⟩, rw [← units.coe_inv, units.inv_mul] } @[simp, to_additive] protected lemma mul_inv_cancel : is_unit a → a * a⁻¹ = 1 := by { rintro ⟨u, rfl⟩, rw [← units.coe_inv, units.mul_inv] } end is_unit -- namespace end is_unit -- section section noncomputable_defs variables {M : Type*} /-- Constructs a `group` structure on a `monoid` consisting only of units. -/ noncomputable def group_of_is_unit [hM : monoid M] (h : ∀ (a : M), is_unit a) : group M := { inv := λ a, ↑((h a).unit)⁻¹, mul_left_inv := λ a, by { change ↑((h a).unit)⁻¹ * a = 1, rw [units.inv_mul_eq_iff_eq_mul, (h a).unit_spec, mul_one] }, .. hM } /-- Constructs a `comm_group` structure on a `comm_monoid` consisting only of units. -/ noncomputable def comm_group_of_is_unit [hM : comm_monoid M] (h : ∀ (a : M), is_unit a) : comm_group M := { inv := λ a, ↑((h a).unit)⁻¹, mul_left_inv := λ a, by { change ↑((h a).unit)⁻¹ * a = 1, rw [units.inv_mul_eq_iff_eq_mul, (h a).unit_spec, mul_one] }, .. hM } end noncomputable_defs
ddd2b5d00de5d161443d66bd894f360a57e9c380
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/matrix/basic_auto.lean
736c5f2a77bf56037efa28566ab8a63d9c7c0877
[]
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
59,683
lean
/- Copyright (c) 2018 Ellen Arlt. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Ellen Arlt, Blair Shi, Sean Leather, Mario Carneiro, Johan Commelin -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.algebra.big_operators.pi import Mathlib.algebra.module.pi import Mathlib.algebra.module.linear_map import Mathlib.algebra.big_operators.ring import Mathlib.algebra.star.basic import Mathlib.data.equiv.ring import Mathlib.data.fintype.card import Mathlib.PostPort universes u u' v u_2 u_3 w u_1 u_4 u_5 u_6 namespace Mathlib /-! # Matrices -/ /-- `matrix m n` is the type of matrices whose rows are indexed by the fintype `m` and whose columns are indexed by the fintype `n`. -/ def matrix (m : Type u) (n : Type u') [fintype m] [fintype n] (α : Type v) := m → n → α namespace matrix theorem ext_iff {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {α : Type v} {M : matrix m n α} {N : matrix m n α} : (∀ (i : m) (j : n), M i j = N i j) ↔ M = N := sorry theorem ext {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {α : Type v} {M : matrix m n α} {N : matrix m n α} : (∀ (i : m) (j : n), M i j = N i j) → M = N := iff.mp ext_iff /-- `M.map f` is the matrix obtained by applying `f` to each entry of the matrix `M`. -/ def map {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {α : Type v} (M : matrix m n α) {β : Type w} (f : α → β) : matrix m n β := fun (i : m) (j : n) => f (M i j) @[simp] theorem map_apply {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {α : Type v} {M : matrix m n α} {β : Type w} {f : α → β} {i : m} {j : n} : map M f i j = f (M i j) := rfl @[simp] theorem map_map {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {α : Type v} {M : matrix m n α} {β : Type u_1} {γ : Type u_4} {f : α → β} {g : β → γ} : map (map M f) g = map M (g ∘ f) := sorry /-- The transpose of a matrix. -/ def transpose {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {α : Type v} (M : matrix m n α) : matrix n m α := sorry /-- `matrix.col u` is the column matrix whose entries are given by `u`. -/ def col {m : Type u_2} [fintype m] {α : Type v} (w : m → α) : matrix m Unit α := sorry /-- `matrix.row u` is the row matrix whose entries are given by `u`. -/ def row {n : Type u_3} [fintype n] {α : Type v} (v : n → α) : matrix Unit n α := sorry protected instance inhabited {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {α : Type v} [Inhabited α] : Inhabited (matrix m n α) := pi.inhabited m protected instance has_add {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {α : Type v} [Add α] : Add (matrix m n α) := pi.has_add protected instance add_semigroup {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {α : Type v} [add_semigroup α] : add_semigroup (matrix m n α) := pi.add_semigroup protected instance add_comm_semigroup {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {α : Type v} [add_comm_semigroup α] : add_comm_semigroup (matrix m n α) := pi.add_comm_semigroup protected instance has_zero {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {α : Type v} [HasZero α] : HasZero (matrix m n α) := pi.has_zero protected instance add_monoid {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {α : Type v} [add_monoid α] : add_monoid (matrix m n α) := pi.add_monoid protected instance add_comm_monoid {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {α : Type v} [add_comm_monoid α] : add_comm_monoid (matrix m n α) := pi.add_comm_monoid protected instance has_neg {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {α : Type v} [Neg α] : Neg (matrix m n α) := pi.has_neg protected instance has_sub {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {α : Type v} [Sub α] : Sub (matrix m n α) := pi.has_sub protected instance add_group {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {α : Type v} [add_group α] : add_group (matrix m n α) := pi.add_group protected instance add_comm_group {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {α : Type v} [add_comm_group α] : add_comm_group (matrix m n α) := pi.add_comm_group @[simp] theorem zero_apply {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {α : Type v} [HasZero α] (i : m) (j : n) : HasZero.zero i j = 0 := rfl @[simp] theorem neg_apply {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {α : Type v} [Neg α] (M : matrix m n α) (i : m) (j : n) : Neg.neg M i j = -M i j := rfl @[simp] theorem add_apply {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {α : Type v} [Add α] (M : matrix m n α) (N : matrix m n α) (i : m) (j : n) : Add.add M N i j = M i j + N i j := rfl @[simp] theorem sub_apply {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {α : Type v} [Sub α] (M : matrix m n α) (N : matrix m n α) (i : m) (j : n) : Sub.sub M N i j = M i j - N i j := rfl @[simp] theorem map_zero {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {α : Type v} [HasZero α] {β : Type w} [HasZero β] {f : α → β} (h : f 0 = 0) : map 0 f = 0 := sorry theorem map_add {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {α : Type v} [add_monoid α] {β : Type w} [add_monoid β] (f : α →+ β) (M : matrix m n α) (N : matrix m n α) : map (M + N) ⇑f = map M ⇑f + map N ⇑f := sorry theorem map_sub {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {α : Type v} [add_group α] {β : Type w} [add_group β] (f : α →+ β) (M : matrix m n α) (N : matrix m n α) : map (M - N) ⇑f = map M ⇑f - map N ⇑f := sorry theorem subsingleton_of_empty_left {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {α : Type v} (hm : ¬Nonempty m) : subsingleton (matrix m n α) := sorry theorem subsingleton_of_empty_right {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {α : Type v} (hn : ¬Nonempty n) : subsingleton (matrix m n α) := sorry end matrix /-- The `add_monoid_hom` between spaces of matrices induced by an `add_monoid_hom` between their coefficients. -/ def add_monoid_hom.map_matrix {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {α : Type v} [add_monoid α] {β : Type w} [add_monoid β] (f : α →+ β) : matrix m n α →+ matrix m n β := add_monoid_hom.mk (fun (M : matrix m n α) => matrix.map M ⇑f) sorry (matrix.map_add f) @[simp] theorem add_monoid_hom.map_matrix_apply {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {α : Type v} [add_monoid α] {β : Type w} [add_monoid β] (f : α →+ β) (M : matrix m n α) : coe_fn (add_monoid_hom.map_matrix f) M = matrix.map M ⇑f := rfl namespace matrix /-- `diagonal d` is the square matrix such that `(diagonal d) i i = d i` and `(diagonal d) i j = 0` if `i ≠ j`. -/ def diagonal {n : Type u_3} [fintype n] {α : Type v} [DecidableEq n] [HasZero α] (d : n → α) : matrix n n α := fun (i j : n) => ite (i = j) (d i) 0 @[simp] theorem diagonal_apply_eq {n : Type u_3} [fintype n] {α : Type v} [DecidableEq n] [HasZero α] {d : n → α} (i : n) : diagonal d i i = d i := sorry @[simp] theorem diagonal_apply_ne {n : Type u_3} [fintype n] {α : Type v} [DecidableEq n] [HasZero α] {d : n → α} {i : n} {j : n} (h : i ≠ j) : diagonal d i j = 0 := sorry theorem diagonal_apply_ne' {n : Type u_3} [fintype n] {α : Type v} [DecidableEq n] [HasZero α] {d : n → α} {i : n} {j : n} (h : j ≠ i) : diagonal d i j = 0 := diagonal_apply_ne (ne.symm h) @[simp] theorem diagonal_zero {n : Type u_3} [fintype n] {α : Type v} [DecidableEq n] [HasZero α] : (diagonal fun (_x : n) => 0) = 0 := sorry @[simp] theorem diagonal_transpose {n : Type u_3} [fintype n] {α : Type v} [DecidableEq n] [HasZero α] (v : n → α) : transpose (diagonal v) = diagonal v := sorry @[simp] theorem diagonal_add {n : Type u_3} [fintype n] {α : Type v} [DecidableEq n] [add_monoid α] (d₁ : n → α) (d₂ : n → α) : diagonal d₁ + diagonal d₂ = diagonal fun (i : n) => d₁ i + d₂ i := sorry @[simp] theorem diagonal_map {n : Type u_3} [fintype n] {α : Type v} [DecidableEq n] {β : Type w} [HasZero α] [HasZero β] {f : α → β} (h : f 0 = 0) {d : n → α} : map (diagonal d) f = diagonal fun (m : n) => f (d m) := sorry protected instance has_one {n : Type u_3} [fintype n] {α : Type v} [DecidableEq n] [HasZero α] [HasOne α] : HasOne (matrix n n α) := { one := diagonal fun (_x : n) => 1 } @[simp] theorem diagonal_one {n : Type u_3} [fintype n] {α : Type v} [DecidableEq n] [HasZero α] [HasOne α] : (diagonal fun (_x : n) => 1) = 1 := rfl theorem one_apply {n : Type u_3} [fintype n] {α : Type v} [DecidableEq n] [HasZero α] [HasOne α] {i : n} {j : n} : HasOne.one i j = ite (i = j) 1 0 := rfl @[simp] theorem one_apply_eq {n : Type u_3} [fintype n] {α : Type v} [DecidableEq n] [HasZero α] [HasOne α] (i : n) : HasOne.one i i = 1 := diagonal_apply_eq i @[simp] theorem one_apply_ne {n : Type u_3} [fintype n] {α : Type v} [DecidableEq n] [HasZero α] [HasOne α] {i : n} {j : n} : i ≠ j → HasOne.one i j = 0 := diagonal_apply_ne theorem one_apply_ne' {n : Type u_3} [fintype n] {α : Type v} [DecidableEq n] [HasZero α] [HasOne α] {i : n} {j : n} : j ≠ i → HasOne.one i j = 0 := diagonal_apply_ne' @[simp] theorem one_map {n : Type u_3} [fintype n] {α : Type v} [DecidableEq n] [HasZero α] [HasOne α] {β : Type w} [HasZero β] [HasOne β] {f : α → β} (h₀ : f 0 = 0) (h₁ : f 1 = 1) : map 1 f = 1 := sorry @[simp] theorem bit0_apply {m : Type u_2} [fintype m] {α : Type v} [Add α] (M : matrix m m α) (i : m) (j : m) : bit0 M i j = bit0 (M i j) := rfl theorem bit1_apply {n : Type u_3} [fintype n] {α : Type v} [DecidableEq n] [add_monoid α] [HasOne α] (M : matrix n n α) (i : n) (j : n) : bit1 M i j = ite (i = j) (bit1 (M i j)) (bit0 (M i j)) := sorry @[simp] theorem bit1_apply_eq {n : Type u_3} [fintype n] {α : Type v} [DecidableEq n] [add_monoid α] [HasOne α] (M : matrix n n α) (i : n) : bit1 M i i = bit1 (M i i) := sorry @[simp] theorem bit1_apply_ne {n : Type u_3} [fintype n] {α : Type v} [DecidableEq n] [add_monoid α] [HasOne α] (M : matrix n n α) {i : n} {j : n} (h : i ≠ j) : bit1 M i j = bit0 (M i j) := sorry /-- `dot_product v w` is the sum of the entrywise products `v i * w i` -/ def dot_product {m : Type u_2} [fintype m] {α : Type v} [Mul α] [add_comm_monoid α] (v : m → α) (w : m → α) : α := finset.sum finset.univ fun (i : m) => v i * w i theorem dot_product_assoc {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {α : Type v} [semiring α] (u : m → α) (v : m → n → α) (w : n → α) : dot_product (fun (j : n) => dot_product u fun (i : m) => v i j) w = dot_product u fun (i : m) => dot_product (v i) w := sorry theorem dot_product_comm {m : Type u_2} [fintype m] {α : Type v} [comm_semiring α] (v : m → α) (w : m → α) : dot_product v w = dot_product w v := sorry @[simp] theorem dot_product_punit {α : Type v} [add_comm_monoid α] [Mul α] (v : PUnit → α) (w : PUnit → α) : dot_product v w = v PUnit.unit * w PUnit.unit := sorry @[simp] theorem dot_product_zero {m : Type u_2} [fintype m] {α : Type v} [semiring α] (v : m → α) : dot_product v 0 = 0 := sorry @[simp] theorem dot_product_zero' {m : Type u_2} [fintype m] {α : Type v} [semiring α] (v : m → α) : (dot_product v fun (_x : m) => 0) = 0 := dot_product_zero v @[simp] theorem zero_dot_product {m : Type u_2} [fintype m] {α : Type v} [semiring α] (v : m → α) : dot_product 0 v = 0 := sorry @[simp] theorem zero_dot_product' {m : Type u_2} [fintype m] {α : Type v} [semiring α] (v : m → α) : dot_product (fun (_x : m) => 0) v = 0 := zero_dot_product v @[simp] theorem add_dot_product {m : Type u_2} [fintype m] {α : Type v} [semiring α] (u : m → α) (v : m → α) (w : m → α) : dot_product (u + v) w = dot_product u w + dot_product v w := sorry @[simp] theorem dot_product_add {m : Type u_2} [fintype m] {α : Type v} [semiring α] (u : m → α) (v : m → α) (w : m → α) : dot_product u (v + w) = dot_product u v + dot_product u w := sorry @[simp] theorem diagonal_dot_product {m : Type u_2} [fintype m] {α : Type v} [DecidableEq m] [semiring α] (v : m → α) (w : m → α) (i : m) : dot_product (diagonal v i) w = v i * w i := sorry @[simp] theorem dot_product_diagonal {m : Type u_2} [fintype m] {α : Type v} [DecidableEq m] [semiring α] (v : m → α) (w : m → α) (i : m) : dot_product v (diagonal w i) = v i * w i := sorry @[simp] theorem dot_product_diagonal' {m : Type u_2} [fintype m] {α : Type v} [DecidableEq m] [semiring α] (v : m → α) (w : m → α) (i : m) : (dot_product v fun (j : m) => diagonal w j i) = v i * w i := sorry @[simp] theorem neg_dot_product {m : Type u_2} [fintype m] {α : Type v} [ring α] (v : m → α) (w : m → α) : dot_product (-v) w = -dot_product v w := sorry @[simp] theorem dot_product_neg {m : Type u_2} [fintype m] {α : Type v} [ring α] (v : m → α) (w : m → α) : dot_product v (-w) = -dot_product v w := sorry @[simp] theorem smul_dot_product {m : Type u_2} [fintype m] {α : Type v} [semiring α] (x : α) (v : m → α) (w : m → α) : dot_product (x • v) w = x * dot_product v w := sorry @[simp] theorem dot_product_smul {m : Type u_2} [fintype m] {α : Type v} [comm_semiring α] (x : α) (v : m → α) (w : m → α) : dot_product v (x • w) = x * dot_product v w := sorry /-- `M ⬝ N` is the usual product of matrices `M` and `N`, i.e. we have that `(M ⬝ N) i k` is the dot product of the `i`-th row of `M` by the `k`-th column of `Ǹ`. -/ protected def mul {l : Type u_1} {m : Type u_2} {n : Type u_3} [fintype l] [fintype m] [fintype n] {α : Type v} [Mul α] [add_comm_monoid α] (M : matrix l m α) (N : matrix m n α) : matrix l n α := fun (i : l) (k : n) => dot_product (fun (j : m) => M i j) fun (j : m) => N j k theorem mul_apply {l : Type u_1} {m : Type u_2} {n : Type u_3} [fintype l] [fintype m] [fintype n] {α : Type v} [Mul α] [add_comm_monoid α] {M : matrix l m α} {N : matrix m n α} {i : l} {k : n} : matrix.mul M N i k = finset.sum finset.univ fun (j : m) => M i j * N j k := rfl protected instance has_mul {n : Type u_3} [fintype n] {α : Type v} [Mul α] [add_comm_monoid α] : Mul (matrix n n α) := { mul := matrix.mul } @[simp] theorem mul_eq_mul {n : Type u_3} [fintype n] {α : Type v} [Mul α] [add_comm_monoid α] (M : matrix n n α) (N : matrix n n α) : M * N = matrix.mul M N := rfl theorem mul_apply' {n : Type u_3} [fintype n] {α : Type v} [Mul α] [add_comm_monoid α] {M : matrix n n α} {N : matrix n n α} {i : n} {k : n} : matrix.mul M N i k = dot_product (fun (j : n) => M i j) fun (j : n) => N j k := rfl protected theorem mul_assoc {l : Type u_1} {m : Type u_2} {n : Type u_3} {o : Type u_4} [fintype l] [fintype m] [fintype n] [fintype o] {α : Type v} [semiring α] (L : matrix l m α) (M : matrix m n α) (N : matrix n o α) : matrix.mul (matrix.mul L M) N = matrix.mul L (matrix.mul M N) := ext fun (i : l) (j : o) => dot_product_assoc (fun (j : m) => L i j) (fun (i : m) (j : n) => M i j) fun (j_1 : n) => N j_1 j protected instance semigroup {n : Type u_3} [fintype n] {α : Type v} [semiring α] : semigroup (matrix n n α) := semigroup.mk Mul.mul matrix.mul_assoc @[simp] theorem diagonal_neg {n : Type u_3} [fintype n] {α : Type v} [DecidableEq n] [add_group α] (d : n → α) : -diagonal d = diagonal fun (i : n) => -d i := sorry @[simp] protected theorem mul_zero {m : Type u_2} {n : Type u_3} {o : Type u_4} [fintype m] [fintype n] [fintype o] {α : Type v} [semiring α] (M : matrix m n α) : matrix.mul M 0 = 0 := ext fun (i : m) (j : o) => dot_product_zero fun (j : n) => M i j @[simp] protected theorem zero_mul {l : Type u_1} {m : Type u_2} {n : Type u_3} [fintype l] [fintype m] [fintype n] {α : Type v} [semiring α] (M : matrix m n α) : matrix.mul 0 M = 0 := ext fun (i : l) (j : n) => zero_dot_product fun (j_1 : m) => M j_1 j protected theorem mul_add {m : Type u_2} {n : Type u_3} {o : Type u_4} [fintype m] [fintype n] [fintype o] {α : Type v} [semiring α] (L : matrix m n α) (M : matrix n o α) (N : matrix n o α) : matrix.mul L (M + N) = matrix.mul L M + matrix.mul L N := ext fun (i : m) (j : o) => dot_product_add (fun (j : n) => L i j) (fun (i : n) => M i j) fun (i : n) => N i j protected theorem add_mul {l : Type u_1} {m : Type u_2} {n : Type u_3} [fintype l] [fintype m] [fintype n] {α : Type v} [semiring α] (L : matrix l m α) (M : matrix l m α) (N : matrix m n α) : matrix.mul (L + M) N = matrix.mul L N + matrix.mul M N := ext fun (i : l) (j : n) => add_dot_product (fun (i_1 : m) => L i i_1) (fun (i_1 : m) => M i i_1) fun (j_1 : m) => N j_1 j @[simp] theorem diagonal_mul {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {α : Type v} [semiring α] [DecidableEq m] (d : m → α) (M : matrix m n α) (i : m) (j : n) : matrix.mul (diagonal d) M i j = d i * M i j := diagonal_dot_product (fun (i : m) => d i) (fun (j_1 : m) => M j_1 j) i @[simp] theorem mul_diagonal {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {α : Type v} [semiring α] [DecidableEq n] (d : n → α) (M : matrix m n α) (i : m) (j : n) : matrix.mul M (diagonal d) i j = M i j * d j := eq.mpr (id (Eq._oldrec (Eq.refl (matrix.mul M (diagonal d) i j = M i j * d j)) (Eq.symm (diagonal_transpose d)))) (dot_product_diagonal (fun (j : n) => M i j) (fun (j : n) => d j) j) @[simp] protected theorem one_mul {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {α : Type v} [semiring α] [DecidableEq m] (M : matrix m n α) : matrix.mul 1 M = M := sorry @[simp] protected theorem mul_one {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {α : Type v} [semiring α] [DecidableEq n] (M : matrix m n α) : matrix.mul M 1 = M := sorry protected instance monoid {n : Type u_3} [fintype n] {α : Type v} [semiring α] [DecidableEq n] : monoid (matrix n n α) := monoid.mk semigroup.mul sorry 1 sorry sorry protected instance semiring {n : Type u_3} [fintype n] {α : Type v} [semiring α] [DecidableEq n] : semiring (matrix n n α) := semiring.mk add_comm_monoid.add sorry add_comm_monoid.zero sorry sorry sorry monoid.mul sorry monoid.one sorry sorry matrix.zero_mul matrix.mul_zero matrix.mul_add matrix.add_mul @[simp] theorem diagonal_mul_diagonal {n : Type u_3} [fintype n] {α : Type v} [semiring α] [DecidableEq n] (d₁ : n → α) (d₂ : n → α) : matrix.mul (diagonal d₁) (diagonal d₂) = diagonal fun (i : n) => d₁ i * d₂ i := sorry theorem diagonal_mul_diagonal' {n : Type u_3} [fintype n] {α : Type v} [semiring α] [DecidableEq n] (d₁ : n → α) (d₂ : n → α) : diagonal d₁ * diagonal d₂ = diagonal fun (i : n) => d₁ i * d₂ i := diagonal_mul_diagonal d₁ d₂ @[simp] theorem map_mul {m : Type u_2} {n : Type u_3} {o : Type u_4} [fintype m] [fintype n] [fintype o] {α : Type v} [semiring α] {L : matrix m n α} {M : matrix n o α} {β : Type w} [semiring β] {f : α →+* β} : map (matrix.mul L M) ⇑f = matrix.mul (map L ⇑f) (map M ⇑f) := sorry -- TODO: there should be a way to avoid restating these for each `foo_hom`. /-- A version of `one_map` where `f` is a ring hom. -/ @[simp] theorem ring_hom_map_one {n : Type u_3} [fintype n] {α : Type v} [semiring α] [DecidableEq n] {β : Type w} [semiring β] (f : α →+* β) : map 1 ⇑f = 1 := one_map (ring_hom.map_zero f) (ring_hom.map_one f) /-- A version of `one_map` where `f` is a `ring_equiv`. -/ @[simp] theorem ring_equiv_map_one {n : Type u_3} [fintype n] {α : Type v} [semiring α] [DecidableEq n] {β : Type w} [semiring β] (f : α ≃+* β) : map 1 ⇑f = 1 := one_map (ring_equiv.map_zero f) (ring_equiv.map_one f) /-- A version of `map_zero` where `f` is a `zero_hom`. -/ @[simp] theorem zero_hom_map_zero {n : Type u_3} [fintype n] {α : Type v} [semiring α] {β : Type w} [HasZero β] (f : zero_hom α β) : map 0 ⇑f = 0 := map_zero (zero_hom.map_zero f) /-- A version of `map_zero` where `f` is a `add_monoid_hom`. -/ @[simp] theorem add_monoid_hom_map_zero {n : Type u_3} [fintype n] {α : Type v} [semiring α] {β : Type w} [add_monoid β] (f : α →+ β) : map 0 ⇑f = 0 := map_zero (add_monoid_hom.map_zero f) /-- A version of `map_zero` where `f` is a `add_equiv`. -/ @[simp] theorem add_equiv_map_zero {n : Type u_3} [fintype n] {α : Type v} [semiring α] {β : Type w} [add_monoid β] (f : α ≃+ β) : map 0 ⇑f = 0 := map_zero (add_equiv.map_zero f) /-- A version of `map_zero` where `f` is a `linear_map`. -/ @[simp] theorem linear_map_map_zero {n : Type u_3} [fintype n] {α : Type v} [semiring α] {R : Type u_1} [semiring R] {β : Type w} [add_comm_monoid β] [semimodule R α] [semimodule R β] (f : linear_map R α β) : map 0 ⇑f = 0 := map_zero (linear_map.map_zero f) /-- A version of `map_zero` where `f` is a `linear_equiv`. -/ @[simp] theorem linear_equiv_map_zero {n : Type u_3} [fintype n] {α : Type v} [semiring α] {R : Type u_1} [semiring R] {β : Type w} [add_comm_monoid β] [semimodule R α] [semimodule R β] (f : linear_equiv R α β) : map 0 ⇑f = 0 := map_zero (linear_equiv.map_zero f) /-- A version of `map_zero` where `f` is a `ring_hom`. -/ @[simp] theorem ring_hom_map_zero {n : Type u_3} [fintype n] {α : Type v} [semiring α] {β : Type w} [semiring β] (f : α →+* β) : map 0 ⇑f = 0 := map_zero (ring_hom.map_zero f) /-- A version of `map_zero` where `f` is a `ring_equiv`. -/ @[simp] theorem ring_equiv_map_zero {n : Type u_3} [fintype n] {α : Type v} [semiring α] {β : Type w} [semiring β] (f : α ≃+* β) : map 0 ⇑f = 0 := map_zero (ring_equiv.map_zero f) theorem is_add_monoid_hom_mul_left {l : Type u_1} {m : Type u_2} {n : Type u_3} [fintype l] [fintype m] [fintype n] {α : Type v} [semiring α] (M : matrix l m α) : is_add_monoid_hom fun (x : matrix m n α) => matrix.mul M x := is_add_monoid_hom.mk (matrix.mul_zero M) theorem is_add_monoid_hom_mul_right {l : Type u_1} {m : Type u_2} {n : Type u_3} [fintype l] [fintype m] [fintype n] {α : Type v} [semiring α] (M : matrix m n α) : is_add_monoid_hom fun (x : matrix l m α) => matrix.mul x M := is_add_monoid_hom.mk (matrix.zero_mul M) protected theorem sum_mul {l : Type u_1} {m : Type u_2} {n : Type u_3} [fintype l] [fintype m] [fintype n] {α : Type v} [semiring α] {β : Type u_4} (s : finset β) (f : β → matrix l m α) (M : matrix m n α) : matrix.mul (finset.sum s fun (a : β) => f a) M = finset.sum s fun (a : β) => matrix.mul (f a) M := Eq.symm (finset.sum_hom s fun (x : matrix l m α) => matrix.mul x M) /- This line does not type-check without `id` and `: _`. Lean did not recognize that two different `add_monoid` instances were def-eq -/ protected theorem mul_sum {l : Type u_1} {m : Type u_2} {n : Type u_3} [fintype l] [fintype m] [fintype n] {α : Type v} [semiring α] {β : Type u_4} (s : finset β) (f : β → matrix m n α) (M : matrix l m α) : matrix.mul M (finset.sum s fun (a : β) => f a) = finset.sum s fun (a : β) => matrix.mul M (f a) := Eq.symm (finset.sum_hom s fun (x : matrix m n α) => matrix.mul M x) /- This line does not type-check without `id` and `: _`. Lean did not recognize that two different `add_monoid` instances were def-eq -/ @[simp] theorem row_mul_col_apply {m : Type u_2} [fintype m] {α : Type v} [semiring α] (v : m → α) (w : m → α) (i : Unit) (j : Unit) : matrix.mul (row v) (col w) i j = dot_product v w := rfl end matrix /-- The `ring_hom` between spaces of square matrices induced by a `ring_hom` between their coefficients. -/ def ring_hom.map_matrix {m : Type u_2} [fintype m] {α : Type v} [DecidableEq m] [semiring α] {β : Type w} [semiring β] (f : α →+* β) : matrix m m α →+* matrix m m β := ring_hom.mk (fun (M : matrix m m α) => matrix.map M ⇑f) sorry sorry sorry sorry @[simp] theorem ring_hom.map_matrix_apply {m : Type u_2} [fintype m] {α : Type v} [DecidableEq m] [semiring α] {β : Type w} [semiring β] (f : α →+* β) (M : matrix m m α) : coe_fn (ring_hom.map_matrix f) M = matrix.map M ⇑f := rfl namespace matrix @[simp] theorem neg_mul {m : Type u_2} {n : Type u_3} {o : Type u_4} [fintype m] [fintype n] [fintype o] {α : Type v} [ring α] (M : matrix m n α) (N : matrix n o α) : matrix.mul (-M) N = -matrix.mul M N := ext fun (i : m) (j : o) => neg_dot_product (fun (i_1 : n) => M i i_1) fun (j_1 : n) => N j_1 j @[simp] theorem mul_neg {m : Type u_2} {n : Type u_3} {o : Type u_4} [fintype m] [fintype n] [fintype o] {α : Type v} [ring α] (M : matrix m n α) (N : matrix n o α) : matrix.mul M (-N) = -matrix.mul M N := ext fun (i : m) (j : o) => dot_product_neg (fun (j : n) => M i j) fun (i : n) => N i j protected theorem sub_mul {m : Type u_2} {n : Type u_3} {o : Type u_4} [fintype m] [fintype n] [fintype o] {α : Type v} [ring α] (M : matrix m n α) (M' : matrix m n α) (N : matrix n o α) : matrix.mul (M - M') N = matrix.mul M N - matrix.mul M' N := sorry protected theorem mul_sub {m : Type u_2} {n : Type u_3} {o : Type u_4} [fintype m] [fintype n] [fintype o] {α : Type v} [ring α] (M : matrix m n α) (N : matrix n o α) (N' : matrix n o α) : matrix.mul M (N - N') = matrix.mul M N - matrix.mul M N' := sorry protected instance ring {n : Type u_3} [fintype n] {α : Type v} [DecidableEq n] [ring α] : ring (matrix n n α) := ring.mk semiring.add sorry semiring.zero sorry sorry add_comm_group.neg add_comm_group.sub sorry sorry semiring.mul sorry semiring.one sorry sorry sorry sorry protected instance has_scalar {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {α : Type v} [semiring α] : has_scalar α (matrix m n α) := pi.has_scalar protected instance semimodule {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {α : Type v} {β : Type w} [semiring α] [add_comm_monoid β] [semimodule α β] : semimodule α (matrix m n β) := pi.semimodule m (fun (ᾰ : m) => n → β) α @[simp] theorem smul_apply {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {α : Type v} [semiring α] (a : α) (A : matrix m n α) (i : m) (j : n) : has_scalar.smul a A i j = a * A i j := rfl theorem smul_eq_diagonal_mul {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {α : Type v} [semiring α] [DecidableEq m] (M : matrix m n α) (a : α) : a • M = matrix.mul (diagonal fun (_x : m) => a) M := sorry @[simp] theorem smul_mul {l : Type u_1} {m : Type u_2} {n : Type u_3} [fintype l] [fintype m] [fintype n] {α : Type v} [semiring α] (M : matrix m n α) (a : α) (N : matrix n l α) : matrix.mul (a • M) N = a • matrix.mul M N := ext fun (i : m) (j : l) => smul_dot_product a (fun (i_1 : n) => M i i_1) fun (j_1 : n) => N j_1 j @[simp] theorem mul_mul_left {m : Type u_2} {n : Type u_3} {o : Type u_4} [fintype m] [fintype n] [fintype o] {α : Type v} [semiring α] (M : matrix m n α) (N : matrix n o α) (a : α) : matrix.mul (fun (i : m) (j : n) => a * M i j) N = a • matrix.mul M N := sorry /-- The ring homomorphism `α →+* matrix n n α` sending `a` to the diagonal matrix with `a` on the diagonal. -/ def scalar {α : Type v} [semiring α] (n : Type u) [DecidableEq n] [fintype n] : α →+* matrix n n α := ring_hom.mk (fun (a : α) => a • 1) sorry sorry sorry sorry @[simp] theorem coe_scalar {n : Type u_3} [fintype n] {α : Type v} [semiring α] [DecidableEq n] : ⇑(scalar n) = fun (a : α) => a • 1 := rfl theorem scalar_apply_eq {n : Type u_3} [fintype n] {α : Type v} [semiring α] [DecidableEq n] (a : α) (i : n) : coe_fn (scalar n) a i i = a := sorry theorem scalar_apply_ne {n : Type u_3} [fintype n] {α : Type v} [semiring α] [DecidableEq n] (a : α) (i : n) (j : n) (h : i ≠ j) : coe_fn (scalar n) a i j = 0 := sorry theorem scalar_inj {n : Type u_3} [fintype n] {α : Type v} [semiring α] [DecidableEq n] [Nonempty n] {r : α} {s : α} : coe_fn (scalar n) r = coe_fn (scalar n) s ↔ r = s := sorry theorem smul_eq_mul_diagonal {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {α : Type v} [comm_semiring α] [DecidableEq n] (M : matrix m n α) (a : α) : a • M = matrix.mul M (diagonal fun (_x : n) => a) := sorry @[simp] theorem mul_smul {l : Type u_1} {m : Type u_2} {n : Type u_3} [fintype l] [fintype m] [fintype n] {α : Type v} [comm_semiring α] (M : matrix m n α) (a : α) (N : matrix n l α) : matrix.mul M (a • N) = a • matrix.mul M N := ext fun (i : m) (j : l) => dot_product_smul a (fun (j : n) => M i j) fun (i : n) => N i j @[simp] theorem mul_mul_right {m : Type u_2} {n : Type u_3} {o : Type u_4} [fintype m] [fintype n] [fintype o] {α : Type v} [comm_semiring α] (M : matrix m n α) (N : matrix n o α) (a : α) : (matrix.mul M fun (i : n) (j : o) => a * N i j) = a • matrix.mul M N := sorry theorem scalar.commute {n : Type u_3} [fintype n] {α : Type v} [comm_semiring α] [DecidableEq n] (r : α) (M : matrix n n α) : commute (coe_fn (scalar n) r) M := sorry /-- For two vectors `w` and `v`, `vec_mul_vec w v i j` is defined to be `w i * v j`. Put another way, `vec_mul_vec w v` is exactly `col w ⬝ row v`. -/ def vec_mul_vec {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {α : Type v} [semiring α] (w : m → α) (v : n → α) : matrix m n α := sorry /-- `mul_vec M v` is the matrix-vector product of `M` and `v`, where `v` is seen as a column matrix. Put another way, `mul_vec M v` is the vector whose entries are those of `M ⬝ col v` (see `col_mul_vec`). -/ def mul_vec {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {α : Type v} [semiring α] (M : matrix m n α) (v : n → α) : m → α := sorry /-- `vec_mul v M` is the vector-matrix product of `v` and `M`, where `v` is seen as a row matrix. Put another way, `vec_mul v M` is the vector whose entries are those of `row v ⬝ M` (see `row_vec_mul`). -/ def vec_mul {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {α : Type v} [semiring α] (v : m → α) (M : matrix m n α) : n → α := sorry protected instance mul_vec.is_add_monoid_hom_left {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {α : Type v} [semiring α] (v : n → α) : is_add_monoid_hom fun (M : matrix m n α) => mul_vec M v := is_add_monoid_hom.mk (funext fun (x : m) => eq.mpr (id (Eq.trans ((fun (a a_1 : α) (e_1 : a = a_1) (ᾰ ᾰ_1 : α) (e_2 : ᾰ = ᾰ_1) => congr (congr_arg Eq e_1) e_2) (mul_vec 0 v x) 0 (Eq.trans (Eq.trans (mul_vec.equations._eqn_1 0 v x) ((fun [_inst_2 : fintype n] {α : Type v} (v v_1 : n → α) (e_5 : v = v_1) (w w_1 : n → α) (e_6 : w = w_1) => eq.drec (eq.drec (Eq.refl (dot_product v w)) e_6) e_5) (fun (j : n) => HasZero.zero x j) (fun (j : n) => 0) (funext fun (j : n) => zero_apply x j) v v (Eq.refl v))) (zero_dot_product' v)) (HasZero.zero x) 0 (pi.zero_apply x)) (propext (eq_self_iff_true 0)))) trivial) theorem mul_vec_diagonal {m : Type u_2} [fintype m] {α : Type v} [semiring α] [DecidableEq m] (v : m → α) (w : m → α) (x : m) : mul_vec (diagonal v) w x = v x * w x := diagonal_dot_product v w x theorem vec_mul_diagonal {m : Type u_2} [fintype m] {α : Type v} [semiring α] [DecidableEq m] (v : m → α) (w : m → α) (x : m) : vec_mul v (diagonal w) x = v x * w x := dot_product_diagonal' v w x @[simp] theorem mul_vec_one {m : Type u_2} [fintype m] {α : Type v} [semiring α] [DecidableEq m] (v : m → α) : mul_vec 1 v = v := sorry @[simp] theorem vec_mul_one {m : Type u_2} [fintype m] {α : Type v} [semiring α] [DecidableEq m] (v : m → α) : vec_mul v 1 = v := sorry @[simp] theorem mul_vec_zero {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {α : Type v} [semiring α] (A : matrix m n α) : mul_vec A 0 = 0 := sorry @[simp] theorem vec_mul_zero {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {α : Type v} [semiring α] (A : matrix m n α) : vec_mul 0 A = 0 := sorry @[simp] theorem vec_mul_vec_mul {m : Type u_2} {n : Type u_3} {o : Type u_4} [fintype m] [fintype n] [fintype o] {α : Type v} [semiring α] (v : m → α) (M : matrix m n α) (N : matrix n o α) : vec_mul (vec_mul v M) N = vec_mul v (matrix.mul M N) := funext fun (x : o) => dot_product_assoc v (fun (i : m) (j : n) => M i j) fun (i : n) => N i x @[simp] theorem mul_vec_mul_vec {m : Type u_2} {n : Type u_3} {o : Type u_4} [fintype m] [fintype n] [fintype o] {α : Type v} [semiring α] (v : o → α) (M : matrix m n α) (N : matrix n o α) : mul_vec M (mul_vec N v) = mul_vec (matrix.mul M N) v := funext fun (x : m) => Eq.symm (dot_product_assoc (fun (j : n) => M x j) (fun (i : n) (j : o) => N i j) v) theorem vec_mul_vec_eq {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {α : Type v} [semiring α] (w : m → α) (v : n → α) : vec_mul_vec w v = matrix.mul (col w) (row v) := sorry /-- `std_basis_matrix i j a` is the matrix with `a` in the `i`-th row, `j`-th column, and zeroes elsewhere. -/ def std_basis_matrix {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {α : Type v} [semiring α] [DecidableEq m] [DecidableEq n] (i : m) (j : n) (a : α) : matrix m n α := fun (i' : m) (j' : n) => ite (i' = i ∧ j' = j) a 0 @[simp] theorem smul_std_basis_matrix {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {α : Type v} [semiring α] [DecidableEq m] [DecidableEq n] (i : m) (j : n) (a : α) (b : α) : b • std_basis_matrix i j a = std_basis_matrix i j (b • a) := sorry @[simp] theorem std_basis_matrix_zero {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {α : Type v} [semiring α] [DecidableEq m] [DecidableEq n] (i : m) (j : n) : std_basis_matrix i j 0 = 0 := sorry theorem std_basis_matrix_add {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {α : Type v} [semiring α] [DecidableEq m] [DecidableEq n] (i : m) (j : n) (a : α) (b : α) : std_basis_matrix i j (a + b) = std_basis_matrix i j a + std_basis_matrix i j b := sorry theorem matrix_eq_sum_std_basis {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {α : Type v} [semiring α] [DecidableEq m] [DecidableEq n] (x : matrix n m α) : x = finset.sum finset.univ fun (i : n) => finset.sum finset.univ fun (j : m) => std_basis_matrix i j (x i j) := sorry -- TODO: tie this up with the `basis` machinery of linear algebra -- this is not completely trivial because we are indexing by two types, instead of one -- TODO: add `std_basis_vec` theorem std_basis_eq_basis_mul_basis {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] [DecidableEq m] [DecidableEq n] (i : m) (j : n) : std_basis_matrix i j 1 = vec_mul_vec (fun (i' : m) => ite (i = i') 1 0) fun (j' : n) => ite (j = j') 1 0 := sorry protected theorem induction_on' {n : Type u_3} [fintype n] [DecidableEq n] {X : Type u_1} [semiring X] {M : matrix n n X → Prop} (m : matrix n n X) (h_zero : M 0) (h_add : ∀ (p q : matrix n n X), M p → M q → M (p + q)) (h_std_basis : ∀ (i j : n) (x : X), M (std_basis_matrix i j x)) : M m := sorry protected theorem induction_on {n : Type u_3} [fintype n] [DecidableEq n] [Nonempty n] {X : Type u_1} [semiring X] {M : matrix n n X → Prop} (m : matrix n n X) (h_add : ∀ (p q : matrix n n X), M p → M q → M (p + q)) (h_std_basis : ∀ (i j : n) (x : X), M (std_basis_matrix i j x)) : M m := sorry theorem neg_vec_mul {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {α : Type v} [ring α] (v : m → α) (A : matrix m n α) : vec_mul (-v) A = -vec_mul v A := funext fun (x : n) => neg_dot_product v fun (i : m) => A i x theorem vec_mul_neg {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {α : Type v} [ring α] (v : m → α) (A : matrix m n α) : vec_mul v (-A) = -vec_mul v A := funext fun (x : n) => dot_product_neg v fun (i : m) => A i x theorem neg_mul_vec {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {α : Type v} [ring α] (v : n → α) (A : matrix m n α) : mul_vec (-A) v = -mul_vec A v := funext fun (x : m) => neg_dot_product (fun (i : n) => A x i) v theorem mul_vec_neg {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {α : Type v} [ring α] (v : n → α) (A : matrix m n α) : mul_vec A (-v) = -mul_vec A v := funext fun (x : m) => dot_product_neg (fun (j : n) => A x j) v theorem smul_mul_vec_assoc {n : Type u_3} [fintype n] {α : Type v} [ring α] (A : matrix n n α) (b : n → α) (a : α) : mul_vec (a • A) b = a • mul_vec A b := sorry /-- Tell `simp` what the entries are in a transposed matrix. Compare with `mul_apply`, `diagonal_apply_eq`, etc. -/ @[simp] theorem transpose_apply {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {α : Type v} (M : matrix m n α) (i : m) (j : n) : transpose M j i = M i j := rfl @[simp] theorem transpose_transpose {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {α : Type v} (M : matrix m n α) : transpose (transpose M) = M := ext fun (i : m) (j : n) => Eq.refl (transpose (transpose M) i j) @[simp] theorem transpose_zero {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {α : Type v} [HasZero α] : transpose 0 = 0 := ext fun (i : n) (j : m) => Eq.refl (transpose 0 i j) @[simp] theorem transpose_one {n : Type u_3} [fintype n] {α : Type v} [DecidableEq n] [HasZero α] [HasOne α] : transpose 1 = 1 := sorry @[simp] theorem transpose_add {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {α : Type v} [Add α] (M : matrix m n α) (N : matrix m n α) : transpose (M + N) = transpose M + transpose N := sorry @[simp] theorem transpose_sub {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {α : Type v} [add_group α] (M : matrix m n α) (N : matrix m n α) : transpose (M - N) = transpose M - transpose N := sorry @[simp] theorem transpose_mul {l : Type u_1} {m : Type u_2} {n : Type u_3} [fintype l] [fintype m] [fintype n] {α : Type v} [comm_semiring α] (M : matrix m n α) (N : matrix n l α) : transpose (matrix.mul M N) = matrix.mul (transpose N) (transpose M) := ext fun (i : l) (j : m) => dot_product_comm (fun (i : n) => (fun (j_1 : n) => M j j_1) i) fun (i_1 : n) => (fun (j : n) => N j i) i_1 @[simp] theorem transpose_smul {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {α : Type v} [semiring α] (c : α) (M : matrix m n α) : transpose (c • M) = c • transpose M := ext fun (i : n) (j : m) => Eq.refl (transpose (c • M) i j) @[simp] theorem transpose_neg {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {α : Type v} [Neg α] (M : matrix m n α) : transpose (-M) = -transpose M := ext fun (i : n) (j : m) => Eq.refl (transpose (-M) i j) theorem transpose_map {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {α : Type v} {β : Type w} {f : α → β} {M : matrix m n α} : map (transpose M) f = transpose (map M f) := ext fun (i : n) (j : m) => Eq.refl (map (transpose M) f i j) /-- When `R` is a *-(semi)ring, `matrix n n R` becomes a *-(semi)ring with the star operation given by taking the conjugate, and the star of each entry. -/ protected instance star_ring {n : Type u_3} [fintype n] [DecidableEq n] {R : Type u_5} [semiring R] [star_ring R] : star_ring (matrix n n R) := star_ring.mk sorry @[simp] theorem star_apply {n : Type u_3} [fintype n] [DecidableEq n] {R : Type u_5} [semiring R] [star_ring R] (M : matrix n n R) (i : n) (j : n) : star M i j = star (M j i) := rfl /-- `M.minor row col` is the matrix obtained by reindexing the rows and the lines of `M`, such that `M.minor row col i j = M (row i) (col j)`. Note that the total number of row/colums doesn't have to be preserved. -/ def minor {l : Type u_1} {m : Type u_2} {n : Type u_3} {o : Type u_4} [fintype l] [fintype m] [fintype n] [fintype o] {α : Type v} (A : matrix m n α) (row : l → m) (col : o → n) : matrix l o α := fun (i : l) (j : o) => A (row i) (col j) /-- The left `n × l` part of a `n × (l+r)` matrix. -/ def sub_left {α : Type v} {m : ℕ} {l : ℕ} {r : ℕ} (A : matrix (fin m) (fin (l + r)) α) : matrix (fin m) (fin l) α := minor A id ⇑(fin.cast_add r) /-- The right `n × r` part of a `n × (l+r)` matrix. -/ def sub_right {α : Type v} {m : ℕ} {l : ℕ} {r : ℕ} (A : matrix (fin m) (fin (l + r)) α) : matrix (fin m) (fin r) α := minor A id ⇑(fin.nat_add l) /-- The top `u × n` part of a `(u+d) × n` matrix. -/ def sub_up {α : Type v} {d : ℕ} {u : ℕ} {n : ℕ} (A : matrix (fin (u + d)) (fin n) α) : matrix (fin u) (fin n) α := minor A (⇑(fin.cast_add d)) id /-- The bottom `d × n` part of a `(u+d) × n` matrix. -/ def sub_down {α : Type v} {d : ℕ} {u : ℕ} {n : ℕ} (A : matrix (fin (u + d)) (fin n) α) : matrix (fin d) (fin n) α := minor A (⇑(fin.nat_add u)) id /-- The top-right `u × r` part of a `(u+d) × (l+r)` matrix. -/ def sub_up_right {α : Type v} {d : ℕ} {u : ℕ} {l : ℕ} {r : ℕ} (A : matrix (fin (u + d)) (fin (l + r)) α) : matrix (fin u) (fin r) α := sub_up (sub_right A) /-- The bottom-right `d × r` part of a `(u+d) × (l+r)` matrix. -/ def sub_down_right {α : Type v} {d : ℕ} {u : ℕ} {l : ℕ} {r : ℕ} (A : matrix (fin (u + d)) (fin (l + r)) α) : matrix (fin d) (fin r) α := sub_down (sub_right A) /-- The top-left `u × l` part of a `(u+d) × (l+r)` matrix. -/ def sub_up_left {α : Type v} {d : ℕ} {u : ℕ} {l : ℕ} {r : ℕ} (A : matrix (fin (u + d)) (fin (l + r)) α) : matrix (fin u) (fin l) α := sub_up (sub_left A) /-- The bottom-left `d × l` part of a `(u+d) × (l+r)` matrix. -/ def sub_down_left {α : Type v} {d : ℕ} {u : ℕ} {l : ℕ} {r : ℕ} (A : matrix (fin (u + d)) (fin (l + r)) α) : matrix (fin d) (fin l) α := sub_down (sub_left A) /-! ### `row_col` section Simplification lemmas for `matrix.row` and `matrix.col`. -/ @[simp] theorem col_add {m : Type u_2} [fintype m] {α : Type v} [semiring α] (v : m → α) (w : m → α) : col (v + w) = col v + col w := ext fun (i : m) (j : Unit) => Eq.refl (col (v + w) i j) @[simp] theorem col_smul {m : Type u_2} [fintype m] {α : Type v} [semiring α] (x : α) (v : m → α) : col (x • v) = x • col v := ext fun (i : m) (j : Unit) => Eq.refl (col (x • v) i j) @[simp] theorem row_add {m : Type u_2} [fintype m] {α : Type v} [semiring α] (v : m → α) (w : m → α) : row (v + w) = row v + row w := ext fun (i : Unit) (j : m) => Eq.refl (row (v + w) i j) @[simp] theorem row_smul {m : Type u_2} [fintype m] {α : Type v} [semiring α] (x : α) (v : m → α) : row (x • v) = x • row v := ext fun (i : Unit) (j : m) => Eq.refl (row (x • v) i j) @[simp] theorem col_apply {m : Type u_2} [fintype m] {α : Type v} (v : m → α) (i : m) (j : Unit) : col v i j = v i := rfl @[simp] theorem row_apply {m : Type u_2} [fintype m] {α : Type v} (v : m → α) (i : Unit) (j : m) : row v i j = v j := rfl @[simp] theorem transpose_col {m : Type u_2} [fintype m] {α : Type v} (v : m → α) : transpose (col v) = row v := ext fun (i : Unit) (j : m) => Eq.refl (transpose (col v) i j) @[simp] theorem transpose_row {m : Type u_2} [fintype m] {α : Type v} (v : m → α) : transpose (row v) = col v := ext fun (i : m) (j : Unit) => Eq.refl (transpose (row v) i j) theorem row_vec_mul {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {α : Type v} [semiring α] (M : matrix m n α) (v : m → α) : row (vec_mul v M) = matrix.mul (row v) M := ext fun (i : Unit) (j : n) => Eq.refl (row (vec_mul v M) i j) theorem col_vec_mul {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {α : Type v} [semiring α] (M : matrix m n α) (v : m → α) : col (vec_mul v M) = transpose (matrix.mul (row v) M) := ext fun (i : n) (j : Unit) => Eq.refl (col (vec_mul v M) i j) theorem col_mul_vec {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {α : Type v} [semiring α] (M : matrix m n α) (v : n → α) : col (mul_vec M v) = matrix.mul M (col v) := ext fun (i : m) (j : Unit) => Eq.refl (col (mul_vec M v) i j) theorem row_mul_vec {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {α : Type v} [semiring α] (M : matrix m n α) (v : n → α) : row (mul_vec M v) = transpose (matrix.mul M (col v)) := ext fun (i : Unit) (j : m) => Eq.refl (row (mul_vec M v) i j) /-- Update, i.e. replace the `i`th row of matrix `A` with the values in `b`. -/ def update_row {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {α : Type v} [DecidableEq n] (M : matrix n m α) (i : n) (b : m → α) : matrix n m α := function.update M i b /-- Update, i.e. replace the `j`th column of matrix `A` with the values in `b`. -/ def update_column {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {α : Type v} [DecidableEq m] (M : matrix n m α) (j : m) (b : n → α) : matrix n m α := fun (i : n) => function.update (M i) j (b i) @[simp] theorem update_row_self {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {α : Type v} {M : matrix n m α} {i : n} {b : m → α} [DecidableEq n] : update_row M i b i = b := function.update_same i b M @[simp] theorem update_column_self {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {α : Type v} {M : matrix n m α} {i : n} {j : m} {c : n → α} [DecidableEq m] : update_column M j c i j = c i := function.update_same j (c i) (M i) @[simp] theorem update_row_ne {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {α : Type v} {M : matrix n m α} {i : n} {b : m → α} [DecidableEq n] {i' : n} (i_ne : i' ≠ i) : update_row M i b i' = M i' := function.update_noteq i_ne b M @[simp] theorem update_column_ne {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {α : Type v} {M : matrix n m α} {i : n} {j : m} {c : n → α} [DecidableEq m] {j' : m} (j_ne : j' ≠ j) : update_column M j c i j' = M i j' := function.update_noteq j_ne (c i) (M i) theorem update_row_apply {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {α : Type v} {M : matrix n m α} {i : n} {j : m} {b : m → α} [DecidableEq n] {i' : n} : update_row M i b i' j = ite (i' = i) (b j) (M i' j) := sorry theorem update_column_apply {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {α : Type v} {M : matrix n m α} {i : n} {j : m} {c : n → α} [DecidableEq m] {j' : m} : update_column M j c i j' = ite (j' = j) (c i) (M i j') := sorry theorem update_row_transpose {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {α : Type v} {M : matrix n m α} {j : m} {c : n → α} [DecidableEq m] : update_row (transpose M) j c = transpose (update_column M j c) := sorry theorem update_column_transpose {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {α : Type v} {M : matrix n m α} {i : n} {b : m → α} [DecidableEq n] : update_column (transpose M) i b = transpose (update_row M i b) := sorry /-- We can form a single large matrix by flattening smaller 'block' matrices of compatible dimensions. -/ def from_blocks {l : Type u_1} {m : Type u_2} {n : Type u_3} {o : Type u_4} [fintype l] [fintype m] [fintype n] [fintype o] {α : Type v} (A : matrix n l α) (B : matrix n m α) (C : matrix o l α) (D : matrix o m α) : matrix (n ⊕ o) (l ⊕ m) α := sum.elim (fun (i : n) => sum.elim (A i) (B i)) fun (i : o) => sum.elim (C i) (D i) @[simp] theorem from_blocks_apply₁₁ {l : Type u_1} {m : Type u_2} {n : Type u_3} {o : Type u_4} [fintype l] [fintype m] [fintype n] [fintype o] {α : Type v} (A : matrix n l α) (B : matrix n m α) (C : matrix o l α) (D : matrix o m α) (i : n) (j : l) : from_blocks A B C D (sum.inl i) (sum.inl j) = A i j := rfl @[simp] theorem from_blocks_apply₁₂ {l : Type u_1} {m : Type u_2} {n : Type u_3} {o : Type u_4} [fintype l] [fintype m] [fintype n] [fintype o] {α : Type v} (A : matrix n l α) (B : matrix n m α) (C : matrix o l α) (D : matrix o m α) (i : n) (j : m) : from_blocks A B C D (sum.inl i) (sum.inr j) = B i j := rfl @[simp] theorem from_blocks_apply₂₁ {l : Type u_1} {m : Type u_2} {n : Type u_3} {o : Type u_4} [fintype l] [fintype m] [fintype n] [fintype o] {α : Type v} (A : matrix n l α) (B : matrix n m α) (C : matrix o l α) (D : matrix o m α) (i : o) (j : l) : from_blocks A B C D (sum.inr i) (sum.inl j) = C i j := rfl @[simp] theorem from_blocks_apply₂₂ {l : Type u_1} {m : Type u_2} {n : Type u_3} {o : Type u_4} [fintype l] [fintype m] [fintype n] [fintype o] {α : Type v} (A : matrix n l α) (B : matrix n m α) (C : matrix o l α) (D : matrix o m α) (i : o) (j : m) : from_blocks A B C D (sum.inr i) (sum.inr j) = D i j := rfl /-- Given a matrix whose row and column indexes are sum types, we can extract the correspnding "top left" submatrix. -/ def to_blocks₁₁ {l : Type u_1} {m : Type u_2} {n : Type u_3} {o : Type u_4} [fintype l] [fintype m] [fintype n] [fintype o] {α : Type v} (M : matrix (n ⊕ o) (l ⊕ m) α) : matrix n l α := fun (i : n) (j : l) => M (sum.inl i) (sum.inl j) /-- Given a matrix whose row and column indexes are sum types, we can extract the correspnding "top right" submatrix. -/ def to_blocks₁₂ {l : Type u_1} {m : Type u_2} {n : Type u_3} {o : Type u_4} [fintype l] [fintype m] [fintype n] [fintype o] {α : Type v} (M : matrix (n ⊕ o) (l ⊕ m) α) : matrix n m α := fun (i : n) (j : m) => M (sum.inl i) (sum.inr j) /-- Given a matrix whose row and column indexes are sum types, we can extract the correspnding "bottom left" submatrix. -/ def to_blocks₂₁ {l : Type u_1} {m : Type u_2} {n : Type u_3} {o : Type u_4} [fintype l] [fintype m] [fintype n] [fintype o] {α : Type v} (M : matrix (n ⊕ o) (l ⊕ m) α) : matrix o l α := fun (i : o) (j : l) => M (sum.inr i) (sum.inl j) /-- Given a matrix whose row and column indexes are sum types, we can extract the correspnding "bottom right" submatrix. -/ def to_blocks₂₂ {l : Type u_1} {m : Type u_2} {n : Type u_3} {o : Type u_4} [fintype l] [fintype m] [fintype n] [fintype o] {α : Type v} (M : matrix (n ⊕ o) (l ⊕ m) α) : matrix o m α := fun (i : o) (j : m) => M (sum.inr i) (sum.inr j) theorem from_blocks_to_blocks {l : Type u_1} {m : Type u_2} {n : Type u_3} {o : Type u_4} [fintype l] [fintype m] [fintype n] [fintype o] {α : Type v} (M : matrix (n ⊕ o) (l ⊕ m) α) : from_blocks (to_blocks₁₁ M) (to_blocks₁₂ M) (to_blocks₂₁ M) (to_blocks₂₂ M) = M := sorry @[simp] theorem to_blocks_from_blocks₁₁ {l : Type u_1} {m : Type u_2} {n : Type u_3} {o : Type u_4} [fintype l] [fintype m] [fintype n] [fintype o] {α : Type v} (A : matrix n l α) (B : matrix n m α) (C : matrix o l α) (D : matrix o m α) : to_blocks₁₁ (from_blocks A B C D) = A := rfl @[simp] theorem to_blocks_from_blocks₁₂ {l : Type u_1} {m : Type u_2} {n : Type u_3} {o : Type u_4} [fintype l] [fintype m] [fintype n] [fintype o] {α : Type v} (A : matrix n l α) (B : matrix n m α) (C : matrix o l α) (D : matrix o m α) : to_blocks₁₂ (from_blocks A B C D) = B := rfl @[simp] theorem to_blocks_from_blocks₂₁ {l : Type u_1} {m : Type u_2} {n : Type u_3} {o : Type u_4} [fintype l] [fintype m] [fintype n] [fintype o] {α : Type v} (A : matrix n l α) (B : matrix n m α) (C : matrix o l α) (D : matrix o m α) : to_blocks₂₁ (from_blocks A B C D) = C := rfl @[simp] theorem to_blocks_from_blocks₂₂ {l : Type u_1} {m : Type u_2} {n : Type u_3} {o : Type u_4} [fintype l] [fintype m] [fintype n] [fintype o] {α : Type v} (A : matrix n l α) (B : matrix n m α) (C : matrix o l α) (D : matrix o m α) : to_blocks₂₂ (from_blocks A B C D) = D := rfl theorem from_blocks_transpose {l : Type u_1} {m : Type u_2} {n : Type u_3} {o : Type u_4} [fintype l] [fintype m] [fintype n] [fintype o] {α : Type v} (A : matrix n l α) (B : matrix n m α) (C : matrix o l α) (D : matrix o m α) : transpose (from_blocks A B C D) = from_blocks (transpose A) (transpose C) (transpose B) (transpose D) := sorry theorem from_blocks_smul {l : Type u_1} {m : Type u_2} {n : Type u_3} {o : Type u_4} [fintype l] [fintype m] [fintype n] [fintype o] {α : Type v} [semiring α] (x : α) (A : matrix n l α) (B : matrix n m α) (C : matrix o l α) (D : matrix o m α) : x • from_blocks A B C D = from_blocks (x • A) (x • B) (x • C) (x • D) := sorry theorem from_blocks_add {l : Type u_1} {m : Type u_2} {n : Type u_3} {o : Type u_4} [fintype l] [fintype m] [fintype n] [fintype o] {α : Type v} [semiring α] (A : matrix n l α) (B : matrix n m α) (C : matrix o l α) (D : matrix o m α) (A' : matrix n l α) (B' : matrix n m α) (C' : matrix o l α) (D' : matrix o m α) : from_blocks A B C D + from_blocks A' B' C' D' = from_blocks (A + A') (B + B') (C + C') (D + D') := sorry theorem from_blocks_multiply {l : Type u_1} {m : Type u_2} {n : Type u_3} {o : Type u_4} [fintype l] [fintype m] [fintype n] [fintype o] {α : Type v} [semiring α] {p : Type u_5} {q : Type u_6} [fintype p] [fintype q] (A : matrix n l α) (B : matrix n m α) (C : matrix o l α) (D : matrix o m α) (A' : matrix l p α) (B' : matrix l q α) (C' : matrix m p α) (D' : matrix m q α) : matrix.mul (from_blocks A B C D) (from_blocks A' B' C' D') = from_blocks (matrix.mul A A' + matrix.mul B C') (matrix.mul A B' + matrix.mul B D') (matrix.mul C A' + matrix.mul D C') (matrix.mul C B' + matrix.mul D D') := sorry @[simp] theorem from_blocks_diagonal {l : Type u_1} {m : Type u_2} [fintype l] [fintype m] {α : Type v} [semiring α] [DecidableEq l] [DecidableEq m] (d₁ : l → α) (d₂ : m → α) : from_blocks (diagonal d₁) 0 0 (diagonal d₂) = diagonal (sum.elim d₁ d₂) := sorry @[simp] theorem from_blocks_one {l : Type u_1} {m : Type u_2} [fintype l] [fintype m] {α : Type v} [semiring α] [DecidableEq l] [DecidableEq m] : from_blocks 1 0 0 1 = 1 := sorry /-- `matrix.block_diagonal M` turns `M : o → matrix m n α'` into a `m × o`-by`n × o` block matrix which has the entries of `M` along the diagonal and zero elsewhere. -/ def block_diagonal {m : Type u_2} {n : Type u_3} {o : Type u_4} [fintype m] [fintype n] [fintype o] {α : Type v} (M : o → matrix m n α) [DecidableEq o] [HasZero α] : matrix (m × o) (n × o) α := sorry theorem block_diagonal_apply {m : Type u_2} {n : Type u_3} {o : Type u_4} [fintype m] [fintype n] [fintype o] {α : Type v} (M : o → matrix m n α) [DecidableEq o] [HasZero α] (ik : m × o) (jk : n × o) : block_diagonal M ik jk = ite (prod.snd ik = prod.snd jk) (M (prod.snd ik) (prod.fst ik) (prod.fst jk)) 0 := prod.cases_on ik fun (ik_fst : m) (ik_snd : o) => prod.cases_on jk fun (jk_fst : n) (jk_snd : o) => Eq.refl (block_diagonal M (ik_fst, ik_snd) (jk_fst, jk_snd)) @[simp] theorem block_diagonal_apply_eq {m : Type u_2} {n : Type u_3} {o : Type u_4} [fintype m] [fintype n] [fintype o] {α : Type v} (M : o → matrix m n α) [DecidableEq o] [HasZero α] (i : m) (j : n) (k : o) : block_diagonal M (i, k) (j, k) = M k i j := if_pos rfl theorem block_diagonal_apply_ne {m : Type u_2} {n : Type u_3} {o : Type u_4} [fintype m] [fintype n] [fintype o] {α : Type v} (M : o → matrix m n α) [DecidableEq o] [HasZero α] (i : m) (j : n) {k : o} {k' : o} (h : k ≠ k') : block_diagonal M (i, k) (j, k') = 0 := if_neg h @[simp] theorem block_diagonal_transpose {m : Type u_2} {n : Type u_3} {o : Type u_4} [fintype m] [fintype n] [fintype o] {α : Type v} (M : o → matrix m n α) [DecidableEq o] [HasZero α] : transpose (block_diagonal M) = block_diagonal fun (k : o) => transpose (M k) := sorry @[simp] theorem block_diagonal_zero {m : Type u_2} {n : Type u_3} {o : Type u_4} [fintype m] [fintype n] [fintype o] {α : Type v} [DecidableEq o] [HasZero α] : block_diagonal 0 = 0 := sorry @[simp] theorem block_diagonal_diagonal {m : Type u_2} {o : Type u_4} [fintype m] [fintype o] {α : Type v} [DecidableEq o] [HasZero α] [DecidableEq m] (d : o → m → α) : (block_diagonal fun (k : o) => diagonal (d k)) = diagonal fun (ik : m × o) => d (prod.snd ik) (prod.fst ik) := sorry @[simp] theorem block_diagonal_one {m : Type u_2} {o : Type u_4} [fintype m] [fintype o] {α : Type v} [DecidableEq o] [HasZero α] [DecidableEq m] [HasOne α] : block_diagonal 1 = 1 := sorry @[simp] theorem block_diagonal_add {m : Type u_2} {n : Type u_3} {o : Type u_4} [fintype m] [fintype n] [fintype o] {α : Type v} (M : o → matrix m n α) (N : o → matrix m n α) [DecidableEq o] [add_monoid α] : block_diagonal (M + N) = block_diagonal M + block_diagonal N := sorry @[simp] theorem block_diagonal_neg {m : Type u_2} {n : Type u_3} {o : Type u_4} [fintype m] [fintype n] [fintype o] {α : Type v} (M : o → matrix m n α) [DecidableEq o] [add_group α] : block_diagonal (-M) = -block_diagonal M := sorry @[simp] theorem block_diagonal_sub {m : Type u_2} {n : Type u_3} {o : Type u_4} [fintype m] [fintype n] [fintype o] {α : Type v} (M : o → matrix m n α) (N : o → matrix m n α) [DecidableEq o] [add_group α] : block_diagonal (M - N) = block_diagonal M - block_diagonal N := sorry @[simp] theorem block_diagonal_mul {m : Type u_2} {n : Type u_3} {o : Type u_4} [fintype m] [fintype n] [fintype o] {α : Type v} (M : o → matrix m n α) [DecidableEq o] {p : Type u_1} [fintype p] [semiring α] (N : o → matrix n p α) : (block_diagonal fun (k : o) => matrix.mul (M k) (N k)) = matrix.mul (block_diagonal M) (block_diagonal N) := sorry @[simp] theorem block_diagonal_smul {m : Type u_2} {n : Type u_3} {o : Type u_4} [fintype m] [fintype n] [fintype o] {α : Type v} (M : o → matrix m n α) [DecidableEq o] {R : Type u_1} [semiring R] [add_comm_monoid α] [semimodule R α] (x : R) : block_diagonal (x • M) = x • block_diagonal M := sorry end matrix namespace ring_hom theorem map_matrix_mul {m : Type u_2} {n : Type u_3} {o : Type u_4} [fintype m] [fintype n] [fintype o] {α : Type v} {β : Type u_5} [semiring α] [semiring β] (M : matrix m n α) (N : matrix n o α) (i : m) (j : o) (f : α →+* β) : coe_fn f (matrix.mul M N i j) = matrix.mul (fun (i : m) (j : n) => coe_fn f (M i j)) (fun (i : n) (j : o) => coe_fn f (N i j)) i j := sorry end Mathlib
f80a0b7cd1ea68628b344b7fd4f11f01d1885ce4
c8b4b578b2fe61d500fbca7480e506f6603ea698
/src/caseII/statement.lean
496ac273097a9358da573bf6d924c9142c5559fd
[]
no_license
leanprover-community/flt-regular
aa7e564f2679dfd2e86015a5a9674a6e1197f7cc
67fb3e176584bbc03616c221a7be6fa28c5ccd32
refs/heads/master
1,692,188,905,751
1,691,766,312,000
1,691,766,312,000
421,021,216
19
4
null
1,694,532,115,000
1,635,166,136,000
Lean
UTF-8
Lean
false
false
524
lean
import may_assume.lemmas namespace flt_regular /-- Statement of case II. -/ def caseII.statement : Prop := ∀ ⦃a b c : ℤ⦄ ⦃p : ℕ⦄ [hp : fact p.prime] (hreg : @is_regular_prime p hp) (hodd : p ≠ 2) (hprod : a * b * c ≠ 0) (caseII : ↑p ∣ a * b * c), a ^ p + b ^ p ≠ c ^ p /-- CaseII. -/ theorem caseII {a b c : ℤ} {p : ℕ} [fact p.prime] (hreg : is_regular_prime p) (hodd : p ≠ 2) (hprod : a * b * c ≠ 0) (caseII : ↑p ∣ a * b * c) : a ^ p + b ^ p ≠ c ^ p := sorry end flt_regular
c5adbbc56291aaa711c6ab09a73ae8238c72670e
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/stage0/src/Init/Data/List/BasicAux.lean
566881697f965950e8df5d024d7c2bd9450a7668
[ "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
6,125
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ prelude import Init.Data.Nat.Linear import Init.Data.List.Basic import Init.Util universe u namespace List /-! The following functions can't be defined at `Init.Data.List.Basic`, because they depend on `Init.Util`, and `Init.Util` depends on `Init.Data.List.Basic`. -/ def get! [Inhabited α] : List α → Nat → α | a::_, 0 => a | _::as, n+1 => get! as n | _, _ => panic! "invalid index" def get? : List α → Nat → Option α | a::_, 0 => some a | _::as, n+1 => get? as n | _, _ => none def getD (as : List α) (idx : Nat) (a₀ : α) : α := (as.get? idx).getD a₀ def head! [Inhabited α] : List α → α | [] => panic! "empty list" | a::_ => a def head? : List α → Option α | [] => none | a::_ => some a def headD : List α → α → α | [], a₀ => a₀ | a::_, _ => a def head : (as : List α) → as ≠ [] → α | a::_, _ => a def tail! : List α → List α | [] => panic! "empty list" | _::as => as def tail? : List α → Option (List α) | [] => none | _::as => some as def tailD : List α → List α → List α | [], as₀ => as₀ | _::as, _ => as def getLast : ∀ (as : List α), as ≠ [] → α | [], h => absurd rfl h | [a], _ => a | _::b::as, _ => getLast (b::as) (fun h => List.noConfusion h) def getLast! [Inhabited α] : List α → α | [] => panic! "empty list" | a::as => getLast (a::as) (fun h => List.noConfusion h) def getLast? : List α → Option α | [] => none | a::as => some (getLast (a::as) (fun h => List.noConfusion h)) def getLastD : List α → α → α | [], a₀ => a₀ | a::as, _ => getLast (a::as) (fun h => List.noConfusion h) def rotateLeft (xs : List α) (n : Nat := 1) : List α := let len := xs.length if len ≤ 1 then xs else let n := n % len let b := xs.take n let e := xs.drop n e ++ b def rotateRight (xs : List α) (n : Nat := 1) : List α := let len := xs.length if len ≤ 1 then xs else let n := len - n % len let b := xs.take n let e := xs.drop n e ++ b theorem get_append_left (as bs : List α) (h : i < as.length) {h'} : (as ++ bs).get ⟨i, h'⟩ = as.get ⟨i, h⟩ := by induction as generalizing i with | nil => trivial | cons a as ih => cases i with | zero => rfl | succ i => apply ih theorem get_append_right (as bs : List α) (h : ¬ i < as.length) {h' h''} : (as ++ bs).get ⟨i, h'⟩ = bs.get ⟨i - as.length, h''⟩ := by induction as generalizing i with | nil => trivial | cons a as ih => cases i with simp [get, Nat.succ_sub_succ] <;> simp_arith [Nat.succ_sub_succ] at h | succ i => apply ih; simp_arith [h] theorem get_last {as : List α} {i : Fin (length (as ++ [a]))} (h : ¬ i.1 < as.length) : (as ++ [a] : List _).get i = a := by cases i; rename_i i h' induction as generalizing i with | nil => cases i with | zero => simp [List.get] | succ => simp_arith at h' | cons a as ih => cases i with simp_arith at h | succ i => apply ih; simp_arith [h] theorem sizeOf_lt_of_mem [SizeOf α] {as : List α} (h : a ∈ as) : sizeOf a < sizeOf as := by induction h with | head => simp_arith | tail _ _ ih => exact Nat.lt_trans ih (by simp_arith) /-- This tactic, added to the `decreasing_trivial` toolbox, proves that `sizeOf a < sizeOf as` when `a ∈ as`, which is useful for well founded recursions over a nested inductive like `inductive T | mk : List T → T`. -/ macro "sizeOf_list_dec" : tactic => `(first | apply sizeOf_lt_of_mem; assumption; done | apply Nat.lt_trans (sizeOf_lt_of_mem ?h) case' h => assumption simp_arith) macro_rules | `(tactic| decreasing_trivial) => `(tactic| sizeOf_list_dec) theorem append_cancel_left {as bs cs : List α} (h : as ++ bs = as ++ cs) : bs = cs := by induction as with | nil => assumption | cons a as ih => injection h with _ h exact ih h theorem append_cancel_right {as bs cs : List α} (h : as ++ bs = cs ++ bs) : as = cs := by match as, cs with | [], [] => rfl | [], c::cs => have aux := congrArg length h; simp_arith at aux | a::as, [] => have aux := congrArg length h; simp_arith at aux | a::as, c::cs => injection h with h₁ h₂; subst h₁; rw [append_cancel_right h₂] @[simp] theorem append_cancel_left_eq (as bs cs : List α) : (as ++ bs = as ++ cs) = (bs = cs) := by apply propext; apply Iff.intro next => apply append_cancel_left next => intro h; simp [h] @[simp] theorem append_cancel_right_eq (as bs cs : List α) : (as ++ bs = cs ++ bs) = (as = cs) := by apply propext; apply Iff.intro next => apply append_cancel_right next => intro h; simp [h] @[simp] theorem sizeOf_get [SizeOf α] (as : List α) (i : Fin as.length) : sizeOf (as.get i) < sizeOf as := by match as, i with | a::as, ⟨0, _⟩ => simp_arith [get] | a::as, ⟨i+1, h⟩ => have ih := sizeOf_get as ⟨i, Nat.le_of_succ_le_succ h⟩ apply Nat.lt_trans ih simp_arith theorem le_antisymm [LT α] [s : Antisymm (¬ · < · : α → α → Prop)] {as bs : List α} (h₁ : as ≤ bs) (h₂ : bs ≤ as) : as = bs := match as, bs with | [], [] => rfl | [], b::bs => False.elim <| h₂ (List.lt.nil ..) | a::as, [] => False.elim <| h₁ (List.lt.nil ..) | a::as, b::bs => by by_cases hab : a < b · exact False.elim <| h₂ (List.lt.head _ _ hab) · by_cases hba : b < a · exact False.elim <| h₁ (List.lt.head _ _ hba) · have h₁ : as ≤ bs := fun h => h₁ (List.lt.tail hba hab h) have h₂ : bs ≤ as := fun h => h₂ (List.lt.tail hab hba h) have ih : as = bs := le_antisymm h₁ h₂ have : a = b := s.antisymm hab hba simp [this, ih] instance [LT α] [Antisymm (¬ · < · : α → α → Prop)] : Antisymm (· ≤ · : List α → List α → Prop) where antisymm h₁ h₂ := le_antisymm h₁ h₂ end List
d0b8a7f1125168b804a41403d1b482fc993cc1a8
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/algebra/category/Algebra/basic.lean
24769d5efe05cf78ac3000f1802fbfc7be2ac608
[]
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,857
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.algebra.algebra.basic import Mathlib.algebra.algebra.subalgebra import Mathlib.algebra.free_algebra import Mathlib.algebra.category.CommRing.basic import Mathlib.algebra.category.Module.basic import Mathlib.PostPort universes v u l u_1 namespace Mathlib /-- The category of R-modules and their morphisms. -/ structure Algebra (R : Type u) [comm_ring R] where carrier : Type v is_ring : ring carrier is_algebra : algebra R carrier namespace Algebra protected instance has_coe_to_sort (R : Type u) [comm_ring R] : has_coe_to_sort (Algebra R) := has_coe_to_sort.mk (Type v) carrier protected instance category_theory.category (R : Type u) [comm_ring R] : category_theory.category (Algebra R) := category_theory.category.mk protected instance category_theory.concrete_category (R : Type u) [comm_ring R] : category_theory.concrete_category (Algebra R) := category_theory.concrete_category.mk (category_theory.functor.mk (fun (R_1 : Algebra R) => ↥R_1) fun (R_1 S : Algebra R) (f : R_1 ⟶ S) => ⇑f) protected instance has_forget_to_Ring (R : Type u) [comm_ring R] : category_theory.has_forget₂ (Algebra R) Ring := category_theory.has_forget₂.mk (category_theory.functor.mk (fun (A : Algebra R) => Ring.of ↥A) fun (A₁ A₂ : Algebra R) (f : A₁ ⟶ A₂) => alg_hom.to_ring_hom f) protected instance has_forget_to_Module (R : Type u) [comm_ring R] : category_theory.has_forget₂ (Algebra R) (Module R) := category_theory.has_forget₂.mk (category_theory.functor.mk (fun (M : Algebra R) => Module.of R ↥M) fun (M₁ M₂ : Algebra R) (f : M₁ ⟶ M₂) => alg_hom.to_linear_map f) /-- The object in the category of R-algebras associated to a type equipped with the appropriate typeclasses. -/ def of (R : Type u) [comm_ring R] (X : Type v) [ring X] [algebra R X] : Algebra R := mk X protected instance inhabited (R : Type u) [comm_ring R] : Inhabited (Algebra R) := { default := of R R } @[simp] theorem coe_of (R : Type u) [comm_ring R] (X : Type u) [ring X] [algebra R X] : ↥(of R X) = X := rfl /-- Forgetting to the underlying type and then building the bundled object returns the original algebra. -/ @[simp] theorem of_self_iso_hom {R : Type u} [comm_ring R] (M : Algebra R) : category_theory.iso.hom (of_self_iso M) = 𝟙 := Eq.refl (category_theory.iso.hom (of_self_iso M)) @[simp] theorem id_apply {R : Type u} [comm_ring R] {M : Module R} (m : ↥M) : coe_fn 𝟙 m = m := rfl @[simp] theorem coe_comp {R : Type u} [comm_ring R] {M : Module R} {N : Module R} {U : Module R} (f : M ⟶ N) (g : N ⟶ U) : ⇑(f ≫ g) = ⇑g ∘ ⇑f := rfl /-- The "free algebra" functor, sending a type `S` to the free algebra on `S`. -/ @[simp] theorem free_obj_is_algebra (R : Type u) [comm_ring R] (S : Type u_1) : is_algebra (category_theory.functor.obj (free R) S) = free_algebra.algebra R S := Eq.refl (is_algebra (category_theory.functor.obj (free R) S)) /-- The free/forget ajunction for `R`-algebras. -/ def adj (R : Type u) [comm_ring R] : free R ⊣ category_theory.forget (Algebra R) := category_theory.adjunction.mk_of_hom_equiv (category_theory.adjunction.core_hom_equiv.mk fun (X : Type (max u u_1)) (A : Algebra R) => equiv.symm (free_algebra.lift R)) end Algebra /-- Build an isomorphism in the category `Algebra R` from a `alg_equiv` between `algebra`s. -/ @[simp] theorem alg_equiv.to_Algebra_iso_hom {R : Type u} [comm_ring R] {X₁ : Type u} {X₂ : Type u} {g₁ : ring X₁} {g₂ : ring X₂} {m₁ : algebra R X₁} {m₂ : algebra R X₂} (e : alg_equiv R X₁ X₂) : category_theory.iso.hom (alg_equiv.to_Algebra_iso e) = ↑e := Eq.refl (category_theory.iso.hom (alg_equiv.to_Algebra_iso e)) namespace category_theory.iso /-- Build a `alg_equiv` from an isomorphism in the category `Algebra R`. -/ @[simp] theorem to_alg_equiv_apply {R : Type u} [comm_ring R] {X : Algebra R} {Y : Algebra R} (i : X ≅ Y) : ∀ (ᾰ : ↥X), coe_fn (to_alg_equiv i) ᾰ = coe_fn (hom i) ᾰ := fun (ᾰ : ↥X) => Eq.refl (coe_fn (to_alg_equiv i) ᾰ) end category_theory.iso /-- Algebra equivalences between `algebras`s are the same as (isomorphic to) isomorphisms in `Algebra`. -/ def alg_equiv_iso_Algebra_iso {R : Type u} [comm_ring R] {X : Type u} {Y : Type u} [ring X] [ring Y] [algebra R X] [algebra R Y] : alg_equiv R X Y ≅ Algebra.of R X ≅ Algebra.of R Y := category_theory.iso.mk (fun (e : alg_equiv R X Y) => alg_equiv.to_Algebra_iso e) fun (i : Algebra.of R X ≅ Algebra.of R Y) => category_theory.iso.to_alg_equiv i protected instance Algebra.has_coe {R : Type u} [comm_ring R] (X : Type u) [ring X] [algebra R X] : has_coe (subalgebra R X) (Algebra R) := has_coe.mk fun (N : subalgebra R X) => Algebra.of R ↥N protected instance Algebra.forget_reflects_isos {R : Type u} [comm_ring R] : category_theory.reflects_isomorphisms (category_theory.forget (Algebra R)) := category_theory.reflects_isomorphisms.mk fun (X Y : Algebra R) (f : X ⟶ Y) (_x : category_theory.is_iso (category_theory.functor.map (category_theory.forget (Algebra R)) f)) => let i : category_theory.functor.obj (category_theory.forget (Algebra R)) X ≅ category_theory.functor.obj (category_theory.forget (Algebra R)) Y := category_theory.as_iso (category_theory.functor.map (category_theory.forget (Algebra R)) f); let e : alg_equiv R ↥X ↥Y := alg_equiv.mk (alg_hom.to_fun f) (equiv.inv_fun (category_theory.iso.to_equiv i)) sorry sorry sorry sorry sorry; category_theory.is_iso.mk (category_theory.iso.inv (alg_equiv.to_Algebra_iso e))
55512bc19eb9982c841976662778c314c664f725
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/353.lean
d98ee9b01d0514cb605f71a81086f0a6557a03fd
[ "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
479
lean
class ArrSort (α : Sort u1) where Arr : α → α → Sort u2 class Arr (α : Sort u1) (γ : Sort u2) where Arr : α → α → γ infix:70 " ~> " => Arr.Arr @[default_instance] instance inst1 {α : Sort _} [ArrSort α] : Arr α (Sort _) := { Arr := ArrSort.Arr } instance inst2 : ArrSort Prop := { Arr := λ a b => a → b } set_option pp.all true set_option trace.Meta.debug true structure Function' where map : ∀ {a₁ a₂ : Bool}, (a₁ ~> a₂) ~> (a₁ ~> a₂)
57ac70060131c7f2cdb458cd133179aca0d55237
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/tactic3.lean
55e0e576f30aa8141eaeca5fec587d3295096ba3
[ "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
193
lean
import logic open tactic theorem tst {A B : Prop} (H1 : A) (H2 : B) : A := by (trace "first"; state; now | trace "second"; state; fail | trace "third"; assumption) check tst
23b5b7b1a24d91e2982ffe46720e5f73718707c0
ea11767c9c6a467c4b7710ec6f371c95cfc023fd
/src/monoidal_categories/internal_objects/modules.lean
966b1d70f0b6ffce381114409b684e895dbc93b6
[]
no_license
RitaAhmadi/lean-monoidal-categories
68a23f513e902038e44681336b87f659bbc281e0
81f43e1e0d623a96695aa8938951d7422d6d7ba6
refs/heads/master
1,651,458,686,519
1,529,824,613,000
1,529,824,613,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,457
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Stephen Morgan, Scott Morrison import .semigroup_modules import .monoids open categories open categories.monoidal_category namespace categories.internal_objects universes u v open MonoidObject structure ModuleObject {C : Type u} [𝒞 : monoidal_category.{u v} C] (A : C) [MonoidObject A] extends SemigroupModuleObject A := (identity : (inverse_left_unitor module) ≫ ((ι A) ⊗ (𝟙 module)) ≫ action = 𝟙 module) attribute [simp,ematch] ModuleObject.identity variables {C : Type u} [𝒞 : monoidal_category.{u v} C] {A : C} [MonoidObject A] include 𝒞 structure ModuleMorphism ( X Y : ModuleObject A ) extends SemigroupModuleMorphism X.to_SemigroupModuleObject Y.to_SemigroupModuleObject @[applicable] lemma ModuleMorphism_pointwise_equal { X Y : ModuleObject A } ( f g : ModuleMorphism X Y ) ( w : f.map = g.map ) : f = g := begin induction f with f_underlying, induction g with g_underlying, tidy, end definition CategoryOfModules : category.{(max u v) v} (ModuleObject A) := { Hom := λ X Y, ModuleMorphism X Y, identity := λ X, ⟨ ⟨ 𝟙 X.module, by obviously ⟩ ⟩, -- we need double ⟨ ⟨ ... ⟩ ⟩ because we're using structure extension compose := λ _ _ _ f g, ⟨ ⟨ f.map ≫ g.map, by obviously ⟩ ⟩ } end categories.internal_objects
971736b3ee2c8b8b86ed2fce75d667d45f84bb98
ea80d7bb31b9673a3a06d5148363b44b66c53796
/thys/core/generated.lean
f1166676dea1edfeba0bd8bdbba7a635474ea48d
[]
no_license
gitter-badger/electrolysis
2a59d6e0fe1b6629a14a1202e31b1a8ff1c93ced
4f63846e817cb52bdac4ae65ef3d17634e6ffc36
refs/heads/master
1,608,825,996,259
1,467,154,609,000
1,467,154,609,000
62,184,345
0
0
null
null
null
null
UTF-8
Lean
false
false
6,252
lean
import core.pre import data.nat data.list noncomputable theory open classical open int open nat open option open prod.ops open sum namespace core open core inductive cmp.Ordering := | Less {} : cmp.Ordering | Equal {} : cmp.Ordering | Greater {} : cmp.Ordering structure ops.RangeTo (Idx : Type) := mk {} :: (end_ : Idx) structure ops.Range (Idx : Type) := mk {} :: (start : Idx) (end_ : Idx) /- /// Implements slicing with syntax `&self[begin .. end]`. /// /// Returns a slice of self for the index range [`begin`..`end`). /// /// This operation is `O(1)`. /// /// # Panics /// /// Requires that `begin <= end` and `end <= self.len()`, /// otherwise slicing will panic. -/ definition slice._T_.ops_Index_ops_Range_usize__.index {T : Type} (self : slice T) (index : ops.Range usize) := if ops.Range.start index ≤ ops.Range.end_ index ∧ ops.Range.end_ index ≤ list.length self then some (list.firstn (ops.Range.end_ index - ops.Range.start index) (list.dropn (ops.Range.start index) self)) else none definition slice._T_.ops_Index_ops_RangeTo_usize__.index {T : Type} (self : (slice T)) (index : (ops.RangeTo usize)) := let self ← self; let index ← index; let t1 ← self; let t4 ← (0 : nat); let t6 ← (ops.RangeTo.end_ index); let t5 ← t6; let t3 ← ops.Range.mk t4 t5; do tmp__ ← @slice._T_.ops_Index_ops_Range_usize__.index _ t1 t3; let t0 ← tmp__; let ret ← t0; some (ret) structure ops.RangeFrom (Idx : Type) := mk {} :: (start : Idx) definition slice._T_.ops_Index_ops_RangeFrom_usize__.index {T : Type} (self : (slice T)) (index : (ops.RangeFrom usize)) := let self ← self; let index ← index; let t1 ← self; let t5 ← (ops.RangeFrom.start index); let t4 ← t5; let t7 ← self; do tmp__ ← @slice._T_.slice_SliceExt.len _ t7; let t6 ← tmp__; let t3 ← ops.Range.mk t4 t6; do tmp__ ← @slice._T_.ops_Index_ops_Range_usize__.index _ t1 t3; let t0 ← tmp__; let ret ← t0; some (ret) definition slice._T_.slice_SliceExt.split_at {T : Type} (self : (slice T)) (mid : usize) := let self ← self; let mid ← mid; let t3 ← self; let t7 ← mid; let t6 ← t7; let t5 ← ops.RangeTo.mk t6; do tmp__ ← @slice._T_.ops_Index_ops_RangeTo_usize__.index _ t3 t5; let t2 ← tmp__; let t1 ← t2; let t0 ← t1; let t11 ← self; let t14 ← mid; let t13 ← t14; let t12 ← ops.RangeFrom.mk t13; do tmp__ ← @slice._T_.ops_Index_ops_RangeFrom_usize__.index _ t11 t12; let t10 ← tmp__; let t9 ← t10; let t8 ← t9; let ret ← (t0, t8); some (ret) structure slice.SliceExt [class] (Self : Type) (Item : Type) := (len : Self → option (usize)) definition slice._T_.slice_SliceExt [instance] (T : Type) := ⦃ slice.SliceExt (slice T) T, len := slice._T_.slice_SliceExt.len ⦄ definition slice.SliceExt.is_empty {Self : Type} (Item : Type) [slice_SliceExt_Self : slice.SliceExt Self Item] (self : Self) := let self ← self; let t1 ← self; do tmp__ ← @slice.SliceExt.len _ _ slice_SliceExt_Self t1; let t0 ← tmp__; let ret ← t0 = (0 : nat); some (ret) inductive result.Result (T : Type) (E : Type) := | Ok {} : T → result.Result T E | Err {} : E → result.Result T E section parameters {T : Type} {F : Type} parameters [ops_FnMut__T__F : ops.FnMut (T) F (cmp.Ordering )] parameters (self : (slice T)) (f : F) definition slice._T_.slice_SliceExt.binary_search_by.loop_4 state__ := match state__ with (f, base, s) := let t3 ← s; let t6 ← s; do tmp__ ← @slice._T_.slice_SliceExt.len _ t6; let t5 ← tmp__; do tmp__ ← checked.shr t5 (1 : int); let t4 ← tmp__; do tmp__ ← @slice._T_.slice_SliceExt.split_at _ t3 t4; let t2 ← tmp__; let head ← t2.1; let tail ← t2.2; let t9 ← tail; do tmp__ ← @slice.SliceExt.is_empty _ _ (slice._T_.slice_SliceExt T) t9; let t8 ← tmp__; if t8 then do tmp__ ← let t10 ← base; let ret ← result.Result.Err t10; some (ret) ; some (inr tmp__) else let t16 ← list.length tail; let t17 ← (0 : nat) < t16; if t17 then do tmp__ ← slice._T_.slice_SliceExt.get_unchecked tail (0 : nat); let t15 ← tmp__; let t14 ← t15; let t13 ← (t14); do tmp__ ← @ops.FnMut.call_mut _ _ _ ops_FnMut__T__F f t13; match tmp__ with (t11, f) := match t11 with | cmp.Ordering.Less := let t23 ← head; do tmp__ ← @slice._T_.slice_SliceExt.len _ t23; let t22 ← tmp__; let t21 ← t22 + (1 : nat); let base ← base + t21; let t28 ← tail; let t30 ← (1 : nat); let t29 ← ops.RangeFrom.mk t30; do tmp__ ← @slice._T_.ops_Index_ops_RangeFrom_usize__.index _ t28 t29; let t27 ← tmp__; let t26 ← t27; let t25 ← t26; let s ← t25; some (inl (f, base, s)) | cmp.Ordering.Equal := do tmp__ ← let t33 ← base; let t35 ← head; do tmp__ ← @slice._T_.slice_SliceExt.len _ t35; let t34 ← tmp__; let t32 ← t33 + t34; let ret ← result.Result.Ok t32; some (ret) ; some (inr tmp__) | cmp.Ordering.Greater := let t31 ← head; let s ← t31; some (inl (f, base, s)) end end else do tmp__ ← let t18 ← ("rust/src/libcore/slice.rs", (307 : nat)); let t19 ← t18; none ; some (inr tmp__)end definition slice._T_.slice_SliceExt.binary_search_by := let self ← self; let f ← f; let base ← (0 : nat); let t1 ← self; let s ← t1; loop' (slice._T_.slice_SliceExt.binary_search_by.loop_4) (f, base, s) end structure cmp.PartialEq [class] (Rhs : Type) (Self : Type) := (eq : Self → Rhs → option (Prop)) structure cmp.Eq [class] (Self : Type) extends cmp.PartialEq Self Self inductive option.Option (T : Type) := | None {} : option.Option T | Some {} : T → option.Option T structure cmp.PartialOrd [class] (Rhs : Type) (Self : Type) extends cmp.PartialEq Rhs Self := (partial_cmp : Self → Rhs → option ((option.Option (cmp.Ordering )))) structure cmp.Ord [class] (Self : Type) extends cmp.Eq Self, cmp.PartialOrd Self Self := (cmp : Self → Self → option ((cmp.Ordering ))) definition slice._T_.slice_SliceExt.binary_search {T : Type} [cmp_Ord_T : cmp.Ord T] (self : (slice T)) (x : T) := let self ← self; let x ← x; let t0 ← self; let t3 ← x; let t2 ← (λp, let p ← p; let t0 ← p; let t2 ← t3; do tmp__ ← @cmp.Ord.cmp _ cmp_Ord_T t0 t2; let ret ← tmp__; some ret); do tmp__ ← @slice._T_.slice_SliceExt.binary_search_by _ _ fn t0 t2; let ret ← tmp__; some (ret) end core
3ee86d9ea07c9362113692ceff456bc6d300fe51
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/run/injection1.lean
9b4513e72e3fd285f824fb576e6d6e0b21b7ae0b
[ "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
794
lean
open nat tactic inductive vec (A : Type) : nat → Type | nil : vec nat.zero | cons : ∀ {n}, A → vec n → vec (succ n) example (n : nat) (v w : vec nat n) (a b : nat) : vec.cons a v = vec.cons b w → a = b := by do intro `H, H ← get_local `H, injection H, trace_state, assumption example (n : nat) (v w : vec nat n) (a b : nat) : vec.cons a v = vec.cons b w → v = w := by do intro `H, H ← get_local `H, injection H, trace_state, assumption print "----------------" example (a b : nat) : succ a = succ b → a = b := by do intro `H, H ← get_local `H, injection H, trace_state, assumption example (a b c d : nat) : (a, b) = (c, d) → a = c := by do intro `H, H ← get_local `H, injection_with H [`H1, `H2], H1 ← get_local `H1, exact H1
f114828dcde1c1c7ee2139018768bdc55d7522ae
8b147c3d61a55005ca839480a4045e69683f7655
/compiler.lean
9b1b2f0f3d25fba1004f5d300d738d941c6ba74c
[]
no_license
dselsam/unrealistic_compiler
ce69efac0d573642b67f44a63eb5f18cdf596b27
70514de492a6a1ed705ad247333ae5b3f8455a83
refs/heads/master
1,609,483,664,302
1,500,654,169,000
1,500,654,169,000
97,516,326
0
0
null
null
null
null
UTF-8
Lean
false
false
19,520
lean
import data.hash_map library_dev.data.list.set namespace state @[inline] def modify {σ : Type} : (σ → σ) → state σ unit := λ f s, ((), f s) def inc : state ℕ unit := modify (λ n, n + 1) def dec : state ℕ unit := modify (λ n, n - 1) end state namespace list def dnth {α : Type*} [decidable_eq α] [inhabited α] (xs : list α) (n : ℕ) : α := match xs^.nth n with | (some x) := x | none := default α end def at_nth {α : Type*} (xs : list α) (idx : ℕ) (x : α) : Prop := nth xs idx = some x def set_nth {α : Type*} : list α → ℕ → α → option (list α) | (x::xs) 0 a := some (a :: xs) | (x::xs) (i+1) a := do ys ← set_nth xs i a, return (x :: ys) | [] _ _ := none lemma at_nth_of_dnth_lt {α : Type*} [decidable_eq α] [inhabited α] {xs : list α} {idx : ℕ} : idx < length xs → at_nth xs idx (dnth xs idx) := sorry lemma at_nth_of_len {α : Type*} {xs ys : list α} {x : α} {k : ℕ} : k = length xs → at_nth (xs ++ x :: ys) k x := sorry end list namespace hash_map def dfind {α : Type*} [decidable_eq α] {β : α → Type*} [∀ a, inhabited (β a)] (m : hash_map α β) (a : α) : β a := match m^.find a with | (some b) := b | none := default (β a) end end hash_map section seq variables {α : Type*} (rel : α → α → Prop) inductive star : α → α → Prop | rfl : ∀ (x : α), star x x | rtrans : ∀ (x y z : α), rel x y → star y z → star x y end seq namespace star variables {α : Type*} (rel : α → α → Prop) lemma trans (x y z : α) : star rel x y → star rel y z → star rel x z := sorry end star namespace compiler open tactic list structure var : Type := (id : ℕ) namespace var instance : decidable_eq var := by mk_dec_eq_instance end var @[reducible] def vstate : Type := hash_map var (λ v : var, ℕ) def empty_vstate : vstate := mk_hash_map (λ v : var, v^.id) inductive aexp : Type | aconst : ℕ → aexp | avar : var → aexp | aadd : aexp → aexp → aexp | asub : aexp → aexp → aexp | amul : aexp → aexp → aexp inductive bexp : Type | btrue : bexp | bfalse : bexp | bnot : bexp → bexp | band : bexp → bexp → bexp | beq : aexp → aexp → bexp | ble : aexp → aexp → bexp def aeval (st : vstate) : aexp → ℕ | (aexp.aconst n) := n | (aexp.avar v) := st^.dfind v | (aexp.aadd e₁ e₂) := aeval e₁ + aeval e₂ | (aexp.asub e₁ e₂) := aeval e₁ - aeval e₂ | (aexp.amul e₁ e₂) := aeval e₁ * aeval e₂ def beval (st : vstate) : bexp → bool | (bexp.btrue) := tt | (bexp.bfalse) := ff | (bexp.bnot b) := bnot (beval b) | (bexp.band b₁ b₂) := beval b₁ && beval b₂ | (bexp.beq e₁ e₂) := aeval st e₁ = aeval st e₂ | (bexp.ble e₁ e₂) := aeval st e₁ ≤ aeval st e₂ inductive com : Type | cskip : com | cass : var → aexp → com | cseq : com → com → com | cif : bexp → com → com → com | cwhile : bexp → com → com open com inductive ceval : com → vstate → vstate → Prop | eskip : ∀ st, ceval cskip st st | eass : ∀ st a n x, aeval st a = n → ceval (cass x a) st (st^.insert x n) | eseq : ∀ c₁ c₂ st₁ st₂ st₃, ceval c₁ st₁ st₂ → ceval c₂ st₂ st₃ → ceval (cseq c₁ c₂) st₁ st₃ | eift : ∀ st₁ st₂ b c₁ c₂, beval st₁ b = tt → ceval c₁ st₁ st₂ → ceval (cif b c₁ c₂) st₁ st₂ | eiff : ∀ st₁ st₂ b c₁ c₂, beval st₁ b = ff → ceval c₂ st₁ st₂ → ceval (cif b c₁ c₂) st₁ st₂ | ewhilet : ∀ st₁ st₂ st₃ b c, beval st₁ b = tt → ceval c st₁ st₂ → ceval (cwhile b c) st₂ st₃ → ceval (cwhile b c) st₁ st₃ | ewhilef : ∀ st b c, beval st b = ff → ceval (cwhile b c) st st open ceval inductive instruction : Type | iconst : ℕ → instruction | iget : ℕ → instruction | iset : ℕ → instruction | iadd : instruction | isub : instruction | imul : instruction | ibf : ℕ → instruction | ibb : ℕ → instruction | ibeq : ℕ → instruction | ibne : ℕ → instruction | ible : ℕ → instruction | ibgt : ℕ → instruction | ihalt : instruction open instruction @[reducible] def code := list instruction. @[reducible] def stack : Type := list ℕ @[reducible] def config : Type := ℕ × stack inductive veval (c : code) : config -> config -> Prop | vconst : ∀ pc stk n, at_nth c pc (iconst n) → veval (pc, stk) (pc + 1, n :: stk) | vget : ∀ pc stk n v, at_nth c pc (iget n) → at_nth stk n v → veval (pc, stk) (pc + 1, v :: stk) | vset : ∀ pc stk n v stk', at_nth c pc (iset n) → set_nth stk n v = some stk' → veval (pc, v :: stk) (pc + 1, stk') | vadd : ∀ pc stk n n₁ n₂, at_nth c pc iadd → n = n₁ + n₂ → veval (pc, n₂ :: n₁ :: stk) (pc + 1, n :: stk) | vsub : ∀ pc stk n₁ n₂, at_nth c pc iadd → veval (pc, n₂ :: n₁ :: stk) (pc + 1, (n₁ - n₂) :: stk) | vmul : ∀ pc stk n₁ n₂, at_nth c pc iadd → veval (pc, n₂ :: n₁ :: stk) (pc + 1, (n₁ * n₂) :: stk) | vbf : ∀ pc stk ofs pc', at_nth c pc (ibf ofs) → pc' = (pc + ofs) + 1 → veval (pc, stk) (pc', stk) | vbb : ∀ pc stk ofs pc', at_nth c pc (ibf ofs) → pc' + ofs = pc + 1 → veval (pc, stk) (pc', stk) | vbeq : ∀ pc stk ofs n₁ n₂ pc', at_nth c pc (ibeq ofs) → pc' = (if n₁ = n₂ then (pc + ofs) + 1 else pc + 1) → veval (pc, n₂ :: n₁ :: stk) (pc', stk) | vbne : ∀ pc stk ofs n₁ n₂ pc', at_nth c pc (ibne ofs) → pc' = (if n₁ = n₂ then pc + 1 else (pc + ofs) + 1) → veval (pc, n₂ :: n₁ :: stk) (pc', stk) | vble : ∀ pc stk ofs n₁ n₂ pc', at_nth c pc (ible ofs) → pc' = (if n₁ ≤ n₂ then (pc + ofs) + 1 else pc + 1) → veval (pc, n₂ :: n₁ :: stk) (pc', stk) | vbgt : ∀ pc stk ofs n₁ n₂ pc', at_nth c pc (ibgt ofs) → pc' = (if n₁ ≤ n₂ then pc + 1 else (pc + ofs) + 1) → veval (pc, n₂ :: n₁ :: stk) (pc', stk) def vhalts (c : code) (stk_init stk_fin : stack) : Prop := ∃ pc, at_nth c pc ihalt ∧ star (veval c) (0, stk_init) (pc, stk_fin) def collect_assigned_vars : com → list var | (cskip) := [] | (cass v _) := [v] | (cseq c₁ c₂) := collect_assigned_vars c₁ ∪ collect_assigned_vars c₂ | (cif b c₁ c₂) := collect_assigned_vars c₁ ∪ collect_assigned_vars c₂ | (cwhile b c) := collect_assigned_vars c @[reducible] def stack_offsets : Type := hash_map var (λ v : var, ℕ) def compute_stack_offsets_core : list var → stack_offsets → stack_offsets | [] s := s | (v :: vs) s := compute_stack_offsets_core vs (s^.insert v (length vs)) def compute_stack_offsets (c : com) : stack_offsets := compute_stack_offsets_core (collect_assigned_vars c) (mk_hash_map (λ (v : var), v^.id)) -- TODO(dhs): not sure if this is the best way to do it def agree (offsets : stack_offsets) (vofs : ℕ) (st : vstate) (stk : stack) : Prop := ∀ (v : var), st^.dfind v = dnth stk (offsets^.dfind v + vofs) lemma agree_push {offsets : stack_offsets} {vofs : ℕ} {st : vstate} {stk : stack} {n : ℕ} : agree offsets vofs st stk → agree offsets (vofs + 1) st (n :: stk) := sorry lemma agree_insert {offsets : stack_offsets} {vofs : ℕ} {st : vstate} {stk : stack} : agree offsets vofs st stk → ∀ v n, agree offsets vofs (hash_map.insert st v n) (update_nth stk (hash_map.dfind offsets v) n) := sorry inductive codeseq_at : code → ℕ → code → Prop | intro : ∀ code₁ code₂ code₃ pc, pc = length code₁ → codeseq_at (code₁ ++ code₂ ++ code₃) pc code₂ def compile_aexp_core (offsets : stack_offsets) : aexp → ℕ → code | (aexp.aconst n) vofs := [iconst n] | (aexp.avar v) vofs := [iget $ offsets^.dfind v + vofs] | (aexp.aadd e₁ e₂) vofs := compile_aexp_core e₂ vofs ++ compile_aexp_core e₁ (vofs + 1) ++ [iadd] | (aexp.asub e₁ e₂) vofs := compile_aexp_core e₂ vofs ++ compile_aexp_core e₁ (vofs + 1) ++ [isub] | (aexp.amul e₁ e₂) vofs := compile_aexp_core e₂ vofs ++ compile_aexp_core e₁ (vofs + 1) ++ [imul] def compile_aexp (offsets : stack_offsets) (e : aexp) := compile_aexp_core offsets e 0 -- TODO(dhs): weaken the forall? def astack_contains_vars (offsets : stack_offsets) : stack → ℕ → aexp → Prop | stk vofs (aexp.aconst n) := true | stk vofs (aexp.avar v) := offsets^.dfind v + vofs < length stk | stk vofs (aexp.aadd e₁ e₂) := astack_contains_vars stk vofs e₂ ∧ ∀ x, astack_contains_vars (x :: stk) (vofs + 1) e₁ | stk vofs (aexp.asub e₁ e₂) := astack_contains_vars stk vofs e₂ ∧ ∀ x, astack_contains_vars (x :: stk) (vofs + 1) e₁ | stk vofs (aexp.amul e₁ e₂) := astack_contains_vars stk vofs e₂ ∧ ∀ x, astack_contains_vars (x :: stk) (vofs + 1) e₁ lemma compile_aexp_core_correct : ∀ code st e pc stk offsets vofs, codeseq_at code pc (compile_aexp_core offsets e vofs) → agree offsets vofs st stk → astack_contains_vars offsets stk vofs e → star (veval code) (pc, stk) (pc + length (compile_aexp_core offsets e vofs), aeval st e :: stk) | .(_) st (aexp.aconst n) .(pc) stk offsets vofs (codeseq_at.intro code₁ ._ code₃ pc H_pc) H_agree H_astack := begin simp [compile_aexp_core, length, aeval], apply star.rtrans, apply veval.vconst, apply at_nth_of_len H_pc, apply star.rfl end | .(_) st (aexp.avar v) .(pc) stk offsets vofs (codeseq_at.intro code₁ ._ code₃ pc H_pc) H_agree H_astack := begin simp [compile_aexp_core, length, aeval], apply star.rtrans, apply veval.vget, apply at_nth_of_len H_pc, simp [agree] at H_agree, simp [astack_contains_vars] at H_astack, rw H_agree, apply at_nth_of_dnth_lt H_astack, apply star.rfl end | .(_) st (aexp.aadd e₁ e₂) .(pc) stk offsets vofs (codeseq_at.intro code₁ ._ code₃ pc H_pc) H_agree H_astack := begin simp [compile_aexp_core, length, aeval], apply star.trans, -- Compile e₂ apply compile_aexp_core_correct _ st e₂ _ _ offsets vofs _ H_agree (and.left H_astack), rw ← append_assoc, apply codeseq_at.intro _ _ _ _ H_pc, -- Compile e₁ apply star.trans, apply compile_aexp_core_correct _ st e₁ _ _ offsets (vofs+1) _ (agree_push H_agree) (and.right H_astack _), have H_assoc : (code₁ ++ (compile_aexp_core offsets e₂ vofs ++ (compile_aexp_core offsets e₁ (vofs + 1) ++ iadd :: code₃))) = (code₁ ++ compile_aexp_core offsets e₂ vofs) ++ (compile_aexp_core offsets e₁ (vofs + 1)) ++ iadd :: code₃ := sorry, rw H_assoc, clear H_assoc, apply codeseq_at.intro _ _ _ _, simp [H_pc, length_append], -- Add instruction apply star.rtrans, have H_assoc : code₁ ++ (compile_aexp_core offsets e₂ vofs ++ (compile_aexp_core offsets e₁ (vofs + 1) ++ iadd :: code₃)) = (code₁ ++ compile_aexp_core offsets e₂ vofs ++ compile_aexp_core offsets e₁ (vofs + 1)) ++ [iadd] ++ code₃ := sorry, rw H_assoc, clear H_assoc, have H_one_at_end : pc + (1 + (length (compile_aexp_core offsets e₂ vofs) + length (compile_aexp_core offsets e₁ (vofs + 1)))) = (pc + length (compile_aexp_core offsets e₂ vofs) + length (compile_aexp_core offsets e₁ (vofs + 1))) + 1 := sorry, rw H_one_at_end, clear H_one_at_end, apply veval.vadd, have H_cons : code₁ ++ compile_aexp_core offsets e₂ vofs ++ compile_aexp_core offsets e₁ (vofs + 1) ++ [iadd] ++ code₃ = (code₁ ++ compile_aexp_core offsets e₂ vofs ++ compile_aexp_core offsets e₁ (vofs + 1)) ++ (iadd :: code₃) := sorry, rw H_cons, clear H_cons, apply at_nth_of_len, simp [H_pc, length_append], simp, apply star.rfl, end def compile_bexp (offsets : stack_offsets) : bexp → bool → ℕ → code | (bexp.btrue) cond ofs := if cond then [ibf ofs] else [] | (bexp.bfalse) cond ofs := if cond then [] else [ibf ofs] | (bexp.bnot b) cond ofs := compile_bexp b (bnot cond) ofs | (bexp.band b₁ b₂) cond ofs := let code₂ := compile_bexp b₂ cond ofs, code₁ := compile_bexp b₁ ff (if cond then length code₂ else ofs + length code₂) in code₁ ++ code₂ | (bexp.beq e₁ e₂) cond ofs := compile_aexp_core offsets e₂ 0 ++ compile_aexp_core offsets e₁ 1 ++ (if cond then [ibeq ofs] else [ibne ofs]) | (bexp.ble e₁ e₂) cond ofs := compile_aexp_core offsets e₂ 0 ++ compile_aexp_core offsets e₁ 1 ++ (if cond then [ible ofs] else [ibgt ofs]) -- TODO(dhs): weaken the forall? -- TODO(dhs): is this even right? We'll see soon. def bstack_contains_vars (offsets : stack_offsets) : stack → bexp → Prop | stk (bexp.btrue) := true | stk (bexp.bfalse) := true | stk (bexp.bnot b) := bstack_contains_vars stk b | stk (bexp.band b₁ b₂) := bstack_contains_vars stk b₁ ∧ bstack_contains_vars stk b₂ | stk (bexp.beq e₁ e₂) := astack_contains_vars offsets stk 0 e₂ ∧ ∀ x, astack_contains_vars offsets (x::stk) 1 e₁ | stk (bexp.ble e₁ e₂) := astack_contains_vars offsets stk 0 e₂ ∧ ∀ x, astack_contains_vars offsets (x::stk) 1 e₁ --set_option pp.all true --set_option trace.type_context.is_def_eq true --set_option trace.type_context.is_def_eq_detail true lemma compile_bexp_correct : ∀ code st b cond ofs pc stk offsets, codeseq_at code pc (compile_bexp offsets b cond ofs) → agree offsets 0 st stk → bstack_contains_vars offsets stk b → star (veval code) (pc, stk) (pc + (length (compile_bexp offsets b cond ofs) + ite (beval st b = cond) ofs 0), stk) /- | .(_) st (bexp.btrue) cond ofs .(pc) stk offsets (codeseq_at.intro code₁ ._ code₃ pc H_pc) H_agree H_bstack := begin simp [compile_bexp, compile_aexp_core, length, aeval, beval], cases cond, { simp, apply star.rfl }, simp, apply star.rtrans, apply veval.vbf _ _ ofs, apply at_nth_of_len H_pc, simp, apply star.rfl end | .(_) st (bexp.bfalse) cond ofs .(pc) stk offsets (codeseq_at.intro code₁ ._ code₃ pc H_pc) H_agree H_bstack := begin simp [compile_bexp, compile_aexp_core, length, aeval, beval], cases cond, { simp, apply star.rtrans, apply veval.vbf _ _ ofs, apply at_nth_of_len H_pc, simp, apply star.rfl }, { simp, apply star.rfl }, end | .(_) st (bexp.bnot b) cond ofs .(pc) stk offsets (codeseq_at.intro code₁ ._ code₃ pc H_pc) H_agree H_bstack := begin simp [compile_bexp, compile_aexp_core, length, aeval, beval], -- TODO(dhs): come on, Lean have H_bnot : ∀ beq, (@ite (bnot (beval st b) = cond) beq _ ofs 0) = (ite (beval st b = bnot cond) ofs 0) := sorry, rw H_bnot, clear H_bnot, apply compile_bexp_correct (code₁ ++ (compile_bexp offsets b (bnot cond) ofs ++ code₃)) st b (bnot cond) ofs pc stk offsets _ H_agree H_bstack, rw ← append_assoc, apply codeseq_at.intro _ _ _ _ H_pc, end -/ | .(_) st (bexp.band b₁ b₂) cond ofs .(pc) stk offsets (codeseq_at.intro code₁ ._ code₃ pc H_pc) H_agree H_bstack := begin simp [compile_bexp, compile_aexp_core, length, aeval, beval], -- b₁ apply star.trans, have H_assoc : (code₁ ++ (compile_bexp offsets b₁ ff (ite ↑cond (length (compile_bexp offsets b₂ cond ofs)) (ofs + length (compile_bexp offsets b₂ cond ofs))) ++ (compile_bexp offsets b₂ cond ofs ++ code₃))) = (code₁ ++ (compile_bexp offsets b₁ ff (ite ↑cond (length (compile_bexp offsets b₂ cond ofs)) (ofs + length (compile_bexp offsets b₂ cond ofs)))) ++ (compile_bexp offsets b₂ cond ofs ++ code₃)) := sorry, rw H_assoc, clear H_assoc, apply compile_bexp_correct _ st b₁ ff _ pc stk offsets _ H_agree (and.left H_bstack), tactic.rotate 1, apply codeseq_at.intro _ _ _ _ H_pc, -- cases cond, simp, have H_em : (beval st b₁ = ff ∨ beval st b₁ = tt) := sorry, cases H_em with H_ff H_tt, simp [H_ff], apply star.rfl, simp [H_tt], have H_assoc : (code₁ ++ (compile_bexp offsets b₁ ff (ofs + length (compile_bexp offsets b₂ ff ofs)) ++ (compile_bexp offsets b₂ ff ofs ++ code₃))) = (code₁ ++ compile_bexp offsets b₁ ff (ofs + length (compile_bexp offsets b₂ ff ofs)) ++ (compile_bexp offsets b₂ ff ofs ++ code₃)) := sorry, rw H_assoc, clear H_assoc, -- TODO(dhs): why won't it unify? have H_come_on_lean : ∀ bdec, @ite (beval st b₂ = ff) bdec _ ofs 0 = ite (beval st b₂ = ff) ofs 0 := sorry, have H_rec₂ := compile_bexp_correct (code₁ ++ compile_bexp offsets b₁ ff (ofs + length (compile_bexp offsets b₂ ff ofs)) ++ (compile_bexp offsets b₂ ff ofs ++ code₃)) st b₂ ff ofs (pc + length (compile_bexp offsets b₁ ff (ofs + length (compile_bexp offsets b₂ ff ofs)))) stk offsets, simp [H_come_on_lean] at H_rec₂, simp [H_come_on_lean], apply H_rec₂, clear H_rec₂, have H_assoc : (code₁ ++ (compile_bexp offsets b₁ ff (ofs + length (compile_bexp offsets b₂ ff ofs)) ++ (compile_bexp offsets b₂ ff ofs ++ code₃))) = (code₁ ++ compile_bexp offsets b₁ ff (ofs + length (compile_bexp offsets b₂ ff ofs))) ++ compile_bexp offsets b₂ ff ofs ++ code₃ := sorry, rw H_assoc, clear H_assoc, apply codeseq_at.intro, simp [H_pc], exact H_agree, exact and.right H_bstack, -- cond = tt exact sorry end -- Example program --------------------------- -- (cass `x 1) -- (cass `y (+ x x)) -- (cass `z (+ x (+ y x)) -- Want -------------------------- -- Initial stack: [x:=0, y:=0, z:=0] -- cass `x 1 ==> push 1, iset 1 ==> [x:=1, y:=0, z:=0] -- cass `y (+ x x) ==> iget 0, iget 1, iadd, iset 2 ==> [x:=2, y:=4, z:=0] -- cass `z (+ x (+ y x)) ==> iget 0, iget 2, iget 2, iadd, iadd, iset 3 definition compile_com (offsets : stack_offsets) : com → code | cskip := [] | (cass v e) := compile_aexp offsets e ++ [iset $ offsets^.dfind v] | (cseq c₁ c₂) := compile_com c₁ ++ compile_com c₂ | (cif b c₁ c₂) := let code₁ := compile_com c₁, code₂ := compile_com c₂ in compile_bexp offsets b false (length code₁ + 1) ++ code₁ ++ [ibf (length code₂)] ++ code₂ | (cwhile b c) := let code_body := compile_com c, code_test := compile_bexp offsets b ff (length code_body + 1) in code_test ++ code_body ++ [ibb (length code_test + length code_body + 1)] -- TODO(dhs): is this _strong_ enough, with `offsets` an argument? -- TODO(dhs): is this _weak_ enough, to prove? theorem compile_correct_terminating_alt : ∀ code st c st', ceval c st st' → ∀ offsets stk pc, codeseq_at code pc (compile_com offsets c) → agree offsets 0 st stk → ∃ stk', star (veval code) (pc, stk) (pc + length (compile_com offsets c), stk') ∧ agree offsets 0 st' stk' | code ._ ._ ._ (eskip st) := begin simp [compile_com, length], intros offsets stk pc H_codeseq H_agree, apply exists.intro stk, split, exact H_agree, apply star.rfl end | code ._ ._ ._ (eass st a n x H_aeval) := begin simp [compile_com, length], intros offsets stk pc H_codeseq H_agree, apply exists.intro (update_nth stk (offsets^.dfind x) n), split, apply agree_insert H_agree, apply compile_aexp_core_correct, end | code ._ ._ ._ (eseq c₁ c₂ st₁ st₂ st₃ H_c₁ H_c₂) := begin end | code ._ ._ ._ (eift st₁ st₂ b c₁ c₂ H_beval_t H_ceval₁) := begin end | code ._ ._ ._ (eiff st₁ st₂ b c₁ c₂ H_beval_f H_ceval₂) := begin end | code ._ ._ ._ (ewhilet st₁ st₂ st₃ b c H_beval_t H_ceval_step H_ceval_loop) := begin end | code ._ ._ ._ (ewhilef st b c H_beval_f) := begin end end compiler
d26467c40d68ccbcaa598837b6b8bda2601cd1d8
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/linear_algebra/affine_space/affine_map.lean
15b92296a23b5b7f25f1492072bf4ec909025301
[ "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
25,058
lean
/- Copyright (c) 2020 Joseph Myers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joseph Myers -/ import data.set.pointwise.interval import linear_algebra.affine_space.basic import linear_algebra.bilinear_map import linear_algebra.pi import linear_algebra.prod /-! # Affine maps This file defines affine maps. ## Main definitions * `affine_map` is the type of affine maps between two affine spaces with the same ring `k`. Various basic examples of affine maps are defined, including `const`, `id`, `line_map` and `homothety`. ## Notations * `P1 →ᵃ[k] P2` is a notation for `affine_map k P1 P2`; * `affine_space V P`: a localized notation for `add_torsor V P` defined in `linear_algebra.affine_space.basic`. ## Implementation notes `out_param` is used in the definition of `[add_torsor V P]` to make `V` an implicit argument (deduced from `P`) in most cases; `include V` is needed in many cases for `V`, and type classes using it, to be added as implicit arguments to individual lemmas. As for modules, `k` is an explicit argument rather than implied by `P` or `V`. This file only provides purely algebraic definitions and results. Those depending on analysis or topology are defined elsewhere; see `analysis.normed_space.add_torsor` and `topology.algebra.affine`. ## References * https://en.wikipedia.org/wiki/Affine_space * https://en.wikipedia.org/wiki/Principal_homogeneous_space -/ open_locale affine /-- An `affine_map k P1 P2` (notation: `P1 →ᵃ[k] P2`) is a map from `P1` to `P2` that induces a corresponding linear map from `V1` to `V2`. -/ structure affine_map (k : Type*) {V1 : Type*} (P1 : Type*) {V2 : Type*} (P2 : Type*) [ring k] [add_comm_group V1] [module k V1] [affine_space V1 P1] [add_comm_group V2] [module k V2] [affine_space V2 P2] := (to_fun : P1 → P2) (linear : V1 →ₗ[k] V2) (map_vadd' : ∀ (p : P1) (v : V1), to_fun (v +ᵥ p) = linear v +ᵥ to_fun p) notation P1 ` →ᵃ[`:25 k:25 `] `:0 P2:0 := affine_map k P1 P2 instance (k : Type*) {V1 : Type*} (P1 : Type*) {V2 : Type*} (P2 : Type*) [ring k] [add_comm_group V1] [module k V1] [affine_space V1 P1] [add_comm_group V2] [module k V2] [affine_space V2 P2]: has_coe_to_fun (P1 →ᵃ[k] P2) (λ _, P1 → P2) := ⟨affine_map.to_fun⟩ namespace linear_map variables {k : Type*} {V₁ : Type*} {V₂ : Type*} [ring k] [add_comm_group V₁] [module k V₁] [add_comm_group V₂] [module k V₂] (f : V₁ →ₗ[k] V₂) /-- Reinterpret a linear map as an affine map. -/ def to_affine_map : V₁ →ᵃ[k] V₂ := { to_fun := f, linear := f, map_vadd' := λ p v, f.map_add v p } @[simp] lemma coe_to_affine_map : ⇑f.to_affine_map = f := rfl @[simp] lemma to_affine_map_linear : f.to_affine_map.linear = f := rfl end linear_map namespace affine_map variables {k : Type*} {V1 : Type*} {P1 : Type*} {V2 : Type*} {P2 : Type*} {V3 : Type*} {P3 : Type*} {V4 : Type*} {P4 : Type*} [ring k] [add_comm_group V1] [module k V1] [affine_space V1 P1] [add_comm_group V2] [module k V2] [affine_space V2 P2] [add_comm_group V3] [module k V3] [affine_space V3 P3] [add_comm_group V4] [module k V4] [affine_space V4 P4] include V1 V2 /-- Constructing an affine map and coercing back to a function produces the same map. -/ @[simp] lemma coe_mk (f : P1 → P2) (linear add) : ((mk f linear add : P1 →ᵃ[k] P2) : P1 → P2) = f := rfl /-- `to_fun` is the same as the result of coercing to a function. -/ @[simp] lemma to_fun_eq_coe (f : P1 →ᵃ[k] P2) : f.to_fun = ⇑f := rfl /-- An affine map on the result of adding a vector to a point produces the same result as the linear map applied to that vector, added to the affine map applied to that point. -/ @[simp] lemma map_vadd (f : P1 →ᵃ[k] P2) (p : P1) (v : V1) : f (v +ᵥ p) = f.linear v +ᵥ f p := f.map_vadd' p v /-- The linear map on the result of subtracting two points is the result of subtracting the result of the affine map on those two points. -/ @[simp] lemma linear_map_vsub (f : P1 →ᵃ[k] P2) (p1 p2 : P1) : f.linear (p1 -ᵥ p2) = f p1 -ᵥ f p2 := by conv_rhs { rw [←vsub_vadd p1 p2, map_vadd, vadd_vsub] } /-- Two affine maps are equal if they coerce to the same function. -/ @[ext] lemma ext {f g : P1 →ᵃ[k] P2} (h : ∀ p, f p = g p) : f = g := begin rcases f with ⟨f, f_linear, f_add⟩, rcases g with ⟨g, g_linear, g_add⟩, obtain rfl : f = g := funext h, congr' with v, cases (add_torsor.nonempty : nonempty P1) with p, apply vadd_right_cancel (f p), erw [← f_add, ← g_add] end lemma ext_iff {f g : P1 →ᵃ[k] P2} : f = g ↔ ∀ p, f p = g p := ⟨λ h p, h ▸ rfl, ext⟩ lemma coe_fn_injective : @function.injective (P1 →ᵃ[k] P2) (P1 → P2) coe_fn := λ f g H, ext $ congr_fun H protected lemma congr_arg (f : P1 →ᵃ[k] P2) {x y : P1} (h : x = y) : f x = f y := congr_arg _ h protected lemma congr_fun {f g : P1 →ᵃ[k] P2} (h : f = g) (x : P1) : f x = g x := h ▸ rfl variables (k P1) /-- Constant function as an `affine_map`. -/ def const (p : P2) : P1 →ᵃ[k] P2 := { to_fun := function.const P1 p, linear := 0, map_vadd' := λ p v, by simp } @[simp] lemma coe_const (p : P2) : ⇑(const k P1 p) = function.const P1 p := rfl @[simp] lemma const_linear (p : P2) : (const k P1 p).linear = 0 := rfl variables {k P1} lemma linear_eq_zero_iff_exists_const (f : P1 →ᵃ[k] P2) : f.linear = 0 ↔ ∃ q, f = const k P1 q := begin refine ⟨λ h, _, λ h, _⟩, { use f (classical.arbitrary P1), ext, rw [coe_const, function.const_apply, ← @vsub_eq_zero_iff_eq V2, ← f.linear_map_vsub, h, linear_map.zero_apply], }, { rcases h with ⟨q, rfl⟩, exact const_linear k P1 q, }, end instance nonempty : nonempty (P1 →ᵃ[k] P2) := (add_torsor.nonempty : nonempty P2).elim $ λ p, ⟨const k P1 p⟩ /-- Construct an affine map by verifying the relation between the map and its linear part at one base point. Namely, this function takes a map `f : P₁ → P₂`, a linear map `f' : V₁ →ₗ[k] V₂`, and a point `p` such that for any other point `p'` we have `f p' = f' (p' -ᵥ p) +ᵥ f p`. -/ def mk' (f : P1 → P2) (f' : V1 →ₗ[k] V2) (p : P1) (h : ∀ p' : P1, f p' = f' (p' -ᵥ p) +ᵥ f p) : P1 →ᵃ[k] P2 := { to_fun := f, linear := f', map_vadd' := λ p' v, by rw [h, h p', vadd_vsub_assoc, f'.map_add, vadd_vadd] } @[simp] lemma coe_mk' (f : P1 → P2) (f' : V1 →ₗ[k] V2) (p h) : ⇑(mk' f f' p h) = f := rfl @[simp] lemma mk'_linear (f : P1 → P2) (f' : V1 →ₗ[k] V2) (p h) : (mk' f f' p h).linear = f' := rfl section has_smul variables {R : Type*} [monoid R] [distrib_mul_action R V2] [smul_comm_class k R V2] /-- The space of affine maps to a module inherits an `R`-action from the action on its codomain. -/ instance : mul_action R (P1 →ᵃ[k] V2) := { smul := λ c f, ⟨c • f, c • f.linear, λ p v, by simp [smul_add]⟩, one_smul := λ f, ext $ λ p, one_smul _ _, mul_smul := λ c₁ c₂ f, ext $ λ p, mul_smul _ _ _ } @[simp, norm_cast] lemma coe_smul (c : R) (f : P1 →ᵃ[k] V2) : ⇑(c • f) = c • f := rfl @[simp] lemma smul_linear (t : R) (f : P1 →ᵃ[k] V2) : (t • f).linear = t • f.linear := rfl instance [distrib_mul_action Rᵐᵒᵖ V2] [is_central_scalar R V2] : is_central_scalar R (P1 →ᵃ[k] V2) := { op_smul_eq_smul := λ r x, ext $ λ _, op_smul_eq_smul _ _ } end has_smul instance : has_zero (P1 →ᵃ[k] V2) := { zero := ⟨0, 0, λ p v, (zero_vadd _ _).symm⟩ } instance : has_add (P1 →ᵃ[k] V2) := { add := λ f g, ⟨f + g, f.linear + g.linear, λ p v, by simp [add_add_add_comm]⟩ } instance : has_sub (P1 →ᵃ[k] V2) := { sub := λ f g, ⟨f - g, f.linear - g.linear, λ p v, by simp [sub_add_sub_comm]⟩ } instance : has_neg (P1 →ᵃ[k] V2) := { neg := λ f, ⟨-f, -f.linear, λ p v, by simp [add_comm]⟩ } @[simp, norm_cast] lemma coe_zero : ⇑(0 : P1 →ᵃ[k] V2) = 0 := rfl @[simp, norm_cast] lemma coe_add (f g : P1 →ᵃ[k] V2) : ⇑(f + g) = f + g := rfl @[simp, norm_cast] lemma coe_neg (f : P1 →ᵃ[k] V2) : ⇑(-f) = -f := rfl @[simp, norm_cast] lemma coe_sub (f g : P1 →ᵃ[k] V2) : ⇑(f - g) = f - g := rfl @[simp] lemma zero_linear : (0 : P1 →ᵃ[k] V2).linear = 0 := rfl @[simp] lemma add_linear (f g : P1 →ᵃ[k] V2) : (f + g).linear = f.linear + g.linear := rfl @[simp] lemma sub_linear (f g : P1 →ᵃ[k] V2) : (f - g).linear = f.linear - g.linear := rfl @[simp] lemma neg_linear (f : P1 →ᵃ[k] V2) : (-f).linear = -f.linear := rfl /-- The set of affine maps to a vector space is an additive commutative group. -/ instance : add_comm_group (P1 →ᵃ[k] V2) := coe_fn_injective.add_comm_group _ coe_zero coe_add coe_neg coe_sub (λ _ _, coe_smul _ _) (λ _ _, coe_smul _ _) /-- The space of affine maps from `P1` to `P2` is an affine space over the space of affine maps from `P1` to the vector space `V2` corresponding to `P2`. -/ instance : affine_space (P1 →ᵃ[k] V2) (P1 →ᵃ[k] P2) := { vadd := λ f g, ⟨λ p, f p +ᵥ g p, f.linear + g.linear, λ p v, by simp [vadd_vadd, add_right_comm]⟩, zero_vadd := λ f, ext $ λ p, zero_vadd _ (f p), add_vadd := λ f₁ f₂ f₃, ext $ λ p, add_vadd (f₁ p) (f₂ p) (f₃ p), vsub := λ f g, ⟨λ p, f p -ᵥ g p, f.linear - g.linear, λ p v, by simp [vsub_vadd_eq_vsub_sub, vadd_vsub_assoc, add_sub, sub_add_eq_add_sub]⟩, vsub_vadd' := λ f g, ext $ λ p, vsub_vadd (f p) (g p), vadd_vsub' := λ f g, ext $ λ p, vadd_vsub (f p) (g p) } @[simp] lemma vadd_apply (f : P1 →ᵃ[k] V2) (g : P1 →ᵃ[k] P2) (p : P1) : (f +ᵥ g) p = f p +ᵥ g p := rfl @[simp] lemma vsub_apply (f g : P1 →ᵃ[k] P2) (p : P1) : (f -ᵥ g : P1 →ᵃ[k] V2) p = f p -ᵥ g p := rfl /-- `prod.fst` as an `affine_map`. -/ def fst : (P1 × P2) →ᵃ[k] P1 := { to_fun := prod.fst, linear := linear_map.fst k V1 V2, map_vadd' := λ _ _, rfl } @[simp] lemma coe_fst : ⇑(fst : (P1 × P2) →ᵃ[k] P1) = prod.fst := rfl @[simp] lemma fst_linear : (fst : (P1 × P2) →ᵃ[k] P1).linear = linear_map.fst k V1 V2 := rfl /-- `prod.snd` as an `affine_map`. -/ def snd : (P1 × P2) →ᵃ[k] P2 := { to_fun := prod.snd, linear := linear_map.snd k V1 V2, map_vadd' := λ _ _, rfl } @[simp] lemma coe_snd : ⇑(snd : (P1 × P2) →ᵃ[k] P2) = prod.snd := rfl @[simp] lemma snd_linear : (snd : (P1 × P2) →ᵃ[k] P2).linear = linear_map.snd k V1 V2 := rfl variables (k P1) omit V2 /-- Identity map as an affine map. -/ def id : P1 →ᵃ[k] P1 := { to_fun := id, linear := linear_map.id, map_vadd' := λ p v, rfl } /-- The identity affine map acts as the identity. -/ @[simp] lemma coe_id : ⇑(id k P1) = _root_.id := rfl @[simp] lemma id_linear : (id k P1).linear = linear_map.id := rfl variable {P1} /-- The identity affine map acts as the identity. -/ lemma id_apply (p : P1) : id k P1 p = p := rfl variables {k P1} instance : inhabited (P1 →ᵃ[k] P1) := ⟨id k P1⟩ include V2 V3 /-- Composition of affine maps. -/ def comp (f : P2 →ᵃ[k] P3) (g : P1 →ᵃ[k] P2) : P1 →ᵃ[k] P3 := { to_fun := f ∘ g, linear := f.linear.comp g.linear, map_vadd' := begin intros p v, rw [function.comp_app, g.map_vadd, f.map_vadd], refl end } /-- Composition of affine maps acts as applying the two functions. -/ @[simp] lemma coe_comp (f : P2 →ᵃ[k] P3) (g : P1 →ᵃ[k] P2) : ⇑(f.comp g) = f ∘ g := rfl /-- Composition of affine maps acts as applying the two functions. -/ lemma comp_apply (f : P2 →ᵃ[k] P3) (g : P1 →ᵃ[k] P2) (p : P1) : f.comp g p = f (g p) := rfl omit V3 @[simp] lemma comp_id (f : P1 →ᵃ[k] P2) : f.comp (id k P1) = f := ext $ λ p, rfl @[simp] lemma id_comp (f : P1 →ᵃ[k] P2) : (id k P2).comp f = f := ext $ λ p, rfl include V3 V4 lemma comp_assoc (f₃₄ : P3 →ᵃ[k] P4) (f₂₃ : P2 →ᵃ[k] P3) (f₁₂ : P1 →ᵃ[k] P2) : (f₃₄.comp f₂₃).comp f₁₂ = f₃₄.comp (f₂₃.comp f₁₂) := rfl omit V2 V3 V4 instance : monoid (P1 →ᵃ[k] P1) := { one := id k P1, mul := comp, one_mul := id_comp, mul_one := comp_id, mul_assoc := comp_assoc } @[simp] lemma coe_mul (f g : P1 →ᵃ[k] P1) : ⇑(f * g) = f ∘ g := rfl @[simp] lemma coe_one : ⇑(1 : P1 →ᵃ[k] P1) = _root_.id := rfl /-- `affine_map.linear` on endomorphisms is a `monoid_hom`. -/ @[simps] def linear_hom : (P1 →ᵃ[k] P1) →* (V1 →ₗ[k] V1) := { to_fun := linear, map_one' := rfl, map_mul' := λ _ _, rfl } include V2 @[simp] lemma injective_iff_linear_injective (f : P1 →ᵃ[k] P2) : function.injective f.linear ↔ function.injective f := begin obtain ⟨p⟩ := (infer_instance : nonempty P1), have h : ⇑f.linear = (equiv.vadd_const (f p)).symm ∘ f ∘ (equiv.vadd_const p), { ext v, simp [f.map_vadd, vadd_vsub_assoc], }, rw [h, equiv.comp_injective, equiv.injective_comp], end @[simp] lemma surjective_iff_linear_surjective (f : P1 →ᵃ[k] P2) : function.surjective f.linear ↔ function.surjective f := begin obtain ⟨p⟩ := (infer_instance : nonempty P1), have h : ⇑f.linear = (equiv.vadd_const (f p)).symm ∘ f ∘ (equiv.vadd_const p), { ext v, simp [f.map_vadd, vadd_vsub_assoc], }, rw [h, equiv.comp_surjective, equiv.surjective_comp], end lemma image_vsub_image {s t : set P1} (f : P1 →ᵃ[k] P2) : (f '' s) -ᵥ (f '' t) = f.linear '' (s -ᵥ t) := begin ext v, simp only [set.mem_vsub, set.mem_image, exists_exists_and_eq_and, exists_and_distrib_left, ← f.linear_map_vsub], split, { rintros ⟨x, hx, y, hy, hv⟩, exact ⟨x -ᵥ y, ⟨x, hx, y, hy, rfl⟩, hv⟩, }, { rintros ⟨-, ⟨x, hx, y, hy, rfl⟩, rfl⟩, exact ⟨x, hx, y, hy, rfl⟩, }, end omit V2 /-! ### Definition of `affine_map.line_map` and lemmas about it -/ /-- The affine map from `k` to `P1` sending `0` to `p₀` and `1` to `p₁`. -/ def line_map (p₀ p₁ : P1) : k →ᵃ[k] P1 := ((linear_map.id : k →ₗ[k] k).smul_right (p₁ -ᵥ p₀)).to_affine_map +ᵥ const k k p₀ lemma coe_line_map (p₀ p₁ : P1) : (line_map p₀ p₁ : k → P1) = λ c, c • (p₁ -ᵥ p₀) +ᵥ p₀ := rfl lemma line_map_apply (p₀ p₁ : P1) (c : k) : line_map p₀ p₁ c = c • (p₁ -ᵥ p₀) +ᵥ p₀ := rfl lemma line_map_apply_module' (p₀ p₁ : V1) (c : k) : line_map p₀ p₁ c = c • (p₁ - p₀) + p₀ := rfl lemma line_map_apply_module (p₀ p₁ : V1) (c : k) : line_map p₀ p₁ c = (1 - c) • p₀ + c • p₁ := by simp [line_map_apply_module', smul_sub, sub_smul]; abel omit V1 lemma line_map_apply_ring' (a b c : k) : line_map a b c = c * (b - a) + a := rfl lemma line_map_apply_ring (a b c : k) : line_map a b c = (1 - c) * a + c * b := line_map_apply_module a b c include V1 lemma line_map_vadd_apply (p : P1) (v : V1) (c : k) : line_map p (v +ᵥ p) c = c • v +ᵥ p := by rw [line_map_apply, vadd_vsub] @[simp] lemma line_map_linear (p₀ p₁ : P1) : (line_map p₀ p₁ : k →ᵃ[k] P1).linear = linear_map.id.smul_right (p₁ -ᵥ p₀) := add_zero _ lemma line_map_same_apply (p : P1) (c : k) : line_map p p c = p := by simp [line_map_apply] @[simp] lemma line_map_same (p : P1) : line_map p p = const k k p := ext $ line_map_same_apply p @[simp] lemma line_map_apply_zero (p₀ p₁ : P1) : line_map p₀ p₁ (0:k) = p₀ := by simp [line_map_apply] @[simp] lemma line_map_apply_one (p₀ p₁ : P1) : line_map p₀ p₁ (1:k) = p₁ := by simp [line_map_apply] @[simp] lemma line_map_eq_line_map_iff [no_zero_smul_divisors k V1] {p₀ p₁ : P1} {c₁ c₂ : k} : line_map p₀ p₁ c₁ = line_map p₀ p₁ c₂ ↔ p₀ = p₁ ∨ c₁ = c₂ := by rw [line_map_apply, line_map_apply, ←@vsub_eq_zero_iff_eq V1, vadd_vsub_vadd_cancel_right, ←sub_smul, smul_eq_zero, sub_eq_zero, vsub_eq_zero_iff_eq, or_comm, eq_comm] @[simp] lemma line_map_eq_left_iff [no_zero_smul_divisors k V1] {p₀ p₁ : P1} {c : k} : line_map p₀ p₁ c = p₀ ↔ p₀ = p₁ ∨ c = 0 := by rw [←@line_map_eq_line_map_iff k V1, line_map_apply_zero] @[simp] lemma line_map_eq_right_iff [no_zero_smul_divisors k V1] {p₀ p₁ : P1} {c : k} : line_map p₀ p₁ c = p₁ ↔ p₀ = p₁ ∨ c = 1 := by rw [←@line_map_eq_line_map_iff k V1, line_map_apply_one] variables (k) lemma line_map_injective [no_zero_smul_divisors k V1] {p₀ p₁ : P1} (h : p₀ ≠ p₁) : function.injective (line_map p₀ p₁ : k → P1) := λ c₁ c₂ hc, (line_map_eq_line_map_iff.mp hc).resolve_left h variables {k} include V2 @[simp] lemma apply_line_map (f : P1 →ᵃ[k] P2) (p₀ p₁ : P1) (c : k) : f (line_map p₀ p₁ c) = line_map (f p₀) (f p₁) c := by simp [line_map_apply] @[simp] lemma comp_line_map (f : P1 →ᵃ[k] P2) (p₀ p₁ : P1) : f.comp (line_map p₀ p₁) = line_map (f p₀) (f p₁) := ext $ f.apply_line_map p₀ p₁ @[simp] lemma fst_line_map (p₀ p₁ : P1 × P2) (c : k) : (line_map p₀ p₁ c).1 = line_map p₀.1 p₁.1 c := fst.apply_line_map p₀ p₁ c @[simp] lemma snd_line_map (p₀ p₁ : P1 × P2) (c : k) : (line_map p₀ p₁ c).2 = line_map p₀.2 p₁.2 c := snd.apply_line_map p₀ p₁ c omit V2 lemma line_map_symm (p₀ p₁ : P1) : line_map p₀ p₁ = (line_map p₁ p₀).comp (line_map (1:k) (0:k)) := by { rw [comp_line_map], simp } lemma line_map_apply_one_sub (p₀ p₁ : P1) (c : k) : line_map p₀ p₁ (1 - c) = line_map p₁ p₀ c := by { rw [line_map_symm p₀, comp_apply], congr, simp [line_map_apply] } @[simp] lemma line_map_vsub_left (p₀ p₁ : P1) (c : k) : line_map p₀ p₁ c -ᵥ p₀ = c • (p₁ -ᵥ p₀) := vadd_vsub _ _ @[simp] lemma left_vsub_line_map (p₀ p₁ : P1) (c : k) : p₀ -ᵥ line_map p₀ p₁ c = c • (p₀ -ᵥ p₁) := by rw [← neg_vsub_eq_vsub_rev, line_map_vsub_left, ← smul_neg, neg_vsub_eq_vsub_rev] @[simp] lemma line_map_vsub_right (p₀ p₁ : P1) (c : k) : line_map p₀ p₁ c -ᵥ p₁ = (1 - c) • (p₀ -ᵥ p₁) := by rw [← line_map_apply_one_sub, line_map_vsub_left] @[simp] lemma right_vsub_line_map (p₀ p₁ : P1) (c : k) : p₁ -ᵥ line_map p₀ p₁ c = (1 - c) • (p₁ -ᵥ p₀) := by rw [← line_map_apply_one_sub, left_vsub_line_map] lemma line_map_vadd_line_map (v₁ v₂ : V1) (p₁ p₂ : P1) (c : k) : line_map v₁ v₂ c +ᵥ line_map p₁ p₂ c = line_map (v₁ +ᵥ p₁) (v₂ +ᵥ p₂) c := ((fst : V1 × P1 →ᵃ[k] V1) +ᵥ snd).apply_line_map (v₁, p₁) (v₂, p₂) c lemma line_map_vsub_line_map (p₁ p₂ p₃ p₄ : P1) (c : k) : line_map p₁ p₂ c -ᵥ line_map p₃ p₄ c = line_map (p₁ -ᵥ p₃) (p₂ -ᵥ p₄) c := -- Why Lean fails to find this instance without a hint? by letI : affine_space (V1 × V1) (P1 × P1) := prod.add_torsor; exact ((fst : P1 × P1 →ᵃ[k] P1) -ᵥ (snd : P1 × P1 →ᵃ[k] P1)).apply_line_map (_, _) (_, _) c /-- Decomposition of an affine map in the special case when the point space and vector space are the same. -/ lemma decomp (f : V1 →ᵃ[k] V2) : (f : V1 → V2) = f.linear + (λ z, f 0) := begin ext x, calc f x = f.linear x +ᵥ f 0 : by simp [← f.map_vadd] ... = (f.linear.to_fun + λ (z : V1), f 0) x : by simp end /-- Decomposition of an affine map in the special case when the point space and vector space are the same. -/ lemma decomp' (f : V1 →ᵃ[k] V2) : (f.linear : V1 → V2) = f - (λ z, f 0) := by rw decomp ; simp only [linear_map.map_zero, pi.add_apply, add_sub_cancel, zero_add] omit V1 lemma image_interval {k : Type*} [linear_ordered_field k] (f : k →ᵃ[k] k) (a b : k) : f '' set.interval a b = set.interval (f a) (f b) := begin have : ⇑f = (λ x, x + f 0) ∘ λ x, x * (f 1 - f 0), { ext x, change f x = x • (f 1 -ᵥ f 0) +ᵥ f 0, rw [← f.linear_map_vsub, ← f.linear.map_smul, ← f.map_vadd], simp only [vsub_eq_sub, add_zero, mul_one, vadd_eq_add, sub_zero, smul_eq_mul] }, rw [this, set.image_comp], simp only [set.image_add_const_interval, set.image_mul_const_interval] end section variables {ι : Type*} {V : Π i : ι, Type*} {P : Π i : ι, Type*} [Π i, add_comm_group (V i)] [Π i, module k (V i)] [Π i, add_torsor (V i) (P i)] include V /-- Evaluation at a point as an affine map. -/ def proj (i : ι) : (Π i : ι, P i) →ᵃ[k] P i := { to_fun := λ f, f i, linear := @linear_map.proj k ι _ V _ _ i, map_vadd' := λ p v, rfl } @[simp] lemma proj_apply (i : ι) (f : Π i, P i) : @proj k _ ι V P _ _ _ i f = f i := rfl @[simp] lemma proj_linear (i : ι) : (@proj k _ ι V P _ _ _ i).linear = @linear_map.proj k ι _ V _ _ i := rfl lemma pi_line_map_apply (f g : Π i, P i) (c : k) (i : ι) : line_map f g c i = line_map (f i) (g i) c := (proj i : (Π i, P i) →ᵃ[k] P i).apply_line_map f g c end end affine_map namespace affine_map variables {R k V1 P1 V2 : Type*} section ring variables [ring k] [add_comm_group V1] [affine_space V1 P1] [add_comm_group V2] variables [module k V1] [module k V2] include V1 section distrib_mul_action variables [monoid R] [distrib_mul_action R V2] [smul_comm_class k R V2] /-- The space of affine maps to a module inherits an `R`-action from the action on its codomain. -/ instance : distrib_mul_action R (P1 →ᵃ[k] V2) := { smul_add := λ c f g, ext $ λ p, smul_add _ _ _, smul_zero := λ c, ext $ λ p, smul_zero _ } end distrib_mul_action section module variables [semiring R] [module R V2] [smul_comm_class k R V2] /-- The space of affine maps taking values in an `R`-module is an `R`-module. -/ instance : module R (P1 →ᵃ[k] V2) := { smul := (•), add_smul := λ c₁ c₂ f, ext $ λ p, add_smul _ _ _, zero_smul := λ f, ext $ λ p, zero_smul _ _, .. affine_map.distrib_mul_action } variables (R) /-- The space of affine maps between two modules is linearly equivalent to the product of the domain with the space of linear maps, by taking the value of the affine map at `(0 : V1)` and the linear part. See note [bundled maps over different rings]-/ @[simps] def to_const_prod_linear_map : (V1 →ᵃ[k] V2) ≃ₗ[R] V2 × (V1 →ₗ[k] V2) := { to_fun := λ f, ⟨f 0, f.linear⟩, inv_fun := λ p, p.2.to_affine_map + const k V1 p.1, left_inv := λ f, by { ext, rw f.decomp, simp, }, right_inv := by { rintros ⟨v, f⟩, ext; simp, }, map_add' := by simp, map_smul' := by simp, } end module end ring section comm_ring variables [comm_ring k] [add_comm_group V1] [affine_space V1 P1] [add_comm_group V2] variables [module k V1] [module k V2] include V1 /-- `homothety c r` is the homothety (also known as dilation) about `c` with scale factor `r`. -/ def homothety (c : P1) (r : k) : P1 →ᵃ[k] P1 := r • (id k P1 -ᵥ const k P1 c) +ᵥ const k P1 c lemma homothety_def (c : P1) (r : k) : homothety c r = r • (id k P1 -ᵥ const k P1 c) +ᵥ const k P1 c := rfl lemma homothety_apply (c : P1) (r : k) (p : P1) : homothety c r p = r • (p -ᵥ c : V1) +ᵥ c := rfl lemma homothety_eq_line_map (c : P1) (r : k) (p : P1) : homothety c r p = line_map c p r := rfl @[simp] lemma homothety_one (c : P1) : homothety c (1:k) = id k P1 := by { ext p, simp [homothety_apply] } @[simp] lemma homothety_apply_same (c : P1) (r : k) : homothety c r c = c := line_map_same_apply c r lemma homothety_mul_apply (c : P1) (r₁ r₂ : k) (p : P1) : homothety c (r₁ * r₂) p = homothety c r₁ (homothety c r₂ p) := by simp [homothety_apply, mul_smul] lemma homothety_mul (c : P1) (r₁ r₂ : k) : homothety c (r₁ * r₂) = (homothety c r₁).comp (homothety c r₂) := ext $ homothety_mul_apply c r₁ r₂ @[simp] lemma homothety_zero (c : P1) : homothety c (0:k) = const k P1 c := by { ext p, simp [homothety_apply] } @[simp] lemma homothety_add (c : P1) (r₁ r₂ : k) : homothety c (r₁ + r₂) = r₁ • (id k P1 -ᵥ const k P1 c) +ᵥ homothety c r₂ := by simp only [homothety_def, add_smul, vadd_vadd] /-- `homothety` as a multiplicative monoid homomorphism. -/ def homothety_hom (c : P1) : k →* P1 →ᵃ[k] P1 := ⟨homothety c, homothety_one c, homothety_mul c⟩ @[simp] lemma coe_homothety_hom (c : P1) : ⇑(homothety_hom c : k →* _) = homothety c := rfl /-- `homothety` as an affine map. -/ def homothety_affine (c : P1) : k →ᵃ[k] (P1 →ᵃ[k] P1) := ⟨homothety c, (linear_map.lsmul k _).flip (id k P1 -ᵥ const k P1 c), function.swap (homothety_add c)⟩ @[simp] lemma coe_homothety_affine (c : P1) : ⇑(homothety_affine c : k →ᵃ[k] _) = homothety c := rfl end comm_ring end affine_map section variables {𝕜 E F : Type*} [ring 𝕜] [add_comm_group E] [add_comm_group F] [module 𝕜 E] [module 𝕜 F] /-- Applying an affine map to an affine combination of two points yields an affine combination of the images. -/ lemma convex.combo_affine_apply {x y : E} {a b : 𝕜} {f : E →ᵃ[𝕜] F} (h : a + b = 1) : f (a • x + b • y) = a • f x + b • f y := by { simp only [convex.combo_eq_smul_sub_add h, ←vsub_eq_sub], exact f.apply_line_map _ _ _ } end
9251b348e8cb8b137a26716863c6b3d61a6f855c
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/analysis/calculus/conformal/inner_product.lean
b81bb673c1eda9d31d6a406decfd0a85525801f7
[ "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
2,632
lean
/- Copyright (c) 2021 Yourong Zang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yourong Zang -/ import analysis.calculus.conformal.normed_space import analysis.inner_product_space.conformal_linear_map /-! # Conformal maps between inner product spaces > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. A function between inner product spaces is which has a derivative at `x` is conformal at `x` iff the derivative preserves inner products up to a scalar multiple. -/ noncomputable theory variables {E F : Type*} variables [normed_add_comm_group E] [normed_add_comm_group F] variables [inner_product_space ℝ E] [inner_product_space ℝ F] open_locale real_inner_product_space /-- A real differentiable map `f` is conformal at point `x` if and only if its differential `fderiv ℝ f x` at that point scales every inner product by a positive scalar. -/ lemma conformal_at_iff' {f : E → F} {x : E} : conformal_at f x ↔ ∃ (c : ℝ), 0 < c ∧ ∀ (u v : E), ⟪fderiv ℝ f x u, fderiv ℝ f x v⟫ = c * ⟪u, v⟫ := by rw [conformal_at_iff_is_conformal_map_fderiv, is_conformal_map_iff] /-- A real differentiable map `f` is conformal at point `x` if and only if its differential `f'` at that point scales every inner product by a positive scalar. -/ lemma conformal_at_iff {f : E → F} {x : E} {f' : E →L[ℝ] F} (h : has_fderiv_at f f' x) : conformal_at f x ↔ ∃ (c : ℝ), 0 < c ∧ ∀ (u v : E), ⟪f' u, f' v⟫ = c * ⟪u, v⟫ := by simp only [conformal_at_iff', h.fderiv] /-- The conformal factor of a conformal map at some point `x`. Some authors refer to this function as the characteristic function of the conformal map. -/ def conformal_factor_at {f : E → F} {x : E} (h : conformal_at f x) : ℝ := classical.some (conformal_at_iff'.mp h) lemma conformal_factor_at_pos {f : E → F} {x : E} (h : conformal_at f x) : 0 < conformal_factor_at h := (classical.some_spec $ conformal_at_iff'.mp h).1 lemma conformal_factor_at_inner_eq_mul_inner' {f : E → F} {x : E} (h : conformal_at f x) (u v : E) : ⟪(fderiv ℝ f x) u, (fderiv ℝ f x) v⟫ = (conformal_factor_at h : ℝ) * ⟪u, v⟫ := (classical.some_spec $ conformal_at_iff'.mp h).2 u v lemma conformal_factor_at_inner_eq_mul_inner {f : E → F} {x : E} {f' : E →L[ℝ] F} (h : has_fderiv_at f f' x) (H : conformal_at f x) (u v : E) : ⟪f' u, f' v⟫ = (conformal_factor_at H : ℝ) * ⟪u, v⟫ := (H.differentiable_at.has_fderiv_at.unique h) ▸ conformal_factor_at_inner_eq_mul_inner' H u v
186954a332e219afddea0d0d7a70cc0f2e675fcd
4727251e0cd73359b15b664c3170e5d754078599
/src/linear_algebra/lagrange.lean
fae4f3c345c356e7795551def79e85df7ca5b724
[ "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
9,743
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.big_operators.basic import ring_theory.polynomial.basic /-! # Lagrange interpolation ## Main definitions * `lagrange.basis s x` where `s : finset F` and `x : F`: the Lagrange basis polynomial that evaluates to `1` at `x` and `0` at other elements of `s`. * `lagrange.interpolate s f` where `s : finset F` and `f : F → F`: the Lagrange interpolant that evaluates to `f x` at `x` for `x ∈ s`. -/ noncomputable theory open_locale big_operators classical polynomial universe u namespace lagrange variables {F : Type u} [decidable_eq F] [field F] (s : finset F) variables {F' : Type u} [field F'] (s' : finset F') open polynomial /-- Lagrange basis polynomials that evaluate to 1 at `x` and 0 at other elements of `s`. -/ def basis (x : F) : F[X] := ∏ y in s.erase x, C (x - y)⁻¹ * (X - C y) @[simp] theorem basis_empty (x : F) : basis ∅ x = 1 := rfl @[simp] theorem basis_singleton_self (x : F) : basis {x} x = 1 := by rw [basis, finset.erase_singleton, finset.prod_empty] @[simp] theorem eval_basis_self (x : F) : (basis s x).eval x = 1 := begin rw [basis, ← coe_eval_ring_hom, (eval_ring_hom x).map_prod, coe_eval_ring_hom, finset.prod_eq_one], intros y hy, simp_rw [eval_mul, eval_sub, eval_C, eval_X], exact inv_mul_cancel (sub_ne_zero_of_ne (finset.ne_of_mem_erase hy).symm) end @[simp] theorem eval_basis_ne (x y : F) (h1 : y ∈ s) (h2 : y ≠ x) : (basis s x).eval y = 0 := begin rw [basis, ← coe_eval_ring_hom, (eval_ring_hom y).map_prod, coe_eval_ring_hom, finset.prod_eq_zero (finset.mem_erase.2 ⟨h2, h1⟩)], simp_rw [eval_mul, eval_sub, eval_C, eval_X, sub_self, mul_zero] end theorem eval_basis (x y : F) (h : y ∈ s) : (basis s x).eval y = if y = x then 1 else 0 := by { split_ifs with H, { subst H, apply eval_basis_self }, { exact eval_basis_ne s x y h H } } @[simp] theorem nat_degree_basis (x : F) (hx : x ∈ s) : (basis s x).nat_degree = s.card - 1 := begin unfold basis, generalize hsx : s.erase x = sx, have : x ∉ sx := hsx ▸ finset.not_mem_erase x s, rw [← finset.insert_erase hx, hsx, finset.card_insert_of_not_mem this, add_tsub_cancel_right], clear hx hsx s, revert this, apply sx.induction_on, { intros hx, rw [finset.prod_empty, nat_degree_one], refl }, { intros y s hys ih hx, rw [finset.mem_insert, not_or_distrib] at hx, have h1 : C (x - y)⁻¹ ≠ C 0 := λ h, hx.1 (eq_of_sub_eq_zero $ inv_eq_zero.1 $ C_inj.1 h), have h2 : X ^ 1 - C y ≠ 0 := by convert X_pow_sub_C_ne_zero zero_lt_one y, rw C_0 at h1, rw pow_one at h2, rw [finset.prod_insert hys, nat_degree_mul (mul_ne_zero h1 h2), ih hx.2, finset.card_insert_of_not_mem hys, nat_degree_mul h1 h2, nat_degree_C, zero_add, nat_degree, degree_X_sub_C, add_comm], refl, rw [ne, finset.prod_eq_zero_iff], rintro ⟨z, hzs, hz⟩, rw mul_eq_zero at hz, cases hz with hz hz, { rw [← C_0, C_inj, inv_eq_zero, sub_eq_zero] at hz, exact hx.2 (hz.symm ▸ hzs) }, { rw ← pow_one (X : F[X]) at hz, exact X_pow_sub_C_ne_zero zero_lt_one _ hz } } end variables (f : F → F) /-- Lagrange interpolation: given a finset `s` and a function `f : F → F`, `interpolate s f` is the unique polynomial of degree `< s.card` that takes value `f x` on all `x` in `s`. -/ def interpolate : F[X] := ∑ x in s, C (f x) * basis s x @[simp] theorem interpolate_empty (f) : interpolate (∅ : finset F) f = 0 := rfl @[simp] theorem interpolate_singleton (f) (x : F) : interpolate {x} f = C (f x) := by rw [interpolate, finset.sum_singleton, basis_singleton_self, mul_one] @[simp] theorem eval_interpolate (x) (H : x ∈ s) : eval x (interpolate s f) = f x := begin rw [interpolate, ←coe_eval_ring_hom, ring_hom.map_sum, coe_eval_ring_hom, finset.sum_eq_single x], { simp }, { intros y hy hxy, simp [eval_basis_ne s y x H hxy.symm] }, { intro h, exact (h H).elim } end theorem degree_interpolate_lt : (interpolate s f).degree < s.card := if H : s = ∅ then by { subst H, rw [interpolate_empty, degree_zero], exact with_bot.bot_lt_coe _ } else (degree_sum_le _ _).trans_lt $ (finset.sup_lt_iff $ with_bot.bot_lt_coe s.card).2 $ λ b _, calc (C (f b) * basis s b).degree ≤ (C (f b)).degree + (basis s b).degree : degree_mul_le _ _ ... ≤ 0 + (basis s b).degree : add_le_add_right degree_C_le _ ... = (basis s b).degree : zero_add _ ... ≤ (basis s b).nat_degree : degree_le_nat_degree ... = (s.card - 1 : ℕ) : by { rwa nat_degree_basis } ... < s.card : with_bot.coe_lt_coe.2 (nat.pred_lt $ mt finset.card_eq_zero.1 H) theorem degree_interpolate_erase {x} (hx : x ∈ s) : (interpolate (s.erase x) f).degree < (s.card - 1 : ℕ) := begin convert degree_interpolate_lt (s.erase x) f, rw finset.card_erase_of_mem hx, end theorem interpolate_eq_of_eval_eq (f g : F → F) {s : finset F} (hs : ∀ x ∈ s, f x = g x) : interpolate s f = interpolate s g := begin rw [interpolate, interpolate], refine finset.sum_congr rfl (λ x hx, _), rw hs x hx, end /-- Linear version of `interpolate`. -/ def linterpolate : (F → F) →ₗ[F] polynomial F := { to_fun := interpolate s, map_add' := λ f g, by { simp_rw [interpolate, ← finset.sum_add_distrib, ← add_mul, ← C_add], refl }, map_smul' := λ c f, by { simp_rw [interpolate, finset.smul_sum, C_mul', smul_smul], refl } } @[simp] lemma interpolate_add (f g) : interpolate s (f + g) = interpolate s f + interpolate s g := (linterpolate s).map_add f g @[simp] lemma interpolate_zero : interpolate s 0 = 0 := (linterpolate s).map_zero @[simp] lemma interpolate_neg (f) : interpolate s (-f) = -interpolate s f := (linterpolate s).map_neg f @[simp] lemma interpolate_sub (f g) : interpolate s (f - g) = interpolate s f - interpolate s g := (linterpolate s).map_sub f g @[simp] lemma interpolate_smul (c : F) (f) : interpolate s (c • f) = c • interpolate s f := (linterpolate s).map_smul c f theorem eq_zero_of_eval_eq_zero {f : F'[X]} (hf1 : f.degree < s'.card) (hf2 : ∀ x ∈ s', f.eval x = 0) : f = 0 := by_contradiction $ λ hf3, not_le_of_lt hf1 $ calc (s'.card : with_bot ℕ) ≤ f.roots.to_finset.card : with_bot.coe_le_coe.2 $ finset.card_le_of_subset $ λ x hx, (multiset.mem_to_finset).mpr $ (mem_roots hf3).2 $ hf2 x hx ... ≤ f.roots.card : with_bot.coe_le_coe.2 $ f.roots.to_finset_card_le ... ≤ f.degree : card_roots hf3 theorem eq_of_eval_eq {f g : F'[X]} (hf : f.degree < s'.card) (hg : g.degree < s'.card) (hfg : ∀ x ∈ s', f.eval x = g.eval x) : f = g := eq_of_sub_eq_zero $ eq_zero_of_eval_eq_zero s' (lt_of_le_of_lt (degree_sub_le f g) $ max_lt hf hg) (λ x hx, by rw [eval_sub, hfg x hx, sub_self]) theorem eq_interpolate_of_eval_eq {g : F[X]} (hg : g.degree < s.card) (hgf : ∀ x ∈ s, g.eval x = f x) : interpolate s f = g := eq_of_eval_eq s (degree_interpolate_lt _ _) hg $ λ x hx, begin rw hgf x hx, exact eval_interpolate _ _ _ hx, end theorem eq_interpolate (f : F[X]) (hf : f.degree < s.card) : interpolate s (λ x, f.eval x) = f := eq_of_eval_eq s (degree_interpolate_lt s _) hf $ λ x hx, eval_interpolate s _ x hx /-- Lagrange interpolation induces isomorphism between functions from `s` and polynomials of degree less than `s.card`. -/ def fun_equiv_degree_lt : degree_lt F s.card ≃ₗ[F] (s → F) := { to_fun := λ f x, f.1.eval x, map_add' := λ f g, funext $ λ x, eval_add, map_smul' := λ c f, funext $ by simp, inv_fun := λ f, ⟨interpolate s (λ x, if hx : x ∈ s then f ⟨x, hx⟩ else 0), mem_degree_lt.2 $ degree_interpolate_lt _ _⟩, left_inv := λ f, begin apply subtype.eq, simp only [subtype.coe_mk, subtype.val_eq_coe, dite_eq_ite], convert eq_interpolate s f (mem_degree_lt.1 f.2) using 1, rw interpolate_eq_of_eval_eq, intros x hx, rw if_pos hx end, right_inv := λ f, funext $ λ ⟨x, hx⟩, begin convert eval_interpolate s _ x hx, simp_rw dif_pos hx end } theorem interpolate_eq_interpolate_erase_add {x y : F} (hx : x ∈ s) (hy : y ∈ s) (hxy : x ≠ y) : interpolate s f = C (y - x)⁻¹ * ((X - C x) * interpolate (s.erase x) f + (C y - X) * interpolate (s.erase y) f) := begin refine eq_interpolate_of_eval_eq _ _ _ (λ z hz, _), { rw [degree_mul, degree_C (inv_ne_zero (sub_ne_zero.2 hxy.symm)), zero_add], refine lt_of_le_of_lt (degree_add_le _ _) (max_lt _ _), { rw [degree_mul, degree_X_sub_C], convert (with_bot.add_lt_add_iff_left with_bot.coe_ne_bot).2 (degree_interpolate_erase s f hx), simp [nat.one_add, nat.sub_one, nat.succ_pred_eq_of_pos (finset.card_pos.2 ⟨x, hx⟩)] }, { rw [degree_mul, ←neg_sub, degree_neg, degree_X_sub_C], convert (with_bot.add_lt_add_iff_left with_bot.coe_ne_bot).2 (degree_interpolate_erase s f hy), simp [nat.one_add, nat.sub_one, nat.succ_pred_eq_of_pos (finset.card_pos.2 ⟨y, hy⟩)] } }, { by_cases hzx : z = x, { simp [hzx, eval_interpolate (s.erase y) f x (finset.mem_erase_of_ne_of_mem hxy hx), inv_mul_eq_iff_eq_mul₀ (sub_ne_zero_of_ne hxy.symm)] }, { by_cases hzy : z = y, { simp [hzy, eval_interpolate (s.erase x) f y (finset.mem_erase_of_ne_of_mem hxy.symm hy), inv_mul_eq_iff_eq_mul₀ (sub_ne_zero_of_ne hxy.symm)] }, { simp only [eval_interpolate (s.erase x) f z (finset.mem_erase_of_ne_of_mem hzx hz), eval_interpolate (s.erase y) f z (finset.mem_erase_of_ne_of_mem hzy hz), inv_mul_eq_iff_eq_mul₀ (sub_ne_zero_of_ne hxy.symm), eval_mul, eval_C, eval_add, eval_sub, eval_X], ring } } } end end lagrange
f05008fcd65ee400aeb5ab6c1c3abfa79478dddf
ebbdcbd7ddc89a9ef7c3b397b301d5f5272a918f
/qp/p1_categories/c3_wtypes/s5_wtypes.lean
053d131b974a22d98d14769088105169835fadbe
[]
no_license
intoverflow/qvr
34b9ef23604738381ca20b7d622fd0399d88f2dd
0cfcd33fe4bf8d93851a00cec5bfd21e77105d74
refs/heads/master
1,616,591,570,371
1,492,575,772,000
1,492,575,772,000
80,061,627
0
0
null
null
null
null
UTF-8
Lean
false
false
3,773
lean
/- ----------------------------------------------------------------------- W-types. ----------------------------------------------------------------------- -/ import .s4_poly_endofuns namespace qp open stdaux universe variables ℓobj ℓhom /- ----------------------------------------------------------------------- W-types. ----------------------------------------------------------------------- -/ /-! #brief A W-type. -/ @[class] definition HasWType (C : Cat.{ℓobj ℓhom}) [C_HasFinal : HasFinal C] [C_HasAllPullbacks : HasAllPullbacks C] [C_HasDepProd : HasAllDepProd C] (P : PolyEndoFun C) := HasInitAlg P^.endo /-! #brief Helper for showing that a function has a W-Type. -/ definition HasWType.show (C : Cat.{ℓobj ℓhom}) [C_HasFinal : HasFinal C] [C_HasAllPullbacks : HasAllPullbacks C] [C_HasDepProd : HasAllDepProd C] (P : PolyEndoFun C) (ty : C^.obj) (hom : C^.hom (P^.endo^.obj ty) ty) (ini : ∀ (ty' : C^.obj) (hom' : C^.hom (P^.endo^.obj ty') ty') , C^.hom ty ty') (ωcomm : ∀ (ty' : C^.obj) (hom' : C^.hom (P^.endo^.obj ty') ty') , hom' ∘∘ P^.endo^.hom (ini ty' hom') = ini ty' hom' ∘∘ hom) (ωuniq : ∀ (ty' : C^.obj) (hom' : C^.hom (P^.endo^.obj ty') ty') (h : C^.hom ty ty') (ωh : hom' ∘∘ P^.endo^.hom h = h ∘∘ hom) , h = ini ty' hom') : HasWType C P := HasInit.show { carr := ty , hom := hom } (λ X, { hom := ini X^.carr X^.hom , comm := ωcomm X^.carr X^.hom }) (λ X h, EndoAlgHom.eq (ωuniq X^.carr X^.hom h^.hom h^.comm)) /-! #brief Adámek's construction for W-types. -/ definition HasWType.Adamek (C : Cat.{ℓobj ℓhom}) [C_HasInit : HasInit C] [C_HasFinal : HasFinal C] [C_HasAllPullbacks : HasAllPullbacks C] [C_HasDepProd : HasAllDepProd C] [C_HasAllCoLimitsFrom : HasAllCoLimitsFrom C NatCat] (P : PolyEndoFun C) (f_PresCoLimitsFrom : PresCoLimitsFrom (DepProdFun P^.hom) NatCat) : HasWType C P := NatIso.EndoAlgBij.HasInitAlg₁ (PolyEndoFun.Adamek P^.hom) P^.iso /-! #brief The carrier of a W-type. -/ definition wtype.carr {C : Cat.{ℓobj ℓhom}} [C_HasAllFinProducts : HasAllFinProducts C] [C_HasFinal : HasFinal C] [C_HasAllPullbacks : HasAllPullbacks C] [C_HasDepProd : HasAllDepProd C] (P : PolyEndoFun C) [P_HasWType : HasWType C P] : C^.obj := @initalg.carr _ _ P_HasWType /-! #brief The structure hom of a W-type. -/ definition wtype.fold {C : Cat.{ℓobj ℓhom}} [C_HasAllFinProducts : HasAllFinProducts C] [C_HasFinal : HasFinal C] [C_HasAllPullbacks : HasAllPullbacks C] [C_HasDepProd : HasAllDepProd C] (P : PolyEndoFun C) [P_HasWType : HasWType C P] : C^.hom (P^.endo^.obj (wtype.carr P)) (wtype.carr P) := @initalg.hom C P^.endo P_HasWType /-! #brief The inverse of the structure hom of a W-type. -/ definition wtype.unfold {C : Cat.{ℓobj ℓhom}} [C_HasAllFinProducts : HasAllFinProducts C] [C_HasFinal : HasFinal C] [C_HasAllPullbacks : HasAllPullbacks C] [C_HasDepProd : HasAllDepProd C] (P : PolyEndoFun C) [P_HasWType : HasWType C P] : C^.hom (wtype.carr P) (P^.endo^.obj (wtype.carr P)) := @initalg.unhom C P^.endo P_HasWType /-! #brief hom and elim are isos. -/ definition wtype.iso {C : Cat.{ℓobj ℓhom}} [C_HasAllFinProducts : HasAllFinProducts C] [C_HasFinal : HasFinal C] [C_HasAllPullbacks : HasAllPullbacks C] [C_HasDepProd : HasAllDepProd C] (P : PolyEndoFun C) [P_HasWType : HasWType C P] : Iso (wtype.fold P) (wtype.unfold P) := @initalg.iso C P^.endo P_HasWType end qp
bff4b254632083bdb3742f7cb9f9e8bdc9841135
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebra/gcd_monoid/multiset.lean
b00b7a2084a854c8c8cf50a77fefa1ad37fcaba5
[ "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
6,688
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 algebra.gcd_monoid.basic /-! # GCD and LCM operations on multisets ## Main definitions - `multiset.gcd` - the greatest common denominator of a `multiset` of elements of a `gcd_monoid` - `multiset.lcm` - the least common multiple of a `multiset` of elements of a `gcd_monoid` ## Implementation notes TODO: simplify with a tactic and `data.multiset.lattice` ## Tags multiset, gcd -/ namespace multiset variables {α : Type*} [cancel_comm_monoid_with_zero α] [normalized_gcd_monoid α] /-! ### lcm -/ section lcm /-- Least common multiple of a multiset -/ def lcm (s : multiset α) : α := s.fold gcd_monoid.lcm 1 @[simp] lemma lcm_zero : (0 : multiset α).lcm = 1 := fold_zero _ _ @[simp] lemma lcm_cons (a : α) (s : multiset α) : (a ::ₘ s).lcm = gcd_monoid.lcm a s.lcm := fold_cons_left _ _ _ _ @[simp] lemma lcm_singleton {a : α} : ({a} : multiset α).lcm = normalize a := (fold_singleton _ _ _).trans $ lcm_one_right _ @[simp] lemma lcm_add (s₁ s₂ : multiset α) : (s₁ + s₂).lcm = gcd_monoid.lcm s₁.lcm s₂.lcm := eq.trans (by simp [lcm]) (fold_add _ _ _ _ _) lemma lcm_dvd {s : multiset α} {a : α} : s.lcm ∣ a ↔ (∀ b ∈ s, b ∣ a) := multiset.induction_on s (by simp) (by simp [or_imp_distrib, forall_and_distrib, lcm_dvd_iff] {contextual := tt}) lemma dvd_lcm {s : multiset α} {a : α} (h : a ∈ s) : a ∣ s.lcm := lcm_dvd.1 dvd_rfl _ h lemma lcm_mono {s₁ s₂ : multiset α} (h : s₁ ⊆ s₂) : s₁.lcm ∣ s₂.lcm := lcm_dvd.2 $ assume b hb, dvd_lcm (h hb) @[simp] lemma normalize_lcm (s : multiset α) : normalize (s.lcm) = s.lcm := multiset.induction_on s (by simp) $ λ a s IH, by simp @[simp] theorem lcm_eq_zero_iff [nontrivial α] (s : multiset α) : s.lcm = 0 ↔ (0 : α) ∈ s := begin induction s using multiset.induction_on with a s ihs, { simp only [lcm_zero, one_ne_zero, not_mem_zero] }, { simp only [mem_cons, lcm_cons, lcm_eq_zero_iff, ihs, @eq_comm _ a] }, end variables [decidable_eq α] @[simp] lemma lcm_dedup (s : multiset α) : (dedup s).lcm = s.lcm := multiset.induction_on s (by simp) $ λ a s IH, begin by_cases a ∈ s; simp [IH, h], unfold lcm, rw [← cons_erase h, fold_cons_left, ← lcm_assoc, lcm_same], apply lcm_eq_of_associated_left (associated_normalize _), end @[simp] lemma lcm_ndunion (s₁ s₂ : multiset α) : (ndunion s₁ s₂).lcm = gcd_monoid.lcm s₁.lcm s₂.lcm := by { rw [← lcm_dedup, dedup_ext.2, lcm_dedup, lcm_add], simp } @[simp] lemma lcm_union (s₁ s₂ : multiset α) : (s₁ ∪ s₂).lcm = gcd_monoid.lcm s₁.lcm s₂.lcm := by { rw [← lcm_dedup, dedup_ext.2, lcm_dedup, lcm_add], simp } @[simp] lemma lcm_ndinsert (a : α) (s : multiset α) : (ndinsert a s).lcm = gcd_monoid.lcm a s.lcm := by { rw [← lcm_dedup, dedup_ext.2, lcm_dedup, lcm_cons], simp } end lcm /-! ### gcd -/ section gcd /-- Greatest common divisor of a multiset -/ def gcd (s : multiset α) : α := s.fold gcd_monoid.gcd 0 @[simp] lemma gcd_zero : (0 : multiset α).gcd = 0 := fold_zero _ _ @[simp] lemma gcd_cons (a : α) (s : multiset α) : (a ::ₘ s).gcd = gcd_monoid.gcd a s.gcd := fold_cons_left _ _ _ _ @[simp] lemma gcd_singleton {a : α} : ({a} : multiset α).gcd = normalize a := (fold_singleton _ _ _).trans $ gcd_zero_right _ @[simp] lemma gcd_add (s₁ s₂ : multiset α) : (s₁ + s₂).gcd = gcd_monoid.gcd s₁.gcd s₂.gcd := eq.trans (by simp [gcd]) (fold_add _ _ _ _ _) lemma dvd_gcd {s : multiset α} {a : α} : a ∣ s.gcd ↔ (∀ b ∈ s, a ∣ b) := multiset.induction_on s (by simp) (by simp [or_imp_distrib, forall_and_distrib, dvd_gcd_iff] {contextual := tt}) lemma gcd_dvd {s : multiset α} {a : α} (h : a ∈ s) : s.gcd ∣ a := dvd_gcd.1 dvd_rfl _ h lemma gcd_mono {s₁ s₂ : multiset α} (h : s₁ ⊆ s₂) : s₂.gcd ∣ s₁.gcd := dvd_gcd.2 $ assume b hb, gcd_dvd (h hb) @[simp] lemma normalize_gcd (s : multiset α) : normalize (s.gcd) = s.gcd := multiset.induction_on s (by simp) $ λ a s IH, by simp theorem gcd_eq_zero_iff (s : multiset α) : s.gcd = 0 ↔ ∀ (x : α), x ∈ s → x = 0 := begin split, { intros h x hx, apply eq_zero_of_zero_dvd, rw ← h, apply gcd_dvd hx }, { apply s.induction_on, { simp }, intros a s sgcd h, simp [h a (mem_cons_self a s), sgcd (λ x hx, h x (mem_cons_of_mem hx))] } end lemma gcd_map_mul (a : α) (s : multiset α) : (s.map ((*) a)).gcd = normalize a * s.gcd := begin refine s.induction_on _ (λ b s ih, _), { simp_rw [map_zero, gcd_zero, mul_zero] }, { simp_rw [map_cons, gcd_cons, ← gcd_mul_left], rw ih, apply ((normalize_associated a).mul_right _).gcd_eq_right }, end section variables [decidable_eq α] @[simp] lemma gcd_dedup (s : multiset α) : (dedup s).gcd = s.gcd := multiset.induction_on s (by simp) $ λ a s IH, begin by_cases a ∈ s; simp [IH, h], unfold gcd, rw [← cons_erase h, fold_cons_left, ← gcd_assoc, gcd_same], apply (associated_normalize _).gcd_eq_left, end @[simp] lemma gcd_ndunion (s₁ s₂ : multiset α) : (ndunion s₁ s₂).gcd = gcd_monoid.gcd s₁.gcd s₂.gcd := by { rw [← gcd_dedup, dedup_ext.2, gcd_dedup, gcd_add], simp } @[simp] lemma gcd_union (s₁ s₂ : multiset α) : (s₁ ∪ s₂).gcd = gcd_monoid.gcd s₁.gcd s₂.gcd := by { rw [← gcd_dedup, dedup_ext.2, gcd_dedup, gcd_add], simp } @[simp] lemma gcd_ndinsert (a : α) (s : multiset α) : (ndinsert a s).gcd = gcd_monoid.gcd a s.gcd := by { rw [← gcd_dedup, dedup_ext.2, gcd_dedup, gcd_cons], simp } end lemma extract_gcd' (s t : multiset α) (hs : ∃ x, x ∈ s ∧ x ≠ (0 : α)) (ht : s = t.map ((*) s.gcd)) : t.gcd = 1 := ((@mul_right_eq_self₀ _ _ s.gcd _).1 $ by conv_lhs { rw [← normalize_gcd, ← gcd_map_mul, ← ht] }) .resolve_right $ by { contrapose! hs, exact s.gcd_eq_zero_iff.1 hs } lemma extract_gcd (s : multiset α) (hs : s ≠ 0) : ∃ t : multiset α, s = t.map ((*) s.gcd) ∧ t.gcd = 1 := begin classical, by_cases h : ∀ x ∈ s, x = (0 : α), { use repeat 1 s.card, rw [map_repeat, eq_repeat, mul_one, s.gcd_eq_zero_iff.2 h, ←nsmul_singleton, ←gcd_dedup], rw [dedup_nsmul (card_pos.2 hs).ne', dedup_singleton, gcd_singleton], exact ⟨⟨rfl, h⟩, normalize_one⟩ }, { choose f hf using @gcd_dvd _ _ _ s, have := _, push_neg at h, refine ⟨s.pmap @f (λ _, id), this, extract_gcd' s _ h this⟩, rw map_pmap, conv_lhs { rw [← s.map_id, ← s.pmap_eq_map _ _ (λ _, id)] }, congr' with x hx, rw [id, ← hf hx] }, end end gcd end multiset
dbb4399bd5c0b6c03cd6819532eae2902069f9bc
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/tactic/equiv_rw.lean
766703bf8924f8e3428d5e76b0fa78cae8feed90
[ "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
13,720
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import logic.equiv.defs import tactic.clear import tactic.simp_result import tactic.apply import control.equiv_functor.instances -- these make equiv_rw more powerful! import logic.equiv.functor -- so do these! /-! # The `equiv_rw` tactic transports goals or hypotheses along equivalences. The basic syntax is `equiv_rw e`, where `e : α ≃ β` is an equivalence. This will try to replace occurrences of `α` in the goal with `β`, for example transforming * `⊢ α` to `⊢ β`, * `⊢ option α` to `⊢ option β` * `⊢ {a // P}` to `{b // P (⇑(equiv.symm e) b)}` The tactic can also be used to rewrite hypotheses, using the syntax `equiv_rw e at h`. ## Implementation details The main internal function is `equiv_rw_type e t`, which attempts to turn an expression `e : α ≃ β` into a new equivalence with left hand side `t`. As an example, with `t = option α`, it will generate `functor.map_equiv option e`. This is achieved by generating a new synthetic goal `%%t ≃ _`, and calling `solve_by_elim` with an appropriate set of congruence lemmas. To avoid having to specify the relevant congruence lemmas by hand, we mostly rely on `equiv_functor.map_equiv` and `bifunctor.map_equiv` along with some structural congruence lemmas such as * `equiv.arrow_congr'`, * `equiv.subtype_equiv_of_subtype'`, * `equiv.sigma_congr_left'`, and * `equiv.Pi_congr_left'`. The main `equiv_rw` function, when operating on the goal, simply generates a new equivalence `e'` with left hand side matching the target, and calls `apply e'.inv_fun`. When operating on a hypothesis `x : α`, we introduce a new fact `h : x = e.symm (e x)`, revert this, and then attempt to `generalize`, replacing all occurrences of `e x` with a new constant `y`, before `intro`ing and `subst`ing `h`, and renaming `y` back to `x`. ## Future improvements In a future PR I anticipate that `derive equiv_functor` should work on many examples, (internally using `transport`, which is in turn based on `equiv_rw`) and we can incrementally bootstrap the strength of `equiv_rw`. An ambitious project might be to add `equiv_rw!`, a tactic which, when failing to find appropriate `equiv_functor` instances, attempts to `derive` them on the spot. For now `equiv_rw` is entirely based on `equiv`, but the framework can readily be generalised to also work with other types of equivalences, for example specific notations such as ring equivalence (`≃+*`), or general categorical isomorphisms (`≅`). This will allow us to transport across more general types of equivalences, but this will wait for another subsequent PR. -/ namespace tactic /-- A list of lemmas used for constructing congruence equivalences. -/ -- Although this looks 'hard-coded', in fact the lemma `equiv_functor.map_equiv` -- allows us to extend `equiv_rw` simply by constructing new instance so `equiv_functor`. -- TODO: We should also use `category_theory.functorial` and `category_theory.hygienic` instances. -- (example goal: we could rewrite along an isomorphism of rings (either as `R ≅ S` or `R ≃+* S`) -- and turn an `x : mv_polynomial σ R` into an `x : mv_polynomial σ S`.). meta def equiv_congr_lemmas : list (tactic expr) := [ `equiv.of_iff, -- TODO decide what to do with this; it's an equiv_bifunctor? `equiv.equiv_congr, -- The function arrow is technically a bifunctor `Typeᵒᵖ → Type → Type`, -- but the pattern matcher will never see this. `equiv.arrow_congr', -- Allow rewriting in subtypes: `equiv.subtype_equiv_of_subtype', -- Allow rewriting in the first component of a sigma-type: `equiv.sigma_congr_left', -- Allow rewriting ∀s: -- (You might think that repeated application of `equiv.forall_congr' -- would handle the higher arity cases, but unfortunately unification is not clever enough.) `equiv.forall₃_congr', `equiv.forall₂_congr', `equiv.forall_congr', -- Allow rewriting in argument of Pi types: `equiv.Pi_congr_left', -- Handles `sum` and `prod`, and many others: `bifunctor.map_equiv, -- Handles `list`, `option`, `unique`, and many others: `equiv_functor.map_equiv, -- We have to filter results to ensure we don't cheat and use exclusively -- `equiv.refl` and `iff.refl`! `equiv.refl, `iff.refl ].map (λ n, mk_const n) declare_trace equiv_rw_type /-- Configuration structure for `equiv_rw`. * `max_depth` bounds the search depth for equivalences to rewrite along. The default value is 10. (e.g., if you're rewriting along `e : α ≃ β`, and `max_depth := 2`, you can rewrite `option (option α))` but not `option (option (option α))`. -/ meta structure equiv_rw_cfg := (max_depth : ℕ := 10) /-- Implementation of `equiv_rw_type`, using `solve_by_elim`. Expects a goal of the form `t ≃ _`, and tries to solve it using `eq : α ≃ β` and congruence lemmas. -/ meta def equiv_rw_type_core (eq : expr) (cfg : equiv_rw_cfg) : tactic unit := do /- We now call `solve_by_elim` to try to generate the requested equivalence. There are a few subtleties! * We make sure that `eq` is the first lemma, so it is applied whenever possible. * In `equiv_congr_lemmas`, we put `equiv.refl` last so it is only used when it is not possible to descend further. * Since some congruence lemmas generate subgoals with `∀` statements, we use the `pre_apply` subtactic of `solve_by_elim` to preprocess each new goal with `intros`. -/ solve_by_elim { use_symmetry := false, use_exfalso := false, lemma_thunks := some (pure eq :: equiv_congr_lemmas), ctx_thunk := pure [], max_depth := cfg.max_depth, -- Subgoals may contain function types, -- and we want to continue trying to construct equivalences after the binders. pre_apply := tactic.intros >> skip, backtrack_all_goals := tt, -- If solve_by_elim gets stuck, make sure it isn't because there's a later `≃` or `↔` goal -- that we should still attempt. discharger := `[success_if_fail { match_target _ ≃ _ }] >> `[success_if_fail { match_target _ ↔ _ }] >> (`[show _ ≃ _] <|> `[show _ ↔ _]) <|> trace_if_enabled `equiv_rw_type "Failed, no congruence lemma applied!" >> failed, -- We use the `accept` tactic in `solve_by_elim` to provide tracing. accept := λ goals, lock_tactic_state (do when_tracing `equiv_rw_type (do goals.mmap pp >>= λ goals, trace format!"So far, we've built: {goals}"), done <|> when_tracing `equiv_rw_type (do gs ← get_goals, gs ← gs.mmap (λ g, infer_type g >>= pp), trace format!"Attempting to adapt to {gs}")) } /-- `equiv_rw_type e t` rewrites the type `t` using the equivalence `e : α ≃ β`, returning a new equivalence `t ≃ t'`. -/ meta def equiv_rw_type (eqv : expr) (ty : expr) (cfg : equiv_rw_cfg) : tactic expr := do when_tracing `equiv_rw_type (do ty_pp ← pp ty, eqv_pp ← pp eqv, eqv_ty_pp ← infer_type eqv >>= pp, trace format!"Attempting to rewrite the type `{ty_pp}` using `{eqv_pp} : {eqv_ty_pp}`."), `(_ ≃ _) ← infer_type eqv | fail format!"{eqv} must be an `equiv`", -- We prepare a synthetic goal of type `(%%ty ≃ _)`, for some placeholder right hand side. equiv_ty ← to_expr ``(%%ty ≃ _), -- Now call `equiv_rw_type_core`. new_eqv ← prod.snd <$> (solve_aux equiv_ty $ equiv_rw_type_core eqv cfg), -- Check that we actually used the equivalence `eq` -- (`equiv_rw_type_core` will always find `equiv.refl`, -- but hopefully only after all other possibilities) new_eqv ← instantiate_mvars new_eqv, -- We previously had `guard (eqv.occurs new_eqv)` here, but `kdepends_on` is more reliable. kdepends_on new_eqv eqv >>= guardb <|> (do eqv_pp ← pp eqv, ty_pp ← pp ty, fail format!"Could not construct an equivalence from {eqv_pp} of the form: {ty_pp} ≃ _"), -- Finally we simplify the resulting equivalence, -- to compress away some `map_equiv equiv.refl` subexpressions. prod.fst <$> new_eqv.simp {fail_if_unchanged := ff} mk_simp_attribute equiv_rw_simp "The simpset `equiv_rw_simp` is used by the tactic `equiv_rw` to simplify applications of equivalences and their inverses." attribute [equiv_rw_simp] equiv.symm_symm equiv.apply_symm_apply equiv.symm_apply_apply /-- Attempt to replace the hypothesis with name `x` by transporting it along the equivalence in `e : α ≃ β`. -/ meta def equiv_rw_hyp (x : name) (e : expr) (cfg : equiv_rw_cfg := {}) : tactic unit := -- We call `dsimp_result` to perform the beta redex introduced by `revert` dsimp_result (do x' ← get_local x, x_ty ← infer_type x', -- Adapt `e` to an equivalence with left-hand-side `x_ty`. e ← equiv_rw_type e x_ty cfg, eq ← to_expr ``(%%x' = equiv.symm %%e (equiv.to_fun %%e %%x')), prf ← to_expr ``((equiv.symm_apply_apply %%e %%x').symm), h ← note_anon eq prf, -- Revert the new hypothesis, so it is also part of the goal. revert h, ex ← to_expr ``(equiv.to_fun %%e %%x'), -- Now call `generalize`, -- attempting to replace all occurrences of `e x`, -- calling it for now `j : β`, with `k : x = e.symm j`. generalize ex (by apply_opt_param) transparency.none, -- Reintroduce `x` (now of type `b`), and the hypothesis `h`. intro x, h ← intro1, -- Finally, if we're working on properties, substitute along `h`, then do some cleanup, -- and if we're working on data, just throw out the old `x`. b ← target >>= is_prop, if b then do subst h, `[try { simp only with equiv_rw_simp }] else -- We may need to unfreeze `x` before we can `clear` it. unfreezing_hyp x' (clear' tt [x']) <|> fail format!"equiv_rw expected to be able to clear the original hypothesis {x}, but couldn't.", skip) {fail_if_unchanged := ff} tt -- call `dsimp_result` with `no_defaults := tt`. /-- Rewrite the goal using an equiv `e`. -/ meta def equiv_rw_target (e : expr) (cfg : equiv_rw_cfg := {}) : tactic unit := do t ← target, e ← equiv_rw_type e t cfg, s ← to_expr ``(equiv.inv_fun %%e), tactic.eapply s, skip end tactic namespace tactic.interactive open tactic setup_tactic_parser /-- Auxiliary function to call `equiv_rw_hyp` on a `list pexpr` recursively. -/ meta def equiv_rw_hyp_aux (hyp : name) (cfg : equiv_rw_cfg) (permissive : bool := ff) : list expr → itactic | [] := skip | (e :: t) := do if permissive then equiv_rw_hyp hyp e cfg <|> skip else equiv_rw_hyp hyp e cfg, equiv_rw_hyp_aux t /-- Auxiliary function to call `equiv_rw_target` on a `list pexpr` recursively. -/ meta def equiv_rw_target_aux (cfg : equiv_rw_cfg) (permissive : bool) : list expr → itactic | [] := skip | (e :: t) := do if permissive then equiv_rw_target e cfg <|> skip else equiv_rw_target e cfg, equiv_rw_target_aux t /-- `equiv_rw e at h₁ h₂ ⋯`, where each `hᵢ : α` is a hypothesis, and `e : α ≃ β`, will attempt to transport each `hᵢ` along `e`, producing a new hypothesis `hᵢ : β`, with all occurrences of `hᵢ` in other hypotheses and the goal replaced with `e.symm hᵢ`. `equiv_rw e` will attempt to transport the goal along an equivalence `e : α ≃ β`. In its minimal form it replaces the goal `⊢ α` with `⊢ β` by calling `apply e.inv_fun`. `equiv_rw [e₁, e₂, ⋯] at h₁ h₂ ⋯` is equivalent to `{ equiv_rw [e₁, e₂, ⋯] at h₁, equiv_rw [e₁, e₂, ⋯] at h₂, ⋯ }`. `equiv_rw [e₁, e₂, ⋯] at *` will attempt to apply `equiv_rw [e₁, e₂, ⋯]` on the goal and on each expression available in the local context (except on the `eᵢ`s themselves), failing silently when it can't. Failing on a rewrite for a certain `eᵢ` at a certain hypothesis `h` doesn't stop `equiv_rw` from trying the other equivalences on the list at `h`. This only happens for the wildcard location. `equiv_rw` will also try rewriting under (equiv_)functors, so it can turn a hypothesis `h : list α` into `h : list β` or a goal `⊢ unique α` into `⊢ unique β`. The maximum search depth for rewriting in subexpressions is controlled by `equiv_rw e {max_depth := n}`. -/ meta def equiv_rw (l : parse pexpr_list_or_texpr) (locat : parse location) (cfg : equiv_rw_cfg := {}) : itactic := do es ← l.mmap (λ e, to_expr e), match locat with | loc.wildcard := do equiv_rw_target_aux cfg tt es, ctx ← local_context, ctx.mmap (λ e, if e ∈ es then skip else equiv_rw_hyp_aux e.local_pp_name cfg tt es), skip | loc.ns names := do names.mmap (λ hyp', match hyp' with | some hyp := equiv_rw_hyp_aux hyp cfg ff es | none := equiv_rw_target_aux cfg ff es end), skip end add_tactic_doc { name := "equiv_rw", category := doc_category.tactic, decl_names := [`tactic.interactive.equiv_rw], tags := ["rewriting", "equiv", "transport"] } /-- Solve a goal of the form `t ≃ _`, by constructing an equivalence from `e : α ≃ β`. This is the same equivalence that `equiv_rw` would use to rewrite a term of type `t`. A typical usage might be: ``` have e' : option α ≃ option β := by equiv_rw_type e ``` -/ meta def equiv_rw_type (e : parse texpr) (cfg : equiv_rw_cfg := {}) : itactic := do `(%%t ≃ _) ← target | fail "`equiv_rw_type` solves goals of the form `t ≃ _`.", e ← to_expr e, tactic.equiv_rw_type e t cfg >>= tactic.exact add_tactic_doc { name := "equiv_rw_type", category := doc_category.tactic, decl_names := [`tactic.interactive.equiv_rw_type], tags := ["rewriting", "equiv", "transport"] } end tactic.interactive
97b59d901e1d6aff1ae6d0406888459a59a6e633
453dcd7c0d1ef170b0843a81d7d8caedc9741dce
/data/equiv/basic.lean
329b733a5eaa50c4ff9328a7696b6bf43120828c
[ "Apache-2.0" ]
permissive
amswerdlow/mathlib
9af77a1f08486d8fa059448ae2d97795bd12ec0c
27f96e30b9c9bf518341705c99d641c38638dfd0
refs/heads/master
1,585,200,953,598
1,534,275,532,000
1,534,275,532,000
144,564,700
0
0
null
1,534,156,197,000
1,534,156,197,000
null
UTF-8
Lean
false
false
25,928
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Mario Carneiro In the standard library we cannot assume the univalence axiom. We say two types are equivalent if they are isomorphic. Two equivalent types have the same cardinality. -/ import logic.function data.set.basic open function universes u v w variables {α : Sort u} {β : Sort v} {γ : Sort w} /-- `α ≃ β` is the type of functions from `α → β` with a two-sided inverse. -/ structure equiv (α : Sort*) (β : Sort*) := (to_fun : α → β) (inv_fun : β → α) (left_inv : left_inverse inv_fun to_fun) (right_inv : right_inverse inv_fun to_fun) namespace equiv /-- `perm α` is the type of bijections from `α` to itself. -/ @[reducible] def perm (α : Sort*) := equiv α α infix ` ≃ `:50 := equiv instance : has_coe_to_fun (α ≃ β) := ⟨_, to_fun⟩ @[simp] theorem coe_fn_mk (f : α → β) (g l r) : (equiv.mk f g l r : α → β) = f := rfl theorem eq_of_to_fun_eq : ∀ {e₁ e₂ : equiv α β}, (e₁ : α → β) = e₂ → e₁ = e₂ | ⟨f₁, g₁, l₁, r₁⟩ ⟨f₂, g₂, l₂, r₂⟩ h := have f₁ = f₂, from h, have g₁ = g₂, from funext $ assume x, have f₁ (g₁ x) = f₂ (g₂ x), from (r₁ x).trans (r₂ x).symm, have f₁ (g₁ x) = f₁ (g₂ x), by subst f₂; exact this, show g₁ x = g₂ x, from injective_of_left_inverse l₁ this, by simp * lemma ext (f g : equiv α β) (H : ∀ x, f x = g x) : f = g := eq_of_to_fun_eq (funext H) @[refl] protected def refl (α : Sort*) : α ≃ α := ⟨id, id, λ x, rfl, λ x, rfl⟩ @[symm] protected def symm (e : α ≃ β) : β ≃ α := ⟨e.inv_fun, e.to_fun, e.right_inv, e.left_inv⟩ @[trans] protected def trans (e₁ : α ≃ β) (e₂ : β ≃ γ) : α ≃ γ := ⟨e₂.to_fun ∘ e₁.to_fun, e₁.inv_fun ∘ e₂.inv_fun, e₂.left_inv.comp e₁.left_inv, e₂.right_inv.comp e₁.right_inv⟩ protected theorem bijective : ∀ f : α ≃ β, bijective f | ⟨f, g, h₁, h₂⟩ := ⟨injective_of_left_inverse h₁, surjective_of_has_right_inverse ⟨_, h₂⟩⟩ protected theorem subsingleton (e : α ≃ β) : ∀ [subsingleton β], subsingleton α | ⟨H⟩ := ⟨λ a b, e.bijective.1 (H _ _)⟩ protected def decidable_eq (e : α ≃ β) [H : decidable_eq β] : decidable_eq α | a b := decidable_of_iff _ e.bijective.1.eq_iff protected def cast {α β : Sort*} (h : α = β) : α ≃ β := ⟨cast h, cast h.symm, λ x, by cases h; refl, λ x, by cases h; refl⟩ @[simp] theorem coe_fn_symm_mk (f : α → β) (g l r) : ((equiv.mk f g l r).symm : β → α) = g := rfl @[simp] theorem refl_apply (x : α) : equiv.refl α x = x := rfl @[simp] theorem trans_apply : ∀ (f : α ≃ β) (g : β ≃ γ) (a : α), (f.trans g) a = g (f a) | ⟨f₁, g₁, l₁, r₁⟩ ⟨f₂, g₂, l₂, r₂⟩ a := rfl @[simp] theorem apply_inverse_apply : ∀ (e : α ≃ β) (x : β), e (e.symm x) = x | ⟨f₁, g₁, l₁, r₁⟩ x := by simp [equiv.symm]; rw r₁ @[simp] theorem inverse_apply_apply : ∀ (e : α ≃ β) (x : α), e.symm (e x) = x | ⟨f₁, g₁, l₁, r₁⟩ x := by simp [equiv.symm]; rw l₁ @[simp] lemma inverse_trans_apply (f : α ≃ β) (g : β ≃ γ) (a : γ) : (f.trans g).symm a = f.symm (g.symm a) := rfl @[simp] theorem apply_eq_iff_eq : ∀ (f : α ≃ β) (x y : α), f x = f y ↔ x = y | ⟨f₁, g₁, l₁, r₁⟩ x y := (injective_of_left_inverse l₁).eq_iff @[simp] theorem cast_apply {α β} (h : α = β) (x : α) : equiv.cast h x = cast h x := rfl theorem apply_eq_iff_eq_inverse_apply : ∀ (f : α ≃ β) (x : α) (y : β), f x = y ↔ x = f.symm y | ⟨f₁, g₁, l₁, r₁⟩ x y := by simp [equiv.symm]; show f₁ x = y ↔ x = g₁ y; from ⟨λ e : f₁ x = y, e ▸ (l₁ x).symm, λ e : x = g₁ y, e.symm ▸ r₁ y⟩ @[simp] theorem symm_symm (e : α ≃ β) : e.symm.symm = e := by cases e; refl @[simp] theorem trans_refl (e : α ≃ β) : e.trans (equiv.refl β) = e := by cases e; refl @[simp] theorem refl_trans (e : α ≃ β) : (equiv.refl α).trans e = e := by cases e; refl @[simp] theorem symm_trans (e : α ≃ β) : e.symm.trans e = equiv.refl β := ext _ _ (by simp) @[simp] theorem trans_symm (e : α ≃ β) : e.trans e.symm = equiv.refl α := ext _ _ (by simp) theorem left_inverse_symm (f : equiv α β) : left_inverse f.symm f := f.left_inv theorem right_inverse_symm (f : equiv α β) : function.right_inverse f.symm f := f.right_inv protected lemma image_eq_preimage {α β} (e : α ≃ β) (s : set α) : e '' s = e.symm ⁻¹' s := set.ext $ assume x, set.mem_image_iff_of_inverse e.left_inv e.right_inv protected lemma subset_image {α β} (e : α ≃ β) (s : set α) (t : set β) : t ⊆ e '' s ↔ e.symm '' t ⊆ s := by rw [set.image_subset_iff, e.image_eq_preimage] lemma symm_image_image {α β} (f : equiv α β) (s : set α) : f.symm '' (f '' s) = s := by rw [← set.image_comp]; simpa using set.image_id s protected lemma image_compl {α β} (f : equiv α β) (s : set α) : f '' -s = -(f '' s) := set.image_compl_eq f.bijective /- The group of permutations (self-equivalences) of a type `α` -/ namespace perm instance perm_group {α : Type u} : group (perm α) := begin refine { mul := λ f g, equiv.trans g f, one := equiv.refl α, inv:= equiv.symm, ..}; intros; apply equiv.ext; try { apply trans_apply }, apply inverse_apply_apply end @[simp] theorem mul_apply {α : Type u} (f g : perm α) (x) : (f * g) x = f (g x) := equiv.trans_apply _ _ _ @[simp] theorem one_apply {α : Type u} (x) : (1 : perm α) x = x := rfl @[simp] lemma inv_apply_self {α : Type u} (f : perm α) (x) : f⁻¹ (f x) = x := equiv.inverse_apply_apply _ _ @[simp] lemma apply_inv_self {α : Type u} (f : perm α) (x) : f (f⁻¹ x) = x := equiv.apply_inverse_apply _ _ lemma one_def {α : Type u} : (1 : perm α) = equiv.refl α := rfl lemma mul_def {α : Type u} (f g : perm α) : f * g = g.trans f := rfl lemma inv_def {α : Type u} (f : perm α) : f⁻¹ = f.symm := rfl end perm def equiv_empty (h : α → false) : α ≃ empty := ⟨λ x, (h x).elim, λ e, e.rec _, λ x, (h x).elim, λ e, e.rec _⟩ def false_equiv_empty : false ≃ empty := equiv_empty _root_.id def empty_of_not_nonempty {α : Sort*} (h : ¬ nonempty α) : α ≃ empty := ⟨assume a, (h ⟨a⟩).elim, assume e, e.rec_on _, assume a, (h ⟨a⟩).elim, assume e, e.rec_on _⟩ protected def ulift {α : Type u} : ulift α ≃ α := ⟨ulift.down, ulift.up, ulift.up_down, λ a, rfl⟩ protected def plift : plift α ≃ α := ⟨plift.down, plift.up, plift.up_down, plift.down_up⟩ @[congr] def arrow_congr {α₁ β₁ α₂ β₂ : Sort*} : α₁ ≃ α₂ → β₁ ≃ β₂ → (α₁ → β₁) ≃ (α₂ → β₂) | ⟨f₁, g₁, l₁, r₁⟩ ⟨f₂, g₂, l₂, r₂⟩ := ⟨λ (h : α₁ → β₁) (a : α₂), f₂ (h (g₁ a)), λ (h : α₂ → β₂) (a : α₁), g₂ (h (f₁ a)), λ h, by funext a; dsimp; rw [l₁, l₂], λ h, by funext a; dsimp; rw [r₁, r₂]⟩ def punit_equiv_punit : punit.{v} ≃ punit.{w} := ⟨λ _, punit.star, λ _, punit.star, λ u, by cases u; refl, λ u, by cases u; reflexivity⟩ section @[simp] def arrow_unit_equiv_unit (α : Sort*) : (α → punit.{v}) ≃ punit.{w} := ⟨λ f, punit.star, λ u f, punit.star, λ f, by funext x; cases f x; refl, λ u, by cases u; reflexivity⟩ @[simp] def unit_arrow_equiv (α : Sort*) : (punit.{u} → α) ≃ α := ⟨λ f, f punit.star, λ a u, a, λ f, by funext x; cases x; refl, λ u, rfl⟩ @[simp] def empty_arrow_equiv_unit (α : Sort*) : (empty → α) ≃ punit.{u} := ⟨λ f, punit.star, λ u e, e.rec _, λ f, funext $ λ x, x.rec _, λ u, by cases u; refl⟩ @[simp] def false_arrow_equiv_unit (α : Sort*) : (false → α) ≃ punit.{u} := calc (false → α) ≃ (empty → α) : arrow_congr false_equiv_empty (equiv.refl _) ... ≃ punit : empty_arrow_equiv_unit _ def arrow_empty_unit {α : Sort*} : (empty → α) ≃ punit.{u} := ⟨λf, punit.star, λu e, e.rec_on _, assume f, funext $ assume e, e.rec_on _, assume u, punit_eq _ _⟩ end @[congr] def prod_congr {α₁ β₁ α₂ β₂ : Sort*} : α₁ ≃ α₂ → β₁ ≃ β₂ → (α₁ × β₁) ≃ (α₂ × β₂) | ⟨f₁, g₁, l₁, r₁⟩ ⟨f₂, g₂, l₂, r₂⟩ := ⟨λ ⟨a, b⟩, (f₁ a, f₂ b), λ ⟨a, b⟩, (g₁ a, g₂ b), λ ⟨a, b⟩, show (g₁ (f₁ a), g₂ (f₂ b)) = (a, b), by rw [l₁ a, l₂ b], λ ⟨a, b⟩, show (f₁ (g₁ a), f₂ (g₂ b)) = (a, b), by rw [r₁ a, r₂ b]⟩ @[simp] theorem prod_congr_apply {α₁ β₁ α₂ β₂ : Sort*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) (a : α₁) (b : β₁) : prod_congr e₁ e₂ (a, b) = (e₁ a, e₂ b) := by cases e₁; cases e₂; refl @[simp] def prod_comm (α β : Sort*) : (α × β) ≃ (β × α) := ⟨λ p, (p.2, p.1), λ p, (p.2, p.1), λ⟨a, b⟩, rfl, λ⟨a, b⟩, rfl⟩ @[simp] def prod_assoc (α β γ : Sort*) : ((α × β) × γ) ≃ (α × (β × γ)) := ⟨λ p, ⟨p.1.1, ⟨p.1.2, p.2⟩⟩, λp, ⟨⟨p.1, p.2.1⟩, p.2.2⟩, λ ⟨⟨a, b⟩, c⟩, rfl, λ ⟨a, ⟨b, c⟩⟩, rfl⟩ @[simp] theorem prod_assoc_apply {α β γ : Sort*} (p : (α × β) × γ) : prod_assoc α β γ p = ⟨p.1.1, ⟨p.1.2, p.2⟩⟩ := rfl section @[simp] def prod_unit (α : Sort*) : (α × punit.{u+1}) ≃ α := ⟨λ p, p.1, λ a, (a, punit.star), λ ⟨_, punit.star⟩, rfl, λ a, rfl⟩ @[simp] theorem prod_unit_apply {α : Sort*} (a : α × punit.{u+1}) : prod_unit α a = a.1 := rfl @[simp] def unit_prod (α : Sort*) : (punit.{u+1} × α) ≃ α := calc (punit × α) ≃ (α × punit) : prod_comm _ _ ... ≃ α : prod_unit _ @[simp] theorem unit_prod_apply {α : Sort*} (a : punit.{u+1} × α) : unit_prod α a = a.2 := rfl @[simp] def prod_empty (α : Sort*) : (α × empty) ≃ empty := equiv_empty (λ ⟨_, e⟩, e.rec _) @[simp] def empty_prod (α : Sort*) : (empty × α) ≃ empty := equiv_empty (λ ⟨e, _⟩, e.rec _) end section open sum def psum_equiv_sum (α β : Sort*) : psum α β ≃ (α ⊕ β) := ⟨λ s, psum.cases_on s inl inr, λ s, sum.cases_on s psum.inl psum.inr, λ s, by cases s; refl, λ s, by cases s; refl⟩ def sum_congr {α₁ β₁ α₂ β₂ : Sort*} : α₁ ≃ α₂ → β₁ ≃ β₂ → (α₁ ⊕ β₁) ≃ (α₂ ⊕ β₂) | ⟨f₁, g₁, l₁, r₁⟩ ⟨f₂, g₂, l₂, r₂⟩ := ⟨λ s, match s with inl a₁ := inl (f₁ a₁) | inr b₁ := inr (f₂ b₁) end, λ s, match s with inl a₂ := inl (g₁ a₂) | inr b₂ := inr (g₂ b₂) end, λ s, match s with inl a := congr_arg inl (l₁ a) | inr a := congr_arg inr (l₂ a) end, λ s, match s with inl a := congr_arg inl (r₁ a) | inr a := congr_arg inr (r₂ a) end⟩ @[simp] theorem sum_congr_apply_inl {α₁ β₁ α₂ β₂ : Sort*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) (a : α₁) : sum_congr e₁ e₂ (inl a) = inl (e₁ a) := by cases e₁; cases e₂; refl @[simp] theorem sum_congr_apply_inr {α₁ β₁ α₂ β₂ : Sort*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) (b : β₁) : sum_congr e₁ e₂ (inr b) = inr (e₂ b) := by cases e₁; cases e₂; refl def bool_equiv_unit_sum_unit : bool ≃ (punit.{u+1} ⊕ punit.{v+1}) := ⟨λ b, cond b (inr punit.star) (inl punit.star), λ s, sum.rec_on s (λ_, ff) (λ_, tt), λ b, by cases b; refl, λ s, by rcases s with ⟨⟨⟩⟩ | ⟨⟨⟩⟩; refl⟩ noncomputable def Prop_equiv_bool : Prop ≃ bool := ⟨λ p, @to_bool p (classical.prop_decidable _), λ b, b, λ p, by simp, λ b, by simp⟩ @[simp] def sum_comm (α β : Sort*) : (α ⊕ β) ≃ (β ⊕ α) := ⟨λ s, match s with inl a := inr a | inr b := inl b end, λ s, match s with inl b := inr b | inr a := inl a end, λ s, by cases s; refl, λ s, by cases s; refl⟩ @[simp] def sum_assoc (α β γ : Sort*) : ((α ⊕ β) ⊕ γ) ≃ (α ⊕ (β ⊕ γ)) := ⟨λ s, match s with inl (inl a) := inl a | inl (inr b) := inr (inl b) | inr c := inr (inr c) end, λ s, match s with inl a := inl (inl a) | inr (inl b) := inl (inr b) | inr (inr c) := inr c end, λ s, by rcases s with ⟨_ | _⟩ | _; refl, λ s, by rcases s with _ | _ | _; refl⟩ @[simp] theorem sum_assoc_apply_in1 {α β γ} (a) : sum_assoc α β γ (inl (inl a)) = inl a := rfl @[simp] theorem sum_assoc_apply_in2 {α β γ} (b) : sum_assoc α β γ (inl (inr b)) = inr (inl b) := rfl @[simp] theorem sum_assoc_apply_in3 {α β γ} (c) : sum_assoc α β γ (inr c) = inr (inr c) := rfl @[simp] def sum_empty (α : Sort*) : (α ⊕ empty) ≃ α := ⟨λ s, match s with inl a := a | inr e := empty.rec _ e end, inl, λ s, by rcases s with _ | ⟨⟨⟩⟩; refl, λ a, rfl⟩ @[simp] def empty_sum (α : Sort*) : (empty ⊕ α) ≃ α := (sum_comm _ _).trans $ sum_empty _ @[simp] def option_equiv_sum_unit (α : Sort*) : option α ≃ (α ⊕ punit.{u+1}) := ⟨λ o, match o with none := inr punit.star | some a := inl a end, λ s, match s with inr _ := none | inl a := some a end, λ o, by cases o; refl, λ s, by rcases s with _ | ⟨⟨⟩⟩; refl⟩ def sum_equiv_sigma_bool (α β : Sort*) : (α ⊕ β) ≃ (Σ b: bool, cond b α β) := ⟨λ s, match s with inl a := ⟨tt, a⟩ | inr b := ⟨ff, b⟩ end, λ s, match s with ⟨tt, a⟩ := inl a | ⟨ff, b⟩ := inr b end, λ s, by cases s; refl, λ s, by rcases s with ⟨_|_, _⟩; refl⟩ def equiv_fib {α β : Type*} (f : α → β) : α ≃ Σ y : β, {x // f x = y} := ⟨λ x, ⟨f x, x, rfl⟩, λ x, x.2.1, λ x, rfl, λ ⟨y, x, rfl⟩, rfl⟩ end section def Pi_congr_right {α} {β₁ β₂ : α → Sort*} (F : ∀ a, β₁ a ≃ β₂ a) : (Π a, β₁ a) ≃ (Π a, β₂ a) := ⟨λ H a, F a (H a), λ H a, (F a).symm (H a), λ H, funext $ by simp, λ H, funext $ by simp⟩ end section def psigma_equiv_sigma {α} (β : α → Sort*) : psigma β ≃ sigma β := ⟨λ ⟨a, b⟩, ⟨a, b⟩, λ ⟨a, b⟩, ⟨a, b⟩, λ ⟨a, b⟩, rfl, λ ⟨a, b⟩, rfl⟩ def sigma_congr_right {α} {β₁ β₂ : α → Sort*} (F : ∀ a, β₁ a ≃ β₂ a) : sigma β₁ ≃ sigma β₂ := ⟨λ ⟨a, b⟩, ⟨a, F a b⟩, λ ⟨a, b⟩, ⟨a, (F a).symm b⟩, λ ⟨a, b⟩, congr_arg (sigma.mk a) $ inverse_apply_apply (F a) b, λ ⟨a, b⟩, congr_arg (sigma.mk a) $ apply_inverse_apply (F a) b⟩ def sigma_congr_left {α₁ α₂} {β : α₂ → Sort*} : ∀ f : α₁ ≃ α₂, (Σ a:α₁, β (f a)) ≃ (Σ a:α₂, β a) | ⟨f, g, l, r⟩ := ⟨λ ⟨a, b⟩, ⟨f a, b⟩, λ ⟨a, b⟩, ⟨g a, @@eq.rec β b (r a).symm⟩, λ ⟨a, b⟩, match g (f a), l a : ∀ a' (h : a' = a), @sigma.mk _ (β ∘ f) _ (@@eq.rec β b (congr_arg f h.symm)) = ⟨a, b⟩ with | _, rfl := rfl end, λ ⟨a, b⟩, match f (g a), _ : ∀ a' (h : a' = a), sigma.mk a' (@@eq.rec β b h.symm) = ⟨a, b⟩ with | _, rfl := rfl end⟩ def sigma_equiv_prod (α β : Sort*) : (Σ_:α, β) ≃ (α × β) := ⟨λ ⟨a, b⟩, ⟨a, b⟩, λ ⟨a, b⟩, ⟨a, b⟩, λ ⟨a, b⟩, rfl, λ ⟨a, b⟩, rfl⟩ def sigma_equiv_prod_of_equiv {α β} {β₁ : α → Sort*} (F : ∀ a, β₁ a ≃ β) : sigma β₁ ≃ (α × β) := (sigma_congr_right F).trans (sigma_equiv_prod α β) end section def arrow_prod_equiv_prod_arrow (α β γ : Type*) : (γ → α × β) ≃ ((γ → α) × (γ → β)) := ⟨λ f, (λ c, (f c).1, λ c, (f c).2), λ p c, (p.1 c, p.2 c), λ f, funext $ λ c, prod.mk.eta, λ p, by cases p; refl⟩ def arrow_arrow_equiv_prod_arrow (α β γ : Sort*) : (α → β → γ) ≃ (α × β → γ) := ⟨λ f, λ p, f p.1 p.2, λ f, λ a b, f (a, b), λ f, rfl, λ f, by funext p; cases p; refl⟩ open sum def sum_arrow_equiv_prod_arrow (α β γ : Type*) : ((α ⊕ β) → γ) ≃ ((α → γ) × (β → γ)) := ⟨λ f, (f ∘ inl, f ∘ inr), λ p s, sum.rec_on s p.1 p.2, λ f, by funext s; cases s; refl, λ p, by cases p; refl⟩ def sum_prod_distrib (α β γ : Sort*) : ((α ⊕ β) × γ) ≃ ((α × γ) ⊕ (β × γ)) := ⟨λ p, match p with (inl a, c) := inl (a, c) | (inr b, c) := inr (b, c) end, λ s, match s with inl (a, c) := (inl a, c) | inr (b, c) := (inr b, c) end, λ p, by rcases p with ⟨_ | _, _⟩; refl, λ s, by rcases s with ⟨_, _⟩ | ⟨_, _⟩; refl⟩ @[simp] theorem sum_prod_distrib_apply_left {α β γ} (a : α) (c : γ) : sum_prod_distrib α β γ (sum.inl a, c) = sum.inl (a, c) := rfl @[simp] theorem sum_prod_distrib_apply_right {α β γ} (b : β) (c : γ) : sum_prod_distrib α β γ (sum.inr b, c) = sum.inr (b, c) := rfl def prod_sum_distrib (α β γ : Sort*) : (α × (β ⊕ γ)) ≃ ((α × β) ⊕ (α × γ)) := calc (α × (β ⊕ γ)) ≃ ((β ⊕ γ) × α) : prod_comm _ _ ... ≃ ((β × α) ⊕ (γ × α)) : sum_prod_distrib _ _ _ ... ≃ ((α × β) ⊕ (α × γ)) : sum_congr (prod_comm _ _) (prod_comm _ _) @[simp] theorem prod_sum_distrib_apply_left {α β γ} (a : α) (b : β) : prod_sum_distrib α β γ (a, sum.inl b) = sum.inl (a, b) := rfl @[simp] theorem prod_sum_distrib_apply_right {α β γ} (a : α) (c : γ) : prod_sum_distrib α β γ (a, sum.inr c) = sum.inr (a, c) := rfl def bool_prod_equiv_sum (α : Type u) : (bool × α) ≃ (α ⊕ α) := calc (bool × α) ≃ ((unit ⊕ unit) × α) : prod_congr bool_equiv_unit_sum_unit (equiv.refl _) ... ≃ (α × (unit ⊕ unit)) : prod_comm _ _ ... ≃ ((α × unit) ⊕ (α × unit)) : prod_sum_distrib _ _ _ ... ≃ (α ⊕ α) : sum_congr (prod_unit _) (prod_unit _) end section open sum nat def nat_equiv_nat_sum_unit : ℕ ≃ (ℕ ⊕ punit.{u+1}) := ⟨λ n, match n with zero := inr punit.star | succ a := inl a end, λ s, match s with inl n := succ n | inr punit.star := zero end, λ n, begin cases n, repeat { refl } end, λ s, begin cases s with a u, { refl }, {cases u, { refl }} end⟩ @[simp] def nat_sum_unit_equiv_nat : (ℕ ⊕ punit.{u+1}) ≃ ℕ := nat_equiv_nat_sum_unit.symm def int_equiv_nat_sum_nat : ℤ ≃ (ℕ ⊕ ℕ) := by refine ⟨_, _, _, _⟩; intro z; {cases z; [left, right]; assumption} <|> {cases z; refl} end def list_equiv_of_equiv {α β : Type*} : α ≃ β → list α ≃ list β | ⟨f, g, l, r⟩ := by refine ⟨list.map f, list.map g, λ x, _, λ x, _⟩; simp [id_of_left_inverse l, id_of_right_inverse r] def fin_equiv_subtype (n : ℕ) : fin n ≃ {m // m < n} := ⟨λ x, ⟨x.1, x.2⟩, λ x, ⟨x.1, x.2⟩, λ ⟨a, b⟩, rfl,λ ⟨a, b⟩, rfl⟩ def decidable_eq_of_equiv [decidable_eq β] (e : α ≃ β) : decidable_eq α | a₁ a₂ := decidable_of_iff (e a₁ = e a₂) e.bijective.1.eq_iff def inhabited_of_equiv [inhabited β] (e : α ≃ β) : inhabited α := ⟨e.symm (default _)⟩ section open subtype def subtype_equiv_of_subtype {p : α → Prop} : Π (e : α ≃ β), {a : α // p a} ≃ {b : β // p (e.symm b)} | ⟨f, g, l, r⟩ := ⟨subtype.map f $ assume a ha, show p (g (f a)), by rwa [l], subtype.map g $ assume a ha, ha, assume p, by simp [map_comp, l.comp_eq_id]; rw [map_id]; refl, assume p, by simp [map_comp, r.comp_eq_id]; rw [map_id]; refl⟩ def subtype_subtype_equiv_subtype {α : Type u} (p : α → Prop) (q : subtype p → Prop) : subtype q ≃ {a : α // ∃h:p a, q ⟨a, h⟩ } := ⟨λ⟨⟨a, ha⟩, ha'⟩, ⟨a, ha, ha'⟩, λ⟨a, ha⟩, ⟨⟨a, ha.cases_on $ assume h _, h⟩, by cases ha; exact ha_h⟩, assume ⟨⟨a, ha⟩, h⟩, rfl, assume ⟨a, h₁, h₂⟩, rfl⟩ end namespace set open set protected def univ (α) : @univ α ≃ α := ⟨subtype.val, λ a, ⟨a, trivial⟩, λ ⟨a, _⟩, rfl, λ a, rfl⟩ protected def empty (α) : (∅ : set α) ≃ empty := equiv_empty $ λ ⟨x, h⟩, not_mem_empty x h protected def union {α} {s t : set α} [decidable_pred s] (H : s ∩ t = ∅) : (s ∪ t : set α) ≃ (s ⊕ t) := ⟨λ ⟨x, h⟩, if hs : x ∈ s then sum.inl ⟨_, hs⟩ else sum.inr ⟨_, h.resolve_left hs⟩, λ o, match o with | (sum.inl ⟨x, h⟩) := ⟨x, or.inl h⟩ | (sum.inr ⟨x, h⟩) := ⟨x, or.inr h⟩ end, λ ⟨x, h'⟩, by by_cases x ∈ s; simp [union._match_1, union._match_2, h]; congr, λ o, by rcases o with ⟨x, h⟩ | ⟨x, h⟩; simp [union._match_1, union._match_2, h]; simp [show x ∉ s, from λ h', eq_empty_iff_forall_not_mem.1 H _ ⟨h', h⟩]⟩ protected def singleton {α} (a : α) : ({a} : set α) ≃ punit.{u} := ⟨λ _, punit.star, λ _, ⟨a, mem_singleton _⟩, λ ⟨x, h⟩, by simp at h; subst x, λ ⟨⟩, rfl⟩ protected def insert {α} {s : set.{u} α} [decidable_pred s] {a : α} (H : a ∉ s) : (insert a s : set α) ≃ (s ⊕ punit.{u+1}) := by rw ← union_singleton; exact (set.union $ inter_singleton_eq_empty.2 H).trans (sum_congr (equiv.refl _) (set.singleton _)) protected def sum_compl {α} (s : set α) [decidable_pred s] : (s ⊕ (-s : set α)) ≃ α := (set.union (inter_compl_self _)).symm.trans (by rw union_compl_self; exact set.univ _) protected def prod {α β} (s : set α) (t : set β) : (s.prod t) ≃ (s × t) := ⟨λ ⟨⟨x, y⟩, ⟨h₁, h₂⟩⟩, ⟨⟨x, h₁⟩, ⟨y, h₂⟩⟩, λ ⟨⟨x, h₁⟩, ⟨y, h₂⟩⟩, ⟨⟨x, y⟩, ⟨h₁, h₂⟩⟩, λ ⟨⟨x, y⟩, ⟨h₁, h₂⟩⟩, rfl, λ ⟨⟨x, h₁⟩, ⟨y, h₂⟩⟩, rfl⟩ protected noncomputable def image {α β} (f : α → β) (s : set α) (H : injective f) : s ≃ (f '' s) := ⟨λ ⟨x, h⟩, ⟨f x, mem_image_of_mem _ h⟩, λ ⟨y, h⟩, ⟨classical.some h, (classical.some_spec h).1⟩, λ ⟨x, h⟩, subtype.eq (H (classical.some_spec (mem_image_of_mem f h)).2), λ ⟨y, h⟩, subtype.eq (classical.some_spec h).2⟩ @[simp] theorem image_apply {α β} (f : α → β) (s : set α) (H : injective f) (a h) : set.image f s H ⟨a, h⟩ = ⟨f a, mem_image_of_mem _ h⟩ := rfl protected noncomputable def range {α β} (f : α → β) (H : injective f) : α ≃ range f := (set.univ _).symm.trans $ (set.image f univ H).trans (equiv.cast $ by rw image_univ) @[simp] theorem range_apply {α β} (f : α → β) (H : injective f) (a) : set.range f H a = ⟨f a, set.mem_range_self _⟩ := by dunfold equiv.set.range equiv.set.univ; simp [set_coe_cast, -image_univ, image_univ.symm] end set noncomputable def of_bijective {α β} {f : α → β} (hf : bijective f) : α ≃ β := begin have hg := bijective_comp equiv.plift.symm.bijective (bijective_comp hf equiv.plift.bijective), refine equiv.plift.symm.trans (equiv.trans _ equiv.plift), exact (set.range _ hg.1).trans ((equiv.cast (by rw set.range_iff_surjective.2 hg.2)).trans (set.univ _)) end @[simp] theorem of_bijective_to_fun {α β} {f : α → β} (hf : bijective f) : (of_bijective hf : α → β) = f := begin funext a, dunfold of_bijective equiv.set.univ, have hg := bijective_comp equiv.plift.symm.bijective (bijective_comp hf equiv.plift.bijective), simp [set.set_coe_cast, (∘), set.range_iff_surjective.2 hg.2], end section swap variable [decidable_eq α] open decidable def swap_core (a b r : α) : α := if r = a then b else if r = b then a else r theorem swap_core_self (r a : α) : swap_core a a r = r := by unfold swap_core; split_ifs; cc theorem swap_core_swap_core (r a b : α) : swap_core a b (swap_core a b r) = r := by unfold swap_core; split_ifs; cc theorem swap_core_comm (r a b : α) : swap_core a b r = swap_core b a r := by unfold swap_core; split_ifs; cc /-- `swap a b` is the permutation that swaps `a` and `b` and leaves other values as is. -/ def swap (a b : α) : perm α := ⟨swap_core a b, swap_core a b, λr, swap_core_swap_core r a b, λr, swap_core_swap_core r a b⟩ theorem swap_self (a : α) : swap a a = equiv.refl _ := eq_of_to_fun_eq $ funext $ λ r, swap_core_self r a theorem swap_comm (a b : α) : swap a b = swap b a := eq_of_to_fun_eq $ funext $ λ r, swap_core_comm r _ _ theorem swap_apply_def (a b x : α) : swap a b x = if x = a then b else if x = b then a else x := rfl theorem swap_apply_left (a b : α) : swap a b a = b := if_pos rfl theorem swap_apply_right (a b : α) : swap a b b = a := by by_cases b = a; simp [swap_apply_def, *] theorem swap_apply_of_ne_of_ne {a b x : α} : x ≠ a → x ≠ b → swap a b x = x := by simp [swap_apply_def] {contextual := tt} theorem swap_swap (a b : α) : (swap a b).trans (swap a b) = equiv.refl _ := eq_of_to_fun_eq $ funext $ λ x, swap_core_swap_core _ _ _ theorem swap_comp_apply {a b x : α} (π : perm α) : π.trans (swap a b) x = if π x = a then b else if π x = b then a else π x := by cases π; refl @[simp] lemma swap_inv {α : Type*} [decidable_eq α] (x y : α) : (swap x y)⁻¹ = swap x y := rfl @[simp] lemma symm_trans_swap_trans [decidable_eq α] [decidable_eq β] (a b : α) (e : α ≃ β) : (e.symm.trans (swap a b)).trans e = swap (e a) (e b) := equiv.ext _ _ (λ x, begin have : ∀ a, e.symm x = a ↔ x = e a := λ a, by rw @eq_comm _ (e.symm x); split; intros; simp * at *, simp [swap_apply_def, this], split_ifs; simp end) /-- Augment an equivalence with a prescribed mapping `f a = b` -/ def set_value (f : α ≃ β) (a : α) (b : β) : α ≃ β := (swap a (f.symm b)).trans f @[simp] theorem set_value_eq (f : α ≃ β) (a : α) (b : β) : set_value f a b a = b := by dsimp [set_value]; simp [swap_apply_left] end swap end equiv instance {α} [subsingleton α] : subsingleton (ulift α) := equiv.ulift.subsingleton instance {α} [subsingleton α] : subsingleton (plift α) := equiv.plift.subsingleton instance {α} [decidable_eq α] : decidable_eq (ulift α) := equiv.ulift.decidable_eq instance {α} [decidable_eq α] : decidable_eq (plift α) := equiv.plift.decidable_eq
578113b5a1acbdb43c5ee8ec5d0f5a35b3489d7b
302b541ac2e998a523ae04da7673fd0932ded126
/tests/playground/closure.lean
81b090188f974ad1cec4ae0d29f478bde9624d7f
[]
no_license
mattweingarten/lambdapure
4aeff69e8e3b8e78ea3c0a2b9b61770ef5a689b1
f920a4ad78e6b1e3651f30bf8445c9105dfa03a8
refs/heads/master
1,680,665,168,790
1,618,420,180,000
1,618,420,180,000
310,816,264
2
1
null
null
null
null
UTF-8
Lean
false
false
171
lean
set_option trace.compiler.ir.init true def bar : Nat -> Nat -> Nat -> Nat | x,y,z => if x > y + z then 0 else 1 def foo (n : Nat) : (Nat -> Nat -> Nat) := bar n
4a0e9ead67d54cf8525d3932c6f624ea1500c1b6
1fd908b06e3f9c1252cb2285ada1102623a67f72
/init/equiv.lean
f906cc275dcd0a5ca22cad31913955c1ad60d73c
[ "Apache-2.0" ]
permissive
avigad/hott3
609a002849182721e7c7ae536d9f1e2956d6d4d3
f64750cd2de7a81e87d4828246d1369d59f16f43
refs/heads/master
1,629,027,243,322
1,510,946,717,000
1,510,946,717,000
103,570,461
0
0
null
1,505,415,620,000
1,505,415,620,000
null
UTF-8
Lean
false
false
19,629
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad, Jakob von Raumer, Floris van Doorn Ported from Coq HoTT -/ import .path .meta.rewrite universes u v w hott_theory namespace hott open function /- Equivalences -/ -- This is our definition of equivalence. In the HoTT-book it's called -- ihae (half-adjoint equivalence). class is_equiv {A : Type u} {B : Type v} (f : A → B) := mk' :: (inv : B → A) (right_inv : Πb, f (inv b) = b) (left_inv : Πa, inv (f a) = a) (adj : Πx, right_inv (f x) = ap f (left_inv x)) attribute [reducible] is_equiv.inv -- A more bundled version of equivalence structure equiv (A : Type u) (B : Type v) := (to_fun : A → B) (to_is_equiv : is_equiv to_fun) namespace is_equiv /- Some instances and closure properties of equivalences -/ postfix `⁻¹ᶠ`:std.prec.max_plus := inv section variables {A : Type u} {B : Type v} {C : Type w} (g : B → C) (f : A → B) {f' : A → B} -- The variant of mk' where f is explicit. @[hott] protected def mk := @is_equiv.mk' A B f -- The identity function is an equivalence. @[hott,instance] def is_equiv_id (A : Type v) : (is_equiv (id : A → A)) := is_equiv.mk id id (λa, idp) (λa, idp) (λa, idp) -- The composition of two equivalences is, again, an equivalence. @[hott, instance] def is_equiv_compose [Hf : is_equiv f] [Hg : is_equiv g] : is_equiv (g ∘ f) := is_equiv.mk (g ∘ f) (f⁻¹ᶠ ∘ g⁻¹ᶠ) begin intro c, apply (⬝), tactic.swap, apply right_inv g, apply ap g, apply right_inv f end begin intro a, dsimp [(∘)], apply (⬝), {apply ap (inv f), apply left_inv g}, {apply left_inv} end begin abstract { exact (λa, (whisker_left _ (adj g (f a))) ⬝ (ap_con g _ _)⁻¹ ⬝ ap02 g ((ap_con_eq_con (right_inv f) (left_inv g (f a)))⁻¹ ⬝ (ap_compose f (inv f) _ ◾ adj f a) ⬝ (ap_con f _ _)⁻¹ ) ⬝ (ap_compose g f _)⁻¹) } end -- Any function equal to an equivalence is an equivlance as well. @[hott] def is_equiv_eq_closed {f : A → B} [Hf : is_equiv f] (Heq : f = f') : is_equiv f' := eq.rec_on Heq Hf end section parameters {A : Type u} {B : Type v} (f : A → B) (g : B → A) (ret : Πb, f (g b) = b) (sec : Πa, g (f a) = a) @[hott] def adjointify_left_inv' (a : A) : g (f a) = a := ap g (ap f (inverse (sec a))) ⬝ ap g (ret (f a)) ⬝ sec a def adjointify_adj' (a : A) : ret (f a) = ap f (adjointify_left_inv' a) := let fgretrfa := ap f (ap g (ret (f a))) in let fgfinvsect := ap f (ap g (ap f (sec a)⁻¹)) in let fgfa := f (g (f a)) in let retrfa := ret (f a) in have eq1 : ap f (sec a) = _, from calc ap f (sec a) = idp ⬝ ap f (sec a) : by rwr idp_con ... = (ret (f a) ⬝ (ret (f a))⁻¹) ⬝ ap f (sec a) : by rwr con.right_inv ... = ((ret fgfa)⁻¹ ⬝ ap (f ∘ g) (ret (f a))) ⬝ ap f (sec a) : by rwr con_ap_eq_con (λ x, (ret x)⁻¹) ... = ((ret fgfa)⁻¹ ⬝ fgretrfa) ⬝ ap f (sec a) : by rwr ap_compose ... = (ret fgfa)⁻¹ ⬝ (fgretrfa ⬝ ap f (sec a)) : by rwr con.assoc, have eq2 : ap f (sec a) ⬝ idp = (ret fgfa)⁻¹ ⬝ (fgretrfa ⬝ ap f (sec a)), from con_idp _ ⬝ eq1, have eq3 : idp = _, from calc idp = (ap f (sec a))⁻¹ ⬝ ((ret fgfa)⁻¹ ⬝ (fgretrfa ⬝ ap f (sec a))) : eq_inv_con_of_con_eq eq2 ... = ((ap f (sec a))⁻¹ ⬝ (ret fgfa)⁻¹) ⬝ (fgretrfa ⬝ ap f (sec a)) : by rwr con.assoc' ... = (ap f (sec a)⁻¹ ⬝ (ret fgfa)⁻¹) ⬝ (fgretrfa ⬝ ap f (sec a)) : by rwr ap_inv ... = ((ap f (sec a)⁻¹ ⬝ (ret fgfa)⁻¹) ⬝ fgretrfa) ⬝ ap f (sec a) : by rwr con.assoc' ... = ((retrfa⁻¹ ⬝ ap (f ∘ g) (ap f (sec a)⁻¹)) ⬝ fgretrfa) ⬝ ap f (sec a) : by rwr con_ap_eq_con (λ x, (ret x)⁻¹) ... = ((retrfa⁻¹ ⬝ fgfinvsect) ⬝ fgretrfa) ⬝ ap f (sec a) : by rwr ap_compose ... = (retrfa⁻¹ ⬝ (fgfinvsect ⬝ fgretrfa)) ⬝ ap f (sec a) : by rwr con.assoc' ... = retrfa⁻¹ ⬝ ap f (ap g (ap f (sec a)⁻¹) ⬝ ap g (ret (f a))) ⬝ ap f (sec a) : by rwr ap_con ... = retrfa⁻¹ ⬝ (ap f (ap g (ap f (sec a)⁻¹) ⬝ ap g (ret (f a))) ⬝ ap f (sec a)) : by rwr con.assoc' ... = retrfa⁻¹ ⬝ ap f ((ap g (ap f (sec a)⁻¹) ⬝ ap g (ret (f a))) ⬝ sec a) : by rwr ← ap_con, show ret (f a) = ap f ((ap g (ap f (sec a)⁻¹) ⬝ ap g (ret (f a))) ⬝ sec a), from eq_of_idp_eq_inv_con eq3 @[hott] def adjointify : is_equiv f := is_equiv.mk f g ret adjointify_left_inv' adjointify_adj' end -- Any function pointwise equal to an equivalence is an equivalence as well. @[hott] def homotopy_closed {A B : Type _} (f : A → B) {f' : A → B} [Hf : is_equiv f] (Hty : f ~ f') : is_equiv f' := adjointify f' (inv f) (λ b, (Hty (inv f b))⁻¹ ⬝ right_inv f b) (λ a, (ap (inv f) (Hty a))⁻¹ ⬝ left_inv f a) @[hott] def inv_homotopy_closed {A B : Type _} {f : A → B} {f' : B → A} [Hf : is_equiv f] (Hty : f⁻¹ᶠ ~ f') : is_equiv f := adjointify f f' (λ b, ap f (Hty _)⁻¹ᵖ ⬝ right_inv f b) (λ a, (Hty _)⁻¹ᵖ ⬝ left_inv f a) @[hott] def inv_homotopy_inv {A B : Type _} {f g : A → B} [is_equiv f] [is_equiv g] (p : f ~ g) : inv f ~ inv g := λb, (left_inv g (f⁻¹ᶠ b))⁻¹ ⬝ ap g⁻¹ᶠ ((p (f⁻¹ᶠ b))⁻¹ ⬝ right_inv f b) instance is_equiv_up (A : Type _) : is_equiv (ulift.up : A → ulift A) := adjointify ulift.up ulift.down (λa, by induction a;reflexivity) (λa, idp) section variables {A : Type _} {B: Type _} {C : Type _} (f : A → B) {f' : A → B} [Hf : is_equiv f] (g : B → C) include Hf -- The function equiv_rect says that given an equivalence f : A → B, -- and a hypothesis from B, one may always assume that the hypothesis -- is in the image of e. -- In fibrational terms, if we have a fibration over B which has a section -- once pulled back along an equivalence f : A → B, then it has a section -- over all of B. @[hott] def is_equiv_rect (P : B → Type _) (g : Πa, P (f a)) (b : B) : P b := right_inv f b ▸ g (f⁻¹ᶠ b) @[hott] def is_equiv_rect' (P : A → B → Type _) (g : Πb, P (f⁻¹ᶠ b) b) (a : A) : P a (f a) := transport (λ x, P x (f a)) (left_inv f a) (g (f a)) @[hott] def is_equiv_rect_comp (P : B → Type _) (df : Π (x : A), P (f x)) (x : A) : is_equiv_rect f P df (f x) = df x := calc is_equiv_rect f P df (f x) = right_inv f (f x) ▸ df (f⁻¹ᶠ (f x)) : by refl ... = ap f (left_inv f x) ▸ df (f⁻¹ᶠ (f x)) : by rwr adj ... = transport (P∘f) (left_inv f x) (df (f⁻¹ᶠ (f x))) : by rwr tr_compose ... = df x : by rwr (apdt df (left_inv f x)) @[hott] def adj_inv (b : B) : left_inv f (f⁻¹ᶠ b) = ap f⁻¹ᶠ (right_inv f b) := (is_equiv_rect f (λ fa, left_inv f (f⁻¹ᶠ fa) = ap f⁻¹ᶠ (right_inv f fa): _) (λa, (eq.cancel_right (left_inv f (id a)): _) (whisker_left _ (ap_id _)⁻¹ᵖ ⬝ (ap_con_eq_con_ap (left_inv f) (left_inv f a))⁻¹) ⬝ ap_compose _ _ _ ⬝ (ap02 f⁻¹ᶠ (adj f a).inverse): _) b: _) --The inverse of an equivalence is, again, an equivalence. @[instance,hott] def is_equiv_inv : is_equiv f⁻¹ᶠ := is_equiv.mk f⁻¹ᶠ f (left_inv f) (right_inv f) (adj_inv f) -- The 2-out-of-3 properties @[hott] def cancel_right (g : B → C) [Hgf : is_equiv (g ∘ f)] : (is_equiv g) := have Hfinv : is_equiv f⁻¹ᶠ, from is_equiv_inv f, @homotopy_closed _ _ _ _ (is_equiv_compose (g ∘ f) f⁻¹ᶠ) (λb, ap g (@right_inv _ _ f _ b)) @[hott] def cancel_left (g : C → A) [Hgf : is_equiv (f ∘ g)] : (is_equiv g) := have Hfinv : is_equiv f⁻¹ᶠ, from is_equiv_inv f, @homotopy_closed _ _ _ _ (is_equiv_compose f⁻¹ᶠ (f ∘ g)) (λa, left_inv f (g a)) @[hott] def eq_of_fn_eq_fn' {x y : A} (q : f x = f y) : x = y := (left_inv f x)⁻¹ ⬝ ap f⁻¹ᶠ q ⬝ left_inv f y @[hott] def ap_eq_of_fn_eq_fn' {x y : A} (q : f x = f y) : ap f (eq_of_fn_eq_fn' f q) = q := ap_con _ _ _ ⬝ whisker_right _ (ap_con _ _ _) ⬝ ((ap_inv _ _ ⬝ inverse2 (adj f _)⁻¹) ◾ (inverse (ap_compose f f⁻¹ᶠ _)) ◾ (adj f _)⁻¹) ⬝ con_ap_con_eq_con_con (right_inv f) _ _ ⬝ whisker_right _ (con.left_inv _) ⬝ idp_con _ @[hott] def eq_of_fn_eq_fn'_ap {x y : A} (q : x = y) : eq_of_fn_eq_fn' f (ap f q) = q := by induction q; apply con.left_inv @[instance,hott] def is_equiv_ap (x y : A) : is_equiv (ap f : x = y → f x = f y) := adjointify (ap f) (eq_of_fn_eq_fn' f) (ap_eq_of_fn_eq_fn' f) (eq_of_fn_eq_fn'_ap f) end section variables {A : Type u} {B : Type v} {C : Type w} {f : A → B} [Hf : is_equiv f] include Hf section rewrite_rules variables {a : A} {b : B} @[hott] def eq_of_eq_inv (p : a = f⁻¹ᶠ b) : f a = b := ap f p ⬝ right_inv f b @[hott] def eq_of_inv_eq (p : f⁻¹ᶠ b = a) : b = f a := (right_inv f b)⁻¹ ⬝ ap f p @[hott] def inv_eq_of_eq (p : b = f a) : f⁻¹ᶠ b = a := ap f⁻¹ᶠ p ⬝ left_inv f a @[hott] def eq_inv_of_eq (p : f a = b) : a = f⁻¹ᶠ b := (left_inv f a)⁻¹ ⬝ ap f⁻¹ᶠ p end rewrite_rules variable (f) section pre_compose variables (α : A → C) (β : B → C) @[hott] def homotopy_of_homotopy_inv_pre (p : β ~ α ∘ f⁻¹ᶠ) : β ∘ f ~ α := λ a, p (f a) ⬝ ap α (left_inv f a) @[hott] def homotopy_of_inv_homotopy_pre (p : α ∘ f⁻¹ᶠ ~ β) : α ~ β ∘ f := λ a, (ap α (left_inv f a))⁻¹ ⬝ p (f a) @[hott] def inv_homotopy_of_homotopy_pre (p : α ~ β ∘ f) : α ∘ f⁻¹ᶠ ~ β := λ b, p (f⁻¹ᶠ b) ⬝ ap β (right_inv f b) @[hott] def homotopy_inv_of_homotopy_pre (p : β ∘ f ~ α) : β ~ α ∘ f⁻¹ᶠ := λ b, (ap β (right_inv f b))⁻¹ ⬝ p (f⁻¹ᶠ b) end pre_compose section post_compose variables (α : C → A) (β : C → B) @[hott] def homotopy_of_homotopy_inv_post (p : α ~ f⁻¹ᶠ ∘ β) : f ∘ α ~ β := λ c, ap f (p c) ⬝ right_inv f (β c) @[hott] def homotopy_of_inv_homotopy_post (p : f⁻¹ᶠ ∘ β ~ α) : β ~ f ∘ α := λ c, (right_inv f (β c))⁻¹ ⬝ ap f (p c) @[hott] def inv_homotopy_of_homotopy_post (p : β ~ f ∘ α) : f⁻¹ᶠ ∘ β ~ α := λ c, ap f⁻¹ᶠ (p c) ⬝ left_inv f (α c) @[hott] def homotopy_inv_of_homotopy_post (p : f ∘ α ~ β) : α ~ f⁻¹ᶠ ∘ β := λ c, (left_inv f (α c))⁻¹ ⬝ ap f⁻¹ᶠ (p c) end post_compose end --Transporting is an equivalence @[hott] def is_equiv_tr {A : Type u} (P : A → Type v) {x y : A} (p : x = y) : (is_equiv (transport P p)) := is_equiv.mk _ (transport P p⁻¹) (tr_inv_tr p) (inv_tr_tr p) (tr_inv_tr_lemma p) -- a version where the transport is a cast. Note: A and B live in the same universe here. @[hott, instance] def is_equiv_cast {A B : Type _} (H : A = B) : is_equiv (cast H) := is_equiv_tr (λX, X) H section variables {A : Type _} {B : A → Type _} {C : A → Type _} (f : Π{a}, B a → C a) [H : Πa, is_equiv (@f a)] {g : A → A} {g' : A → A} (h : Π{a}, B (g' a) → B (g a)) (h' : Π{a}, C (g' a) → C (g a)) include H @[hott] def inv_commute' (p : Π⦃a : A⦄ (b : B (g' a)), f (h b) = h' (f b)) {a : A} (c : C (g' a)) : f⁻¹ᶠ (h' c) = h (f⁻¹ᶠ c) := eq_of_fn_eq_fn' f (right_inv f (h' c) ⬝ ap h' (right_inv f c)⁻¹ ⬝ (p (f⁻¹ᶠ c))⁻¹) @[hott] def fun_commute_of_inv_commute' (p : Π⦃a : A⦄ (c : C (g' a)), f⁻¹ᶠ (h' c) = h (f⁻¹ᶠ c)) {a : A} (b : B (g' a)) : f (h b) = h' (f b) := eq_of_fn_eq_fn' f⁻¹ᶠ (left_inv f (h b) ⬝ ap h (left_inv f b)⁻¹ ⬝ (p (f b))⁻¹) @[hott] def ap_inv_commute' (p : Π⦃a : A⦄ (b : B (g' a)), f (h b) = h' (f b)) {a : A} (c : C (g' a)) : ap f (inv_commute' @f @h @h' p c) = right_inv f (h' c) ⬝ ap h' (right_inv f c)⁻¹ ⬝ (p (f⁻¹ᶠ c))⁻¹ := ap_eq_of_fn_eq_fn' _ _ -- inv_commute'_fn is in types.equiv end -- This is inv_commute' for A ≡ unit @[hott] def inv_commute1' {B C : Type _} (f : B → C) [is_equiv f] (h : B → B) (h' : C → C) (p : Π(b : B), f (h b) = h' (f b)) (c : C) : f⁻¹ᶠ (h' c) = h (f⁻¹ᶠ c) := eq_of_fn_eq_fn' f (right_inv f (h' c) ⬝ ap h' (right_inv f c)⁻¹ ⬝ (p (f⁻¹ᶠ c))⁻¹) end is_equiv open hott.is_equiv namespace eq local attribute [instance] is_equiv_tr @[hott] def tr_inv_fn {A : Type _} {B : A → Type _} {a a' : A} (p : a = a') : transport B p⁻¹ = (transport B p)⁻¹ᶠ := idp @[hott] def tr_inv {A : Type _} {B : A → Type _} {a a' : A} (p : a = a') (b : B a') : p⁻¹ ▸ b = (transport B p)⁻¹ᶠ b := idp @[hott] def cast_inv_fn {A B : Type _} (p : A = B) : cast p⁻¹ = (cast p)⁻¹ᶠ := idp @[hott] def cast_inv {A B : Type _} (p : A = B) (b : B) : cast p⁻¹ b = (cast p)⁻¹ᶠ b := idp end eq infix ` ≃ `:25 := equiv attribute [instance] equiv.to_is_equiv namespace equiv section variables {A : Type u} {B : Type v} {C : Type w} instance: has_coe_to_fun (A ≃ B) := ⟨_, to_fun⟩ @[hott, hsimp] def to_fun_equiv {A B : Type _} (f : A → B) (H : is_equiv f) : @coe_fn _ equiv.has_coe_to_fun (equiv.mk f H) = f := idp open is_equiv @[hott] protected def MK (f : A → B) (g : B → A) (right_inv : Πb, f (g b) = b) (left_inv : Πa, g (f a) = a) : A ≃ B := equiv.mk f (adjointify f g right_inv left_inv) @[hott, reducible] def to_inv (f : A ≃ B) : B → A := f⁻¹ᶠ @[hott, hsimp] def to_right_inv (f : A ≃ B) (b : B) : f (f⁻¹ᶠ b) = b := right_inv f b @[hott, hsimp] def to_left_inv (f : A ≃ B) (a : A) : f⁻¹ᶠ (f a) = a := left_inv f a @[refl, hott] protected def rfl : A ≃ A := equiv.mk id (hott.is_equiv.is_equiv_id _) @[hott] protected def refl (A : Type _) : A ≃ A := @equiv.rfl A @[symm, hott] protected def symm (f : A ≃ B) : B ≃ A := equiv.mk f⁻¹ᶠ (is_equiv.is_equiv_inv f) @[trans, hott] protected def trans (f : A ≃ B) (g : B ≃ C) : A ≃ C := equiv.mk (g ∘ f) (is_equiv_compose _ _) infixl ` ⬝e `:75 := equiv.trans postfix `⁻¹ᵉ`:(max + 1) := equiv.symm @[reducible, hott] def erfl := @equiv.rfl @[hott] def to_inv_trans (f : A ≃ B) (g : B ≃ C) : (f ⬝e g)⁻¹ᶠ = g⁻¹ᵉ ⬝e f⁻¹ᵉ := idp @[hott,instance] def is_equiv_to_inv (f : A ≃ B) : is_equiv f⁻¹ᶠ := is_equiv.is_equiv_inv _ @[hott] def equiv_change_fun (f : A ≃ B) {f' : A → B} (Heq : f ~ f') : A ≃ B := equiv.mk f' (is_equiv.homotopy_closed f Heq) @[hott] def equiv_change_inv (f : A ≃ B) {f' : B → A} (Heq : f⁻¹ᶠ ~ f') : A ≃ B := equiv.mk f (inv_homotopy_closed Heq) --rename: eq_equiv_fn_eq_fn_of_is_equiv @[hott] def eq_equiv_fn_eq (f : A → B) [H : is_equiv f] (a b : A) : (a = b) ≃ (f a = f b) := equiv.mk (ap f) (is_equiv_ap _ _ _) --rename: eq_equiv_fn_eq_fn @[hott] def eq_equiv_fn_eq_of_equiv (f : A ≃ B) (a b : A) : (a = b) ≃ (f a = f b) := equiv.mk (ap f) (is_equiv_ap _ _ _) @[hott] def equiv_ap (P : A → Type _) {a b : A} (p : a = b) : P a ≃ P b := equiv.mk (transport P p) (is_equiv_tr _ _) @[hott] def equiv_of_eq {A B : Type u} (p : A = B) : A ≃ B := equiv.mk (cast p) (is_equiv_tr id _) @[hott, hsimp] def equiv_of_eq_refl (A : Type _) : equiv_of_eq (refl A) = equiv.refl A := idp @[hott] def eq_of_fn_eq_fn (f : A ≃ B) {x y : A} (q : f x = f y) : x = y := (left_inv _ x)⁻¹ ⬝ ap f⁻¹ᶠ q ⬝ left_inv _ y @[hott] def eq_of_fn_eq_fn_inv (f : A ≃ B) {x y : B} (q : f⁻¹ᵉ x = f⁻¹ᵉ y) : x = y := (right_inv _ x)⁻¹ ⬝ ap f q ⬝ right_inv f y @[hott] def ap_eq_of_fn_eq_fn (f : A ≃ B) {x y : A} (q : f x = f y) : ap f (eq_of_fn_eq_fn f q) = q := ap_eq_of_fn_eq_fn' f q @[hott] def eq_of_fn_eq_fn_ap (f : A ≃ B) {x y : A} (q : x = y) : eq_of_fn_eq_fn f (ap f q) = q := eq_of_fn_eq_fn'_ap f q @[hott] def to_inv_homotopy_inv {f g : A ≃ B} (p : f ~ g) : f⁻¹ᵉ ~ g⁻¹ᵉ := inv_homotopy_inv p --we need this theorem for the funext_of_ua proof @[hott] theorem inv_eq {A B : Type _} (eqf eqg : A ≃ B) (p : eqf = eqg) : eqf⁻¹ᶠ = eqg⁻¹ᶠ := eq.rec_on p idp @[trans, hott] def equiv_of_equiv_of_eq {A B C : Type _} (p : A = B) (q : B ≃ C) : A ≃ C := equiv_of_eq p ⬝e q @[trans, hott] def equiv_of_eq_of_equiv {A B C : Type _} (p : A ≃ B) (q : B = C) : A ≃ C := p ⬝e equiv_of_eq q @[hott] def equiv_lift (A : Type _) : A ≃ ulift A := equiv.mk ulift.up (by apply_instance) @[hott] def equiv_rect (f : A ≃ B) (P : B → Type _) (g : Πa, P (f a)) (b : B) : P b := right_inv f b ▸ g (f⁻¹ᶠ b) @[hott] def equiv_rect' (f : A ≃ B) (P : A → B → Type _) (g : Πb, P (f⁻¹ᶠ b) b) (a : A) : P a (f a) := transport (λ x : A, P x (f a)) (left_inv f a) (g (f a)) @[hott] def equiv_rect_comp (f : A ≃ B) (P : B → Type _) (df : Π (x : A), P (f x)) (x : A) : equiv_rect f P df (f x) = df x := calc equiv_rect f P df (f x) = right_inv f (f x) ▸ df (f⁻¹ᶠ (f x)) : by refl ... = ap f (left_inv f x) ▸ df (f⁻¹ᶠ (f x)) : by rwr ← adj ... = transport (P∘f) (left_inv f x) (df (f⁻¹ᶠ (f x))) : by rwr tr_compose ... = df x : by apply apdt df (left_inv f x) end section variables {A : Type _} {B : Type _} (f : A ≃ B) {a : A} {b : B} @[hott] def to_eq_of_eq_inv (p : a = f⁻¹ᶠ b) : f a = b := ap f p ⬝ to_right_inv f b @[hott] def to_eq_of_inv_eq (p : f⁻¹ᶠ b = a) : b = f a := (to_right_inv f b)⁻¹ ⬝ ap f p @[hott] def to_inv_eq_of_eq (p : b = f a) : f⁻¹ᶠ b = a := ap _ p ⬝ left_inv f a @[hott] def to_eq_inv_of_eq (p : f a = b) : a = f⁻¹ᶠ b := (left_inv f a)⁻¹ ⬝ ap _ p end section variables {A : Type _} {B : A → Type _} {C : A → Type _} (f : Π{a}, B a ≃ C a) {g : A → A} {g' : A → A} (h : Π{a}, B (g' a) → B (g a)) (h' : Π{a}, C (g' a) → C (g a)) @[hott] def inv_commute (p : Π⦃a : A⦄ (b : B (g' a)), f.to_fun (h b) = h' (f.to_fun b)) {a : A} (c : C (g' a)) : f.to_inv (h' c) = h (f.to_inv c) := inv_commute' (λ a, f.to_fun) @h @h' p c @[hott] def fun_commute_of_inv_commute (p : Π⦃a : A⦄ (c : C (g' a)), f.to_inv (h' c) = h (f.to_inv c)) {a : A} (b : B (g' a)) : f.to_fun (h b) = h' (f.to_fun b) := fun_commute_of_inv_commute' (λ a, f.to_fun) @h @h' p b @[hott] def inv_commute1 {B C : Type _} (f : B ≃ C) (h : B → B) (h' : C → C) (p : Π(b : B), f (h b) = h' (f b)) (c : C) : f⁻¹ᶠ (h' c) = h (f⁻¹ᶠ c) := inv_commute1' f h h' p c end infixl ` ⬝pe `:75 := equiv_of_equiv_of_eq infixl ` ⬝ep `:75 := equiv_of_eq_of_equiv end equiv open equiv namespace is_equiv @[hott] def is_equiv_of_equiv_of_homotopy {A B : Type _} (f : A ≃ B) {f' : A → B} (Hty : f ~ f') : is_equiv f' := @homotopy_closed _ _ f f' _ Hty end is_equiv end hott
57e0734b1035b2e9977e158ac1b197e6d9af3b1c
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/stage0/src/Init/Data/UInt.lean
a7933b387b9c8e3c75fbe0be842b8a3ac1efcd6c
[ "Apache-2.0" ]
permissive
WojciechKarpiel/lean4
7f89706b8e3c1f942b83a2c91a3a00b05da0e65b
f6e1314fa08293dea66a329e05b6c196a0189163
refs/heads/master
1,686,633,402,214
1,625,821,189,000
1,625,821,258,000
384,640,886
0
0
Apache-2.0
1,625,903,617,000
1,625,903,026,000
null
UTF-8
Lean
false
false
14,643
lean
/- Copyright (c) 2018 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Data.Fin.Basic import Init.System.Platform open Nat @[extern "lean_uint8_of_nat"] def UInt8.ofNat (n : @& Nat) : UInt8 := ⟨Fin.ofNat n⟩ abbrev Nat.toUInt8 := UInt8.ofNat @[extern "lean_uint8_to_nat"] def UInt8.toNat (n : UInt8) : Nat := n.val.val @[extern c inline "#1 + #2"] def UInt8.add (a b : UInt8) : UInt8 := ⟨a.val + b.val⟩ @[extern c inline "#1 - #2"] def UInt8.sub (a b : UInt8) : UInt8 := ⟨a.val - b.val⟩ @[extern c inline "#1 * #2"] def UInt8.mul (a b : UInt8) : UInt8 := ⟨a.val * b.val⟩ @[extern c inline "#2 == 0 ? 0 : #1 / #2"] def UInt8.div (a b : UInt8) : UInt8 := ⟨a.val / b.val⟩ @[extern c inline "#2 == 0 ? #1 : #1 % #2"] def UInt8.mod (a b : UInt8) : UInt8 := ⟨a.val % b.val⟩ @[extern "lean_uint8_modn"] def UInt8.modn (a : UInt8) (n : @& Nat) : UInt8 := ⟨a.val % n⟩ @[extern c inline "#1 & #2"] def UInt8.land (a b : UInt8) : UInt8 := ⟨Fin.land a.val b.val⟩ @[extern c inline "#1 | #2"] def UInt8.lor (a b : UInt8) : UInt8 := ⟨Fin.lor a.val b.val⟩ @[extern c inline "#1 ^ #2"] def UInt8.xor (a b : UInt8) : UInt8 := ⟨Fin.xor a.val b.val⟩ @[extern c inline "#1 << #2 % 8"] def UInt8.shiftLeft (a b : UInt8) : UInt8 := ⟨a.val <<< (modn b 8).val⟩ @[extern c inline "#1 >> #2 % 8"] def UInt8.shiftRight (a b : UInt8) : UInt8 := ⟨a.val >>> (modn b 8).val⟩ def UInt8.lt (a b : UInt8) : Prop := a.val < b.val def UInt8.le (a b : UInt8) : Prop := a.val ≤ b.val instance : OfNat UInt8 n := ⟨UInt8.ofNat n⟩ instance : Add UInt8 := ⟨UInt8.add⟩ instance : Sub UInt8 := ⟨UInt8.sub⟩ instance : Mul UInt8 := ⟨UInt8.mul⟩ instance : Mod UInt8 := ⟨UInt8.mod⟩ instance : HMod UInt8 Nat UInt8 := ⟨UInt8.modn⟩ instance : Div UInt8 := ⟨UInt8.div⟩ instance : LT UInt8 := ⟨UInt8.lt⟩ instance : LE UInt8 := ⟨UInt8.le⟩ @[extern c inline "~ #1"] def UInt8.complement (a:UInt8) : UInt8 := 0-(a+1) instance : Complement UInt8 := ⟨UInt8.complement⟩ instance : AndOp UInt8 := ⟨UInt8.land⟩ instance : OrOp UInt8 := ⟨UInt8.lor⟩ instance : Xor UInt8 := ⟨UInt8.xor⟩ instance : ShiftLeft UInt8 := ⟨UInt8.shiftLeft⟩ instance : ShiftRight UInt8 := ⟨UInt8.shiftRight⟩ set_option bootstrap.genMatcherCode false in @[extern c inline "#1 < #2"] def UInt8.decLt (a b : UInt8) : Decidable (a < b) := match a, b with | ⟨n⟩, ⟨m⟩ => inferInstanceAs (Decidable (n < m)) set_option bootstrap.genMatcherCode false in @[extern c inline "#1 <= #2"] def UInt8.decLe (a b : UInt8) : Decidable (a ≤ b) := match a, b with | ⟨n⟩, ⟨m⟩ => inferInstanceAs (Decidable (n <= m)) instance (a b : UInt8) : Decidable (a < b) := UInt8.decLt a b instance (a b : UInt8) : Decidable (a ≤ b) := UInt8.decLe a b @[extern "lean_uint16_of_nat"] def UInt16.ofNat (n : @& Nat) : UInt16 := ⟨Fin.ofNat n⟩ abbrev Nat.toUInt16 := UInt16.ofNat @[extern "lean_uint16_to_nat"] def UInt16.toNat (n : UInt16) : Nat := n.val.val @[extern c inline "#1 + #2"] def UInt16.add (a b : UInt16) : UInt16 := ⟨a.val + b.val⟩ @[extern c inline "#1 - #2"] def UInt16.sub (a b : UInt16) : UInt16 := ⟨a.val - b.val⟩ @[extern c inline "#1 * #2"] def UInt16.mul (a b : UInt16) : UInt16 := ⟨a.val * b.val⟩ @[extern c inline "#2 == 0 ? 0 : #1 / #2"] def UInt16.div (a b : UInt16) : UInt16 := ⟨a.val / b.val⟩ @[extern c inline "#2 == 0 ? #1 : #1 % #2"] def UInt16.mod (a b : UInt16) : UInt16 := ⟨a.val % b.val⟩ @[extern "lean_uint16_modn"] def UInt16.modn (a : UInt16) (n : @& Nat) : UInt16 := ⟨a.val % n⟩ @[extern c inline "#1 & #2"] def UInt16.land (a b : UInt16) : UInt16 := ⟨Fin.land a.val b.val⟩ @[extern c inline "#1 | #2"] def UInt16.lor (a b : UInt16) : UInt16 := ⟨Fin.lor a.val b.val⟩ @[extern c inline "#1 ^ #2"] def UInt16.xor (a b : UInt16) : UInt16 := ⟨Fin.xor a.val b.val⟩ @[extern c inline "#1 << #2 % 16"] def UInt16.shiftLeft (a b : UInt16) : UInt16 := ⟨a.val <<< (modn b 16).val⟩ @[extern c inline "#1 >> #2 % 16"] def UInt16.shiftRight (a b : UInt16) : UInt16 := ⟨a.val >>> (modn b 16).val⟩ def UInt16.lt (a b : UInt16) : Prop := a.val < b.val def UInt16.le (a b : UInt16) : Prop := a.val ≤ b.val instance : OfNat UInt16 n := ⟨UInt16.ofNat n⟩ instance : Add UInt16 := ⟨UInt16.add⟩ instance : Sub UInt16 := ⟨UInt16.sub⟩ instance : Mul UInt16 := ⟨UInt16.mul⟩ instance : Mod UInt16 := ⟨UInt16.mod⟩ instance : HMod UInt16 Nat UInt16 := ⟨UInt16.modn⟩ instance : Div UInt16 := ⟨UInt16.div⟩ instance : LT UInt16 := ⟨UInt16.lt⟩ instance : LE UInt16 := ⟨UInt16.le⟩ @[extern c inline "~ #1"] def UInt16.complement (a:UInt16) : UInt16 := 0-(a+1) instance : Complement UInt16 := ⟨UInt16.complement⟩ instance : AndOp UInt16 := ⟨UInt16.land⟩ instance : OrOp UInt16 := ⟨UInt16.lor⟩ instance : Xor UInt16 := ⟨UInt16.xor⟩ instance : ShiftLeft UInt16 := ⟨UInt16.shiftLeft⟩ instance : ShiftRight UInt16 := ⟨UInt16.shiftRight⟩ set_option bootstrap.genMatcherCode false in @[extern c inline "#1 < #2"] def UInt16.decLt (a b : UInt16) : Decidable (a < b) := match a, b with | ⟨n⟩, ⟨m⟩ => inferInstanceAs (Decidable (n < m)) set_option bootstrap.genMatcherCode false in @[extern c inline "#1 <= #2"] def UInt16.decLe (a b : UInt16) : Decidable (a ≤ b) := match a, b with | ⟨n⟩, ⟨m⟩ => inferInstanceAs (Decidable (n <= m)) instance (a b : UInt16) : Decidable (a < b) := UInt16.decLt a b instance (a b : UInt16) : Decidable (a ≤ b) := UInt16.decLe a b @[extern "lean_uint32_of_nat"] def UInt32.ofNat (n : @& Nat) : UInt32 := ⟨Fin.ofNat n⟩ @[extern "lean_uint32_of_nat"] def UInt32.ofNat' (n : Nat) (h : n < UInt32.size) : UInt32 := ⟨⟨n, h⟩⟩ abbrev Nat.toUInt32 := UInt32.ofNat @[extern c inline "#1 + #2"] def UInt32.add (a b : UInt32) : UInt32 := ⟨a.val + b.val⟩ @[extern c inline "#1 - #2"] def UInt32.sub (a b : UInt32) : UInt32 := ⟨a.val - b.val⟩ @[extern c inline "#1 * #2"] def UInt32.mul (a b : UInt32) : UInt32 := ⟨a.val * b.val⟩ @[extern c inline "#2 == 0 ? 0 : #1 / #2"] def UInt32.div (a b : UInt32) : UInt32 := ⟨a.val / b.val⟩ @[extern c inline "#2 == 0 ? #1 : #1 % #2"] def UInt32.mod (a b : UInt32) : UInt32 := ⟨a.val % b.val⟩ @[extern "lean_uint32_modn"] def UInt32.modn (a : UInt32) (n : @& Nat) : UInt32 := ⟨a.val % n⟩ @[extern c inline "#1 & #2"] def UInt32.land (a b : UInt32) : UInt32 := ⟨Fin.land a.val b.val⟩ @[extern c inline "#1 | #2"] def UInt32.lor (a b : UInt32) : UInt32 := ⟨Fin.lor a.val b.val⟩ @[extern c inline "#1 ^ #2"] def UInt32.xor (a b : UInt32) : UInt32 := ⟨Fin.xor a.val b.val⟩ @[extern c inline "#1 << #2 % 32"] def UInt32.shiftLeft (a b : UInt32) : UInt32 := ⟨a.val <<< (modn b 32).val⟩ @[extern c inline "#1 >> #2 % 32"] def UInt32.shiftRight (a b : UInt32) : UInt32 := ⟨a.val >>> (modn b 32).val⟩ @[extern c inline "((uint8_t)#1)"] def UInt32.toUInt8 (a : UInt32) : UInt8 := a.toNat.toUInt8 @[extern c inline "((uint16_t)#1)"] def UInt32.toUInt16 (a : UInt32) : UInt16 := a.toNat.toUInt16 @[extern c inline "((uint32_t)#1)"] def UInt8.toUInt32 (a : UInt8) : UInt32 := a.toNat.toUInt32 instance : OfNat UInt32 n := ⟨UInt32.ofNat n⟩ instance : Add UInt32 := ⟨UInt32.add⟩ instance : Sub UInt32 := ⟨UInt32.sub⟩ instance : Mul UInt32 := ⟨UInt32.mul⟩ instance : Mod UInt32 := ⟨UInt32.mod⟩ instance : HMod UInt32 Nat UInt32 := ⟨UInt32.modn⟩ instance : Div UInt32 := ⟨UInt32.div⟩ @[extern c inline "~ #1"] def UInt32.complement (a:UInt32) : UInt32 := 0-(a+1) instance : Complement UInt32 := ⟨UInt32.complement⟩ instance : AndOp UInt32 := ⟨UInt32.land⟩ instance : OrOp UInt32 := ⟨UInt32.lor⟩ instance : Xor UInt32 := ⟨UInt32.xor⟩ instance : ShiftLeft UInt32 := ⟨UInt32.shiftLeft⟩ instance : ShiftRight UInt32 := ⟨UInt32.shiftRight⟩ @[extern "lean_uint64_of_nat"] def UInt64.ofNat (n : @& Nat) : UInt64 := ⟨Fin.ofNat n⟩ abbrev Nat.toUInt64 := UInt64.ofNat @[extern "lean_uint64_to_nat"] def UInt64.toNat (n : UInt64) : Nat := n.val.val @[extern c inline "#1 + #2"] def UInt64.add (a b : UInt64) : UInt64 := ⟨a.val + b.val⟩ @[extern c inline "#1 - #2"] def UInt64.sub (a b : UInt64) : UInt64 := ⟨a.val - b.val⟩ @[extern c inline "#1 * #2"] def UInt64.mul (a b : UInt64) : UInt64 := ⟨a.val * b.val⟩ @[extern c inline "#2 == 0 ? 0 : #1 / #2"] def UInt64.div (a b : UInt64) : UInt64 := ⟨a.val / b.val⟩ @[extern c inline "#2 == 0 ? #1 : #1 % #2"] def UInt64.mod (a b : UInt64) : UInt64 := ⟨a.val % b.val⟩ @[extern "lean_uint64_modn"] def UInt64.modn (a : UInt64) (n : @& Nat) : UInt64 := ⟨a.val % n⟩ @[extern c inline "#1 & #2"] def UInt64.land (a b : UInt64) : UInt64 := ⟨Fin.land a.val b.val⟩ @[extern c inline "#1 | #2"] def UInt64.lor (a b : UInt64) : UInt64 := ⟨Fin.lor a.val b.val⟩ @[extern c inline "#1 ^ #2"] def UInt64.xor (a b : UInt64) : UInt64 := ⟨Fin.xor a.val b.val⟩ @[extern c inline "#1 << #2 % 64"] def UInt64.shiftLeft (a b : UInt64) : UInt64 := ⟨a.val <<< (modn b 64).val⟩ @[extern c inline "#1 >> #2 % 64"] def UInt64.shiftRight (a b : UInt64) : UInt64 := ⟨a.val >>> (modn b 64).val⟩ def UInt64.lt (a b : UInt64) : Prop := a.val < b.val def UInt64.le (a b : UInt64) : Prop := a.val ≤ b.val @[extern c inline "((uint8_t)#1)"] def UInt64.toUInt8 (a : UInt64) : UInt8 := a.toNat.toUInt8 @[extern c inline "((uint16_t)#1)"] def UInt64.toUInt16 (a : UInt64) : UInt16 := a.toNat.toUInt16 @[extern c inline "((uint32_t)#1)"] def UInt64.toUInt32 (a : UInt64) : UInt32 := a.toNat.toUInt32 @[extern c inline "((uint64_t)#1)"] def UInt32.toUInt64 (a : UInt32) : UInt64 := a.toNat.toUInt64 instance : OfNat UInt64 n := ⟨UInt64.ofNat n⟩ instance : Add UInt64 := ⟨UInt64.add⟩ instance : Sub UInt64 := ⟨UInt64.sub⟩ instance : Mul UInt64 := ⟨UInt64.mul⟩ instance : Mod UInt64 := ⟨UInt64.mod⟩ instance : HMod UInt64 Nat UInt64 := ⟨UInt64.modn⟩ instance : Div UInt64 := ⟨UInt64.div⟩ instance : LT UInt64 := ⟨UInt64.lt⟩ instance : LE UInt64 := ⟨UInt64.le⟩ @[extern c inline "~ #1"] def UInt64.complement (a:UInt64) : UInt64 := 0-(a+1) instance : Complement UInt64 := ⟨UInt64.complement⟩ instance : AndOp UInt64 := ⟨UInt64.land⟩ instance : OrOp UInt64 := ⟨UInt64.lor⟩ instance : Xor UInt64 := ⟨UInt64.xor⟩ instance : ShiftLeft UInt64 := ⟨UInt64.shiftLeft⟩ instance : ShiftRight UInt64 := ⟨UInt64.shiftRight⟩ @[extern c inline "(uint64_t)#1"] def Bool.toUInt64 (b : Bool) : UInt64 := if b then 1 else 0 set_option bootstrap.genMatcherCode false in @[extern c inline "#1 < #2"] def UInt64.decLt (a b : UInt64) : Decidable (a < b) := match a, b with | ⟨n⟩, ⟨m⟩ => inferInstanceAs (Decidable (n < m)) set_option bootstrap.genMatcherCode false in @[extern c inline "#1 <= #2"] def UInt64.decLe (a b : UInt64) : Decidable (a ≤ b) := match a, b with | ⟨n⟩, ⟨m⟩ => inferInstanceAs (Decidable (n <= m)) instance (a b : UInt64) : Decidable (a < b) := UInt64.decLt a b instance (a b : UInt64) : Decidable (a ≤ b) := UInt64.decLe a b theorem usizeSzGt0 : USize.size > 0 := Nat.posPowOfPos System.Platform.numBits (Nat.zeroLtSucc _) @[extern "lean_usize_of_nat"] def USize.ofNat (n : @& Nat) : USize := ⟨Fin.ofNat' n usizeSzGt0⟩ abbrev Nat.toUSize := USize.ofNat @[extern "lean_usize_to_nat"] def USize.toNat (n : USize) : Nat := n.val.val @[extern c inline "#1 + #2"] def USize.add (a b : USize) : USize := ⟨a.val + b.val⟩ @[extern c inline "#1 - #2"] def USize.sub (a b : USize) : USize := ⟨a.val - b.val⟩ @[extern c inline "#1 * #2"] def USize.mul (a b : USize) : USize := ⟨a.val * b.val⟩ @[extern c inline "#2 == 0 ? 0 : #1 / #2"] def USize.div (a b : USize) : USize := ⟨a.val / b.val⟩ @[extern c inline "#2 == 0 ? #1 : #1 % #2"] def USize.mod (a b : USize) : USize := ⟨a.val % b.val⟩ @[extern "lean_usize_modn"] def USize.modn (a : USize) (n : @& Nat) : USize := ⟨a.val % n⟩ @[extern c inline "#1 & #2"] def USize.land (a b : USize) : USize := ⟨Fin.land a.val b.val⟩ @[extern c inline "#1 | #2"] def USize.lor (a b : USize) : USize := ⟨Fin.lor a.val b.val⟩ @[extern c inline "#1 ^ #2"] def USize.xor (a b : USize) : USize := ⟨Fin.xor a.val b.val⟩ @[extern c inline "#1 << #2 % (sizeof(size_t) * 8)"] def USize.shiftLeft (a b : USize) : USize := ⟨a.val <<< (modn b System.Platform.numBits).val⟩ @[extern c inline "#1 >> #2 % (sizeof(size_t) * 8)"] def USize.shiftRight (a b : USize) : USize := ⟨a.val >>> (modn b System.Platform.numBits).val⟩ @[extern c inline "#1"] def UInt32.toUSize (a : UInt32) : USize := a.toNat.toUSize @[extern c inline "(uint32_t)#1"] def USize.toUInt32 (a : USize) : UInt32 := a.toNat.toUInt32 def USize.lt (a b : USize) : Prop := a.val < b.val def USize.le (a b : USize) : Prop := a.val ≤ b.val instance : OfNat USize n := ⟨USize.ofNat n⟩ instance : Add USize := ⟨USize.add⟩ instance : Sub USize := ⟨USize.sub⟩ instance : Mul USize := ⟨USize.mul⟩ instance : Mod USize := ⟨USize.mod⟩ instance : HMod USize Nat USize := ⟨USize.modn⟩ instance : Div USize := ⟨USize.div⟩ instance : LT USize := ⟨USize.lt⟩ instance : LE USize := ⟨USize.le⟩ @[extern c inline "~ #1"] def USize.complement (a:USize) : USize := 0-(a+1) instance : Complement USize := ⟨USize.complement⟩ instance : AndOp USize := ⟨USize.land⟩ instance : OrOp USize := ⟨USize.lor⟩ instance : Xor USize := ⟨USize.xor⟩ instance : ShiftLeft USize := ⟨USize.shiftLeft⟩ instance : ShiftRight USize := ⟨USize.shiftRight⟩ set_option bootstrap.genMatcherCode false in @[extern c inline "#1 < #2"] def USize.decLt (a b : USize) : Decidable (a < b) := match a, b with | ⟨n⟩, ⟨m⟩ => inferInstanceAs (Decidable (n < m)) set_option bootstrap.genMatcherCode false in @[extern c inline "#1 <= #2"] def USize.decLe (a b : USize) : Decidable (a ≤ b) := match a, b with | ⟨n⟩, ⟨m⟩ => inferInstanceAs (Decidable (n <= m)) instance (a b : USize) : Decidable (a < b) := USize.decLt a b instance (a b : USize) : Decidable (a ≤ b) := USize.decLe a b theorem USize.modn_lt {m : Nat} : ∀ (u : USize), m > 0 → USize.toNat (u % m) < m | ⟨u⟩, h => Fin.modn_lt u h
2c07d9ebdbd0fed8b98db60ac26d9a710108854c
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/lake/Lake/Build/Context.lean
8885a9957a1f615bb8990b063700f5ea0851d84a
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
1,907
lean
/- Copyright (c) 2021 Mac Malone. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mac Malone -/ import Lake.Util.Log import Lake.Util.Task import Lake.Util.Error import Lake.Util.OptionIO import Lake.Config.Context import Lake.Build.Trace import Lake.Build.Store import Lake.Build.Topological open System namespace Lake /-- A Lake context with some additional caching for builds. -/ structure BuildContext extends Context where leanTrace : BuildTrace oldMode : Bool := false startedBuilds : IO.Ref Nat finishedBuilds : IO.Ref Nat /-- A transformer to equip a monad with a `BuildContext`. -/ abbrev BuildT := ReaderT BuildContext /-- The monad for the Lake build manager. -/ abbrev SchedulerM := BuildT <| LogT BaseIO /-- The core monad for Lake builds. -/ abbrev BuildM := BuildT LogIO /-- A transformer to equip a monad with a Lake build store. -/ abbrev BuildStoreT := StateT BuildStore /-- A Lake build cycle. -/ abbrev BuildCycle := Cycle BuildKey /-- A transformer for monads that may encounter a build cycle. -/ abbrev BuildCycleT := CycleT BuildKey /-- A recursive build of a Lake build store that may encounter a cycle. -/ abbrev RecBuildM := BuildCycleT <| BuildStoreT BuildM instance [Pure m] : MonadLift LakeM (BuildT m) where monadLift x := fun ctx => pure <| x.run ctx.toContext @[inline] def BuildM.run (ctx : BuildContext) (self : BuildM α) : LogIO α := self ctx def BuildM.catchFailure (f : Unit → BaseIO α) (self : BuildM α) : SchedulerM α := fun ctx logMethods => self ctx logMethods |>.catchFailure f def logStep (message : String) : BuildM Unit := do let done ← (← read).finishedBuilds.get let started ← (← read).startedBuilds.get logInfo s!"[{done}/{started}] {message}" def createParentDirs (path : FilePath) : IO Unit := do if let some dir := path.parent then IO.FS.createDirAll dir
88b4c8e6aea7606fc7341b11913640ada2a2a8b8
556aeb81a103e9e0ac4e1fe0ce1bc6e6161c3c5e
/src/starkware/cairo/lean/semantics/air_encoding/glue.lean
e24f380734e8278818dc8154d1ceb030a3b64f3d
[ "Apache-2.0" ]
permissive
starkware-libs/formal-proofs
d6b731604461bf99e6ba820e68acca62a21709e8
f5fa4ba6a471357fd171175183203d0b437f6527
refs/heads/master
1,691,085,444,753
1,690,507,386,000
1,690,507,386,000
410,476,629
32
9
Apache-2.0
1,690,506,773,000
1,632,639,790,000
Lean
UTF-8
Lean
false
false
29,331
lean
/- This file translates the autogenerated data and constraints to the form used in the formalization. -/ import starkware.cairo.lean.semantics.air_encoding.constraints_autogen import starkware.cairo.lean.semantics.air_encoding.constraints import starkware.cairo.lean.semantics.air_encoding.memory import starkware.cairo.lean.semantics.air_encoding.range_check open_locale classical big_operators noncomputable theory variables {F : Type*} [field F] [fintype F] /- interpreting instruction constraints -/ def cpu__decode.to_instruction_constraints {c : columns F} (cd : cpu__decode c) (j : nat) : instruction_constraints (c.cpu__decode__instruction (j * 16)) -- inst (c.cpu__decode__off1 (j * 16)) -- off_op0_tilde (c.cpu__decode__off2 (j * 16)) -- off_op1_tilde (c.cpu__decode__off0 (j * 16)) -- off_dst_tilde (λ k : fin 16, c.cpu__decode__opcode_rc__column (j * 16 + k)) -- f_tilde := { h_instruction := begin dsimp, have := cd.opcode_rc_input (j * 16) (by simp), rw [eq_of_sub_eq_zero this, add_zero], ring end, h_bit := begin intro k, dsimp [tilde_type.to_f, column.off], have : ↑(k.succ) = ↑k + 1, by simp, rw [this, mul_sub, add_zero, add_zero, ←add_assoc, mul_one], have : ¬(j * 16 + ↑k) % 16 = 15, { rw [add_comm, nat.add_mul_mod_self_right], apply ne_of_lt, rw [nat.mod_eq_of_lt (lt_trans k.prop (nat.lt_succ_self _))], apply k.prop }, have h := cd.opcode_rc__bit (j * 16 + k) this, rw [←two_mul, column.off] at h, exact h, end, h_last_value := begin dsimp, have : (j * 16 + 15) % 16 = 15, { rw [add_comm, nat.add_mul_mod_self_right, nat.mod_eq_of_lt (nat.lt_succ_self _)] }, exact cd.opcode_rc__zero (j * 16 + 15) this end } /- interpreting execution step constraints -/ def cpu__operands.to_step_constraints {c : columns F} {inp : input_data F} (ops : cpu__operands c) (upd : cpu__update_registers inp c) (opcodes : cpu__opcodes c) (j : ℕ) (hj : j ≠ inp.trace_length / 16 - 1) : step_constraints (c.cpu__decode__off1 (j * 16)) -- off_op0_tilde (c.cpu__decode__off2 (j * 16)) -- off_op1_tilde (c.cpu__decode__off0 (j * 16)) -- off_dst_tilde (λ k : fin 16, c.cpu__decode__opcode_rc__column (j * 16 + k)) -- f_tilde (c.cpu__registers__fp (j * 16)) -- fp (c.cpu__registers__ap (j * 16)) -- ap (c.cpu__decode__pc (j * 16)) -- pc (c.cpu__registers__fp ((j + 1) * 16)) -- next fp (c.cpu__registers__ap ((j + 1) * 16)) -- next ap (c.cpu__decode__pc ((j + 1) * 16)) -- next pc (c.cpu__operands__mem_dst__addr (j * 16)) -- dst_addr (c.cpu__operands__mem_op0__addr (j * 16)) -- op0_addr (c.cpu__operands__mem_op1__addr (j * 16)) -- op1_addr (c.cpu__operands__mem_dst__value (j * 16)) -- dst (c.cpu__operands__mem_op0__value (j * 16)) -- op0 (c.cpu__operands__mem_op1__value (j * 16)) -- op1 := have h0 : (j * 16 % 16 = 0), by simp, have h1 : ¬ (j * 16 = 16 * (inp.trace_length / 16 - 1)), by { rwa [mul_comm, mul_right_inj' _], norm_num }, { mul := c.cpu__operands__ops_mul (j * 16), res := c.cpu__operands__res (j * 16), t0 := c.cpu__update_registers__update_pc__tmp0 (j * 16), t1 := c.cpu__update_registers__update_pc__tmp1 (j * 16), h_dst_addr := begin simp [tilde_type.f_dst_reg, tilde_type.to_f, column.off, two_mul], have h := ops.mem_dst_addr _ h0, simp [column.off] at h, rw [sub_eq_zero] at h, rw ←sub_eq_iff_eq_add.mpr h.symm, ring end, h_op0_addr := begin simp [tilde_type.f_op0_reg, tilde_type.to_f, column.off, two_mul], have h := ops.mem0_addr _ h0, simp [column.off] at h, rw [sub_eq_zero] at h, rw ←sub_eq_iff_eq_add.mpr h.symm, ring end, h_op1_addr := begin have coe3 : ↑(3 : fin 15) = 3 := fin.coe_eq_val _, have coe4 : ↑(4 : fin 15) = 4 := fin.coe_eq_val _, simp [tilde_type.f_op1_imm, tilde_type.f_op1_ap, tilde_type.f_op1_fp, tilde_type.to_f, column.off, two_mul, coe3, coe4], have h := ops.mem1_addr _ h0, simp [column.off] at h, rw [sub_eq_zero] at h, rw ←sub_eq_iff_eq_add.mpr h.symm, ring, end, h_mul := eq_of_sub_eq_zero (ops.ops_mul _ h0), h_res := begin have coe5 : ↑(5 : fin 15) = 5 := fin.coe_eq_val _, have coe6 : ↑(6 : fin 15) = 6 := fin.coe_eq_val _, have coe9 : ↑(9 : fin 15) = 9 := fin.coe_eq_val _, simp [tilde_type.f_pc_jnz, tilde_type.f_res_add, tilde_type.f_res_mul, tilde_type.to_f, column.off, coe5, coe6, coe9, two_mul], have h := ops.res _ h0, rw [sub_eq_zero] at h, transitivity, apply h, norm_num, ring, end, h_t0_eq := begin simp [tilde_type.f_pc_jnz, tilde_type.to_f, column.off, two_mul], exact eq_of_sub_eq_zero (upd.update_pc__tmp0 _ ⟨h0, h1⟩) end, h_t1_eq := eq_of_sub_eq_zero (upd.update_pc__tmp1 _ ⟨h0, h1⟩), h_next_pc_eq := begin have coe9 : ↑(9 : fin 15) = 9 := fin.coe_eq_val _, dsimp, simp only [tilde_type.f_pc_jnz, tilde_type.f_op1_imm, tilde_type.to_f, column.off, coe9, two_mul, add_zero, fin.coe_two, fin.coe_succ, fin.coe_cast_succ, add_mul], have h := upd.update_pc__pc_cond_positive _ ⟨h0, h1⟩, convert h using 2, simp [column.off], ring end, h_next_pc_eq' := begin dsimp, have coe7 : ↑(7 : fin 15) = 7 := fin.coe_eq_val _, have coe8 : ↑(8 : fin 15) = 8 := fin.coe_eq_val _, have coe9 : ↑(9 : fin 15) = 9 := fin.coe_eq_val _, rw ←upd.update_pc__pc_cond_negative _ ⟨h0, h1⟩, simp [tilde_type.f_pc_jnz, tilde_type.f_pc_jump_abs, tilde_type.f_pc_jump_rel, tilde_type.f_op1_imm, tilde_type.to_f, column.off, coe7, coe8, coe9, two_mul, add_zero, add_mul, fin.coe_two, fin.coe_succ, fin.coe_cast_succ], ring end, h_opcode_call := begin rw ←opcodes.call__push_fp _ h0, dsimp, simp only [tilde_type.f_opcode_call, tilde_type.to_f, column.off, add_zero, fin.coe_succ, fin.coe_cast_succ, ←two_mul], refl end, h_opcode_call' := begin have coe12 : ↑(12 : fin 15) = 12 := fin.coe_eq_val _, rw ←opcodes.call__push_pc _ h0, dsimp, simp only [tilde_type.f_opcode_call, tilde_type.f_op1_imm, tilde_type.to_f, column.off, add_zero, fin.coe_succ, fin.coe_cast_succ, ←two_mul, coe12], ring end, h_opcode_assert_eq := begin have coe14 : ↑(14 : fin 15) = 14 := fin.coe_eq_val _, rw ←opcodes.assert_eq__assert_eq _ h0, dsimp, simp only [tilde_type.f_opcode_assert_eq, tilde_type.to_f, column.off, add_zero, fin.coe_succ, fin.coe_cast_succ, ←two_mul, coe14] end, h_next_ap := begin have coe10 : ↑(10 : fin 15) = 10 := fin.coe_eq_val _, have coe11 : ↑(11 : fin 15) = 11 := fin.coe_eq_val _, have coe12 : ↑(12 : fin 15) = 12 := fin.coe_eq_val _, dsimp, simp only [add_mul, one_mul, column.off, add_zero], transitivity, { exact eq_of_sub_eq_zero (upd.update_ap__ap_update _ ⟨h0, h1⟩) }, simp only [tilde_type.f_opcode_call, tilde_type.f_ap_add, tilde_type.f_ap_add1, tilde_type.to_f, column.off, fin.coe_succ, fin.coe_cast_succ, coe10, coe11, coe12, ←two_mul], norm_num, ring end, h_next_fp := begin have coe12 : ↑(12 : fin 15) = 12 := fin.coe_eq_val _, have coe13 : ↑(13 : fin 15) = 13 := fin.coe_eq_val _, dsimp, simp only [add_mul, one_mul, column.off, add_zero], transitivity, { exact eq_of_sub_eq_zero (upd.update_fp__fp_update _ ⟨h0, h1⟩) }, simp only [tilde_type.f_opcode_call, tilde_type.f_opcode_ret, tilde_type.to_f, column.off, fin.coe_succ, fin.coe_cast_succ, coe12, coe13, ←two_mul], norm_num, ring end } /- interpreting range check constraints Note: there are inp.trace_length / 16 - 1 steps (so the execution trace, including the last step, has length inp.trace_length / 16), but there are inp.trace_length / 16 many 16-bit range-checked elements. -/ def rc16.to_range_check_constraints {c : columns F} {ci : columns_inter F} {inp : input_data F} {pd : public_data F} (rc16 : rc16 inp pd c ci) (trace_length_pos : inp.trace_length > 0) (public_memory_prod_eq_one : pd.rc16__perm__public_memory_prod = 1) (trace_length_le_char : inp.trace_length ≤ ring_char F) : range_check_constraints (inp.trace_length / 16 - 1) -- T (inp.trace_length / 16) -- rc16_len (λ j, c.cpu__decode__off1 (j * 16)) -- off_op0_tilde : fin T → F (λ j, c.cpu__decode__off2 (j * 16)) -- off_op1_tilde : fin T → F (λ j, c.cpu__decode__off0 (j * 16)) -- off_dst_tilde : fin T → F (λ j, c.rc_builtin__inner_rc (j * 16)) -- rc16_val : fin rc16_len → F pd.rc_min pd.rc_max := have h : ∀ j : ℕ, ∀ i : fin (inp.trace_length / 16 - 1), j < 16 → (↑i * 16 + j) < inp.trace_length - 1 + 1, begin rintros j ⟨i, ilt⟩ jlt, rw nat.sub_add_cancel trace_length_pos, apply lt_of_lt_of_le (add_lt_add_left jlt _), suffices : (i + 1) * 16 ≤ inp.trace_length, by rwa [add_mul] at this, apply le_trans (nat.mul_le_mul_right _ _) (nat.div_mul_le_self _ 16), exact lt_of_lt_of_le ilt (nat.pred_le _) end, have h' : ∀ j : ℕ, ∀ i : fin (inp.trace_length / 16), j < 16 → (↑i * 16 + j) < inp.trace_length - 1 + 1, begin rintros j ⟨i, ilt⟩ jlt, rw nat.sub_add_cancel trace_length_pos, apply lt_of_lt_of_le (add_lt_add_left jlt _), suffices : (i + 1) * 16 ≤ inp.trace_length, by rwa [add_mul] at this, apply le_trans (nat.mul_le_mul_right _ _) (nat.div_mul_le_self _ 16), exact nat.succ_le_of_lt ilt end, { n := inp.trace_length - 1, a := λ i, c.rc16_pool i, a' := λ i, c.rc16__sorted i, p := λ i, ci.rc16__perm__cum_prod0 i, z := pd.rc16__perm__interaction_elm, embed_off_op0 := λ i, ⟨↑i * 16 + 8, h 8 i (by norm_num)⟩, embed_off_op1 := λ i, ⟨↑i * 16 + 4, h 4 i (by norm_num)⟩, embed_off_dst := λ i, ⟨↑i * 16, h 0 i (by norm_num)⟩, embed_rc16_vals := λ i, ⟨↑i * 16 + 12, h' 12 i (by norm_num)⟩, h_embed_op0 := λ i, rfl, h_embed_op1 := λ i, rfl, h_embed_dst := λ i, rfl, h_embed_rc16 := λ i, rfl, h_continuity := begin intro i, rw [←rc16.diff_is_bit _ (ne_of_lt i.is_lt), mul_sub, mul_one], simp, refl end, h_initial := begin rw [←sub_eq_zero, ←rc16.perm__init0 _ rfl], simp [column.off], abel end, h_cumulative := begin intro i, rw [←sub_eq_zero, ←rc16.perm__step0 _ (ne_of_lt i.is_lt)], simp [column.off] end, h_final := (eq_of_sub_eq_zero (rc16.perm__last _ rfl)).trans public_memory_prod_eq_one, h_rc_min := eq_of_sub_eq_zero $ rc16.minimum _ rfl, h_rc_max := eq_of_sub_eq_zero $ rc16.maximum _ rfl, h_n_lt := begin apply nat.lt_of_succ_le, rw [nat.succ_eq_add_one, nat.sub_add_cancel trace_length_pos], exact trace_length_le_char end } /- interpreting memory constraints -/ def memory.to_memory_block_constraints {inp : input_data F} {pd : public_data F} {c : columns F} {ci : columns_inter F} (h_mem_star : let z := pd.memory__multi_column_perm__perm__interaction_elm, alpha := pd.memory__multi_column_perm__hash_interaction_elm0, p := pd.memory__multi_column_perm__perm__public_memory_prod, dom_m_star := { x // option.is_some (inp.m_star x) } in p * ∏ a : dom_m_star, (z - (a.val + alpha * mem_val a)) = z^(fintype.card dom_m_star)) (m : memory inp pd c ci) : memory_block_constraints (inp.trace_length / 2 - 1) -- n (λ i, c.mem_pool__addr (2 * i)) -- a (λ i, c.mem_pool__value (2 * i)) -- v inp.m_star := have h0 : ∀ j : fin (inp.trace_length / 2 - 1), ↑j * 2 % 2 = 0, by intro j; simp, have h1 : ∀ j : fin (inp.trace_length / 2 - 1), ¬ (↑j * 2 = 2 * (inp.trace_length / 2 - 1)), begin rintros ⟨j, jlt⟩, have hj : j ≠ inp.trace_length / 2 - 1 := ne_of_lt jlt, rwa [mul_comm, mul_right_inj' _], norm_num end, { a' := (λ j, c.column20 (2 * j)), v' := (λ j, c.column20 (2 * j + 1)), p := (λ j, ci.column24_inter1 (2 * j)), alpha := pd.memory__multi_column_perm__hash_interaction_elm0, z := pd.memory__multi_column_perm__perm__interaction_elm, h_continuity := begin intro j, rw [←m.diff_is_bit (↑j * 2) ⟨h0 j, h1 j⟩, mul_comm 2], simp [column.off, add_mul, mul_comm 2], ring end, h_single_valued := begin intro j, apply neg_inj.mp, rw [neg_zero, ←m.is_func (↑j * 2) ⟨h0 j, h1 j⟩], simp [column.off, add_mul, mul_add, mul_comm 2, add_assoc], norm_num, ring end, h_initial := begin rw [←sub_eq_zero, ←m.multi_column_perm__perm__init0 _ rfl], simp [column.off], ring end, h_cumulative := begin intro j, rw [←sub_eq_zero, ←m.multi_column_perm__perm__step0 (↑j * 2) ⟨h0 j, h1 j⟩], simp [column.off, add_mul, mul_add, mul_comm 2, add_assoc] end, h_final := begin apply eq.trans _ h_mem_star, rw [←eq_of_sub_eq_zero (m.multi_column_perm__perm__last _ rfl)], refl end } /- interpreting range check builtin constraints -/ /-- Use 8 16-bit range-checked elements for each 128-bit range-checked element -/ def rc_to_rc16 {inp : input_data F} : fin (inp.trace_length / 128) → fin 8 → fin (inp.trace_length / 16) := λ i j, ⟨i * 8 + j, begin cases i with i hi, cases j with j hj, calc ↑i * 8 + ↑j < (i + 1) * 8 : by { rw [add_mul, one_mul], apply add_lt_add_left hj } ... = ((i + 1) * 8 * 16) / 16 : by { rw nat.mul_div_cancel, norm_num } ... ≤ inp.trace_length / 16 : by { apply nat.div_le_div_right, rw mul_assoc, norm_num, rw ← nat.le_div_iff_mul_le, exact nat.succ_le_of_lt hi, norm_num } end⟩ def rc_builtin.to_rc_builtin_constraints {inp : input_data F} {pd : public_data F} {c : columns F} (rcb : rc_builtin inp pd c) : rc_builtin_constraints (inp.trace_length / 16) (pd.initial_rc_addr) (inp.trace_length / 128) (λ j, c.rc_builtin__inner_rc (j * 16)) (λ j, c.rc_builtin__mem__addr (j * 128)) (λ j, c.rc_builtin__mem__value (j * 128)) rc_to_rc16 := { h_rc_init_addr := λ h, eq_of_sub_eq_zero (rcb.init_addr _ rfl), h_rc_addr_step := begin intros i hi, have := rcb.addr_step (i * 128), simp [column.off, nat.succ_eq_add_one, add_mul, one_mul, add_assoc], norm_num, convert eq_of_sub_eq_zero (this _), simp, rw [mul_comm _ 128, nat.mul_right_inj (show 0 < 128, by norm_num)], contrapose! hi, rw [hi, nat.succ_eq_add_one], apply le_tsub_add end, h_rc_value := begin intro i, have := rcb.value (i * 128), simp at this, rw [columns.rc_builtin__mem__value, ←eq_of_sub_eq_zero this], simp only [rc_to_rc16, column.off, columns.rc_builtin__inner_rc], iterate 14 { congr' 1 }; { simp [column.off, add_mul, mul_assoc], congr' 1, try { norm_num } } end } theorem card_dom_aux {inp : input_data F} (h_card : 8 * fintype.card { x // option.is_some (inp.m_star x) } + 2 ≤ inp.trace_length) : 4 * fintype.card { x // option.is_some (inp.m_star x) } ≤ inp.trace_length / 2 - 1 := begin apply nat.le_pred_of_lt, apply nat.lt_of_succ_le, rw [nat.le_div_iff_mul_le' (show 0 < 2, by norm_num), nat.succ_mul, mul_comm, ←mul_assoc], norm_num, exact h_card end def embed_mem {inp : input_data F} (h_card : 8 * fintype.card { x // option.is_some (inp.m_star x) } + 2 ≤ inp.trace_length) (a : mem_dom inp.m_star) : fin (inp.trace_length / 2 - 1 + 1) := let i := (fintype.equiv_fin { x // option.is_some (inp.m_star x) }).to_fun a in ⟨4 * i.val + 1, nat.succ_lt_succ (lt_of_lt_of_le (nat.mul_lt_mul_of_pos_left i.is_lt (by norm_num)) (card_dom_aux h_card))⟩ def public_memory.to_memory_embedding_constraints {c : columns F} {inp : input_data F} (pm : public_memory c) (h_card : 8 * fintype.card { x // option.is_some (inp.m_star x) } + 2 ≤ inp.trace_length) : memory_embedding_constraints (inp.trace_length / 16 - 1) -- T (inp.trace_length / 128) -- rc_len (λ j, c.cpu__decode__pc (j * 16)) -- pc (λ j, c.cpu__decode__instruction (j * 16)) -- inst (λ j, c.cpu__operands__mem_dst__addr (j * 16)) -- dst_addr (λ j, c.cpu__operands__mem_dst__value (j * 16)) -- dst (λ j, c.cpu__operands__mem_op0__addr (j * 16)) -- op0_addr (λ j, c.cpu__operands__mem_op0__value (j * 16)) -- op0 (λ j, c.cpu__operands__mem_op1__addr (j * 16)) -- op1_addr (λ j, c.cpu__operands__mem_op1__value (j * 16)) -- op1 (λ j, c.rc_builtin__mem__addr (j * 128)) -- rc_addr (λ j, c.rc_builtin__mem__value (j * 128)) -- rc inp.m_star -- mem_star (inp.trace_length / 2 - 1) -- n (λ i, c.mem_pool__addr (2 * i)) -- a (λ i, c.mem_pool__value (2 * i)) -- v := have h : ∀ j : ℕ, ∀ i : fin (inp.trace_length / 16 - 1), j < 8 → (↑i * 8 + j) < inp.trace_length / 2 - 1 + 1, begin rintros j ⟨i, ilt⟩ jlt, apply nat.lt_succ_of_le, apply nat.le_pred_of_lt, have : i * 8 + j < (i + 1) * 8, { rw [add_mul, one_mul], exact add_lt_add_left jlt _ }, apply lt_of_lt_of_le this, rw [nat.le_div_iff_mul_le' (show 0 < 2, by norm_num), mul_assoc], norm_num, rw [←nat.le_div_iff_mul_le' (show 0 < 16, by norm_num)], apply nat.succ_le_of_lt, exact lt_of_lt_of_le ilt (nat.pred_le _) end, have h1 : ∀ i : fin (inp.trace_length / 128), (↑i * 64 + 51) < inp.trace_length / 2 - 1 + 1, begin rintros ⟨i, ilt⟩, apply nat.lt_succ_of_le, apply nat.le_pred_of_lt, have : i * 64 + 51 < (i + 1) * 64, { rw add_mul, apply add_lt_add_left, norm_num }, apply lt_of_lt_of_le this, apply le_trans (nat.mul_le_mul_right _ (nat.succ_le_of_lt ilt)), rw [nat.le_div_iff_mul_le' (show 0 < 2, by norm_num), mul_assoc], norm_num, apply nat.div_mul_le_self end, have jaux : ∀ j : fin (inp.trace_length / 16 - 1), (j : ℕ) * 8 = 4 * (2 * j), by { intro j, rw [←mul_assoc, mul_comm (4 * 2)], refl }, { embed_inst := λ i, ⟨↑i * 8 + 0, h 0 i (by norm_num)⟩, embed_dst := λ i, ⟨↑i * 8 + 4, h 4 i (by norm_num)⟩, embed_op0 := λ i, ⟨↑i * 8 + 2, h 2 i (by norm_num)⟩, embed_op1 := λ i, ⟨↑i * 8 + 6, h 6 i (by norm_num)⟩, embed_rc := λ i, ⟨↑i * 64 + 51, h1 i⟩, embed_mem := embed_mem h_card, h_embed_pc := by { intro i, dsimp [column.off], congr' 1, ring }, h_embed_inst := by { intro i, dsimp [column.off], congr' 1, ring }, h_embed_dst_addr := by { intro i, dsimp [column.off], congr' 1, ring }, h_embed_dst := by { intro i, dsimp [column.off], congr' 1, ring }, h_embed_op0_addr := by { intro i, dsimp [column.off], congr' 1, ring }, h_embed_op0 := by { intro i, dsimp [column.off], congr' 1, ring }, h_embed_op1_addr := by { intro i, dsimp [column.off], congr' 1, ring }, h_embed_op1 := by { intro i, dsimp [column.off], congr' 1, ring }, h_embed_rc_addr := by { intro i, dsimp [column.off], congr' 1, ring }, h_embed_rc := by { intro i, dsimp [column.off], congr' 1, ring }, h_embed_dom := begin intro a, simp [column.off], apply pm.addr_zero, simp, rw [←mul_assoc], exact nat.mul_mod_right _ _ end, h_embed_val := begin intro a, simp [column.off], apply pm.value_zero, simp, rw [←mul_assoc], exact nat.mul_mod_right _ _ end, h_embed_mem_inj := begin intros a1 a2, dsimp [embed_mem], rw [fin.eq_iff_veq, add_left_inj 1, mul_right_inj' (show 4 ≠ 0, by norm_num), ←fin.ext_iff], apply equiv.injective end, h_embed_mem_disj_inst := begin intros a j h', rw [fin.eq_iff_veq] at h', dsimp at h', have := congr_arg (λ n, n % 4) h', dsimp [embed_mem] at this, rw [add_comm, add_comm _ 0, jaux, nat.add_mul_mod_self_left, nat.add_mul_mod_self_left] at this, norm_num at this end, h_embed_mem_disj_dst := begin intros a j h', rw [fin.eq_iff_veq] at h', dsimp [embed_mem] at h', have := congr_arg (λ n, n % 4) h', dsimp at this, rw [add_comm, add_comm _ 4, jaux, nat.add_mul_mod_self_left, nat.add_mul_mod_self_left] at this, norm_num at this end, h_embed_mem_disj_op0 := begin intros a j h', rw [fin.eq_iff_veq] at h', dsimp [embed_mem] at h', have := congr_arg (λ n, n % 4) h', dsimp at this, rw [add_comm, add_comm _ 2, jaux, nat.add_mul_mod_self_left, nat.add_mul_mod_self_left] at this, norm_num at this end, h_embed_mem_disj_op1 := begin intros a j h', rw [fin.eq_iff_veq] at h', dsimp [embed_mem] at h', have := congr_arg (λ n, n % 4) h', dsimp at this, rw [add_comm, add_comm _ 6, jaux, nat.add_mul_mod_self_left, nat.add_mul_mod_self_left] at this, norm_num at this end, h_embed_mem_disj_rc := begin intros a j h', rw [fin.eq_iff_veq] at h', dsimp [embed_mem] at h', have jaux' : 64 = 16 * 4, by norm_num, have := congr_arg (λ n, n % 4) h', dsimp at this, rw [add_comm, add_comm _ 51, nat.add_mul_mod_self_left] at this, simp only [jaux', ←mul_assoc] at this, norm_num at this end } /- putting it all together -/ def input_data.to_input_data_aux (inp : input_data F) (pd : public_data F) (rc_max_lt : pd.rc_max < 2^16) (rc_min_le : pd.rc_min ≤ pd.rc_max) : input_data_aux F := { T := inp.trace_length / 16 - 1, rc16_len := inp.trace_length / 16, rc_len := inp.trace_length / 128, pc_I := inp.initial_pc, pc_F := inp.final_pc, ap_I := inp.initial_ap, ap_F := inp.final_ap, mem_star := inp.m_star, rc_min := pd.rc_min, rc_max := pd.rc_max, initial_rc_addr := pd.initial_rc_addr, rc_to_rc16 := rc_to_rc16, h_rc_lt := rc_max_lt, h_rc_le := rc_min_le } def to_constraints {inp : input_data F} {pd : public_data F} {c : columns F} {ci : columns_inter F} /- autogenerated constraints -/ (cd : cpu__decode c) (ops : cpu__operands c) (upd : cpu__update_registers inp c) (opcodes : cpu__opcodes c) (m : memory inp pd c ci) (rc : rc16 inp pd c ci) (pm : public_memory c) (rcb : rc_builtin inp pd c) (iandf : toplevel_constraints inp c) /- extra assumptions -/ (h_mem_star : let z := pd.memory__multi_column_perm__perm__interaction_elm, alpha := pd.memory__multi_column_perm__hash_interaction_elm0, p := pd.memory__multi_column_perm__perm__public_memory_prod, dom_m_star := { x // option.is_some (inp.m_star x) } in p * ∏ a : dom_m_star, (z - (a.val + alpha * mem_val a)) = z^(fintype.card dom_m_star)) (h_card_dom : 8 * fintype.card { x // option.is_some (inp.m_star x) } + 2 ≤ inp.trace_length) (public_memory_prod_eq_one : pd.rc16__perm__public_memory_prod = 1) (rc_max_lt : pd.rc_max < 2^16) (rc_min_le : pd.rc_min ≤ pd.rc_max) (trace_length_le_char : inp.trace_length ≤ ring_char F) : constraints (inp.to_input_data_aux pd rc_max_lt rc_min_le) := have trace_length_pos : inp.trace_length > 0, from lt_of_lt_of_le (nat.zero_lt_succ _) h_card_dom, { fp := λ j, c.cpu__registers__fp (j * 16), ap := λ j, c.cpu__registers__ap (j * 16), pc := λ j, c.cpu__decode__pc (j * 16), inst := λ j, c.cpu__decode__instruction (j * 16), off_op0_tilde := λ j, c.cpu__decode__off1 (j * 16), off_op1_tilde := λ j, c.cpu__decode__off2 (j * 16), off_dst_tilde := λ j, c.cpu__decode__off0 (j * 16), rc16_val := λ j, c.rc_builtin__inner_rc (j * 16), f_tilde := λ j k, c.cpu__decode__opcode_rc__column (j * 16 + k), dst_addr := λ j, c.cpu__operands__mem_dst__addr (j * 16), dst := λ j, c.cpu__operands__mem_dst__value (j * 16), op0_addr := λ j, c.cpu__operands__mem_op0__addr (j * 16), op0 := λ j, c.cpu__operands__mem_op0__value (j * 16), op1_addr := λ j, c.cpu__operands__mem_op1__addr (j * 16), op1 := λ j, c.cpu__operands__mem_op1__value (j * 16), rc_addr := λj, c.rc_builtin__mem__addr (j * 128), rc_val := λj, c.rc_builtin__mem__value (j * 128), h_pc_I := eq_of_sub_eq_zero (iandf.initial_pc _ rfl), h_ap_I := eq_of_sub_eq_zero (iandf.initial_ap _ rfl), h_fp_I := eq_of_sub_eq_zero (iandf.initial_fp _ rfl), h_pc_F := by { rw mul_comm _ 16, exact eq_of_sub_eq_zero (iandf.final_pc _ rfl) }, h_ap_F := by { rw mul_comm _ 16, exact eq_of_sub_eq_zero (iandf.final_ap _ rfl) }, mc := { n := inp.trace_length / 2 - 1, a := λ i, c.mem_pool__addr (2 * i), v := λ i, c.mem_pool__value (2 * i), em := pm.to_memory_embedding_constraints h_card_dom, mb := m.to_memory_block_constraints h_mem_star, h_n_lt := begin apply lt_of_lt_of_le _ trace_length_le_char, apply nat.lt_of_succ_le, rw [nat.sub_one, nat.succ_pred_eq_of_pos], { apply nat.div_le_self }, apply nat.div_pos _ (show 0 < 2, by norm_num), apply le_trans _ h_card_dom, apply le_add_left (le_refl _), end}, rc := rc.to_range_check_constraints trace_length_pos public_memory_prod_eq_one trace_length_le_char, ic := λ i, cd.to_instruction_constraints i, sc := λ i, by { rw fin.coe_succ, exact ops.to_step_constraints upd opcodes i (ne_of_lt i.is_lt) }, rcb := rcb.to_rc_builtin_constraints } /- probabilistic constraints -/ def bad1 {inp : input_data F} (h_card : 8 * fintype.card { x // option.is_some (inp.m_star x) } + 2 ≤ inp.trace_length) (c19 c20 : column F) : finset F := bad_set_1 (real_a inp.m_star (λ i, c19 (2 * i)) (embed_mem h_card)) (real_v inp.m_star (λ i, c19 (2 * i + 1)) (embed_mem h_card)) (λ j, c20 (2 * ↑j)) (λ j, c20 (2 * ↑j + 1)) def bad2 {inp : input_data F} (pd : public_data F) (h_card : 8 * fintype.card { x // option.is_some (inp.m_star x) } + 2 ≤ inp.trace_length) (c19 c20 : column F) : finset F := bad_set_2 (real_a inp.m_star (λ i, c19 (2 * i)) (embed_mem h_card)) (real_v inp.m_star (λ i, c19 (2 * i + 1)) (embed_mem h_card)) (λ j, c20 (2 * ↑j)) (λ j, c20 (2 * ↑j + 1)) pd.memory__multi_column_perm__hash_interaction_elm0 def bad3 (inp : input_data F) (c0 c2 : column F) : finset F := bad_set_3 (λ (i : fin (inp.trace_length - 1 + 1)), c0 i) (λ (i : fin (inp.trace_length - 1 + 1)), c2 i) lemma trace_length_div_two_pos {inp : input_data F} (h_card : 8 * fintype.card { x // option.is_some (inp.m_star x) } + 2 ≤ inp.trace_length) : inp.trace_length / 2 > 0 := begin apply nat.div_pos _ (show 0 < 2, by norm_num), apply le_trans _ h_card, apply le_add_left (le_refl _) end theorem bad1_bound {inp : input_data F} (h_card : 8 * fintype.card { x // option.is_some (inp.m_star x) } + 2 ≤ inp.trace_length) (c19 c20 : column F) : (bad1 h_card c19 c20).card ≤ (inp.trace_length / 2)^2 := begin transitivity, apply card_bad_set_1_le, rw [nat.sub_add_cancel, pow_two], apply trace_length_div_two_pos h_card end theorem bad2_bound {inp : input_data F} (pd : public_data F) (h_card : 8 * fintype.card { x // option.is_some (inp.m_star x) } + 2 ≤ inp.trace_length) (c19 c20 : column F) : (bad2 pd h_card c19 c20).card ≤ inp.trace_length / 2 := begin transitivity, apply card_bad_set_2_le, rw nat.sub_add_cancel, apply trace_length_div_two_pos h_card end theorem bad3_bound {inp : input_data F} (h_card : 8 * fintype.card { x // option.is_some (inp.m_star x) } + 2 ≤ inp.trace_length) (c0 c2 : column F) : (bad3 inp c0 c2).card ≤ inp.trace_length := begin transitivity, apply card_bad_set_3_le, rw nat.sub_add_cancel, exact lt_of_lt_of_le (nat.zero_lt_succ _) h_card end
9ad5717dc1d0e1f7267c186ca4d9c8a9601173e2
7cef822f3b952965621309e88eadf618da0c8ae9
/src/topology/uniform_space/cauchy.lean
fb7392c7b48cae36894bdf8b4af0cb596e000e3f
[ "Apache-2.0" ]
permissive
rmitta/mathlib
8d90aee30b4db2b013e01f62c33f297d7e64a43d
883d974b608845bad30ae19e27e33c285200bf84
refs/heads/master
1,585,776,832,544
1,576,874,096,000
1,576,874,096,000
153,663,165
0
2
Apache-2.0
1,544,806,490,000
1,539,884,365,000
Lean
UTF-8
Lean
false
false
22,547
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 Theory of Cauchy filters in uniform spaces. Complete uniform spaces. Totally bounded subsets. -/ import topology.uniform_space.basic data.set.intervals universes u v open filter topological_space lattice set classical open_locale classical variables {α : Type u} {β : Type v} [uniform_space α] open_locale uniformity topological_space /-- A filter `f` is Cauchy if for every entourage `r`, there exists an `s ∈ f` such that `s × s ⊆ r`. This is a generalization of Cauchy sequences, because if `a : ℕ → α` then the filter of sets containing cofinitely many of the `a n` is Cauchy iff `a` is a Cauchy sequence. -/ def cauchy (f : filter α) := f ≠ ⊥ ∧ filter.prod f f ≤ (𝓤 α) /-- A set `s` is called *complete*, if any Cauchy filter `f` such that `s ∈ f` has a limit in `s` (formally, it satisfies `f ≤ 𝓝 x` for some `x ∈ s`). -/ def is_complete (s : set α) := ∀f, cauchy f → f ≤ principal s → ∃x∈s, f ≤ 𝓝 x lemma cauchy_iff {f : filter α} : cauchy f ↔ (f ≠ ⊥ ∧ (∀ s ∈ 𝓤 α, ∃t∈f.sets, set.prod t t ⊆ s)) := and_congr iff.rfl $ forall_congr $ assume s, forall_congr $ assume hs, mem_prod_same_iff lemma cauchy_map_iff {l : filter β} {f : β → α} : cauchy (l.map f) ↔ (l ≠ ⊥ ∧ tendsto (λp:β×β, (f p.1, f p.2)) (l.prod l) (𝓤 α)) := by rw [cauchy, (≠), map_eq_bot_iff, prod_map_map_eq]; refl lemma cauchy_downwards {f g : filter α} (h_c : cauchy f) (hg : g ≠ ⊥) (h_le : g ≤ f) : cauchy g := ⟨hg, le_trans (filter.prod_mono h_le h_le) h_c.right⟩ lemma cauchy_nhds {a : α} : cauchy (𝓝 a) := ⟨nhds_neq_bot, calc filter.prod (𝓝 a) (𝓝 a) = (𝓤 α).lift (λs:set (α×α), (𝓤 α).lift' (λt:set(α×α), set.prod {y : α | (y, a) ∈ s} {y : α | (a, y) ∈ t})) : nhds_nhds_eq_uniformity_uniformity_prod ... ≤ (𝓤 α).lift' (λs:set (α×α), comp_rel s s) : le_infi $ assume s, le_infi $ assume hs, infi_le_of_le s $ infi_le_of_le hs $ infi_le_of_le s $ infi_le_of_le hs $ principal_mono.mpr $ assume ⟨x, y⟩ ⟨(hx : (x, a) ∈ s), (hy : (a, y) ∈ s)⟩, ⟨a, hx, hy⟩ ... ≤ 𝓤 α : comp_le_uniformity⟩ lemma cauchy_pure {a : α} : cauchy (pure a) := cauchy_downwards cauchy_nhds (show principal {a} ≠ ⊥, by simp) (pure_le_nhds a) /-- The common part of the proofs of `le_nhds_of_cauchy_adhp` and `sequentially_complete.le_nhds_of_seq_tendsto_nhds`: if for any entourage `s` one can choose a set `t ∈ f` of diameter `s` such that it contains a point `y` with `(x, y) ∈ s`, then `f` converges to `x`. -/ lemma le_nhds_of_cauchy_adhp_aux {f : filter α} {x : α} (adhs : ∀ s ∈ 𝓤 α, ∃ t ∈ f, (set.prod t t ⊆ s) ∧ ∃ y, (y ∈ t) ∧ (x, y) ∈ s) : f ≤ 𝓝 x := begin -- Consider a neighborhood `s` of `x` assume s hs, -- Take an entourage twice smaller than `s` rcases comp_mem_uniformity_sets (mem_nhds_uniformity_iff.1 hs) with ⟨U, U_mem, hU⟩, -- Take a set `t ∈ f`, `t × t ⊆ U`, and a point `y ∈ t` such that `(x, y) ∈ U` rcases adhs U U_mem with ⟨t, t_mem, ht, y, hy, hxy⟩, apply mem_sets_of_superset t_mem, -- Given a point `z ∈ t`, we have `(x, y) ∈ U` and `(y, z) ∈ t × t ⊆ U`, hence `z ∈ s` exact (λ z hz, hU (prod_mk_mem_comp_rel hxy (ht $ mk_mem_prod hy hz)) rfl) end /-- If `x` is an adherent (cluster) point for a Cauchy filter `f`, then it is a limit point for `f`. -/ lemma le_nhds_of_cauchy_adhp {f : filter α} {x : α} (hf : cauchy f) (adhs : f ⊓ 𝓝 x ≠ ⊥) : f ≤ 𝓝 x := le_nhds_of_cauchy_adhp_aux begin assume s hs, -- Take `t ∈ f` such that `t × t ⊆ s`. rcases (cauchy_iff.1 hf).2 s hs with ⟨t, t_mem, ht⟩, use [t, t_mem, ht], exact exists_mem_of_ne_empty (forall_sets_neq_empty_iff_neq_bot.2 adhs _ (inter_mem_inf_sets t_mem (mem_nhds_left x hs))) end lemma le_nhds_iff_adhp_of_cauchy {f : filter α} {x : α} (hf : cauchy f) : f ≤ 𝓝 x ↔ f ⊓ 𝓝 x ≠ ⊥ := ⟨assume h, (inf_of_le_left h).symm ▸ hf.left, le_nhds_of_cauchy_adhp hf⟩ lemma cauchy_map [uniform_space β] {f : filter α} {m : α → β} (hm : uniform_continuous m) (hf : cauchy f) : cauchy (map m f) := ⟨have f ≠ ⊥, from hf.left, by simp; assumption, calc filter.prod (map m f) (map m f) = map (λp:α×α, (m p.1, m p.2)) (filter.prod f f) : filter.prod_map_map_eq ... ≤ map (λp:α×α, (m p.1, m p.2)) (𝓤 α) : map_mono hf.right ... ≤ 𝓤 β : hm⟩ lemma cauchy_comap [uniform_space β] {f : filter β} {m : α → β} (hm : comap (λp:α×α, (m p.1, m p.2)) (𝓤 β) ≤ 𝓤 α) (hf : cauchy f) (hb : comap m f ≠ ⊥) : cauchy (comap m f) := ⟨hb, calc filter.prod (comap m f) (comap m f) = comap (λp:α×α, (m p.1, m p.2)) (filter.prod f f) : filter.prod_comap_comap_eq ... ≤ comap (λp:α×α, (m p.1, m p.2)) (𝓤 β) : comap_mono hf.right ... ≤ 𝓤 α : hm⟩ /-- Cauchy sequences. Usually defined on ℕ, but often it is also useful to say that a function defined on ℝ is Cauchy at +∞ to deduce convergence. Therefore, we define it in a type class that is general enough to cover both ℕ and ℝ, which are the main motivating examples. -/ def cauchy_seq [semilattice_sup β] (u : β → α) := cauchy (at_top.map u) lemma cauchy_seq_of_tendsto_nhds [semilattice_sup β] [nonempty β] (f : β → α) {x} (hx : tendsto f at_top (𝓝 x)) : cauchy_seq f := cauchy_downwards cauchy_nhds (map_ne_bot at_top_ne_bot) hx lemma cauchy_seq_iff_prod_map [inhabited β] [semilattice_sup β] {u : β → α} : cauchy_seq u ↔ map (prod.map u u) at_top ≤ 𝓤 α := iff.trans (and_iff_right (map_ne_bot at_top_ne_bot)) (prod_map_at_top_eq u u ▸ iff.rfl) lemma cauchy_seq_of_controlled [semilattice_sup β] [inhabited β] (U : β → set (α × α)) (hU : ∀ s ∈ 𝓤 α, ∃ n, U n ⊆ s) {f : β → α} (hf : ∀ {N m n : β}, N ≤ m → N ≤ n → (f m, f n) ∈ U N) : cauchy_seq f := cauchy_seq_iff_prod_map.2 begin assume s hs, rw [mem_map, mem_at_top_sets], cases hU s hs with N hN, refine ⟨(N, N), λ mn hmn, _⟩, cases mn with m n, exact hN (hf hmn.1 hmn.2) end /-- A complete space is defined here using uniformities. A uniform space is complete if every Cauchy filter converges. -/ class complete_space (α : Type u) [uniform_space α] : Prop := (complete : ∀{f:filter α}, cauchy f → ∃x, f ≤ 𝓝 x) lemma complete_univ {α : Type u} [uniform_space α] [complete_space α] : is_complete (univ : set α) := begin assume f hf _, rcases complete_space.complete hf with ⟨x, hx⟩, exact ⟨x, by simp, hx⟩ end lemma cauchy_prod [uniform_space β] {f : filter α} {g : filter β} : cauchy f → cauchy g → cauchy (filter.prod f g) | ⟨f_proper, hf⟩ ⟨g_proper, hg⟩ := ⟨filter.prod_neq_bot.2 ⟨f_proper, g_proper⟩, let p_α := λp:(α×β)×(α×β), (p.1.1, p.2.1), p_β := λp:(α×β)×(α×β), (p.1.2, p.2.2) in suffices (f.prod f).comap p_α ⊓ (g.prod g).comap p_β ≤ (𝓤 α).comap p_α ⊓ (𝓤 β).comap p_β, by simpa [uniformity_prod, filter.prod, filter.comap_inf, filter.comap_comap_comp, (∘), lattice.inf_assoc, lattice.inf_comm, lattice.inf_left_comm], lattice.inf_le_inf (filter.comap_mono hf) (filter.comap_mono hg)⟩ instance complete_space.prod [uniform_space β] [complete_space α] [complete_space β] : complete_space (α × β) := { complete := λ f hf, let ⟨x1, hx1⟩ := complete_space.complete $ cauchy_map uniform_continuous_fst hf in let ⟨x2, hx2⟩ := complete_space.complete $ cauchy_map uniform_continuous_snd hf in ⟨(x1, x2), by rw [nhds_prod_eq, filter.prod_def]; from filter.le_lift (λ s hs, filter.le_lift' $ λ t ht, have H1 : prod.fst ⁻¹' s ∈ f.sets := hx1 hs, have H2 : prod.snd ⁻¹' t ∈ f.sets := hx2 ht, filter.inter_mem_sets H1 H2)⟩ } /--If `univ` is complete, the space is a complete space -/ lemma complete_space_of_is_complete_univ (h : is_complete (univ : set α)) : complete_space α := ⟨λ f hf, let ⟨x, _, hx⟩ := h f hf ((@principal_univ α).symm ▸ le_top) in ⟨x, hx⟩⟩ lemma cauchy_iff_exists_le_nhds [complete_space α] {l : filter α} (hl : l ≠ ⊥) : cauchy l ↔ (∃x, l ≤ 𝓝 x) := ⟨complete_space.complete, assume ⟨x, hx⟩, cauchy_downwards cauchy_nhds hl hx⟩ lemma cauchy_map_iff_exists_tendsto [complete_space α] {l : filter β} {f : β → α} (hl : l ≠ ⊥) : cauchy (l.map f) ↔ (∃x, tendsto f l (𝓝 x)) := cauchy_iff_exists_le_nhds (map_ne_bot hl) /-- A Cauchy sequence in a complete space converges -/ theorem cauchy_seq_tendsto_of_complete [semilattice_sup β] [complete_space α] {u : β → α} (H : cauchy_seq u) : ∃x, tendsto u at_top (𝓝 x) := complete_space.complete H /-- If `K` is a complete subset, then any cauchy sequence in `K` converges to a point in `K` -/ lemma cauchy_seq_tendsto_of_is_complete [semilattice_sup β] {K : set α} (h₁ : is_complete K) {u : β → α} (h₂ : ∀ n, u n ∈ K) (h₃ : cauchy_seq u) : ∃ v ∈ K, tendsto u at_top (𝓝 v) := h₁ _ h₃ $ le_principal_iff.2 $ mem_map_sets_iff.2 ⟨univ, univ_mem_sets, by { simp only [image_univ], rintros _ ⟨n, rfl⟩, exact h₂ n }⟩ theorem le_nhds_lim_of_cauchy {α} [uniform_space α] [complete_space α] [inhabited α] {f : filter α} (hf : cauchy f) : f ≤ 𝓝 (lim f) := lim_spec (complete_space.complete hf) lemma is_complete_of_is_closed [complete_space α] {s : set α} (h : is_closed s) : is_complete s := λ f cf fs, let ⟨x, hx⟩ := complete_space.complete cf in ⟨x, is_closed_iff_nhds.mp h x (neq_bot_of_le_neq_bot cf.left (le_inf hx fs)), hx⟩ /-- A set `s` is totally bounded if for every entourage `d` there is a finite set of points `t` such that every element of `s` is `d`-near to some element of `t`. -/ def totally_bounded (s : set α) : Prop := ∀d ∈ 𝓤 α, ∃t : set α, finite t ∧ s ⊆ (⋃y∈t, {x | (x,y) ∈ d}) theorem totally_bounded_iff_subset {s : set α} : totally_bounded s ↔ ∀d ∈ 𝓤 α, ∃t ⊆ s, finite t ∧ s ⊆ (⋃y∈t, {x | (x,y) ∈ d}) := ⟨λ H d hd, begin rcases comp_symm_of_uniformity hd with ⟨r, hr, rs, rd⟩, rcases H r hr with ⟨k, fk, ks⟩, let u := {y ∈ k | ∃ x, x ∈ s ∧ (x, y) ∈ r}, let f : u → α := λ x, classical.some x.2.2, have : ∀ x : u, f x ∈ s ∧ (f x, x.1) ∈ r := λ x, classical.some_spec x.2.2, refine ⟨range f, _, _, _⟩, { exact range_subset_iff.2 (λ x, (this x).1) }, { have : finite u := finite_subset fk (λ x h, h.1), exact ⟨@set.fintype_range _ _ _ _ this.fintype⟩ }, { intros x xs, have := ks xs, simp at this, rcases this with ⟨y, hy, xy⟩, let z : coe_sort u := ⟨y, hy, x, xs, xy⟩, exact mem_bUnion_iff.2 ⟨_, ⟨z, rfl⟩, rd $ mem_comp_rel.2 ⟨_, xy, rs (this z).2⟩⟩ } end, λ H d hd, let ⟨t, _, ht⟩ := H d hd in ⟨t, ht⟩⟩ lemma totally_bounded_subset {s₁ s₂ : set α} (hs : s₁ ⊆ s₂) (h : totally_bounded s₂) : totally_bounded s₁ := assume d hd, let ⟨t, ht₁, ht₂⟩ := h d hd in ⟨t, ht₁, subset.trans hs ht₂⟩ lemma totally_bounded_empty : totally_bounded (∅ : set α) := λ d hd, ⟨∅, finite_empty, empty_subset _⟩ lemma totally_bounded_closure {s : set α} (h : totally_bounded s) : totally_bounded (closure s) := assume t ht, let ⟨t', ht', hct', htt'⟩ := mem_uniformity_is_closed ht, ⟨c, hcf, hc⟩ := h t' ht' in ⟨c, hcf, calc closure s ⊆ closure (⋃ (y : α) (H : y ∈ c), {x : α | (x, y) ∈ t'}) : closure_mono hc ... = _ : closure_eq_of_is_closed $ is_closed_bUnion hcf $ assume i hi, continuous_iff_is_closed.mp (continuous_id.prod_mk continuous_const) _ hct' ... ⊆ _ : bUnion_subset $ assume i hi, subset.trans (assume x, @htt' (x, i)) (subset_bUnion_of_mem hi)⟩ lemma totally_bounded_image [uniform_space β] {f : α → β} {s : set α} (hf : uniform_continuous f) (hs : totally_bounded s) : totally_bounded (f '' s) := assume t ht, have {p:α×α | (f p.1, f p.2) ∈ t} ∈ 𝓤 α, from hf ht, let ⟨c, hfc, hct⟩ := hs _ this in ⟨f '' c, finite_image f hfc, begin simp [image_subset_iff], simp [subset_def] at hct, intros x hx, simp [-mem_image], exact let ⟨i, hi, ht⟩ := hct x hx in ⟨f i, mem_image_of_mem f hi, ht⟩ end⟩ lemma cauchy_of_totally_bounded_of_ultrafilter {s : set α} {f : filter α} (hs : totally_bounded s) (hf : is_ultrafilter f) (h : f ≤ principal s) : cauchy f := ⟨hf.left, assume t ht, let ⟨t', ht'₁, ht'_symm, ht'_t⟩ := comp_symm_of_uniformity ht in let ⟨i, hi, hs_union⟩ := hs t' ht'₁ in have (⋃y∈i, {x | (x,y) ∈ t'}) ∈ f.sets, from mem_sets_of_superset (le_principal_iff.mp h) hs_union, have ∃y∈i, {x | (x,y) ∈ t'} ∈ f.sets, from mem_of_finite_Union_ultrafilter hf hi this, let ⟨y, hy, hif⟩ := this in have set.prod {x | (x,y) ∈ t'} {x | (x,y) ∈ t'} ⊆ comp_rel t' t', from assume ⟨x₁, x₂⟩ ⟨(h₁ : (x₁, y) ∈ t'), (h₂ : (x₂, y) ∈ t')⟩, ⟨y, h₁, ht'_symm h₂⟩, (filter.prod f f).sets_of_superset (prod_mem_prod hif hif) (subset.trans this ht'_t)⟩ lemma totally_bounded_iff_filter {s : set α} : totally_bounded s ↔ (∀f, f ≠ ⊥ → f ≤ principal s → ∃c ≤ f, cauchy c) := ⟨assume : totally_bounded s, assume f hf hs, ⟨ultrafilter_of f, ultrafilter_of_le, cauchy_of_totally_bounded_of_ultrafilter this (ultrafilter_ultrafilter_of hf) (le_trans ultrafilter_of_le hs)⟩, assume h : ∀f, f ≠ ⊥ → f ≤ principal s → ∃c ≤ f, cauchy c, assume d hd, classical.by_contradiction $ assume hs, have hd_cover : ∀{t:set α}, finite t → ¬ s ⊆ (⋃y∈t, {x | (x,y) ∈ d}), by simpa using hs, let f := ⨅t:{t : set α // finite t}, principal (s \ (⋃y∈t.val, {x | (x,y) ∈ d})), ⟨a, ha⟩ := @exists_mem_of_ne_empty α s (assume h, hd_cover finite_empty $ h.symm ▸ empty_subset _) in have f ≠ ⊥, from infi_neq_bot_of_directed ⟨a⟩ (assume ⟨t₁, ht₁⟩ ⟨t₂, ht₂⟩, ⟨⟨t₁ ∪ t₂, finite_union ht₁ ht₂⟩, principal_mono.mpr $ diff_subset_diff_right $ Union_subset_Union $ assume t, Union_subset_Union_const or.inl, principal_mono.mpr $ diff_subset_diff_right $ Union_subset_Union $ assume t, Union_subset_Union_const or.inr⟩) (assume ⟨t, ht⟩, by simp [diff_eq_empty]; exact hd_cover ht), have f ≤ principal s, from infi_le_of_le ⟨∅, finite_empty⟩ $ by simp; exact subset.refl s, let ⟨c, (hc₁ : c ≤ f), (hc₂ : cauchy c)⟩ := h f ‹f ≠ ⊥› this, ⟨m, hm, (hmd : set.prod m m ⊆ d)⟩ := (@mem_prod_same_iff α c d).mp $ hc₂.right hd in have c ≤ principal s, from le_trans ‹c ≤ f› this, have m ∩ s ∈ c.sets, from inter_mem_sets hm $ le_principal_iff.mp this, let ⟨y, hym, hys⟩ := inhabited_of_mem_sets hc₂.left this in let ys := (⋃y'∈({y}:set α), {x | (x, y') ∈ d}) in have m ⊆ ys, from assume y' hy', show y' ∈ (⋃y'∈({y}:set α), {x | (x, y') ∈ d}), by simp; exact @hmd (y', y) ⟨hy', hym⟩, have c ≤ principal (s - ys), from le_trans hc₁ $ infi_le_of_le ⟨{y}, finite_singleton _⟩ $ le_refl _, have (s - ys) ∩ (m ∩ s) ∈ c.sets, from inter_mem_sets (le_principal_iff.mp this) ‹m ∩ s ∈ c.sets›, have ∅ ∈ c.sets, from c.sets_of_superset this $ assume x ⟨⟨hxs, hxys⟩, hxm, _⟩, hxys $ ‹m ⊆ ys› hxm, hc₂.left $ empty_in_sets_eq_bot.mp this⟩ lemma totally_bounded_iff_ultrafilter {s : set α} : totally_bounded s ↔ (∀f, is_ultrafilter f → f ≤ principal s → cauchy f) := ⟨assume hs f, cauchy_of_totally_bounded_of_ultrafilter hs, assume h, totally_bounded_iff_filter.mpr $ assume f hf hfs, have cauchy (ultrafilter_of f), from h (ultrafilter_of f) (ultrafilter_ultrafilter_of hf) (le_trans ultrafilter_of_le hfs), ⟨ultrafilter_of f, ultrafilter_of_le, this⟩⟩ lemma compact_iff_totally_bounded_complete {s : set α} : compact s ↔ totally_bounded s ∧ is_complete s := ⟨λ hs, ⟨totally_bounded_iff_ultrafilter.2 (λ f hf1 hf2, let ⟨x, xs, fx⟩ := compact_iff_ultrafilter_le_nhds.1 hs f hf1 hf2 in cauchy_downwards (cauchy_nhds) (hf1.1) fx), λ f fc fs, let ⟨a, as, fa⟩ := hs f fc.1 fs in ⟨a, as, le_nhds_of_cauchy_adhp fc fa⟩⟩, λ ⟨ht, hc⟩, compact_iff_ultrafilter_le_nhds.2 (λf hf hfs, hc _ (totally_bounded_iff_ultrafilter.1 ht _ hf hfs) hfs)⟩ @[priority 100] -- see Note [lower instance priority] instance complete_of_compact {α : Type u} [uniform_space α] [compact_space α] : complete_space α := ⟨λf hf, by simpa [principal_univ] using (compact_iff_totally_bounded_complete.1 compact_univ).2 f hf⟩ lemma compact_of_totally_bounded_is_closed [complete_space α] {s : set α} (ht : totally_bounded s) (hc : is_closed s) : compact s := (@compact_iff_totally_bounded_complete α _ s).2 ⟨ht, is_complete_of_is_closed hc⟩ /-! ### Sequentially complete space In this section we prove that a uniform space is complete provided that it is sequentially complete (i.e., any Cauchy sequence converges) and its uniformity filter admits a countable generating set. In particular, this applies to (e)metric spaces, see file `topology/metric_space/cau_seq_filter`. More precisely, we assume that there is a sequence of entourages `U_n` such that any other entourage includes one of `U_n`. Then any Cauchy filter `f` generates a decreasing sequence of sets `s_n ∈ f` such that `s_n × s_n ⊆ U_n`. Choose a sequence `x_n∈s_n`. It is easy to show that this is a Cauchy sequence. If this sequence converges to some `a`, then `f ≤ 𝓝 a`. -/ namespace sequentially_complete variables {f : filter α} (hf : cauchy f) {U : ℕ → set (α × α)} (U_mem : ∀ n, U n ∈ 𝓤 α) (U_le : ∀ s ∈ 𝓤 α, ∃ n, U n ⊆ s) open set finset noncomputable theory /-- An auxiliary sequence of sets approximating a Cauchy filter. -/ def set_seq_aux (n : ℕ) : {s : set α // ∃ (_ : s ∈ f), s.prod s ⊆ U n } := indefinite_description _ $ (cauchy_iff.1 hf).2 (U n) (U_mem n) /-- Given a Cauchy filter `f` and a sequence `U` of entourages, `set_seq` provides a sequence of monotonically decreasing sets `s n ∈ f` such that `(s n).prod (s n) ⊆ U`. -/ def set_seq (n : ℕ) : set α := ⋂ m ∈ Iic n, (set_seq_aux hf U_mem m).val lemma set_seq_mem (n : ℕ) : set_seq hf U_mem n ∈ f := Inter_mem_sets (finite_le_nat n) (λ m _, (set_seq_aux hf U_mem m).2.fst) lemma set_seq_mono ⦃m n : ℕ⦄ (h : m ≤ n) : set_seq hf U_mem n ⊆ set_seq hf U_mem m := bInter_subset_bInter_left (λ k hk, le_trans hk h) lemma set_seq_sub_aux (n : ℕ) : set_seq hf U_mem n ⊆ set_seq_aux hf U_mem n := bInter_subset_of_mem right_mem_Iic lemma set_seq_prod_subset {N m n} (hm : N ≤ m) (hn : N ≤ n) : (set_seq hf U_mem m).prod (set_seq hf U_mem n) ⊆ U N := begin assume p hp, refine (set_seq_aux hf U_mem N).2.snd ⟨_, _⟩; apply set_seq_sub_aux, exact set_seq_mono hf U_mem hm hp.1, exact set_seq_mono hf U_mem hn hp.2 end /-- A sequence of points such that `seq n ∈ set_seq n`. Here `set_seq` is a monotonically decreasing sequence of sets `set_seq n ∈ f` with diameters controlled by a given sequence of entourages. -/ def seq (n : ℕ) : α := some $ inhabited_of_mem_sets hf.1 (set_seq_mem hf U_mem n) lemma seq_mem (n : ℕ) : seq hf U_mem n ∈ set_seq hf U_mem n := some_spec $ inhabited_of_mem_sets hf.1 (set_seq_mem hf U_mem n) lemma seq_pair_mem ⦃N m n : ℕ⦄ (hm : N ≤ m) (hn : N ≤ n) : (seq hf U_mem m, seq hf U_mem n) ∈ U N := set_seq_prod_subset hf U_mem hm hn ⟨seq_mem hf U_mem m, seq_mem hf U_mem n⟩ include U_le theorem seq_is_cauchy_seq : cauchy_seq $ seq hf U_mem := cauchy_seq_of_controlled U U_le $ seq_pair_mem hf U_mem /-- If the sequence `sequentially_complete.seq` converges to `a`, then `f ≤ 𝓝 a`. -/ theorem le_nhds_of_seq_tendsto_nhds ⦃a : α⦄ (ha : tendsto (seq hf U_mem) at_top (𝓝 a)) : f ≤ 𝓝 a := le_nhds_of_cauchy_adhp_aux begin assume s hs, rcases U_le s hs with ⟨m, hm⟩, rcases (tendsto_at_top' _ _).1 ha _ (mem_nhds_left a (U_mem m)) with ⟨n, hn⟩, refine ⟨set_seq hf U_mem (max m n), set_seq_mem hf U_mem _, _, seq hf U_mem (max m n), seq_mem hf U_mem _, _⟩, { have := le_max_left m n, exact set.subset.trans (set_seq_prod_subset hf U_mem this this) hm }, { exact hm (hn _ $ le_max_right m n) } end end sequentially_complete namespace uniform_space open sequentially_complete variables (U : ℕ → set (α × α)) (U_mem : ∀ n, U n ∈ 𝓤 α) (U_le : ∀ s ∈ 𝓤 α, ∃ n, U n ⊆ s) (U' : ℕ → set (α × α)) (U'_mem : ∀ n, U' n ∈ 𝓤 α) /-- A uniform space is complete provided that (a) its uniformity filter has a countable basis; (b) any sequence satisfying a "controlled" version of the Cauchy condition converges. -/ theorem complete_of_convergent_controlled_sequences (H : ∀ u : ℕ → α, (∀ N m n, N ≤ m → N ≤ n → (u m, u n) ∈ U' N) → ∃ a, tendsto u at_top (𝓝 a)) : complete_space α := -- We take a sequence majorated by both `U` and `U'` let U'' := λ n, U n ∩ U' n in have U''_sub_U : ∀ n, U'' n ⊆ U n, from λ n, inter_subset_left _ _, have U''_sub_U' : ∀ n, U'' n ⊆ U' n, from λ n, inter_subset_right _ _, have U''_mem : ∀ n, U'' n ∈ 𝓤 α, from λ n, inter_mem_sets (U_mem n) (U'_mem n), have U''_le : ∀ s ∈ 𝓤 α, ∃ n, U'' n ⊆ s, from λ s hs, (U_le s hs).imp (λ n hn x hx, hn $ U''_sub_U n hx), begin refine ⟨λ f hf, (H (seq hf U''_mem) (λ N m n hm hn, _)).imp $ le_nhds_of_seq_tendsto_nhds hf U''_mem U''_le⟩, exact U''_sub_U' _ (seq_pair_mem hf U''_mem hm hn), end /-- A sequentially complete uniform space with a countable basis of the uniformity filter is complete. -/ theorem complete_of_cauchy_seq_tendsto (H : ∀ u : ℕ → α, cauchy_seq u → ∃a, tendsto u at_top (𝓝 a)) : complete_space α := complete_of_convergent_controlled_sequences U U_mem U_le U U_mem (λ u hu, H u $ cauchy_seq_of_controlled U U_le hu) end uniform_space
ab7b2cc21aa6e212b16b8c6462fe879a5c9f55d0
72f5572e1935cd1fb8bb2f4d3e83baf510ef2910
/lean/hello.lean
709ed558790d4ff7662dc1df49506b951f52f0ee
[]
no_license
0918nobita/theorem-proving
7f546c0d4fe37745ad3bf86c12590dab3fc8ccce
394e45bbd67e916d6800dbfdcf89dcabb139f4c1
refs/heads/main
1,690,365,095,725
1,631,347,571,000
1,631,347,617,000
404,406,926
2
0
null
null
null
null
UTF-8
Lean
false
false
2,265
lean
-- #check コマンドは項の型を出力する #check 1 #check fun (x : Nat) => x + 1 -- #eval コマンドは即座に式を評価し結果を出力する #eval (fun (x : Nat) => x + 1) 3 def fact : Nat → Nat | 0 => 1 | n + 1 => (n + 1) * fact n #eval fact 5 #check @toString #eval List.map (fun x => toString x) [1, 2, 3] #eval [4, 5, 6].map toString -- [intro タクティック] -- 現在のゴールが `forall x : t, u` ならば、intro タクティックは局所文脈に `x : t` を追加する。 -- 新しいサブゴール対象は u となる。 -- [cases タクティック] -- `cases x` は x が局所文脈での帰納的型の変数であることを推定してメインゴールを分割し、 -- その帰納的型のコンストラクタそれぞれに対して、対象がコンストラクタの全般的なインスタンスに置き換えられたひとつのゴールを生成する。 -- 局所文脈の要素の型が x に依存している場合、その要素は後で元に戻され再導入されるため、場合分けがその仮定に同様に影響を与える。 theorem ex1 : p ∨ q → q ∨ p := by intro h cases h with | Or.inl h1 => apply Or.inr; exact h1 | Or.inr h2 => apply Or.inl; exact h2 -- Lean の主要なコンセプトは「型」と「関数」 -- すべての Lean プログラムの最も基本的な要素は、名前空間に集約される関数である。 -- 関数は入力に対して出力を生成するために働き、それらは名前空間に集約される。 -- 名前空間はものをグループ化する主要な方法である。 -- 関数は def コマンドを用いて定義される。 -- def コマンドは関数に名前を与え、その引数を定義する def sampleFunction1 x := x * x + 3 def result1 := sampleFunction1 5 -- {} 内の値は toString 多相関数を用いて文字列に変換され、埋め込まれて出力される #eval println! "The result of squaring the integer 5 and adding 3 is {result1}" -- 必要なら、仮引数の型を指定することができる def sampleFunction2 (x : Nat) := 2 * x - 3 def result2 := sampleFunction2 7 #eval println! "The result of applying the 2nd sample function to 7 is {result2}"
8fc505eeb25f3aac74b1ee89fe021618364c34ba
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/tactic/trunc_cases.lean
a4a50b80011e6e9d63768808783afcb58480a43b
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
1,538
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.tactic.chain import Mathlib.data.quot import Mathlib.PostPort namespace Mathlib namespace tactic /-- Auxiliary tactic for `trunc_cases`. -/ /-- Auxiliary tactic for `trunc_cases`. -/ /-- Auxiliary tactic for `trunc_cases`. -/ namespace interactive /-- `trunc_cases e` performs case analysis on a `trunc` expression `e`, attempting the following strategies: 1. when the goal is a subsingleton, calling `induction e using trunc.rec_on_subsingleton`, 2. when the goal does not depend on `e`, calling `fapply trunc.lift_on e`, and using `intro` and `clear` afterwards to make the goals look like we used `induction`, 3. otherwise, falling through to `trunc.rec_on`, and in the new invariance goal calling `cases h_p` on the useless `h_p : true` hypothesis, and then attempting to simplify the `eq.rec`. `trunc_cases e with h` names the new hypothesis `h`. If `e` is a local hypothesis already, `trunc_cases` defaults to reusing the same name. `trunc_cases e with h h_a h_b` will use the names `h_a` and `h_b` for the new hypothesis in the invariance goal if `trunc_cases` uses `trunc.lift_on` or `trunc.rec_on`. Finally, if the new hypothesis from inside the `trunc` is a type class, `trunc_cases` resets the instance cache so that it is immediately available. -/ end interactive end tactic
dadfe5d486263a8c05b0fd5b7d3e739ed0dcac18
7b66d83f3b69dae0a3dfb684d7ebe5e9e3f3c913
/src/demos/structures.lean
f4ec8797bb002005ee87a9424f39a5f9352c742d
[]
permissive
dpochekutov/lftcm2020
58a09e10f0e638075b97884d3c2612eb90296adb
cdfbf1ac089f21058e523db73f2476c9c98ed16a
refs/heads/master
1,669,226,265,076
1,594,629,725,000
1,594,629,725,000
279,213,346
1
0
MIT
1,594,622,757,000
1,594,615,843,000
null
UTF-8
Lean
false
false
4,719
lean
import data.rat.basic import algebra.group.prod /-! Lecture 1: * Use one structure as a running example, probably `equiv` or `embedding`. * Declaring a structure * name, arguments, type, fields * Using a structure * Using projections (without and with the `open` command) * projection notation * `.1`, `.2` Lecture 2: * The `extends` keyword * Declaring objects of a structure * Using the structure notation `{ field1 := _ }` and the `..` notation (and hole commands) * Using the anonymous constructor * maybe: using the constructor `foo.mk` Lecture 3: Classes * Difference between structures and classes * How to use classes * When to use classes Lecture 4: "advanced" topics * Proving equalities between objects of a structure * ext * Subtypes and prod (& existential & sigma types) * maybe: declaring coercions * ... -/ noncomputable theory open function variables {α β : Type*} #print embedding #print equiv /- potential examples / exercises / solutions to exercises -/ structure bijection (α β : Type*) extends embedding α β := (surjective : surjective to_fun) instance : has_coe_to_fun (bijection α β) := ⟨_, λ f, f.to_fun⟩ /- after lecture 2, though it's mostly an exercise in searching the library (or proving something nontrivial) -/ def equiv_of_bijection (f : bijection α β) : α ≃ β := equiv.of_bijective f ⟨f.inj', f.surjective⟩ def bijection_of_equiv (f : α ≃ β) : bijection α β := { to_fun := f, inj' := f.injective, surjective := f.surjective } /- after lecture 4 -/ def bijection_equiv_equiv : bijection α β ≃ (α ≃ β) := sorry structure Group := (G : Type*) (op : G → G → G) (infix * := op) -- temporary notation for `op`, just inside this structure declaration (op_assoc' : ∀ (x y z : G), (x * y) * z = x * (y * z)) (id : G) (notation 1 := id) -- temporary notation for `1`, just inside this structure declaration (id_op' : ∀ (x : G), 1 * x = x) (inv : G → G) (postfix ⁻¹ := inv) -- temporary notation for `inv`, just inside this structure declaration (op_left_inv' : ∀ (x : G), x⁻¹ * x = 1) /- exercise after lesson 2 -/ namespace Group variables {G : Group} /- declaring that if `G : Group`, then we can view `G` as a type. -/ instance : has_coe_to_sort Group := ⟨_, Group.G⟩ /- declaring notation `*`, `⁻¹` and `1` for `G : Group`. -/ instance : has_mul G := ⟨G.op⟩ instance : has_inv G := ⟨G.inv⟩ instance : has_one G := ⟨G.id⟩ /- the axioms for groups are satisfied -/ lemma op_assoc (x y z : G) : (x * y) * z = x * (y * z) := G.op_assoc' x y z lemma id_op (x : G) : 1 * x = x := G.id_op' x lemma op_left_inv (x : G) : x⁻¹ * x = 1 := G.op_left_inv' x /- Use these axioms to prove this useful lemma. -/ lemma eq_id_of_op_eq_self {G : Group} {x : G} : x * x = x → x = 1 := by { intro hx, rw [←id_op x, ← op_left_inv x, op_assoc, hx] } /- Apply the previous lemma to show that `⁻¹` is also a right-sided inverse. -/ lemma op_right_inv {G : Group} (x : G) : x * x⁻¹ = 1 := by { apply eq_id_of_op_eq_self, rw [op_assoc x x⁻¹ (x * x⁻¹), ← op_assoc x⁻¹ x x⁻¹, op_left_inv, id_op] } /- we can prove that `1` is also a right identity. -/ lemma op_id {G : Group} (x : G) : x * 1 = x := by { rw [← op_left_inv x, ← op_assoc, op_right_inv, id_op] } /- after lecture 2 -/ /- show that the rationals under addition form a group. The underlying type will be `ℚ`. -/ def rat_Group : Group := { G := ℚ, op := (+), op_assoc' := add_assoc, id := 0, id_op' := zero_add, inv := λ x, -x, op_left_inv' := neg_add_self } /- However, one disadvantage is that to use these group operations we now have to write `(x y : rat_Group)` instead of `(x y : ℚ)`. That's why in Lean we do something else, explained in the next lecture. -/ /- after lecture 4 -/ /- show that the cartesian product of two groups is a group. The underlying type will be `G × H`. -/ def prod_Group2 (G H : Group) : Group := { G := G × H, op := λ x y, (x.1 * y.1, x.2 * y.2), op_assoc' := by { intros, ext; simp; rw [op_assoc] }, id := (1, 1), id_op' := by { intros, ext; simp; rw [id_op] }, inv := λ x, (x.1⁻¹, x.2⁻¹), op_left_inv' := by { intros, ext; simp; rw [op_left_inv] } } -- solution 2: use operations from the library (cannot use `mul_assoc` etc. from the library, since we have not declared the appropriate instances) def prod_Group (G H : Group) : Group := { G := G × H, op := (*), op_assoc' := by { intros, ext; simp; rw [op_assoc] }, id := 1, id_op' := by { intros, ext; simp; rw [id_op] }, inv := λ x, x⁻¹, op_left_inv' := by { intros, ext; simp; rw [op_left_inv] } } end Group
d119772d63333c1b83a935e263663ac4f65b5a65
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/ring_theory/nakayama.lean
5843c7a1ff70b8465e568f8d22a9212158772957
[ "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
4,563
lean
/- Copyright (c) 2021 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import ring_theory.noetherian import ring_theory.jacobson /-! # Nakayama's lemma This file contains some alternative statements of Nakayama's Lemma as found in [Stacks: Nakayama's Lemma](https://stacks.math.columbia.edu/tag/00DV). ## Main statements * `submodule.eq_smul_of_le_smul_of_le_jacobson` - A version of (2) in [Stacks: Nakayama's Lemma](https://stacks.math.columbia.edu/tag/00DV)., generalising to the Jacobson of any ideal. * `submodule.eq_bot_of_le_smul_of_le_jacobson_bot` - Statement (2) in [Stacks: Nakayama's Lemma](https://stacks.math.columbia.edu/tag/00DV). * `submodule.smul_sup_eq_smul_sup_of_le_smul_of_le_jacobson` - A version of (4) in [Stacks: Nakayama's Lemma](https://stacks.math.columbia.edu/tag/00DV)., generalising to the Jacobson of any ideal. * `submodule.smul_sup_eq_of_le_smul_of_le_jacobson_bot` - Statement (4) in [Stacks: Nakayama's Lemma](https://stacks.math.columbia.edu/tag/00DV). Note that a version of Statement (1) in [Stacks: Nakayama's Lemma](https://stacks.math.columbia.edu/tag/00DV) can be found in `ring_theory/noetherian` under the name `submodule.exists_sub_one_mem_and_smul_eq_zero_of_fg_of_le_smul` ## References * [Stacks: Nakayama's Lemma](https://stacks.math.columbia.edu/tag/00DV) ## Tags Nakayama, Jacobson -/ variables {R M : Type*} [comm_ring R] [add_comm_group M] [module R M] open ideal namespace submodule /-- *Nakayama's Lemma** - A slightly more general version of (2) in [Stacks 00DV](https://stacks.math.columbia.edu/tag/00DV). See also `eq_bot_of_le_smul_of_le_jacobson_bot` for the special case when `J = ⊥`. -/ lemma eq_smul_of_le_smul_of_le_jacobson {I J : ideal R} {N : submodule R M} (hN : N.fg) (hIN : N ≤ I • N) (hIjac : I ≤ jacobson J) : N = J • N := begin refine le_antisymm _ (submodule.smul_le.2 (λ _ _ _, submodule.smul_mem _ _)), intros n hn, cases submodule.exists_sub_one_mem_and_smul_eq_zero_of_fg_of_le_smul I N hN hIN with r hr, cases exists_mul_sub_mem_of_sub_one_mem_jacobson r (hIjac hr.1) with s hs, have : n = (-(r * s - 1) • n), { rw [neg_sub, sub_smul, mul_comm, mul_smul, hr.2 n hn, one_smul, smul_zero, sub_zero] }, rw this, exact submodule.smul_mem_smul (submodule.neg_mem _ hs) hn end /-- *Nakayama's Lemma** - Statement (2) in [Stacks 00DV](https://stacks.math.columbia.edu/tag/00DV). See also `eq_smul_of_le_smul_of_le_jacobson` for a generalisation to the `jacobson` of any ideal -/ lemma eq_bot_of_le_smul_of_le_jacobson_bot (I : ideal R) (N : submodule R M) (hN : N.fg) (hIN : N ≤ I • N) (hIjac : I ≤ jacobson ⊥) : N = ⊥ := by rw [eq_smul_of_le_smul_of_le_jacobson hN hIN hIjac, submodule.bot_smul] /-- *Nakayama's Lemma** - A slightly more general version of (4) in [Stacks 00DV](https://stacks.math.columbia.edu/tag/00DV). See also `smul_sup_eq_of_le_smul_of_le_jacobson_bot` for the special case when `J = ⊥`. -/ lemma smul_sup_eq_smul_sup_of_le_smul_of_le_jacobson {I J : ideal R} {N N' : submodule R M} (hN' : N'.fg) (hIJ : I ≤ jacobson J) (hNN : N ⊔ N' ≤ N ⊔ I • N') : N ⊔ I • N' = N ⊔ J • N' := begin have hNN' : N ⊔ N' = N ⊔ I • N', from le_antisymm hNN (sup_le_sup_left (submodule.smul_le.2 (λ _ _ _, submodule.smul_mem _ _)) _), have : (I • N').map N.mkq = N'.map N.mkq, { rw ← (submodule.comap_injective_of_surjective (linear_map.range_eq_top.1 (submodule.range_mkq N))).eq_iff, simpa [comap_map_eq, sup_comm, eq_comm] using hNN' }, have := @submodule.eq_smul_of_le_smul_of_le_jacobson _ _ _ _ _ I J (N'.map N.mkq) (fg_map hN') (by rw [← map_smul'', this]; exact le_refl _) hIJ, rw [← map_smul'', ← (submodule.comap_injective_of_surjective (linear_map.range_eq_top.1 (submodule.range_mkq N))).eq_iff, comap_map_eq, comap_map_eq, submodule.ker_mkq, sup_comm, hNN'] at this, rw [this, sup_comm] end /-- *Nakayama's Lemma** - Statement (4) in [Stacks 00DV](https://stacks.math.columbia.edu/tag/00DV). See also `smul_sup_eq_smul_sup_of_le_smul_of_le_jacobson` for a generalisation to the `jacobson` of any ideal -/ lemma smul_sup_le_of_le_smul_of_le_jacobson_bot {I : ideal R} {N N' : submodule R M} (hN' : N'.fg) (hIJ : I ≤ jacobson ⊥) (hNN : N ⊔ N' ≤ N ⊔ I • N') : I • N' ≤ N := by rw [← sup_eq_left, smul_sup_eq_smul_sup_of_le_smul_of_le_jacobson hN' hIJ hNN, bot_smul, sup_bot_eq] end submodule
c52e3ab22aebf1f4e02bba774af68f6bcdb5787b
367134ba5a65885e863bdc4507601606690974c1
/src/algebra/char_p/default.lean
768ba641836089e5d706eaa5a1b5bf5d203ac168
[ "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
114
lean
import algebra.char_p.basic import algebra.char_p.pi import algebra.char_p.quotient import algebra.char_p.subring
95d6d7312f97ce9fe7ec77dacae1274b11e3fa45
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/topology/category/Compactum.lean
6248193ebb7e3580a0e24a25aa4a4a407f8916cc
[]
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
10,359
lean
/- Copyright (c) 2020 Adam Topaz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Adam Topaz -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.category_theory.monad.types import Mathlib.category_theory.monad.limits import Mathlib.category_theory.equivalence import Mathlib.topology.category.CompHaus import Mathlib.data.set.constructions import Mathlib.PostPort universes u_1 u_2 namespace Mathlib /-! # Compacta and Compact Hausdorff Spaces Recall that, given a monad `M` on `Type*`, an *algebra* for `M` consists of the following data: - A type `X : Type*` - A "structure" map `M X → X`. This data must also satisfy a distributivity and unit axiom, and algebras for `M` form a category in an evident way. See the file `category_theory.monad.algebra` for a general version, as well as the following link. https://ncatlab.org/nlab/show/monad This file proves the equivalence between the category of *compact Hausdorff topological spaces* and the category of algebras for the *ultrafilter monad*. ## Notation: Here are the main objects introduced in this file. - `Compactum` is the type of compacta, which we define as algebras for the ultrafilter monad. - `Compactum_to_CompHaus` is the functor `Compactum ⥤ CompHaus`. Here `CompHaus` is the usual category of compact Hausdorff spaces. - `Compactum_to_CompHaus.is_equivalence` is a term of type `is_equivalence Compactum_to_CompHaus`. The proof of this equivalence is a bit technical. But the idea is quite simply that the structure map `ultrafilter X → X` for an algebra `X` of the ultrafilter monad should be considered as the map sending an ultrafilter to its limit in `X`. The topology on `X` is then defined by mimicking the characterization of open sets in terms of ultrafilters. Any `X : Compactum` is endowed with a coercion to `Type*`, as well as the following instances: - `topological_space X`. - `compact_space X`. - `t2_space X`. Any morphism `f : X ⟶ Y` of is endowed with a coercion to a function `X → Y`, which is shown to be continuous in `continuous_of_hom`. The function `Compactum.of_topological_space` can be used to construct a `Compactum` from a topological space which satisfies `compact_space` and `t2_space`. We also add wrappers around structures which already exist. Here are the main ones, all in the `Compactum` namespace: - `forget : Compactum ⥤ Type*` is the forgetful functor, which induces a `concrete_category` instance for `Compactum`. - `free : Type* ⥤ Compactum` is the left adjoint to `forget`, and the adjunction is in `adj`. - `str : ultrafilter X → X` is the structure map for `X : Compactum`. The notation `X.str` is preferred. - `join : ultrafilter (ultrafilter X) → ultrafilter X` is the monadic join for `X : Compactum`. Again, the notation `X.join` is preferred. - `incl : X → ultrafilter X` is the unit for `X : Compactum`. The notation `X.incl` is preferred. ## References - E. Manes, Algebraic Theories, Graduate Texts in Mathematics 26, Springer-Verlag, 1976. - https://ncatlab.org/nlab/show/ultrafilter -/ /-- The type `Compactum` of Compacta, defined as algebras for the ultrafilter monad. -/ def Compactum := category_theory.monad.algebra (category_theory.of_type_functor ultrafilter) namespace Compactum /-- The forgetful functor to Type* -/ def forget : Compactum ⥤ Type u_1 := category_theory.monad.forget (category_theory.of_type_functor ultrafilter) /-- The "free" Compactum functor. -/ def free : Type u_1 ⥤ Compactum := category_theory.monad.free (category_theory.of_type_functor ultrafilter) /-- The adjunction between `free` and `forget`. -/ def adj : free ⊣ forget := category_theory.monad.adj (category_theory.of_type_functor ultrafilter) -- Basic instances protected instance category_theory.concrete_category : category_theory.concrete_category Compactum := category_theory.concrete_category.mk forget protected instance has_coe_to_sort : has_coe_to_sort Compactum := has_coe_to_sort.mk (Type u_1) (category_theory.functor.obj forget) protected instance category_theory.has_hom.hom.has_coe_to_fun {X : Compactum} {Y : Compactum} : has_coe_to_fun (X ⟶ Y) := has_coe_to_fun.mk (fun (f : X ⟶ Y) => ↥X → ↥Y) fun (f : X ⟶ Y) => category_theory.monad.algebra.hom.f f protected instance category_theory.limits.has_limits : category_theory.limits.has_limits Compactum := category_theory.has_limits_of_has_limits_creates_limits forget /-- The structure map for a compactum, essentially sending an ultrafilter to its limit. -/ def str (X : Compactum) : ultrafilter ↥X → ↥X := category_theory.monad.algebra.a X /-- The monadic join. -/ def join (X : Compactum) : ultrafilter (ultrafilter ↥X) → ultrafilter ↥X := category_theory.nat_trans.app μ_ ↥X /-- The inclusion of `X` into `ultrafilter X`. -/ def incl (X : Compactum) : ↥X → ultrafilter ↥X := category_theory.nat_trans.app η_ (category_theory.functor.obj forget X) @[simp] theorem str_incl (X : Compactum) (x : ↥X) : str X (incl X x) = x := sorry @[simp] theorem str_hom_commute (X : Compactum) (Y : Compactum) (f : X ⟶ Y) (xs : ultrafilter ↥X) : coe_fn f (str X xs) = str Y (ultrafilter.map (⇑f) xs) := sorry @[simp] theorem join_distrib (X : Compactum) (uux : ultrafilter (ultrafilter ↥X)) : str X (join X uux) = str X (ultrafilter.map (str X) uux) := sorry protected instance topological_space {X : Compactum} : topological_space ↥X := topological_space.mk (fun (U : set ↥X) => ∀ (F : ultrafilter ↥X), str X F ∈ U → U ∈ F) sorry sorry sorry theorem is_closed_iff {X : Compactum} (S : set ↥X) : is_closed S ↔ ∀ (F : ultrafilter ↥X), S ∈ F → str X F ∈ S := sorry protected instance compact_space {X : Compactum} : compact_space ↥X := compact_space.mk (eq.mpr (id (Eq._oldrec (Eq.refl (is_compact set.univ)) (propext compact_iff_ultrafilter_le_nhds))) fun (F : ultrafilter ↥X) (h : ↑F ≤ filter.principal set.univ) => Exists.intro (str X F) (Exists.intro trivial (eq.mpr (id (Eq._oldrec (Eq.refl (↑F ≤ nhds (str X F))) (propext le_nhds_iff))) fun (S : set ↥X) (h1 : str X F ∈ S) (h2 : is_open S) => h2 F h1))) /-- A local definition used only in the proofs. -/ /-- A local definition used only in the proofs. -/ theorem is_closed_cl {X : Compactum} (A : set ↥X) : is_closed (cl A) := eq.mpr (id (Eq._oldrec (Eq.refl (is_closed (cl A))) (propext (is_closed_iff (cl A))))) fun (F : ultrafilter ↥X) (hF : cl A ∈ F) => cl_cl A (Exists.intro F { left := hF, right := rfl }) theorem str_eq_of_le_nhds {X : Compactum} (F : ultrafilter ↥X) (x : ↥X) : ↑F ≤ nhds x → str X F = x := sorry theorem le_nhds_of_str_eq {X : Compactum} (F : ultrafilter ↥X) (x : ↥X) : str X F = x → ↑F ≤ nhds x := fun (h : str X F = x) => iff.mpr le_nhds_iff fun (s : set ↥X) (hx : x ∈ s) (hs : is_open s) => hs F (eq.mpr (id (Eq._oldrec (Eq.refl (str X F ∈ s)) h)) hx) -- All the hard work above boils down to this t2_space instance. protected instance t2_space {X : Compactum} : t2_space ↥X := eq.mpr (id (Eq._oldrec (Eq.refl (t2_space ↥X)) (propext t2_iff_ultrafilter))) fun (x y : ↥X) (F : ultrafilter ↥X) (hx : ↑F ≤ nhds x) (hy : ↑F ≤ nhds y) => eq.mpr (id (Eq._oldrec (Eq.refl (x = y)) (Eq.symm (str_eq_of_le_nhds F x hx)))) (eq.mpr (id (Eq._oldrec (Eq.refl (str X F = y)) (Eq.symm (str_eq_of_le_nhds F y hy)))) (Eq.refl (str X F))) /-- The structure map of a compactum actually computes limits. -/ theorem Lim_eq_str {X : Compactum} (F : ultrafilter ↥X) : ultrafilter.Lim F = str X F := eq.mpr (id (Eq._oldrec (Eq.refl (ultrafilter.Lim F = str X F)) (propext ultrafilter.Lim_eq_iff_le_nhds))) (eq.mpr (id (Eq._oldrec (Eq.refl (↑F ≤ nhds (str X F))) (propext le_nhds_iff))) fun (s : set ↥X) (ᾰ : str X F ∈ s) (ᾰ_1 : is_open s) => ᾰ_1 F ᾰ) theorem cl_eq_closure {X : Compactum} (A : set ↥X) : cl A = closure A := sorry /-- Any morphism of compacta is continuous. -/ theorem continuous_of_hom {X : Compactum} {Y : Compactum} (f : X ⟶ Y) : continuous ⇑f := sorry /-- Given any compact Hausdorff space, we construct a Compactum. -/ def of_topological_space (X : Type u_1) [topological_space X] [compact_space X] [t2_space X] : Compactum := category_theory.monad.algebra.mk X ultrafilter.Lim /-- Any continuous map between Compacta is a morphism of compacta. -/ def hom_of_continuous {X : Compactum} {Y : Compactum} (f : ↥X → ↥Y) (cont : continuous f) : X ⟶ Y := category_theory.monad.algebra.hom.mk f end Compactum /-- The functor functor from Compactum to CompHaus. -/ def Compactum_to_CompHaus : Compactum ⥤ CompHaus := category_theory.functor.mk (fun (X : Compactum) => CompHaus.mk (category_theory.bundled.mk ↥X)) fun (X Y : Compactum) (f : X ⟶ Y) => continuous_map.mk ⇑f namespace Compactum_to_CompHaus /-- The functor Compactum_to_CompHaus is full. -/ def full : category_theory.full Compactum_to_CompHaus := category_theory.full.mk fun (X Y : Compactum) (f : category_theory.functor.obj Compactum_to_CompHaus X ⟶ category_theory.functor.obj Compactum_to_CompHaus Y) => Compactum.hom_of_continuous (continuous_map.to_fun f) sorry /-- The functor Compactum_to_CompHaus is faithful. -/ theorem faithful : category_theory.faithful Compactum_to_CompHaus := category_theory.faithful.mk /-- This definition is used to prove essential surjectivity of Compactum_to_CompHaus. -/ def iso_of_topological_space {D : CompHaus} : category_theory.functor.obj Compactum_to_CompHaus (Compactum.of_topological_space ↥D) ≅ D := category_theory.iso.mk (continuous_map.mk id) (continuous_map.mk id) /-- The functor Compactum_to_CompHaus is essentially surjective. -/ theorem ess_surj : category_theory.ess_surj Compactum_to_CompHaus := category_theory.ess_surj.mk fun (X : CompHaus) => Exists.intro (Compactum.of_topological_space ↥X) (Nonempty.intro iso_of_topological_space) /-- The functor Compactum_to_CompHaus is an equivalence of categories. -/ def is_equivalence : category_theory.is_equivalence Compactum_to_CompHaus := category_theory.equivalence.equivalence_of_fully_faithfully_ess_surj Compactum_to_CompHaus
1e2192735c5c98132f7b67bcad9f0c03053a92e6
7b02c598aa57070b4cf4fbfe2416d0479220187f
/algebra/short_five.hlean
af701b99a8fc103b6f98db20e4e73ac0374c5ec4
[ "Apache-2.0" ]
permissive
jdchristensen/Spectral
50d4f0ddaea1484d215ef74be951da6549de221d
6ded2b94d7ae07c4098d96a68f80a9cd3d433eb8
refs/heads/master
1,611,555,010,649
1,496,724,191,000
1,496,724,191,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,338
hlean
/- Author: Jeremy Avigad -/ import .module_chain_complex open eq pointed sigma fiber equiv is_equiv sigma.ops is_trunc nat trunc open algebra function succ_str open left_module section short_five variable {R : Ring} variables {A₀ B₀ C₀ A₁ B₁ C₁ : LeftModule R} variables {f₀ : A₀ →lm B₀} {g₀ : B₀ →lm C₀} variables {f₁ : A₁ →lm B₁} {g₁ : B₁ →lm C₁} variables {h : A₀ →lm A₁} {k : B₀ →lm B₁} {l : C₀ →lm C₁} premise (short_exact₀ : is_short_exact f₀ g₀) premise (short_exact₁ : is_short_exact f₁ g₁) premise (hsquare₁ : hsquare f₀ f₁ h k) premise (hsquare₂ : hsquare g₀ g₁ k l) include short_exact₀ short_exact₁ hsquare₁ hsquare₂ open algebra.is_short_exact lemma short_five_mono [embh : is_embedding h] [embl : is_embedding l] : is_embedding k := have is_embedding f₁, from is_emb short_exact₁, is_embedding_of_is_add_hom k (take b, suppose k b = 0, have l (g₀ b) = 0, by rewrite [hsquare₂, ▸*, this, respect_zero], have g₀ b = 0, from eq_zero_of_eq_zero_of_is_embedding this, image.elim (ker_in_im short_exact₀ _ this) (take a, suppose f₀ a = b, have f₁ (h a) = 0, by rewrite [-hsquare₁, ▸*, this]; assumption, have h a = 0, from eq_zero_of_eq_zero_of_is_embedding this, have a = 0, from eq_zero_of_eq_zero_of_is_embedding this, show b = 0, by rewrite [-`f₀ a = b`, this, respect_zero])) lemma short_five_epi (surjh : is_surjective h) (surjl : is_surjective l) : is_surjective k := have surjg₀ : is_surjective g₀, from is_surj short_exact₀, take b₁ : B₁, image.elim (surjl (g₁ b₁)) ( take c₀ : C₀, assume lc₀ : l c₀ = g₁ b₁, image.elim (surjg₀ c₀) ( take b₀ : B₀, assume g₀b₀ : g₀ b₀ = c₀, have g₁ (k b₀ - b₁) = 0, by rewrite [respect_sub, -hsquare₂, ▸*, g₀b₀, lc₀, sub_self], image.elim (ker_in_im short_exact₁ _ this) ( take a₁ : A₁, assume f₁a₁ : f₁ a₁ = k b₀ - b₁, image.elim (surjh a₁) ( take a₀ : A₀, assume ha₀ : h a₀ = a₁, have k (f₀ a₀) = k b₀ - b₁, by rewrite [hsquare₁, ▸*, ha₀, f₁a₁], have k (b₀ - f₀ a₀) = b₁, by rewrite [respect_sub, this, sub_sub_self], image.mk _ this)))) end short_five section short_exact open module_chain_complex variables {R : Ring} {N : succ_str} record is_short_exact_at (C : module_chain_complex R N) (n : N) := (is_contr_0 : is_contr (C n)) (is_exact_at_1 : is_exact_at_m C n) (is_exact_at_2 : is_exact_at_m C (S n)) (is_exact_at_3 : is_exact_at_m C (S (S n))) (is_contr_4 : is_contr (C (S (S (S (S n)))))) /- TODO: show that this gives rise to a short exact sequence in the sense above -/ end short_exact section short_five_redux open module_chain_complex variables {R : Ring} {N : succ_str} /- TODO: restate short five in these terms -/ end short_five_redux /- TODO: state and prove strong_four, adapting the template below. section strong_four variables {R : Type} [ring R] variables {A B C D A' B' C' D' : Type} variables [left_module R A] [left_module R B] [left_module R C] [left_module R D] variables [left_module R A'] [left_module R B'] [left_module R C'] [left_module R D'] variables (ρ : A → B) [is_module_hom R ρ] variables (σ : B → C) [is_module_hom R σ] variables (τ : C → D) [is_module_hom R τ] variable (chainρσ : ∀ a, σ (ρ a) = 0) variable (exactρσ : ∀ {b}, σ b = 0 → ∃ a, ρ a = b) variable (chainστ : ∀ b, τ (σ b) = 0) variable (exactστ : ∀ {c}, τ c = 0 → ∃ b, σ b = c) variables (ρ' : A' → B') [is_module_hom R ρ'] variables (σ' : B' → C') [is_module_hom R σ'] variables (τ' : C' → D') [is_module_hom R τ'] variable (chainρ'σ' : ∀ a', σ' (ρ' a') = 0) variable (exactρ'σ' : ∀ {b'}, σ' b' = 0 → ∃ a', ρ' a' = b') variable (chainσ'τ' : ∀ b', τ' (σ' b') = 0) variable (exactσ'τ' : ∀ {c'}, τ' c' = 0 → ∃ b', σ' b' = c') variables (α : A → A') [is_module_hom R α] variables (β : B → B') [is_module_hom R β] variables (γ : C → C') [is_module_hom R γ] variables (δ : D → D') [is_module_hom R δ] variables (sq₁ : comm_square ρ ρ' α β) variables (sq₂ : comm_square σ σ' β γ) variables (sq₃ : comm_square τ τ' γ δ) include sq₃ σ' sq₂ exactρ'σ' sq₁ chainρσ theorem strong_four_a (epiα : is_surjective α) (monoδ : is_embedding δ) (c : C) (γc0 : γ c = 0) : Σ b, (β b = 0 × σ b = c) := have δ (τ c) = 0, by rewrite [sq₃, γc0, hom_zero], have τ c = 0, from eq_zero_of_eq_zero_of_is_embedding this, obtain b (σbc : σ b = c), from exactστ this, have σ' (β b) = 0, by rewrite [-sq₂, σbc, γc0], obtain a' (ρ'a'βb : ρ' a' = β b), from exactρ'σ' this, obtain a (αaa' : α a = a'), from epiα a', exists.intro (b - ρ a) (pair (show β (b - ρ a) = 0, by rewrite [hom_sub, -ρ'a'βb, sq₁, αaa', sub_self]) (show σ (b - ρ a) = c, from calc σ (b - ρ a) = σ b - σ (ρ a) : hom_sub _ ... = σ b : by rewrite [chainρσ, sub_zero] ... = c : σbc)) end strong_four -/
9452277b3dc6674654c69fbbb2ec7f7ce7951868
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/data/list/chain.lean
6c32f98a89be090874abb086e4ac13fa29a348a4
[ "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
13,042
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Kenny Lau, Yury Kudryashov -/ import data.list.pairwise import logic.relation /-! # Relation chain This file provides basic results about `list.chain` (definition in `data.list.defs`). A list `[a₂, ..., aₙ]` is a `chain` starting at `a₁` with respect to the relation `r` if `r a₁ a₂` and `r a₂ a₃` and ... and `r aₙ₋₁ aₙ`. We write it `chain r a₁ [a₂, ..., aₙ]`. A graph-specialized version is in development and will hopefully be added under `combinatorics.` sometime soon. -/ universes u v open nat namespace list variables {α : Type u} {β : Type v} {R : α → α → Prop} mk_iff_of_inductive_prop list.chain list.chain_iff theorem rel_of_chain_cons {a b : α} {l : list α} (p : chain R a (b :: l)) : R a b := (chain_cons.1 p).1 theorem chain_of_chain_cons {a b : α} {l : list α} (p : chain R a (b :: l)) : chain R b l := (chain_cons.1 p).2 theorem chain.imp' {S : α → α → Prop} (HRS : ∀ ⦃a b⦄, R a b → S a b) {a b : α} (Hab : ∀ ⦃c⦄, R a c → S b c) {l : list α} (p : chain R a l) : chain S b l := by induction p with _ a c l r p IH generalizing b; constructor; [exact Hab r, exact IH (@HRS _)] theorem chain.imp {S : α → α → Prop} (H : ∀ a b, R a b → S a b) {a : α} {l : list α} (p : chain R a l) : chain S a l := p.imp' H (H a) theorem chain.iff {S : α → α → Prop} (H : ∀ a b, R a b ↔ S a b) {a : α} {l : list α} : chain R a l ↔ chain S a l := ⟨chain.imp (λ a b, (H a b).1), chain.imp (λ a b, (H a b).2)⟩ theorem chain.iff_mem {a : α} {l : list α} : chain R a l ↔ chain (λ x y, x ∈ a :: l ∧ y ∈ l ∧ R x y) a l := ⟨λ p, by induction p with _ a b l r p IH; constructor; [exact ⟨mem_cons_self _ _, mem_cons_self _ _, r⟩, exact IH.imp (λ a b ⟨am, bm, h⟩, ⟨mem_cons_of_mem _ am, mem_cons_of_mem _ bm, h⟩)], chain.imp (λ a b h, h.2.2)⟩ theorem chain_singleton {a b : α} : chain R a [b] ↔ R a b := by simp only [chain_cons, chain.nil, and_true] theorem chain_split {a b : α} {l₁ l₂ : list α} : chain R a (l₁ ++ b :: l₂) ↔ chain R a (l₁ ++ [b]) ∧ chain R b l₂ := by induction l₁ with x l₁ IH generalizing a; simp only [*, nil_append, cons_append, chain.nil, chain_cons, and_true, and_assoc] theorem chain_map (f : β → α) {b : β} {l : list β} : chain R (f b) (map f l) ↔ chain (λ a b : β, R (f a) (f b)) b l := by induction l generalizing b; simp only [map, chain.nil, chain_cons, *] theorem chain_of_chain_map {S : β → β → Prop} (f : α → β) (H : ∀ a b : α, S (f a) (f b) → R a b) {a : α} {l : list α} (p : chain S (f a) (map f l)) : chain R a l := ((chain_map f).1 p).imp H theorem chain_map_of_chain {S : β → β → Prop} (f : α → β) (H : ∀ a b : α, R a b → S (f a) (f b)) {a : α} {l : list α} (p : chain R a l) : chain S (f a) (map f l) := (chain_map f).2 $ p.imp H theorem chain_pmap_of_chain {S : β → β → Prop} {p : α → Prop} {f : Π a, p a → β} (H : ∀ a b ha hb, R a b → S (f a ha) (f b hb)) {a : α} {l : list α} (hl₁ : chain R a l) (ha : p a) (hl₂ : ∀ a ∈ l, p a) : chain S (f a ha) (list.pmap f l hl₂) := begin induction l with lh lt l_ih generalizing a, { simp }, { simp [H _ _ _ _ (rel_of_chain_cons hl₁), l_ih _ (chain_of_chain_cons hl₁)] } end theorem chain_of_chain_pmap {S : β → β → Prop} {p : α → Prop} (f : Π a, p a → β) {l : list α} (hl₁ : ∀ a ∈ l, p a) {a : α} (ha : p a) (hl₂ : chain S (f a ha) (list.pmap f l hl₁)) (H : ∀ a b ha hb, S (f a ha) (f b hb) → R a b) : chain R a l := begin induction l with lh lt l_ih generalizing a, { simp }, { simp [H _ _ _ _ (rel_of_chain_cons hl₂), l_ih _ _ (chain_of_chain_cons hl₂)] } end theorem chain_of_pairwise {a : α} {l : list α} (p : pairwise R (a :: l)) : chain R a l := begin cases pairwise_cons.1 p with r p', clear p, induction p' with b l r' p IH generalizing a, {exact chain.nil}, simp only [chain_cons, forall_mem_cons] at r, exact chain_cons.2 ⟨r.1, IH r'⟩ end theorem chain_iff_pairwise (tr : transitive R) {a : α} {l : list α} : chain R a l ↔ pairwise R (a :: l) := ⟨λ c, begin induction c with b b c l r p IH, {exact pairwise_singleton _ _}, apply IH.cons _, simp only [mem_cons_iff, forall_eq_or_imp, r, true_and], show ∀ x ∈ l, R b x, from λ x m, (tr r (rel_of_pairwise_cons IH m)), end, chain_of_pairwise⟩ theorem chain_iff_nth_le {R} : ∀ {a : α} {l : list α}, chain R a l ↔ (∀ h : 0 < length l, R a (nth_le l 0 h)) ∧ (∀ i (h : i < length l - 1), R (nth_le l i (lt_of_lt_pred h)) (nth_le l (i+1) (lt_pred_iff.mp h))) | a [] := by simp | a (b :: t) := begin rw [chain_cons, chain_iff_nth_le], split, { rintro ⟨R, ⟨h0, h⟩⟩, split, { intro w, exact R }, intros i w, cases i, { apply h0 }, convert h i _ using 1, simp only [succ_eq_add_one, add_succ_sub_one, add_zero, length, add_lt_add_iff_right] at w, exact lt_pred_iff.mpr w, }, rintro ⟨h0, h⟩, split, { apply h0, simp, }, split, { apply h 0, }, intros i w, convert h (i+1) _ using 1, exact lt_pred_iff.mp w, end theorem chain'.imp {S : α → α → Prop} (H : ∀ a b, R a b → S a b) {l : list α} (p : chain' R l) : chain' S l := by cases l; [trivial, exact p.imp H] theorem chain'.iff {S : α → α → Prop} (H : ∀ a b, R a b ↔ S a b) {l : list α} : chain' R l ↔ chain' S l := ⟨chain'.imp (λ a b, (H a b).1), chain'.imp (λ a b, (H a b).2)⟩ theorem chain'.iff_mem : ∀ {l : list α}, chain' R l ↔ chain' (λ x y, x ∈ l ∧ y ∈ l ∧ R x y) l | [] := iff.rfl | (x :: l) := ⟨λ h, (chain.iff_mem.1 h).imp $ λ a b ⟨h₁, h₂, h₃⟩, ⟨h₁, or.inr h₂, h₃⟩, chain'.imp $ λ a b h, h.2.2⟩ @[simp] theorem chain'_nil : chain' R [] := trivial @[simp] theorem chain'_singleton (a : α) : chain' R [a] := chain.nil theorem chain'_split {a : α} : ∀ {l₁ l₂ : list α}, chain' R (l₁ ++ a :: l₂) ↔ chain' R (l₁ ++ [a]) ∧ chain' R (a :: l₂) | [] l₂ := (and_iff_right (chain'_singleton a)).symm | (b :: l₁) l₂ := chain_split theorem chain'_map (f : β → α) {l : list β} : chain' R (map f l) ↔ chain' (λ a b : β, R (f a) (f b)) l := by cases l; [refl, exact chain_map _] theorem chain'_of_chain'_map {S : β → β → Prop} (f : α → β) (H : ∀ a b : α, S (f a) (f b) → R a b) {l : list α} (p : chain' S (map f l)) : chain' R l := ((chain'_map f).1 p).imp H theorem chain'_map_of_chain' {S : β → β → Prop} (f : α → β) (H : ∀ a b : α, R a b → S (f a) (f b)) {l : list α} (p : chain' R l) : chain' S (map f l) := (chain'_map f).2 $ p.imp H theorem pairwise.chain' : ∀ {l : list α}, pairwise R l → chain' R l | [] _ := trivial | (a :: l) h := chain_of_pairwise h theorem chain'_iff_pairwise (tr : transitive R) : ∀ {l : list α}, chain' R l ↔ pairwise R l | [] := (iff_true_intro pairwise.nil).symm | (a :: l) := chain_iff_pairwise tr @[simp] theorem chain'_cons {x y l} : chain' R (x :: y :: l) ↔ R x y ∧ chain' R (y :: l) := chain_cons theorem chain'.cons {x y l} (h₁ : R x y) (h₂ : chain' R (y :: l)) : chain' R (x :: y :: l) := chain'_cons.2 ⟨h₁, h₂⟩ theorem chain'.tail : ∀ {l} (h : chain' R l), chain' R l.tail | [] _ := trivial | [x] _ := trivial | (x :: y :: l) h := (chain'_cons.mp h).right theorem chain'.rel_head {x y l} (h : chain' R (x :: y :: l)) : R x y := rel_of_chain_cons h theorem chain'.rel_head' {x l} (h : chain' R (x :: l)) ⦃y⦄ (hy : y ∈ head' l) : R x y := by { rw ← cons_head'_tail hy at h, exact h.rel_head } theorem chain'.cons' {x} : ∀ {l : list α}, chain' R l → (∀ y ∈ l.head', R x y) → chain' R (x :: l) | [] _ _ := chain'_singleton x | (a :: l) hl H := hl.cons $ H _ rfl theorem chain'_cons' {x l} : chain' R (x :: l) ↔ (∀ y ∈ head' l, R x y) ∧ chain' R l := ⟨λ h, ⟨h.rel_head', h.tail⟩, λ ⟨h₁, h₂⟩, h₂.cons' h₁⟩ theorem chain'.append : ∀ {l₁ l₂ : list α} (h₁ : chain' R l₁) (h₂ : chain' R l₂) (h : ∀ (x ∈ l₁.last') (y ∈ l₂.head'), R x y), chain' R (l₁ ++ l₂) | [] l₂ h₁ h₂ h := h₂ | [a] l₂ h₁ h₂ h := h₂.cons' $ h _ rfl | (a :: b :: l) l₂ h₁ h₂ h := begin simp only [last'] at h, have : chain' R (b :: l) := h₁.tail, exact (this.append h₂ h).cons h₁.rel_head end theorem chain'_pair {x y} : chain' R [x, y] ↔ R x y := by simp only [chain'_singleton, chain'_cons, and_true] theorem chain'.imp_head {x y} (h : ∀ {z}, R x z → R y z) {l} (hl : chain' R (x :: l)) : chain' R (y :: l) := hl.tail.cons' $ λ z hz, h $ hl.rel_head' hz theorem chain'_reverse : ∀ {l}, chain' R (reverse l) ↔ chain' (flip R) l | [] := iff.rfl | [a] := by simp only [chain'_singleton, reverse_singleton] | (a :: b :: l) := by rw [chain'_cons, reverse_cons, reverse_cons, append_assoc, cons_append, nil_append, chain'_split, ← reverse_cons, @chain'_reverse (b :: l), and_comm, chain'_pair, flip] theorem chain'_iff_nth_le {R} : ∀ {l : list α}, chain' R l ↔ ∀ i (h : i < length l - 1), R (nth_le l i (lt_of_lt_pred h)) (nth_le l (i+1) (lt_pred_iff.mp h)) | [] := by simp | [a] := by simp | (a :: b :: t) := begin rw [chain'_cons, chain'_iff_nth_le], split, { rintro ⟨R, h⟩ i w, cases i, { exact R, }, { convert h i _ using 1, simp only [succ_eq_add_one, add_succ_sub_one, add_zero, length, add_lt_add_iff_right] at w, simpa using w, }, }, { rintro h, split, { apply h 0, simp, }, { intros i w, convert h (i+1) _ using 1, simp only [add_zero, length, add_succ_sub_one] at w, simpa using w, } }, end /-- If `l₁ l₂` and `l₃` are lists and `l₁ ++ l₂` and `l₂ ++ l₃` both satisfy `chain' R`, then so does `l₁ ++ l₂ ++ l₃` provided `l₂ ≠ []` -/ lemma chain'.append_overlap : ∀ {l₁ l₂ l₃ : list α} (h₁ : chain' R (l₁ ++ l₂)) (h₂ : chain' R (l₂ ++ l₃)) (hn : l₂ ≠ []), chain' R (l₁ ++ l₂ ++ l₃) | [] l₂ l₃ h₁ h₂ hn := h₂ | l₁ [] l₃ h₁ h₂ hn := (hn rfl).elim | [a] (b :: l₂) l₃ h₁ h₂ hn := by { simp at *, tauto } | (a :: b :: l₁) (c :: l₂) l₃ h₁ h₂ hn := begin simp only [cons_append, chain'_cons] at h₁ h₂ ⊢, simp only [← cons_append] at h₁ h₂ ⊢, exact ⟨h₁.1, chain'.append_overlap h₁.2 h₂ (cons_ne_nil _ _)⟩ end variables {r : α → α → Prop} {a b : α} /-- If `a` and `b` are related by the reflexive transitive closure of `r`, then there is a `r`-chain starting from `a` and ending on `b`. The converse of `relation_refl_trans_gen_of_exists_chain`. -/ lemma exists_chain_of_relation_refl_trans_gen (h : relation.refl_trans_gen r a b) : ∃ l, chain r a l ∧ last (a :: l) (cons_ne_nil _ _) = b := begin apply relation.refl_trans_gen.head_induction_on h, { exact ⟨[], chain.nil, rfl⟩ }, { intros c d e t ih, obtain ⟨l, hl₁, hl₂⟩ := ih, refine ⟨d :: l, chain.cons e hl₁, _⟩, rwa last_cons_cons } end /-- Given a chain from `a` to `b`, and a predicate true at `b`, if `r x y → p y → p x` then the predicate is true everywhere in the chain and at `a`. That is, we can propagate the predicate up the chain. -/ lemma chain.induction (p : α → Prop) (l : list α) (h : chain r a l) (hb : last (a :: l) (cons_ne_nil _ _) = b) (carries : ∀ ⦃x y : α⦄, r x y → p y → p x) (final : p b) : ∀ i ∈ a :: l, p i := begin induction l generalizing a, { cases hb, simp [final] }, { rw chain_cons at h, rintro _ (rfl | _), apply carries h.1 (l_ih h.2 hb _ (or.inl rfl)), apply l_ih h.2 hb _ H } end /-- Given a chain from `a` to `b`, and a predicate true at `b`, if `r x y → p y → p x` then the predicate is true at `a`. That is, we can propagate the predicate all the way up the chain. -/ @[elab_as_eliminator] lemma chain.induction_head (p : α → Prop) (l : list α) (h : chain r a l) (hb : last (a :: l) (cons_ne_nil _ _) = b) (carries : ∀ ⦃x y : α⦄, r x y → p y → p x) (final : p b) : p a := (chain.induction p l h hb carries final) _ (mem_cons_self _ _) /-- If there is an `r`-chain starting from `a` and ending at `b`, then `a` and `b` are related by the reflexive transitive closure of `r`. The converse of `exists_chain_of_relation_refl_trans_gen`. -/ lemma relation_refl_trans_gen_of_exists_chain (l) (hl₁ : chain r a l) (hl₂ : last (a :: l) (cons_ne_nil _ _) = b) : relation.refl_trans_gen r a b := chain.induction_head _ l hl₁ hl₂ (λ x y, relation.refl_trans_gen.head) relation.refl_trans_gen.refl end list
c32c3ffa37efaaede798c69016e52942288a9159
82e44445c70db0f03e30d7be725775f122d72f3e
/src/category_theory/abelian/diagram_lemmas/four.lean
0bea6dcb0d2a43a6a66ca249e0b71ddb5b27a6b4
[ "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
7,600
lean
/- Copyright (c) 2020 Markus Himmel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Markus Himmel -/ import category_theory.abelian.pseudoelements /-! # The four and five lemmas Consider the following commutative diagram with exact rows in an abelian category: ``` A ---f--> B ---g--> C ---h--> D ---i--> E | | | | | α β γ δ ε | | | | | v v v v v A' --f'-> B' --g'-> C' --h'-> D' --i'-> E' ``` We show: - the "mono" version of the four lemma: if `α` is an epimorphism and `β` and `δ` are monomorphisms, then `γ` is a monomorphism, - the "epi" version of the four lemma: if `β` and `δ` are epimorphisms and `ε` is a monomorphism, then `γ` is an epimorphism, - the five lemma: if `α`, `β`, `δ` and `ε` are isomorphisms, then `γ` is an isomorphism. ## Implementation details To show the mono version, we use pseudoelements. For the epi version, we use a completely different arrow-theoretic proof. In theory, it should be sufficient to have one version and the other should follow automatically by duality. In practice, mathlib's knowledge about duality isn't quite at the point where this is doable easily. However, one key duality statement about exactness is needed in the proof of the epi version of the four lemma: we need to know that exactness of a pair `(f, g)`, which we defined via the map from the image of `f` to the kernel of `g`, is the same as "co-exactness", defined via the map from the cokernel of `f` to the coimage of `g` (more precisely, we only need the consequence that if `(f, g)` is exact, then the factorization of `g` through the cokernel of `f` is monomorphic). Luckily, in the case of abelian categories, we have the characterization that `(f, g)` is exact if and only if `f ≫ g = 0` and `kernel.ι g ≫ cokernel.π f = 0`, and the latter condition is self dual, so the equivalence of exactness and co-exactness follows easily. ## Tags four lemma, five lemma, diagram lemma, diagram chase -/ open category_theory (hiding comp_apply) open category_theory.abelian.pseudoelement open category_theory.limits universes v u variables {V : Type u} [category.{v} V] [abelian V] local attribute [instance] preadditive.has_equalizers_of_has_kernels local attribute [instance] object_to_sort hom_to_fun namespace category_theory.abelian variables {A B C D A' B' C' D' : V} variables {f : A ⟶ B} {g : B ⟶ C} {h : C ⟶ D} variables {f' : A' ⟶ B'} {g' : B' ⟶ C'} {h' : C' ⟶ D'} variables {α : A ⟶ A'} {β : B ⟶ B'} {γ : C ⟶ C'} {δ : D ⟶ D'} variables (comm₁ : α ≫ f' = f ≫ β) (comm₂ : β ≫ g' = g ≫ γ) (comm₃ : γ ≫ h' = h ≫ δ) include comm₁ comm₂ comm₃ section variables [exact f g] [exact g h] [exact f' g'] /-- The four lemma, mono version. For names of objects and morphisms, refer to the following diagram: ``` A ---f--> B ---g--> C ---h--> D | | | | α β γ δ | | | | v v v v A' --f'-> B' --g'-> C' --h'-> D' ``` -/ lemma mono_of_epi_of_mono_of_mono (hα : epi α) (hβ : mono β) (hδ : mono δ) : mono γ := mono_of_zero_of_map_zero _ $ λ c hc, have h c = 0, from suffices δ (h c) = 0, from zero_of_map_zero _ (pseudo_injective_of_mono _) _ this, calc δ (h c) = h' (γ c) : by rw [←comp_apply, ←comm₃, comp_apply] ... = h' 0 : by rw hc ... = 0 : apply_zero _, exists.elim (pseudo_exact_of_exact.2 _ this) $ λ b hb, have g' (β b) = 0, from calc g' (β b) = γ (g b) : by rw [←comp_apply, comm₂, comp_apply] ... = γ c : by rw hb ... = 0 : hc, exists.elim (pseudo_exact_of_exact.2 _ this) $ λ a' ha', exists.elim (pseudo_surjective_of_epi α a') $ λ a ha, have f a = b, from suffices β (f a) = β b, from pseudo_injective_of_mono _ this, calc β (f a) = f' (α a) : by rw [←comp_apply, ←comm₁, comp_apply] ... = f' a' : by rw ha ... = β b : ha', calc c = g b : hb.symm ... = g (f a) : by rw this ... = 0 : pseudo_exact_of_exact.1 _ end section variables [exact g h] [exact f' g'] [exact g' h'] /-- The four lemma, epi version. For names of objects and morphisms, refer to the following diagram: ``` A ---f--> B ---g--> C ---h--> D | | | | α β γ δ | | | | v v v v A' --f'-> B' --g'-> C' --h'-> D' ``` -/ lemma epi_of_epi_of_epi_of_mono (hα : epi α) (hγ : epi γ) (hδ : mono δ) : epi β := preadditive.epi_of_cancel_zero _ $ λ R r hβr, have hf'r : f' ≫ r = 0, from limits.zero_of_epi_comp α $ calc α ≫ f' ≫ r = f ≫ β ≫ r : by rw reassoc_of comm₁ ... = f ≫ 0 : by rw hβr ... = 0 : has_zero_morphisms.comp_zero _ _, let y : R ⟶ pushout r g' := pushout.inl, z : C' ⟶ pushout r g' := pushout.inr in have mono y, from mono_inl_of_factor_thru_epi_mono_factorization r g' (cokernel.π f') (cokernel.desc f' g' (by simp)) (by simp) (cokernel.desc f' r hf'r) (by simp) _ (colimit.is_colimit _), have hz : g ≫ γ ≫ z = 0, from calc g ≫ γ ≫ z = β ≫ g' ≫ z : by rw ←reassoc_of comm₂ ... = β ≫ r ≫ y : by rw ←pushout.condition ... = 0 ≫ y : by rw reassoc_of hβr ... = 0 : has_zero_morphisms.zero_comp _ _, let v : pushout r g' ⟶ pushout (γ ≫ z) (h ≫ δ) := pushout.inl, w : D' ⟶ pushout (γ ≫ z) (h ≫ δ) := pushout.inr in have mono v, from mono_inl_of_factor_thru_epi_mono_factorization _ _ (cokernel.π g) (cokernel.desc g h (by simp) ≫ δ) (by simp) (cokernel.desc _ _ hz) (by simp) _ (colimit.is_colimit _), have hzv : z ≫ v = h' ≫ w, from (cancel_epi γ).1 $ calc γ ≫ z ≫ v = h ≫ δ ≫ w : by rw [←category.assoc, pushout.condition, category.assoc] ... = γ ≫ h' ≫ w : by rw reassoc_of comm₃, suffices (r ≫ y) ≫ v = 0, by exactI zero_of_comp_mono _ (zero_of_comp_mono _ this), calc (r ≫ y) ≫ v = g' ≫ z ≫ v : by rw [pushout.condition, category.assoc] ... = g' ≫ h' ≫ w : by rw hzv ... = 0 ≫ w : exact.w_assoc _ ... = 0 : has_zero_morphisms.zero_comp _ _ end section five variables {E E' : V} {i : D ⟶ E} {i' : D' ⟶ E'} {ε : E ⟶ E'} (comm₄ : δ ≫ i' = i ≫ ε) variables [exact f g] [exact g h] [exact h i] [exact f' g'] [exact g' h'] [exact h' i'] variables [is_iso α] [is_iso β] [is_iso δ] [is_iso ε] include comm₄ /-- The five lemma. For names of objects and morphisms, refer to the following diagram: ``` A ---f--> B ---g--> C ---h--> D ---i--> E | | | | | α β γ δ ε | | | | | v v v v v A' --f'-> B' --g'-> C' --h'-> D' --i'-> E' ``` -/ lemma is_iso_of_is_iso_of_is_iso_of_is_iso_of_is_iso : is_iso γ := have mono γ, by apply mono_of_epi_of_mono_of_mono comm₁ comm₂ comm₃; apply_instance, have epi γ, by apply epi_of_epi_of_epi_of_mono comm₂ comm₃ comm₄; apply_instance, by exactI is_iso_of_mono_of_epi _ end five end category_theory.abelian
20e985d5e19784c23b994502be1502c57d6e7e11
756551a6bafe9c7552e87708361fadc519f7eeab
/lean/love02_backward_proofs_exercise_solution.lean
c360381f2b75c0c1fdbe70cb17eab8cb63dfb667
[]
no_license
lifeislikethisonly/logical_verification_2020
50fe9bae0a890d57989589ca84e5cc8bbe4e2d55
7a9f4bd73498189d9beb5d4591e0f2b3ca316111
refs/heads/master
1,674,981,358,396
1,607,086,735,000
1,607,086,735,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,665
lean
import .love02_backward_proofs_demo /- # LoVe Exercise 2: Backward Proofs -/ set_option pp.beta true set_option pp.generalized_field_notation false namespace LoVe namespace backward_proofs /- ## Question 1: Connectives and Quantifiers 1.1. Carry out the following proofs using basic tactics. Hint: Some strategies for carrying out such proofs are described at the end of Section 2.3 in the Hitchhiker's Guide. -/ lemma I (a : Prop) : a → a := begin intro ha, exact ha end lemma K (a b : Prop) : a → b → b := begin intros ha hb, exact hb end lemma C (a b c : Prop) : (a → b → c) → b → a → c := begin intros hg hb ha, apply hg, exact ha, exact hb end lemma proj_1st (a : Prop) : a → a → a := begin intros ha ha', exact ha end /- Please give a different answer than for `proj_1st`: -/ lemma proj_2nd (a : Prop) : a → a → a := begin intros ha ha', exact ha' end lemma some_nonsense (a b c : Prop) : (a → b → c) → a → (a → c) → b → c := begin intros hg ha hf hb, apply hg, exact ha, exact hb end /- 1.2. Prove the contraposition rule using basic tactics. -/ lemma contrapositive (a b : Prop) : (a → b) → ¬ b → ¬ a := begin intros hab hnb ha, apply hnb, apply hab, apply ha end /- 1.3. Prove the distributivity of `∀` over `∧` using basic tactics. Hint: This exercise is tricky, especially the right-to-left direction. Some forward reasoning, like in the proof of `and_swap₂` in the lecture, might be necessary. -/ lemma forall_and {α : Type} (p q : α → Prop) : (∀x, p x ∧ q x) ↔ (∀x, p x) ∧ (∀x, q x) := begin apply iff.intro, { intro h, apply and.intro, { intro x, apply and.elim_left, apply h }, { intro x, apply and.elim_right, apply h } }, { intros h x, apply and.intro, { apply and.elim_left h }, { apply and.elim_right h } } end /- ## Question 2: Natural Numbers 2.1. Prove the following recursive equations on the first argument of the `mul` operator defined in lecture 1. -/ #check mul lemma mul_zero (n : ℕ) : mul 0 n = 0 := begin induction' n, { refl }, { simp [add, mul, ih] } end lemma mul_succ (m n : ℕ) : mul (nat.succ m) n = add (mul m n) n := begin induction' n, { refl }, { simp [add, add_succ, add_assoc, mul, ih] } end /- 2.2. Prove commutativity and associativity of multiplication using the `induction'` tactic. Choose the induction variable carefully. -/ lemma mul_comm (m n : ℕ) : mul m n = mul n m := begin induction' m, { simp [mul, mul_zero] }, { simp [mul, mul_succ, ih], cc } end lemma mul_assoc (l m n : ℕ) : mul (mul l m) n = mul l (mul m n) := begin induction' n, { refl }, { simp [mul, mul_add, ih] } end /- 2.3. Prove the symmetric variant of `mul_add` using `rw`. To apply commutativity at a specific position, instantiate the rule by passing some arguments (e.g., `mul_comm _ l`). -/ lemma add_mul (l m n : ℕ) : mul (add l m) n = add (mul n l) (mul n m) := begin rw mul_comm _ n, rw mul_add end /- ## Question 3 (**optional**): Intuitionistic Logic Intuitionistic logic is extended to classical logic by assuming a classical axiom. There are several possibilities for the choice of axiom. In this question, we are concerned with the logical equivalence of three different axioms: -/ def excluded_middle := ∀a : Prop, a ∨ ¬ a def peirce := ∀a b : Prop, ((a → b) → a) → a def double_negation := ∀a : Prop, (¬¬ a) → a /- For the proofs below, please avoid using lemmas from Lean's `classical` namespace, because this would defeat the purpose of the exercise. 3.1 (**optional**). Prove the following implication using tactics. Hint: You will need `or.elim` and `false.elim`. You can use `rw excluded_middle` to unfold the definition of `excluded_middle`, and similarly for `peirce`. -/ lemma peirce_of_em : excluded_middle → peirce := begin rw excluded_middle, rw peirce, intro hem, intros a b haba, apply or.elim (hem a), { intro, assumption }, { intro hna, apply haba, intro ha, apply false.elim, apply hna, assumption } end /- 3.2 (**optional**). Prove the following implication using tactics. -/ lemma dn_of_peirce : peirce → double_negation := begin rw peirce, rw double_negation, intros hpeirce a hnna, apply hpeirce a false, intro hna, apply false.elim, apply hnna, exact hna end /- We leave the missing implication for the homework: -/ namespace sorry_lemmas lemma em_of_dn : double_negation → excluded_middle := sorry end sorry_lemmas end backward_proofs end LoVe
73c6f5baf5744a8e6564861554ea90e21028c0b5
8930e38ac0fae2e5e55c28d0577a8e44e2639a6d
/tactic/interactive.lean
eea2ea7ec9812db02df200cc7b1be662cdfeb42a
[ "Apache-2.0" ]
permissive
SG4316/mathlib
3d64035d02a97f8556ad9ff249a81a0a51a3321a
a7846022507b531a8ab53b8af8a91953fceafd3a
refs/heads/master
1,584,869,960,527
1,530,718,645,000
1,530,724,110,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
20,491
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.dlist data.dlist.basic data.prod category.basic tactic.basic tactic.rcases tactic.generalize_proofs tactic.split_ifs meta.expr open lean open lean.parser local postfix `?`:9001 := optional local postfix *:9001 := many namespace tactic namespace interactive open interactive interactive.types expr local notation `listΣ` := list_Sigma local notation `listΠ` := list_Pi /-- This parser uses the "inverted" meaning for the `many` constructor: rather than representing a sum of products, here it represents a product of sums. We fix this by applying `invert`, defined below, to the result. -/ @[reducible] def rcases_patt_inverted := rcases_patt meta def rcases_parse : parser (listΣ rcases_patt_inverted) := with_desc "patt" $ let p := (rcases_patt.one <$> ident_) <|> (rcases_patt.many <$> brackets "⟨" "⟩" (sep_by (tk ",") rcases_parse)) in list.cons <$> p <*> (tk "|" *> p)* meta def rcases_parse.invert : listΣ rcases_patt_inverted → listΣ (listΠ rcases_patt) := let invert' (l : listΣ rcases_patt_inverted) : rcases_patt := match l with | [rcases_patt.one n] := rcases_patt.one n | _ := rcases_patt.many (rcases_parse.invert l) end in list.map $ λ p, match p with | rcases_patt.one n := [rcases_patt.one n] | rcases_patt.many l := invert' <$> l end /-- The `rcases` tactic is the same as `cases`, but with more flexibility in the `with` pattern syntax to allow for recursive case splitting. The pattern syntax uses the following recursive grammar: ``` patt ::= (patt_list "|")* patt_list patt_list ::= id | "_" | "⟨" (patt ",")* patt "⟩" ``` A pattern like `⟨a, b, c⟩ | ⟨d, e⟩` will do a split over the inductive datatype, naming the first three parameters of the first constructor as `a,b,c` and the first two of the second constructor `d,e`. If the list is not as long as the number of arguments to the constructor or the number of constructors, the remaining variables will be automatically named. If there are nested brackets such as `⟨⟨a⟩, b | c⟩ | d` then these will cause more case splits as necessary. If there are too many arguments, such as `⟨a, b, c⟩` for splitting on `∃ x, ∃ y, p x`, then it will be treated as `⟨a, ⟨b, c⟩⟩`, splitting the last parameter as necessary. -/ meta def rcases (p : parse texpr) (ids : parse (tk "with" *> rcases_parse)?) : tactic unit := tactic.rcases p $ rcases_parse.invert $ ids.get_or_else [default _] /-- This is a "finishing" tactic modification of `simp`. The tactic `simpa [rules, ...] using e` will simplify the hypothesis `e` using `rules`, then simplify the goal using `rules`, and try to close the goal using `assumption`. If `e` is a term instead of a local constant, it is first added to the local context using `have`. -/ meta def simpa (use_iota_eqn : parse $ (tk "!")?) (no_dflt : parse only_flag) (hs : parse simp_arg_list) (attr_names : parse with_ident_list) (tgt : parse (tk "using" *> texpr)?) (cfg : simp_config_ext := {}) : tactic unit := let simp_at (lc) := simp use_iota_eqn no_dflt hs attr_names (loc.ns lc) cfg >> try (assumption <|> trivial) in match tgt with | none := get_local `this >> simp_at [some `this, none] <|> simp_at [none] | some e := (do e ← i_to_expr e, match e with | local_const _ lc _ _ := simp_at [some lc, none] | e := do t ← infer_type e, assertv `this t e >> simp_at [some `this, none] end) <|> (do simp_at [none], ty ← target, e ← i_to_expr_strict ``(%%e : %%ty), -- for positional error messages, don't care about the result pty ← pp ty, ptgt ← pp e, -- Fail deliberately, to advise regarding `simp; exact` usage fail ("simpa failed, 'using' expression type not directly " ++ "inferrable. Try:\n\nsimpa ... using\nshow " ++ to_fmt pty ++ ",\nfrom " ++ ptgt : format)) end /-- `try_for n { tac }` executes `tac` for `n` ticks, otherwise uses `sorry` to close the goal. Never fails. Useful for debugging. -/ meta def try_for (max : parse parser.pexpr) (tac : itactic) : tactic unit := do max ← i_to_expr_strict max >>= tactic.eval_expr nat, tactic.try_for max tac <|> (tactic.trace "try_for timeout, using sorry" >> admit) /-- Multiple subst. `substs x y z` is the same as `subst x, subst y, subst z`. -/ meta def substs (l : parse ident*) : tactic unit := l.mmap' (λ h, get_local h >>= tactic.subst) /-- Unfold coercion-related definitions -/ meta def unfold_coes (loc : parse location) : tactic unit := unfold [``coe,``lift_t,``has_lift_t.lift,``coe_t,``has_coe_t.coe,``coe_b,``has_coe.coe, ``coe_fn, ``has_coe_to_fun.coe, ``coe_sort, ``has_coe_to_sort.coe] loc /-- For debugging only. This tactic checks the current state for any missing dropped goals and restores them. Useful when there are no goals to solve but "result contains meta-variables". -/ meta def recover : tactic unit := do r ← tactic.result, tactic.set_goals $ r.fold [] $ λ e _ l, match e with | expr.mvar _ _ _ := insert e l | _ := l end /-- Like `try { tac }`, but in the case of failure it continues from the failure state instead of reverting to the original state. -/ meta def continue (tac : itactic) : tactic unit := λ s, result.cases_on (tac s) (λ a, result.success ()) (λ e ref, result.success ()) /-- Move goal `n` to the front. -/ meta def swap (n := 2) : tactic unit := if n = 2 then tactic.swap else tactic.rotate (n-1) /-- Generalize proofs in the goal, naming them with the provided list. -/ meta def generalize_proofs : parse ident_* → tactic unit := tactic.generalize_proofs /-- Clear all hypotheses starting with `_`, like `_match` and `_let_match`. -/ meta def clear_ : tactic unit := tactic.repeat $ do l ← local_context, l.reverse.mfirst $ λ h, do name.mk_string s p ← return $ local_pp_name h, guard (s.front = '_'), cl ← infer_type h >>= is_class, guard (¬ cl), tactic.clear h /-- Same as the `congr` tactic, but takes an optional argument which gives the depth of recursive applications. This is useful when `congr` is too aggressive in breaking down the goal. For example, given `⊢ f (g (x + y)) = f (g (y + x))`, `congr'` produces the goals `⊢ x = y` and `⊢ y = x`, while `congr' 2` produces the intended `⊢ x + y = y + x`. -/ meta def congr' : parse (with_desc "n" small_nat)? → tactic unit | (some 0) := failed | o := focus1 (assumption <|> (congr_core >> all_goals (reflexivity <|> try (congr' (nat.pred <$> o))))) /-- Acts like `have`, but removes a hypothesis with the same name as this one. For example if the state is `h : p ⊢ goal` and `f : p → q`, then after `replace h := f h` the goal will be `h : q ⊢ goal`, where `have h := f h` would result in the state `h : p, h : q ⊢ goal`. This can be used to simulate the `specialize` and `apply at` tactics of Coq. -/ meta def replace (h : parse ident?) (q₁ : parse (tk ":" *> texpr)?) (q₂ : parse $ (tk ":=" *> texpr)?) : tactic unit := do let h := h.get_or_else `this, old ← try_core (get_local h), «have» h q₁ q₂, match old, q₂ with | none, _ := skip | some o, some _ := tactic.clear o | some o, none := swap >> tactic.clear o >> swap end /-- Unfreeze local instances, which allows us to revert instances in the context. -/ meta def unfreezeI := tactic.unfreeze_local_instances /-- Reset the instance cache. This allows any new instances added to the context to be used in typeclass inference. -/ meta def resetI := reset_instance_cache /-- Like `intro`, but uses the introduced variable in typeclass inference. -/ meta def introI (p : parse ident_?) : tactic unit := intro p >> reset_instance_cache /-- Like `intros`, but uses the introduced variable(s) in typeclass inference. -/ meta def introsI (p : parse ident_*) : tactic unit := intros p >> reset_instance_cache /-- Used to add typeclasses to the context so that they can be used in typeclass inference. The syntax is the same as `have`, but the proof-omitted version is not supported. For this one must write `have : t, { <proof> }, resetI, <proof>`. -/ meta def haveI (h : parse ident?) (q₁ : parse (tk ":" *> texpr)?) (q₂ : parse (tk ":=" *> texpr)) : tactic unit := do h ← match h with | none := get_unused_name "_inst" | some a := return a end, «have» (some h) q₁ (some q₂), match q₁ with | none := swap >> reset_instance_cache >> swap | some p₂ := reset_instance_cache end /-- Used to add typeclasses to the context so that they can be used in typeclass inference. The syntax is the same as `let`. -/ meta def letI (h : parse ident?) (q₁ : parse (tk ":" *> texpr)?) (q₂ : parse $ (tk ":=" *> texpr)?) : tactic unit := do h ← match h with | none := get_unused_name "_inst" | some a := return a end, «let» (some h) q₁ q₂, match q₁ with | none := swap >> reset_instance_cache >> swap | some p₂ := reset_instance_cache end /-- Like `exact`, but uses all variables in the context for typeclass inference. -/ meta def exactI (q : parse texpr) : tactic unit := reset_instance_cache >> exact q meta def symm_apply (e : expr) (cfg : apply_cfg := {}) : tactic (list (name × expr)) := tactic.apply e cfg <|> (symmetry >> tactic.apply e cfg) /-- `apply_assumption` looks for an assumption of the form `... → ∀ _, ... → head` where `head` matches the current goal. alternatively, when encountering an assumption of the form `sg₀ → ¬ sg₁`, after the main approach failed, the goal is dismissed and `sg₀` and `sg₁` are made into the new goal. optional arguments: - asms: list of rules to consider instead of the local constants - tac: a tactic to run on each subgoals after applying an assumption; if this tactic fails, the corresponding assumption will be rejected and the next one will be attempted. -/ meta def apply_assumption (asms : option (list expr) := none) (tac : tactic unit := return ()) : tactic unit := do { ctx ← asms.to_monad <|> local_context, ctx.any_of (λ H, () <$ symm_apply H ; tac) } <|> do { exfalso, ctx ← asms.to_monad <|> local_context, ctx.any_of (λ H, () <$ symm_apply H ; tac) } <|> fail "assumption tactic failed" open nat meta def solve_by_elim_aux (discharger : tactic unit) (asms : option (list expr)) : ℕ → tactic unit | 0 := done | (succ n) := discharger <|> (apply_assumption asms $ solve_by_elim_aux n) meta structure by_elim_opt := (discharger : tactic unit := done) (restr_hyp_set : option (list expr) := none) (max_rep : ℕ := 3) /-- `solve_by_elim` calls `apply_assumption` on the main goal to find an assumption whose head matches and repeated calls `apply_assumption` on the generated subgoals until no subgoals remains or up to `depth` times. `solve_by_elim` discharges the current goal or fails `solve_by_elim` does some back-tracking if `apply_assumption` chooses an unproductive assumption optional arguments: - discharger: a subsidiary tactic to try at each step (`cc` is often helpful) - asms: list of assumptions / rules to consider instead of local constants - depth: number of attempts at discharging generated sub-goals -/ meta def solve_by_elim (opt : by_elim_opt := { }) : tactic unit := solve_by_elim_aux opt.discharger opt.restr_hyp_set opt.max_rep /-- `tautology` breaks down assumptions of the form `_ ∧ _`, `_ ∨ _`, `_ ↔ _` and `∃ _, _` and splits a goal of the form `_ ∧ _`, `_ ↔ _` or `∃ _, _` until it can be discharged using `reflexivity` or `solve_by_elim` -/ meta def tautology : tactic unit := repeat (do gs ← get_goals, () <$ tactic.intros; casesm (some ()) [``(_ ∧ _),``(_ ∨ _),``(Exists _),``(false)]; constructor_matching (some ()) [``(_ ∧ _),``(_ ↔ _),``(true)], gs' ← get_goals, guard (gs ≠ gs') ) ; repeat (reflexivity <|> solve_by_elim <|> constructor_matching none [``(_ ∧ _),``(_ ↔ _),``(Exists _)]) ; done /-- Shorter name for the tactic `tautology`. -/ meta def tauto := tautology /-- Tag lemmas of the form: ``` lemma my_collection.ext (a b : my_collection) (h : ∀ x, a.lookup x = b.lookup y) : a = b := ... ``` -/ @[user_attribute] meta def extensional_attribute : user_attribute := { name := `extensionality, descr := "lemmas usable by `ext` tactic" } attribute [extensionality] _root_.funext array.ext prod.ext /-- `ext1 id` selects and apply one extensionality lemma (with attribute `extensionality`), using `id`, if provided, to name a local constant introduced by the lemma. If `id` is omitted, the local constant is named automatically, as per `intro`. -/ meta def ext1 (x : parse ident_ ?) : tactic unit := do ls ← attribute.get_instances `extensionality, ls.any_of (λ l, applyc l) <|> fail "no applicable extensionality rule found", try ( interactive.intro x ) meta def ext_arg := prod.mk <$> (some <$> small_nat) <*> (tk "with" *> ident_* <|> pure []) <|> prod.mk none <$> (ident_*) /-- - `ext` applies as many extensionality lemmas as possible; - `ext ids`, with `ids` a list of identifiers, finds extentionality and applies them until it runs out of identifiers in `ids` to name the local constants. When trying to prove: ``` α β : Type, f g : α → set β ⊢ f = g ``` applying `ext x y` yields: ``` α β : Type, f g : α → set β, x : α, y : β ⊢ y ∈ f x ↔ y ∈ f x ``` by applying functional extensionality and set extensionality. A maximum depth can be provided with `ext 3 with x y z`. -/ meta def ext : parse ext_arg → tactic unit | (some n, []) := ext1 none >> iterate_at_most (pred n) (ext1 none) | (none, []) := ext1 none >> repeat (ext1 none) | (n, xs) := tactic.ext xs n private meta def generalize_arg_p_aux : pexpr → parser (pexpr × name) | (app (app (macro _ [const `eq _ ]) h) (local_const x _ _ _)) := pure (h, x) | _ := fail "parse error" private meta def generalize_arg_p : parser (pexpr × name) := with_desc "expr = id" $ parser.pexpr 0 >>= generalize_arg_p_aux lemma {u} generalize_a_aux {α : Sort u} (h : ∀ x : Sort u, (α → x) → x) : α := h α id /-- Like `generalize` but also considers assumptions specified by the user. The user can also specify to omit the goal. -/ meta def generalize_hyp (h : parse ident?) (_ : parse $ tk ":") (p : parse generalize_arg_p) (l : parse location) : tactic unit := do h' ← get_unused_name `h, x' ← get_unused_name `x, g ← if ¬ l.include_goal then do refine ``(generalize_a_aux _), some <$> (prod.mk <$> tactic.intro x' <*> tactic.intro h') else pure none, n ← l.get_locals >>= tactic.revert_lst, generalize h () p, intron n, match g with | some (x',h') := do tactic.apply h', tactic.clear h', tactic.clear x' | none := return () end /-- Similar to `refine` but generates equality proof obligations for every discrepancy between the goal and the type of the rule. -/ meta def convert (sym : parse (with_desc "←" (tk "<-")?)) (r : parse texpr) (n : parse (tk "using" *> small_nat)?) : tactic unit := do v ← mk_mvar, if sym.is_some then refine ``(eq.mp %%v %%r) else refine ``(eq.mpr %%v %%r), gs ← get_goals, set_goals [v], congr' n, gs' ← get_goals, set_goals $ gs' ++ gs meta def clean_ids : list name := [``id, ``id_rhs, ``id_delta] /-- Remove identity functions from a term. These are normally automatically generated with terms like `show t, from p` or `(p : t)` which translate to some variant on `@id t p` in order to retain the type. -/ meta def clean (q : parse texpr) : tactic unit := do tgt : expr ← target, e ← i_to_expr_strict ``(%%q : %%tgt), tactic.exact $ e.replace (λ e n, match e with | (app (app (const n _) _) e') := if n ∈ clean_ids then some e' else none | (app (lam _ _ _ (var 0)) e') := some e' | _ := none end) meta def source_fields (missing : list (name × name)) (e : pexpr) : tactic (list (name × pexpr)) := do e ← to_expr e, t ← infer_type e, let struct_n : name := t.get_app_fn.const_name, exp_fields ← (∩ missing) <$> expanded_field_list struct_n, exp_fields.mmap $ λ ⟨p,n⟩, (prod.mk n ∘ to_pexpr) <$> mk_mapp (n.update_prefix p) [none,some e] meta def collect_struct' : pexpr → state_t (list $ expr×structure_instance_info) tactic pexpr | e := do some str ← pure (e.get_structure_instance_info) | e.traverse collect_struct', v ← monad_lift mk_mvar, modify (list.cons (v,str)), pure $ to_pexpr v meta def collect_struct (e : pexpr) : tactic $ pexpr × list (expr×structure_instance_info) := prod.map id list.reverse <$> (collect_struct' e).run [] meta def refine_one (str : structure_instance_info) : tactic $ list (expr×structure_instance_info) := do tgt ← target, let struct_n : name := tgt.get_app_fn.const_name, exp_fields ← expanded_field_list struct_n, let missing_f := exp_fields.filter (λ f, (f.2 : name) ∉ str.field_names), (src_field_names,src_field_vals) ← (@list.unzip name _ ∘ list.join) <$> str.sources.mmap (source_fields missing_f), let provided := exp_fields.filter (λ f, (f.2 : name) ∈ str.field_names), let missing_f' := missing_f.filter (λ x, x.2 ∉ src_field_names), vs ← mk_mvar_list missing_f'.length, (field_values,new_goals) ← list.unzip <$> (str.field_values.mmap collect_struct : tactic _), e' ← to_expr $ pexpr.mk_structure_instance { struct := some struct_n , field_names := str.field_names ++ missing_f'.map prod.snd ++ src_field_names , field_values := field_values ++ vs.map to_pexpr ++ src_field_vals }, tactic.exact e', gs ← with_enable_tags ( mmap₂ (λ (n : name × name) v, do set_goals [v], try (interactive.unfold (provided.map $ λ ⟨s,f⟩, f.update_prefix s) (loc.ns [none])), apply_auto_param <|> apply_opt_param <|> (set_main_tag [`_field,n.2,n.1]), get_goals) missing_f' vs), set_goals gs.join, return new_goals.join meta def refine_recursively : expr × structure_instance_info → tactic (list expr) | (e,str) := do set_goals [e], rs ← refine_one str, gs ← get_goals, gs' ← rs.mmap refine_recursively, return $ gs'.join ++ gs /-- `refine_struct { .. }` acts like `refine` but works only with structure instance literals. It creates a goal for each missing field and tags it with the name of the field so that `have_field` can be used to generically refer to the field currently being refined. As an example, we can use `refine_struct` to automate the construction semigroup instances: ``` refine_struct ( { .. } : semigroup α ), -- case semigroup, mul -- α : Type u, -- ⊢ α → α → α -- case semigroup, mul_assoc -- α : Type u, -- ⊢ ∀ (a b c : α), a * b * c = a * (b * c) ``` -/ meta def refine_struct : parse texpr → tactic unit | e := do (x,xs) ← collect_struct e, refine x, gs ← get_goals, xs' ← xs.mmap refine_recursively, set_goals (xs'.join ++ gs) meta def guard_tags (tags : parse ident*) : tactic unit := do (t : list name) ← get_main_tag, guard (t = tags) meta def get_current_field : tactic name := do [_,field,str] ← get_main_tag, expr.const_name <$> resolve_name (field.update_prefix str) /-- `have_field`, used after `refine_struct _` poses `field` as a local constant with the type of the field of the current goal: ``` refine_struct ({ .. } : semigroup α), { have_field, ... }, { have_field, ... }, ``` behaves like ``` refine_struct ({ .. } : semigroup α), { have field := @semigroup.mul, ... }, { have field := @semigroup.mul_assoc, ... }, ``` -/ meta def have_field : tactic unit := propagate_tags $ get_current_field >>= mk_const >>= note `field none >> return () /-- `apply_field` functions as `have_field, apply field, clear field` -/ meta def apply_field : tactic unit := propagate_tags $ get_current_field >>= applyc end interactive end tactic
f3028550d8d94278a850a321679d8df9530865ac
30b012bb72d640ec30c8fdd4c45fdfa67beb012c
/analysis/bounded_linear_maps.lean
728f79890069a0c70e894eb486a373ef01a9344b
[ "Apache-2.0" ]
permissive
kckennylau/mathlib
21fb810b701b10d6606d9002a4004f7672262e83
47b3477e20ffb5a06588dd3abb01fe0fe3205646
refs/heads/master
1,634,976,409,281
1,542,042,832,000
1,542,319,733,000
109,560,458
0
0
Apache-2.0
1,542,369,208,000
1,509,867,494,000
Lean
UTF-8
Lean
false
false
5,864
lean
/- Copyright (c) 2018 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Johannes Hölzl Continuous linear functions -- functions between normed vector spaces which are bounded and linear. -/ import algebra.field import tactic.norm_num import analysis.normed_space @[simp] lemma mul_inv_eq' {α} [discrete_field α] (a b : α) : (a * b)⁻¹ = b⁻¹ * a⁻¹ := classical.by_cases (assume : a = 0, by simp [this]) $ assume ha, classical.by_cases (assume : b = 0, by simp [this]) $ assume hb, mul_inv_eq hb ha noncomputable theory local attribute [instance] classical.prop_decidable local notation f ` →_{`:50 a `} `:0 b := filter.tendsto f (nhds a) (nhds b) open filter (tendsto) variables {k : Type*} [normed_field k] variables {E : Type*} [normed_space k E] variables {F : Type*} [normed_space k F] variables {G : Type*} [normed_space k G] structure is_bounded_linear_map {k : Type*} [normed_field k] {E : Type*} [normed_space k E] {F : Type*} [normed_space k F] (L : E → F) extends is_linear_map L : Prop := (bound : ∃ M, M > 0 ∧ ∀ x : E, ∥ L x ∥ ≤ M * ∥ x ∥) include k lemma is_linear_map.with_bound {L : E → F} (hf : is_linear_map L) (M : ℝ) (h : ∀ x : E, ∥ L x ∥ ≤ M * ∥ x ∥) : is_bounded_linear_map L := ⟨ hf, classical.by_cases (assume : M ≤ 0, ⟨1, zero_lt_one, assume x, le_trans (h x) $ mul_le_mul_of_nonneg_right (le_trans this zero_le_one) (norm_nonneg x)⟩) (assume : ¬ M ≤ 0, ⟨M, lt_of_not_ge this, h⟩)⟩ namespace is_bounded_linear_map lemma zero : is_bounded_linear_map (λ (x:E), (0:F)) := (0 : E →ₗ F).is_linear.with_bound 0 $ by simp [le_refl] lemma id : is_bounded_linear_map (λ (x:E), x) := linear_map.id.is_linear.with_bound 1 $ by simp [le_refl] lemma smul {f : E → F} (c : k) : is_bounded_linear_map f → is_bounded_linear_map (λ e, c • f e) | ⟨hf, ⟨M, hM, h⟩⟩ := (c • hf.mk' f).is_linear.with_bound (∥c∥ * M) $ assume x, calc ∥c • f x∥ = ∥c∥ * ∥f x∥ : norm_smul c (f x) ... ≤ ∥c∥ * (M * ∥x∥) : mul_le_mul_of_nonneg_left (h x) (norm_nonneg c) ... = (∥c∥ * M) * ∥x∥ : (mul_assoc _ _ _).symm lemma neg {f : E → F} (hf : is_bounded_linear_map f) : is_bounded_linear_map (λ e, -f e) := begin rw show (λ e, -f e) = (λ e, (-1) • f e), { funext, simp }, exact smul (-1) hf end lemma add {f : E → F} {g : E → F} : is_bounded_linear_map f → is_bounded_linear_map g → is_bounded_linear_map (λ e, f e + g e) | ⟨hlf, Mf, hMf, hf⟩ ⟨hlg, Mg, hMg, hg⟩ := (hlf.mk' _ + hlg.mk' _).is_linear.with_bound (Mf + Mg) $ assume x, calc ∥f x + g x∥ ≤ ∥f x∥ + ∥g x∥ : norm_triangle _ _ ... ≤ Mf * ∥x∥ + Mg * ∥x∥ : add_le_add (hf x) (hg x) ... ≤ (Mf + Mg) * ∥x∥ : by rw add_mul lemma sub {f : E → F} {g : E → F} (hf : is_bounded_linear_map f) (hg : is_bounded_linear_map g) : is_bounded_linear_map (λ e, f e - g e) := add hf (neg hg) lemma comp {f : E → F} {g : F → G} : is_bounded_linear_map g → is_bounded_linear_map f → is_bounded_linear_map (g ∘ f) | ⟨hlg, Mg, hMg, hg⟩ ⟨hlf, Mf, hMf, hf⟩ := ((hlg.mk' _).comp (hlf.mk' _)).is_linear.with_bound (Mg * Mf) $ assume x, calc ∥g (f x)∥ ≤ Mg * ∥f x∥ : hg _ ... ≤ Mg * (Mf * ∥x∥) : mul_le_mul_of_nonneg_left (hf _) (le_of_lt hMg) ... = Mg * Mf * ∥x∥ : (mul_assoc _ _ _).symm lemma tendsto {L : E → F} (x : E) : is_bounded_linear_map L → L →_{x} (L x) | ⟨hL, M, hM, h_ineq⟩ := tendsto_iff_norm_tendsto_zero.2 $ squeeze_zero (assume e, norm_nonneg _) (assume e, calc ∥L e - L x∥ = ∥hL.mk' L (e - x)∥ : by rw (hL.mk' _).map_sub e x; refl ... ≤ M*∥e-x∥ : h_ineq (e-x)) (suffices (λ (e : E), M * ∥e - x∥) →_{x} (M * 0), by simpa, tendsto_mul tendsto_const_nhds (lim_norm _)) lemma continuous {L : E → F} (hL : is_bounded_linear_map L) : continuous L := continuous_iff_tendsto.2 $ assume x, hL.tendsto x lemma lim_zero_bounded_linear_map {L : E → F} (H : is_bounded_linear_map L) : (L →_{0} 0) := (H.1.mk' _).map_zero ▸ continuous_iff_tendsto.1 H.continuous 0 end is_bounded_linear_map -- Next lemma is stated for real normed space but it would work as soon as the base field is an extension of ℝ lemma bounded_continuous_linear_map {E : Type*} [normed_space ℝ E] {F : Type*} [normed_space ℝ F] {L : E → F} (lin : is_linear_map L) (cont : continuous L) : is_bounded_linear_map L := let ⟨δ, δ_pos, hδ⟩ := exists_delta_of_continuous cont zero_lt_one 0 in have HL0 : L 0 = 0, from (lin.mk' _).map_zero, have H : ∀{a}, ∥a∥ ≤ δ → ∥L a∥ < 1, by simpa only [HL0, dist_zero_right] using hδ, lin.with_bound (δ⁻¹) $ assume x, classical.by_cases (assume : x = 0, by simp only [this, HL0, norm_zero, mul_zero]) $ assume h : x ≠ 0, let p := ∥x∥ * δ⁻¹, q := p⁻¹ in have p_inv : p⁻¹ = δ*∥x∥⁻¹, by simp, have norm_x_pos : ∥x∥ > 0 := (norm_pos_iff x).2 h, have norm_x : ∥x∥ ≠ 0 := mt (norm_eq_zero x).1 h, have p_pos : p > 0 := mul_pos norm_x_pos (inv_pos δ_pos), have p0 : _ := ne_of_gt p_pos, have q_pos : q > 0 := inv_pos p_pos, have q0 : _ := ne_of_gt q_pos, have ∥p⁻¹ • x∥ = δ := calc ∥p⁻¹ • x∥ = abs p⁻¹ * ∥x∥ : by rw norm_smul; refl ... = p⁻¹ * ∥x∥ : by rw [abs_of_nonneg $ le_of_lt q_pos] ... = δ : by simp [mul_assoc, inv_mul_cancel norm_x], calc ∥L x∥ = (p * q) * ∥L x∥ : begin dsimp [q], rw [mul_inv_cancel p0, one_mul] end ... = p * ∥L (q • x)∥ : by simp [lin.smul, norm_smul, real.norm_eq_abs, abs_of_pos q_pos, mul_assoc] ... ≤ p * 1 : mul_le_mul_of_nonneg_left (le_of_lt $ H $ le_of_eq $ this) (le_of_lt p_pos) ... = δ⁻¹ * ∥x∥ : by rw [mul_one, mul_comm]
33de336329c89c8845bf4b0d89cf74c443cae148
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/data/mv_polynomial/comap.lean
a532cd8918d99ee348445af537c70dd7a5cd1203
[ "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
3,618
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import data.mv_polynomial.rename /-! # `comap` operation on `mv_polynomial` This file defines the `comap` function on `mv_polynomial`. `mv_polynomial.comap` is a low-tech example of a map of "algebraic varieties," modulo the fact that `mathlib` does not yet define varieties. ## Notation As in other polynomial files, we typically use the notation: + `σ : Type*` (indexing the variables) + `R : Type*` `[comm_semiring R]` (the coefficients) -/ namespace mv_polynomial variables {σ : Type*} {τ : Type*} {υ : Type*} {R : Type*} [comm_semiring R] /-- Given an algebra hom `f : mv_polynomial σ R →ₐ[R] mv_polynomial τ R` and a variable evaluation `v : τ → R`, `comap f v` produces a variable evaluation `σ → R`. -/ noncomputable def comap (f : mv_polynomial σ R →ₐ[R] mv_polynomial τ R) : (τ → R) → (σ → R) := λ x i, aeval x (f (X i)) @[simp] lemma comap_apply (f : mv_polynomial σ R →ₐ[R] mv_polynomial τ R) (x : τ → R) (i : σ) : comap f x i = aeval x (f (X i)) := rfl @[simp] lemma comap_id_apply (x : σ → R) : comap (alg_hom.id R (mv_polynomial σ R)) x = x := by { funext i, simp only [comap, alg_hom.id_apply, id.def, aeval_X], } variables (σ R) lemma comap_id : comap (alg_hom.id R (mv_polynomial σ R)) = id := by { funext x, exact comap_id_apply x } variables {σ R} lemma comap_comp_apply (f : mv_polynomial σ R →ₐ[R] mv_polynomial τ R) (g : mv_polynomial τ R →ₐ[R] mv_polynomial υ R) (x : υ → R) : comap (g.comp f) x = comap f (comap g x) := begin funext i, transitivity (aeval x (aeval (λ i, g (X i)) (f (X i)))), { apply eval₂_hom_congr rfl rfl, rw alg_hom.comp_apply, suffices : g = aeval (λ i, g (X i)), { rw ← this, }, exact aeval_unique g }, { simp only [comap, aeval_eq_eval₂_hom, map_eval₂_hom, alg_hom.comp_apply], refine eval₂_hom_congr _ rfl rfl, ext r, apply aeval_C }, end lemma comap_comp (f : mv_polynomial σ R →ₐ[R] mv_polynomial τ R) (g : mv_polynomial τ R →ₐ[R] mv_polynomial υ R) : comap (g.comp f) = comap f ∘ comap g := by { funext x, exact comap_comp_apply _ _ _ } lemma comap_eq_id_of_eq_id (f : mv_polynomial σ R →ₐ[R] mv_polynomial σ R) (hf : ∀ φ, f φ = φ) (x : σ → R) : comap f x = x := by { convert comap_id_apply x, ext1 φ, rw [hf, alg_hom.id_apply] } lemma comap_rename (f : σ → τ) (x : τ → R) : comap (rename f) x = x ∘ f := by { ext i, simp only [rename_X, comap_apply, aeval_X] } /-- If two polynomial types over the same coefficient ring `R` are equivalent, there is a bijection between the types of functions from their variable types to `R`. -/ noncomputable def comap_equiv (f : mv_polynomial σ R ≃ₐ[R] mv_polynomial τ R) : (τ → R) ≃ (σ → R) := { to_fun := comap f, inv_fun := comap f.symm, left_inv := by { intro x, rw [← comap_comp_apply], apply comap_eq_id_of_eq_id, intro, simp only [alg_hom.id_apply, alg_equiv.comp_symm], }, right_inv := by { intro x, rw [← comap_comp_apply], apply comap_eq_id_of_eq_id, intro, simp only [alg_hom.id_apply, alg_equiv.symm_comp] }, } @[simp] lemma comap_equiv_coe (f : mv_polynomial σ R ≃ₐ[R] mv_polynomial τ R) : (comap_equiv f : (τ → R) → (σ → R)) = comap f := rfl @[simp] lemma comap_equiv_symm_coe (f : mv_polynomial σ R ≃ₐ[R] mv_polynomial τ R) : ((comap_equiv f).symm : (σ → R) → (τ → R)) = comap f.symm := rfl end mv_polynomial
bf7ec77ce14cd5290b38341c6775e8953d398b82
206422fb9edabf63def0ed2aa3f489150fb09ccb
/src/data/nat/cast.lean
6d247d82f9d03f9b79a39f326309ecbd3bcfa582
[ "Apache-2.0" ]
permissive
hamdysalah1/mathlib
b915f86b2503feeae268de369f1b16932321f097
95454452f6b3569bf967d35aab8d852b1ddf8017
refs/heads/master
1,677,154,116,545
1,611,797,994,000
1,611,797,994,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
10,482
lean
/- Copyright (c) 2014 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro Natural homomorphism from the natural numbers into a monoid with one. -/ import algebra.ordered_field import data.nat.basic namespace nat variables {α : Type*} section variables [has_zero α] [has_one α] [has_add α] /-- Canonical homomorphism from `ℕ` to a type `α` with `0`, `1` and `+`. -/ protected def cast : ℕ → α | 0 := 0 | (n+1) := cast n + 1 /-- Computationally friendlier cast than `nat.cast`, using binary representation. -/ protected def bin_cast (n : ℕ) : α := @nat.binary_rec (λ _, α) 0 (λ odd k a, cond odd (a + a + 1) (a + a)) n /-- Coercions such as `nat.cast_coe` that go from a concrete structure such as `ℕ` to an arbitrary ring `α` should be set up as follows: ```lean @[priority 900] instance : has_coe_t ℕ α := ⟨...⟩ ``` It needs to be `has_coe_t` instead of `has_coe` because otherwise type-class inference would loop when constructing the transitive coercion `ℕ → ℕ → ℕ → ...`. The reduced priority is necessary so that it doesn't conflict with instances such as `has_coe_t α (option α)`. For this to work, we reduce the priority of the `coe_base` and `coe_trans` instances because we want the instances for `has_coe_t` to be tried in the following order: 1. `has_coe_t` instances declared in mathlib (such as `has_coe_t α (with_top α)`, etc.) 2. `coe_base`, which contains instances such as `has_coe (fin n) n` 3. `nat.cast_coe : has_coe_t ℕ α` etc. 4. `coe_trans` If `coe_trans` is tried first, then `nat.cast_coe` doesn't get a chance to apply. -/ library_note "coercion into rings" attribute [instance, priority 950] coe_base attribute [instance, priority 500] coe_trans -- see note [coercion into rings] @[priority 900] instance cast_coe : has_coe_t ℕ α := ⟨nat.cast⟩ @[simp, norm_cast] theorem cast_zero : ((0 : ℕ) : α) = 0 := rfl theorem cast_add_one (n : ℕ) : ((n + 1 : ℕ) : α) = n + 1 := rfl @[simp, norm_cast, priority 500] theorem cast_succ (n : ℕ) : ((succ n : ℕ) : α) = n + 1 := rfl @[simp, norm_cast] theorem cast_ite (P : Prop) [decidable P] (m n : ℕ) : (((ite P m n) : ℕ) : α) = ite P (m : α) (n : α) := by { split_ifs; refl, } end @[simp, norm_cast] theorem cast_one [add_monoid α] [has_one α] : ((1 : ℕ) : α) = 1 := zero_add _ @[simp, norm_cast] theorem cast_add [add_monoid α] [has_one α] (m) : ∀ n, ((m + n : ℕ) : α) = m + n | 0 := (add_zero _).symm | (n+1) := show ((m + n : ℕ) : α) + 1 = m + (n + 1), by rw [cast_add n, add_assoc] @[simp] lemma bin_cast_eq [add_monoid α] [has_one α] (n : ℕ) : (nat.bin_cast n : α) = ((n : ℕ) : α) := begin rw nat.bin_cast, apply binary_rec _ _ n, { rw [binary_rec_zero, cast_zero] }, { intros b k h, rw [binary_rec_eq, h], { cases b; simp [bit, bit0, bit1] }, { simp } }, end /-- `coe : ℕ → α` as an `add_monoid_hom`. -/ def cast_add_monoid_hom (α : Type*) [add_monoid α] [has_one α] : ℕ →+ α := { to_fun := coe, map_add' := cast_add, map_zero' := cast_zero } @[simp] lemma coe_cast_add_monoid_hom [add_monoid α] [has_one α] : (cast_add_monoid_hom α : ℕ → α) = coe := rfl @[simp, norm_cast] theorem cast_bit0 [add_monoid α] [has_one α] (n : ℕ) : ((bit0 n : ℕ) : α) = bit0 n := cast_add _ _ @[simp, norm_cast] theorem cast_bit1 [add_monoid α] [has_one α] (n : ℕ) : ((bit1 n : ℕ) : α) = bit1 n := by rw [bit1, cast_add_one, cast_bit0]; refl lemma cast_two {α : Type*} [add_monoid α] [has_one α] : ((2 : ℕ) : α) = 2 := by simp @[simp, norm_cast] theorem cast_pred [add_group α] [has_one α] : ∀ {n}, 0 < n → ((n - 1 : ℕ) : α) = n - 1 | (n+1) h := (add_sub_cancel (n:α) 1).symm @[simp, norm_cast] theorem cast_sub [add_group α] [has_one α] {m n} (h : m ≤ n) : ((n - m : ℕ) : α) = n - m := eq_sub_of_add_eq $ by rw [← cast_add, nat.sub_add_cancel h] @[simp, norm_cast] theorem cast_mul [semiring α] (m) : ∀ n, ((m * n : ℕ) : α) = m * n | 0 := (mul_zero _).symm | (n+1) := (cast_add _ _).trans $ show ((m * n : ℕ) : α) + m = m * (n + 1), by rw [cast_mul n, left_distrib, mul_one] @[simp] theorem cast_dvd {α : Type*} [field α] {m n : ℕ} (n_dvd : n ∣ m) (n_nonzero : (n:α) ≠ 0) : ((m / n : ℕ) : α) = m / n := begin rcases n_dvd with ⟨k, rfl⟩, have : n ≠ 0, {rintro rfl, simpa using n_nonzero}, rw nat.mul_div_cancel_left _ (pos_iff_ne_zero.2 this), rw [nat.cast_mul, mul_div_cancel_left _ n_nonzero], end /-- `coe : ℕ → α` as a `ring_hom` -/ def cast_ring_hom (α : Type*) [semiring α] : ℕ →+* α := { to_fun := coe, map_one' := cast_one, map_mul' := cast_mul, .. cast_add_monoid_hom α } @[simp] lemma coe_cast_ring_hom [semiring α] : (cast_ring_hom α : ℕ → α) = coe := rfl lemma cast_commute [semiring α] (n : ℕ) (x : α) : commute ↑n x := nat.rec_on n (commute.zero_left x) $ λ n ihn, ihn.add_left $ commute.one_left x lemma commute_cast [semiring α] (x : α) (n : ℕ) : commute x n := (n.cast_commute x).symm section variables [ordered_semiring α] @[simp] theorem cast_nonneg : ∀ n : ℕ, 0 ≤ (n : α) | 0 := le_refl _ | (n+1) := add_nonneg (cast_nonneg n) zero_le_one theorem mono_cast : monotone (coe : ℕ → α) := λ m n h, let ⟨k, hk⟩ := le_iff_exists_add.1 h in by simp [hk] variable [nontrivial α] theorem strict_mono_cast : strict_mono (coe : ℕ → α) := λ m n h, nat.le_induction (lt_add_of_pos_right _ zero_lt_one) (λ n _ h, lt_add_of_lt_of_pos h zero_lt_one) _ h @[simp, norm_cast] theorem cast_le {m n : ℕ} : (m : α) ≤ n ↔ m ≤ n := strict_mono_cast.le_iff_le @[simp, norm_cast] theorem cast_lt {m n : ℕ} : (m : α) < n ↔ m < n := strict_mono_cast.lt_iff_lt @[simp] theorem cast_pos {n : ℕ} : (0 : α) < n ↔ 0 < n := by rw [← cast_zero, cast_lt] lemma cast_add_one_pos (n : ℕ) : 0 < (n : α) + 1 := add_pos_of_nonneg_of_pos n.cast_nonneg zero_lt_one @[simp, norm_cast] theorem one_lt_cast {n : ℕ} : 1 < (n : α) ↔ 1 < n := by rw [← cast_one, cast_lt] @[simp, norm_cast] theorem one_le_cast {n : ℕ} : 1 ≤ (n : α) ↔ 1 ≤ n := by rw [← cast_one, cast_le] @[simp, norm_cast] theorem cast_lt_one {n : ℕ} : (n : α) < 1 ↔ n = 0 := by rw [← cast_one, cast_lt, lt_succ_iff, le_zero_iff] @[simp, norm_cast] theorem cast_le_one {n : ℕ} : (n : α) ≤ 1 ↔ n ≤ 1 := by rw [← cast_one, cast_le] end @[simp, norm_cast] theorem cast_min [linear_ordered_semiring α] {a b : ℕ} : (↑(min a b) : α) = min a b := by by_cases a ≤ b; simp [h, min] @[simp, norm_cast] theorem cast_max [linear_ordered_semiring α] {a b : ℕ} : (↑(max a b) : α) = max a b := by by_cases a ≤ b; simp [h, max] @[simp, norm_cast] theorem abs_cast [linear_ordered_ring α] (a : ℕ) : abs (a : α) = a := abs_of_nonneg (cast_nonneg a) lemma coe_nat_dvd [comm_semiring α] {m n : ℕ} (h : m ∣ n) : (m : α) ∣ (n : α) := ring_hom.map_dvd (nat.cast_ring_hom α) h alias coe_nat_dvd ← has_dvd.dvd.nat_cast section linear_ordered_field variables [linear_ordered_field α] lemma inv_pos_of_nat {n : ℕ} : 0 < ((n : α) + 1)⁻¹ := inv_pos.2 $ add_pos_of_nonneg_of_pos n.cast_nonneg zero_lt_one lemma one_div_pos_of_nat {n : ℕ} : 0 < 1 / ((n : α) + 1) := by { rw one_div, exact inv_pos_of_nat } lemma one_div_le_one_div {n m : ℕ} (h : n ≤ m) : 1 / ((m : α) + 1) ≤ 1 / ((n : α) + 1) := by { refine one_div_le_one_div_of_le _ _, exact nat.cast_add_one_pos _, simpa } lemma one_div_lt_one_div {n m : ℕ} (h : n < m) : 1 / ((m : α) + 1) < 1 / ((n : α) + 1) := by { refine one_div_lt_one_div_of_lt _ _, exact nat.cast_add_one_pos _, simpa } end linear_ordered_field end nat namespace add_monoid_hom variables {A B : Type*} [add_monoid A] @[ext] lemma ext_nat {f g : ℕ →+ A} (h : f 1 = g 1) : f = g := ext $ λ n, nat.rec_on n (f.map_zero.trans g.map_zero.symm) $ λ n ihn, by simp only [nat.succ_eq_add_one, *, map_add] variables [has_one A] [add_monoid B] [has_one B] lemma eq_nat_cast (f : ℕ →+ A) (h1 : f 1 = 1) : ∀ n : ℕ, f n = n := congr_fun $ show f = nat.cast_add_monoid_hom A, from ext_nat (h1.trans nat.cast_one.symm) lemma map_nat_cast (f : A →+ B) (h1 : f 1 = 1) (n : ℕ) : f n = n := (f.comp (nat.cast_add_monoid_hom A)).eq_nat_cast (by simp [h1]) _ end add_monoid_hom namespace ring_hom variables {R : Type*} {S : Type*} [semiring R] [semiring S] @[simp] lemma eq_nat_cast (f : ℕ →+* R) (n : ℕ) : f n = n := f.to_add_monoid_hom.eq_nat_cast f.map_one n @[simp] lemma map_nat_cast (f : R →+* S) (n : ℕ) : f n = n := (f.comp (nat.cast_ring_hom R)).eq_nat_cast n lemma ext_nat (f g : ℕ →+* R) : f = g := coe_add_monoid_hom_injective $ add_monoid_hom.ext_nat $ f.map_one.trans g.map_one.symm end ring_hom @[simp, norm_cast] theorem nat.cast_id (n : ℕ) : ↑n = n := ((ring_hom.id ℕ).eq_nat_cast n).symm @[simp] theorem nat.cast_with_bot : ∀ (n : ℕ), @coe ℕ (with_bot ℕ) (@coe_to_lift _ _ nat.cast_coe) n = n | 0 := rfl | (n+1) := by rw [with_bot.coe_add, nat.cast_add, nat.cast_with_bot n]; refl instance nat.subsingleton_ring_hom {R : Type*} [semiring R] : subsingleton (ℕ →+* R) := ⟨ring_hom.ext_nat⟩ namespace with_top variables {α : Type*} variables [has_zero α] [has_one α] [has_add α] @[simp, norm_cast] lemma coe_nat : ∀(n : nat), ((n : α) : with_top α) = n | 0 := rfl | (n+1) := by { push_cast, rw [coe_nat n] } @[simp] lemma nat_ne_top (n : nat) : (n : with_top α) ≠ ⊤ := by { rw [←coe_nat n], apply coe_ne_top } @[simp] lemma top_ne_nat (n : nat) : (⊤ : with_top α) ≠ n := by { rw [←coe_nat n], apply top_ne_coe } lemma add_one_le_of_lt {i n : with_top ℕ} (h : i < n) : i + 1 ≤ n := begin cases n, { exact le_top }, cases i, { exact (not_le_of_lt h le_top).elim }, exact with_top.coe_le_coe.2 (with_top.coe_lt_coe.1 h) end lemma one_le_iff_pos {n : with_top ℕ} : 1 ≤ n ↔ 0 < n := ⟨λ h, (coe_lt_coe.2 zero_lt_one).trans_le h, λ h, by simpa only [zero_add] using add_one_le_of_lt h⟩ @[elab_as_eliminator] lemma nat_induction {P : with_top ℕ → Prop} (a : with_top ℕ) (h0 : P 0) (hsuc : ∀n:ℕ, P n → P n.succ) (htop : (∀n : ℕ, P n) → P ⊤) : P a := begin have A : ∀n:ℕ, P n := λ n, nat.rec_on n h0 hsuc, cases a, { exact htop A }, { exact A a } end end with_top
54d7bb78d90f7c7ad5771a81b4d84e89b438647f
d406927ab5617694ec9ea7001f101b7c9e3d9702
/archive/100-theorems-list/9_area_of_a_circle.lean
5e6177e2c5c98119ddf60b018f4d03d7d246f650
[ "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
6,503
lean
/- Copyright (c) 2021 James Arthur, Benjamin Davidson, Andrew Souther. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: James Arthur, Benjamin Davidson, Andrew Souther -/ import measure_theory.integral.interval_integral import analysis.special_functions.sqrt import analysis.special_functions.trigonometric.inverse_deriv /-! # Freek № 9: The Area of a Circle In this file we show that the area of a disc with nonnegative radius `r` is `π * r^2`. The main tools our proof uses are `volume_region_between_eq_integral`, which allows us to represent the area of the disc as an integral, and `interval_integral.integral_eq_sub_of_has_deriv_at'_of_le`, the second fundamental theorem of calculus. We begin by defining `disc` in `ℝ × ℝ`, then show that `disc` can be represented as the `region_between` two functions. Though not necessary for the main proof, we nonetheless choose to include a proof of the measurability of the disc in order to convince the reader that the set whose volume we will be calculating is indeed measurable and our result is therefore meaningful. In the main proof, `area_disc`, we use `volume_region_between_eq_integral` followed by `interval_integral.integral_of_le` to reduce our goal to a single `interval_integral`: `∫ (x : ℝ) in -r..r, 2 * sqrt (r ^ 2 - x ^ 2) = π * r ^ 2`. After disposing of the trivial case `r = 0`, we show that `λ x, 2 * sqrt (r ^ 2 - x ^ 2)` is equal to the derivative of `λ x, r ^ 2 * arcsin (x / r) + x * sqrt (r ^ 2 - x ^ 2)` everywhere on `Ioo (-r) r` and that those two functions are continuous, then apply the second fundamental theorem of calculus with those facts. Some simple algebra then completes the proof. Note that we choose to define `disc` as a set of points in `ℝ × ℝ`. This is admittedly not ideal; it would be more natural to define `disc` as a `metric.ball` in `euclidean_space ℝ (fin 2)` (as well as to provide a more general proof in higher dimensions). However, our proof indirectly relies on a number of theorems (particularly `measure_theory.measure.prod_apply`) which do not yet exist for Euclidean space, thus forcing us to use this less-preferable definition. As `measure_theory.pi` continues to develop, it should eventually become possible to redefine `disc` and extend our proof to the n-ball. -/ open set real measure_theory interval_integral open_locale real nnreal /-- A disc of radius `r` is defined as the collection of points `(p.1, p.2)` in `ℝ × ℝ` such that `p.1 ^ 2 + p.2 ^ 2 < r ^ 2`. Note that this definition is not equivalent to `metric.ball (0 : ℝ × ℝ) r`. This was done intentionally because `dist` in `ℝ × ℝ` is defined as the uniform norm, making the `metric.ball` in `ℝ × ℝ` a square, not a disc. See the module docstring for an explanation of why we don't define the disc in Euclidean space. -/ def disc (r : ℝ) := {p : ℝ × ℝ | p.1 ^ 2 + p.2 ^ 2 < r ^ 2} variable (r : ℝ≥0) /-- A disc of radius `r` can be represented as the region between the two curves `λ x, - sqrt (r ^ 2 - x ^ 2)` and `λ x, sqrt (r ^ 2 - x ^ 2)`. -/ lemma disc_eq_region_between : disc r = region_between (λ x, -sqrt (r^2 - x^2)) (λ x, sqrt (r^2 - x^2)) (Ioc (-r) r) := begin ext p, simp only [disc, region_between, mem_set_of_eq, mem_Ioo, mem_Ioc, pi.neg_apply], split; intro h, { cases abs_lt_of_sq_lt_sq' (lt_of_add_lt_of_nonneg_left h (sq_nonneg p.2)) r.2, rw [add_comm, ← lt_sub_iff_add_lt] at h, exact ⟨⟨left, right.le⟩, sq_lt.mp h⟩ }, { rw [add_comm, ← lt_sub_iff_add_lt], exact sq_lt.mpr h.2 }, end /-- The disc is a `measurable_set`. -/ theorem measurable_set_disc : measurable_set (disc r) := by apply measurable_set_lt; apply continuous.measurable; continuity /-- **Area of a Circle**: The area of a disc with radius `r` is `π * r ^ 2`. -/ theorem area_disc : volume (disc r) = nnreal.pi * r ^ 2 := begin let f := λ x, sqrt (r ^ 2 - x ^ 2), let F := λ x, (r:ℝ) ^ 2 * arcsin (r⁻¹ * x) + x * sqrt (r ^ 2 - x ^ 2), have hf : continuous f := by continuity, suffices : ∫ x in -r..r, 2 * f x = nnreal.pi * r ^ 2, { have h : integrable_on f (Ioc (-r) r) := hf.integrable_on_Icc.mono_set Ioc_subset_Icc_self, calc volume (disc r) = volume (region_between (λ x, -f x) f (Ioc (-r) r)) : by rw disc_eq_region_between ... = ennreal.of_real (∫ x in Ioc (-r:ℝ) r, (f - has_neg.neg ∘ f) x) : volume_region_between_eq_integral h.neg h measurable_set_Ioc (λ x hx, neg_le_self (sqrt_nonneg _)) ... = ennreal.of_real (∫ x in (-r:ℝ)..r, 2 * f x) : by simp [two_mul, integral_of_le] ... = nnreal.pi * r ^ 2 : by rw_mod_cast [this, ← ennreal.coe_nnreal_eq], }, obtain ⟨hle, (heq | hlt)⟩ := ⟨nnreal.coe_nonneg r, hle.eq_or_lt⟩, { simp [← heq] }, have hderiv : ∀ x ∈ Ioo (-r:ℝ) r, has_deriv_at F (2 * f x) x, { rintros x ⟨hx1, hx2⟩, convert ((has_deriv_at_const x ((r:ℝ)^2)).mul ((has_deriv_at_arcsin _ _).comp x ((has_deriv_at_const x (r:ℝ)⁻¹).mul (has_deriv_at_id' x)))).add ((has_deriv_at_id' x).mul ((((has_deriv_at_id' x).pow 2).const_sub ((r:ℝ)^2)).sqrt _)), { have h : sqrt (1 - x ^ 2 / r ^ 2) * r = sqrt (r ^ 2 - x ^ 2), { rw [← sqrt_sq hle, ← sqrt_mul, sub_mul, sqrt_sq hle, mul_comm_div, div_self (pow_ne_zero 2 hlt.ne'), one_mul, mul_one], simpa [sqrt_sq hle, div_le_one (pow_pos hlt 2)] using sq_le_sq' hx1.le hx2.le }, field_simp, rw [h, mul_left_comm, ← sq, neg_mul_eq_mul_neg, mul_div_mul_left (-x^2) _ two_ne_zero, add_left_comm, div_add_div_same, tactic.ring.add_neg_eq_sub, div_sqrt, two_mul] }, { suffices : -(1:ℝ) < r⁻¹ * x, by exact this.ne', calc -(1:ℝ) = r⁻¹ * -r : by simp [hlt.ne'] ... < r⁻¹ * x : by nlinarith [inv_pos.mpr hlt] }, { suffices : (r:ℝ)⁻¹ * x < 1, by exact this.ne, calc (r:ℝ)⁻¹ * x < r⁻¹ * r : by nlinarith [inv_pos.mpr hlt] ... = 1 : inv_mul_cancel hlt.ne' }, { nlinarith } }, have hcont := (by continuity : continuous F).continuous_on, calc ∫ x in -r..r, 2 * f x = F r - F (-r) : integral_eq_sub_of_has_deriv_at_of_le (neg_le_self r.2) hcont hderiv (continuous_const.mul hf).continuous_on.interval_integrable ... = nnreal.pi * r ^ 2 : by norm_num [F, inv_mul_cancel hlt.ne', ← mul_div_assoc, mul_comm π], end
50ec722a46ff5b28d2b8077b202d5ae196c73e18
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/logic/equiv/basic.lean
84745166d6e14f3a4c0c53f747de11c2c372f37e
[ "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
63,001
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Mario Carneiro -/ import logic.equiv.defs import data.option.basic import data.prod.basic import data.sigma.basic import data.subtype import data.sum.basic import logic.function.conjugate /-! # Equivalence between types > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file we continue the work on equivalences begun in `logic/equiv/defs.lean`, defining * canonical isomorphisms between various types: e.g., - `equiv.sum_equiv_sigma_bool` is the canonical equivalence between the sum of two types `α ⊕ β` and the sigma-type `Σ b : bool, cond b α β`; - `equiv.prod_sum_distrib : α × (β ⊕ γ) ≃ (α × β) ⊕ (α × γ)` shows that type product and type sum satisfy the distributive law up to a canonical equivalence; * operations on equivalences: e.g., - `equiv.prod_congr ea eb : α₁ × β₁ ≃ α₂ × β₂`: combine two equivalences `ea : α₁ ≃ α₂` and `eb : β₁ ≃ β₂` using `prod.map`. More definitions of this kind can be found in other files. E.g., `data/equiv/transfer_instance` does it for many algebraic type classes like `group`, `module`, etc. ## Tags equivalence, congruence, bijective map -/ open function universes u v w z variables {α : Sort u} {β : Sort v} {γ : Sort w} namespace equiv /-- `pprod α β` is equivalent to `α × β` -/ @[simps apply symm_apply] def pprod_equiv_prod {α β : Type*} : pprod α β ≃ α × β := { to_fun := λ x, (x.1, x.2), inv_fun := λ x, ⟨x.1, x.2⟩, left_inv := λ ⟨x, y⟩, rfl, right_inv := λ ⟨x, y⟩, rfl } /-- Product of two equivalences, in terms of `pprod`. If `α ≃ β` and `γ ≃ δ`, then `pprod α γ ≃ pprod β δ`. -/ @[congr, simps apply] def pprod_congr {δ : Sort z} (e₁ : α ≃ β) (e₂ : γ ≃ δ) : pprod α γ ≃ pprod β δ := { to_fun := λ x, ⟨e₁ x.1, e₂ x.2⟩, inv_fun := λ x, ⟨e₁.symm x.1, e₂.symm x.2⟩, left_inv := λ ⟨x, y⟩, by simp, right_inv := λ ⟨x, y⟩, by simp } /-- Combine two equivalences using `pprod` in the domain and `prod` in the codomain. -/ @[simps apply symm_apply] def pprod_prod {α₁ β₁ : Sort*} {α₂ β₂ : Type*} (ea : α₁ ≃ α₂) (eb : β₁ ≃ β₂) : pprod α₁ β₁ ≃ α₂ × β₂ := (ea.pprod_congr eb).trans pprod_equiv_prod /-- Combine two equivalences using `pprod` in the codomain and `prod` in the domain. -/ @[simps apply symm_apply] def prod_pprod {α₁ β₁ : Type*} {α₂ β₂ : Sort*} (ea : α₁ ≃ α₂) (eb : β₁ ≃ β₂) : α₁ × β₁ ≃ pprod α₂ β₂ := (ea.symm.pprod_prod eb.symm).symm /-- `pprod α β` is equivalent to `plift α × plift β` -/ @[simps apply symm_apply] def pprod_equiv_prod_plift {α β : Sort*} : pprod α β ≃ plift α × plift β := equiv.plift.symm.pprod_prod equiv.plift.symm /-- Product of two equivalences. If `α₁ ≃ α₂` and `β₁ ≃ β₂`, then `α₁ × β₁ ≃ α₂ × β₂`. This is `prod.map` as an equivalence. -/ @[congr, simps apply { fully_applied := ff }] def prod_congr {α₁ β₁ α₂ β₂ : Type*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) : α₁ × β₁ ≃ α₂ × β₂ := ⟨prod.map e₁ e₂, prod.map e₁.symm e₂.symm, λ ⟨a, b⟩, by simp, λ ⟨a, b⟩, by simp⟩ @[simp] theorem prod_congr_symm {α₁ β₁ α₂ β₂ : Type*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) : (prod_congr e₁ e₂).symm = prod_congr e₁.symm e₂.symm := rfl /-- Type product is commutative up to an equivalence: `α × β ≃ β × α`. This is `prod.swap` as an equivalence.-/ def prod_comm (α β : Type*) : α × β ≃ β × α := ⟨prod.swap, prod.swap, prod.swap_swap, prod.swap_swap⟩ @[simp] lemma coe_prod_comm (α β : Type*) : ⇑(prod_comm α β) = prod.swap := rfl @[simp] lemma prod_comm_apply {α β : Type*} (x : α × β) : prod_comm α β x = x.swap := rfl @[simp] lemma prod_comm_symm (α β) : (prod_comm α β).symm = prod_comm β α := rfl /-- Type product is associative up to an equivalence. -/ @[simps] def prod_assoc (α β γ : Sort*) : (α × β) × γ ≃ α × (β × γ) := ⟨λ p, (p.1.1, p.1.2, p.2), λ p, ((p.1, p.2.1), p.2.2), λ ⟨⟨a, b⟩, c⟩, rfl, λ ⟨a, ⟨b, c⟩⟩, rfl⟩ /-- Four-way commutativity of `prod`. The name matches `mul_mul_mul_comm`. -/ @[simps apply] def prod_prod_prod_comm (α β γ δ : Type*) : (α × β) × (γ × δ) ≃ (α × γ) × (β × δ) := { to_fun := λ abcd, ((abcd.1.1, abcd.2.1), (abcd.1.2, abcd.2.2)), inv_fun := λ acbd, ((acbd.1.1, acbd.2.1), (acbd.1.2, acbd.2.2)), left_inv := λ ⟨⟨a, b⟩, ⟨c, d⟩⟩, rfl, right_inv := λ ⟨⟨a, c⟩, ⟨b, d⟩⟩, rfl, } @[simp] lemma prod_prod_prod_comm_symm (α β γ δ : Type*) : (prod_prod_prod_comm α β γ δ).symm = prod_prod_prod_comm α γ β δ := rfl /-- Functions on `α × β` are equivalent to functions `α → β → γ`. -/ @[simps {fully_applied := ff}] def curry (α β γ : Type*) : (α × β → γ) ≃ (α → β → γ) := { to_fun := curry, inv_fun := uncurry, left_inv := uncurry_curry, right_inv := curry_uncurry } section /-- `punit` is a right identity for type product up to an equivalence. -/ @[simps] def prod_punit (α : Type*) : α × punit.{u+1} ≃ α := ⟨λ p, p.1, λ a, (a, punit.star), λ ⟨_, punit.star⟩, rfl, λ a, rfl⟩ /-- `punit` is a left identity for type product up to an equivalence. -/ @[simps] def punit_prod (α : Type*) : punit.{u+1} × α ≃ α := calc punit × α ≃ α × punit : prod_comm _ _ ... ≃ α : prod_punit _ /-- Any `unique` type is a right identity for type product up to equivalence. -/ def prod_unique (α β : Type*) [unique β] : α × β ≃ α := ((equiv.refl α).prod_congr $ equiv_punit β).trans $ prod_punit α @[simp] lemma coe_prod_unique {α β : Type*} [unique β] : ⇑(prod_unique α β) = prod.fst := rfl lemma prod_unique_apply {α β : Type*} [unique β] (x : α × β) : prod_unique α β x = x.1 := rfl @[simp] lemma prod_unique_symm_apply {α β : Type*} [unique β] (x : α) : (prod_unique α β).symm x = (x, default) := rfl /-- Any `unique` type is a left identity for type product up to equivalence. -/ def unique_prod (α β : Type*) [unique β] : β × α ≃ α := ((equiv_punit β).prod_congr $ equiv.refl α).trans $ punit_prod α @[simp] lemma coe_unique_prod {α β : Type*} [unique β] : ⇑(unique_prod α β) = prod.snd := rfl lemma unique_prod_apply {α β : Type*} [unique β] (x : β × α) : unique_prod α β x = x.2 := rfl @[simp] lemma unique_prod_symm_apply {α β : Type*} [unique β] (x : α) : (unique_prod α β).symm x = (default, x) := rfl /-- `empty` type is a right absorbing element for type product up to an equivalence. -/ def prod_empty (α : Type*) : α × empty ≃ empty := equiv_empty _ /-- `empty` type is a left absorbing element for type product up to an equivalence. -/ def empty_prod (α : Type*) : empty × α ≃ empty := equiv_empty _ /-- `pempty` type is a right absorbing element for type product up to an equivalence. -/ def prod_pempty (α : Type*) : α × pempty ≃ pempty := equiv_pempty _ /-- `pempty` type is a left absorbing element for type product up to an equivalence. -/ def pempty_prod (α : Type*) : pempty × α ≃ pempty := equiv_pempty _ end section open sum /-- `psum` is equivalent to `sum`. -/ def psum_equiv_sum (α β : Type*) : psum α β ≃ α ⊕ β := { to_fun := λ s, psum.cases_on s inl inr, inv_fun := sum.elim psum.inl psum.inr, left_inv := λ s, by cases s; refl, right_inv := λ s, by cases s; refl } /-- If `α ≃ α'` and `β ≃ β'`, then `α ⊕ β ≃ α' ⊕ β'`. This is `sum.map` as an equivalence. -/ @[simps apply] def sum_congr {α₁ β₁ α₂ β₂ : Type*} (ea : α₁ ≃ α₂) (eb : β₁ ≃ β₂) : α₁ ⊕ β₁ ≃ α₂ ⊕ β₂ := ⟨sum.map ea eb, sum.map ea.symm eb.symm, λ x, by simp, λ x, by simp⟩ /-- If `α ≃ α'` and `β ≃ β'`, then `psum α β ≃ psum α' β'`. -/ def psum_congr {δ : Sort z} (e₁ : α ≃ β) (e₂ : γ ≃ δ) : psum α γ ≃ psum β δ := { to_fun := λ x, psum.cases_on x (psum.inl ∘ e₁) (psum.inr ∘ e₂), inv_fun := λ x, psum.cases_on x (psum.inl ∘ e₁.symm) (psum.inr ∘ e₂.symm), left_inv := by rintro (x|x); simp, right_inv := by rintro (x|x); simp } /-- Combine two `equiv`s using `psum` in the domain and `sum` in the codomain. -/ def psum_sum {α₁ β₁ : Sort*} {α₂ β₂ : Type*} (ea : α₁ ≃ α₂) (eb : β₁ ≃ β₂) : psum α₁ β₁ ≃ α₂ ⊕ β₂ := (ea.psum_congr eb).trans (psum_equiv_sum _ _) /-- Combine two `equiv`s using `sum` in the domain and `psum` in the codomain. -/ def sum_psum {α₁ β₁ : Type*} {α₂ β₂ : Sort*} (ea : α₁ ≃ α₂) (eb : β₁ ≃ β₂) : α₁ ⊕ β₁ ≃ psum α₂ β₂ := (ea.symm.psum_sum eb.symm).symm @[simp] lemma sum_congr_trans {α₁ α₂ β₁ β₂ γ₁ γ₂ : Sort*} (e : α₁ ≃ β₁) (f : α₂ ≃ β₂) (g : β₁ ≃ γ₁) (h : β₂ ≃ γ₂) : (equiv.sum_congr e f).trans (equiv.sum_congr g h) = (equiv.sum_congr (e.trans g) (f.trans h)) := by { ext i, cases i; refl } @[simp] lemma sum_congr_symm {α β γ δ : Sort*} (e : α ≃ β) (f : γ ≃ δ) : (equiv.sum_congr e f).symm = (equiv.sum_congr (e.symm) (f.symm)) := rfl @[simp] lemma sum_congr_refl {α β : Sort*} : equiv.sum_congr (equiv.refl α) (equiv.refl β) = equiv.refl (α ⊕ β) := by { ext i, cases i; refl } namespace perm /-- Combine a permutation of `α` and of `β` into a permutation of `α ⊕ β`. -/ @[reducible] def sum_congr {α β : Type*} (ea : equiv.perm α) (eb : equiv.perm β) : equiv.perm (α ⊕ β) := equiv.sum_congr ea eb @[simp] lemma sum_congr_apply {α β : Type*} (ea : equiv.perm α) (eb : equiv.perm β) (x : α ⊕ β) : sum_congr ea eb x = sum.map ⇑ea ⇑eb x := equiv.sum_congr_apply ea eb x @[simp] lemma sum_congr_trans {α β : Sort*} (e : equiv.perm α) (f : equiv.perm β) (g : equiv.perm α) (h : equiv.perm β) : (sum_congr e f).trans (sum_congr g h) = sum_congr (e.trans g) (f.trans h) := equiv.sum_congr_trans e f g h @[simp] lemma sum_congr_symm {α β : Sort*} (e : equiv.perm α) (f : equiv.perm β) : (sum_congr e f).symm = sum_congr (e.symm) (f.symm) := equiv.sum_congr_symm e f @[simp] lemma sum_congr_refl {α β : Sort*} : sum_congr (equiv.refl α) (equiv.refl β) = equiv.refl (α ⊕ β) := equiv.sum_congr_refl end perm /-- `bool` is equivalent the sum of two `punit`s. -/ def bool_equiv_punit_sum_punit : bool ≃ punit.{u+1} ⊕ punit.{v+1} := ⟨λ b, cond b (inr punit.star) (inl punit.star), sum.elim (λ _, ff) (λ _, tt), λ b, by cases b; refl, λ s, by rcases s with ⟨⟨⟩⟩ | ⟨⟨⟩⟩; refl⟩ /-- Sum of types is commutative up to an equivalence. This is `sum.swap` as an equivalence. -/ @[simps apply {fully_applied := ff}] def sum_comm (α β : Type*) : α ⊕ β ≃ β ⊕ α := ⟨sum.swap, sum.swap, sum.swap_swap, sum.swap_swap⟩ @[simp] lemma sum_comm_symm (α β) : (sum_comm α β).symm = sum_comm β α := rfl /-- Sum of types is associative up to an equivalence. -/ def sum_assoc (α β γ : Type*) : (α ⊕ β) ⊕ γ ≃ α ⊕ (β ⊕ γ) := ⟨sum.elim (sum.elim sum.inl (sum.inr ∘ sum.inl)) (sum.inr ∘ sum.inr), sum.elim (sum.inl ∘ sum.inl) $ sum.elim (sum.inl ∘ sum.inr) sum.inr, by rintros (⟨_ | _⟩ | _); refl, by rintros (_ | ⟨_ | _⟩); refl⟩ @[simp] lemma sum_assoc_apply_inl_inl {α β γ} (a) : sum_assoc α β γ (inl (inl a)) = inl a := rfl @[simp] lemma sum_assoc_apply_inl_inr {α β γ} (b) : sum_assoc α β γ (inl (inr b)) = inr (inl b) := rfl @[simp] lemma sum_assoc_apply_inr {α β γ} (c) : sum_assoc α β γ (inr c) = inr (inr c) := rfl @[simp] lemma sum_assoc_symm_apply_inl {α β γ} (a) : (sum_assoc α β γ).symm (inl a) = inl (inl a) := rfl @[simp] lemma sum_assoc_symm_apply_inr_inl {α β γ} (b) : (sum_assoc α β γ).symm (inr (inl b)) = inl (inr b) := rfl @[simp] lemma sum_assoc_symm_apply_inr_inr {α β γ} (c) : (sum_assoc α β γ).symm (inr (inr c)) = inr c := rfl /-- Sum with `empty` is equivalent to the original type. -/ @[simps symm_apply] def sum_empty (α β : Type*) [is_empty β] : α ⊕ β ≃ α := ⟨sum.elim id is_empty_elim, inl, λ s, by { rcases s with _ | x, refl, exact is_empty_elim x }, λ a, rfl⟩ @[simp] lemma sum_empty_apply_inl {α β : Type*} [is_empty β] (a : α) : sum_empty α β (sum.inl a) = a := rfl /-- The sum of `empty` with any `Sort*` is equivalent to the right summand. -/ @[simps symm_apply] def empty_sum (α β : Type*) [is_empty α] : α ⊕ β ≃ β := (sum_comm _ _).trans $ sum_empty _ _ @[simp] lemma empty_sum_apply_inr {α β : Type*} [is_empty α] (b : β) : empty_sum α β (sum.inr b) = b := rfl /-- `option α` is equivalent to `α ⊕ punit` -/ def option_equiv_sum_punit (α : Type*) : option α ≃ α ⊕ punit.{u+1} := ⟨λ o, o.elim (inr punit.star) inl, λ s, s.elim some (λ _, none), λ o, by cases o; refl, λ s, by rcases s with _ | ⟨⟨⟩⟩; refl⟩ @[simp] lemma option_equiv_sum_punit_none {α} : option_equiv_sum_punit α none = sum.inr punit.star := rfl @[simp] lemma option_equiv_sum_punit_some {α} (a) : option_equiv_sum_punit α (some a) = sum.inl a := rfl @[simp] lemma option_equiv_sum_punit_coe {α} (a : α) : option_equiv_sum_punit α a = sum.inl a := rfl @[simp] lemma option_equiv_sum_punit_symm_inl {α} (a) : (option_equiv_sum_punit α).symm (sum.inl a) = a := rfl @[simp] lemma option_equiv_sum_punit_symm_inr {α} (a) : (option_equiv_sum_punit α).symm (sum.inr a) = none := rfl /-- The set of `x : option α` such that `is_some x` is equivalent to `α`. -/ @[simps] def option_is_some_equiv (α : Type*) : {x : option α // x.is_some} ≃ α := { to_fun := λ o, option.get o.2, inv_fun := λ x, ⟨some x, dec_trivial⟩, left_inv := λ o, subtype.eq $ option.some_get _, right_inv := λ x, option.get_some _ _ } /-- The product over `option α` of `β a` is the binary product of the product over `α` of `β (some α)` and `β none` -/ @[simps] def pi_option_equiv_prod {α : Type*} {β : option α → Type*} : (Π a : option α, β a) ≃ (β none × Π a : α, β (some a)) := { to_fun := λ f, (f none, λ a, f (some a)), inv_fun := λ x a, option.cases_on a x.fst x.snd, left_inv := λ f, funext $ λ a, by cases a; refl, right_inv := λ x, by simp } /-- `α ⊕ β` is equivalent to a `sigma`-type over `bool`. Note that this definition assumes `α` and `β` to be types from the same universe, so it cannot by used directly to transfer theorems about sigma types to theorems about sum types. In many cases one can use `ulift` to work around this difficulty. -/ def sum_equiv_sigma_bool (α β : Type u) : α ⊕ β ≃ (Σ b: bool, cond b α β) := ⟨λ s, s.elim (λ x, ⟨tt, x⟩) (λ x, ⟨ff, x⟩), λ s, match s with ⟨tt, a⟩ := inl a | ⟨ff, b⟩ := inr b end, λ s, by cases s; refl, λ s, by rcases s with ⟨_|_, _⟩; refl⟩ /-- `sigma_fiber_equiv f` for `f : α → β` is the natural equivalence between the type of all fibres of `f` and the total space `α`. -/ -- See also `equiv.sigma_preimage_equiv`. @[simps] def sigma_fiber_equiv {α β : Type*} (f : α → β) : (Σ y : β, {x // f x = y}) ≃ α := ⟨λ x, ↑x.2, λ x, ⟨f x, x, rfl⟩, λ ⟨y, x, rfl⟩, rfl, λ x, rfl⟩ end section sum_compl /-- For any predicate `p` on `α`, the sum of the two subtypes `{a // p a}` and its complement `{a // ¬ p a}` is naturally equivalent to `α`. See `subtype_or_equiv` for sum types over subtypes `{x // p x}` and `{x // q x}` that are not necessarily `is_compl p q`. -/ def sum_compl {α : Type*} (p : α → Prop) [decidable_pred p] : {a // p a} ⊕ {a // ¬ p a} ≃ α := { to_fun := sum.elim coe coe, inv_fun := λ a, if h : p a then sum.inl ⟨a, h⟩ else sum.inr ⟨a, h⟩, left_inv := by { rintros (⟨x,hx⟩|⟨x,hx⟩); dsimp; [rw dif_pos, rw dif_neg], }, right_inv := λ a, by { dsimp, split_ifs; refl } } @[simp] lemma sum_compl_apply_inl {α : Type*} (p : α → Prop) [decidable_pred p] (x : {a // p a}) : sum_compl p (sum.inl x) = x := rfl @[simp] lemma sum_compl_apply_inr {α : Type*} (p : α → Prop) [decidable_pred p] (x : {a // ¬ p a}) : sum_compl p (sum.inr x) = x := rfl @[simp] lemma sum_compl_apply_symm_of_pos {α : Type*} (p : α → Prop) [decidable_pred p] (a : α) (h : p a) : (sum_compl p).symm a = sum.inl ⟨a, h⟩ := dif_pos h @[simp] lemma sum_compl_apply_symm_of_neg {α : Type*} (p : α → Prop) [decidable_pred p] (a : α) (h : ¬ p a) : (sum_compl p).symm a = sum.inr ⟨a, h⟩ := dif_neg h /-- Combines an `equiv` between two subtypes with an `equiv` between their complements to form a permutation. -/ def subtype_congr {α : Type*} {p q : α → Prop} [decidable_pred p] [decidable_pred q] (e : {x // p x} ≃ {x // q x}) (f : {x // ¬p x} ≃ {x // ¬q x}) : perm α := (sum_compl p).symm.trans ((sum_congr e f).trans (sum_compl q)) open equiv variables {ε : Type*} {p : ε → Prop} [decidable_pred p] variables (ep ep' : perm {a // p a}) (en en' : perm {a // ¬ p a}) /-- Combining permutations on `ε` that permute only inside or outside the subtype split induced by `p : ε → Prop` constructs a permutation on `ε`. -/ def perm.subtype_congr : equiv.perm ε := perm_congr (sum_compl p) (sum_congr ep en) lemma perm.subtype_congr.apply (a : ε) : ep.subtype_congr en a = if h : p a then ep ⟨a, h⟩ else en ⟨a, h⟩ := by { by_cases h : p a; simp [perm.subtype_congr, h] } @[simp] lemma perm.subtype_congr.left_apply {a : ε} (h : p a) : ep.subtype_congr en a = ep ⟨a, h⟩ := by simp [perm.subtype_congr.apply, h] @[simp] lemma perm.subtype_congr.left_apply_subtype (a : {a // p a}) : ep.subtype_congr en a = ep a := by { convert perm.subtype_congr.left_apply _ _ a.property, simp } @[simp] lemma perm.subtype_congr.right_apply {a : ε} (h : ¬ p a) : ep.subtype_congr en a = en ⟨a, h⟩ := by simp [perm.subtype_congr.apply, h] @[simp] lemma perm.subtype_congr.right_apply_subtype (a : {a // ¬ p a}) : ep.subtype_congr en a = en a := by { convert perm.subtype_congr.right_apply _ _ a.property, simp } @[simp] lemma perm.subtype_congr.refl : perm.subtype_congr (equiv.refl {a // p a}) (equiv.refl {a // ¬ p a}) = equiv.refl ε := by { ext x, by_cases h : p x; simp [h] } @[simp] lemma perm.subtype_congr.symm : (ep.subtype_congr en).symm = perm.subtype_congr ep.symm en.symm := begin ext x, by_cases h : p x, { have : p (ep.symm ⟨x, h⟩) := subtype.property _, simp [perm.subtype_congr.apply, h, symm_apply_eq, this] }, { have : ¬ p (en.symm ⟨x, h⟩) := subtype.property (en.symm _), simp [perm.subtype_congr.apply, h, symm_apply_eq, this] } end @[simp] lemma perm.subtype_congr.trans : (ep.subtype_congr en).trans (ep'.subtype_congr en') = perm.subtype_congr (ep.trans ep') (en.trans en') := begin ext x, by_cases h : p x, { have : p (ep ⟨x, h⟩) := subtype.property _, simp [perm.subtype_congr.apply, h, this] }, { have : ¬ p (en ⟨x, h⟩) := subtype.property (en _), simp [perm.subtype_congr.apply, h, symm_apply_eq, this] } end end sum_compl section subtype_preimage variables (p : α → Prop) [decidable_pred p] (x₀ : {a // p a} → β) /-- For a fixed function `x₀ : {a // p a} → β` defined on a subtype of `α`, the subtype of functions `x : α → β` that agree with `x₀` on the subtype `{a // p a}` is naturally equivalent to the type of functions `{a // ¬ p a} → β`. -/ @[simps] def subtype_preimage : {x : α → β // x ∘ coe = x₀} ≃ ({a // ¬ p a} → β) := { to_fun := λ (x : {x : α → β // x ∘ coe = x₀}) a, (x : α → β) a, inv_fun := λ x, ⟨λ a, if h : p a then x₀ ⟨a, h⟩ else x ⟨a, h⟩, funext $ λ ⟨a, h⟩, dif_pos h⟩, left_inv := λ ⟨x, hx⟩, subtype.val_injective $ funext $ λ a, (by { dsimp, split_ifs; [ rw ← hx, skip ]; refl }), right_inv := λ x, funext $ λ ⟨a, h⟩, show dite (p a) _ _ = _, by { dsimp, rw [dif_neg h] } } lemma subtype_preimage_symm_apply_coe_pos (x : {a // ¬ p a} → β) (a : α) (h : p a) : ((subtype_preimage p x₀).symm x : α → β) a = x₀ ⟨a, h⟩ := dif_pos h lemma subtype_preimage_symm_apply_coe_neg (x : {a // ¬ p a} → β) (a : α) (h : ¬ p a) : ((subtype_preimage p x₀).symm x : α → β) a = x ⟨a, h⟩ := dif_neg h end subtype_preimage section /-- A family of equivalences `Π a, β₁ a ≃ β₂ a` generates an equivalence between `Π a, β₁ a` and `Π a, β₂ a`. -/ def Pi_congr_right {α} {β₁ β₂ : α → Sort*} (F : Π a, β₁ a ≃ β₂ a) : (Π a, β₁ a) ≃ (Π a, β₂ a) := ⟨λ H a, F a (H a), λ H a, (F a).symm (H a), λ H, funext $ by simp, λ H, funext $ by simp⟩ /-- Given `φ : α → β → Sort*`, we have an equivalence between `Π a b, φ a b` and `Π b a, φ a b`. This is `function.swap` as an `equiv`. -/ @[simps apply] def Pi_comm {α β} (φ : α → β → Sort*) : (Π a b, φ a b) ≃ (Π b a, φ a b) := ⟨swap, swap, λ x, rfl, λ y, rfl⟩ @[simp] lemma Pi_comm_symm {α β} {φ : α → β → Sort*} : (Pi_comm φ).symm = (Pi_comm $ swap φ) := rfl /-- Dependent `curry` equivalence: the type of dependent functions on `Σ i, β i` is equivalent to the type of dependent functions of two arguments (i.e., functions to the space of functions). This is `sigma.curry` and `sigma.uncurry` together as an equiv. -/ def Pi_curry {α} {β : α → Sort*} (γ : Π a, β a → Sort*) : (Π x : Σ i, β i, γ x.1 x.2) ≃ (Π a b, γ a b) := { to_fun := sigma.curry, inv_fun := sigma.uncurry, left_inv := sigma.uncurry_curry, right_inv := sigma.curry_uncurry } end section prod_congr variables {α₁ β₁ β₂ : Type*} (e : α₁ → β₁ ≃ β₂) /-- A family of equivalences `Π (a : α₁), β₁ ≃ β₂` generates an equivalence between `β₁ × α₁` and `β₂ × α₁`. -/ def prod_congr_left : β₁ × α₁ ≃ β₂ × α₁ := { to_fun := λ ab, ⟨e ab.2 ab.1, ab.2⟩, inv_fun := λ ab, ⟨(e ab.2).symm ab.1, ab.2⟩, left_inv := by { rintros ⟨a, b⟩, simp }, right_inv := by { rintros ⟨a, b⟩, simp } } @[simp] lemma prod_congr_left_apply (b : β₁) (a : α₁) : prod_congr_left e (b, a) = (e a b, a) := rfl lemma prod_congr_refl_right (e : β₁ ≃ β₂) : prod_congr e (equiv.refl α₁) = prod_congr_left (λ _, e) := by { ext ⟨a, b⟩ : 1, simp } /-- A family of equivalences `Π (a : α₁), β₁ ≃ β₂` generates an equivalence between `α₁ × β₁` and `α₁ × β₂`. -/ def prod_congr_right : α₁ × β₁ ≃ α₁ × β₂ := { to_fun := λ ab, ⟨ab.1, e ab.1 ab.2⟩, inv_fun := λ ab, ⟨ab.1, (e ab.1).symm ab.2⟩, left_inv := by { rintros ⟨a, b⟩, simp }, right_inv := by { rintros ⟨a, b⟩, simp } } @[simp] lemma prod_congr_right_apply (a : α₁) (b : β₁) : prod_congr_right e (a, b) = (a, e a b) := rfl lemma prod_congr_refl_left (e : β₁ ≃ β₂) : prod_congr (equiv.refl α₁) e = prod_congr_right (λ _, e) := by { ext ⟨a, b⟩ : 1, simp } @[simp] lemma prod_congr_left_trans_prod_comm : (prod_congr_left e).trans (prod_comm _ _) = (prod_comm _ _).trans (prod_congr_right e) := by { ext ⟨a, b⟩ : 1, simp } @[simp] lemma prod_congr_right_trans_prod_comm : (prod_congr_right e).trans (prod_comm _ _) = (prod_comm _ _).trans (prod_congr_left e) := by { ext ⟨a, b⟩ : 1, simp } lemma sigma_congr_right_sigma_equiv_prod : (sigma_congr_right e).trans (sigma_equiv_prod α₁ β₂) = (sigma_equiv_prod α₁ β₁).trans (prod_congr_right e) := by { ext ⟨a, b⟩ : 1, simp } lemma sigma_equiv_prod_sigma_congr_right : (sigma_equiv_prod α₁ β₁).symm.trans (sigma_congr_right e) = (prod_congr_right e).trans (sigma_equiv_prod α₁ β₂).symm := by { ext ⟨a, b⟩ : 1, simp } /-- A family of equivalences between fibers gives an equivalence between domains. -/ -- See also `equiv.of_preimage_equiv`. @[simps] def of_fiber_equiv {α β γ : Type*} {f : α → γ} {g : β → γ} (e : Π c, {a // f a = c} ≃ {b // g b = c}) : α ≃ β := (sigma_fiber_equiv f).symm.trans $ (equiv.sigma_congr_right e).trans (sigma_fiber_equiv g) lemma of_fiber_equiv_map {α β γ} {f : α → γ} {g : β → γ} (e : Π c, {a // f a = c} ≃ {b // g b = c}) (a : α) : g (of_fiber_equiv e a) = f a := (_ : {b // g b = _}).prop /-- A variation on `equiv.prod_congr` where the equivalence in the second component can depend on the first component. A typical example is a shear mapping, explaining the name of this declaration. -/ @[simps {fully_applied := ff}] def prod_shear {α₁ β₁ α₂ β₂ : Type*} (e₁ : α₁ ≃ α₂) (e₂ : α₁ → β₁ ≃ β₂) : α₁ × β₁ ≃ α₂ × β₂ := { to_fun := λ x : α₁ × β₁, (e₁ x.1, e₂ x.1 x.2), inv_fun := λ y : α₂ × β₂, (e₁.symm y.1, (e₂ $ e₁.symm y.1).symm y.2), left_inv := by { rintro ⟨x₁, y₁⟩, simp only [symm_apply_apply] }, right_inv := by { rintro ⟨x₁, y₁⟩, simp only [apply_symm_apply] } } end prod_congr namespace perm variables {α₁ β₁ β₂ : Type*} [decidable_eq α₁] (a : α₁) (e : perm β₁) /-- `prod_extend_right a e` extends `e : perm β` to `perm (α × β)` by sending `(a, b)` to `(a, e b)` and keeping the other `(a', b)` fixed. -/ def prod_extend_right : perm (α₁ × β₁) := { to_fun := λ ab, if ab.fst = a then (a, e ab.snd) else ab, inv_fun := λ ab, if ab.fst = a then (a, e.symm ab.snd) else ab, left_inv := by { rintros ⟨k', x⟩, dsimp only, split_ifs with h; simp [h] }, right_inv := by { rintros ⟨k', x⟩, dsimp only, split_ifs with h; simp [h] } } @[simp] lemma prod_extend_right_apply_eq (b : β₁) : prod_extend_right a e (a, b) = (a, e b) := if_pos rfl lemma prod_extend_right_apply_ne {a a' : α₁} (h : a' ≠ a) (b : β₁) : prod_extend_right a e (a', b) = (a', b) := if_neg h lemma eq_of_prod_extend_right_ne {e : perm β₁} {a a' : α₁} {b : β₁} (h : prod_extend_right a e (a', b) ≠ (a', b)) : a' = a := by { contrapose! h, exact prod_extend_right_apply_ne _ h _ } @[simp] lemma fst_prod_extend_right (ab : α₁ × β₁) : (prod_extend_right a e ab).fst = ab.fst := begin rw [prod_extend_right, coe_fn_mk], split_ifs with h, { rw h }, { refl } end end perm section /-- The type of functions to a product `α × β` is equivalent to the type of pairs of functions `γ → α` and `γ → β`. -/ def arrow_prod_equiv_prod_arrow (α β γ : Type*) : (γ → α × β) ≃ (γ → α) × (γ → β) := ⟨λ f, (λ c, (f c).1, λ c, (f c).2), λ p c, (p.1 c, p.2 c), λ f, funext $ λ c, prod.mk.eta, λ p, by { cases p, refl }⟩ open sum /-- The type of functions on a sum type `α ⊕ β` is equivalent to the type of pairs of functions on `α` and on `β`. -/ def sum_arrow_equiv_prod_arrow (α β γ : Type*) : ((α ⊕ β) → γ) ≃ (α → γ) × (β → γ) := ⟨λ f, (f ∘ inl, f ∘ inr), λ p, sum.elim p.1 p.2, λ f, by { ext ⟨⟩; refl }, λ p, by { cases p, refl }⟩ @[simp] lemma sum_arrow_equiv_prod_arrow_apply_fst {α β γ} (f : (α ⊕ β) → γ) (a : α) : (sum_arrow_equiv_prod_arrow α β γ f).1 a = f (inl a) := rfl @[simp] lemma sum_arrow_equiv_prod_arrow_apply_snd {α β γ} (f : (α ⊕ β) → γ) (b : β) : (sum_arrow_equiv_prod_arrow α β γ f).2 b = f (inr b) := rfl @[simp] lemma sum_arrow_equiv_prod_arrow_symm_apply_inl {α β γ} (f : α → γ) (g : β → γ) (a : α) : ((sum_arrow_equiv_prod_arrow α β γ).symm (f, g)) (inl a) = f a := rfl @[simp] lemma sum_arrow_equiv_prod_arrow_symm_apply_inr {α β γ} (f : α → γ) (g : β → γ) (b : β) : ((sum_arrow_equiv_prod_arrow α β γ).symm (f, g)) (inr b) = g b := rfl /-- Type product is right distributive with respect to type sum up to an equivalence. -/ def sum_prod_distrib (α β γ : Sort*) : (α ⊕ β) × γ ≃ (α × γ) ⊕ (β × γ) := ⟨λ p, p.1.map (λ x, (x, p.2)) (λ x, (x, p.2)), λ s, s.elim (prod.map inl id) (prod.map inr id), by rintro ⟨_ | _, _⟩; refl, by rintro (⟨_, _⟩ | ⟨_, _⟩); refl⟩ @[simp] theorem sum_prod_distrib_apply_left {α β γ} (a : α) (c : γ) : sum_prod_distrib α β γ (sum.inl a, c) = sum.inl (a, c) := rfl @[simp] theorem sum_prod_distrib_apply_right {α β γ} (b : β) (c : γ) : sum_prod_distrib α β γ (sum.inr b, c) = sum.inr (b, c) := rfl @[simp] theorem sum_prod_distrib_symm_apply_left {α β γ} (a : α × γ) : (sum_prod_distrib α β γ).symm (inl a) = (inl a.1, a.2) := rfl @[simp] theorem sum_prod_distrib_symm_apply_right {α β γ} (b : β × γ) : (sum_prod_distrib α β γ).symm (inr b) = (inr b.1, b.2) := rfl /-- Type product is left distributive with respect to type sum up to an equivalence. -/ def prod_sum_distrib (α β γ : Sort*) : α × (β ⊕ γ) ≃ (α × β) ⊕ (α × γ) := calc α × (β ⊕ γ) ≃ (β ⊕ γ) × α : prod_comm _ _ ... ≃ (β × α) ⊕ (γ × α) : sum_prod_distrib _ _ _ ... ≃ (α × β) ⊕ (α × γ) : sum_congr (prod_comm _ _) (prod_comm _ _) @[simp] theorem prod_sum_distrib_apply_left {α β γ} (a : α) (b : β) : prod_sum_distrib α β γ (a, sum.inl b) = sum.inl (a, b) := rfl @[simp] theorem prod_sum_distrib_apply_right {α β γ} (a : α) (c : γ) : prod_sum_distrib α β γ (a, sum.inr c) = sum.inr (a, c) := rfl @[simp] theorem prod_sum_distrib_symm_apply_left {α β γ} (a : α × β) : (prod_sum_distrib α β γ).symm (inl a) = (a.1, inl a.2) := rfl @[simp] theorem prod_sum_distrib_symm_apply_right {α β γ} (a : α × γ) : (prod_sum_distrib α β γ).symm (inr a) = (a.1, inr a.2) := rfl /-- An indexed sum of disjoint sums of types is equivalent to the sum of the indexed sums. -/ @[simps] def sigma_sum_distrib {ι : Type*} (α β : ι → Type*) : (Σ i, α i ⊕ β i) ≃ (Σ i, α i) ⊕ Σ i, β i := ⟨λ p, p.2.map (sigma.mk p.1) (sigma.mk p.1), sum.elim (sigma.map id (λ _, sum.inl)) (sigma.map id (λ _, sum.inr)), λ p, by { rcases p with ⟨i, (a | b)⟩; refl }, λ p, by { rcases p with (⟨i, a⟩ | ⟨i, b⟩); refl }⟩ /-- The product of an indexed sum of types (formally, a `sigma`-type `Σ i, α i`) by a type `β` is equivalent to the sum of products `Σ i, (α i × β)`. -/ def sigma_prod_distrib {ι : Type*} (α : ι → Type*) (β : Type*) : ((Σ i, α i) × β) ≃ (Σ i, (α i × β)) := ⟨λ p, ⟨p.1.1, (p.1.2, p.2)⟩, λ p, (⟨p.1, p.2.1⟩, p.2.2), λ p, by { rcases p with ⟨⟨_, _⟩, _⟩, refl }, λ p, by { rcases p with ⟨_, ⟨_, _⟩⟩, refl }⟩ /-- An equivalence that separates out the 0th fiber of `(Σ (n : ℕ), f n)`. -/ def sigma_nat_succ (f : ℕ → Type u) : (Σ n, f n) ≃ f 0 ⊕ Σ n, f (n + 1) := ⟨λ x, @sigma.cases_on ℕ f (λ _, f 0 ⊕ Σ n, f (n + 1)) x (λ n, @nat.cases_on (λ i, f i → (f 0 ⊕ Σ (n : ℕ), f (n + 1))) n (λ (x : f 0), sum.inl x) (λ (n : ℕ) (x : f n.succ), sum.inr ⟨n, x⟩)), sum.elim (sigma.mk 0) (sigma.map nat.succ (λ _, id)), by { rintro ⟨(n | n), x⟩; refl }, by { rintro (x | ⟨n, x⟩); refl }⟩ /-- The product `bool × α` is equivalent to `α ⊕ α`. -/ @[simps] def bool_prod_equiv_sum (α : Type u) : bool × α ≃ α ⊕ α := { to_fun := λ p, cond p.1 (inr p.2) (inl p.2), inv_fun := sum.elim (prod.mk ff) (prod.mk tt), left_inv := by rintro ⟨(_|_), _⟩; refl, right_inv := by rintro (_|_); refl } /-- The function type `bool → α` is equivalent to `α × α`. -/ @[simps] def bool_arrow_equiv_prod (α : Type u) : (bool → α) ≃ α × α := { to_fun := λ f, (f tt, f ff), inv_fun := λ p b, cond b p.1 p.2, left_inv := λ f, funext $ bool.forall_bool.2 ⟨rfl, rfl⟩, right_inv := λ ⟨x, y⟩, rfl } end section open sum nat /-- The set of natural numbers is equivalent to `ℕ ⊕ punit`. -/ def nat_equiv_nat_sum_punit : ℕ ≃ ℕ ⊕ punit.{u+1} := { to_fun := λ n, nat.cases_on n (inr punit.star) inl, inv_fun := sum.elim nat.succ (λ _, 0), left_inv := λ n, by cases n; refl, right_inv := by rintro (_|_|_); refl } /-- `ℕ ⊕ punit` is equivalent to `ℕ`. -/ def nat_sum_punit_equiv_nat : ℕ ⊕ punit.{u+1} ≃ ℕ := nat_equiv_nat_sum_punit.symm /-- The type of integer numbers is equivalent to `ℕ ⊕ ℕ`. -/ def int_equiv_nat_sum_nat : ℤ ≃ ℕ ⊕ ℕ := { to_fun := λ z, int.cases_on z inl inr, inv_fun := sum.elim coe int.neg_succ_of_nat, left_inv := by rintro (m|n); refl, right_inv := by rintro (m|n); refl } end /-- An equivalence between `α` and `β` generates an equivalence between `list α` and `list β`. -/ def list_equiv_of_equiv {α β : Type*} (e : α ≃ β) : list α ≃ list β := { to_fun := list.map e, inv_fun := list.map e.symm, left_inv := λ l, by rw [list.map_map, e.symm_comp_self, list.map_id], right_inv := λ l, by rw [list.map_map, e.self_comp_symm, list.map_id] } /-- If `α` is equivalent to `β`, then `unique α` is equivalent to `unique β`. -/ def unique_congr (e : α ≃ β) : unique α ≃ unique β := { to_fun := λ h, @equiv.unique _ _ h e.symm, inv_fun := λ h, @equiv.unique _ _ h e, left_inv := λ _, subsingleton.elim _ _, right_inv := λ _, subsingleton.elim _ _ } /-- If `α` is equivalent to `β`, then `is_empty α` is equivalent to `is_empty β`. -/ lemma is_empty_congr (e : α ≃ β) : is_empty α ↔ is_empty β := ⟨λ h, @function.is_empty _ _ h e.symm, λ h, @function.is_empty _ _ h e⟩ protected lemma is_empty (e : α ≃ β) [is_empty β] : is_empty α := e.is_empty_congr.mpr ‹_› section open subtype /-- If `α` is equivalent to `β` and the predicates `p : α → Prop` and `q : β → Prop` are equivalent at corresponding points, then `{a // p a}` is equivalent to `{b // q b}`. For the statement where `α = β`, that is, `e : perm α`, see `perm.subtype_perm`. -/ def subtype_equiv {p : α → Prop} {q : β → Prop} (e : α ≃ β) (h : ∀ a, p a ↔ q (e a)) : {a : α // p a} ≃ {b : β // q b} := { to_fun := λ a, ⟨e a, (h _).mp a.prop⟩, inv_fun := λ b, ⟨e.symm b, (h _).mpr ((e.apply_symm_apply b).symm ▸ b.prop)⟩, left_inv := λ a, subtype.ext $ by simp, right_inv := λ b, subtype.ext $ by simp } @[simp] lemma subtype_equiv_refl {p : α → Prop} (h : ∀ a, p a ↔ p (equiv.refl _ a) := λ a, iff.rfl) : (equiv.refl α).subtype_equiv h = equiv.refl {a : α // p a} := by { ext, refl } @[simp] lemma subtype_equiv_symm {p : α → Prop} {q : β → Prop} (e : α ≃ β) (h : ∀ (a : α), p a ↔ q (e a)) : (e.subtype_equiv h).symm = e.symm.subtype_equiv (λ a, by { convert (h $ e.symm a).symm, exact (e.apply_symm_apply a).symm }) := rfl @[simp] lemma subtype_equiv_trans {p : α → Prop} {q : β → Prop} {r : γ → Prop} (e : α ≃ β) (f : β ≃ γ) (h : ∀ (a : α), p a ↔ q (e a)) (h' : ∀ (b : β), q b ↔ r (f b)): (e.subtype_equiv h).trans (f.subtype_equiv h') = (e.trans f).subtype_equiv (λ a, (h a).trans (h' $ e a)) := rfl @[simp] lemma subtype_equiv_apply {p : α → Prop} {q : β → Prop} (e : α ≃ β) (h : ∀ (a : α), p a ↔ q (e a)) (x : {x // p x}) : e.subtype_equiv h x = ⟨e x, (h _).1 x.2⟩ := rfl /-- If two predicates `p` and `q` are pointwise equivalent, then `{x // p x}` is equivalent to `{x // q x}`. -/ @[simps] def subtype_equiv_right {p q : α → Prop} (e : ∀x, p x ↔ q x) : {x // p x} ≃ {x // q x} := subtype_equiv (equiv.refl _) e /-- If `α ≃ β`, then for any predicate `p : β → Prop` the subtype `{a // p (e a)}` is equivalent to the subtype `{b // p b}`. -/ def subtype_equiv_of_subtype {p : β → Prop} (e : α ≃ β) : {a : α // p (e a)} ≃ {b : β // p b} := subtype_equiv e $ by simp /-- If `α ≃ β`, then for any predicate `p : α → Prop` the subtype `{a // p a}` is equivalent to the subtype `{b // p (e.symm b)}`. This version is used by `equiv_rw`. -/ def subtype_equiv_of_subtype' {p : α → Prop} (e : α ≃ β) : {a : α // p a} ≃ {b : β // p (e.symm b)} := e.symm.subtype_equiv_of_subtype.symm /-- If two predicates are equal, then the corresponding subtypes are equivalent. -/ def subtype_equiv_prop {α : Sort*} {p q : α → Prop} (h : p = q) : subtype p ≃ subtype q := subtype_equiv (equiv.refl α) (assume a, h ▸ iff.rfl) /-- A subtype of a subtype is equivalent to the subtype of elements satisfying both predicates. This version allows the “inner” predicate to depend on `h : p a`. -/ @[simps] def subtype_subtype_equiv_subtype_exists {α : Sort u} (p : α → Prop) (q : subtype p → Prop) : subtype q ≃ {a : α // ∃h:p a, q ⟨a, h⟩ } := ⟨λ a, ⟨a, a.1.2, by { rcases a with ⟨⟨a, hap⟩, haq⟩, exact haq }⟩, λ a, ⟨⟨a, a.2.fst⟩, a.2.snd⟩, assume ⟨⟨a, ha⟩, h⟩, rfl, assume ⟨a, h₁, h₂⟩, rfl⟩ /-- A subtype of a subtype is equivalent to the subtype of elements satisfying both predicates. -/ @[simps] def subtype_subtype_equiv_subtype_inter {α : Sort u} (p q : α → Prop) : {x : subtype p // q x.1} ≃ subtype (λ x, p x ∧ q x) := (subtype_subtype_equiv_subtype_exists p _).trans $ subtype_equiv_right $ λ x, exists_prop /-- If the outer subtype has more restrictive predicate than the inner one, then we can drop the latter. -/ @[simps] def subtype_subtype_equiv_subtype {α : Type u} {p q : α → Prop} (h : ∀ {x}, q x → p x) : {x : subtype p // q x.1} ≃ subtype q := (subtype_subtype_equiv_subtype_inter p _).trans $ subtype_equiv_right $ λ x, and_iff_right_of_imp h /-- If a proposition holds for all elements, then the subtype is equivalent to the original type. -/ @[simps apply symm_apply] def subtype_univ_equiv {α : Type u} {p : α → Prop} (h : ∀ x, p x) : subtype p ≃ α := ⟨λ x, x, λ x, ⟨x, h x⟩, λ x, subtype.eq rfl, λ x, rfl⟩ /-- A subtype of a sigma-type is a sigma-type over a subtype. -/ def subtype_sigma_equiv {α : Type u} (p : α → Type v) (q : α → Prop) : { y : sigma p // q y.1 } ≃ Σ(x : subtype q), p x.1 := ⟨λ x, ⟨⟨x.1.1, x.2⟩, x.1.2⟩, λ x, ⟨⟨x.1.1, x.2⟩, x.1.2⟩, λ ⟨⟨x, h⟩, y⟩, rfl, λ ⟨⟨x, y⟩, h⟩, rfl⟩ /-- A sigma type over a subtype is equivalent to the sigma set over the original type, if the fiber is empty outside of the subset -/ def sigma_subtype_equiv_of_subset {α : Type u} (p : α → Type v) (q : α → Prop) (h : ∀ x, p x → q x) : (Σ x : subtype q, p x) ≃ Σ x : α, p x := (subtype_sigma_equiv p q).symm.trans $ subtype_univ_equiv $ λ x, h x.1 x.2 /-- If a predicate `p : β → Prop` is true on the range of a map `f : α → β`, then `Σ y : {y // p y}, {x // f x = y}` is equivalent to `α`. -/ def sigma_subtype_fiber_equiv {α : Type u} {β : Type v} (f : α → β) (p : β → Prop) (h : ∀ x, p (f x)) : (Σ y : subtype p, {x : α // f x = y}) ≃ α := calc _ ≃ Σ y : β, {x : α // f x = y} : sigma_subtype_equiv_of_subset _ p (λ y ⟨x, h'⟩, h' ▸ h x) ... ≃ α : sigma_fiber_equiv f /-- If for each `x` we have `p x ↔ q (f x)`, then `Σ y : {y // q y}, f ⁻¹' {y}` is equivalent to `{x // p x}`. -/ def sigma_subtype_fiber_equiv_subtype {α : Type u} {β : Type v} (f : α → β) {p : α → Prop} {q : β → Prop} (h : ∀ x, p x ↔ q (f x)) : (Σ y : subtype q, {x : α // f x = y}) ≃ subtype p := calc (Σ y : subtype q, {x : α // f x = y}) ≃ Σ y : subtype q, {x : subtype p // subtype.mk (f x) ((h x).1 x.2) = y} : begin apply sigma_congr_right, assume y, symmetry, refine (subtype_subtype_equiv_subtype_exists _ _).trans (subtype_equiv_right _), assume x, exact ⟨λ ⟨hp, h'⟩, congr_arg subtype.val h', λ h', ⟨(h x).2 (h'.symm ▸ y.2), subtype.eq h'⟩⟩ end ... ≃ subtype p : sigma_fiber_equiv (λ x : subtype p, (⟨f x, (h x).1 x.property⟩ : subtype q)) /-- A sigma type over an `option` is equivalent to the sigma set over the original type, if the fiber is empty at none. -/ def sigma_option_equiv_of_some {α : Type u} (p : option α → Type v) (h : p none → false) : (Σ x : option α, p x) ≃ (Σ x : α, p (some x)) := begin have h' : ∀ x, p x → x.is_some, { intro x, cases x, { intro n, exfalso, exact h n }, { intro s, exact rfl } }, exact (sigma_subtype_equiv_of_subset _ _ h').symm.trans (sigma_congr_left' (option_is_some_equiv α)), end /-- The `pi`-type `Π i, π i` is equivalent to the type of sections `f : ι → Σ i, π i` of the `sigma` type such that for all `i` we have `(f i).fst = i`. -/ def pi_equiv_subtype_sigma (ι : Type*) (π : ι → Type*) : (Π i, π i) ≃ {f : ι → Σ i, π i // ∀ i, (f i).1 = i } := ⟨ λf, ⟨λi, ⟨i, f i⟩, assume i, rfl⟩, λf i, begin rw ← f.2 i, exact (f.1 i).2 end, assume f, funext $ assume i, rfl, assume ⟨f, hf⟩, subtype.eq $ funext $ assume i, sigma.eq (hf i).symm $ eq_of_heq $ rec_heq_of_heq _ $ rec_heq_of_heq _ $ heq.refl _⟩ /-- The set of functions `f : Π a, β a` such that for all `a` we have `p a (f a)` is equivalent to the set of functions `Π a, {b : β a // p a b}`. -/ def subtype_pi_equiv_pi {α : Sort u} {β : α → Sort v} {p : Πa, β a → Prop} : {f : Πa, β a // ∀a, p a (f a) } ≃ Πa, { b : β a // p a b } := ⟨λf a, ⟨f.1 a, f.2 a⟩, λf, ⟨λa, (f a).1, λa, (f a).2⟩, by { rintro ⟨f, h⟩, refl }, by { rintro f, funext a, exact subtype.ext_val rfl }⟩ /-- A subtype of a product defined by componentwise conditions is equivalent to a product of subtypes. -/ def subtype_prod_equiv_prod {α : Type u} {β : Type v} {p : α → Prop} {q : β → Prop} : {c : α × β // p c.1 ∧ q c.2} ≃ ({a // p a} × {b // q b}) := ⟨λ x, ⟨⟨x.1.1, x.2.1⟩, ⟨x.1.2, x.2.2⟩⟩, λ x, ⟨⟨x.1.1, x.2.1⟩, ⟨x.1.2, x.2.2⟩⟩, λ ⟨⟨_, _⟩, ⟨_, _⟩⟩, rfl, λ ⟨⟨_, _⟩, ⟨_, _⟩⟩, rfl⟩ /-- A subtype of a `prod` is equivalent to a sigma type whose fibers are subtypes. -/ def subtype_prod_equiv_sigma_subtype {α β : Type*} (p : α → β → Prop) : {x : α × β // p x.1 x.2} ≃ Σ a, {b : β // p a b} := { to_fun := λ x, ⟨x.1.1, x.1.2, x.prop⟩, inv_fun := λ x, ⟨⟨x.1, x.2⟩, x.2.prop⟩, left_inv := λ x, by ext; refl, right_inv := λ ⟨a, b, pab⟩, rfl } /-- The type `Π (i : α), β i` can be split as a product by separating the indices in `α` depending on whether they satisfy a predicate `p` or not. -/ @[simps] def pi_equiv_pi_subtype_prod {α : Type*} (p : α → Prop) (β : α → Type*) [decidable_pred p] : (Π (i : α), β i) ≃ (Π (i : {x // p x}), β i) × (Π (i : {x // ¬ p x}), β i) := { to_fun := λ f, (λ x, f x, λ x, f x), inv_fun := λ f x, if h : p x then f.1 ⟨x, h⟩ else f.2 ⟨x, h⟩, right_inv := begin rintros ⟨f, g⟩, ext1; { ext y, rcases y, simp only [y_property, dif_pos, dif_neg, not_false_iff, subtype.coe_mk], refl }, end, left_inv := λ f, begin ext x, by_cases h : p x; { simp only [h, dif_neg, dif_pos, not_false_iff], refl }, end } /-- A product of types can be split as the binary product of one of the types and the product of all the remaining types. -/ @[simps] def pi_split_at {α : Type*} [decidable_eq α] (i : α) (β : α → Type*) : (Π j, β j) ≃ β i × Π j : {j // j ≠ i}, β j := { to_fun := λ f, ⟨f i, λ j, f j⟩, inv_fun := λ f j, if h : j = i then h.symm.rec f.1 else f.2 ⟨j, h⟩, right_inv := λ f, by { ext, exacts [dif_pos rfl, (dif_neg x.2).trans (by cases x; refl)] }, left_inv := λ f, by { ext, dsimp only, split_ifs, { subst h }, { refl } } } /-- A product of copies of a type can be split as the binary product of one copy and the product of all the remaining copies. -/ @[simps] def fun_split_at {α : Type*} [decidable_eq α] (i : α) (β : Type*) : (α → β) ≃ β × ({j // j ≠ i} → β) := pi_split_at i _ end section subtype_equiv_codomain variables {X : Type*} {Y : Type*} [decidable_eq X] {x : X} /-- The type of all functions `X → Y` with prescribed values for all `x' ≠ x` is equivalent to the codomain `Y`. -/ def subtype_equiv_codomain (f : {x' // x' ≠ x} → Y) : {g : X → Y // g ∘ coe = f} ≃ Y := (subtype_preimage _ f).trans $ @fun_unique {x' // ¬ x' ≠ x} _ $ show unique {x' // ¬ x' ≠ x}, from @equiv.unique _ _ (show unique {x' // x' = x}, from { default := ⟨x, rfl⟩, uniq := λ ⟨x', h⟩, subtype.val_injective h }) (subtype_equiv_right $ λ a, not_not) @[simp] lemma coe_subtype_equiv_codomain (f : {x' // x' ≠ x} → Y) : (subtype_equiv_codomain f : {g : X → Y // g ∘ coe = f} → Y) = λ g, (g : X → Y) x := rfl @[simp] lemma subtype_equiv_codomain_apply (f : {x' // x' ≠ x} → Y) (g : {g : X → Y // g ∘ coe = f}) : subtype_equiv_codomain f g = (g : X → Y) x := rfl lemma coe_subtype_equiv_codomain_symm (f : {x' // x' ≠ x} → Y) : ((subtype_equiv_codomain f).symm : Y → {g : X → Y // g ∘ coe = f}) = λ y, ⟨λ x', if h : x' ≠ x then f ⟨x', h⟩ else y, by { funext x', dsimp, erw [dif_pos x'.2, subtype.coe_eta] }⟩ := rfl @[simp] lemma subtype_equiv_codomain_symm_apply (f : {x' // x' ≠ x} → Y) (y : Y) (x' : X) : ((subtype_equiv_codomain f).symm y : X → Y) x' = if h : x' ≠ x then f ⟨x', h⟩ else y := rfl @[simp] lemma subtype_equiv_codomain_symm_apply_eq (f : {x' // x' ≠ x} → Y) (y : Y) : ((subtype_equiv_codomain f).symm y : X → Y) x = y := dif_neg (not_not.mpr rfl) lemma subtype_equiv_codomain_symm_apply_ne (f : {x' // x' ≠ x} → Y) (y : Y) (x' : X) (h : x' ≠ x) : ((subtype_equiv_codomain f).symm y : X → Y) x' = f ⟨x', h⟩ := dif_pos h end subtype_equiv_codomain /-- If `f` is a bijective function, then its domain is equivalent to its codomain. -/ @[simps apply] noncomputable def of_bijective (f : α → β) (hf : bijective f) : α ≃ β := { to_fun := f, inv_fun := function.surj_inv hf.surjective, left_inv := function.left_inverse_surj_inv hf, right_inv := function.right_inverse_surj_inv _} lemma of_bijective_apply_symm_apply (f : α → β) (hf : bijective f) (x : β) : f ((of_bijective f hf).symm x) = x := (of_bijective f hf).apply_symm_apply x @[simp] lemma of_bijective_symm_apply_apply (f : α → β) (hf : bijective f) (x : α) : (of_bijective f hf).symm (f x) = x := (of_bijective f hf).symm_apply_apply x instance : can_lift (α → β) (α ≃ β) coe_fn bijective := { prf := λ f hf, ⟨of_bijective f hf, rfl⟩ } section variables {α' β' : Type*} (e : perm α') {p : β' → Prop} [decidable_pred p] (f : α' ≃ subtype p) /-- Extend the domain of `e : equiv.perm α` to one that is over `β` via `f : α → subtype p`, where `p : β → Prop`, permuting only the `b : β` that satisfy `p b`. This can be used to extend the domain across a function `f : α → β`, keeping everything outside of `set.range f` fixed. For this use-case `equiv` given by `f` can be constructed by `equiv.of_left_inverse'` or `equiv.of_left_inverse` when there is a known inverse, or `equiv.of_injective` in the general case.`. -/ def perm.extend_domain : perm β' := (perm_congr f e).subtype_congr (equiv.refl _) @[simp] lemma perm.extend_domain_apply_image (a : α') : e.extend_domain f (f a) = f (e a) := by simp [perm.extend_domain] lemma perm.extend_domain_apply_subtype {b : β'} (h : p b) : e.extend_domain f b = f (e (f.symm ⟨b, h⟩)) := by simp [perm.extend_domain, h] lemma perm.extend_domain_apply_not_subtype {b : β'} (h : ¬ p b) : e.extend_domain f b = b := by simp [perm.extend_domain, h] @[simp] lemma perm.extend_domain_refl : perm.extend_domain (equiv.refl _) f = equiv.refl _ := by simp [perm.extend_domain] @[simp] lemma perm.extend_domain_symm : (e.extend_domain f).symm = perm.extend_domain e.symm f := rfl lemma perm.extend_domain_trans (e e' : perm α') : (e.extend_domain f).trans (e'.extend_domain f) = perm.extend_domain (e.trans e') f := by simp [perm.extend_domain, perm_congr_trans] end /-- Subtype of the quotient is equivalent to the quotient of the subtype. Let `α` be a setoid with equivalence relation `~`. Let `p₂` be a predicate on the quotient type `α/~`, and `p₁` be the lift of this predicate to `α`: `p₁ a ↔ p₂ ⟦a⟧`. Let `~₂` be the restriction of `~` to `{x // p₁ x}`. Then `{x // p₂ x}` is equivalent to the quotient of `{x // p₁ x}` by `~₂`. -/ def subtype_quotient_equiv_quotient_subtype (p₁ : α → Prop) [s₁ : setoid α] [s₂ : setoid (subtype p₁)] (p₂ : quotient s₁ → Prop) (hp₂ : ∀ a, p₁ a ↔ p₂ ⟦a⟧) (h : ∀ x y : subtype p₁, @setoid.r _ s₂ x y ↔ (x : α) ≈ y) : {x // p₂ x} ≃ quotient s₂ := { to_fun := λ a, quotient.hrec_on a.1 (λ a h, ⟦⟨a, (hp₂ _).2 h⟩⟧) (λ a b hab, hfunext (by rw quotient.sound hab) (λ h₁ h₂ _, heq_of_eq (quotient.sound ((h _ _).2 hab)))) a.2, inv_fun := λ a, quotient.lift_on a (λ a, (⟨⟦a.1⟧, (hp₂ _).1 a.2⟩ : {x // p₂ x})) (λ a b hab, subtype.ext_val (quotient.sound ((h _ _).1 hab))), left_inv := λ ⟨a, ha⟩, quotient.induction_on a (λ a ha, rfl) ha, right_inv := λ a, quotient.induction_on a (λ ⟨a, ha⟩, rfl) } @[simp] lemma subtype_quotient_equiv_quotient_subtype_mk (p₁ : α → Prop) [s₁ : setoid α] [s₂ : setoid (subtype p₁)] (p₂ : quotient s₁ → Prop) (hp₂ : ∀ a, p₁ a ↔ p₂ ⟦a⟧) (h : ∀ x y : subtype p₁, @setoid.r _ s₂ x y ↔ (x : α) ≈ y) (x hx) : subtype_quotient_equiv_quotient_subtype p₁ p₂ hp₂ h ⟨⟦x⟧, hx⟩ = ⟦⟨x, (hp₂ _).2 hx⟩⟧ := rfl @[simp] lemma subtype_quotient_equiv_quotient_subtype_symm_mk (p₁ : α → Prop) [s₁ : setoid α] [s₂ : setoid (subtype p₁)] (p₂ : quotient s₁ → Prop) (hp₂ : ∀ a, p₁ a ↔ p₂ ⟦a⟧) (h : ∀ x y : subtype p₁, @setoid.r _ s₂ x y ↔ (x : α) ≈ y) (x) : (subtype_quotient_equiv_quotient_subtype p₁ p₂ hp₂ h).symm ⟦x⟧ = ⟨⟦x⟧, (hp₂ _).1 x.prop⟩ := rfl section swap variable [decidable_eq α] /-- A helper function for `equiv.swap`. -/ def swap_core (a b r : α) : α := if r = a then b else if r = b then a else r theorem swap_core_self (r a : α) : swap_core a a r = r := by { unfold swap_core, split_ifs; cc } theorem swap_core_swap_core (r a b : α) : swap_core a b (swap_core a b r) = r := by { unfold swap_core, split_ifs; cc } theorem swap_core_comm (r a b : α) : swap_core a b r = swap_core b a r := by { unfold swap_core, split_ifs; cc } /-- `swap a b` is the permutation that swaps `a` and `b` and leaves other values as is. -/ def swap (a b : α) : perm α := ⟨swap_core a b, swap_core a b, λr, swap_core_swap_core r a b, λr, swap_core_swap_core r a b⟩ @[simp] theorem swap_self (a : α) : swap a a = equiv.refl _ := ext $ λ r, swap_core_self r a theorem swap_comm (a b : α) : swap a b = swap b a := ext $ λ r, swap_core_comm r _ _ theorem swap_apply_def (a b x : α) : swap a b x = if x = a then b else if x = b then a else x := rfl @[simp] theorem swap_apply_left (a b : α) : swap a b a = b := if_pos rfl @[simp] theorem swap_apply_right (a b : α) : swap a b b = a := by { by_cases h : b = a; simp [swap_apply_def, h], } theorem swap_apply_of_ne_of_ne {a b x : α} : x ≠ a → x ≠ b → swap a b x = x := by simp [swap_apply_def] {contextual := tt} @[simp] theorem swap_swap (a b : α) : (swap a b).trans (swap a b) = equiv.refl _ := ext $ λ x, swap_core_swap_core _ _ _ @[simp] lemma symm_swap (a b : α) : (swap a b).symm = swap a b := rfl @[simp] lemma swap_eq_refl_iff {x y : α} : swap x y = equiv.refl _ ↔ x = y := begin refine ⟨λ h, (equiv.refl _).injective _, λ h, h ▸ (swap_self _)⟩, rw [←h, swap_apply_left, h, refl_apply] end theorem swap_comp_apply {a b x : α} (π : perm α) : π.trans (swap a b) x = if π x = a then b else if π x = b then a else π x := by { cases π, refl } lemma swap_eq_update (i j : α) : (equiv.swap i j : α → α) = update (update id j i) i j := funext $ λ x, by rw [update_apply _ i j, update_apply _ j i, equiv.swap_apply_def, id.def] lemma comp_swap_eq_update (i j : α) (f : α → β) : f ∘ equiv.swap i j = update (update f j (f i)) i (f j) := by rw [swap_eq_update, comp_update, comp_update, comp.right_id] @[simp] lemma symm_trans_swap_trans [decidable_eq β] (a b : α) (e : α ≃ β) : (e.symm.trans (swap a b)).trans e = swap (e a) (e b) := equiv.ext (λ x, begin have : ∀ a, e.symm x = a ↔ x = e a := λ a, by { rw @eq_comm _ (e.symm x), split; intros; simp * at * }, simp [swap_apply_def, this], split_ifs; simp end) @[simp] lemma trans_swap_trans_symm [decidable_eq β] (a b : β) (e : α ≃ β) : (e.trans (swap a b)).trans e.symm = swap (e.symm a) (e.symm b) := symm_trans_swap_trans a b e.symm @[simp] lemma swap_apply_self (i j a : α) : swap i j (swap i j a) = a := by rw [← equiv.trans_apply, equiv.swap_swap, equiv.refl_apply] /-- A function is invariant to a swap if it is equal at both elements -/ lemma apply_swap_eq_self {v : α → β} {i j : α} (hv : v i = v j) (k : α) : v (swap i j k) = v k := begin by_cases hi : k = i, { rw [hi, swap_apply_left, hv] }, by_cases hj : k = j, { rw [hj, swap_apply_right, hv] }, rw swap_apply_of_ne_of_ne hi hj, end lemma swap_apply_eq_iff {x y z w : α} : swap x y z = w ↔ z = swap x y w := by rw [apply_eq_iff_eq_symm_apply, symm_swap] lemma swap_apply_ne_self_iff {a b x : α} : swap a b x ≠ x ↔ a ≠ b ∧ (x = a ∨ x = b) := begin by_cases hab : a = b, { simp [hab] }, by_cases hax : x = a, { simp [hax, eq_comm] }, by_cases hbx : x = b, { simp [hbx] }, simp [hab, hax, hbx, swap_apply_of_ne_of_ne] end namespace perm @[simp] lemma sum_congr_swap_refl {α β : Sort*} [decidable_eq α] [decidable_eq β] (i j : α) : equiv.perm.sum_congr (equiv.swap i j) (equiv.refl β) = equiv.swap (sum.inl i) (sum.inl j) := begin ext x, cases x, { simp [sum.map, swap_apply_def], split_ifs; refl}, { simp [sum.map, swap_apply_of_ne_of_ne] }, end @[simp] lemma sum_congr_refl_swap {α β : Sort*} [decidable_eq α] [decidable_eq β] (i j : β) : equiv.perm.sum_congr (equiv.refl α) (equiv.swap i j) = equiv.swap (sum.inr i) (sum.inr j) := begin ext x, cases x, { simp [sum.map, swap_apply_of_ne_of_ne] }, { simp [sum.map, swap_apply_def], split_ifs; refl}, end end perm /-- Augment an equivalence with a prescribed mapping `f a = b` -/ def set_value (f : α ≃ β) (a : α) (b : β) : α ≃ β := (swap a (f.symm b)).trans f @[simp] theorem set_value_eq (f : α ≃ β) (a : α) (b : β) : set_value f a b a = b := by { dsimp [set_value], simp [swap_apply_left] } end swap end equiv namespace function.involutive /-- Convert an involutive function `f` to a permutation with `to_fun = inv_fun = f`. -/ def to_perm (f : α → α) (h : involutive f) : equiv.perm α := ⟨f, f, h.left_inverse, h.right_inverse⟩ @[simp] lemma coe_to_perm {f : α → α} (h : involutive f) : (h.to_perm f : α → α) = f := rfl @[simp] lemma to_perm_symm {f : α → α} (h : involutive f) : (h.to_perm f).symm = h.to_perm f := rfl lemma to_perm_involutive {f : α → α} (h : involutive f) : involutive (h.to_perm f) := h end function.involutive lemma plift.eq_up_iff_down_eq {x : plift α} {y : α} : x = plift.up y ↔ x.down = y := equiv.plift.eq_symm_apply lemma function.injective.map_swap {α β : Sort*} [decidable_eq α] [decidable_eq β] {f : α → β} (hf : function.injective f) (x y z : α) : f (equiv.swap x y z) = equiv.swap (f x) (f y) (f z) := begin conv_rhs { rw equiv.swap_apply_def }, split_ifs with h₁ h₂, { rw [hf h₁, equiv.swap_apply_left] }, { rw [hf h₂, equiv.swap_apply_right] }, { rw [equiv.swap_apply_of_ne_of_ne (mt (congr_arg f) h₁) (mt (congr_arg f) h₂)] } end namespace equiv section variables (P : α → Sort w) (e : α ≃ β) /-- Transport dependent functions through an equivalence of the base space. -/ @[simps] def Pi_congr_left' : (Π a, P a) ≃ (Π b, P (e.symm b)) := { to_fun := λ f x, f (e.symm x), inv_fun := λ f x, begin rw [← e.symm_apply_apply x], exact f (e x) end, left_inv := λ f, funext $ λ x, eq_of_heq ((eq_rec_heq _ _).trans (by { dsimp, rw e.symm_apply_apply })), right_inv := λ f, funext $ λ x, eq_of_heq ((eq_rec_heq _ _).trans (by { rw e.apply_symm_apply })) } end section variables (P : β → Sort w) (e : α ≃ β) /-- Transporting dependent functions through an equivalence of the base, expressed as a "simplification". -/ def Pi_congr_left : (Π a, P (e a)) ≃ (Π b, P b) := (Pi_congr_left' P e.symm).symm end section variables {W : α → Sort w} {Z : β → Sort z} (h₁ : α ≃ β) (h₂ : Π a : α, (W a ≃ Z (h₁ a))) /-- Transport dependent functions through an equivalence of the base spaces and a family of equivalences of the matching fibers. -/ def Pi_congr : (Π a, W a) ≃ (Π b, Z b) := (equiv.Pi_congr_right h₂).trans (equiv.Pi_congr_left _ h₁) @[simp] lemma coe_Pi_congr_symm : ((h₁.Pi_congr h₂).symm : (Π b, Z b) → (Π a, W a)) = λ f a, (h₂ a).symm (f (h₁ a)) := rfl lemma Pi_congr_symm_apply (f : Π b, Z b) : (h₁.Pi_congr h₂).symm f = λ a, (h₂ a).symm (f (h₁ a)) := rfl @[simp] lemma Pi_congr_apply_apply (f : Π a, W a) (a : α) : h₁.Pi_congr h₂ f (h₁ a) = h₂ a (f a) := begin change cast _ ((h₂ (h₁.symm (h₁ a))) (f (h₁.symm (h₁ a)))) = (h₂ a) (f a), generalize_proofs hZa, revert hZa, rw h₁.symm_apply_apply a, simp, end end section variables {W : α → Sort w} {Z : β → Sort z} (h₁ : α ≃ β) (h₂ : Π b : β, (W (h₁.symm b) ≃ Z b)) /-- Transport dependent functions through an equivalence of the base spaces and a family of equivalences of the matching fibres. -/ def Pi_congr' : (Π a, W a) ≃ (Π b, Z b) := (Pi_congr h₁.symm (λ b, (h₂ b).symm)).symm @[simp] lemma coe_Pi_congr' : (h₁.Pi_congr' h₂ : (Π a, W a) → (Π b, Z b)) = λ f b, h₂ b $ f $ h₁.symm b := rfl lemma Pi_congr'_apply (f : Π a, W a) : h₁.Pi_congr' h₂ f = λ b, h₂ b $ f $ h₁.symm b := rfl @[simp] lemma Pi_congr'_symm_apply_symm_apply (f : Π b, Z b) (b : β) : (h₁.Pi_congr' h₂).symm f (h₁.symm b) = (h₂ b).symm (f b) := begin change cast _ ((h₂ (h₁ (h₁.symm b))).symm (f (h₁ (h₁.symm b)))) = (h₂ b).symm (f b), generalize_proofs hWb, revert hWb, generalize hb : h₁ (h₁.symm b) = b', rw h₁.apply_symm_apply b at hb, subst hb, simp, end end section binary_op variables {α₁ β₁ : Type*} (e : α₁ ≃ β₁) (f : α₁ → α₁ → α₁) lemma semiconj_conj (f : α₁ → α₁) : semiconj e f (e.conj f) := λ x, by simp lemma semiconj₂_conj : semiconj₂ e f (e.arrow_congr e.conj f) := λ x y, by simp instance [is_associative α₁ f] : is_associative β₁ (e.arrow_congr (e.arrow_congr e) f) := (e.semiconj₂_conj f).is_associative_right e.surjective instance [is_idempotent α₁ f] : is_idempotent β₁ (e.arrow_congr (e.arrow_congr e) f) := (e.semiconj₂_conj f).is_idempotent_right e.surjective instance [is_left_cancel α₁ f] : is_left_cancel β₁ (e.arrow_congr (e.arrow_congr e) f) := ⟨e.surjective.forall₃.2 $ λ x y z, by simpa using @is_left_cancel.left_cancel _ f _ x y z⟩ instance [is_right_cancel α₁ f] : is_right_cancel β₁ (e.arrow_congr (e.arrow_congr e) f) := ⟨e.surjective.forall₃.2 $ λ x y z, by simpa using @is_right_cancel.right_cancel _ f _ x y z⟩ end binary_op end equiv lemma function.injective.swap_apply [decidable_eq α] [decidable_eq β] {f : α → β} (hf : function.injective f) (x y z : α) : equiv.swap (f x) (f y) (f z) = f (equiv.swap x y z) := begin by_cases hx : z = x, by simp [hx], by_cases hy : z = y, by simp [hy], rw [equiv.swap_apply_of_ne_of_ne hx hy, equiv.swap_apply_of_ne_of_ne (hf.ne hx) (hf.ne hy)] end lemma function.injective.swap_comp [decidable_eq α] [decidable_eq β] {f : α → β} (hf : function.injective f) (x y : α) : equiv.swap (f x) (f y) ∘ f = f ∘ equiv.swap x y := funext $ λ z, hf.swap_apply _ _ _ /-- If `α` is a subsingleton, then it is equivalent to `α × α`. -/ def subsingleton_prod_self_equiv {α : Type*} [subsingleton α] : α × α ≃ α := { to_fun := λ p, p.1, inv_fun := λ a, (a, a), left_inv := λ p, subsingleton.elim _ _, right_inv := λ p, subsingleton.elim _ _, } /-- To give an equivalence between two subsingleton types, it is sufficient to give any two functions between them. -/ def equiv_of_subsingleton_of_subsingleton [subsingleton α] [subsingleton β] (f : α → β) (g : β → α) : α ≃ β := { to_fun := f, inv_fun := g, left_inv := λ _, subsingleton.elim _ _, right_inv := λ _, subsingleton.elim _ _ } /-- A nonempty subsingleton type is (noncomputably) equivalent to `punit`. -/ noncomputable def equiv.punit_of_nonempty_of_subsingleton {α : Sort*} [h : nonempty α] [subsingleton α] : α ≃ punit.{v} := equiv_of_subsingleton_of_subsingleton (λ _, punit.star) (λ _, h.some) /-- `unique (unique α)` is equivalent to `unique α`. -/ def unique_unique_equiv : unique (unique α) ≃ unique α := equiv_of_subsingleton_of_subsingleton (λ h, h.default) (λ h, { default := h, uniq := λ _, subsingleton.elim _ _ }) namespace function lemma update_comp_equiv {α β α' : Sort*} [decidable_eq α'] [decidable_eq α] (f : α → β) (g : α' ≃ α) (a : α) (v : β) : update f a v ∘ g = update (f ∘ g) (g.symm a) v := by rw [← update_comp_eq_of_injective _ g.injective, g.apply_symm_apply] lemma update_apply_equiv_apply {α β α' : Sort*} [decidable_eq α'] [decidable_eq α] (f : α → β) (g : α' ≃ α) (a : α) (v : β) (a' : α') : update f a v (g a') = update (f ∘ g) (g.symm a) v a' := congr_fun (update_comp_equiv f g a v) a' lemma Pi_congr_left'_update [decidable_eq α] [decidable_eq β] (P : α → Sort*) (e : α ≃ β) (f : Π a, P a) (b : β) (x : P (e.symm b)) : e.Pi_congr_left' P (update f (e.symm b) x) = update (e.Pi_congr_left' P f) b x := begin ext b', rcases eq_or_ne b' b with rfl | h, { simp, }, { simp [h], }, end lemma Pi_congr_left'_symm_update [decidable_eq α] [decidable_eq β] (P : α → Sort*) (e : α ≃ β) (f : Π b, P (e.symm b)) (b : β) (x : P (e.symm b)) : (e.Pi_congr_left' P).symm (update f b x) = update ((e.Pi_congr_left' P).symm f) (e.symm b) x := by simp [(e.Pi_congr_left' P).symm_apply_eq, Pi_congr_left'_update] end function
5e1c2e6e04241f707c4d02f568d4fcff73a7d6f3
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/topology/subset_properties.lean
97d583e2dacd988e37ad06b80d5d6b677efe9e49
[ "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
92,508
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, Yury Kudryashov -/ import order.filter.pi import topology.bases import data.finset.order import data.set.accumulate import data.set.bool_indicator import topology.bornology.basic import topology.locally_finite import order.minimal /-! # Properties of subsets of topological spaces > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file we define various properties of subsets of a topological space, and some classes on topological spaces. ## Main definitions We define the following properties for sets in a topological space: * `is_compact`: each open cover has a finite subcover. This is defined in mathlib using filters. The main property of a compact set is `is_compact.elim_finite_subcover`. * `is_clopen`: a set that is both open and closed. * `is_irreducible`: a nonempty set that has contains no non-trivial pair of disjoint opens. See also the section below in the module doc. For each of these definitions (except for `is_clopen`), we also have a class stating that the whole space satisfies that property: `compact_space`, `irreducible_space` Furthermore, we have three more classes: * `locally_compact_space`: for every point `x`, every open neighborhood of `x` contains a compact neighborhood of `x`. The definition is formulated in terms of the neighborhood filter. * `sigma_compact_space`: a space that is the union of a countably many compact subspaces; * `noncompact_space`: a space that is not a compact space. ## On the definition of irreducible and connected sets/spaces In informal mathematics, irreducible spaces are assumed to be nonempty. We formalise the predicate without that assumption as `is_preirreducible`. In other words, the only difference is whether the empty space counts as irreducible. There are good reasons to consider the empty space to be “too simple to be simple” See also https://ncatlab.org/nlab/show/too+simple+to+be+simple, and in particular https://ncatlab.org/nlab/show/too+simple+to+be+simple#relationship_to_biased_definitions. -/ open set filter classical topological_space open_locale classical topology filter universes u v variables {α : Type u} {β : Type v} {ι : Type*} {π : ι → Type*} variables [topological_space α] [topological_space β] {s t : set α} /- compact sets -/ section compact /-- A set `s` is compact if for every nontrivial filter `f` that contains `s`, there exists `a ∈ s` such that every set of `f` meets every neighborhood of `a`. -/ def is_compact (s : set α) := ∀ ⦃f⦄ [ne_bot f], f ≤ 𝓟 s → ∃ a ∈ s, cluster_pt a f /-- The complement to a compact set belongs to a filter `f` if it belongs to each filter `𝓝 a ⊓ f`, `a ∈ s`. -/ lemma is_compact.compl_mem_sets (hs : is_compact s) {f : filter α} (hf : ∀ a ∈ s, sᶜ ∈ 𝓝 a ⊓ f) : sᶜ ∈ f := begin contrapose! hf, simp only [not_mem_iff_inf_principal_compl, compl_compl, inf_assoc, ← exists_prop] at hf ⊢, exact @hs _ hf inf_le_right end /-- The complement to a compact set belongs to a filter `f` if each `a ∈ s` has a neighborhood `t` within `s` such that `tᶜ` belongs to `f`. -/ lemma is_compact.compl_mem_sets_of_nhds_within (hs : is_compact s) {f : filter α} (hf : ∀ a ∈ s, ∃ t ∈ 𝓝[s] a, tᶜ ∈ f) : sᶜ ∈ f := begin refine hs.compl_mem_sets (λ a ha, _), rcases hf a ha with ⟨t, ht, hst⟩, replace ht := mem_inf_principal.1 ht, apply mem_inf_of_inter ht hst, rintros x ⟨h₁, h₂⟩ hs, exact h₂ (h₁ hs) end /-- If `p : set α → Prop` is stable under restriction and union, and each point `x` of a compact set `s` has a neighborhood `t` within `s` such that `p t`, then `p s` holds. -/ @[elab_as_eliminator] lemma is_compact.induction_on {s : set α} (hs : is_compact s) {p : set α → Prop} (he : p ∅) (hmono : ∀ ⦃s t⦄, s ⊆ t → p t → p s) (hunion : ∀ ⦃s t⦄, p s → p t → p (s ∪ t)) (hnhds : ∀ x ∈ s, ∃ t ∈ 𝓝[s] x, p t) : p s := let f : filter α := { sets := {t | p tᶜ}, univ_sets := by simpa, sets_of_superset := λ t₁ t₂ ht₁ ht, hmono (compl_subset_compl.2 ht) ht₁, inter_sets := λ t₁ t₂ ht₁ ht₂, by simp [compl_inter, hunion ht₁ ht₂] } in have sᶜ ∈ f, from hs.compl_mem_sets_of_nhds_within (by simpa using hnhds), by simpa /-- The intersection of a compact set and a closed set is a compact set. -/ lemma is_compact.inter_right (hs : is_compact s) (ht : is_closed t) : is_compact (s ∩ t) := begin introsI f hnf hstf, obtain ⟨a, hsa, ha⟩ : ∃ a ∈ s, cluster_pt a f := hs (le_trans hstf (le_principal_iff.2 (inter_subset_left _ _))), have : a ∈ t := (ht.mem_of_nhds_within_ne_bot $ ha.mono $ le_trans hstf (le_principal_iff.2 (inter_subset_right _ _))), exact ⟨a, ⟨hsa, this⟩, ha⟩ end /-- The intersection of a closed set and a compact set is a compact set. -/ lemma is_compact.inter_left (ht : is_compact t) (hs : is_closed s) : is_compact (s ∩ t) := inter_comm t s ▸ ht.inter_right hs /-- The set difference of a compact set and an open set is a compact set. -/ lemma is_compact.diff (hs : is_compact s) (ht : is_open t) : is_compact (s \ t) := hs.inter_right (is_closed_compl_iff.mpr ht) /-- A closed subset of a compact set is a compact set. -/ lemma is_compact_of_is_closed_subset (hs : is_compact s) (ht : is_closed t) (h : t ⊆ s) : is_compact t := inter_eq_self_of_subset_right h ▸ hs.inter_right ht lemma is_compact.image_of_continuous_on {f : α → β} (hs : is_compact s) (hf : continuous_on f s) : is_compact (f '' s) := begin intros l lne ls, have : ne_bot (l.comap f ⊓ 𝓟 s) := comap_inf_principal_ne_bot_of_image_mem lne (le_principal_iff.1 ls), obtain ⟨a, has, ha⟩ : ∃ a ∈ s, cluster_pt a (l.comap f ⊓ 𝓟 s) := @@hs this inf_le_right, use [f a, mem_image_of_mem f has], have : tendsto f (𝓝 a ⊓ (comap f l ⊓ 𝓟 s)) (𝓝 (f a) ⊓ l), { convert (hf a has).inf (@tendsto_comap _ _ f l) using 1, rw nhds_within, ac_refl }, exact @@tendsto.ne_bot _ this ha, end lemma is_compact.image {f : α → β} (hs : is_compact s) (hf : continuous f) : is_compact (f '' s) := hs.image_of_continuous_on hf.continuous_on lemma is_compact.adherence_nhdset {f : filter α} (hs : is_compact s) (hf₂ : f ≤ 𝓟 s) (ht₁ : is_open t) (ht₂ : ∀ a ∈ s, cluster_pt a f → a ∈ t) : t ∈ f := classical.by_cases mem_of_eq_bot $ assume : f ⊓ 𝓟 tᶜ ≠ ⊥, let ⟨a, ha, (hfa : cluster_pt a $ f ⊓ 𝓟 tᶜ)⟩ := @@hs ⟨this⟩ $ inf_le_of_left_le hf₂ in have a ∈ t, from ht₂ a ha (hfa.of_inf_left), have tᶜ ∩ t ∈ 𝓝[tᶜ] a, from inter_mem_nhds_within _ (is_open.mem_nhds ht₁ this), have A : 𝓝[tᶜ] a = ⊥, from empty_mem_iff_bot.1 $ compl_inter_self t ▸ this, have 𝓝[tᶜ] a ≠ ⊥, from hfa.of_inf_right.ne, absurd A this lemma is_compact_iff_ultrafilter_le_nhds : is_compact s ↔ (∀ f : ultrafilter α, ↑f ≤ 𝓟 s → ∃ a ∈ s, ↑f ≤ 𝓝 a) := begin refine (forall_ne_bot_le_iff _).trans _, { rintro f g hle ⟨a, has, haf⟩, exact ⟨a, has, haf.mono hle⟩ }, { simp only [ultrafilter.cluster_pt_iff] } end alias is_compact_iff_ultrafilter_le_nhds ↔ is_compact.ultrafilter_le_nhds _ /-- For every open directed cover of a compact set, there exists a single element of the cover which itself includes the set. -/ lemma is_compact.elim_directed_cover {ι : Type v} [hι : nonempty ι] (hs : is_compact s) (U : ι → set α) (hUo : ∀ i, is_open (U i)) (hsU : s ⊆ ⋃ i, U i) (hdU : directed (⊆) U) : ∃ i, s ⊆ U i := hι.elim $ λ i₀, is_compact.induction_on hs ⟨i₀, empty_subset _⟩ (λ s₁ s₂ hs ⟨i, hi⟩, ⟨i, subset.trans hs hi⟩) (λ s₁ s₂ ⟨i, hi⟩ ⟨j, hj⟩, let ⟨k, hki, hkj⟩ := hdU i j in ⟨k, union_subset (subset.trans hi hki) (subset.trans hj hkj)⟩) (λ x hx, let ⟨i, hi⟩ := mem_Union.1 (hsU hx) in ⟨U i, mem_nhds_within_of_mem_nhds (is_open.mem_nhds (hUo i) hi), i, subset.refl _⟩) /-- For every open cover of a compact set, there exists a finite subcover. -/ lemma is_compact.elim_finite_subcover {ι : Type v} (hs : is_compact s) (U : ι → set α) (hUo : ∀ i, is_open (U i)) (hsU : s ⊆ ⋃ i, U i) : ∃ t : finset ι, s ⊆ ⋃ i ∈ t, U i := hs.elim_directed_cover _ (λ t, is_open_bUnion $ λ i _, hUo i) (Union_eq_Union_finset U ▸ hsU) (directed_of_sup $ λ t₁ t₂ h, bUnion_subset_bUnion_left h) lemma is_compact.elim_nhds_subcover' (hs : is_compact s) (U : Π x ∈ s, set α) (hU : ∀ x ∈ s, U x ‹x ∈ s› ∈ 𝓝 x) : ∃ t : finset s, s ⊆ ⋃ x ∈ t, U (x : s) x.2 := (hs.elim_finite_subcover (λ x : s, interior (U x x.2)) (λ x, is_open_interior) (λ x hx, mem_Union.2 ⟨⟨x, hx⟩, mem_interior_iff_mem_nhds.2 $ hU _ _⟩)).imp $ λ t ht, subset.trans ht $ Union₂_mono $ λ _ _, interior_subset lemma is_compact.elim_nhds_subcover (hs : is_compact s) (U : α → set α) (hU : ∀ x ∈ s, U x ∈ 𝓝 x) : ∃ t : finset α, (∀ x ∈ t, x ∈ s) ∧ s ⊆ ⋃ x ∈ t, U x := let ⟨t, ht⟩ := hs.elim_nhds_subcover' (λ x _, U x) hU in ⟨t.image coe, λ x hx, let ⟨y, hyt, hyx⟩ := finset.mem_image.1 hx in hyx ▸ y.2, by rwa finset.set_bUnion_finset_image⟩ /-- The neighborhood filter of a compact set is disjoint with a filter `l` if and only if the neighborhood filter of each point of this set is disjoint with `l`. -/ lemma is_compact.disjoint_nhds_set_left {l : filter α} (hs : is_compact s) : disjoint (𝓝ˢ s) l ↔ ∀ x ∈ s, disjoint (𝓝 x) l := begin refine ⟨λ h x hx, h.mono_left $ nhds_le_nhds_set hx, λ H, _⟩, choose! U hxU hUl using λ x hx, (nhds_basis_opens x).disjoint_iff_left.1 (H x hx), choose hxU hUo using hxU, rcases hs.elim_nhds_subcover U (λ x hx, (hUo x hx).mem_nhds (hxU x hx)) with ⟨t, hts, hst⟩, refine (has_basis_nhds_set _).disjoint_iff_left.2 ⟨⋃ x ∈ t, U x, ⟨is_open_bUnion $ λ x hx, hUo x (hts x hx), hst⟩, _⟩, rw [compl_Union₂, bInter_finset_mem], exact λ x hx, hUl x (hts x hx) end /-- A filter `l` is disjoint with the neighborhood filter of a compact set if and only if it is disjoint with the neighborhood filter of each point of this set. -/ lemma is_compact.disjoint_nhds_set_right {l : filter α} (hs : is_compact s) : disjoint l (𝓝ˢ s) ↔ ∀ x ∈ s, disjoint l (𝓝 x) := by simpa only [disjoint.comm] using hs.disjoint_nhds_set_left /-- For every directed family of closed sets whose intersection avoids a compact set, there exists a single element of the family which itself avoids this compact set. -/ lemma is_compact.elim_directed_family_closed {ι : Type v} [hι : nonempty ι] (hs : is_compact s) (Z : ι → set α) (hZc : ∀ i, is_closed (Z i)) (hsZ : s ∩ (⋂ i, Z i) = ∅) (hdZ : directed (⊇) Z) : ∃ i : ι, s ∩ Z i = ∅ := let ⟨t, ht⟩ := hs.elim_directed_cover (compl ∘ Z) (λ i, (hZc i).is_open_compl) (by simpa only [subset_def, not_forall, eq_empty_iff_forall_not_mem, mem_Union, exists_prop, mem_inter_iff, not_and, iff_self, mem_Inter, mem_compl_iff] using hsZ) (hdZ.mono_comp _ $ λ _ _, compl_subset_compl.mpr) in ⟨t, by simpa only [subset_def, not_forall, eq_empty_iff_forall_not_mem, mem_Union, exists_prop, mem_inter_iff, not_and, iff_self, mem_Inter, mem_compl_iff] using ht⟩ /-- For every family of closed sets whose intersection avoids a compact set, there exists a finite subfamily whose intersection avoids this compact set. -/ lemma is_compact.elim_finite_subfamily_closed {s : set α} {ι : Type v} (hs : is_compact s) (Z : ι → set α) (hZc : ∀ i, is_closed (Z i)) (hsZ : s ∩ (⋂ i, Z i) = ∅) : ∃ t : finset ι, s ∩ (⋂ i ∈ t, Z i) = ∅ := let ⟨t, ht⟩ := hs.elim_finite_subcover (λ i, (Z i)ᶜ) (λ i, (hZc i).is_open_compl) (by simpa only [subset_def, not_forall, eq_empty_iff_forall_not_mem, mem_Union, exists_prop, mem_inter_iff, not_and, iff_self, mem_Inter, mem_compl_iff] using hsZ) in ⟨t, by simpa only [subset_def, not_forall, eq_empty_iff_forall_not_mem, mem_Union, exists_prop, mem_inter_iff, not_and, iff_self, mem_Inter, mem_compl_iff] using ht⟩ /-- If `s` is a compact set in a topological space `α` and `f : ι → set α` is a locally finite family of sets, then `f i ∩ s` is nonempty only for a finitely many `i`. -/ lemma locally_finite.finite_nonempty_inter_compact {ι : Type*} {f : ι → set α} (hf : locally_finite f) {s : set α} (hs : is_compact s) : {i | (f i ∩ s).nonempty}.finite := begin choose U hxU hUf using hf, rcases hs.elim_nhds_subcover U (λ x _, hxU x) with ⟨t, -, hsU⟩, refine (t.finite_to_set.bUnion (λ x _, hUf x)).subset _, rintro i ⟨x, hx⟩, rcases mem_Union₂.1 (hsU hx.2) with ⟨c, hct, hcx⟩, exact mem_bUnion hct ⟨x, hx.1, hcx⟩ end /-- To show that a compact set intersects the intersection of a family of closed sets, it is sufficient to show that it intersects every finite subfamily. -/ lemma is_compact.inter_Inter_nonempty {s : set α} {ι : Type v} (hs : is_compact s) (Z : ι → set α) (hZc : ∀ i, is_closed (Z i)) (hsZ : ∀ t : finset ι, (s ∩ ⋂ i ∈ t, Z i).nonempty) : (s ∩ ⋂ i, Z i).nonempty := begin simp only [nonempty_iff_ne_empty] at hsZ ⊢, apply mt (hs.elim_finite_subfamily_closed Z hZc), push_neg, exact hsZ end /-- Cantor's intersection theorem: the intersection of a directed family of nonempty compact closed sets is nonempty. -/ lemma is_compact.nonempty_Inter_of_directed_nonempty_compact_closed {ι : Type v} [hι : nonempty ι] (Z : ι → set α) (hZd : directed (⊇) Z) (hZn : ∀ i, (Z i).nonempty) (hZc : ∀ i, is_compact (Z i)) (hZcl : ∀ i, is_closed (Z i)) : (⋂ i, Z i).nonempty := begin let i₀ := hι.some, suffices : (Z i₀ ∩ ⋂ i, Z i).nonempty, by rwa inter_eq_right_iff_subset.mpr (Inter_subset _ i₀) at this, simp only [nonempty_iff_ne_empty] at hZn ⊢, apply mt ((hZc i₀).elim_directed_family_closed Z hZcl), push_neg, simp only [← nonempty_iff_ne_empty] at hZn ⊢, refine ⟨hZd, λ i, _⟩, rcases hZd i₀ i with ⟨j, hji₀, hji⟩, exact (hZn j).mono (subset_inter hji₀ hji) end /-- Cantor's intersection theorem for sequences indexed by `ℕ`: the intersection of a decreasing sequence of nonempty compact closed sets is nonempty. -/ lemma is_compact.nonempty_Inter_of_sequence_nonempty_compact_closed (Z : ℕ → set α) (hZd : ∀ i, Z (i+1) ⊆ Z i) (hZn : ∀ i, (Z i).nonempty) (hZ0 : is_compact (Z 0)) (hZcl : ∀ i, is_closed (Z i)) : (⋂ i, Z i).nonempty := have Zmono : antitone Z := antitone_nat_of_succ_le hZd, have hZd : directed (⊇) Z, from directed_of_sup Zmono, have ∀ i, Z i ⊆ Z 0, from assume i, Zmono $ zero_le i, have hZc : ∀ i, is_compact (Z i), from assume i, is_compact_of_is_closed_subset hZ0 (hZcl i) (this i), is_compact.nonempty_Inter_of_directed_nonempty_compact_closed Z hZd hZn hZc hZcl /-- For every open cover of a compact set, there exists a finite subcover. -/ lemma is_compact.elim_finite_subcover_image {b : set ι} {c : ι → set α} (hs : is_compact s) (hc₁ : ∀ i ∈ b, is_open (c i)) (hc₂ : s ⊆ ⋃ i ∈ b, c i) : ∃ b' ⊆ b, set.finite b' ∧ s ⊆ ⋃ i ∈ b', c i := begin rcases hs.elim_finite_subcover (λ i, c i : b → set α) _ _ with ⟨d, hd⟩; [skip, simpa using hc₁, simpa using hc₂], refine ⟨↑(d.image coe), _, finset.finite_to_set _, _⟩, { simp }, { rwa [finset.coe_image, bUnion_image] } end /-- A set `s` is compact if for every family of closed sets whose intersection avoids `s`, there exists a finite subfamily whose intersection avoids `s`. -/ theorem is_compact_of_finite_subfamily_closed (h : Π {ι : Type u} (Z : ι → (set α)), (∀ i, is_closed (Z i)) → s ∩ (⋂ i, Z i) = ∅ → (∃ (t : finset ι), s ∩ (⋂ i ∈ t, Z i) = ∅)) : is_compact s := assume f hfn hfs, classical.by_contradiction $ assume : ¬ (∃ x ∈ s, cluster_pt x f), have hf : ∀ x ∈ s, 𝓝 x ⊓ f = ⊥, by simpa only [cluster_pt, not_exists, not_not, ne_bot_iff], have ¬ ∃ x ∈ s, ∀ t ∈ f.sets, x ∈ closure t, from assume ⟨x, hxs, hx⟩, have ∅ ∈ 𝓝 x ⊓ f, by rw [empty_mem_iff_bot, hf x hxs], let ⟨t₁, ht₁, t₂, ht₂, ht⟩ := by rw [mem_inf_iff] at this; exact this in have ∅ ∈ 𝓝[t₂] x, by { rw [ht, inter_comm], exact inter_mem_nhds_within _ ht₁ }, have 𝓝[t₂] x = ⊥, by rwa [empty_mem_iff_bot] at this, by simp only [closure_eq_cluster_pts] at hx; exact (hx t₂ ht₂).ne this, let ⟨t, ht⟩ := h (λ i : f.sets, closure i.1) (λ i, is_closed_closure) (by simpa [eq_empty_iff_forall_not_mem, not_exists]) in have (⋂ i ∈ t, subtype.val i) ∈ f, from t.Inter_mem_sets.2 $ assume i hi, i.2, have s ∩ (⋂ i ∈ t, subtype.val i) ∈ f, from inter_mem (le_principal_iff.1 hfs) this, have ∅ ∈ f, from mem_of_superset this $ assume x ⟨hxs, hx⟩, let ⟨i, hit, hxi⟩ := (show ∃ i ∈ t, x ∉ closure (subtype.val i), by { rw [eq_empty_iff_forall_not_mem] at ht, simpa [hxs, not_forall] using ht x }) in have x ∈ closure i.val, from subset_closure (by { rw mem_Inter₂ at hx, exact hx i hit }), show false, from hxi this, hfn.ne $ by rwa [empty_mem_iff_bot] at this /-- A set `s` is compact if for every open cover of `s`, there exists a finite subcover. -/ lemma is_compact_of_finite_subcover (h : Π {ι : Type u} (U : ι → (set α)), (∀ i, is_open (U i)) → s ⊆ (⋃ i, U i) → (∃ (t : finset ι), s ⊆ (⋃ i ∈ t, U i))) : is_compact s := is_compact_of_finite_subfamily_closed $ assume ι Z hZc hsZ, let ⟨t, ht⟩ := h (λ i, (Z i)ᶜ) (assume i, is_open_compl_iff.mpr $ hZc i) (by simpa only [subset_def, not_forall, eq_empty_iff_forall_not_mem, mem_Union, exists_prop, mem_inter_iff, not_and, iff_self, mem_Inter, mem_compl_iff] using hsZ) in ⟨t, by simpa only [subset_def, not_forall, eq_empty_iff_forall_not_mem, mem_Union, exists_prop, mem_inter_iff, not_and, iff_self, mem_Inter, mem_compl_iff] using ht⟩ /-- A set `s` is compact if and only if for every open cover of `s`, there exists a finite subcover. -/ lemma is_compact_iff_finite_subcover : is_compact s ↔ (Π {ι : Type u} (U : ι → (set α)), (∀ i, is_open (U i)) → s ⊆ (⋃ i, U i) → (∃ (t : finset ι), s ⊆ (⋃ i ∈ t, U i))) := ⟨assume hs ι, hs.elim_finite_subcover, is_compact_of_finite_subcover⟩ /-- A set `s` is compact if and only if for every family of closed sets whose intersection avoids `s`, there exists a finite subfamily whose intersection avoids `s`. -/ theorem is_compact_iff_finite_subfamily_closed : is_compact s ↔ (Π {ι : Type u} (Z : ι → (set α)), (∀ i, is_closed (Z i)) → s ∩ (⋂ i, Z i) = ∅ → (∃ (t : finset ι), s ∩ (⋂ i ∈ t, Z i) = ∅)) := ⟨assume hs ι, hs.elim_finite_subfamily_closed, is_compact_of_finite_subfamily_closed⟩ /-- To show that `∀ y ∈ K, P x y` holds for `x` close enough to `x₀` when `K` is compact, it is sufficient to show that for all `y₀ ∈ K` there `P x y` holds for `(x, y)` close enough to `(x₀, y₀)`. -/ lemma is_compact.eventually_forall_of_forall_eventually {x₀ : α} {K : set β} (hK : is_compact K) {P : α → β → Prop} (hP : ∀ y ∈ K, ∀ᶠ (z : α × β) in 𝓝 (x₀, y), P z.1 z.2): ∀ᶠ x in 𝓝 x₀, ∀ y ∈ K, P x y := begin refine hK.induction_on _ _ _ _, { exact eventually_of_forall (λ x y, false.elim) }, { intros s t hst ht, refine ht.mono (λ x h y hys, h y $ hst hys) }, { intros s t hs ht, filter_upwards [hs, ht], rintro x h1 h2 y (hys|hyt), exacts [h1 y hys, h2 y hyt] }, { intros y hyK, specialize hP y hyK, rw [nhds_prod_eq, eventually_prod_iff] at hP, rcases hP with ⟨p, hp, q, hq, hpq⟩, exact ⟨{y | q y}, mem_nhds_within_of_mem_nhds hq, eventually_of_mem hp @hpq⟩ } end @[simp] lemma is_compact_empty : is_compact (∅ : set α) := assume f hnf hsf, not.elim hnf.ne $ empty_mem_iff_bot.1 $ le_principal_iff.1 hsf @[simp] lemma is_compact_singleton {a : α} : is_compact ({a} : set α) := λ f hf hfa, ⟨a, rfl, cluster_pt.of_le_nhds' (hfa.trans $ by simpa only [principal_singleton] using pure_le_nhds a) hf⟩ lemma set.subsingleton.is_compact {s : set α} (hs : s.subsingleton) : is_compact s := subsingleton.induction_on hs is_compact_empty $ λ x, is_compact_singleton lemma set.finite.is_compact_bUnion {s : set ι} {f : ι → set α} (hs : s.finite) (hf : ∀ i ∈ s, is_compact (f i)) : is_compact (⋃ i ∈ s, f i) := is_compact_of_finite_subcover $ assume ι U hUo hsU, have ∀ i : subtype s, ∃ t : finset ι, f i ⊆ (⋃ j ∈ t, U j), from assume ⟨i, hi⟩, (hf i hi).elim_finite_subcover _ hUo (calc f i ⊆ ⋃ i ∈ s, f i : subset_bUnion_of_mem hi ... ⊆ ⋃ j, U j : hsU), let ⟨finite_subcovers, h⟩ := axiom_of_choice this in by haveI : fintype (subtype s) := hs.fintype; exact let t := finset.bUnion finset.univ finite_subcovers in have (⋃ i ∈ s, f i) ⊆ (⋃ i ∈ t, U i), from Union₂_subset $ assume i hi, calc f i ⊆ (⋃ j ∈ finite_subcovers ⟨i, hi⟩, U j) : (h ⟨i, hi⟩) ... ⊆ (⋃ j ∈ t, U j) : bUnion_subset_bUnion_left $ assume j hj, finset.mem_bUnion.mpr ⟨_, finset.mem_univ _, hj⟩, ⟨t, this⟩ lemma finset.is_compact_bUnion (s : finset ι) {f : ι → set α} (hf : ∀ i ∈ s, is_compact (f i)) : is_compact (⋃ i ∈ s, f i) := s.finite_to_set.is_compact_bUnion hf lemma is_compact_accumulate {K : ℕ → set α} (hK : ∀ n, is_compact (K n)) (n : ℕ) : is_compact (accumulate K n) := (finite_le_nat n).is_compact_bUnion $ λ k _, hK k lemma is_compact_Union {f : ι → set α} [finite ι] (h : ∀ i, is_compact (f i)) : is_compact (⋃ i, f i) := by rw ← bUnion_univ; exact finite_univ.is_compact_bUnion (λ i _, h i) lemma set.finite.is_compact (hs : s.finite) : is_compact s := bUnion_of_singleton s ▸ hs.is_compact_bUnion (λ _ _, is_compact_singleton) lemma is_compact.finite_of_discrete [discrete_topology α] {s : set α} (hs : is_compact s) : s.finite := begin have : ∀ x : α, ({x} : set α) ∈ 𝓝 x, by simp [nhds_discrete], rcases hs.elim_nhds_subcover (λ x, {x}) (λ x hx, this x) with ⟨t, hts, hst⟩, simp only [← t.set_bUnion_coe, bUnion_of_singleton] at hst, exact t.finite_to_set.subset hst end lemma is_compact_iff_finite [discrete_topology α] {s : set α} : is_compact s ↔ s.finite := ⟨λ h, h.finite_of_discrete, λ h, h.is_compact⟩ lemma is_compact.union (hs : is_compact s) (ht : is_compact t) : is_compact (s ∪ t) := by rw union_eq_Union; exact is_compact_Union (λ b, by cases b; assumption) lemma is_compact.insert (hs : is_compact s) (a) : is_compact (insert a s) := is_compact_singleton.union hs /-- If `V : ι → set α` is a decreasing family of closed compact sets then any neighborhood of `⋂ i, V i` contains some `V i`. We assume each `V i` is compact *and* closed because `α` is not assumed to be Hausdorff. See `exists_subset_nhd_of_compact` for version assuming this. -/ lemma exists_subset_nhds_of_is_compact' {ι : Type*} [nonempty ι] {V : ι → set α} (hV : directed (⊇) V) (hV_cpct : ∀ i, is_compact (V i)) (hV_closed : ∀ i, is_closed (V i)) {U : set α} (hU : ∀ x ∈ ⋂ i, V i, U ∈ 𝓝 x) : ∃ i, V i ⊆ U := begin obtain ⟨W, hsubW, W_op, hWU⟩ := exists_open_set_nhds hU, rsuffices ⟨i, hi⟩ : ∃ i, V i ⊆ W, { exact ⟨i, hi.trans hWU⟩ }, by_contra' H, replace H : ∀ i, (V i ∩ Wᶜ).nonempty := λ i, set.inter_compl_nonempty_iff.mpr (H i), have : (⋂ i, V i ∩ Wᶜ).nonempty, { refine is_compact.nonempty_Inter_of_directed_nonempty_compact_closed _ (λ i j, _) H (λ i, (hV_cpct i).inter_right W_op.is_closed_compl) (λ i, (hV_closed i).inter W_op.is_closed_compl), rcases hV i j with ⟨k, hki, hkj⟩, refine ⟨k, ⟨λ x, _, λ x, _⟩⟩ ; simp only [and_imp, mem_inter_iff, mem_compl_iff] ; tauto }, have : ¬ (⋂ (i : ι), V i) ⊆ W, by simpa [← Inter_inter, inter_compl_nonempty_iff], contradiction end /-- If `α` has a basis consisting of compact opens, then an open set in `α` is compact open iff it is a finite union of some elements in the basis -/ lemma is_compact_open_iff_eq_finite_Union_of_is_topological_basis (b : ι → set α) (hb : is_topological_basis (set.range b)) (hb' : ∀ i, is_compact (b i)) (U : set α) : is_compact U ∧ is_open U ↔ ∃ (s : set ι), s.finite ∧ U = ⋃ i ∈ s, b i := begin classical, split, { rintro ⟨h₁, h₂⟩, obtain ⟨β, f, e, hf⟩ := hb.open_eq_Union h₂, choose f' hf' using hf, have : b ∘ f' = f := funext hf', subst this, obtain ⟨t, ht⟩ := h₁.elim_finite_subcover (b ∘ f') (λ i, hb.is_open (set.mem_range_self _)) (by rw e), refine ⟨t.image f', set.finite.intro infer_instance, le_antisymm _ _⟩, { refine set.subset.trans ht _, simp only [set.Union_subset_iff, coe_coe], intros i hi, erw ← set.Union_subtype (λ x : ι, x ∈ t.image f') (λ i, b i.1), exact set.subset_Union (λ i : t.image f', b i) ⟨_, finset.mem_image_of_mem _ hi⟩ }, { apply set.Union₂_subset, rintro i hi, obtain ⟨j, hj, rfl⟩ := finset.mem_image.mp hi, rw e, exact set.subset_Union (b ∘ f') j } }, { rintro ⟨s, hs, rfl⟩, split, { exact hs.is_compact_bUnion (λ i _, hb' i) }, { apply is_open_bUnion, intros i hi, exact hb.is_open (set.mem_range_self _) } }, end namespace filter /-- `filter.cocompact` is the filter generated by complements to compact sets. -/ def cocompact (α : Type*) [topological_space α] : filter α := ⨅ (s : set α) (hs : is_compact s), 𝓟 (sᶜ) lemma has_basis_cocompact : (cocompact α).has_basis is_compact compl := has_basis_binfi_principal' (λ s hs t ht, ⟨s ∪ t, hs.union ht, compl_subset_compl.2 (subset_union_left s t), compl_subset_compl.2 (subset_union_right s t)⟩) ⟨∅, is_compact_empty⟩ lemma mem_cocompact : s ∈ cocompact α ↔ ∃ t, is_compact t ∧ tᶜ ⊆ s := has_basis_cocompact.mem_iff.trans $ exists_congr $ λ t, exists_prop lemma mem_cocompact' : s ∈ cocompact α ↔ ∃ t, is_compact t ∧ sᶜ ⊆ t := mem_cocompact.trans $ exists_congr $ λ t, and_congr_right $ λ ht, compl_subset_comm lemma _root_.is_compact.compl_mem_cocompact (hs : is_compact s) : sᶜ ∈ filter.cocompact α := has_basis_cocompact.mem_of_mem hs lemma cocompact_le_cofinite : cocompact α ≤ cofinite := λ s hs, compl_compl s ▸ hs.is_compact.compl_mem_cocompact lemma cocompact_eq_cofinite (α : Type*) [topological_space α] [discrete_topology α] : cocompact α = cofinite := has_basis_cocompact.eq_of_same_basis $ by { convert has_basis_cofinite, ext s, exact is_compact_iff_finite } @[simp] lemma _root_.nat.cocompact_eq : cocompact ℕ = at_top := (cocompact_eq_cofinite ℕ).trans nat.cofinite_eq_at_top lemma tendsto.is_compact_insert_range_of_cocompact {f : α → β} {b} (hf : tendsto f (cocompact α) (𝓝 b)) (hfc : continuous f) : is_compact (insert b (range f)) := begin introsI l hne hle, by_cases hb : cluster_pt b l, { exact ⟨b, or.inl rfl, hb⟩ }, simp only [cluster_pt_iff, not_forall, ← not_disjoint_iff_nonempty_inter, not_not] at hb, rcases hb with ⟨s, hsb, t, htl, hd⟩, rcases mem_cocompact.1 (hf hsb) with ⟨K, hKc, hKs⟩, have : f '' K ∈ l, { filter_upwards [htl, le_principal_iff.1 hle] with y hyt hyf, rcases hyf with (rfl|⟨x, rfl⟩), exacts [(hd.le_bot ⟨mem_of_mem_nhds hsb, hyt⟩).elim, mem_image_of_mem _ (not_not.1 $ λ hxK, hd.le_bot ⟨hKs hxK, hyt⟩)] }, rcases hKc.image hfc (le_principal_iff.2 this) with ⟨y, hy, hyl⟩, exact ⟨y, or.inr $ image_subset_range _ _ hy, hyl⟩ end lemma tendsto.is_compact_insert_range_of_cofinite {f : ι → α} {a} (hf : tendsto f cofinite (𝓝 a)) : is_compact (insert a (range f)) := begin letI : topological_space ι := ⊥, haveI := discrete_topology_bot ι, rw ← cocompact_eq_cofinite at hf, exact hf.is_compact_insert_range_of_cocompact continuous_of_discrete_topology end lemma tendsto.is_compact_insert_range {f : ℕ → α} {a} (hf : tendsto f at_top (𝓝 a)) : is_compact (insert a (range f)) := filter.tendsto.is_compact_insert_range_of_cofinite $ nat.cofinite_eq_at_top.symm ▸ hf /-- `filter.coclosed_compact` is the filter generated by complements to closed compact sets. In a Hausdorff space, this is the same as `filter.cocompact`. -/ def coclosed_compact (α : Type*) [topological_space α] : filter α := ⨅ (s : set α) (h₁ : is_closed s) (h₂ : is_compact s), 𝓟 (sᶜ) lemma has_basis_coclosed_compact : (filter.coclosed_compact α).has_basis (λ s, is_closed s ∧ is_compact s) compl := begin simp only [filter.coclosed_compact, infi_and'], refine has_basis_binfi_principal' _ ⟨∅, is_closed_empty, is_compact_empty⟩, rintro s ⟨hs₁, hs₂⟩ t ⟨ht₁, ht₂⟩, exact ⟨s ∪ t, ⟨⟨hs₁.union ht₁, hs₂.union ht₂⟩, compl_subset_compl.2 (subset_union_left _ _), compl_subset_compl.2 (subset_union_right _ _)⟩⟩ end lemma mem_coclosed_compact : s ∈ coclosed_compact α ↔ ∃ t, is_closed t ∧ is_compact t ∧ tᶜ ⊆ s := by simp [has_basis_coclosed_compact.mem_iff, and_assoc] lemma mem_coclosed_compact' : s ∈ coclosed_compact α ↔ ∃ t, is_closed t ∧ is_compact t ∧ sᶜ ⊆ t := by simp only [mem_coclosed_compact, compl_subset_comm] lemma cocompact_le_coclosed_compact : cocompact α ≤ coclosed_compact α := infi_mono $ λ s, le_infi $ λ _, le_rfl lemma _root_.is_compact.compl_mem_coclosed_compact_of_is_closed (hs : is_compact s) (hs' : is_closed s) : sᶜ ∈ filter.coclosed_compact α := has_basis_coclosed_compact.mem_of_mem ⟨hs', hs⟩ end filter namespace bornology variable (α) /-- Sets that are contained in a compact set form a bornology. Its `cobounded` filter is `filter.cocompact`. See also `bornology.relatively_compact` the bornology of sets with compact closure. -/ def in_compact : bornology α := { cobounded := filter.cocompact α, le_cofinite := filter.cocompact_le_cofinite } variable {α} lemma in_compact.is_bounded_iff : @is_bounded _ (in_compact α) s ↔ ∃ t, is_compact t ∧ s ⊆ t := begin change sᶜ ∈ filter.cocompact α ↔ _, rw filter.mem_cocompact, simp end end bornology section tube_lemma /-- `nhds_contain_boxes s t` means that any open neighborhood of `s × t` in `α × β` includes a product of an open neighborhood of `s` by an open neighborhood of `t`. -/ def nhds_contain_boxes (s : set α) (t : set β) : Prop := ∀ (n : set (α × β)) (hn : is_open n) (hp : s ×ˢ t ⊆ n), ∃ (u : set α) (v : set β), is_open u ∧ is_open v ∧ s ⊆ u ∧ t ⊆ v ∧ u ×ˢ v ⊆ n lemma nhds_contain_boxes.symm {s : set α} {t : set β} : nhds_contain_boxes s t → nhds_contain_boxes t s := assume H n hn hp, let ⟨u, v, uo, vo, su, tv, p⟩ := H (prod.swap ⁻¹' n) (hn.preimage continuous_swap) (by rwa [←image_subset_iff, image_swap_prod]) in ⟨v, u, vo, uo, tv, su, by rwa [←image_subset_iff, image_swap_prod] at p⟩ lemma nhds_contain_boxes.comm {s : set α} {t : set β} : nhds_contain_boxes s t ↔ nhds_contain_boxes t s := iff.intro nhds_contain_boxes.symm nhds_contain_boxes.symm lemma nhds_contain_boxes_of_singleton {x : α} {y : β} : nhds_contain_boxes ({x} : set α) ({y} : set β) := assume n hn hp, let ⟨u, v, uo, vo, xu, yv, hp'⟩ := is_open_prod_iff.mp hn x y (hp $ by simp) in ⟨u, v, uo, vo, by simpa, by simpa, hp'⟩ lemma nhds_contain_boxes_of_compact {s : set α} (hs : is_compact s) (t : set β) (H : ∀ x ∈ s, nhds_contain_boxes ({x} : set α) t) : nhds_contain_boxes s t := assume n hn hp, have ∀ x : s, ∃ uv : set α × set β, is_open uv.1 ∧ is_open uv.2 ∧ {↑x} ⊆ uv.1 ∧ t ⊆ uv.2 ∧ uv.1 ×ˢ uv.2 ⊆ n, from assume ⟨x, hx⟩, have ({x} : set α) ×ˢ t ⊆ n, from subset.trans (prod_mono (by simpa) subset.rfl) hp, let ⟨ux,vx,H1⟩ := H x hx n hn this in ⟨⟨ux,vx⟩,H1⟩, let ⟨uvs, h⟩ := classical.axiom_of_choice this in have us_cover : s ⊆ ⋃ i, (uvs i).1, from assume x hx, subset_Union _ ⟨x,hx⟩ (by simpa using (h ⟨x,hx⟩).2.2.1), let ⟨s0, s0_cover⟩ := hs.elim_finite_subcover _ (λi, (h i).1) us_cover in let u := ⋃(i ∈ s0), (uvs i).1 in let v := ⋂(i ∈ s0), (uvs i).2 in have is_open u, from is_open_bUnion (λi _, (h i).1), have is_open v, from is_open_bInter s0.finite_to_set (λi _, (h i).2.1), have t ⊆ v, from subset_Inter₂ (λi _, (h i).2.2.2.1), have u ×ˢ v ⊆ n, from assume ⟨x',y'⟩ ⟨hx',hy'⟩, have ∃ i ∈ s0, x' ∈ (uvs i).1, by simpa using hx', let ⟨i,is0,hi⟩ := this in (h i).2.2.2.2 ⟨hi, (bInter_subset_of_mem is0 : v ⊆ (uvs i).2) hy'⟩, ⟨u, v, ‹is_open u›, ‹is_open v›, s0_cover, ‹t ⊆ v›, ‹u ×ˢ v ⊆ n›⟩ /-- If `s` and `t` are compact sets and `n` is an open neighborhood of `s × t`, then there exist open neighborhoods `u ⊇ s` and `v ⊇ t` such that `u × v ⊆ n`. -/ lemma generalized_tube_lemma {s : set α} (hs : is_compact s) {t : set β} (ht : is_compact t) {n : set (α × β)} (hn : is_open n) (hp : s ×ˢ t ⊆ n) : ∃ (u : set α) (v : set β), is_open u ∧ is_open v ∧ s ⊆ u ∧ t ⊆ v ∧ u ×ˢ v ⊆ n := have _, from nhds_contain_boxes_of_compact hs t $ assume x _, nhds_contain_boxes.symm $ nhds_contain_boxes_of_compact ht {x} $ assume y _, nhds_contain_boxes_of_singleton, this n hn hp end tube_lemma /-- Type class for compact spaces. Separation is sometimes included in the definition, especially in the French literature, but we do not include it here. -/ class compact_space (α : Type*) [topological_space α] : Prop := (is_compact_univ : is_compact (univ : set α)) @[priority 10] -- see Note [lower instance priority] instance subsingleton.compact_space [subsingleton α] : compact_space α := ⟨subsingleton_univ.is_compact⟩ lemma is_compact_univ_iff : is_compact (univ : set α) ↔ compact_space α := ⟨λ h, ⟨h⟩, λ h, h.1⟩ lemma is_compact_univ [h : compact_space α] : is_compact (univ : set α) := h.is_compact_univ lemma cluster_point_of_compact [compact_space α] (f : filter α) [ne_bot f] : ∃ x, cluster_pt x f := by simpa using is_compact_univ (show f ≤ 𝓟 univ, by simp) lemma compact_space.elim_nhds_subcover [compact_space α] (U : α → set α) (hU : ∀ x, U x ∈ 𝓝 x) : ∃ t : finset α, (⋃ x ∈ t, U x) = ⊤ := begin obtain ⟨t, -, s⟩ := is_compact.elim_nhds_subcover is_compact_univ U (λ x m, hU x), exact ⟨t, by { rw eq_top_iff, exact s }⟩, end theorem compact_space_of_finite_subfamily_closed (h : Π {ι : Type u} (Z : ι → (set α)), (∀ i, is_closed (Z i)) → (⋂ i, Z i) = ∅ → ∃ (t : finset ι), (⋂ i ∈ t, Z i) = ∅) : compact_space α := { is_compact_univ := begin apply is_compact_of_finite_subfamily_closed, intros ι Z, specialize h Z, simpa using h end } lemma is_closed.is_compact [compact_space α] {s : set α} (h : is_closed s) : is_compact s := is_compact_of_is_closed_subset is_compact_univ h (subset_univ _) /-- `α` is a noncompact topological space if it not a compact space. -/ class noncompact_space (α : Type*) [topological_space α] : Prop := (noncompact_univ [] : ¬is_compact (univ : set α)) export noncompact_space (noncompact_univ) lemma is_compact.ne_univ [noncompact_space α] {s : set α} (hs : is_compact s) : s ≠ univ := λ h, noncompact_univ α (h ▸ hs) instance [noncompact_space α] : ne_bot (filter.cocompact α) := begin refine filter.has_basis_cocompact.ne_bot_iff.2 (λ s hs, _), contrapose hs, rw [not_nonempty_iff_eq_empty, compl_empty_iff] at hs, rw hs, exact noncompact_univ α end @[simp] lemma filter.cocompact_eq_bot [compact_space α] : filter.cocompact α = ⊥ := filter.has_basis_cocompact.eq_bot_iff.mpr ⟨set.univ, is_compact_univ, set.compl_univ⟩ instance [noncompact_space α] : ne_bot (filter.coclosed_compact α) := ne_bot_of_le filter.cocompact_le_coclosed_compact lemma noncompact_space_of_ne_bot (h : ne_bot (filter.cocompact α)) : noncompact_space α := ⟨λ h', (filter.nonempty_of_mem h'.compl_mem_cocompact).ne_empty compl_univ⟩ lemma filter.cocompact_ne_bot_iff : ne_bot (filter.cocompact α) ↔ noncompact_space α := ⟨noncompact_space_of_ne_bot, @filter.cocompact.filter.ne_bot _ _⟩ lemma not_compact_space_iff : ¬compact_space α ↔ noncompact_space α := ⟨λ h₁, ⟨λ h₂, h₁ ⟨h₂⟩⟩, λ ⟨h₁⟩ ⟨h₂⟩, h₁ h₂⟩ instance : noncompact_space ℤ := noncompact_space_of_ne_bot $ by simp only [filter.cocompact_eq_cofinite, filter.cofinite_ne_bot] -- Note: We can't make this into an instance because it loops with `finite.compact_space`. /-- A compact discrete space is finite. -/ lemma finite_of_compact_of_discrete [compact_space α] [discrete_topology α] : finite α := finite.of_finite_univ $ is_compact_univ.finite_of_discrete lemma exists_nhds_ne_ne_bot (α : Type*) [topological_space α] [compact_space α] [infinite α] : ∃ z : α, (𝓝[≠] z).ne_bot := begin by_contra' H, simp_rw not_ne_bot at H, haveI := discrete_topology_iff_nhds_ne.mpr H, exact infinite.not_finite (finite_of_compact_of_discrete : finite α), end lemma finite_cover_nhds_interior [compact_space α] {U : α → set α} (hU : ∀ x, U x ∈ 𝓝 x) : ∃ t : finset α, (⋃ x ∈ t, interior (U x)) = univ := let ⟨t, ht⟩ := is_compact_univ.elim_finite_subcover (λ x, interior (U x)) (λ x, is_open_interior) (λ x _, mem_Union.2 ⟨x, mem_interior_iff_mem_nhds.2 (hU x)⟩) in ⟨t, univ_subset_iff.1 ht⟩ lemma finite_cover_nhds [compact_space α] {U : α → set α} (hU : ∀ x, U x ∈ 𝓝 x) : ∃ t : finset α, (⋃ x ∈ t, U x) = univ := let ⟨t, ht⟩ := finite_cover_nhds_interior hU in ⟨t, univ_subset_iff.1 $ ht.symm.subset.trans $ Union₂_mono $ λ x hx, interior_subset⟩ /-- If `α` is a compact space, then a locally finite family of sets of `α` can have only finitely many nonempty elements. -/ lemma locally_finite.finite_nonempty_of_compact {ι : Type*} [compact_space α] {f : ι → set α} (hf : locally_finite f) : {i | (f i).nonempty}.finite := by simpa only [inter_univ] using hf.finite_nonempty_inter_compact is_compact_univ /-- If `α` is a compact space, then a locally finite family of nonempty sets of `α` can have only finitely many elements, `set.finite` version. -/ lemma locally_finite.finite_of_compact {ι : Type*} [compact_space α] {f : ι → set α} (hf : locally_finite f) (hne : ∀ i, (f i).nonempty) : (univ : set ι).finite := by simpa only [hne] using hf.finite_nonempty_of_compact /-- If `α` is a compact space, then a locally finite family of nonempty sets of `α` can have only finitely many elements, `fintype` version. -/ noncomputable def locally_finite.fintype_of_compact {ι : Type*} [compact_space α] {f : ι → set α} (hf : locally_finite f) (hne : ∀ i, (f i).nonempty) : fintype ι := fintype_of_finite_univ (hf.finite_of_compact hne) /-- The comap of the cocompact filter on `β` by a continuous function `f : α → β` is less than or equal to the cocompact filter on `α`. This is a reformulation of the fact that images of compact sets are compact. -/ lemma filter.comap_cocompact_le {f : α → β} (hf : continuous f) : (filter.cocompact β).comap f ≤ filter.cocompact α := begin rw (filter.has_basis_cocompact.comap f).le_basis_iff filter.has_basis_cocompact, intros t ht, refine ⟨f '' t, ht.image hf, _⟩, simpa using t.subset_preimage_image f end lemma is_compact_range [compact_space α] {f : α → β} (hf : continuous f) : is_compact (range f) := by rw ← image_univ; exact is_compact_univ.image hf lemma is_compact_diagonal [compact_space α] : is_compact (diagonal α) := @range_diag α ▸ is_compact_range (continuous_id.prod_mk continuous_id) /-- If X is is_compact then pr₂ : X × Y → Y is a closed map -/ theorem is_closed_proj_of_is_compact {X : Type*} [topological_space X] [compact_space X] {Y : Type*} [topological_space Y] : is_closed_map (prod.snd : X × Y → Y) := begin set πX := (prod.fst : X × Y → X), set πY := (prod.snd : X × Y → Y), assume C (hC : is_closed C), rw is_closed_iff_cluster_pt at hC ⊢, assume y (y_closure : cluster_pt y $ 𝓟 (πY '' C)), haveI : ne_bot (map πX (comap πY (𝓝 y) ⊓ 𝓟 C)), { suffices : ne_bot (map πY (comap πY (𝓝 y) ⊓ 𝓟 C)), by simpa only [map_ne_bot_iff], convert y_closure, calc map πY (comap πY (𝓝 y) ⊓ 𝓟 C) = 𝓝 y ⊓ map πY (𝓟 C) : filter.push_pull' _ _ _ ... = 𝓝 y ⊓ 𝓟 (πY '' C) : by rw map_principal }, obtain ⟨x, hx⟩ : ∃ x, cluster_pt x (map πX (comap πY (𝓝 y) ⊓ 𝓟 C)), from cluster_point_of_compact _, refine ⟨⟨x, y⟩, _, by simp [πY]⟩, apply hC, rw [cluster_pt, ← filter.map_ne_bot_iff πX], convert hx, calc map πX (𝓝 (x, y) ⊓ 𝓟 C) = map πX (comap πX (𝓝 x) ⊓ comap πY (𝓝 y) ⊓ 𝓟 C) : by rw [nhds_prod_eq, filter.prod] ... = map πX (comap πY (𝓝 y) ⊓ 𝓟 C ⊓ comap πX (𝓝 x)) : by ac_refl ... = map πX (comap πY (𝓝 y) ⊓ 𝓟 C) ⊓ 𝓝 x : by rw filter.push_pull ... = 𝓝 x ⊓ map πX (comap πY (𝓝 y) ⊓ 𝓟 C) : by rw inf_comm end lemma exists_subset_nhds_of_compact_space [compact_space α] {ι : Type*} [nonempty ι] {V : ι → set α} (hV : directed (⊇) V) (hV_closed : ∀ i, is_closed (V i)) {U : set α} (hU : ∀ x ∈ ⋂ i, V i, U ∈ 𝓝 x) : ∃ i, V i ⊆ U := exists_subset_nhds_of_is_compact' hV (λ i, (hV_closed i).is_compact) hV_closed hU /-- If `f : α → β` is an `inducing` map, then the image `f '' s` of a set `s` is compact if and only if the set `s` is closed. -/ lemma inducing.is_compact_iff {f : α → β} (hf : inducing f) {s : set α} : is_compact (f '' s) ↔ is_compact s := begin refine ⟨_, λ hs, hs.image hf.continuous⟩, introsI hs F F_ne_bot F_le, obtain ⟨_, ⟨x, x_in : x ∈ s, rfl⟩, hx : cluster_pt (f x) (map f F)⟩ := hs (calc map f F ≤ map f (𝓟 s) : map_mono F_le ... = 𝓟 (f '' s) : map_principal), use [x, x_in], suffices : (map f (𝓝 x ⊓ F)).ne_bot, by simpa [filter.map_ne_bot_iff], rwa calc map f (𝓝 x ⊓ F) = map f ((comap f $ 𝓝 $ f x) ⊓ F) : by rw hf.nhds_eq_comap ... = 𝓝 (f x) ⊓ map f F : filter.push_pull' _ _ _ end /-- If `f : α → β` is an `embedding` (or more generally, an `inducing` map, see `inducing.is_compact_iff`), then the image `f '' s` of a set `s` is compact if and only if the set `s` is closed. -/ lemma embedding.is_compact_iff_is_compact_image {f : α → β} (hf : embedding f) : is_compact s ↔ is_compact (f '' s) := hf.to_inducing.is_compact_iff.symm /-- The preimage of a compact set under a closed embedding is a compact set. -/ lemma closed_embedding.is_compact_preimage {f : α → β} (hf : closed_embedding f) {K : set β} (hK : is_compact K) : is_compact (f ⁻¹' K) := begin replace hK := hK.inter_right hf.closed_range, rwa [← hf.to_inducing.is_compact_iff, image_preimage_eq_inter_range] end /-- A closed embedding is proper, ie, inverse images of compact sets are contained in compacts. Moreover, the preimage of a compact set is compact, see `closed_embedding.is_compact_preimage`. -/ lemma closed_embedding.tendsto_cocompact {f : α → β} (hf : closed_embedding f) : tendsto f (filter.cocompact α) (filter.cocompact β) := filter.has_basis_cocompact.tendsto_right_iff.mpr $ λ K hK, (hf.is_compact_preimage hK).compl_mem_cocompact lemma is_compact_iff_is_compact_in_subtype {p : α → Prop} {s : set {a // p a}} : is_compact s ↔ is_compact ((coe : _ → α) '' s) := embedding_subtype_coe.is_compact_iff_is_compact_image lemma is_compact_iff_is_compact_univ {s : set α} : is_compact s ↔ is_compact (univ : set s) := by rw [is_compact_iff_is_compact_in_subtype, image_univ, subtype.range_coe]; refl lemma is_compact_iff_compact_space {s : set α} : is_compact s ↔ compact_space s := is_compact_iff_is_compact_univ.trans ⟨λ h, ⟨h⟩, @compact_space.is_compact_univ _ _⟩ lemma is_compact.finite {s : set α} (hs : is_compact s) (hs' : discrete_topology s) : s.finite := finite_coe_iff.mp (@finite_of_compact_of_discrete _ _ (is_compact_iff_compact_space.mp hs) hs') lemma exists_nhds_ne_inf_principal_ne_bot {s : set α} (hs : is_compact s) (hs' : s.infinite) : ∃ z ∈ s, (𝓝[≠] z ⊓ 𝓟 s).ne_bot := begin by_contra' H, simp_rw not_ne_bot at H, exact hs' (hs.finite $ discrete_topology_subtype_iff.mpr H), end protected lemma closed_embedding.noncompact_space [noncompact_space α] {f : α → β} (hf : closed_embedding f) : noncompact_space β := noncompact_space_of_ne_bot hf.tendsto_cocompact.ne_bot protected lemma closed_embedding.compact_space [h : compact_space β] {f : α → β} (hf : closed_embedding f) : compact_space α := by { unfreezingI { contrapose! h, rw not_compact_space_iff at h ⊢ }, exact hf.noncompact_space } lemma is_compact.prod {s : set α} {t : set β} (hs : is_compact s) (ht : is_compact t) : is_compact (s ×ˢ t) := begin rw is_compact_iff_ultrafilter_le_nhds at hs ht ⊢, intros f hfs, rw le_principal_iff at hfs, obtain ⟨a : α, sa : a ∈ s, ha : map prod.fst ↑f ≤ 𝓝 a⟩ := hs (f.map prod.fst) (le_principal_iff.2 $ mem_map.2 $ mem_of_superset hfs (λ x, and.left)), obtain ⟨b : β, tb : b ∈ t, hb : map prod.snd ↑f ≤ 𝓝 b⟩ := ht (f.map prod.snd) (le_principal_iff.2 $ mem_map.2 $ mem_of_superset hfs (λ x, and.right)), rw map_le_iff_le_comap at ha hb, refine ⟨⟨a, b⟩, ⟨sa, tb⟩, _⟩, rw nhds_prod_eq, exact le_inf ha hb end /-- Finite topological spaces are compact. -/ @[priority 100] instance finite.compact_space [finite α] : compact_space α := { is_compact_univ := finite_univ.is_compact } /-- The product of two compact spaces is compact. -/ instance [compact_space α] [compact_space β] : compact_space (α × β) := ⟨by { rw ← univ_prod_univ, exact is_compact_univ.prod is_compact_univ }⟩ /-- The disjoint union of two compact spaces is compact. -/ instance [compact_space α] [compact_space β] : compact_space (α ⊕ β) := ⟨begin rw ← range_inl_union_range_inr, exact (is_compact_range continuous_inl).union (is_compact_range continuous_inr) end⟩ instance [finite ι] [Π i, topological_space (π i)] [∀ i, compact_space (π i)] : compact_space (Σ i, π i) := begin refine ⟨_⟩, rw sigma.univ, exact is_compact_Union (λ i, is_compact_range continuous_sigma_mk), end /-- The coproduct of the cocompact filters on two topological spaces is the cocompact filter on their product. -/ lemma filter.coprod_cocompact : (filter.cocompact α).coprod (filter.cocompact β) = filter.cocompact (α × β) := begin ext S, simp only [mem_coprod_iff, exists_prop, mem_comap, filter.mem_cocompact], split, { rintro ⟨⟨A, ⟨t, ht, hAt⟩, hAS⟩, B, ⟨t', ht', hBt'⟩, hBS⟩, refine ⟨t ×ˢ t', ht.prod ht', _⟩, refine subset.trans _ (union_subset hAS hBS), rw compl_subset_comm at ⊢ hAt hBt', refine subset.trans _ (set.prod_mono hAt hBt'), intros x, simp only [compl_union, mem_inter_iff, mem_prod, mem_preimage, mem_compl_iff], tauto }, { rintros ⟨t, ht, htS⟩, refine ⟨⟨(prod.fst '' t)ᶜ, _, _⟩, ⟨(prod.snd '' t)ᶜ, _, _⟩⟩, { exact ⟨prod.fst '' t, ht.image continuous_fst, subset.rfl⟩ }, { rw preimage_compl, rw compl_subset_comm at ⊢ htS, exact subset.trans htS (subset_preimage_image prod.fst _) }, { exact ⟨prod.snd '' t, ht.image continuous_snd, subset.rfl⟩ }, { rw preimage_compl, rw compl_subset_comm at ⊢ htS, exact subset.trans htS (subset_preimage_image prod.snd _) } } end lemma prod.noncompact_space_iff : noncompact_space (α × β) ↔ noncompact_space α ∧ nonempty β ∨ nonempty α ∧ noncompact_space β := by simp [← filter.cocompact_ne_bot_iff, ← filter.coprod_cocompact, filter.coprod_ne_bot_iff] @[priority 100] -- See Note [lower instance priority] instance prod.noncompact_space_left [noncompact_space α] [nonempty β] : noncompact_space (α × β) := prod.noncompact_space_iff.2 (or.inl ⟨‹_›, ‹_›⟩) @[priority 100] -- See Note [lower instance priority] instance prod.noncompact_space_right [nonempty α] [noncompact_space β] : noncompact_space (α × β) := prod.noncompact_space_iff.2 (or.inr ⟨‹_›, ‹_›⟩) section tychonoff variables [Π i, topological_space (π i)] /-- **Tychonoff's theorem**: product of compact sets is compact. -/ lemma is_compact_pi_infinite {s : Π i, set (π i)} : (∀ i, is_compact (s i)) → is_compact {x : Π i, π i | ∀ i, x i ∈ s i} := begin simp only [is_compact_iff_ultrafilter_le_nhds, nhds_pi, filter.pi, exists_prop, mem_set_of_eq, le_infi_iff, le_principal_iff], intros h f hfs, have : ∀ i:ι, ∃ a, a ∈ s i ∧ tendsto (λx:Πi:ι, π i, x i) f (𝓝 a), { refine λ i, h i (f.map _) (mem_map.2 _), exact mem_of_superset hfs (λ x hx, hx i) }, choose a ha, exact ⟨a, assume i, (ha i).left, assume i, (ha i).right.le_comap⟩ end /-- **Tychonoff's theorem** formulated using `set.pi`: product of compact sets is compact. -/ lemma is_compact_univ_pi {s : Π i, set (π i)} (h : ∀ i, is_compact (s i)) : is_compact (pi univ s) := by { convert is_compact_pi_infinite h, simp only [← mem_univ_pi, set_of_mem_eq] } instance pi.compact_space [∀ i, compact_space (π i)] : compact_space (Πi, π i) := ⟨by { rw [← pi_univ univ], exact is_compact_univ_pi (λ i, is_compact_univ) }⟩ instance function.compact_space [compact_space β] : compact_space (ι → β) := pi.compact_space /-- **Tychonoff's theorem** formulated in terms of filters: `filter.cocompact` on an indexed product type `Π d, κ d` the `filter.Coprod` of filters `filter.cocompact` on `κ d`. -/ lemma filter.Coprod_cocompact {δ : Type*} {κ : δ → Type*} [Π d, topological_space (κ d)] : filter.Coprod (λ d, filter.cocompact (κ d)) = filter.cocompact (Π d, κ d) := begin refine le_antisymm (supr_le $ λ i, filter.comap_cocompact_le (continuous_apply i)) _, refine compl_surjective.forall.2 (λ s H, _), simp only [compl_mem_Coprod, filter.mem_cocompact, compl_subset_compl, image_subset_iff] at H ⊢, choose K hKc htK using H, exact ⟨set.pi univ K, is_compact_univ_pi hKc, λ f hf i hi, htK i hf⟩ end end tychonoff instance quot.compact_space {r : α → α → Prop} [compact_space α] : compact_space (quot r) := ⟨by { rw ← range_quot_mk, exact is_compact_range continuous_quot_mk }⟩ instance quotient.compact_space {s : setoid α} [compact_space α] : compact_space (quotient s) := quot.compact_space /-- There are various definitions of "locally compact space" in the literature, which agree for Hausdorff spaces but not in general. This one is the precise condition on X needed for the evaluation `map C(X, Y) × X → Y` to be continuous for all `Y` when `C(X, Y)` is given the compact-open topology. -/ class locally_compact_space (α : Type*) [topological_space α] : Prop := (local_compact_nhds : ∀ (x : α) (n ∈ 𝓝 x), ∃ s ∈ 𝓝 x, s ⊆ n ∧ is_compact s) lemma compact_basis_nhds [locally_compact_space α] (x : α) : (𝓝 x).has_basis (λ s, s ∈ 𝓝 x ∧ is_compact s) (λ s, s) := has_basis_self.2 $ by simpa only [and_comm] using locally_compact_space.local_compact_nhds x lemma local_compact_nhds [locally_compact_space α] {x : α} {n : set α} (h : n ∈ 𝓝 x) : ∃ s ∈ 𝓝 x, s ⊆ n ∧ is_compact s := locally_compact_space.local_compact_nhds _ _ h lemma locally_compact_space_of_has_basis {ι : α → Type*} {p : Π x, ι x → Prop} {s : Π x, ι x → set α} (h : ∀ x, (𝓝 x).has_basis (p x) (s x)) (hc : ∀ x i, p x i → is_compact (s x i)) : locally_compact_space α := ⟨λ x t ht, let ⟨i, hp, ht⟩ := (h x).mem_iff.1 ht in ⟨s x i, (h x).mem_of_mem hp, ht, hc x i hp⟩⟩ instance prod.locally_compact_space (α : Type*) (β : Type*) [topological_space α] [topological_space β] [locally_compact_space α] [locally_compact_space β] : locally_compact_space (α × β) := have _ := λ x : α × β, (compact_basis_nhds x.1).prod_nhds' (compact_basis_nhds x.2), locally_compact_space_of_has_basis this $ λ x s ⟨⟨_, h₁⟩, _, h₂⟩, h₁.prod h₂ section pi variables [Π i, topological_space (π i)] [∀ i, locally_compact_space (π i)] /--In general it suffices that all but finitely many of the spaces are compact, but that's not straightforward to state and use. -/ instance pi.locally_compact_space_of_finite [finite ι] : locally_compact_space (Π i, π i) := ⟨λ t n hn, begin rw [nhds_pi, filter.mem_pi] at hn, obtain ⟨s, hs, n', hn', hsub⟩ := hn, choose n'' hn'' hsub' hc using λ i, locally_compact_space.local_compact_nhds (t i) (n' i) (hn' i), refine ⟨(set.univ : set ι).pi n'', _, subset_trans (λ _ h, _) hsub, is_compact_univ_pi hc⟩, { exact (set_pi_mem_nhds_iff (@set.finite_univ ι _) _).mpr (λ i hi, hn'' i), }, { exact λ i hi, hsub' i (h i trivial), }, end⟩ /-- For spaces that are not Hausdorff. -/ instance pi.locally_compact_space [∀ i, compact_space (π i)] : locally_compact_space (Π i, π i) := ⟨λ t n hn, begin rw [nhds_pi, filter.mem_pi] at hn, obtain ⟨s, hs, n', hn', hsub⟩ := hn, choose n'' hn'' hsub' hc using λ i, locally_compact_space.local_compact_nhds (t i) (n' i) (hn' i), refine ⟨s.pi n'', _, subset_trans (λ _, _) hsub, _⟩, { exact (set_pi_mem_nhds_iff hs _).mpr (λ i _, hn'' i), }, { exact forall₂_imp (λ i hi hi', hsub' i hi'), }, { rw ← set.univ_pi_ite, refine is_compact_univ_pi (λ i, _), by_cases i ∈ s, { rw if_pos h, exact hc i, }, { rw if_neg h, exact compact_space.is_compact_univ, } }, end⟩ instance function.locally_compact_space_of_finite [finite ι] [locally_compact_space β] : locally_compact_space (ι → β) := pi.locally_compact_space_of_finite instance function.locally_compact_space [locally_compact_space β] [compact_space β] : locally_compact_space (ι → β) := pi.locally_compact_space end pi /-- A reformulation of the definition of locally compact space: In a locally compact space, every open set containing `x` has a compact subset containing `x` in its interior. -/ lemma exists_compact_subset [locally_compact_space α] {x : α} {U : set α} (hU : is_open U) (hx : x ∈ U) : ∃ (K : set α), is_compact K ∧ x ∈ interior K ∧ K ⊆ U := begin rcases locally_compact_space.local_compact_nhds x U (hU.mem_nhds hx) with ⟨K, h1K, h2K, h3K⟩, exact ⟨K, h3K, mem_interior_iff_mem_nhds.2 h1K, h2K⟩, end /-- In a locally compact space every point has a compact neighborhood. -/ lemma exists_compact_mem_nhds [locally_compact_space α] (x : α) : ∃ K, is_compact K ∧ K ∈ 𝓝 x := let ⟨K, hKc, hx, H⟩ := exists_compact_subset is_open_univ (mem_univ x) in ⟨K, hKc, mem_interior_iff_mem_nhds.1 hx⟩ /-- In a locally compact space, for every containement `K ⊆ U` of a compact set `K` in an open set `U`, there is a compact neighborhood `L` such that `K ⊆ L ⊆ U`: equivalently, there is a compact `L` such that `K ⊆ interior L` and `L ⊆ U`. -/ lemma exists_compact_between [hα : locally_compact_space α] {K U : set α} (hK : is_compact K) (hU : is_open U) (h_KU : K ⊆ U) : ∃ L, is_compact L ∧ K ⊆ interior L ∧ L ⊆ U := begin choose V hVc hxV hKV using λ x : K, exists_compact_subset hU (h_KU x.2), have : K ⊆ ⋃ x, interior (V x), from λ x hx, mem_Union.2 ⟨⟨x, hx⟩, hxV _⟩, rcases hK.elim_finite_subcover _ (λ x, @is_open_interior α _ (V x)) this with ⟨t, ht⟩, refine ⟨_, t.is_compact_bUnion (λ x _, hVc x), λ x hx, _, set.Union₂_subset (λ i _, hKV i)⟩, rcases mem_Union₂.1 (ht hx) with ⟨y, hyt, hy⟩, exact interior_mono (subset_bUnion_of_mem hyt) hy, end /-- In a locally compact space, every compact set is contained in the interior of a compact set. -/ lemma exists_compact_superset [locally_compact_space α] {K : set α} (hK : is_compact K) : ∃ K', is_compact K' ∧ K ⊆ interior K' := let ⟨L, hLc, hKL, _⟩ := exists_compact_between hK is_open_univ K.subset_univ in ⟨L, hLc, hKL⟩ protected lemma closed_embedding.locally_compact_space [locally_compact_space β] {f : α → β} (hf : closed_embedding f) : locally_compact_space α := begin have : ∀ x : α, (𝓝 x).has_basis (λ s, s ∈ 𝓝 (f x) ∧ is_compact s) (λ s, f ⁻¹' s), { intro x, rw hf.to_embedding.to_inducing.nhds_eq_comap, exact (compact_basis_nhds _).comap _ }, exact locally_compact_space_of_has_basis this (λ x s hs, hf.is_compact_preimage hs.2) end protected lemma is_closed.locally_compact_space [locally_compact_space α] {s : set α} (hs : is_closed s) : locally_compact_space s := (closed_embedding_subtype_coe hs).locally_compact_space protected lemma open_embedding.locally_compact_space [locally_compact_space β] {f : α → β} (hf : open_embedding f) : locally_compact_space α := begin have : ∀ x : α, (𝓝 x).has_basis (λ s, (s ∈ 𝓝 (f x) ∧ is_compact s) ∧ s ⊆ range f) (λ s, f ⁻¹' s), { intro x, rw hf.to_embedding.to_inducing.nhds_eq_comap, exact ((compact_basis_nhds _).restrict_subset $ hf.open_range.mem_nhds $ mem_range_self _).comap _ }, refine locally_compact_space_of_has_basis this (λ x s hs, _), rw [← hf.to_inducing.is_compact_iff, image_preimage_eq_of_subset hs.2], exact hs.1.2 end protected lemma is_open.locally_compact_space [locally_compact_space α] {s : set α} (hs : is_open s) : locally_compact_space s := hs.open_embedding_subtype_coe.locally_compact_space lemma ultrafilter.le_nhds_Lim [compact_space α] (F : ultrafilter α) : ↑F ≤ 𝓝 (@Lim _ _ (F : filter α).nonempty_of_ne_bot F) := begin rcases is_compact_univ.ultrafilter_le_nhds F (by simp) with ⟨x, -, h⟩, exact le_nhds_Lim ⟨x,h⟩, end theorem is_closed.exists_minimal_nonempty_closed_subset [compact_space α] {S : set α} (hS : is_closed S) (hne : S.nonempty) : ∃ (V : set α), V ⊆ S ∧ V.nonempty ∧ is_closed V ∧ (∀ (V' : set α), V' ⊆ V → V'.nonempty → is_closed V' → V' = V) := begin let opens := {U : set α | Sᶜ ⊆ U ∧ is_open U ∧ Uᶜ.nonempty}, obtain ⟨U, ⟨Uc, Uo, Ucne⟩, h⟩ := zorn_subset opens (λ c hc hz, begin by_cases hcne : c.nonempty, { obtain ⟨U₀, hU₀⟩ := hcne, haveI : nonempty {U // U ∈ c} := ⟨⟨U₀, hU₀⟩⟩, obtain ⟨U₀compl, U₀opn, U₀ne⟩ := hc hU₀, use ⋃₀ c, refine ⟨⟨_, _, _⟩, λ U hU a ha, ⟨U, hU, ha⟩⟩, { exact λ a ha, ⟨U₀, hU₀, U₀compl ha⟩ }, { exact is_open_sUnion (λ _ h, (hc h).2.1) }, { convert_to (⋂(U : {U // U ∈ c}), U.1ᶜ).nonempty, { ext, simp only [not_exists, exists_prop, not_and, set.mem_Inter, subtype.forall, mem_set_of_eq, mem_compl_iff, mem_sUnion] }, apply is_compact.nonempty_Inter_of_directed_nonempty_compact_closed, { rintros ⟨U, hU⟩ ⟨U', hU'⟩, obtain ⟨V, hVc, hVU, hVU'⟩ := hz.directed_on U hU U' hU', exact ⟨⟨V, hVc⟩, set.compl_subset_compl.mpr hVU, set.compl_subset_compl.mpr hVU'⟩, }, { exact λ U, (hc U.2).2.2, }, { exact λ U, (is_closed_compl_iff.mpr (hc U.2).2.1).is_compact, }, { exact λ U, (is_closed_compl_iff.mpr (hc U.2).2.1), } } }, { use Sᶜ, refine ⟨⟨set.subset.refl _, is_open_compl_iff.mpr hS, _⟩, λ U Uc, (hcne ⟨U, Uc⟩).elim⟩, rw compl_compl, exact hne, } end), refine ⟨Uᶜ, set.compl_subset_comm.mp Uc, Ucne, is_closed_compl_iff.mpr Uo, _⟩, intros V' V'sub V'ne V'cls, have : V'ᶜ = U, { refine h V'ᶜ ⟨_, is_open_compl_iff.mpr V'cls, _⟩ (set.subset_compl_comm.mp V'sub), exact set.subset.trans Uc (set.subset_compl_comm.mp V'sub), simp only [compl_compl, V'ne], }, rw [←this, compl_compl], end /-- A σ-compact space is a space that is the union of a countable collection of compact subspaces. Note that a locally compact separable T₂ space need not be σ-compact. The sequence can be extracted using `topological_space.compact_covering`. -/ class sigma_compact_space (α : Type*) [topological_space α] : Prop := (exists_compact_covering : ∃ K : ℕ → set α, (∀ n, is_compact (K n)) ∧ (⋃ n, K n) = univ) @[priority 200] -- see Note [lower instance priority] instance compact_space.sigma_compact [compact_space α] : sigma_compact_space α := ⟨⟨λ _, univ, λ _, is_compact_univ, Union_const _⟩⟩ lemma sigma_compact_space.of_countable (S : set (set α)) (Hc : S.countable) (Hcomp : ∀ s ∈ S, is_compact s) (HU : ⋃₀ S = univ) : sigma_compact_space α := ⟨(exists_seq_cover_iff_countable ⟨_, is_compact_empty⟩).2 ⟨S, Hc, Hcomp, HU⟩⟩ @[priority 100] -- see Note [lower instance priority] instance sigma_compact_space_of_locally_compact_second_countable [locally_compact_space α] [second_countable_topology α] : sigma_compact_space α := begin choose K hKc hxK using λ x : α, exists_compact_mem_nhds x, rcases countable_cover_nhds hxK with ⟨s, hsc, hsU⟩, refine sigma_compact_space.of_countable _ (hsc.image K) (ball_image_iff.2 $ λ x _, hKc x) _, rwa sUnion_image end variables (α) [sigma_compact_space α] open sigma_compact_space /-- A choice of compact covering for a `σ`-compact space, chosen to be monotone. -/ def compact_covering : ℕ → set α := accumulate exists_compact_covering.some lemma is_compact_compact_covering (n : ℕ) : is_compact (compact_covering α n) := is_compact_accumulate (classical.some_spec sigma_compact_space.exists_compact_covering).1 n lemma Union_compact_covering : (⋃ n, compact_covering α n) = univ := begin rw [compact_covering, Union_accumulate], exact (classical.some_spec sigma_compact_space.exists_compact_covering).2 end @[mono] lemma compact_covering_subset ⦃m n : ℕ⦄ (h : m ≤ n) : compact_covering α m ⊆ compact_covering α n := monotone_accumulate h variable {α} lemma exists_mem_compact_covering (x : α) : ∃ n, x ∈ compact_covering α n := Union_eq_univ_iff.mp (Union_compact_covering α) x instance [sigma_compact_space β] : sigma_compact_space (α × β) := ⟨⟨λ n, compact_covering α n ×ˢ compact_covering β n, λ _, (is_compact_compact_covering _ _).prod (is_compact_compact_covering _ _), by simp only [Union_prod_of_monotone (compact_covering_subset α) (compact_covering_subset β), Union_compact_covering, univ_prod_univ]⟩⟩ instance [finite ι] [Π i, topological_space (π i)] [Π i, sigma_compact_space (π i)] : sigma_compact_space (Π i, π i) := begin refine ⟨⟨λ n, set.pi univ (λ i, compact_covering (π i) n), λ n, is_compact_univ_pi $ λ i, is_compact_compact_covering _ _, _⟩⟩, rw [Union_univ_pi_of_monotone], { simp only [Union_compact_covering, pi_univ] }, { exact λ i, compact_covering_subset (π i) } end instance [sigma_compact_space β] : sigma_compact_space (α ⊕ β) := ⟨⟨λ n, sum.inl '' compact_covering α n ∪ sum.inr '' compact_covering β n, λ n, ((is_compact_compact_covering α n).image continuous_inl).union ((is_compact_compact_covering β n).image continuous_inr), by simp only [Union_union_distrib, ← image_Union, Union_compact_covering, image_univ, range_inl_union_range_inr]⟩⟩ instance [countable ι] [Π i, topological_space (π i)] [Π i, sigma_compact_space (π i)] : sigma_compact_space (Σ i, π i) := begin casesI is_empty_or_nonempty ι, { apply_instance }, { rcases exists_surjective_nat ι with ⟨f, hf⟩, refine ⟨⟨λ n, ⋃ k ≤ n, sigma.mk (f k) '' compact_covering (π (f k)) n, λ n, _, _⟩⟩, { refine (finite_le_nat _).is_compact_bUnion (λ k _, _), exact (is_compact_compact_covering _ _).image continuous_sigma_mk }, { simp only [Union_eq_univ_iff, sigma.forall, mem_Union, hf.forall], intros k y, rcases exists_mem_compact_covering y with ⟨n, hn⟩, refine ⟨max k n, k, le_max_left _ _, mem_image_of_mem _ _⟩, exact compact_covering_subset _ (le_max_right _ _) hn } } end protected theorem closed_embedding.sigma_compact_space {e : β → α} (he : closed_embedding e) : sigma_compact_space β := ⟨⟨λ n, e ⁻¹' compact_covering α n, λ n, he.is_compact_preimage (is_compact_compact_covering _ _), by rw [← preimage_Union, Union_compact_covering, preimage_univ]⟩⟩ instance [sigma_compact_space β] : sigma_compact_space (ulift.{u} β) := ulift.closed_embedding_down.sigma_compact_space /-- If `α` is a `σ`-compact space, then a locally finite family of nonempty sets of `α` can have only countably many elements, `set.countable` version. -/ protected lemma locally_finite.countable_univ {ι : Type*} {f : ι → set α} (hf : locally_finite f) (hne : ∀ i, (f i).nonempty) : (univ : set ι).countable := begin have := λ n, hf.finite_nonempty_inter_compact (is_compact_compact_covering α n), refine (countable_Union (λ n, (this n).countable)).mono (λ i hi, _), rcases hne i with ⟨x, hx⟩, rcases Union_eq_univ_iff.1 (Union_compact_covering α) x with ⟨n, hn⟩, exact mem_Union.2 ⟨n, x, hx, hn⟩ end /-- If `f : ι → set α` is a locally finite covering of a σ-compact topological space by nonempty sets, then the index type `ι` is encodable. -/ protected noncomputable def locally_finite.encodable {ι : Type*} {f : ι → set α} (hf : locally_finite f) (hne : ∀ i, (f i).nonempty) : encodable ι := @encodable.of_equiv _ _ (hf.countable_univ hne).to_encodable (equiv.set.univ _).symm /-- In a topological space with sigma compact topology, if `f` is a function that sends each point `x` of a closed set `s` to a neighborhood of `x` within `s`, then for some countable set `t ⊆ s`, the neighborhoods `f x`, `x ∈ t`, cover the whole set `s`. -/ lemma countable_cover_nhds_within_of_sigma_compact {f : α → set α} {s : set α} (hs : is_closed s) (hf : ∀ x ∈ s, f x ∈ 𝓝[s] x) : ∃ t ⊆ s, t.countable ∧ s ⊆ ⋃ x ∈ t, f x := begin simp only [nhds_within, mem_inf_principal] at hf, choose t ht hsub using λ n, ((is_compact_compact_covering α n).inter_right hs).elim_nhds_subcover _ (λ x hx, hf x hx.right), refine ⟨⋃ n, (t n : set α), Union_subset $ λ n x hx, (ht n x hx).2, countable_Union $ λ n, (t n).countable_to_set, λ x hx, mem_Union₂.2 _⟩, rcases exists_mem_compact_covering x with ⟨n, hn⟩, rcases mem_Union₂.1 (hsub n ⟨hn, hx⟩) with ⟨y, hyt : y ∈ t n, hyf : x ∈ s → x ∈ f y⟩, exact ⟨y, mem_Union.2 ⟨n, hyt⟩, hyf hx⟩ end /-- In a topological space with sigma compact topology, if `f` is a function that sends each point `x` to a neighborhood of `x`, then for some countable set `s`, the neighborhoods `f x`, `x ∈ s`, cover the whole space. -/ lemma countable_cover_nhds_of_sigma_compact {f : α → set α} (hf : ∀ x, f x ∈ 𝓝 x) : ∃ s : set α, s.countable ∧ (⋃ x ∈ s, f x) = univ := begin simp only [← nhds_within_univ] at hf, rcases countable_cover_nhds_within_of_sigma_compact is_closed_univ (λ x _, hf x) with ⟨s, -, hsc, hsU⟩, exact ⟨s, hsc, univ_subset_iff.1 hsU⟩ end end compact /-- An [exhaustion by compact sets](https://en.wikipedia.org/wiki/Exhaustion_by_compact_sets) of a topological space is a sequence of compact sets `K n` such that `K n ⊆ interior (K (n + 1))` and `(⋃ n, K n) = univ`. If `X` is a locally compact sigma compact space, then `compact_exhaustion.choice X` provides a choice of an exhaustion by compact sets. This choice is also available as `(default : compact_exhaustion X)`. -/ structure compact_exhaustion (X : Type*) [topological_space X] := (to_fun : ℕ → set X) (is_compact' : ∀ n, is_compact (to_fun n)) (subset_interior_succ' : ∀ n, to_fun n ⊆ interior (to_fun (n + 1))) (Union_eq' : (⋃ n, to_fun n) = univ) namespace compact_exhaustion instance : has_coe_to_fun (compact_exhaustion α) (λ _, ℕ → set α) := ⟨to_fun⟩ variables {α} (K : compact_exhaustion α) protected lemma is_compact (n : ℕ) : is_compact (K n) := K.is_compact' n lemma subset_interior_succ (n : ℕ) : K n ⊆ interior (K (n + 1)) := K.subset_interior_succ' n lemma subset_succ (n : ℕ) : K n ⊆ K (n + 1) := subset.trans (K.subset_interior_succ n) interior_subset @[mono] protected lemma subset ⦃m n : ℕ⦄ (h : m ≤ n) : K m ⊆ K n := show K m ≤ K n, from monotone_nat_of_le_succ K.subset_succ h lemma subset_interior ⦃m n : ℕ⦄ (h : m < n) : K m ⊆ interior (K n) := subset.trans (K.subset_interior_succ m) $ interior_mono $ K.subset h lemma Union_eq : (⋃ n, K n) = univ := K.Union_eq' lemma exists_mem (x : α) : ∃ n, x ∈ K n := Union_eq_univ_iff.1 K.Union_eq x /-- The minimal `n` such that `x ∈ K n`. -/ protected noncomputable def find (x : α) : ℕ := nat.find (K.exists_mem x) lemma mem_find (x : α) : x ∈ K (K.find x) := nat.find_spec (K.exists_mem x) lemma mem_iff_find_le {x : α} {n : ℕ} : x ∈ K n ↔ K.find x ≤ n := ⟨λ h, nat.find_min' (K.exists_mem x) h, λ h, K.subset h $ K.mem_find x⟩ /-- Prepend the empty set to a compact exhaustion `K n`. -/ def shiftr : compact_exhaustion α := { to_fun := λ n, nat.cases_on n ∅ K, is_compact' := λ n, nat.cases_on n is_compact_empty K.is_compact, subset_interior_succ' := λ n, nat.cases_on n (empty_subset _) K.subset_interior_succ, Union_eq' := Union_eq_univ_iff.2 $ λ x, ⟨K.find x + 1, K.mem_find x⟩ } @[simp] lemma find_shiftr (x : α) : K.shiftr.find x = K.find x + 1 := nat.find_comp_succ _ _ (not_mem_empty _) lemma mem_diff_shiftr_find (x : α) : x ∈ K.shiftr (K.find x + 1) \ K.shiftr (K.find x) := ⟨K.mem_find _, mt K.shiftr.mem_iff_find_le.1 $ by simp only [find_shiftr, not_le, nat.lt_succ_self]⟩ /-- A choice of an [exhaustion by compact sets](https://en.wikipedia.org/wiki/Exhaustion_by_compact_sets) of a locally compact sigma compact space. -/ noncomputable def choice (X : Type*) [topological_space X] [locally_compact_space X] [sigma_compact_space X] : compact_exhaustion X := begin apply classical.choice, let K : ℕ → {s : set X // is_compact s} := λ n, nat.rec_on n ⟨∅, is_compact_empty⟩ (λ n s, ⟨(exists_compact_superset s.2).some ∪ compact_covering X n, (exists_compact_superset s.2).some_spec.1.union (is_compact_compact_covering _ _)⟩), refine ⟨⟨λ n, K n, λ n, (K n).2, λ n, _, _⟩⟩, { exact subset.trans (exists_compact_superset (K n).2).some_spec.2 (interior_mono $ subset_union_left _ _) }, { refine univ_subset_iff.1 (Union_compact_covering X ▸ _), exact Union_mono' (λ n, ⟨n + 1, subset_union_right _ _⟩) } end noncomputable instance [locally_compact_space α] [sigma_compact_space α] : inhabited (compact_exhaustion α) := ⟨compact_exhaustion.choice α⟩ end compact_exhaustion section clopen /-- A set is clopen if it is both open and closed. -/ def is_clopen (s : set α) : Prop := is_open s ∧ is_closed s protected lemma is_clopen.is_open (hs : is_clopen s) : is_open s := hs.1 protected lemma is_clopen.is_closed (hs : is_clopen s) : is_closed s := hs.2 lemma is_clopen_iff_frontier_eq_empty {s : set α} : is_clopen s ↔ frontier s = ∅ := begin rw [is_clopen, ← closure_eq_iff_is_closed, ← interior_eq_iff_is_open, frontier, diff_eq_empty], refine ⟨λ h, (h.2.trans h.1.symm).subset, λ h, _⟩, exact ⟨interior_subset.antisymm (subset_closure.trans h), (h.trans interior_subset).antisymm subset_closure⟩ end alias is_clopen_iff_frontier_eq_empty ↔ is_clopen.frontier_eq _ theorem is_clopen.union {s t : set α} (hs : is_clopen s) (ht : is_clopen t) : is_clopen (s ∪ t) := ⟨hs.1.union ht.1, hs.2.union ht.2⟩ theorem is_clopen.inter {s t : set α} (hs : is_clopen s) (ht : is_clopen t) : is_clopen (s ∩ t) := ⟨hs.1.inter ht.1, hs.2.inter ht.2⟩ @[simp] theorem is_clopen_empty : is_clopen (∅ : set α) := ⟨is_open_empty, is_closed_empty⟩ @[simp] theorem is_clopen_univ : is_clopen (univ : set α) := ⟨is_open_univ, is_closed_univ⟩ theorem is_clopen.compl {s : set α} (hs : is_clopen s) : is_clopen sᶜ := ⟨hs.2.is_open_compl, hs.1.is_closed_compl⟩ @[simp] theorem is_clopen_compl_iff {s : set α} : is_clopen sᶜ ↔ is_clopen s := ⟨λ h, compl_compl s ▸ is_clopen.compl h, is_clopen.compl⟩ theorem is_clopen.diff {s t : set α} (hs : is_clopen s) (ht : is_clopen t) : is_clopen (s \ t) := hs.inter ht.compl lemma is_clopen.prod {s : set α} {t : set β} (hs : is_clopen s) (ht : is_clopen t) : is_clopen (s ×ˢ t) := ⟨hs.1.prod ht.1, hs.2.prod ht.2⟩ lemma is_clopen_Union {β : Type*} [finite β] {s : β → set α} (h : ∀ i, is_clopen (s i)) : is_clopen (⋃ i, s i) := ⟨is_open_Union (forall_and_distrib.1 h).1, is_closed_Union (forall_and_distrib.1 h).2⟩ lemma is_clopen_bUnion {β : Type*} {s : set β} {f : β → set α} (hs : s.finite) (h : ∀ i ∈ s, is_clopen $ f i) : is_clopen (⋃ i ∈ s, f i) := ⟨is_open_bUnion (λ i hi, (h i hi).1), is_closed_bUnion hs (λ i hi, (h i hi).2)⟩ lemma is_clopen_bUnion_finset {β : Type*} {s : finset β} {f : β → set α} (h : ∀ i ∈ s, is_clopen $ f i) : is_clopen (⋃ i ∈ s, f i) := is_clopen_bUnion s.finite_to_set h lemma is_clopen_Inter {β : Type*} [finite β] {s : β → set α} (h : ∀ i, is_clopen (s i)) : is_clopen (⋂ i, s i) := ⟨(is_open_Inter (forall_and_distrib.1 h).1), (is_closed_Inter (forall_and_distrib.1 h).2)⟩ lemma is_clopen_bInter {β : Type*} {s : set β} (hs : s.finite) {f : β → set α} (h : ∀ i ∈ s, is_clopen (f i)) : is_clopen (⋂ i ∈ s, f i) := ⟨is_open_bInter hs (λ i hi, (h i hi).1), is_closed_bInter (λ i hi, (h i hi).2)⟩ lemma is_clopen_bInter_finset {β : Type*} {s : finset β} {f : β → set α} (h : ∀ i ∈ s, is_clopen (f i)) : is_clopen (⋂ i ∈ s, f i) := is_clopen_bInter s.finite_to_set h lemma is_clopen.preimage {s : set β} (h : is_clopen s) {f : α → β} (hf : continuous f) : is_clopen (f ⁻¹' s) := ⟨h.1.preimage hf, h.2.preimage hf⟩ lemma continuous_on.preimage_clopen_of_clopen {f : α → β} {s : set α} {t : set β} (hf : continuous_on f s) (hs : is_clopen s) (ht : is_clopen t) : is_clopen (s ∩ f⁻¹' t) := ⟨continuous_on.preimage_open_of_open hf hs.1 ht.1, continuous_on.preimage_closed_of_closed hf hs.2 ht.2⟩ /-- The intersection of a disjoint covering by two open sets of a clopen set will be clopen. -/ theorem is_clopen_inter_of_disjoint_cover_clopen {Z a b : set α} (h : is_clopen Z) (cover : Z ⊆ a ∪ b) (ha : is_open a) (hb : is_open b) (hab : disjoint a b) : is_clopen (Z ∩ a) := begin refine ⟨is_open.inter h.1 ha, _⟩, have : is_closed (Z ∩ bᶜ) := is_closed.inter h.2 (is_closed_compl_iff.2 hb), convert this using 1, refine (inter_subset_inter_right Z hab.subset_compl_right).antisymm _, rintro x ⟨hx₁, hx₂⟩, exact ⟨hx₁, by simpa [not_mem_of_mem_compl hx₂] using cover hx₁⟩, end @[simp] lemma is_clopen_discrete [discrete_topology α] (x : set α) : is_clopen x := ⟨is_open_discrete _, is_closed_discrete _⟩ lemma clopen_range_sigma_mk {ι : Type*} {σ : ι → Type*} [Π i, topological_space (σ i)] {i : ι} : is_clopen (set.range (@sigma.mk ι σ i)) := ⟨open_embedding_sigma_mk.open_range, closed_embedding_sigma_mk.closed_range⟩ protected lemma quotient_map.is_clopen_preimage {f : α → β} (hf : quotient_map f) {s : set β} : is_clopen (f ⁻¹' s) ↔ is_clopen s := and_congr hf.is_open_preimage hf.is_closed_preimage variables {X : Type*} [topological_space X] lemma continuous_bool_indicator_iff_clopen (U : set X) : continuous U.bool_indicator ↔ is_clopen U := begin split, { intros hc, rw ← U.preimage_bool_indicator_tt, exact ⟨hc.is_open_preimage _ trivial, continuous_iff_is_closed.mp hc _ (is_closed_discrete _)⟩ }, { refine λ hU, ⟨λ s hs, _⟩, rcases U.preimage_bool_indicator s with (h|h|h|h) ; rw h, exacts [is_open_univ, hU.1, hU.2.is_open_compl, is_open_empty] }, end lemma continuous_on_indicator_iff_clopen (s U : set X) : continuous_on U.bool_indicator s ↔ is_clopen ((coe : s → X) ⁻¹' U) := begin rw [continuous_on_iff_continuous_restrict, ← continuous_bool_indicator_iff_clopen], refl end end clopen section preirreducible /-- A preirreducible set `s` is one where there is no non-trivial pair of disjoint opens on `s`. -/ def is_preirreducible (s : set α) : Prop := ∀ (u v : set α), is_open u → is_open v → (s ∩ u).nonempty → (s ∩ v).nonempty → (s ∩ (u ∩ v)).nonempty /-- An irreducible set `s` is one that is nonempty and where there is no non-trivial pair of disjoint opens on `s`. -/ def is_irreducible (s : set α) : Prop := s.nonempty ∧ is_preirreducible s lemma is_irreducible.nonempty {s : set α} (h : is_irreducible s) : s.nonempty := h.1 lemma is_irreducible.is_preirreducible {s : set α} (h : is_irreducible s) : is_preirreducible s := h.2 theorem is_preirreducible_empty : is_preirreducible (∅ : set α) := λ _ _ _ _ _ ⟨x, h1, h2⟩, h1.elim lemma set.subsingleton.is_preirreducible {s : set α} (hs : s.subsingleton) : is_preirreducible s := λ u v hu hv ⟨x, hxs, hxu⟩ ⟨y, hys, hyv⟩, ⟨y, hys, hs hxs hys ▸ hxu, hyv⟩ theorem is_irreducible_singleton {x} : is_irreducible ({x} : set α) := ⟨singleton_nonempty x, subsingleton_singleton.is_preirreducible⟩ theorem is_preirreducible_iff_closure {s : set α} : is_preirreducible (closure s) ↔ is_preirreducible s := forall₄_congr $ λ u v hu hv, by { iterate 3 { rw closure_inter_open_nonempty_iff }, exacts [hu.inter hv, hv, hu] } theorem is_irreducible_iff_closure {s : set α} : is_irreducible (closure s) ↔ is_irreducible s := and_congr closure_nonempty_iff is_preirreducible_iff_closure alias is_preirreducible_iff_closure ↔ _ is_preirreducible.closure alias is_irreducible_iff_closure ↔ _ is_irreducible.closure theorem exists_preirreducible (s : set α) (H : is_preirreducible s) : ∃ t : set α, is_preirreducible t ∧ s ⊆ t ∧ ∀ u, is_preirreducible u → t ⊆ u → u = t := let ⟨m, hm, hsm, hmm⟩ := zorn_subset_nonempty {t : set α | is_preirreducible t} (λ c hc hcc hcn, let ⟨t, htc⟩ := hcn in ⟨⋃₀ c, λ u v hu hv ⟨y, hy, hyu⟩ ⟨z, hz, hzv⟩, let ⟨p, hpc, hyp⟩ := mem_sUnion.1 hy, ⟨q, hqc, hzq⟩ := mem_sUnion.1 hz in or.cases_on (hcc.total hpc hqc) (assume hpq : p ⊆ q, let ⟨x, hxp, hxuv⟩ := hc hqc u v hu hv ⟨y, hpq hyp, hyu⟩ ⟨z, hzq, hzv⟩ in ⟨x, mem_sUnion_of_mem hxp hqc, hxuv⟩) (assume hqp : q ⊆ p, let ⟨x, hxp, hxuv⟩ := hc hpc u v hu hv ⟨y, hyp, hyu⟩ ⟨z, hqp hzq, hzv⟩ in ⟨x, mem_sUnion_of_mem hxp hpc, hxuv⟩), λ x hxc, subset_sUnion_of_mem hxc⟩) s H in ⟨m, hm, hsm, λ u hu hmu, hmm _ hu hmu⟩ /-- The set of irreducible components of a topological space. -/ def irreducible_components (α : Type*) [topological_space α] : set (set α) := maximals (≤) { s : set α | is_irreducible s } lemma is_closed_of_mem_irreducible_components (s ∈ irreducible_components α) : is_closed s := begin rw [← closure_eq_iff_is_closed, eq_comm], exact subset_closure.antisymm (H.2 H.1.closure subset_closure), end lemma irreducible_components_eq_maximals_closed (α : Type*) [topological_space α] : irreducible_components α = maximals (≤) { s : set α | is_closed s ∧ is_irreducible s } := begin ext s, split, { intro H, exact ⟨⟨is_closed_of_mem_irreducible_components _ H, H.1⟩, λ x h e, H.2 h.2 e⟩ }, { intro H, refine ⟨H.1.2, λ x h e, _⟩, have : closure x ≤ s, { exact H.2 ⟨is_closed_closure, h.closure⟩ (e.trans subset_closure) }, exact le_trans subset_closure this } end /-- A maximal irreducible set that contains a given point. -/ def irreducible_component (x : α) : set α := classical.some (exists_preirreducible {x} is_irreducible_singleton.is_preirreducible) lemma irreducible_component_property (x : α) : is_preirreducible (irreducible_component x) ∧ {x} ⊆ (irreducible_component x) ∧ ∀ u, is_preirreducible u → (irreducible_component x) ⊆ u → u = (irreducible_component x) := classical.some_spec (exists_preirreducible {x} is_irreducible_singleton.is_preirreducible) theorem mem_irreducible_component {x : α} : x ∈ irreducible_component x := singleton_subset_iff.1 (irreducible_component_property x).2.1 theorem is_irreducible_irreducible_component {x : α} : is_irreducible (irreducible_component x) := ⟨⟨x, mem_irreducible_component⟩, (irreducible_component_property x).1⟩ theorem eq_irreducible_component {x : α} : ∀ {s : set α}, is_preirreducible s → irreducible_component x ⊆ s → s = irreducible_component x := (irreducible_component_property x).2.2 lemma irreducible_component_mem_irreducible_components (x : α) : irreducible_component x ∈ irreducible_components α := ⟨is_irreducible_irreducible_component, λ s h₁ h₂,(eq_irreducible_component h₁.2 h₂).le⟩ theorem is_closed_irreducible_component {x : α} : is_closed (irreducible_component x) := is_closed_of_mem_irreducible_components _ (irreducible_component_mem_irreducible_components x) /-- A preirreducible space is one where there is no non-trivial pair of disjoint opens. -/ class preirreducible_space (α : Type u) [topological_space α] : Prop := (is_preirreducible_univ [] : is_preirreducible (univ : set α)) /-- An irreducible space is one that is nonempty and where there is no non-trivial pair of disjoint opens. -/ class irreducible_space (α : Type u) [topological_space α] extends preirreducible_space α : Prop := (to_nonempty [] : nonempty α) -- see Note [lower instance priority] attribute [instance, priority 50] irreducible_space.to_nonempty lemma irreducible_space.is_irreducible_univ (α : Type u) [topological_space α] [irreducible_space α] : is_irreducible (⊤ : set α) := ⟨by simp, preirreducible_space.is_preirreducible_univ α⟩ lemma irreducible_space_def (α : Type u) [topological_space α] : irreducible_space α ↔ is_irreducible (⊤ : set α) := ⟨@@irreducible_space.is_irreducible_univ α _, λ h, by { haveI : preirreducible_space α := ⟨h.2⟩, exact ⟨⟨h.1.some⟩⟩ }⟩ theorem nonempty_preirreducible_inter [preirreducible_space α] {s t : set α} : is_open s → is_open t → s.nonempty → t.nonempty → (s ∩ t).nonempty := by simpa only [univ_inter, univ_subset_iff] using @preirreducible_space.is_preirreducible_univ α _ _ s t /-- In a (pre)irreducible space, a nonempty open set is dense. -/ protected theorem is_open.dense [preirreducible_space α] {s : set α} (ho : is_open s) (hne : s.nonempty) : dense s := dense_iff_inter_open.2 $ λ t hto htne, nonempty_preirreducible_inter hto ho htne hne theorem is_preirreducible.image {s : set α} (H : is_preirreducible s) (f : α → β) (hf : continuous_on f s) : is_preirreducible (f '' s) := begin rintros u v hu hv ⟨_, ⟨⟨x, hx, rfl⟩, hxu⟩⟩ ⟨_, ⟨⟨y, hy, rfl⟩, hyv⟩⟩, rw ← mem_preimage at hxu hyv, rcases continuous_on_iff'.1 hf u hu with ⟨u', hu', u'_eq⟩, rcases continuous_on_iff'.1 hf v hv with ⟨v', hv', v'_eq⟩, have := H u' v' hu' hv', rw [inter_comm s u', ← u'_eq] at this, rw [inter_comm s v', ← v'_eq] at this, rcases this ⟨x, hxu, hx⟩ ⟨y, hyv, hy⟩ with ⟨z, hzs, hzu', hzv'⟩, refine ⟨f z, mem_image_of_mem f hzs, _, _⟩, all_goals { rw ← mem_preimage, apply mem_of_mem_inter_left, show z ∈ _ ∩ s, simp [*] } end theorem is_irreducible.image {s : set α} (H : is_irreducible s) (f : α → β) (hf : continuous_on f s) : is_irreducible (f '' s) := ⟨H.nonempty.image _, H.is_preirreducible.image f hf⟩ lemma subtype.preirreducible_space {s : set α} (h : is_preirreducible s) : preirreducible_space s := { is_preirreducible_univ := begin intros u v hu hv hsu hsv, rw is_open_induced_iff at hu hv, rcases hu with ⟨u, hu, rfl⟩, rcases hv with ⟨v, hv, rfl⟩, rcases hsu with ⟨⟨x, hxs⟩, hxs', hxu⟩, rcases hsv with ⟨⟨y, hys⟩, hys', hyv⟩, rcases h u v hu hv ⟨x, hxs, hxu⟩ ⟨y, hys, hyv⟩ with ⟨z, hzs, ⟨hzu, hzv⟩⟩, exact ⟨⟨z, hzs⟩, ⟨set.mem_univ _, ⟨hzu, hzv⟩⟩⟩ end } lemma subtype.irreducible_space {s : set α} (h : is_irreducible s) : irreducible_space s := { is_preirreducible_univ := (subtype.preirreducible_space h.is_preirreducible).is_preirreducible_univ, to_nonempty := h.nonempty.to_subtype } /-- An infinite type with cofinite topology is an irreducible topological space. -/ @[priority 100] instance {α} [infinite α] : irreducible_space (cofinite_topology α) := { is_preirreducible_univ := λ u v, begin haveI : infinite (cofinite_topology α) := ‹_›, simp only [cofinite_topology.is_open_iff, univ_inter], intros hu hv hu' hv', simpa only [compl_union, compl_compl] using ((hu hu').union (hv hv')).infinite_compl.nonempty end, to_nonempty := (infer_instance : nonempty α) } /-- A set `s` is irreducible if and only if for every finite collection of open sets all of whose members intersect `s`, `s` also intersects the intersection of the entire collection (i.e., there is an element of `s` contained in every member of the collection). -/ lemma is_irreducible_iff_sInter {s : set α} : is_irreducible s ↔ ∀ (U : finset (set α)) (hU : ∀ u ∈ U, is_open u) (H : ∀ u ∈ U, (s ∩ u).nonempty), (s ∩ ⋂₀ ↑U).nonempty := begin split; intro h, { intro U, apply finset.induction_on U, { intros, simpa using h.nonempty }, { intros u U hu IH hU H, rw [finset.coe_insert, sInter_insert], apply h.2, { solve_by_elim [finset.mem_insert_self] }, { apply is_open_sInter (finset.finite_to_set U), intros, solve_by_elim [finset.mem_insert_of_mem] }, { solve_by_elim [finset.mem_insert_self] }, { apply IH, all_goals { intros, solve_by_elim [finset.mem_insert_of_mem] } } } }, { split, { simpa using h ∅ _ _; intro u; simp }, intros u v hu hv hu' hv', simpa using h {u,v} _ _, all_goals { intro t, rw [finset.mem_insert, finset.mem_singleton], rintro (rfl|rfl); assumption } } end /-- A set is preirreducible if and only if for every cover by two closed sets, it is contained in one of the two covering sets. -/ lemma is_preirreducible_iff_closed_union_closed {s : set α} : is_preirreducible s ↔ ∀ (z₁ z₂ : set α), is_closed z₁ → is_closed z₂ → s ⊆ z₁ ∪ z₂ → s ⊆ z₁ ∨ s ⊆ z₂ := begin split, all_goals { intros h t₁ t₂ ht₁ ht₂, specialize h t₁ᶜ t₂ᶜ, simp only [is_open_compl_iff, is_closed_compl_iff] at h, specialize h ht₁ ht₂ }, { contrapose!, simp only [not_subset], rintro ⟨⟨x, hx, hx'⟩, ⟨y, hy, hy'⟩⟩, rcases h ⟨x, hx, hx'⟩ ⟨y, hy, hy'⟩ with ⟨z, hz, hz'⟩, rw ← compl_union at hz', exact ⟨z, hz, hz'⟩ }, { rintro ⟨x, hx, hx'⟩ ⟨y, hy, hy'⟩, rw ← compl_inter at h, delta set.nonempty, rw imp_iff_not_or at h, contrapose! h, split, { intros z hz hz', exact h z ⟨hz, hz'⟩ }, { split; intro H; refine H _ ‹_›; assumption } } end /-- A set is irreducible if and only if for every cover by a finite collection of closed sets, it is contained in one of the members of the collection. -/ lemma is_irreducible_iff_sUnion_closed {s : set α} : is_irreducible s ↔ ∀ (Z : finset (set α)) (hZ : ∀ z ∈ Z, is_closed z) (H : s ⊆ ⋃₀ ↑Z), ∃ z ∈ Z, s ⊆ z := begin rw [is_irreducible, is_preirreducible_iff_closed_union_closed], split; intro h, { intro Z, apply finset.induction_on Z, { intros, rw [finset.coe_empty, sUnion_empty] at H, rcases h.1 with ⟨x, hx⟩, exfalso, tauto }, { intros z Z hz IH hZ H, cases h.2 z (⋃₀ ↑Z) _ _ _ with h' h', { exact ⟨z, finset.mem_insert_self _ _, h'⟩ }, { rcases IH _ h' with ⟨z', hz', hsz'⟩, { exact ⟨z', finset.mem_insert_of_mem hz', hsz'⟩ }, { intros, solve_by_elim [finset.mem_insert_of_mem] } }, { solve_by_elim [finset.mem_insert_self] }, { rw sUnion_eq_bUnion, apply is_closed_bUnion (finset.finite_to_set Z), { intros, solve_by_elim [finset.mem_insert_of_mem] } }, { simpa using H } } }, { split, { by_contradiction hs, simpa using h ∅ _ _, { intro z, simp }, { simpa [set.nonempty] using hs } }, intros z₁ z₂ hz₁ hz₂ H, have := h {z₁, z₂} _ _, simp only [exists_prop, finset.mem_insert, finset.mem_singleton] at this, { rcases this with ⟨z, rfl|rfl, hz⟩; tauto }, { intro t, rw [finset.mem_insert, finset.mem_singleton], rintro (rfl|rfl); assumption }, { simpa using H } } end /-- A nonemtpy open subset of a preirreducible subspace is dense in the subspace. -/ lemma subset_closure_inter_of_is_preirreducible_of_is_open {S U : set α} (hS : is_preirreducible S) (hU : is_open U) (h : (S ∩ U).nonempty) : S ⊆ closure (S ∩ U) := begin by_contra h', obtain ⟨x, h₁, h₂, h₃⟩ := hS _ (closure (S ∩ U))ᶜ hU (is_open_compl_iff.mpr is_closed_closure) h (set.inter_compl_nonempty_iff.mpr h'), exact h₃ (subset_closure ⟨h₁, h₂⟩) end /-- If `∅ ≠ U ⊆ S ⊆ Z` such that `U` is open and `Z` is preirreducible, then `S` is irreducible. -/ lemma is_preirreducible.subset_irreducible {S U Z : set α} (hZ : is_preirreducible Z) (hU : U.nonempty) (hU' : is_open U) (h₁ : U ⊆ S) (h₂ : S ⊆ Z) : is_irreducible S := begin classical, obtain ⟨z, hz⟩ := hU, replace hZ : is_irreducible Z := ⟨⟨z, h₂ (h₁ hz)⟩, hZ⟩, refine ⟨⟨z, h₁ hz⟩, _⟩, rintros u v hu hv ⟨x, hx, hx'⟩ ⟨y, hy, hy'⟩, obtain ⟨a, -, ha'⟩ := is_irreducible_iff_sInter.mp hZ {U, u, v} (by tidy) _, replace ha' : a ∈ U ∧ a ∈ u ∧ a ∈ v := by simpa using ha', exact ⟨a, h₁ ha'.1, ha'.2⟩, { intros U H, simp only [finset.mem_insert, finset.mem_singleton] at H, rcases H with (rfl|rfl|rfl), exacts [⟨z, h₂ (h₁ hz), hz⟩, ⟨x, h₂ hx, hx'⟩, ⟨y, h₂ hy, hy'⟩] } end lemma is_preirreducible.open_subset {Z U : set α} (hZ : is_preirreducible Z) (hU : is_open U) (hU' : U ⊆ Z) : is_preirreducible U := U.eq_empty_or_nonempty.elim (λ h, h.symm ▸ is_preirreducible_empty) (λ h, (hZ.subset_irreducible h hU (λ _, id) hU').2) lemma is_preirreducible.interior {Z : set α} (hZ : is_preirreducible Z) : is_preirreducible (interior Z) := hZ.open_subset is_open_interior interior_subset lemma is_preirreducible.preimage {Z : set α} (hZ : is_preirreducible Z) {f : β → α} (hf : open_embedding f) : is_preirreducible (f ⁻¹' Z) := begin rintros U V hU hV ⟨x, hx, hx'⟩ ⟨y, hy, hy'⟩, obtain ⟨_, h₁, ⟨z, h₂, rfl⟩, ⟨z', h₃, h₄⟩⟩ := hZ _ _ (hf.is_open_map _ hU) (hf.is_open_map _ hV) ⟨f x, hx, set.mem_image_of_mem f hx'⟩ ⟨f y, hy, set.mem_image_of_mem f hy'⟩, cases hf.inj h₄, exact ⟨z, h₁, h₂, h₃⟩ end end preirreducible
06b4b6faae1427bc8ca64f940bce99161e7a32c8
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/ring_theory/nilpotent.lean
b0031b536f90cb8a29401bfebbfcd26b35970524
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
10,097
lean
/- Copyright (c) 2021 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import data.nat.choose.sum import algebra.algebra.bilinear import ring_theory.ideal.operations /-! # Nilpotent elements ## Main definitions * `is_nilpotent` * `is_nilpotent_neg_iff` * `commute.is_nilpotent_add` * `commute.is_nilpotent_mul_left` * `commute.is_nilpotent_mul_right` * `commute.is_nilpotent_sub` -/ universes u v variables {R S : Type u} {x y : R} /-- An element is said to be nilpotent if some natural-number-power of it equals zero. Note that we require only the bare minimum assumptions for the definition to make sense. Even `monoid_with_zero` is too strong since nilpotency is important in the study of rings that are only power-associative. -/ def is_nilpotent [has_zero R] [has_pow R ℕ] (x : R) : Prop := ∃ (n : ℕ), x^n = 0 lemma is_nilpotent.mk [has_zero R] [has_pow R ℕ] (x : R) (n : ℕ) (e : x ^ n = 0) : is_nilpotent x := ⟨n, e⟩ lemma is_nilpotent.zero [monoid_with_zero R] : is_nilpotent (0 : R) := ⟨1, pow_one 0⟩ lemma is_nilpotent.neg [ring R] (h : is_nilpotent x) : is_nilpotent (-x) := begin obtain ⟨n, hn⟩ := h, use n, rw [neg_pow, hn, mul_zero], end @[simp] lemma is_nilpotent_neg_iff [ring R] : is_nilpotent (-x) ↔ is_nilpotent x := ⟨λ h, neg_neg x ▸ h.neg, λ h, h.neg⟩ lemma is_nilpotent.map [monoid_with_zero R] [monoid_with_zero S] {r : R} {F : Type*} [monoid_with_zero_hom_class F R S] (hr : is_nilpotent r) (f : F) : is_nilpotent (f r) := by { use hr.some, rw [← map_pow, hr.some_spec, map_zero] } /-- A structure that has zero and pow is reduced if it has no nonzero nilpotent elements. -/ @[mk_iff] class is_reduced (R : Type*) [has_zero R] [has_pow R ℕ] : Prop := (eq_zero : ∀ (x : R), is_nilpotent x → x = 0) @[priority 900] instance is_reduced_of_no_zero_divisors [monoid_with_zero R] [no_zero_divisors R] : is_reduced R := ⟨λ _ ⟨_, hn⟩, pow_eq_zero hn⟩ @[priority 900] instance is_reduced_of_subsingleton [has_zero R] [has_pow R ℕ] [subsingleton R] : is_reduced R := ⟨λ _ _, subsingleton.elim _ _⟩ lemma is_nilpotent.eq_zero [has_zero R] [has_pow R ℕ] [is_reduced R] (h : is_nilpotent x) : x = 0 := is_reduced.eq_zero x h @[simp] lemma is_nilpotent_iff_eq_zero [monoid_with_zero R] [is_reduced R] : is_nilpotent x ↔ x = 0 := ⟨λ h, h.eq_zero, λ h, h.symm ▸ is_nilpotent.zero⟩ lemma is_reduced_of_injective [monoid_with_zero R] [monoid_with_zero S] {F : Type*} [monoid_with_zero_hom_class F R S] (f : F) (hf : function.injective f) [_root_.is_reduced S] : _root_.is_reduced R := begin constructor, intros x hx, apply hf, rw map_zero, exact (hx.map f).eq_zero, end lemma ring_hom.ker_is_radical_iff_reduced_of_surjective {S F} [comm_semiring R] [comm_ring S] [ring_hom_class F R S] {f : F} (hf : function.surjective f) : (ring_hom.ker f).is_radical ↔ is_reduced S := by simp_rw [is_reduced_iff, hf.forall, is_nilpotent, ← map_pow, ← ring_hom.mem_ker]; refl lemma ideal.is_radical_iff_quotient_reduced [comm_ring R] (I : ideal R) : I.is_radical ↔ is_reduced (R ⧸ I) := by { conv_lhs { rw ← @ideal.mk_ker R _ I }, exact ring_hom.ker_is_radical_iff_reduced_of_surjective (@ideal.quotient.mk_surjective R _ I) } /-- An element `y` in a monoid is radical if for any element `x`, `y` divides `x` whenever it divides a power of `x`. -/ def is_radical [has_dvd R] [has_pow R ℕ] (y : R) : Prop := ∀ (n : ℕ) x, y ∣ x ^ n → y ∣ x lemma zero_is_radical_iff [monoid_with_zero R] : is_radical (0 : R) ↔ is_reduced R := by { simp_rw [is_reduced_iff, is_nilpotent, exists_imp_distrib, ← zero_dvd_iff], exact forall_swap } lemma is_radical_iff_span_singleton [comm_semiring R] : is_radical y ↔ (ideal.span ({y} : set R)).is_radical := begin simp_rw [is_radical, ← ideal.mem_span_singleton], exact forall_swap.trans (forall_congr $ λ r, exists_imp_distrib.symm), end lemma is_radical_iff_pow_one_lt [monoid_with_zero R] (k : ℕ) (hk : 1 < k) : is_radical y ↔ ∀ x, y ∣ x ^ k → y ∣ x := ⟨λ h x, h k x, λ h, k.cauchy_induction_mul (λ n h x hd, h x $ (pow_succ' x n).symm ▸ hd.mul_right x) 0 hk (λ x hd, pow_one x ▸ hd) (λ n _ hn x hd, h x $ hn _ $ (pow_mul x k n).subst hd)⟩ lemma is_reduced_iff_pow_one_lt [monoid_with_zero R] (k : ℕ) (hk : 1 < k) : is_reduced R ↔ ∀ x : R, x ^ k = 0 → x = 0 := by simp_rw [← zero_is_radical_iff, is_radical_iff_pow_one_lt k hk, zero_dvd_iff] namespace commute section semiring variables [semiring R] (h_comm : commute x y) include h_comm lemma is_nilpotent_add (hx : is_nilpotent x) (hy : is_nilpotent y) : is_nilpotent (x + y) := begin obtain ⟨n, hn⟩ := hx, obtain ⟨m, hm⟩ := hy, use n + m - 1, rw h_comm.add_pow', apply finset.sum_eq_zero, rintros ⟨i, j⟩ hij, suffices : x^i * y^j = 0, { simp only [this, nsmul_eq_mul, mul_zero], }, cases nat.le_or_le_of_add_eq_add_pred (finset.nat.mem_antidiagonal.mp hij) with hi hj, { rw [pow_eq_zero_of_le hi hn, zero_mul], }, { rw [pow_eq_zero_of_le hj hm, mul_zero], }, end lemma is_nilpotent_mul_left (h : is_nilpotent x) : is_nilpotent (x * y) := begin obtain ⟨n, hn⟩ := h, use n, rw [h_comm.mul_pow, hn, zero_mul], end lemma is_nilpotent_mul_right (h : is_nilpotent y) : is_nilpotent (x * y) := by { rw h_comm.eq, exact h_comm.symm.is_nilpotent_mul_left h, } end semiring section ring variables [ring R] (h_comm : commute x y) include h_comm lemma is_nilpotent_sub (hx : is_nilpotent x) (hy : is_nilpotent y) : is_nilpotent (x - y) := begin rw ← neg_right_iff at h_comm, rw ← is_nilpotent_neg_iff at hy, rw sub_eq_add_neg, exact h_comm.is_nilpotent_add hx hy, end end ring end commute section comm_semiring variable [comm_semiring R] /-- The nilradical of a commutative semiring is the ideal of nilpotent elements. -/ def nilradical (R : Type*) [comm_semiring R] : ideal R := (0 : ideal R).radical lemma mem_nilradical : x ∈ nilradical R ↔ is_nilpotent x := iff.rfl lemma nilradical_eq_Inf (R : Type*) [comm_semiring R] : nilradical R = Inf { J : ideal R | J.is_prime } := (ideal.radical_eq_Inf ⊥).trans $ by simp_rw and_iff_right bot_le lemma nilpotent_iff_mem_prime : is_nilpotent x ↔ ∀ (J : ideal R), J.is_prime → x ∈ J := by { rw [← mem_nilradical, nilradical_eq_Inf, submodule.mem_Inf], refl } lemma nilradical_le_prime (J : ideal R) [H : J.is_prime] : nilradical R ≤ J := (nilradical_eq_Inf R).symm ▸ Inf_le H @[simp] lemma nilradical_eq_zero (R : Type*) [comm_semiring R] [is_reduced R] : nilradical R = 0 := ideal.ext $ λ _, is_nilpotent_iff_eq_zero end comm_semiring namespace linear_map variables (R) {A : Type v} [comm_semiring R] [semiring A] [algebra R A] @[simp] lemma is_nilpotent_mul_left_iff (a : A) : is_nilpotent (mul_left R a) ↔ is_nilpotent a := begin split; rintros ⟨n, hn⟩; use n; simp only [mul_left_eq_zero_iff, pow_mul_left] at ⊢ hn; exact hn, end @[simp] lemma is_nilpotent_mul_right_iff (a : A) : is_nilpotent (mul_right R a) ↔ is_nilpotent a := begin split; rintros ⟨n, hn⟩; use n; simp only [mul_right_eq_zero_iff, pow_mul_right] at ⊢ hn; exact hn, end end linear_map namespace module.End variables {M : Type v} [ring R] [add_comm_group M] [module R M] variables {f : module.End R M} {p : submodule R M} (hp : p ≤ p.comap f) lemma is_nilpotent.mapq (hnp : is_nilpotent f) : is_nilpotent (p.mapq p f hp) := begin obtain ⟨k, hk⟩ := hnp, use k, simp [← p.mapq_pow, hk], end end module.End section ideal variables [comm_semiring R] [comm_ring S] [algebra R S] (I : ideal S) /-- Let `P` be a property on ideals. If `P` holds for square-zero ideals, and if `P I → P (J ⧸ I) → P J`, then `P` holds for all nilpotent ideals. -/ lemma ideal.is_nilpotent.induction_on (hI : is_nilpotent I) {P : ∀ ⦃S : Type*⦄ [comm_ring S], by exactI ∀ I : ideal S, Prop} (h₁ : ∀ ⦃S : Type*⦄ [comm_ring S], by exactI ∀ I : ideal S, I ^ 2 = ⊥ → P I) (h₂ : ∀ ⦃S : Type*⦄ [comm_ring S], by exactI ∀ I J : ideal S, I ≤ J → P I → P (J.map (ideal.quotient.mk I)) → P J) : P I := begin obtain ⟨n, hI : I ^ n = ⊥⟩ := hI, unfreezingI { revert S }, apply nat.strong_induction_on n, clear n, introsI n H S _ I hI, by_cases hI' : I = ⊥, { subst hI', apply h₁, rw [← ideal.zero_eq_bot, zero_pow], exact zero_lt_two }, cases n, { rw [pow_zero, ideal.one_eq_top] at hI, haveI := subsingleton_of_bot_eq_top hI.symm, exact (hI' (subsingleton.elim _ _)).elim }, cases n, { rw [pow_one] at hI, exact (hI' hI).elim }, apply h₂ (I ^ 2) _ (ideal.pow_le_self two_ne_zero), { apply H n.succ _ (I ^ 2), { rw [← pow_mul, eq_bot_iff, ← hI, nat.succ_eq_add_one, nat.succ_eq_add_one], exact ideal.pow_le_pow (by linarith) }, { exact le_refl n.succ.succ } }, { apply h₁, rw [← ideal.map_pow, ideal.map_quotient_self] }, end lemma is_nilpotent.is_unit_quotient_mk_iff {R : Type*} [comm_ring R] {I : ideal R} (hI : is_nilpotent I) {x : R} : is_unit (ideal.quotient.mk I x) ↔ is_unit x := begin refine ⟨_, λ h, h.map I^.quotient.mk⟩, revert x, apply ideal.is_nilpotent.induction_on I hI; clear hI I, swap, { introv e h₁ h₂ h₃, apply h₁, apply h₂, exactI h₃.map ((double_quot.quot_quot_equiv_quot_sup I J).trans (ideal.quot_equiv_of_eq (sup_eq_right.mpr e))).symm.to_ring_hom }, { introv e H, resetI, obtain ⟨y, hy⟩ := ideal.quotient.mk_surjective (↑(H.unit⁻¹) : S ⧸ I), have : ideal.quotient.mk I (x * y) = ideal.quotient.mk I 1, { rw [map_one, _root_.map_mul, hy, is_unit.mul_coe_inv] }, rw ideal.quotient.eq at this, have : (x * y - 1) ^ 2 = 0, { rw [← ideal.mem_bot, ← e], exact ideal.pow_mem_pow this _ }, have : x * (y * (2 - x * y)) = 1, { rw [eq_comm, ← sub_eq_zero, ← this], ring }, exact is_unit_of_mul_eq_one _ _ this } end end ideal
3e0032661aea3a7aa0c1359cf7b854e03ec2e046
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/playground/patcheqnspace2.lean
2e04b1d22dc8c8da93eaa777632dffb727843f24
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
1,909
lean
import init.lean.parser import init.lean.parser.transform open Lean open Lean.Parser def getAtomTrailingSpace : Syntax → Nat | Syntax.atom (some info) _ => info.trailing.stopPos - info.trailing.startPos | _ => 0 def getMinTrailingSpace (ps : Array Syntax) (i : Nat) : Nat := ps.foldl (fun acc (p : Syntax) => let space : Nat := match p.getTailInfo with | some info => info.trailing.stopPos - info.trailing.startPos | none => 0; if space < acc then space else acc) 100000 def reduceTrailingSpace : Syntax → Nat → Syntax | Syntax.atom (some info) val, delta => Syntax.atom (some { trailing := { stopPos := info.trailing.stopPos - delta, .. info.trailing }, .. info }) val | stx, _ => stx partial def fixPats : Array Syntax → Nat → Array Syntax | ps, i => let minSpace := getMinTrailingSpace ps i; if minSpace <= 1 then ps else let delta := minSpace - 1; ps.map $ fun p => p.modifyArg i $ fun pat => match pat.getTailInfo with | some info => pat.setTailInfo (some { trailing := { stopPos := info.trailing.stopPos - delta, .. info.trailing } , .. info }) | none => pat def fixEqnSyntax (stx : Syntax) : Syntax := stx.rewriteBottomUp $ fun stx => stx.ifNodeKind `Lean.Parser.Command.declValEqns (fun stx => stx.val.modifyArg 0 $ fun altsStx => altsStx.modifyArgs $ fun alts => let pats := alts.map $ fun alt => alt.getArg 1; let patSize := (pats.get 0).getArgs.size; let pats := fixPats pats (patSize - 1); alts.mapIdx $ fun i alt => alt.setArg 1 (pats.get i)) (fun _ => stx) def main (xs : List String) : IO Unit := do [fname] ← pure xs | throw (IO.userError "usage `patch <file-name>`"); env ← mkEmptyEnvironment; stx ← parseFile env fname; let stx := fixEqnSyntax stx; match stx.reprint with | some out => IO.print out | none => throw (IO.userError "failed to reprint")
7b4d04dac959e4db1ae984bea84a094ba8a15461
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/hott/algebra/category/constructions/terminal.hlean
444107903422774c61db13329509fe3cf16d3376
[ "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
1,788
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn Terminal category -/ import .indiscrete open functor is_trunc unit eq namespace category definition terminal_precategory [constructor] : precategory unit := indiscrete_precategory unit definition Terminal_precategory [constructor] : Precategory := precategory.Mk terminal_precategory notation 1 := Terminal_precategory definition one_op : 1ᵒᵖ = 1 := idp definition terminal_functor [constructor] (C : Precategory) : C ⇒ 1 := functor.mk (λx, star) (λx y f, star) (λx, idp) (λx y z g f, idp) definition is_contr_functor_one [instance] (C : Precategory) : is_contr (C ⇒ 1) := is_contr.mk (terminal_functor C) begin intro F, fapply functor_eq, { intro x, apply @is_prop.elim unit}, { intro x y f, apply @is_prop.elim unit} end definition terminal_functor_op (C : Precategory) : (terminal_functor C)ᵒᵖᶠ = terminal_functor Cᵒᵖ := idp definition terminal_functor_comp {C D : Precategory} (F : C ⇒ D) : (terminal_functor D) ∘f F = terminal_functor C := idp definition point [constructor] (C : Precategory) (c : C) : 1 ⇒ C := functor.mk (λx, c) (λx y f, id) (λx, idp) (λx y z g f, !id_id⁻¹) -- we need id_id in the declaration of precategory to make this to hold definitionally definition point_op (C : Precategory) (c : C) : (point C c)ᵒᵖᶠ = point Cᵒᵖ c := idp definition point_comp {C D : Precategory} (F : C ⇒ D) (c : C) : F ∘f point C c = point D (F c) := idp end category
dc96eb1896e3e5d786a9f3d9a471a30c44739b77
4727251e0cd73359b15b664c3170e5d754078599
/src/geometry/manifold/algebra/monoid.lean
d420bbfdded3ac28d4e41aad40e12e50b058a22e
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
11,065
lean
/- Copyright © 2020 Nicolò Cavalleri. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Nicolò Cavalleri -/ import geometry.manifold.cont_mdiff_map /-! # Smooth monoid A smooth monoid is a monoid that is also a smooth manifold, in which multiplication is a smooth map of the product manifold `G` × `G` into `G`. In this file we define the basic structures to talk about smooth monoids: `has_smooth_mul` and its additive counterpart `has_smooth_add`. These structures are general enough to also talk about smooth semigroups. -/ open_locale manifold /-- 1. All smooth algebraic structures on `G` are `Prop`-valued classes that extend `smooth_manifold_with_corners I G`. This way we save users from adding both `[smooth_manifold_with_corners I G]` and `[has_smooth_mul I G]` to the assumptions. While many API lemmas hold true without the `smooth_manifold_with_corners I G` assumption, we're not aware of a mathematically interesting monoid on a topological manifold such that (a) the space is not a `smooth_manifold_with_corners`; (b) the multiplication is smooth at `(a, b)` in the charts `ext_chart_at I a`, `ext_chart_at I b`, `ext_chart_at I (a * b)`. 2. Because of `model_prod` we can't assume, e.g., that a `lie_group` is modelled on `𝓘(𝕜, E)`. So, we formulate the definitions and lemmas for any model. 3. While smoothness of an operation implies its continuity, lemmas like `has_continuous_mul_of_smooth` can't be instances becausen otherwise Lean would have to search for `has_smooth_mul I G` with unknown `𝕜`, `E`, `H`, and `I : model_with_corners 𝕜 E H`. If users needs `[has_continuous_mul G]` in a proof about a smooth monoid, then they need to either add `[has_continuous_mul G]` as an assumption (worse) or use `haveI` in the proof (better). -/ library_note "Design choices about smooth algebraic structures" /-- Basic hypothesis to talk about a smooth (Lie) additive monoid or a smooth additive semigroup. A smooth additive monoid over `α`, for example, is obtained by requiring both the instances `add_monoid α` and `has_smooth_add α`. -/ -- See note [Design choices about smooth algebraic structures] @[ancestor smooth_manifold_with_corners] class has_smooth_add {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {H : Type*} [topological_space H] {E : Type*} [normed_group E] [normed_space 𝕜 E] (I : model_with_corners 𝕜 E H) (G : Type*) [has_add G] [topological_space G] [charted_space H G] extends smooth_manifold_with_corners I G : Prop := (smooth_add : smooth (I.prod I) I (λ p : G×G, p.1 + p.2)) /-- Basic hypothesis to talk about a smooth (Lie) monoid or a smooth semigroup. A smooth monoid over `G`, for example, is obtained by requiring both the instances `monoid G` and `has_smooth_mul I G`. -/ -- See note [Design choices about smooth algebraic structures] @[ancestor smooth_manifold_with_corners, to_additive] class has_smooth_mul {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {H : Type*} [topological_space H] {E : Type*} [normed_group E] [normed_space 𝕜 E] (I : model_with_corners 𝕜 E H) (G : Type*) [has_mul G] [topological_space G] [charted_space H G] extends smooth_manifold_with_corners I G : Prop := (smooth_mul : smooth (I.prod I) I (λ p : G×G, p.1 * p.2)) section has_smooth_mul variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {H : Type*} [topological_space H] {E : Type*} [normed_group E] [normed_space 𝕜 E] {I : model_with_corners 𝕜 E H} {G : Type*} [has_mul G] [topological_space G] [charted_space H G] [has_smooth_mul I G] {E' : Type*} [normed_group E'] [normed_space 𝕜 E'] {H' : Type*} [topological_space H'] {I' : model_with_corners 𝕜 E' H'} {M : Type*} [topological_space M] [charted_space H' M] section variables (I) @[to_additive] lemma smooth_mul : smooth (I.prod I) I (λ p : G×G, p.1 * p.2) := has_smooth_mul.smooth_mul /-- If the multiplication is smooth, then it is continuous. This is not an instance for technical reasons, see note [Design choices about smooth algebraic structures]. -/ @[to_additive "If the addition is smooth, then it is continuous. This is not an instance for technical reasons, see note [Design choices about smooth algebraic structures]."] lemma has_continuous_mul_of_smooth : has_continuous_mul G := ⟨(smooth_mul I).continuous⟩ end @[to_additive] lemma smooth.mul {f : M → G} {g : M → G} (hf : smooth I' I f) (hg : smooth I' I g) : smooth I' I (f * g) := (smooth_mul I).comp (hf.prod_mk hg) @[to_additive] lemma smooth_mul_left {a : G} : smooth I I (λ b : G, a * b) := smooth_const.mul smooth_id @[to_additive] lemma smooth_mul_right {a : G} : smooth I I (λ b : G, b * a) := smooth_id.mul smooth_const @[to_additive] lemma smooth_on.mul {f : M → G} {g : M → G} {s : set M} (hf : smooth_on I' I f s) (hg : smooth_on I' I g s) : smooth_on I' I (f * g) s := ((smooth_mul I).comp_smooth_on (hf.prod_mk hg) : _) variables (I) (g h : G) /-- Left multiplication by `g`. It is meant to mimic the usual notation in Lie groups. Lemmas involving `smooth_left_mul` with the notation `𝑳` usually use `L` instead of `𝑳` in the names. -/ def smooth_left_mul : C^∞⟮I, G; I, G⟯ := ⟨(left_mul g), smooth_mul_left⟩ /-- Right multiplication by `g`. It is meant to mimic the usual notation in Lie groups. Lemmas involving `smooth_right_mul` with the notation `𝑹` usually use `R` instead of `𝑹` in the names. -/ def smooth_right_mul : C^∞⟮I, G; I, G⟯ := ⟨(right_mul g), smooth_mul_right⟩ /- Left multiplication. The abbreviation is `MIL`. -/ localized "notation `𝑳` := smooth_left_mul" in lie_group /- Right multiplication. The abbreviation is `MIR`. -/ localized "notation `𝑹` := smooth_right_mul" in lie_group open_locale lie_group @[simp] lemma L_apply : (𝑳 I g) h = g * h := rfl @[simp] lemma R_apply : (𝑹 I g) h = h * g := rfl @[simp] lemma L_mul {G : Type*} [semigroup G] [topological_space G] [charted_space H G] [has_smooth_mul I G] (g h : G) : 𝑳 I (g * h) = (𝑳 I g).comp (𝑳 I h) := by { ext, simp only [cont_mdiff_map.comp_apply, L_apply, mul_assoc] } @[simp] lemma R_mul {G : Type*} [semigroup G] [topological_space G] [charted_space H G] [has_smooth_mul I G] (g h : G) : 𝑹 I (g * h) = (𝑹 I h).comp (𝑹 I g) := by { ext, simp only [cont_mdiff_map.comp_apply, R_apply, mul_assoc] } section variables {G' : Type*} [monoid G'] [topological_space G'] [charted_space H G'] [has_smooth_mul I G'] (g' : G') lemma smooth_left_mul_one : (𝑳 I g') 1 = g' := mul_one g' lemma smooth_right_mul_one : (𝑹 I g') 1 = g' := one_mul g' end /- Instance of product -/ @[to_additive] instance has_smooth_mul.prod {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {H : Type*} [topological_space H] (I : model_with_corners 𝕜 E H) (G : Type*) [topological_space G] [charted_space H G] [has_mul G] [has_smooth_mul I G] {E' : Type*} [normed_group E'] [normed_space 𝕜 E'] {H' : Type*} [topological_space H'] (I' : model_with_corners 𝕜 E' H') (G' : Type*) [topological_space G'] [charted_space H' G'] [has_mul G'] [has_smooth_mul I' G'] : has_smooth_mul (I.prod I') (G×G') := { smooth_mul := ((smooth_fst.comp smooth_fst).smooth.mul (smooth_fst.comp smooth_snd)).prod_mk ((smooth_snd.comp smooth_fst).smooth.mul (smooth_snd.comp smooth_snd)), .. smooth_manifold_with_corners.prod G G' } end has_smooth_mul section monoid variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {H : Type*} [topological_space H] {E : Type*} [normed_group E] [normed_space 𝕜 E] {I : model_with_corners 𝕜 E H} {G : Type*} [monoid G] [topological_space G] [charted_space H G] [has_smooth_mul I G] {H' : Type*} [topological_space H'] {E' : Type*} [normed_group E'] [normed_space 𝕜 E'] {I' : model_with_corners 𝕜 E' H'} {G' : Type*} [monoid G'] [topological_space G'] [charted_space H' G'] [has_smooth_mul I' G'] lemma smooth_pow : ∀ n : ℕ, smooth I I (λ a : G, a ^ n) | 0 := by { simp only [pow_zero], exact smooth_const } | (k+1) := by simpa [pow_succ] using smooth_id.mul (smooth_pow _) /-- Morphism of additive smooth monoids. -/ structure smooth_add_monoid_morphism (I : model_with_corners 𝕜 E H) (I' : model_with_corners 𝕜 E' H') (G : Type*) [topological_space G] [charted_space H G] [add_monoid G] [has_smooth_add I G] (G' : Type*) [topological_space G'] [charted_space H' G'] [add_monoid G'] [has_smooth_add I' G'] extends G →+ G' := (smooth_to_fun : smooth I I' to_fun) /-- Morphism of smooth monoids. -/ @[to_additive] structure smooth_monoid_morphism (I : model_with_corners 𝕜 E H) (I' : model_with_corners 𝕜 E' H') (G : Type*) [topological_space G] [charted_space H G] [monoid G] [has_smooth_mul I G] (G' : Type*) [topological_space G'] [charted_space H' G'] [monoid G'] [has_smooth_mul I' G'] extends G →* G' := (smooth_to_fun : smooth I I' to_fun) @[to_additive] instance : has_one (smooth_monoid_morphism I I' G G') := ⟨{ smooth_to_fun := smooth_const, to_monoid_hom := 1 }⟩ @[to_additive] instance : inhabited (smooth_monoid_morphism I I' G G') := ⟨1⟩ @[to_additive] instance : has_coe_to_fun (smooth_monoid_morphism I I' G G') (λ _, G → G') := ⟨λ a, a.to_fun⟩ end monoid section comm_monoid open_locale big_operators variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {H : Type*} [topological_space H] {E : Type*} [normed_group E] [normed_space 𝕜 E] {I : model_with_corners 𝕜 E H} {G : Type*} [comm_monoid G] [topological_space G] [charted_space H G] [has_smooth_mul I G] {E' : Type*} [normed_group E'] [normed_space 𝕜 E'] {H' : Type*} [topological_space H'] {I' : model_with_corners 𝕜 E' H'} {M : Type*} [topological_space M] [charted_space H' M] @[to_additive] lemma smooth_finset_prod' {ι} {s : finset ι} {f : ι → M → G} (h : ∀ i ∈ s, smooth I' I (f i)) : smooth I' I (∏ i in s, f i) := finset.prod_induction _ _ (λ f g hf hg, hf.mul hg) (@smooth_const _ _ _ _ _ _ _ I' _ _ _ _ _ _ _ _ I _ _ _ 1) h @[to_additive] lemma smooth_finset_prod {ι} {s : finset ι} {f : ι → M → G} (h : ∀ i ∈ s, smooth I' I (f i)) : smooth I' I (λ x, ∏ i in s, f i x) := by { simp only [← finset.prod_apply], exact smooth_finset_prod' h } open function filter @[to_additive] lemma smooth_finprod {ι} {f : ι → M → G} (h : ∀ i, smooth I' I (f i)) (hfin : locally_finite (λ i, mul_support (f i))) : smooth I' I (λ x, ∏ᶠ i, f i x) := begin intro x, rcases finprod_eventually_eq_prod hfin x with ⟨s, hs⟩, exact (smooth_finset_prod (λ i hi, h i) x).congr_of_eventually_eq hs, end @[to_additive] lemma smooth_finprod_cond {ι} {f : ι → M → G} {p : ι → Prop} (hc : ∀ i, p i → smooth I' I (f i)) (hf : locally_finite (λ i, mul_support (f i))) : smooth I' I (λ x, ∏ᶠ i (hi : p i), f i x) := begin simp only [← finprod_subtype_eq_finprod_cond], exact smooth_finprod (λ i, hc i i.2) (hf.comp_injective subtype.coe_injective) end end comm_monoid
0463ff2e58f3bfb15645157f0186223bfe19781c
a7eef317ddec01b9fc6cfbb876fe7ac00f205ac7
/src/geometry/manifold/basic_smooth_bundle.lean
1b86fe76f627624edba456a1b106e5123a558473
[ "Apache-2.0" ]
permissive
kmill/mathlib
ea5a007b67ae4e9e18dd50d31d8aa60f650425ee
1a419a9fea7b959317eddd556e1bb9639f4dcc05
refs/heads/master
1,668,578,197,719
1,593,629,163,000
1,593,629,163,000
276,482,939
0
0
null
1,593,637,960,000
1,593,637,959,000
null
UTF-8
Lean
false
false
31,736
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import topology.topological_fiber_bundle import geometry.manifold.smooth_manifold_with_corners /-! # Basic smooth bundles In general, a smooth bundle is a bundle over a smooth manifold, whose fiber is a manifold, and for which the coordinate changes are smooth. In this definition, there are charts involved at several places: in the manifold structure of the base, in the manifold structure of the fibers, and in the local trivializations. This makes it a complicated object in general. There is however a specific situation where things are much simpler: when the fiber is a vector space (no need for charts for the fibers), and when the local trivializations of the bundle and the charts of the base coincide. Then everything is expressed in terms of the charts of the base, making for a much simpler overall structure, which is easier to manipulate formally. Most vector bundles that naturally occur in differential geometry are of this form: the tangent bundle, the cotangent bundle, differential forms (used to define de Rham cohomology) and the bundle of Riemannian metrics. Therefore, it is worth defining a specific constructor for this kind of bundle, that we call basic smooth bundles. A basic smooth bundle is thus a smooth bundle over a smooth manifold whose fiber is a vector space, and which is trivial in the coordinate charts of the base. (We recall that in our notion of manifold there is a distinguished atlas, which does not need to be maximal: we require the triviality above this specific atlas). It can be constructed from a basic smooth bundled core, defined below, specifying the changes in the fiber when one goes from one coordinate chart to another one. We do not require that this changes in fiber are linear, but only diffeomorphisms. ## Main definitions * `basic_smooth_bundle_core I M F`: assuming that `M` is a smooth manifold over the model with corners `I` on `(𝕜, E, H)`, and `F` is a normed vector space over `𝕜`, this structure registers, for each pair of charts of `M`, a smooth change of coordinates on `F`. This is the core structure from which one will build a smooth bundle with fiber `F` over `M`. Let `Z` be a basic smooth bundle core over `M` with fiber `F`. We define `Z.to_topological_fiber_bundle_core`, the (topological) fiber bundle core associated to `Z`. From it, we get a space `Z.to_topological_fiber_bundle_core.total_space` (which as a Type is just `M × F`), with the fiber bundle topology. It inherits a manifold structure (where the charts are in bijection with the charts of the basis). We show that this manifold is smooth. Then we use this machinery to construct the tangent bundle of a smooth manifold. * `tangent_bundle_core I M`: the basic smooth bundle core associated to a smooth manifold `M` over a model with corners `I`. * `tangent_bundle I M` : the total space of `tangent_bundle_core I M`. It is itself a smooth manifold over the model with corners `I.tangent`, the product of `I` and the trivial model with corners on `E`. * `tangent_space I x` : the tangent space to `M` at `x` * `tangent_bundle.proj I M`: the projection from the tangent bundle to the base manifold ## Implementation notes In the definition of a basic smooth bundle core, we do not require that the coordinate changes of the fibers are linear map, only that they are diffeomorphisms. Therefore, the fibers of the resulting fiber bundle do not inherit a vector space structure (as an algebraic object) in general. As the fiber, as a type, is just `F`, one can still always register the vector space structure, but it does not make sense to do so (i.e., it will not lead to any useful theorem) unless this structure is canonical, i.e., the coordinate changes are linear maps. For instance, we register the vector space structure on the fibers of the tangent bundle. However, we do not register the normed space structure coming from that of `F` (as it is not canonical, and we also want to keep the possibility to add a Riemannian structure on the manifold later on without having two competing normed space instances on the tangent spaces). We require `F` to be a normed space, and not just a topological vector space, as we want to talk about smooth functions on `F`. The notion of derivative requires a norm to be defined. ## TODO construct the cotangent bundle, and the bundles of differential forms. They should follow functorially from the description of the tangent bundle as a basic smooth bundle. ## Tags Smooth fiber bundle, vector bundle, tangent space, tangent bundle -/ noncomputable theory universe u open topological_space set /-- Core structure used to create a smooth bundle above `M` (a manifold over the model with corner `I`) with fiber the normed vector space `F` over `𝕜`, which is trivial in the chart domains of `M`. This structure registers the changes in the fibers when one changes coordinate charts in the base. We do not require the change of coordinates of the fibers to be linear, only smooth. Therefore, the fibers of the resulting bundle will not inherit a canonical vector space structure in general. -/ structure basic_smooth_bundle_core {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {H : Type*} [topological_space H] (I : model_with_corners 𝕜 E H) (M : Type*) [topological_space M] [charted_space H M] [smooth_manifold_with_corners I M] (F : Type*) [normed_group F] [normed_space 𝕜 F] := (coord_change : atlas H M → atlas H M → H → F → F) (coord_change_self : ∀ i : atlas H M, ∀ x ∈ i.1.target, ∀ v, coord_change i i x v = v) (coord_change_comp : ∀ i j k : atlas H M, ∀ x ∈ ((i.1.symm.trans j.1).trans (j.1.symm.trans k.1)).source, ∀ v, (coord_change j k ((i.1.symm.trans j.1) x)) (coord_change i j x v) = coord_change i k x v) (coord_change_smooth : ∀ i j : atlas H M, times_cont_diff_on 𝕜 ⊤ (λp : E × F, coord_change i j (I.symm p.1) p.2) ((I '' (i.1.symm.trans j.1).source).prod (univ : set F))) /-- The trivial basic smooth bundle core, in which all the changes of coordinates are the identity. -/ def trivial_basic_smooth_bundle_core {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {H : Type*} [topological_space H] (I : model_with_corners 𝕜 E H) (M : Type*) [topological_space M] [charted_space H M] [smooth_manifold_with_corners I M] (F : Type*) [normed_group F] [normed_space 𝕜 F] : basic_smooth_bundle_core I M F := { coord_change := λ i j x v, v, coord_change_self := λ i x hx v, rfl, coord_change_comp := λ i j k x hx v, rfl, coord_change_smooth := λ i j, times_cont_diff_snd.times_cont_diff_on } namespace basic_smooth_bundle_core variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {H : Type*} [topological_space H] {I : model_with_corners 𝕜 E H} {M : Type*} [topological_space M] [charted_space H M] [smooth_manifold_with_corners I M] {F : Type*} [normed_group F] [normed_space 𝕜 F] (Z : basic_smooth_bundle_core I M F) instance : inhabited (basic_smooth_bundle_core I M F) := ⟨trivial_basic_smooth_bundle_core I M F⟩ /-- Fiber bundle core associated to a basic smooth bundle core -/ def to_topological_fiber_bundle_core : topological_fiber_bundle_core (atlas H M) M F := { base_set := λi, i.1.source, is_open_base_set := λi, i.1.open_source, index_at := λx, ⟨chart_at H x, chart_mem_atlas H x⟩, mem_base_set_at := λx, mem_chart_source H x, coord_change := λi j x v, Z.coord_change i j (i.1 x) v, coord_change_self := λi x hx v, Z.coord_change_self i (i.1 x) (i.1.map_source hx) v, coord_change_comp := λi j k x ⟨⟨hx1, hx2⟩, hx3⟩ v, begin have := Z.coord_change_comp i j k (i.1 x) _ v, convert this using 2, { simp only [hx1] with mfld_simps }, { simp only [hx1, hx2, hx3] with mfld_simps } end, coord_change_continuous := λi j, begin have A : continuous_on (λp : E × F, Z.coord_change i j (I.symm p.1) p.2) ((I '' (i.1.symm.trans j.1).source).prod (univ : set F)) := (Z.coord_change_smooth i j).continuous_on, have B : continuous_on (λx : M, I (i.1 x)) i.1.source := I.continuous.comp_continuous_on i.1.continuous_on, have C : continuous_on (λp : M × F, (⟨I (i.1 p.1), p.2⟩ : E × F)) (i.1.source.prod univ), { apply continuous_on.prod _ continuous_snd.continuous_on, exact B.comp continuous_fst.continuous_on (prod_subset_preimage_fst _ _) }, have C' : continuous_on (λp : M × F, (⟨I (i.1 p.1), p.2⟩ : E × F)) ((i.1.source ∩ j.1.source).prod univ) := continuous_on.mono C (prod_mono (inter_subset_left _ _) (subset.refl _)), have D : (i.1.source ∩ j.1.source).prod univ ⊆ (λ (p : M × F), (I (i.1 p.1), p.2)) ⁻¹' ((I '' (i.1.symm.trans j.1).source).prod univ), { rintros ⟨x, v⟩ hx, simp only with mfld_simps at hx, simp only [hx] with mfld_simps }, convert continuous_on.comp A C' D, ext p, simp only with mfld_simps end } @[simp, mfld_simps] lemma base_set (i : atlas H M) : Z.to_topological_fiber_bundle_core.base_set i = i.1.source := rfl /-- Local chart for the total space of a basic smooth bundle -/ def chart {e : local_homeomorph M H} (he : e ∈ atlas H M) : local_homeomorph (Z.to_topological_fiber_bundle_core.total_space) (H × F) := (Z.to_topological_fiber_bundle_core.local_triv ⟨e, he⟩).trans (local_homeomorph.prod e (local_homeomorph.refl F)) @[simp, mfld_simps] lemma chart_source (e : local_homeomorph M H) (he : e ∈ atlas H M) : (Z.chart he).source = Z.to_topological_fiber_bundle_core.proj ⁻¹' e.source := by { ext p, simp only [chart, mem_prod, and_self] with mfld_simps } @[simp, mfld_simps] lemma chart_target (e : local_homeomorph M H) (he : e ∈ atlas H M) : (Z.chart he).target = e.target.prod univ := begin simp only [chart] with mfld_simps, ext p, split; simp {contextual := tt} end /-- The total space of a basic smooth bundle is endowed with a charted space structure, where the charts are in bijection with the charts of the basis. -/ instance to_charted_space : charted_space (H × F) Z.to_topological_fiber_bundle_core.total_space := { atlas := ⋃(e : local_homeomorph M H) (he : e ∈ atlas H M), {Z.chart he}, chart_at := λp, Z.chart (chart_mem_atlas H p.1), mem_chart_source := λp, by simp [mem_chart_source], chart_mem_atlas := λp, begin simp only [mem_Union, mem_singleton_iff, chart_mem_atlas], exact ⟨chart_at H p.1, chart_mem_atlas H p.1, rfl⟩ end } lemma mem_atlas_iff (f : local_homeomorph Z.to_topological_fiber_bundle_core.total_space (H × F)) : f ∈ atlas (H × F) Z.to_topological_fiber_bundle_core.total_space ↔ ∃(e : local_homeomorph M H) (he : e ∈ atlas H M), f = Z.chart he := by simp only [atlas, mem_Union, mem_singleton_iff] @[simp, mfld_simps] lemma mem_chart_source_iff (p q : Z.to_topological_fiber_bundle_core.total_space) : p ∈ (chart_at (H × F) q).source ↔ p.1 ∈ (chart_at H q.1).source := by simp only [chart_at] with mfld_simps @[simp, mfld_simps] lemma mem_chart_target_iff (p : H × F) (q : Z.to_topological_fiber_bundle_core.total_space) : p ∈ (chart_at (H × F) q).target ↔ p.1 ∈ (chart_at H q.1).target := by simp only [chart_at] with mfld_simps @[simp, mfld_simps] lemma coe_chart_at_fst (p q : Z.to_topological_fiber_bundle_core.total_space) : (((chart_at (H × F) q) : _ → H × F) p).1 = (chart_at H q.1 : _ → H) p.1 := rfl @[simp, mfld_simps] lemma coe_chart_at_symm_fst (p : H × F) (q : Z.to_topological_fiber_bundle_core.total_space) : (((chart_at (H × F) q).symm : H × F → Z.to_topological_fiber_bundle_core.total_space) p).1 = ((chart_at H q.1).symm : H → M) p.1 := rfl /-- Smooth manifold structure on the total space of a basic smooth bundle -/ instance to_smooth_manifold : smooth_manifold_with_corners (I.prod (model_with_corners_self 𝕜 F)) Z.to_topological_fiber_bundle_core.total_space := begin /- We have to check that the charts belong to the smooth groupoid, i.e., they are smooth on their source, and their inverses are smooth on the target. Since both objects are of the same kind, it suffices to prove the first statement in A below, and then glue back the pieces at the end. -/ let J := model_with_corners.to_local_equiv (I.prod (model_with_corners_self 𝕜 F)), have A : ∀ (e e' : local_homeomorph M H) (he : e ∈ atlas H M) (he' : e' ∈ atlas H M), times_cont_diff_on 𝕜 ⊤ (J ∘ ((Z.chart he).symm.trans (Z.chart he')) ∘ J.symm) (J.symm ⁻¹' ((Z.chart he).symm.trans (Z.chart he')).source ∩ range J), { assume e e' he he', have : J.symm ⁻¹' ((chart Z he).symm.trans (chart Z he')).source ∩ range J = (I.symm ⁻¹' (e.symm.trans e').source ∩ range I).prod univ, { have : range (λ (p : H × F), (I (p.fst), id p.snd)) = (range I).prod (range (id : F → F)) := prod_range_range_eq.symm, simp only [id.def, range_id] with mfld_simps at this, ext p, simp only [J, chart, model_with_corners.prod, this] with mfld_simps, split, { tauto }, { exact λ⟨⟨hx1, hx2⟩, hx3⟩, ⟨⟨⟨hx1, e.map_target hx1⟩, hx2⟩, hx3⟩ } }, rw this, -- check separately that the two components of the coordinate change are smooth apply times_cont_diff_on.prod, show times_cont_diff_on 𝕜 ⊤ (λ (p : E × F), (I ∘ e' ∘ e.symm ∘ I.symm) p.1) ((I.symm ⁻¹' (e.symm.trans e').source ∩ range I).prod (univ : set F)), { -- the coordinate change on the base is just a coordinate change for `M`, smooth since -- `M` is smooth have A : times_cont_diff_on 𝕜 ⊤ (I ∘ (e.symm.trans e') ∘ I.symm) (I.symm ⁻¹' (e.symm.trans e').source ∩ range I) := (has_groupoid.compatible (times_cont_diff_groupoid ⊤ I) he he').1, have B : times_cont_diff_on 𝕜 ⊤ (λp : E × F, p.1) ((I.symm ⁻¹' (e.symm.trans e').source ∩ range I).prod univ) := times_cont_diff_fst.times_cont_diff_on, exact times_cont_diff_on.comp A B (prod_subset_preimage_fst _ _) }, show times_cont_diff_on 𝕜 ⊤ (λ (p : E × F), Z.coord_change ⟨chart_at H (e.symm (I.symm p.1)), _⟩ ⟨e', he'⟩ ((chart_at H (e.symm (I.symm p.1)) : M → H) (e.symm (I.symm p.1))) (Z.coord_change ⟨e, he⟩ ⟨chart_at H (e.symm (I.symm p.1)), _⟩ (e (e.symm (I.symm p.1))) p.2)) ((I.symm ⁻¹' (e.symm.trans e').source ∩ range I).prod (univ : set F)), { /- The coordinate change in the fiber is more complicated as its definition involves the reference chart chosen at each point. However, it appears with its inverse, so using the cocycle property one can get rid of it, and then conclude using the smoothness of the cocycle as given in the definition of basic smooth bundles. -/ have := Z.coord_change_smooth ⟨e, he⟩ ⟨e', he'⟩, rw model_with_corners.image at this, apply times_cont_diff_on.congr this, rintros ⟨x, v⟩ hx, simp only with mfld_simps at hx, let f := chart_at H (e.symm (I.symm x)), have A : I.symm x ∈ ((e.symm.trans f).trans (f.symm.trans e')).source, by simp only [hx.1.1, hx.1.2] with mfld_simps, rw e.right_inv hx.1.1, have := Z.coord_change_comp ⟨e, he⟩ ⟨f, chart_mem_atlas _ _⟩ ⟨e', he'⟩ (I.symm x) A v, simpa only [] using this } }, haveI : has_groupoid Z.to_topological_fiber_bundle_core.total_space (times_cont_diff_groupoid ⊤ (I.prod (model_with_corners_self 𝕜 F))) := begin split, assume e₀ e₀' he₀ he₀', rcases (Z.mem_atlas_iff _).1 he₀ with ⟨e, he, rfl⟩, rcases (Z.mem_atlas_iff _).1 he₀' with ⟨e', he', rfl⟩, rw [times_cont_diff_groupoid, mem_groupoid_of_pregroupoid], exact ⟨A e e' he he', A e' e he' he⟩ end, constructor end end basic_smooth_bundle_core section tangent_bundle variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {H : Type*} [topological_space H] (I : model_with_corners 𝕜 E H) (M : Type*) [topological_space M] [charted_space H M] [smooth_manifold_with_corners I M] /-- Basic smooth bundle core version of the tangent bundle of a smooth manifold `M` modelled over a model with corners `I` on `(E, H)`. The fibers are equal to `E`, and the coordinate change in the fiber corresponds to the derivative of the coordinate change in `M`. -/ def tangent_bundle_core : basic_smooth_bundle_core I M E := { coord_change := λi j x v, (fderiv_within 𝕜 (I ∘ j.1 ∘ i.1.symm ∘ I.symm) (range I) (I x) : E → E) v, coord_change_smooth := λi j, begin /- To check that the coordinate change of the bundle is smooth, one should just use the smoothness of the charts, and thus the smoothness of their derivatives. -/ rw model_with_corners.image, have A : times_cont_diff_on 𝕜 ⊤ (I ∘ (i.1.symm.trans j.1) ∘ I.symm) (I.symm ⁻¹' (i.1.symm.trans j.1).source ∩ range I) := (has_groupoid.compatible (times_cont_diff_groupoid ⊤ I) i.2 j.2).1, have B : unique_diff_on 𝕜 (I.symm ⁻¹' (i.1.symm.trans j.1).source ∩ range I) := I.unique_diff_preimage_source, have C : times_cont_diff_on 𝕜 ⊤ (λ (p : E × E), (fderiv_within 𝕜 (I ∘ j.1 ∘ i.1.symm ∘ I.symm) (I.symm ⁻¹' (i.1.symm.trans j.1).source ∩ range I) p.1 : E → E) p.2) ((I.symm ⁻¹' (i.1.symm.trans j.1).source ∩ range I).prod univ) := times_cont_diff_on_fderiv_within_apply A B le_top, have D : ∀ x ∈ (I.symm ⁻¹' (i.1.symm.trans j.1).source ∩ range I), fderiv_within 𝕜 (I ∘ j.1 ∘ i.1.symm ∘ I.symm) (range I) x = fderiv_within 𝕜 (I ∘ j.1 ∘ i.1.symm ∘ I.symm) (I.symm ⁻¹' (i.1.symm.trans j.1).source ∩ range I) x, { assume x hx, have N : I.symm ⁻¹' (i.1.symm.trans j.1).source ∈ nhds x := I.continuous_symm.continuous_at.preimage_mem_nhds (mem_nhds_sets (local_homeomorph.open_source _) hx.1), symmetry, rw inter_comm, exact fderiv_within_inter N (I.unique_diff _ hx.2) }, apply times_cont_diff_on.congr C, rintros ⟨x, v⟩ hx, have E : x ∈ I.symm ⁻¹' (i.1.symm.trans j.1).source ∩ range I, by simpa only [prod_mk_mem_set_prod_eq, and_true, mem_univ] using hx, have : I (I.symm x) = x, by simp [E.2], dsimp [-subtype.val_eq_coe], rw [this, D x E], refl end, coord_change_self := λi x hx v, begin /- Locally, a self-change of coordinate is just the identity, thus its derivative is the identity. One just needs to write this carefully, paying attention to the sets where the functions are defined. -/ have A : I.symm ⁻¹' (i.1.symm.trans i.1).source ∩ range I ∈ nhds_within (I x) (range I), { rw inter_comm, apply inter_mem_nhds_within, apply I.continuous_symm.continuous_at.preimage_mem_nhds (mem_nhds_sets (local_homeomorph.open_source _) _), simp only [hx, i.1.map_target] with mfld_simps }, have B : ∀ᶠ y in nhds_within (I x) (range I), (I ∘ i.1 ∘ i.1.symm ∘ I.symm) y = (id : E → E) y, { apply filter.mem_sets_of_superset A, assume y hy, rw ← model_with_corners.image at hy, rcases hy with ⟨z, hz⟩, simp only with mfld_simps at hz, simp only [hz.2.symm, hz.1] with mfld_simps }, have C : fderiv_within 𝕜 (I ∘ i.1 ∘ i.1.symm ∘ I.symm) (range I) (I x) = fderiv_within 𝕜 (id : E → E) (range I) (I x) := fderiv_within_congr_of_mem_nhds_within I.unique_diff_at_image B (by simp only [hx] with mfld_simps), rw fderiv_within_id I.unique_diff_at_image at C, rw C, refl end, coord_change_comp := λi j u x hx, begin /- The cocycle property is just the fact that the derivative of a composition is the product of the derivatives. One needs however to check that all the functions one considers are smooth, and to pay attention to the domains where these functions are defined, making this proof a little bit cumbersome although there is nothing complicated here. -/ have M : I x ∈ (I.symm ⁻¹' ((i.1.symm.trans j.1).trans (j.1.symm.trans u.1)).source ∩ range I) := ⟨by simpa only [mem_preimage, model_with_corners.left_inv] using hx, mem_range_self _⟩, have U : unique_diff_within_at 𝕜 (I.symm ⁻¹' ((i.1.symm.trans j.1).trans (j.1.symm.trans u.1)).source ∩ range I) (I x) := I.unique_diff_preimage_source _ M, have A : fderiv_within 𝕜 ((I ∘ u.1 ∘ j.1.symm ∘ I.symm) ∘ (I ∘ j.1 ∘ i.1.symm ∘ I.symm)) (I.symm ⁻¹' ((i.1.symm.trans j.1).trans (j.1.symm.trans u.1)).source ∩ range I) (I x) = (fderiv_within 𝕜 (I ∘ u.1 ∘ j.1.symm ∘ I.symm) (I.symm ⁻¹' (j.1.symm.trans u.1).source ∩ range I) ((I ∘ j.1 ∘ i.1.symm ∘ I.symm) (I x))).comp (fderiv_within 𝕜 (I ∘ j.1 ∘ i.1.symm ∘ I.symm) (I.symm ⁻¹' ((i.1.symm.trans j.1).trans (j.1.symm.trans u.1)).source ∩ range I) (I x)), { apply fderiv_within.comp _ _ _ _ U, show differentiable_within_at 𝕜 (I ∘ j.1 ∘ i.1.symm ∘ I.symm) (I.symm ⁻¹' ((i.1.symm.trans j.1).trans (j.1.symm.trans u.1)).source ∩ range I) (I x), { have A : times_cont_diff_on 𝕜 ⊤ (I ∘ (i.1.symm.trans j.1) ∘ I.symm) (I.symm ⁻¹' (i.1.symm.trans j.1).source ∩ range I) := (has_groupoid.compatible (times_cont_diff_groupoid ⊤ I) i.2 j.2).1, have B : differentiable_on 𝕜 (I ∘ j.1 ∘ i.1.symm ∘ I.symm) (I.symm ⁻¹' ((i.1.symm.trans j.1).trans (j.1.symm.trans u.1)).source ∩ range I), { apply (A.differentiable_on le_top).mono, have : ((i.1.symm.trans j.1).trans (j.1.symm.trans u.1)).source ⊆ (i.1.symm.trans j.1).source := inter_subset_left _ _, exact inter_subset_inter (preimage_mono this) (subset.refl (range I)) }, apply B, simpa only [] with mfld_simps using hx }, show differentiable_within_at 𝕜 (I ∘ u.1 ∘ j.1.symm ∘ I.symm) (I.symm ⁻¹' (j.1.symm.trans u.1).source ∩ range I) ((I ∘ j.1 ∘ i.1.symm ∘ I.symm) (I x)), { have A : times_cont_diff_on 𝕜 ⊤ (I ∘ (j.1.symm.trans u.1) ∘ I.symm) (I.symm ⁻¹' (j.1.symm.trans u.1).source ∩ range I) := (has_groupoid.compatible (times_cont_diff_groupoid ⊤ I) j.2 u.2).1, apply A.differentiable_on le_top, rw [local_homeomorph.trans_source] at hx, simp only with mfld_simps, exact hx.2 }, show (I.symm ⁻¹' ((i.1.symm.trans j.1).trans (j.1.symm.trans u.1)).source ∩ range I) ⊆ (I ∘ j.1 ∘ i.1.symm ∘ I.symm) ⁻¹' (I.symm ⁻¹' (j.1.symm.trans u.1).source ∩ range I), { assume y hy, simp only with mfld_simps at hy, rw [local_homeomorph.left_inv] at hy, { simp only [hy] with mfld_simps }, { exact hy.1.1.2 } } }, have B : fderiv_within 𝕜 ((I ∘ u.1 ∘ j.1.symm ∘ I.symm) ∘ (I ∘ j.1 ∘ i.1.symm ∘ I.symm)) (I.symm ⁻¹' ((i.1.symm.trans j.1).trans (j.1.symm.trans u.1)).source ∩ range I) (I x) = fderiv_within 𝕜 (I ∘ u.1 ∘ i.1.symm ∘ I.symm) (I.symm ⁻¹' ((i.1.symm.trans j.1).trans (j.1.symm.trans u.1)).source ∩ range I) (I x), { have E : ∀ y ∈ (I.symm ⁻¹' ((i.1.symm.trans j.1).trans (j.1.symm.trans u.1)).source ∩ range I), ((I ∘ u.1 ∘ j.1.symm ∘ I.symm) ∘ (I ∘ j.1 ∘ i.1.symm ∘ I.symm)) y = (I ∘ u.1 ∘ i.1.symm ∘ I.symm) y, { assume y hy, simp only [function.comp_app, model_with_corners.left_inv], rw [j.1.left_inv], exact hy.1.1.2 }, exact fderiv_within_congr U E (E _ M) }, have C : fderiv_within 𝕜 (I ∘ u.1 ∘ i.1.symm ∘ I.symm) (I.symm ⁻¹' ((i.1.symm.trans j.1).trans (j.1.symm.trans u.1)).source ∩ range I) (I x) = fderiv_within 𝕜 (I ∘ u.1 ∘ i.1.symm ∘ I.symm) (range I) (I x), { rw inter_comm, apply fderiv_within_inter _ I.unique_diff_at_image, apply I.continuous_symm.continuous_at.preimage_mem_nhds (mem_nhds_sets (local_homeomorph.open_source _) _), simpa only [model_with_corners.left_inv] using hx }, have D : fderiv_within 𝕜 (I ∘ u.1 ∘ j.1.symm ∘ I.symm) (I.symm ⁻¹' (j.1.symm.trans u.1).source ∩ range I) ((I ∘ j.1 ∘ i.1.symm ∘ I.symm) (I x)) = fderiv_within 𝕜 (I ∘ u.1 ∘ j.1.symm ∘ I.symm) (range I) ((I ∘ j.1 ∘ i.1.symm ∘ I.symm) (I x)), { rw inter_comm, apply fderiv_within_inter _ I.unique_diff_at_image, apply I.continuous_symm.continuous_at.preimage_mem_nhds (mem_nhds_sets (local_homeomorph.open_source _) _), rw [local_homeomorph.trans_source] at hx, simp only with mfld_simps, exact hx.2 }, have E : fderiv_within 𝕜 (I ∘ j.1 ∘ i.1.symm ∘ I.symm) (I.symm ⁻¹' ((i.1.symm.trans j.1).trans (j.1.symm.trans u.1)).source ∩ range I) (I x) = fderiv_within 𝕜 (I ∘ j.1 ∘ i.1.symm ∘ I.symm) (range I) (I x), { rw inter_comm, apply fderiv_within_inter _ I.unique_diff_at_image, apply I.continuous_symm.continuous_at.preimage_mem_nhds (mem_nhds_sets (local_homeomorph.open_source _) _), simpa only [model_with_corners.left_inv] using hx }, rw [B, C, D, E] at A, simp only [A, continuous_linear_map.coe_comp'] with mfld_simps end } /-- The tangent bundle to a smooth manifold, as a plain type. -/ @[nolint has_inhabited_instance] -- is empty if the base manifold is empty def tangent_bundle := (tangent_bundle_core I M).to_topological_fiber_bundle_core.total_space /-- The projection from the tangent bundle of a smooth manifold to the manifold. As the tangent bundle is represented internally as a product type, the notation `p.1` also works for the projection of the point `p`. -/ def tangent_bundle.proj : tangent_bundle I M → M := (tangent_bundle_core I M).to_topological_fiber_bundle_core.proj variable {M} /-- The tangent space at a point of the manifold `M`. It is just `E`. -/ def tangent_space (x : M) : Type* := (tangent_bundle_core I M).to_topological_fiber_bundle_core.fiber x section tangent_bundle_instances /- In general, the definition of tangent_bundle and tangent_space are not reducible, so that type class inference does not pick wrong instances. In this section, we record the right instances for them, noting in particular that the tangent bundle is a smooth manifold. -/ variable (M) local attribute [reducible] tangent_bundle instance : topological_space (tangent_bundle I M) := by apply_instance instance : charted_space (H × E) (tangent_bundle I M) := by apply_instance instance : smooth_manifold_with_corners I.tangent (tangent_bundle I M) := by apply_instance local attribute [reducible] tangent_space topological_fiber_bundle_core.fiber /- When `topological_fiber_bundle_core.fiber` is reducible, then `topological_fiber_bundle_core.topological_space_fiber` can be applied to prove that any space is a topological space, with several unknown metavariables. This is a bad instance, that we disable.-/ local attribute [instance, priority 0] topological_fiber_bundle_core.topological_space_fiber variables {M} (x : M) instance : topological_module 𝕜 (tangent_space I x) := by apply_instance instance : topological_space (tangent_space I x) := by apply_instance instance : add_comm_group (tangent_space I x) := by apply_instance instance : topological_add_group (tangent_space I x) := by apply_instance instance : vector_space 𝕜 (tangent_space I x) := by apply_instance instance : inhabited (tangent_space I x) := ⟨0⟩ end tangent_bundle_instances variable (M) /-- The tangent bundle projection on the basis is a continuous map. -/ lemma tangent_bundle_proj_continuous : continuous (tangent_bundle.proj I M) := topological_fiber_bundle_core.continuous_proj _ /-- The tangent bundle projection on the basis is an open map. -/ lemma tangent_bundle_proj_open : is_open_map (tangent_bundle.proj I M) := topological_fiber_bundle_core.is_open_map_proj _ /-- In the tangent bundle to the model space, the charts are just the identity-/ @[simp, mfld_simps] lemma tangent_bundle_model_space_chart_at (p : tangent_bundle I H) : (chart_at (H × E) p).to_local_equiv = local_equiv.refl (H × E) := begin have A : ∀ x_fst, fderiv_within 𝕜 (I ∘ I.symm) (range I) (I x_fst) = continuous_linear_map.id 𝕜 E, { assume x_fst, have : fderiv_within 𝕜 (I ∘ I.symm) (range I) (I x_fst) = fderiv_within 𝕜 id (range I) (I x_fst), { refine fderiv_within_congr I.unique_diff_at_image (λy hy, _) (by simp), exact model_with_corners.right_inv _ hy }, rwa fderiv_within_id I.unique_diff_at_image at this }, ext x : 1, show (chart_at (H × E) p : tangent_bundle I H → H × E) x = (local_equiv.refl (H × E)) x, { cases x, simp only [chart_at, basic_smooth_bundle_core.chart, topological_fiber_bundle_core.local_triv, topological_fiber_bundle_core.local_triv', tangent_bundle_core, A, continuous_linear_map.coe_id', basic_smooth_bundle_core.to_topological_fiber_bundle_core] with mfld_simps }, show ∀ x, ((chart_at (H × E) p).to_local_equiv).symm x = (local_equiv.refl (H × E)).symm x, { rintros ⟨x_fst, x_snd⟩, simp only [chart_at, basic_smooth_bundle_core.chart, topological_fiber_bundle_core.local_triv, topological_fiber_bundle_core.local_triv', tangent_bundle_core, A, continuous_linear_map.coe_id', basic_smooth_bundle_core.to_topological_fiber_bundle_core] with mfld_simps}, show ((chart_at (H × E) p).to_local_equiv).source = (local_equiv.refl (H × E)).source, by simp only [chart_at] with mfld_simps, end @[simp, mfld_simps] lemma tangent_bundle_model_space_coe_chart_at (p : tangent_bundle I H) : (chart_at (H × E) p : tangent_bundle I H → H × E) = id := by { unfold_coes, simp only with mfld_simps } @[simp, mfld_simps] lemma tangent_bundle_model_space_coe_chart_at_symm (p : tangent_bundle I H) : ((chart_at (H × E) p).symm : H × E → tangent_bundle I H) = id := by { unfold_coes, simp only with mfld_simps, refl } variable (H) /-- In the tangent bundle to the model space, the topology is the product topology, i.e., the bundle is trivial -/ lemma tangent_bundle_model_space_topology_eq_prod : tangent_bundle.topological_space I H = prod.topological_space := begin ext o, let x : tangent_bundle I H := (I.symm (0 : E), (0 : E)), let e := chart_at (H × E) x, have e_source : e.source = univ, by { simp only with mfld_simps, refl }, have e_target : e.target = univ, by { simp only with mfld_simps, refl }, let e' := e.to_homeomorph_of_source_eq_univ_target_eq_univ e_source e_target, split, { assume ho, simpa only [] with mfld_simps using e'.symm.continuous o ho }, { assume ho, simpa only [] with mfld_simps using e'.continuous o ho } end end tangent_bundle
39936ed92fa4462ab550bcd3b244c0165fb6c5b3
fcf3ffa92a3847189ca669cb18b34ef6b2ec2859
/src/world7/level2.lean
69baa6dcceae834db7d1f27ad9cecb39d8108126
[ "Apache-2.0" ]
permissive
nomoid/lean-proofs
4a80a97888699dee42b092b7b959b22d9aa0c066
b9f03a24623d1a1d111d6c2bbf53c617e2596d6a
refs/heads/master
1,674,955,317,080
1,607,475,706,000
1,607,475,706,000
314,104,281
0
0
null
null
null
null
UTF-8
Lean
false
false
172
lean
lemma and_symm (P Q : Prop) : (P ∧ Q) → (Q ∧ P) := begin intro h, cases h with p q, split, { exact q, }, { exact p, }, end
1ea657422d0af9370f7434ea5fcd37ba34d1e335
618003631150032a5676f229d13a079ac875ff77
/test/packaged_goal.lean
df6c66c552a3f1a9d5e62371d76abeae74334116
[ "Apache-2.0" ]
permissive
awainverse/mathlib
939b68c8486df66cfda64d327ad3d9165248c777
ea76bd8f3ca0a8bf0a166a06a475b10663dec44a
refs/heads/master
1,659,592,962,036
1,590,987,592,000
1,590,987,592,000
268,436,019
1
0
Apache-2.0
1,590,990,500,000
1,590,990,500,000
null
UTF-8
Lean
false
false
819
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 tactic.core open tactic /-- Demonstrate the packaged goals and how comparison of dependent goals works. -/ example (m n : ℕ) : m = n := by do { let tac := `[cases m; apply fin.mk.inj], gs₀ ← retrieve $ tac >> get_goals, gs₁ ← retrieve $ tac >> get_goals, guard (gs₀ ≠ gs₁ : bool), gs₀ ← get_proof_state_after tac, gs₁ ← get_proof_state_after tac, guard (gs₀ = gs₁), gs₀ ← get_proof_state_after $ tac >> swap, gs₁ ← get_proof_state_after tac, guard (gs₀ ≠ gs₁), gs₀ ← get_proof_state_after $ tac >> swap, gs₁ ← get_proof_state_after $ tac >> swap, guard (gs₀ = gs₁), tactic.admit }
2e44beaddccdbe2e0523edf695355ed8e84ab851
ad0c7d243dc1bd563419e2767ed42fb323d7beea
/analysis/measure_theory/outer_measure.lean
742d8bb00b55c789d66b979257261cd6cffaf2a2
[ "Apache-2.0" ]
permissive
sebzim4500/mathlib
e0b5a63b1655f910dee30badf09bd7e191d3cf30
6997cafbd3a7325af5cb318561768c316ceb7757
refs/heads/master
1,585,549,958,618
1,538,221,723,000
1,538,221,723,000
150,869,076
0
0
Apache-2.0
1,538,229,323,000
1,538,229,323,000
null
UTF-8
Lean
false
false
18,189
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 Outer measures -- overapproximations of measures -/ import order.galois_connection algebra.big_operators algebra.module analysis.ennreal analysis.limits analysis.measure_theory.measurable_space noncomputable theory open set lattice finset function filter encodable local attribute [instance] classical.prop_decidable namespace measure_theory structure outer_measure (α : Type*) := (measure_of : set α → ennreal) (empty : measure_of ∅ = 0) (mono : ∀{s₁ s₂}, s₁ ⊆ s₂ → measure_of s₁ ≤ measure_of s₂) (Union_nat : ∀(s:ℕ → set α), measure_of (⋃i, s i) ≤ (∑i, measure_of (s i))) namespace outer_measure instance {α} : has_coe_to_fun (outer_measure α) := ⟨_, λ m, m.measure_of⟩ section basic variables {α : Type*} {ms : set (outer_measure α)} {m : outer_measure α} @[simp] theorem empty' (m : outer_measure α) : m ∅ = 0 := m.empty theorem mono' (m : outer_measure α) {s₁ s₂} (h : s₁ ⊆ s₂) : m s₁ ≤ m s₂ := m.mono h theorem Union_aux (m : set α → ennreal) (m0 : m ∅ = 0) {β} [encodable β] (s : β → set α) : (∑ b, m (s b)) = ∑ i, m (⋃ b ∈ decode2 β i, s b) := begin have H : ∀ n, m (⋃ b ∈ decode2 β n, s b) ≠ 0 → (decode2 β n).is_some, { intros n h, cases decode2 β n with b, { exact (h (by simp [m0])).elim }, { exact rfl } }, refine tsum_eq_tsum_of_ne_zero_bij (λ n h, option.get (H n h)) _ _ _, { intros m n hm hn e, have := mem_decode2.1 (option.get_mem (H n hn)), rwa [← e, mem_decode2.1 (option.get_mem (H m hm))] at this }, { intros b h, refine ⟨encode b, _, _⟩, { convert h, simp [ext_iff, encodek2] }, { exact option.get_of_mem _ (encodek2 _) } }, { intros n h, transitivity, swap, rw [show decode2 β n = _, from option.get_mem (H n h)], congr, simp [ext_iff] } end protected theorem Union (m : outer_measure α) {β} [encodable β] (s : β → set α) : m (⋃i, s i) ≤ (∑i, m (s i)) := by rw [Union_decode2, Union_aux _ m.empty' s]; exact m.Union_nat _ lemma Union_null (m : outer_measure α) {β} [encodable β] {s : β → set α} (h : ∀ i, m (s i) = 0) : m (⋃i, s i) = 0 := by simpa [h] using m.Union s protected lemma union (m : outer_measure α) (s₁ s₂ : set α) : m (s₁ ∪ s₂) ≤ m s₁ + m s₂ := begin convert m.Union (λ b, cond b s₁ s₂), { simp [union_eq_Union] }, { rw tsum_fintype, change _ = _ + _, simp } end lemma union_null (m : outer_measure α) {s₁ s₂ : set α} (h₁ : m s₁ = 0) (h₂ : m s₂ = 0) : m (s₁ ∪ s₂) = 0 := by simpa [h₁, h₂] using m.union s₁ s₂ @[extensionality] lemma ext : ∀{μ₁ μ₂ : outer_measure α}, (∀s, μ₁ s = μ₂ s) → μ₁ = μ₂ | ⟨m₁, e₁, _, u₁⟩ ⟨m₂, e₂, _, u₂⟩ h := by congr; exact funext h instance : has_zero (outer_measure α) := ⟨{ measure_of := λ_, 0, empty := rfl, mono := assume _ _ _, le_refl 0, Union_nat := assume s, zero_le _ }⟩ @[simp] theorem zero_apply (s : set α) : (0 : outer_measure α) s = 0 := rfl instance : inhabited (outer_measure α) := ⟨0⟩ instance : has_add (outer_measure α) := ⟨λm₁ m₂, { measure_of := λs, m₁ s + m₂ s, empty := show m₁ ∅ + m₂ ∅ = 0, by simp [outer_measure.empty], mono := assume s₁ s₂ h, add_le_add' (m₁.mono h) (m₂.mono h), Union_nat := assume s, calc m₁ (⋃i, s i) + m₂ (⋃i, s i) ≤ (∑i, m₁ (s i)) + (∑i, m₂ (s i)) : add_le_add' (m₁.Union_nat s) (m₂.Union_nat s) ... = _ : ennreal.tsum_add.symm}⟩ @[simp] theorem add_apply (m₁ m₂ : outer_measure α) (s : set α) : (m₁ + m₂) s = m₁ s + m₂ s := rfl instance : add_comm_monoid (outer_measure α) := { zero := 0, add := (+), add_comm := assume a b, ext $ assume s, add_comm _ _, add_assoc := assume a b c, ext $ assume s, add_assoc _ _ _, add_zero := assume a, ext $ assume s, add_zero _, zero_add := assume a, ext $ assume s, zero_add _ } instance : has_bot (outer_measure α) := ⟨0⟩ instance outer_measure.order_bot : order_bot (outer_measure α) := { le := λm₁ m₂, ∀s, m₁ s ≤ m₂ s, bot := 0, le_refl := assume a s, le_refl _, le_trans := assume a b c hab hbc s, le_trans (hab s) (hbc s), le_antisymm := assume a b hab hba, ext $ assume s, le_antisymm (hab s) (hba s), bot_le := assume a s, zero_le _ } section supremum instance : has_Sup (outer_measure α) := ⟨λms, { measure_of := λs, ⨆m:ms, m.val s, empty := le_zero_iff_eq.1 $ supr_le $ λ ⟨m, h⟩, le_of_eq m.empty, mono := assume s₁ s₂ hs, supr_le_supr $ assume ⟨m, hm⟩, m.mono hs, Union_nat := assume f, supr_le $ assume m, calc m.val (⋃i, f i) ≤ (∑ (i : ℕ), m.val (f i)) : m.val.Union_nat _ ... ≤ (∑i, ⨆m:ms, m.val (f i)) : ennreal.tsum_le_tsum $ assume i, le_supr (λm:ms, m.val (f i)) m }⟩ private lemma le_Sup (hm : m ∈ ms) : m ≤ Sup ms := λ s, le_supr (λm:ms, m.val s) ⟨m, hm⟩ private lemma Sup_le (hm : ∀m' ∈ ms, m' ≤ m) : Sup ms ≤ m := λ s, (supr_le $ assume ⟨m', h'⟩, (hm m' h') s) instance : has_Inf (outer_measure α) := ⟨λs, Sup {m | ∀m'∈s, m ≤ m'}⟩ private lemma Inf_le (hm : m ∈ ms) : Inf ms ≤ m := Sup_le $ assume m' h', h' _ hm private lemma le_Inf (hm : ∀m' ∈ ms, m ≤ m') : m ≤ Inf ms := le_Sup hm instance : complete_lattice (outer_measure α) := { top := Sup univ, le_top := assume a, le_Sup (mem_univ a), Sup := Sup, Sup_le := assume s m, Sup_le, le_Sup := assume s m, le_Sup, Inf := Inf, Inf_le := assume s m, Inf_le, le_Inf := assume s m, le_Inf, sup := λa b, Sup {a, b}, le_sup_left := assume a b, le_Sup $ by simp, le_sup_right := assume a b, le_Sup $ by simp, sup_le := assume a b c ha hb, Sup_le $ by simp [or_imp_distrib, ha, hb] {contextual:=tt}, inf := λa b, Inf {a, b}, inf_le_left := assume a b, Inf_le $ by simp, inf_le_right := assume a b, Inf_le $ by simp, le_inf := assume a b c ha hb, le_Inf $ by simp [or_imp_distrib, ha, hb] {contextual:=tt}, .. outer_measure.order_bot } @[simp] theorem Sup_apply (ms : set (outer_measure α)) (s : set α) : (Sup ms) s = ⨆ m : ms, m s := rfl @[simp] theorem supr_apply {ι} (f : ι → outer_measure α) (s : set α) : (⨆ i : ι, f i) s = ⨆ i, f i s := le_antisymm (supr_le $ λ ⟨_, i, rfl⟩, le_supr _ i) (supr_le $ λ i, le_supr (λ (m : {a : outer_measure α // ∃ i, a = f i}), m.1 s) ⟨f i, i, rfl⟩) @[simp] theorem sup_apply (m₁ m₂ : outer_measure α) (s : set α) : (m₁ ⊔ m₂) s = m₁ s ⊔ m₂ s := by have := supr_apply (λ b, cond b m₁ m₂) s; rwa [supr_bool_eq, supr_bool_eq] at this end supremum def map {β} (f : α → β) (m : outer_measure α) : outer_measure β := { measure_of := λs, m (f ⁻¹' s), empty := m.empty, mono := λ s t h, m.mono (preimage_mono h), Union_nat := λ s, by rw [preimage_Union]; exact m.Union_nat (λ i, f ⁻¹' s i) } @[simp] theorem map_apply {β} (f : α → β) (m : outer_measure α) (s : set β) : map f m s = m (f ⁻¹' s) := rfl @[simp] theorem map_id (m : outer_measure α) : map id m = m := ext $ λ s, rfl @[simp] theorem map_map {β γ} (f : α → β) (g : β → γ) (m : outer_measure α) : map g (map f m) = map (g ∘ f) m := ext $ λ s, rfl instance : functor outer_measure := {map := λ α β, map} instance : is_lawful_functor outer_measure := { id_map := λ α, map_id, comp_map := λ α β γ f g m, (map_map f g m).symm } /-- The dirac outer measure. -/ def dirac (a : α) : outer_measure α := { measure_of := λs, ⨆ h : a ∈ s, 1, empty := by simp, mono := λ s t h, supr_le_supr2 (λ h', ⟨h h', le_refl _⟩), Union_nat := λ s, supr_le $ λ h, let ⟨i, h⟩ := mem_Union.1 h in le_trans (by exact le_supr _ h) (ennreal.le_tsum i) } @[simp] theorem dirac_apply (a : α) (s : set α) : dirac a s = ⨆ h : a ∈ s, 1 := rfl def sum {ι} (f : ι → outer_measure α) : outer_measure α := { measure_of := λs, ∑ i, f i s, empty := by simp, mono := λ s t h, ennreal.tsum_le_tsum (λ i, (f i).mono' h), Union_nat := λ s, by rw ennreal.tsum_comm; exact ennreal.tsum_le_tsum (λ i, (f i).Union_nat _) } @[simp] theorem sum_apply {ι} (f : ι → outer_measure α) (s : set α) : sum f s = ∑ i, f i s := rfl instance : has_scalar ennreal (outer_measure α) := ⟨λ a m, { measure_of := λs, a * m s, empty := by simp, mono := λ s t h, canonically_ordered_semiring.mul_le_mul (le_refl _) (m.mono' h), Union_nat := λ s, by rw ennreal.mul_tsum; exact canonically_ordered_semiring.mul_le_mul (le_refl _) (m.Union_nat _) }⟩ @[simp] theorem smul_apply (a : ennreal) (m : outer_measure α) (s : set α) : (a • m) s = a * m s := rfl instance : semimodule ennreal (outer_measure α) := { smul_add := λ a m₁ m₂, ext $ λ s, mul_add _ _ _, add_smul := λ a b m, ext $ λ s, add_mul _ _ _, mul_smul := λ a b m, ext $ λ s, mul_assoc _ _ _, one_smul := λ m, ext $ λ s, one_mul _, zero_smul := λ m, ext $ λ s, zero_mul _, smul_zero := λ a, ext $ λ s, mul_zero _, ..outer_measure.has_scalar } theorem smul_dirac_apply (a : ennreal) (b : α) (s : set α) : (a • dirac b) s = ⨆ h : b ∈ s, a := by by_cases b ∈ s; simp [h] theorem top_apply {s : set α} (h : s ≠ ∅) : (⊤ : outer_measure α) s = ⊤ := let ⟨a, as⟩ := set.exists_mem_of_ne_empty h in top_unique $ le_supr_of_le ⟨⊤ • dirac a, trivial⟩ $ by simp [smul_dirac_apply, as] end basic section of_function set_option eqn_compiler.zeta true /-- Given any function `m` assigning measures to sets satisying `m ∅ = 0`, there is a unique maximal outer measure `μ` satisfying `μ s ≤ m s` for all `s : set α`. -/ protected def of_function {α : Type*} (m : set α → ennreal) (m_empty : m ∅ = 0) : outer_measure α := let μ := λs, ⨅{f : ℕ → set α} (h : s ⊆ ⋃i, f i), ∑i, m (f i) in { measure_of := μ, empty := le_antisymm (infi_le_of_le (λ_, ∅) $ infi_le_of_le (empty_subset _) $ by simp [m_empty]) (zero_le _), mono := assume s₁ s₂ hs, infi_le_infi $ assume f, infi_le_infi2 $ assume hb, ⟨subset.trans hs hb, le_refl _⟩, Union_nat := assume s, ennreal.le_of_forall_epsilon_le $ begin assume ε hε (hb : (∑i, μ (s i)) < ⊤), rcases ennreal.exists_pos_sum_of_encodable (ennreal.coe_lt_coe.2 hε) ℕ with ⟨ε', hε', hl⟩, refine le_trans _ (add_le_add_left' (le_of_lt hl)), rw ← ennreal.tsum_add, have : ∀i, ∃f:ℕ → set α, s i ⊆ (⋃i, f i) ∧ (∑i, m (f i)) < μ (s i) + ε' i, { intro, have : μ (s i) < μ (s i) + ε' i := ennreal.lt_add_right (lt_of_le_of_lt (by apply ennreal.le_tsum) hb) (by simpa using hε' i), simpa [μ, infi_lt_iff] }, cases classical.axiom_of_choice this with f hf, dsimp at f hf, clear this, refine le_trans _ (ennreal.tsum_le_tsum $ λ i, le_of_lt (hf i).2), rw [← ennreal.tsum_prod, ← tsum_equiv equiv.nat_prod_nat_equiv_nat.symm], swap, {apply_instance}, refine infi_le_of_le _ (infi_le _ _), exact Union_subset (λ i, subset.trans (hf i).1 $ Union_subset $ λ j, subset.trans (by simp) $ subset_Union _ $ equiv.nat_prod_nat_equiv_nat (i, j)), end } theorem of_function_le {α : Type*} (m : set α → ennreal) (m_empty s) : outer_measure.of_function m m_empty s ≤ m s := let f : ℕ → set α := λi, nat.rec_on i s (λn s, ∅) in infi_le_of_le f $ infi_le_of_le (subset_Union f 0) $ le_of_eq $ calc (∑i, m (f i)) = ({0} : finset ℕ).sum (λi, m (f i)) : tsum_eq_sum $ by intro i; cases i; simp [m_empty] ... = m s : by simp; refl theorem le_of_function {α : Type*} {m m_empty} {μ : outer_measure α} : μ ≤ outer_measure.of_function m m_empty ↔ ∀ s, μ s ≤ m s := ⟨λ H s, le_trans (H _) (of_function_le _ _ _), λ H s, le_infi $ λ f, le_infi $ λ hs, le_trans (μ.mono hs) $ le_trans (μ.Union f) $ ennreal.tsum_le_tsum $ λ i, H _⟩ end of_function section caratheodory_measurable universe u parameters {α : Type u} (m : outer_measure α) include m local attribute [simp] set.inter_comm set.inter_left_comm set.inter_assoc variables {s s₁ s₂ : set α} private def C (s : set α) := ∀t, m t = m (t ∩ s) + m (t \ s) private lemma C_iff_le {s : set α} : C s ↔ ∀t, m (t ∩ s) + m (t \ s) ≤ m t := forall_congr $ λ t, le_antisymm_iff.trans $ and_iff_right $ by convert m.union _ _; rw inter_union_diff t s @[simp] private lemma C_empty : C ∅ := by simp [C, m.empty, diff_empty] private lemma C_compl : C s₁ → C (- s₁) := by simp [C, diff_eq] @[simp] private lemma C_compl_iff : C (- s) ↔ C s := ⟨λ h, by simpa using C_compl m h, C_compl⟩ private lemma C_union (h₁ : C s₁) (h₂ : C s₂) : C (s₁ ∪ s₂) := λ t, begin rw [h₁ t, h₂ (t ∩ s₁), h₂ (t \ s₁), h₁ (t ∩ (s₁ ∪ s₂)), inter_diff_assoc _ _ s₁, set.inter_assoc _ _ s₁, inter_eq_self_of_subset_right (set.subset_union_left _ _), union_diff_left, h₂ (t ∩ s₁)], simp [diff_eq] end private lemma measure_inter_union (h : s₁ ∩ s₂ ⊆ ∅) (h₁ : C s₁) {t : set α} : m (t ∩ (s₁ ∪ s₂)) = m (t ∩ s₁) + m (t ∩ s₂) := by rw [h₁, set.inter_assoc, union_inter_cancel_left h, inter_diff_assoc, union_diff_cancel_left h] private lemma C_Union_lt {s : ℕ → set α} : ∀{n:ℕ}, (∀i<n, C (s i)) → C (⋃i<n, s i) | 0 h := by simp [nat.not_lt_zero] | (n + 1) h := by rw Union_lt_succ; exact C_union m (h n (le_refl (n + 1))) (C_Union_lt $ assume i hi, h i $ lt_of_lt_of_le hi $ nat.le_succ _) private lemma C_inter (h₁ : C s₁) (h₂ : C s₂) : C (s₁ ∩ s₂) := by rw [← C_compl_iff, compl_inter]; from C_union _ (C_compl _ h₁) (C_compl _ h₂) private lemma C_sum {s : ℕ → set α} (h : ∀i, C (s i)) (hd : pairwise (disjoint on s)) {t : set α} : ∀ {n}, (finset.range n).sum (λi, m (t ∩ s i)) = m (t ∩ ⋃i<n, s i) | 0 := by simp [nat.not_lt_zero, m.empty] | (nat.succ n) := begin simp [Union_lt_succ], rw [measure_inter_union m _ (h n), C_sum], intro a, simpa using λ h₁ i hi h₂, hd _ _ (ne_of_gt hi) ⟨h₁, h₂⟩ end private lemma C_Union_nat {s : ℕ → set α} (h : ∀i, C (s i)) (hd : pairwise (disjoint on s)) : C (⋃i, s i) := C_iff_le.2 $ λ t, begin have hp : m (t ∩ ⋃i, s i) ≤ (⨆n, m (t ∩ ⋃i<n, s i)), { convert m.Union (λ i, t ∩ s i), { rw inter_Union_left }, { simp [ennreal.tsum_eq_supr_nat, C_sum m h hd] } }, refine le_trans (add_le_add_right' hp) _, rw ennreal.supr_add, refine supr_le (λ n, le_trans (add_le_add_left' _) (ge_of_eq (C_Union_lt m (λ i _, h i) _))), refine m.mono (diff_subset_diff_right _), exact bUnion_subset (λ i _, subset_Union _ i), end private lemma f_Union {s : ℕ → set α} (h : ∀i, C (s i)) (hd : pairwise (disjoint on s)) : m (⋃i, s i) = ∑i, m (s i) := begin refine le_antisymm (m.Union_nat s) _, rw ennreal.tsum_eq_supr_nat, refine supr_le (λ n, _), have := @C_sum _ m _ h hd univ n, simp at this, simp [this], exact m.mono (bUnion_subset (λ i _, subset_Union _ i)), end private def caratheodory_dynkin : measurable_space.dynkin_system α := { has := C, has_empty := C_empty, has_compl := assume s, C_compl, has_Union_nat := assume f hf hn, C_Union_nat hn hf } /-- Given an outer measure `μ`, the Caratheodory measurable space is defined such that `s` is measurable if `∀t, μ t = μ (t ∩ s) + μ (t \ s)`. -/ protected def caratheodory : measurable_space α := caratheodory_dynkin.to_measurable_space $ assume s₁ s₂, C_inter lemma is_caratheodory {s : set α} : caratheodory.is_measurable s ↔ ∀t, m t = m (t ∩ s) + m (t \ s) := iff.rfl lemma is_caratheodory_le {s : set α} : caratheodory.is_measurable s ↔ ∀t, m (t ∩ s) + m (t \ s) ≤ m t := C_iff_le protected lemma Union_eq_of_caratheodory {s : ℕ → set α} (h : ∀i, caratheodory.is_measurable (s i)) (hd : pairwise (disjoint on s)) : m (⋃i, s i) = ∑i, m (s i) := f_Union h hd end caratheodory_measurable variables {α : Type*} lemma caratheodory_is_measurable {m : set α → ennreal} {s : set α} {h₀ : m ∅ = 0} (hs : ∀t, m (t ∩ s) + m (t \ s) ≤ m t) : (outer_measure.of_function m h₀).caratheodory.is_measurable s := let o := (outer_measure.of_function m h₀) in (is_caratheodory_le o).2 $ λ t, le_infi $ λ f, le_infi $ λ hf, begin refine le_trans (add_le_add' (infi_le_of_le (λi, f i ∩ s) $ infi_le _ _) (infi_le_of_le (λi, f i \ s) $ infi_le _ _)) _, { rw ← inter_Union_right, exact inter_subset_inter_left _ hf }, { rw ← diff_Union_right, exact diff_subset_diff_left hf }, { rw ← ennreal.tsum_add, exact ennreal.tsum_le_tsum (λ i, hs _) } end @[simp] theorem zero_caratheodory : (0 : outer_measure α).caratheodory = ⊤ := top_unique $ λ s _ t, (add_zero _).symm theorem le_add_caratheodory (m₁ m₂ : outer_measure α) : m₁.caratheodory ⊓ m₂.caratheodory ≤ (m₁ + m₂ : outer_measure α).caratheodory := λ s ⟨hs₁, hs₂⟩ t, by simp [hs₁ t, hs₂ t] theorem le_sum_caratheodory {ι} (m : ι → outer_measure α) : (⨅ i, (m i).caratheodory) ≤ (sum m).caratheodory := λ s h t, by simp [λ i, measurable_space.is_measurable_infi.1 h i t, ennreal.tsum_add] theorem le_smul_caratheodory (a : ennreal) (m : outer_measure α) : m.caratheodory ≤ (a • m).caratheodory := λ s h t, by simp [h t, mul_add] @[simp] theorem dirac_caratheodory (a : α) : (dirac a).caratheodory = ⊤ := top_unique $ λ s _ t, begin by_cases a ∈ t; simp [h], by_cases a ∈ s; simp [h] end end outer_measure end measure_theory
d0587e0bddf83ced7c2ea34ddb1e22baa8e443d8
4727251e0cd73359b15b664c3170e5d754078599
/src/algebra/invertible.lean
f1ab5c27eaf508facd6bd4990a37b998af89a43c
[ "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
10,420
lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen -/ import algebra.group.units import algebra.ring.basic /-! # Invertible elements This file defines a typeclass `invertible a` for elements `a` with a two-sided multiplicative inverse. The intent of the typeclass is to provide a way to write e.g. `⅟2` in a ring like `ℤ[1/2]` where some inverses exist but there is no general `⁻¹` operator; or to specify that a field has characteristic `≠ 2`. It is the `Type`-valued analogue to the `Prop`-valued `is_unit`. For constructions of the invertible element given a characteristic, see `algebra/char_p/invertible` and other lemmas in that file. ## Notation * `⅟a` is `invertible.inv_of a`, the inverse of `a` ## Implementation notes The `invertible` class lives in `Type`, not `Prop`, to make computation easier. If multiplication is associative, `invertible` is a subsingleton anyway. The `simp` normal form tries to normalize `⅟a` to `a ⁻¹`. Otherwise, it pushes `⅟` inside the expression as much as possible. Since `invertible a` is not a `Prop` (but it is a `subsingleton`), we have to be careful about coherence issues: we should avoid having multiple non-defeq instances for `invertible a` in the same context. This file plays it safe and uses `def` rather than `instance` for most definitions, users can choose which instances to use at the point of use. For example, here's how you can use an `invertible 1` instance: ```lean variables {α : Type*} [monoid α] def something_that_needs_inverses (x : α) [invertible x] := sorry section local attribute [instance] invertible_one def something_one := something_that_needs_inverses 1 end ``` ## Tags invertible, inverse element, inv_of, a half, one half, a third, one third, ½, ⅓ -/ universes u variables {α : Type u} /-- `invertible a` gives a two-sided multiplicative inverse of `a`. -/ class invertible [has_mul α] [has_one α] (a : α) : Type u := (inv_of : α) (inv_of_mul_self : inv_of * a = 1) (mul_inv_of_self : a * inv_of = 1) -- This notation has the same precedence as `has_inv.inv`. notation `⅟`:1034 := invertible.inv_of @[simp] lemma inv_of_mul_self [has_mul α] [has_one α] (a : α) [invertible a] : ⅟a * a = 1 := invertible.inv_of_mul_self @[simp] lemma mul_inv_of_self [has_mul α] [has_one α] (a : α) [invertible a] : a * ⅟a = 1 := invertible.mul_inv_of_self @[simp] lemma inv_of_mul_self_assoc [monoid α] (a b : α) [invertible a] : ⅟a * (a * b) = b := by rw [←mul_assoc, inv_of_mul_self, one_mul] @[simp] lemma mul_inv_of_self_assoc [monoid α] (a b : α) [invertible a] : a * (⅟a * b) = b := by rw [←mul_assoc, mul_inv_of_self, one_mul] @[simp] lemma mul_inv_of_mul_self_cancel [monoid α] (a b : α) [invertible b] : a * ⅟b * b = a := by simp [mul_assoc] @[simp] lemma mul_mul_inv_of_self_cancel [monoid α] (a b : α) [invertible b] : a * b * ⅟b = a := by simp [mul_assoc] lemma inv_of_eq_right_inv [monoid α] {a b : α} [invertible a] (hac : a * b = 1) : ⅟a = b := left_inv_eq_right_inv (inv_of_mul_self _) hac lemma inv_of_eq_left_inv [monoid α] {a b : α} [invertible a] (hac : b * a = 1) : ⅟a = b := (left_inv_eq_right_inv hac (mul_inv_of_self _)).symm lemma invertible_unique {α : Type u} [monoid α] (a b : α) [invertible a] [invertible b] (h : a = b) : ⅟a = ⅟b := by { apply inv_of_eq_right_inv, rw [h, mul_inv_of_self], } instance [monoid α] (a : α) : subsingleton (invertible a) := ⟨ λ ⟨b, hba, hab⟩ ⟨c, hca, hac⟩, by { congr, exact left_inv_eq_right_inv hba hac } ⟩ /-- If `r` is invertible and `s = r`, then `s` is invertible. -/ def invertible.copy [monoid α] {r : α} (hr : invertible r) (s : α) (hs : s = r) : invertible s := { inv_of := ⅟r, inv_of_mul_self := by rw [hs, inv_of_mul_self], mul_inv_of_self := by rw [hs, mul_inv_of_self] } /-- An `invertible` element is a unit. -/ @[simps] def unit_of_invertible [monoid α] (a : α) [invertible a] : αˣ := { val := a, inv := ⅟a, val_inv := by simp, inv_val := by simp, } lemma is_unit_of_invertible [monoid α] (a : α) [invertible a] : is_unit a := ⟨unit_of_invertible a, rfl⟩ /-- Units are invertible in their associated monoid. -/ def units.invertible [monoid α] (u : αˣ) : invertible (u : α) := { inv_of := ↑(u⁻¹), inv_of_mul_self := u.inv_mul, mul_inv_of_self := u.mul_inv } @[simp] lemma inv_of_units [monoid α] (u : αˣ) [invertible (u : α)] : ⅟(u : α) = ↑(u⁻¹) := inv_of_eq_right_inv u.mul_inv lemma is_unit.nonempty_invertible [monoid α] {a : α} (h : is_unit a) : nonempty (invertible a) := let ⟨x, hx⟩ := h in ⟨x.invertible.copy _ hx.symm⟩ /-- Convert `is_unit` to `invertible` using `classical.choice`. Prefer `casesI h.nonempty_invertible` over `letI := h.invertible` if you want to avoid choice. -/ noncomputable def is_unit.invertible [monoid α] {a : α} (h : is_unit a) : invertible a := classical.choice h.nonempty_invertible @[simp] lemma nonempty_invertible_iff_is_unit [monoid α] (a : α) : nonempty (invertible a) ↔ is_unit a := ⟨nonempty.rec $ @is_unit_of_invertible _ _ _, is_unit.nonempty_invertible⟩ /-- Each element of a group is invertible. -/ def invertible_of_group [group α] (a : α) : invertible a := ⟨a⁻¹, inv_mul_self a, mul_inv_self a⟩ @[simp] lemma inv_of_eq_group_inv [group α] (a : α) [invertible a] : ⅟a = a⁻¹ := inv_of_eq_right_inv (mul_inv_self a) /-- `1` is the inverse of itself -/ def invertible_one [monoid α] : invertible (1 : α) := ⟨1, mul_one _, one_mul _⟩ @[simp] lemma inv_of_one [monoid α] [invertible (1 : α)] : ⅟(1 : α) = 1 := inv_of_eq_right_inv (mul_one _) /-- `-⅟a` is the inverse of `-a` -/ def invertible_neg [has_mul α] [has_one α] [has_distrib_neg α] (a : α) [invertible a] : invertible (-a) := ⟨-⅟a, by simp, by simp ⟩ @[simp] lemma inv_of_neg [monoid α] [has_distrib_neg α] (a : α) [invertible a] [invertible (-a)] : ⅟(-a) = -⅟a := inv_of_eq_right_inv (by simp) @[simp] lemma one_sub_inv_of_two [ring α] [invertible (2:α)] : 1 - (⅟2:α) = ⅟2 := (is_unit_of_invertible (2:α)).mul_right_inj.1 $ by rw [mul_sub, mul_inv_of_self, mul_one, bit0, add_sub_cancel] @[simp] lemma inv_of_two_add_inv_of_two [non_assoc_semiring α] [invertible (2 : α)] : (⅟2 : α) + (⅟2 : α) = 1 := by simp only [←two_mul, mul_inv_of_self] /-- `a` is the inverse of `⅟a`. -/ instance invertible_inv_of [has_one α] [has_mul α] {a : α} [invertible a] : invertible (⅟a) := ⟨ a, mul_inv_of_self a, inv_of_mul_self a ⟩ @[simp] lemma inv_of_inv_of [monoid α] (a : α) [invertible a] [invertible (⅟a)] : ⅟(⅟a) = a := inv_of_eq_right_inv (inv_of_mul_self _) @[simp] lemma inv_of_inj [monoid α] {a b : α} [invertible a] [invertible b] : ⅟ a = ⅟ b ↔ a = b := ⟨invertible_unique _ _, invertible_unique _ _⟩ /-- `⅟b * ⅟a` is the inverse of `a * b` -/ def invertible_mul [monoid α] (a b : α) [invertible a] [invertible b] : invertible (a * b) := ⟨ ⅟b * ⅟a, by simp [←mul_assoc], by simp [←mul_assoc] ⟩ @[simp] lemma inv_of_mul [monoid α] (a b : α) [invertible a] [invertible b] [invertible (a * b)] : ⅟(a * b) = ⅟b * ⅟a := inv_of_eq_right_inv (by simp [←mul_assoc]) theorem commute.inv_of_right [monoid α] {a b : α} [invertible b] (h : commute a b) : commute a (⅟b) := calc a * (⅟b) = (⅟b) * (b * a * (⅟b)) : by simp [mul_assoc] ... = (⅟b) * (a * b * ((⅟b))) : by rw h.eq ... = (⅟b) * a : by simp [mul_assoc] theorem commute.inv_of_left [monoid α] {a b : α} [invertible b] (h : commute b a) : commute (⅟b) a := calc (⅟b) * a = (⅟b) * (a * b * (⅟b)) : by simp [mul_assoc] ... = (⅟b) * (b * a * (⅟b)) : by rw h.eq ... = a * (⅟b) : by simp [mul_assoc] lemma commute_inv_of {M : Type*} [has_one M] [has_mul M] (m : M) [invertible m] : commute m (⅟m) := calc m * ⅟m = 1 : mul_inv_of_self m ... = ⅟ m * m : (inv_of_mul_self m).symm lemma nonzero_of_invertible [mul_zero_one_class α] (a : α) [nontrivial α] [invertible a] : a ≠ 0 := λ ha, zero_ne_one $ calc 0 = ⅟a * a : by simp [ha] ... = 1 : inv_of_mul_self a section monoid_with_zero variable [monoid_with_zero α] /-- A variant of `ring.inverse_unit`. -/ @[simp] lemma ring.inverse_invertible (x : α) [invertible x] : ring.inverse x = ⅟x := ring.inverse_unit (unit_of_invertible _) end monoid_with_zero section group_with_zero variable [group_with_zero α] /-- `a⁻¹` is an inverse of `a` if `a ≠ 0` -/ def invertible_of_nonzero {a : α} (h : a ≠ 0) : invertible a := ⟨ a⁻¹, inv_mul_cancel h, mul_inv_cancel h ⟩ @[simp] lemma inv_of_eq_inv (a : α) [invertible a] : ⅟a = a⁻¹ := inv_of_eq_right_inv (mul_inv_cancel (nonzero_of_invertible a)) @[simp] lemma inv_mul_cancel_of_invertible (a : α) [invertible a] : a⁻¹ * a = 1 := inv_mul_cancel (nonzero_of_invertible a) @[simp] lemma mul_inv_cancel_of_invertible (a : α) [invertible a] : a * a⁻¹ = 1 := mul_inv_cancel (nonzero_of_invertible a) @[simp] lemma div_mul_cancel_of_invertible (a b : α) [invertible b] : a / b * b = a := div_mul_cancel a (nonzero_of_invertible b) @[simp] lemma mul_div_cancel_of_invertible (a b : α) [invertible b] : a * b / b = a := mul_div_cancel a (nonzero_of_invertible b) @[simp] lemma div_self_of_invertible (a : α) [invertible a] : a / a = 1 := div_self (nonzero_of_invertible a) /-- `b / a` is the inverse of `a / b` -/ def invertible_div (a b : α) [invertible a] [invertible b] : invertible (a / b) := ⟨b / a, by simp [←mul_div_assoc], by simp [←mul_div_assoc]⟩ @[simp] lemma inv_of_div (a b : α) [invertible a] [invertible b] [invertible (a / b)] : ⅟(a / b) = b / a := inv_of_eq_right_inv (by simp [←mul_div_assoc]) /-- `a` is the inverse of `a⁻¹` -/ def invertible_inv {a : α} [invertible a] : invertible (a⁻¹) := ⟨ a, by simp, by simp ⟩ end group_with_zero /-- Monoid homs preserve invertibility. -/ def invertible.map {R : Type*} {S : Type*} {F : Type*} [mul_one_class R] [mul_one_class S] [monoid_hom_class F R S] (f : F) (r : R) [invertible r] : invertible (f r) := { inv_of := f (⅟r), inv_of_mul_self := by rw [←map_mul, inv_of_mul_self, map_one], mul_inv_of_self := by rw [←map_mul, mul_inv_of_self, map_one] }
e5c878f89b220e307452cda138b7abe9759c55a7
592ee40978ac7604005a4e0d35bbc4b467389241
/Library/generated/mathscheme-lean/MoufangLaw.lean
cd4a591149d30840f95dce7f5f725e842a8247ee
[]
no_license
ysharoda/Deriving-Definitions
3e149e6641fae440badd35ac110a0bd705a49ad2
dfecb27572022de3d4aa702cae8db19957523a59
refs/heads/master
1,679,127,857,700
1,615,939,007,000
1,615,939,007,000
229,785,731
4
0
null
null
null
null
UTF-8
Lean
false
false
5,871
lean
import init.data.nat.basic import init.data.fin.basic import data.vector import .Prelude open Staged open nat open fin open vector section MoufangLaw structure MoufangLaw (A : Type) : Type := (op : (A → (A → A))) (moufangLaw : (∀ {e x y z : A} , ((op y e) = y → (op (op (op x y) z) x) = (op x (op y (op (op e z) x)))))) open MoufangLaw structure Sig (AS : Type) : Type := (opS : (AS → (AS → AS))) structure Product (A : Type) : Type := (opP : ((Prod A A) → ((Prod A A) → (Prod A A)))) (moufangLawP : (∀ {eP xP yP zP : (Prod A A)} , ((opP yP eP) = yP → (opP (opP (opP xP yP) zP) xP) = (opP xP (opP yP (opP (opP eP zP) xP)))))) structure Hom {A1 : Type} {A2 : Type} (Mo1 : (MoufangLaw A1)) (Mo2 : (MoufangLaw A2)) : Type := (hom : (A1 → A2)) (pres_op : (∀ {x1 x2 : A1} , (hom ((op Mo1) x1 x2)) = ((op Mo2) (hom x1) (hom x2)))) structure RelInterp {A1 : Type} {A2 : Type} (Mo1 : (MoufangLaw A1)) (Mo2 : (MoufangLaw A2)) : Type 1 := (interp : (A1 → (A2 → Type))) (interp_op : (∀ {x1 x2 : A1} {y1 y2 : A2} , ((interp x1 y1) → ((interp x2 y2) → (interp ((op Mo1) x1 x2) ((op Mo2) y1 y2)))))) inductive MoufangLawTerm : Type | opL : (MoufangLawTerm → (MoufangLawTerm → MoufangLawTerm)) open MoufangLawTerm inductive ClMoufangLawTerm (A : Type) : Type | sing : (A → ClMoufangLawTerm) | opCl : (ClMoufangLawTerm → (ClMoufangLawTerm → ClMoufangLawTerm)) open ClMoufangLawTerm inductive OpMoufangLawTerm (n : ℕ) : Type | v : ((fin n) → OpMoufangLawTerm) | opOL : (OpMoufangLawTerm → (OpMoufangLawTerm → OpMoufangLawTerm)) open OpMoufangLawTerm inductive OpMoufangLawTerm2 (n : ℕ) (A : Type) : Type | v2 : ((fin n) → OpMoufangLawTerm2) | sing2 : (A → OpMoufangLawTerm2) | opOL2 : (OpMoufangLawTerm2 → (OpMoufangLawTerm2 → OpMoufangLawTerm2)) open OpMoufangLawTerm2 def simplifyCl {A : Type} : ((ClMoufangLawTerm A) → (ClMoufangLawTerm A)) | (opCl x1 x2) := (opCl (simplifyCl x1) (simplifyCl x2)) | (sing x1) := (sing x1) def simplifyOpB {n : ℕ} : ((OpMoufangLawTerm n) → (OpMoufangLawTerm n)) | (opOL x1 x2) := (opOL (simplifyOpB x1) (simplifyOpB x2)) | (v x1) := (v x1) def simplifyOp {n : ℕ} {A : Type} : ((OpMoufangLawTerm2 n A) → (OpMoufangLawTerm2 n A)) | (opOL2 x1 x2) := (opOL2 (simplifyOp x1) (simplifyOp x2)) | (v2 x1) := (v2 x1) | (sing2 x1) := (sing2 x1) def evalB {A : Type} : ((MoufangLaw A) → (MoufangLawTerm → A)) | Mo (opL x1 x2) := ((op Mo) (evalB Mo x1) (evalB Mo x2)) def evalCl {A : Type} : ((MoufangLaw A) → ((ClMoufangLawTerm A) → A)) | Mo (sing x1) := x1 | Mo (opCl x1 x2) := ((op Mo) (evalCl Mo x1) (evalCl Mo x2)) def evalOpB {A : Type} {n : ℕ} : ((MoufangLaw A) → ((vector A n) → ((OpMoufangLawTerm n) → A))) | Mo vars (v x1) := (nth vars x1) | Mo vars (opOL x1 x2) := ((op Mo) (evalOpB Mo vars x1) (evalOpB Mo vars x2)) def evalOp {A : Type} {n : ℕ} : ((MoufangLaw A) → ((vector A n) → ((OpMoufangLawTerm2 n A) → A))) | Mo vars (v2 x1) := (nth vars x1) | Mo vars (sing2 x1) := x1 | Mo vars (opOL2 x1 x2) := ((op Mo) (evalOp Mo vars x1) (evalOp Mo vars x2)) def inductionB {P : (MoufangLawTerm → Type)} : ((∀ (x1 x2 : MoufangLawTerm) , ((P x1) → ((P x2) → (P (opL x1 x2))))) → (∀ (x : MoufangLawTerm) , (P x))) | popl (opL x1 x2) := (popl _ _ (inductionB popl x1) (inductionB popl x2)) def inductionCl {A : Type} {P : ((ClMoufangLawTerm A) → Type)} : ((∀ (x1 : A) , (P (sing x1))) → ((∀ (x1 x2 : (ClMoufangLawTerm A)) , ((P x1) → ((P x2) → (P (opCl x1 x2))))) → (∀ (x : (ClMoufangLawTerm A)) , (P x)))) | psing popcl (sing x1) := (psing x1) | psing popcl (opCl x1 x2) := (popcl _ _ (inductionCl psing popcl x1) (inductionCl psing popcl x2)) def inductionOpB {n : ℕ} {P : ((OpMoufangLawTerm n) → Type)} : ((∀ (fin : (fin n)) , (P (v fin))) → ((∀ (x1 x2 : (OpMoufangLawTerm n)) , ((P x1) → ((P x2) → (P (opOL x1 x2))))) → (∀ (x : (OpMoufangLawTerm n)) , (P x)))) | pv popol (v x1) := (pv x1) | pv popol (opOL x1 x2) := (popol _ _ (inductionOpB pv popol x1) (inductionOpB pv popol x2)) def inductionOp {n : ℕ} {A : Type} {P : ((OpMoufangLawTerm2 n A) → Type)} : ((∀ (fin : (fin n)) , (P (v2 fin))) → ((∀ (x1 : A) , (P (sing2 x1))) → ((∀ (x1 x2 : (OpMoufangLawTerm2 n A)) , ((P x1) → ((P x2) → (P (opOL2 x1 x2))))) → (∀ (x : (OpMoufangLawTerm2 n A)) , (P x))))) | pv2 psing2 popol2 (v2 x1) := (pv2 x1) | pv2 psing2 popol2 (sing2 x1) := (psing2 x1) | pv2 psing2 popol2 (opOL2 x1 x2) := (popol2 _ _ (inductionOp pv2 psing2 popol2 x1) (inductionOp pv2 psing2 popol2 x2)) def stageB : (MoufangLawTerm → (Staged MoufangLawTerm)) | (opL x1 x2) := (stage2 opL (codeLift2 opL) (stageB x1) (stageB x2)) def stageCl {A : Type} : ((ClMoufangLawTerm A) → (Staged (ClMoufangLawTerm A))) | (sing x1) := (Now (sing x1)) | (opCl x1 x2) := (stage2 opCl (codeLift2 opCl) (stageCl x1) (stageCl x2)) def stageOpB {n : ℕ} : ((OpMoufangLawTerm n) → (Staged (OpMoufangLawTerm n))) | (v x1) := (const (code (v x1))) | (opOL x1 x2) := (stage2 opOL (codeLift2 opOL) (stageOpB x1) (stageOpB x2)) def stageOp {n : ℕ} {A : Type} : ((OpMoufangLawTerm2 n A) → (Staged (OpMoufangLawTerm2 n A))) | (sing2 x1) := (Now (sing2 x1)) | (v2 x1) := (const (code (v2 x1))) | (opOL2 x1 x2) := (stage2 opOL2 (codeLift2 opOL2) (stageOp x1) (stageOp x2)) structure StagedRepr (A : Type) (Repr : (Type → Type)) : Type := (opT : ((Repr A) → ((Repr A) → (Repr A)))) end MoufangLaw
720212805b3bb4048872f79691f0ff79eed96089
cf39355caa609c0f33405126beee2739aa3cb77e
/library/init/data/punit.lean
29b6cf4a0d691f047bc051c0b7af051b2bf02294
[ "Apache-2.0" ]
permissive
leanprover-community/lean
12b87f69d92e614daea8bcc9d4de9a9ace089d0e
cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0
refs/heads/master
1,687,508,156,644
1,684,951,104,000
1,684,951,104,000
169,960,991
457
107
Apache-2.0
1,686,744,372,000
1,549,790,268,000
C++
UTF-8
Lean
false
false
516
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ prelude import init.logic lemma punit_eq (a b : punit) : a = b := punit.rec_on a (punit.rec_on b rfl) lemma punit_eq_star (a : punit) : a = punit.star := punit_eq a punit.star instance : subsingleton punit := subsingleton.intro punit_eq instance : inhabited punit := ⟨punit.star⟩ instance : decidable_eq punit := λ a b, is_true (punit_eq a b)
dc8950b1634a654b2bbe58abfbcda0bf4f433869
07c76fbd96ea1786cc6392fa834be62643cea420
/hott/eq2.hlean
f75ae9b58eb6783e75d079032e4d236aa1fd314f
[ "Apache-2.0" ]
permissive
fpvandoorn/lean2
5a430a153b570bf70dc8526d06f18fc000a60ad9
0889cf65b7b3cebfb8831b8731d89c2453dd1e9f
refs/heads/master
1,592,036,508,364
1,545,093,958,000
1,545,093,958,000
75,436,854
0
0
null
1,480,718,780,000
1,480,718,780,000
null
UTF-8
Lean
false
false
13,515
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Floris van Doorn Theorems about 2-dimensional paths -/ import .cubical.square .function open function is_equiv equiv sigma trunc namespace eq variables {A B C : Type} {f : A → B} {a a' a₁ a₂ a₃ a₄ : A} {b b' : B} theorem ap_is_constant_eq (p : Πx, f x = b) (q : a = a') : ap_is_constant p q = eq_con_inv_of_con_eq ((eq_of_square (square_of_pathover (apd p q)))⁻¹ ⬝ whisker_left (p a) (ap_constant q b)) := begin induction q, esimp, generalize (p a), intro p, cases p, apply idpath idp end definition ap_inv2 {p q : a = a'} (r : p = q) : square (ap (ap f) (inverse2 r)) (inverse2 (ap (ap f) r)) (ap_inv f p) (ap_inv f q) := by induction r;exact hrfl definition ap_con2 {p₁ q₁ : a₁ = a₂} {p₂ q₂ : a₂ = a₃} (r₁ : p₁ = q₁) (r₂ : p₂ = q₂) : square (ap (ap f) (r₁ ◾ r₂)) (ap (ap f) r₁ ◾ ap (ap f) r₂) (ap_con f p₁ p₂) (ap_con f q₁ q₂) := by induction r₂;induction r₁;exact hrfl theorem ap_con_right_inv_sq {A B : Type} {a1 a2 : A} (f : A → B) (p : a1 = a2) : square (ap (ap f) (con.right_inv p)) (con.right_inv (ap f p)) (ap_con f p p⁻¹ ⬝ whisker_left _ (ap_inv f p)) idp := by cases p;apply hrefl theorem ap_con_left_inv_sq {A B : Type} {a1 a2 : A} (f : A → B) (p : a1 = a2) : square (ap (ap f) (con.left_inv p)) (con.left_inv (ap f p)) (ap_con f p⁻¹ p ⬝ whisker_right _ (ap_inv f p)) idp := by cases p;apply vrefl definition ap02_compose {A B C : Type} (g : B → C) (f : A → B) {a a' : A} {p₁ p₂ : a = a'} (q : p₁ = p₂) : square (ap_compose g f p₁) (ap_compose g f p₂) (ap02 (g ∘ f) q) (ap02 g (ap02 f q)) := by induction q; exact vrfl definition ap02_id {A : Type} {a a' : A} {p₁ p₂ : a = a'} (q : p₁ = p₂) : square (ap_id p₁) (ap_id p₂) (ap02 id q) q := by induction q; exact vrfl theorem ap_ap_is_constant {A B C : Type} (g : B → C) {f : A → B} {b : B} (p : Πx, f x = b) {x y : A} (q : x = y) : square (ap (ap g) (ap_is_constant p q)) (ap_is_constant (λa, ap g (p a)) q) (ap_compose g f q)⁻¹ (!ap_con ⬝ whisker_left _ !ap_inv) := begin induction q, esimp, generalize (p x), intro p, cases p, apply ids -- induction q, rewrite [↑ap_compose,ap_inv], apply hinverse, apply ap_con_right_inv_sq, end theorem ap_ap_compose {A B C D : Type} (h : C → D) (g : B → C) (f : A → B) {x y : A} (p : x = y) : square (ap_compose (h ∘ g) f p) (ap (ap h) (ap_compose g f p)) (ap_compose h (g ∘ f) p) (ap_compose h g (ap f p)) := by induction p;exact ids theorem ap_compose_inv {A B C : Type} (g : B → C) (f : A → B) {x y : A} (p : x = y) : square (ap_compose g f p⁻¹) (inverse2 (ap_compose g f p) ⬝ (ap_inv g (ap f p))⁻¹) (ap_inv (g ∘ f) p) (ap (ap g) (ap_inv f p)) := by induction p;exact ids theorem ap_compose_con (g : B → C) (f : A → B) (p : a₁ = a₂) (q : a₂ = a₃) : square (ap_compose g f (p ⬝ q)) (ap_compose g f p ◾ ap_compose g f q ⬝ (ap_con g (ap f p) (ap f q))⁻¹) (ap_con (g ∘ f) p q) (ap (ap g) (ap_con f p q)) := by induction q;induction p;exact ids theorem ap_compose_natural {A B C : Type} (g : B → C) (f : A → B) {x y : A} {p q : x = y} (r : p = q) : square (ap (ap (g ∘ f)) r) (ap (ap g ∘ ap f) r) (ap_compose g f p) (ap_compose g f q) := natural_square_tr (ap_compose g f) r theorem whisker_right_eq_of_con_inv_eq_idp {p q : a₁ = a₂} (r : p ⬝ q⁻¹ = idp) : whisker_right q⁻¹ (eq_of_con_inv_eq_idp r) ⬝ con.right_inv q = r := by induction q; esimp at r; cases r; reflexivity theorem ap_eq_of_con_inv_eq_idp (f : A → B) {p q : a₁ = a₂} (r : p ⬝ q⁻¹ = idp) : ap02 f (eq_of_con_inv_eq_idp r) = eq_of_con_inv_eq_idp (whisker_left _ !ap_inv⁻¹ ⬝ !ap_con⁻¹ ⬝ ap02 f r) := by induction q;esimp at *;cases r;reflexivity theorem eq_of_con_inv_eq_idp_con2 {p p' q q' : a₁ = a₂} (r : p = p') (s : q = q') (t : p' ⬝ q'⁻¹ = idp) : eq_of_con_inv_eq_idp (r ◾ inverse2 s ⬝ t) = r ⬝ eq_of_con_inv_eq_idp t ⬝ s⁻¹ := by induction s;induction r;induction q;reflexivity definition naturality_apd_eq {A : Type} {B : A → Type} {a a₂ : A} {f g : Πa, B a} (H : f ~ g) (p : a = a₂) : apd f p = concato_eq (eq_concato (H a) (apd g p)) (H a₂)⁻¹ := begin induction p, esimp, generalizes [H a, g a], intro ga Ha, induction Ha, reflexivity end theorem con_tr_idp {P : A → Type} {x y : A} (q : x = y) (u : P x) : con_tr idp q u = ap (λp, p ▸ u) (idp_con q) := by induction q;reflexivity definition eq_transport_Fl_idp_left {A B : Type} {a : A} {b : B} (f : A → B) (q : f a = b) : eq_transport_Fl idp q = !idp_con⁻¹ := by induction q; reflexivity definition whisker_left_idp_con_eq_assoc {A : Type} {a₁ a₂ a₃ : A} (p : a₁ = a₂) (q : a₂ = a₃) : whisker_left p (idp_con q)⁻¹ = con.assoc p idp q := by induction q; reflexivity definition whisker_left_inverse2 {A : Type} {a : A} {p : a = a} (q : p = idp) : whisker_left p q⁻² ⬝ q = con.right_inv p := by cases q; reflexivity definition whisker_left_idp_square {A : Type} {a a' : A} {p q : a = a'} (r : p = q) : square (whisker_left idp r) r (idp_con p) (idp_con q) := begin induction r, exact hrfl end definition cast_fn_cast_square {A : Type} {B C : A → Type} (f : Π⦃a⦄, B a → C a) {a₁ a₂ : A} (p : a₁ = a₂) (q : a₂ = a₁) (r : p ⬝ q = idp) (b : B a₁) : cast (ap C q) (f (cast (ap B p) b)) = f b := have q⁻¹ = p, from inv_eq_of_idp_eq_con r⁻¹, begin induction this, induction q, reflexivity end definition ap011_ap_square_right {A B C : Type} (f : A → B → C) {a a' : A} (p : a = a') {b₁ b₂ b₃ : B} {q₁₂ : b₁ = b₂} {q₂₃ : b₂ = b₃} {q₁₃ : b₁ = b₃} (r : q₁₂ ⬝ q₂₃ = q₁₃) : square (ap011 f p q₁₂) (ap (λx, f x b₃) p) (ap (f a) q₁₃) (ap (f a') q₂₃) := by induction r; induction q₂₃; induction q₁₂; induction p; exact ids definition ap011_ap_square_left {A B C : Type} (f : B → A → C) {a a' : A} (p : a = a') {b₁ b₂ b₃ : B} {q₁₂ : b₁ = b₂} {q₂₃ : b₂ = b₃} {q₁₃ : b₁ = b₃} (r : q₁₂ ⬝ q₂₃ = q₁₃) : square (ap011 f q₁₂ p) (ap (f b₃) p) (ap (λx, f x a) q₁₃) (ap (λx, f x a') q₂₃) := by induction r; induction q₂₃; induction q₁₂; induction p; exact ids definition con2_assoc {A : Type} {x y z t : A} {p p' : x = y} {q q' : y = z} {r r' : z = t} (h : p = p') (h' : q = q') (h'' : r = r') : square ((h ◾ h') ◾ h'') (h ◾ (h' ◾ h'')) (con.assoc p q r) (con.assoc p' q' r') := by induction h; induction h'; induction h''; exact hrfl definition con_left_inv_idp {A : Type} {x : A} {p : x = x} (q : p = idp) : con.left_inv p = q⁻² ◾ q := by cases q; reflexivity definition eckmann_hilton_con2 {A : Type} {x : A} {p p' q q': idp = idp :> x = x} (h : p = p') (h' : q = q') : square (h ◾ h') (h' ◾ h) (eckmann_hilton p q) (eckmann_hilton p' q') := by induction h; induction h'; exact hrfl definition ap_con_fn {A B : Type} {a a' : A} {b : B} (g h : A → b = b) (p : a = a') : ap (λa, g a ⬝ h a) p = ap g p ◾ ap h p := by induction p; reflexivity definition ap_eq_ap011 {A B C X : Type} (f : A → B → C) (g : X → A) (h : X → B) {x x' : X} (p : x = x') : ap (λx, f (g x) (h x)) p = ap011 f (ap g p) (ap h p) := by induction p; reflexivity definition ap_is_weakly_constant {A B : Type} {f : A → B} (h : is_weakly_constant f) {a a' : A} (p : a = a') : ap f p = (h a a)⁻¹ ⬝ h a a' := by induction p; exact !con.left_inv⁻¹ definition ap_is_constant_idp {A B : Type} {f : A → B} {b : B} (p : Πa, f a = b) {a : A} (q : a = a) (r : q = idp) : ap_is_constant p q = ap02 f r ⬝ (con.right_inv (p a))⁻¹ := by cases r; exact !idp_con⁻¹ definition con_right_inv_natural {A : Type} {a a' : A} {p p' : a = a'} (q : p = p') : con.right_inv p = q ◾ q⁻² ⬝ con.right_inv p' := by induction q; induction p; reflexivity definition whisker_right_ap {A B : Type} {a a' : A}{b₁ b₂ b₃ : B} (q : b₂ = b₃) (f : A → b₁ = b₂) (p : a = a') : whisker_right q (ap f p) = ap (λa, f a ⬝ q) p := by induction p; reflexivity definition ap02_ap_constant {A B C : Type} {a a' : A} (f : B → C) (b : B) (p : a = a') : square (ap_constant p (f b)) (ap02 f (ap_constant p b)) (ap_compose f (λx, b) p) idp := by induction p; exact ids definition ap_constant_compose {A B C : Type} {a a' : A} (c : C) (f : A → B) (p : a = a') : square (ap_constant p c) (ap_constant (ap f p) c) (ap_compose (λx, c) f p) idp := by induction p; exact ids definition ap02_constant {A B : Type} {a a' : A} (b : B) {p p' : a = a'} (q : p = p') : square (ap_constant p b) (ap_constant p' b) (ap02 (λx, b) q) idp := by induction q; exact vrfl definition ap_con_idp_left {A B : Type} (f : A → B) {a a' : A} (p : a = a') : square (ap_con f idp p) idp (ap02 f (idp_con p)) (idp_con (ap f p)) := begin induction p, exact ids end definition apd10_prepostcompose_nondep {A B C D : Type} (h : C → D) {g g' : B → C} (p : g = g') (f : A → B) (a : A) : apd10 (ap (λg a, h (g (f a))) p) a = ap h (apd10 p (f a)) := begin induction p, reflexivity end definition apd10_prepostcompose {A B : Type} {C : B → Type} {D : A → Type} (f : A → B) (h : Πa, C (f a) → D a) {g g' : Πb, C b} (p : g = g') (a : A) : apd10 (ap (λg a, h a (g (f a))) p) a = ap (h a) (apd10 p (f a)) := begin induction p, reflexivity end /- alternative induction principles -/ definition eq.rec_to {A : Type} {a₀ : A} {P : Π⦃a₁⦄, a₀ = a₁ → Type} {a₁ : A} (p₀ : a₀ = a₁) (H : P p₀) ⦃a₂ : A⦄ (p : a₀ = a₂) : P p := begin induction p₀, induction p, exact H end definition eq.rec_to2 {A : Type} {P : Π⦃a₀ a₁⦄, a₀ = a₁ → Type} {a₀ a₀' a₁' : A} (p' : a₀' = a₁') (p₀ : a₀ = a₀') (H : P p') ⦃a₁ : A⦄ (p : a₀ = a₁) : P p := begin induction p₀, induction p', induction p, exact H end definition eq.rec_right_inv {A : Type} (f : A ≃ A) {P : Π⦃a₀ a₁⦄, f a₀ = a₁ → Type} (H : Πa, P (right_inv f a)) ⦃a₀ a₁ : A⦄ (p : f a₀ = a₁) : P p := begin revert a₀ p, refine equiv_rect f⁻¹ᵉ _ _, intro a₀ p, exact eq.rec_to (right_inv f a₀) (H a₀) p, end definition eq.rec_equiv {A B : Type} {a₀ : A} (f : A ≃ B) {P : Π{a₁}, f a₀ = f a₁ → Type} (H : P (idpath (f a₀))) ⦃a₁ : A⦄ (p : f a₀ = f a₁) : P p := begin assert qr : Σ(q : a₀ = a₁), ap f q = p, { exact ⟨inj f p, ap_inj' f p⟩ }, cases qr with q r, apply transport P r, induction q, exact H end definition eq.rec_equiv_symm {A B : Type} {a₁ : A} (f : A ≃ B) {P : Π{a₀}, f a₀ = f a₁ → Type} (H : P (idpath (f a₁))) ⦃a₀ : A⦄ (p : f a₀ = f a₁) : P p := begin assert qr : Σ(q : a₀ = a₁), ap f q = p, { exact ⟨inj f p, ap_inj' f p⟩ }, cases qr with q r, apply transport P r, induction q, exact H end definition eq.rec_equiv_to_same {A B : Type} {a₀ : A} (f : A ≃ B) {P : Π{a₁}, f a₀ = f a₁ → Type} ⦃a₁' : A⦄ (p' : f a₀ = f a₁') (H : P p') ⦃a₁ : A⦄ (p : f a₀ = f a₁) : P p := begin revert a₁' p' H a₁ p, refine eq.rec_equiv f _, exact eq.rec_equiv f end definition eq.rec_equiv_to {A A' B : Type} {a₀ : A} (f : A ≃ B) (g : A' ≃ B) {P : Π{a₁}, f a₀ = g a₁ → Type} ⦃a₁' : A'⦄ (p' : f a₀ = g a₁') (H : P p') ⦃a₁ : A'⦄ (p : f a₀ = g a₁) : P p := begin assert qr : Σ(q : g⁻¹ (f a₀) = a₁), (right_inv g (f a₀))⁻¹ ⬝ ap g q = p, { exact ⟨inj g (right_inv g (f a₀) ⬝ p), whisker_left _ (ap_inj' g _) ⬝ !inv_con_cancel_left⟩ }, assert q'r' : Σ(q' : g⁻¹ (f a₀) = a₁'), (right_inv g (f a₀))⁻¹ ⬝ ap g q' = p', { exact ⟨inj g (right_inv g (f a₀) ⬝ p'), whisker_left _ (ap_inj' g _) ⬝ !inv_con_cancel_left⟩ }, induction qr with q r, induction q'r' with q' r', induction q, induction q', induction r, induction r', exact H end definition eq.rec_grading {A A' B : Type} {a : A} (f : A ≃ B) (g : A' ≃ B) {P : Π{b}, f a = b → Type} {a' : A'} (p' : f a = g a') (H : P p') ⦃b : B⦄ (p : f a = b) : P p := begin revert b p, refine equiv_rect g _ _, exact eq.rec_equiv_to f g p' H end definition eq.rec_grading_unbased {A B B' C : Type} (f : A ≃ B) (g : B ≃ C) (h : B' ≃ C) {P : Π{b c}, g b = c → Type} {a' : A} {b' : B'} (p' : g (f a') = h b') (H : P p') ⦃b : B⦄ ⦃c : C⦄ (q : f a' = b) (p : g b = c) : P p := begin induction q, exact eq.rec_grading (f ⬝e g) h p' H p end end eq
c7f20a60380e6c5363a410b56629fbdebfd6f8c5
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/nat_bug6.lean
85d889fe9d484608e56364ad2d9359d2d778cc21
[ "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
491
lean
import logic open eq.ops namespace experiment inductive nat : Type := | zero : nat | succ : nat → nat namespace nat definition add (x y : nat) : nat := nat.rec x (λn r, succ r) y infixl `+` := add definition mul (n m : nat) := nat.rec zero (fun m x, x + n) m infixl `*` := mul axiom mul_zero_right (n : nat) : n * zero = zero constant P : nat → Prop print "===========================" theorem tst (n : nat) (H : P (n * zero)) : P zero := eq.subst (mul_zero_right _) H end nat exit
8c73d8a795b6938c5ed16afcad8685d6df2c6dbe
2eab05920d6eeb06665e1a6df77b3157354316ad
/src/topology/algebra/module.lean
d2a02d23e9799369cd0962667ede2615c4a75874
[ "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
70,847
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jan-David Salchow, Sébastien Gouëzel, Jean Lo, Yury Kudryashov, Frédéric Dupuis, Heather Macbeth -/ import topology.algebra.ring import topology.algebra.mul_action import topology.uniform_space.uniform_embedding import algebra.algebra.basic import linear_algebra.projection import linear_algebra.pi /-! # Theory of topological modules and continuous linear maps. We use the class `has_continuous_smul` for topological (semi) modules and topological vector spaces. In this file we define continuous (semi-)linear maps, as semilinear maps between topological modules which are continuous. The set of continuous semilinear maps between the topological `R₁`-module `M` and `R₂`-module `M₂` with respect to the `ring_hom` `σ` is denoted by `M →SL[σ] M₂`. Plain linear maps are denoted by `M →L[R] M₂` and star-linear maps by `M →L⋆[R] M₂`. The corresponding notation for equivalences is `M ≃SL[σ] M₂`, `M ≃L[R] M₂` and `M ≃L⋆[R] M₂`. -/ open filter open_locale topological_space big_operators filter universes u v w u' section variables {R : Type*} {M : Type*} [ring R] [topological_space R] [topological_space M] [add_comm_group M] [module R M] lemma has_continuous_smul.of_nhds_zero [topological_ring R] [topological_add_group M] (hmul : tendsto (λ p : R × M, p.1 • p.2) (𝓝 0 ×ᶠ (𝓝 0)) (𝓝 0)) (hmulleft : ∀ m : M, tendsto (λ a : R, a • m) (𝓝 0) (𝓝 0)) (hmulright : ∀ a : R, tendsto (λ m : M, a • m) (𝓝 0) (𝓝 0)) : has_continuous_smul R M := ⟨begin rw continuous_iff_continuous_at, rintros ⟨a₀, m₀⟩, have key : ∀ p : R × M, p.1 • p.2 = a₀ • m₀ + ((p.1 - a₀) • m₀ + a₀ • (p.2 - m₀) + (p.1 - a₀) • (p.2 - m₀)), { rintro ⟨a, m⟩, simp [sub_smul, smul_sub], abel }, rw funext key, clear key, refine tendsto_const_nhds.add (tendsto.add (tendsto.add _ _) _), { rw [sub_self, zero_smul], apply (hmulleft m₀).comp, rw [show (λ p : R × M, p.1 - a₀) = (λ a, a - a₀) ∘ prod.fst, by {ext, refl }, nhds_prod_eq], have : tendsto (λ a, a - a₀) (𝓝 a₀) (𝓝 0), { rw ← sub_self a₀, exact tendsto_id.sub tendsto_const_nhds }, exact this.comp tendsto_fst }, { rw [sub_self, smul_zero], apply (hmulright a₀).comp, rw [show (λ p : R × M, p.2 - m₀) = (λ m, m - m₀) ∘ prod.snd, by {ext, refl }, nhds_prod_eq], have : tendsto (λ m, m - m₀) (𝓝 m₀) (𝓝 0), { rw ← sub_self m₀, exact tendsto_id.sub tendsto_const_nhds }, exact this.comp tendsto_snd }, { rw [sub_self, zero_smul, nhds_prod_eq, show (λ p : R × M, (p.fst - a₀) • (p.snd - m₀)) = (λ p : R × M, p.1 • p.2) ∘ (prod.map (λ a, a - a₀) (λ m, m - m₀)), by { ext, refl }], apply hmul.comp (tendsto.prod_map _ _); { rw ← sub_self , exact tendsto_id.sub tendsto_const_nhds } }, end⟩ end section variables {R : Type*} {M : Type*} [ring R] [topological_space R] [topological_space M] [add_comm_group M] [has_continuous_add M] [module R M] [has_continuous_smul R M] /-- If `M` is a topological module over `R` and `0` is a limit of invertible elements of `R`, then `⊤` is the only submodule of `M` with a nonempty interior. This is the case, e.g., if `R` is a nondiscrete normed field. -/ lemma submodule.eq_top_of_nonempty_interior' [ne_bot (𝓝[{x : R | is_unit x}] 0)] (s : submodule R M) (hs : (interior (s:set M)).nonempty) : s = ⊤ := begin rcases hs with ⟨y, hy⟩, refine (submodule.eq_top_iff'.2 $ λ x, _), rw [mem_interior_iff_mem_nhds] at hy, have : tendsto (λ c:R, y + c • x) (𝓝[{x : R | is_unit x}] 0) (𝓝 (y + (0:R) • x)), from tendsto_const_nhds.add ((tendsto_nhds_within_of_tendsto_nhds tendsto_id).smul tendsto_const_nhds), rw [zero_smul, add_zero] at this, obtain ⟨_, hu : y + _ • _ ∈ s, u, rfl⟩ := nonempty_of_mem (inter_mem (mem_map.1 (this hy)) self_mem_nhds_within), have hy' : y ∈ ↑s := mem_of_mem_nhds hy, rwa [s.add_mem_iff_right hy', ←units.smul_def, s.smul_mem_iff' u] at hu, end variables (R M) /-- Let `R` be a topological ring such that zero is not an isolated point (e.g., a nondiscrete normed field, see `normed_field.punctured_nhds_ne_bot`). Let `M` be a nontrivial module over `R` such that `c • x = 0` implies `c = 0 ∨ x = 0`. Then `M` has no isolated points. We formulate this using `ne_bot (𝓝[{x}ᶜ] x)`. This lemma is not an instance because Lean would need to find `[has_continuous_smul ?m_1 M]` with unknown `?m_1`. We register this as an instance for `R = ℝ` in `real.punctured_nhds_module_ne_bot`. One can also use `haveI := module.punctured_nhds_ne_bot R M` in a proof. -/ lemma module.punctured_nhds_ne_bot [nontrivial M] [ne_bot (𝓝[{0}ᶜ] (0 : R))] [no_zero_smul_divisors R M] (x : M) : ne_bot (𝓝[{x}ᶜ] x) := begin rcases exists_ne (0 : M) with ⟨y, hy⟩, suffices : tendsto (λ c : R, x + c • y) (𝓝[{0}ᶜ] 0) (𝓝[{x}ᶜ] x), from this.ne_bot, refine tendsto.inf _ (tendsto_principal_principal.2 $ _), { convert tendsto_const_nhds.add ((@tendsto_id R _).smul_const y), rw [zero_smul, add_zero] }, { intros c hc, simpa [hy] using hc } end end section closure variables {R : Type u} {M : Type v} [semiring R] [topological_space R] [topological_space M] [add_comm_monoid M] [module R M] [has_continuous_smul R M] lemma submodule.closure_smul_self_subset (s : submodule R M) : (λ p : R × M, p.1 • p.2) '' ((set.univ : set R).prod (closure (s : set M))) ⊆ closure (s : set M) := calc (λ p : R × M, p.1 • p.2) '' ((set.univ : set R).prod (closure (s : set M))) = (λ p : R × M, p.1 • p.2) '' (closure ((set.univ : set R).prod s)) : by simp [closure_prod_eq] ... ⊆ closure ((λ p : R × M, p.1 • p.2) '' ((set.univ : set R).prod s)) : image_closure_subset_closure_image continuous_smul ... = closure s : begin congr, ext x, refine ⟨_, λ hx, ⟨⟨1, x⟩, ⟨set.mem_univ _, hx⟩, one_smul R _⟩⟩, rintros ⟨⟨c, y⟩, ⟨hc, hy⟩, rfl⟩, simp [s.smul_mem c hy] end lemma submodule.closure_smul_self_eq (s : submodule R M) : (λ p : R × M, p.1 • p.2) '' ((set.univ : set R).prod (closure (s : set M))) = closure (s : set M) := set.subset.antisymm s.closure_smul_self_subset (λ x hx, ⟨⟨1, x⟩, ⟨set.mem_univ _, hx⟩, one_smul R _⟩) variables [has_continuous_add M] /-- The (topological-space) closure of a submodule of a topological `R`-module `M` is itself a submodule. -/ def submodule.topological_closure (s : submodule R M) : submodule R M := { carrier := closure (s : set M), smul_mem' := λ c x hx, s.closure_smul_self_subset ⟨⟨c, x⟩, ⟨set.mem_univ _, hx⟩, rfl⟩, ..s.to_add_submonoid.topological_closure } @[simp] lemma submodule.topological_closure_coe (s : submodule R M) : (s.topological_closure : set M) = closure (s : set M) := rfl instance submodule.topological_closure_has_continuous_smul (s : submodule R M) : has_continuous_smul R (s.topological_closure) := { continuous_smul := begin apply continuous_induced_rng, change continuous (λ p : R × s.topological_closure, p.1 • (p.2 : M)), continuity, end, ..s.to_add_submonoid.topological_closure_has_continuous_add } lemma submodule.submodule_topological_closure (s : submodule R M) : s ≤ s.topological_closure := subset_closure lemma submodule.is_closed_topological_closure (s : submodule R M) : is_closed (s.topological_closure : set M) := by convert is_closed_closure lemma submodule.topological_closure_minimal (s : submodule R M) {t : submodule R M} (h : s ≤ t) (ht : is_closed (t : set M)) : s.topological_closure ≤ t := closure_minimal h ht lemma submodule.topological_closure_mono {s : submodule R M} {t : submodule R M} (h : s ≤ t) : s.topological_closure ≤ t.topological_closure := s.topological_closure_minimal (h.trans t.submodule_topological_closure) t.is_closed_topological_closure end closure /-- Continuous linear maps between modules. We only put the type classes that are necessary for the definition, although in applications `M` and `M₂` will be topological modules over the topological ring `R`. -/ structure continuous_linear_map {R : Type*} {S : Type*} [semiring R] [semiring S] (σ : R →+* S) (M : Type*) [topological_space M] [add_comm_monoid M] (M₂ : Type*) [topological_space M₂] [add_comm_monoid M₂] [module R M] [module S M₂] extends M →ₛₗ[σ] M₂ := (cont : continuous to_fun . tactic.interactive.continuity') notation M ` →SL[`:25 σ `] ` M₂ := continuous_linear_map σ M M₂ notation M ` →L[`:25 R `] ` M₂ := continuous_linear_map (ring_hom.id R) M M₂ notation M ` →L⋆[`:25 R `] ` M₂ := continuous_linear_map (@star_ring_aut R _ _ : R →+* R) M M₂ /-- Continuous linear equivalences between modules. We only put the type classes that are necessary for the definition, although in applications `M` and `M₂` will be topological modules over the topological ring `R`. -/ @[nolint has_inhabited_instance] structure continuous_linear_equiv {R : Type*} {S : Type*} [semiring R] [semiring S] (σ : R →+* S) {σ' : S →+* R} [ring_hom_inv_pair σ σ'] [ring_hom_inv_pair σ' σ] (M : Type*) [topological_space M] [add_comm_monoid M] (M₂ : Type*) [topological_space M₂] [add_comm_monoid M₂] [module R M] [module S M₂] extends M ≃ₛₗ[σ] M₂ := (continuous_to_fun : continuous to_fun . tactic.interactive.continuity') (continuous_inv_fun : continuous inv_fun . tactic.interactive.continuity') notation M ` ≃SL[`:50 σ `] ` M₂ := continuous_linear_equiv σ M M₂ notation M ` ≃L[`:50 R `] ` M₂ := continuous_linear_equiv (ring_hom.id R) M M₂ notation M ` ≃L⋆[`:50 R `] ` M₂ := continuous_linear_equiv (@star_ring_aut R _ _ : R →+* R) M M₂ namespace continuous_linear_map section semiring /-! ### Properties that hold for non-necessarily commutative semirings. -/ variables {R₁ : Type*} [semiring R₁] {R₂ : Type*} [semiring R₂] {R₃ : Type*} [semiring R₃] {σ₁₂ : R₁ →+* R₂} {σ₂₃ : R₂ →+* R₃} {M₁ : Type*} [topological_space M₁] [add_comm_monoid M₁] {M₂ : Type*} [topological_space M₂] [add_comm_monoid M₂] {M₃ : Type*} [topological_space M₃] [add_comm_monoid M₃] {M₄ : Type*} [topological_space M₄] [add_comm_monoid M₄] [module R₁ M₁] [module R₂ M₂] [module R₃ M₃] /-- Coerce continuous linear maps to linear maps. -/ instance : has_coe (M₁ →SL[σ₁₂] M₂) (M₁ →ₛₗ[σ₁₂] M₂) := ⟨to_linear_map⟩ -- make the coercion the preferred form @[simp] lemma to_linear_map_eq_coe (f : M₁ →SL[σ₁₂] M₂) : f.to_linear_map = f := rfl /-- Coerce continuous linear maps to functions. -/ -- see Note [function coercion] instance to_fun : has_coe_to_fun (M₁ →SL[σ₁₂] M₂) (λ _, M₁ → M₂) := ⟨λ f, f⟩ @[simp] lemma coe_mk (f : M₁ →ₛₗ[σ₁₂] M₂) (h) : (mk f h : M₁ →ₛₗ[σ₁₂] M₂) = f := rfl @[simp] lemma coe_mk' (f : M₁ →ₛₗ[σ₁₂] M₂) (h) : (mk f h : M₁ → M₂) = f := rfl @[continuity] protected lemma continuous (f : M₁ →SL[σ₁₂] M₂) : continuous f := f.2 theorem coe_injective : function.injective (coe : (M₁ →SL[σ₁₂] M₂) → (M₁ →ₛₗ[σ₁₂] M₂)) := by { intros f g H, cases f, cases g, congr' } @[simp, norm_cast] lemma coe_inj {f g : M₁ →SL[σ₁₂] M₂} : (f : M₁ →ₛₗ[σ₁₂] M₂) = g ↔ f = g := coe_injective.eq_iff theorem coe_fn_injective : @function.injective (M₁ →SL[σ₁₂] M₂) (M₁ → M₂) coe_fn := linear_map.coe_injective.comp coe_injective @[ext] theorem ext {f g : M₁ →SL[σ₁₂] M₂} (h : ∀ x, f x = g x) : f = g := coe_fn_injective $ funext h theorem ext_iff {f g : M₁ →SL[σ₁₂] M₂} : f = g ↔ ∀ x, f x = g x := ⟨λ h x, by rw h, by ext⟩ variables (f g : M₁ →SL[σ₁₂] M₂) (c : R₁) (h : M₂ →SL[σ₂₃] M₃) (x y z : M₁) -- make some straightforward lemmas available to `simp`. @[simp] lemma map_zero : f (0 : M₁) = 0 := (to_linear_map _).map_zero @[simp] lemma map_add : f (x + y) = f x + f y := (to_linear_map _).map_add _ _ @[simp] lemma map_smulₛₗ : f (c • x) = (σ₁₂ c) • f x := (to_linear_map _).map_smulₛₗ _ _ @[simp] lemma map_smul [module R₁ M₂] (f : M₁ →L[R₁] M₂)(c : R₁) (x : M₁) : f (c • x) = c • f x := by simp only [ring_hom.id_apply, map_smulₛₗ] @[simp, priority 900] lemma map_smul_of_tower {R S : Type*} [semiring S] [has_scalar R M₁] [module S M₁] [has_scalar R M₂] [module S M₂] [linear_map.compatible_smul M₁ M₂ R S] (f : M₁ →L[S] M₂) (c : R) (x : M₁) : f (c • x) = c • f x := linear_map.compatible_smul.map_smul f c x lemma map_sum {ι : Type*} (s : finset ι) (g : ι → M₁) : f (∑ i in s, g i) = ∑ i in s, f (g i) := f.to_linear_map.map_sum @[simp, norm_cast] lemma coe_coe : ((f : M₁ →ₛₗ[σ₁₂] M₂) : (M₁ → M₂)) = (f : M₁ → M₂) := rfl @[ext] theorem ext_ring [topological_space R₁] {f g : R₁ →L[R₁] M₁} (h : f 1 = g 1) : f = g := coe_inj.1 $ linear_map.ext_ring h theorem ext_ring_iff [topological_space R₁] {f g : R₁ →L[R₁] M₁} : f = g ↔ f 1 = g 1 := ⟨λ h, h ▸ rfl, ext_ring⟩ /-- If two continuous linear maps are equal on a set `s`, then they are equal on the closure of the `submodule.span` of this set. -/ lemma eq_on_closure_span [t2_space M₂] {s : set M₁} {f g : M₁ →SL[σ₁₂] M₂} (h : set.eq_on f g s) : set.eq_on f g (closure (submodule.span R₁ s : set M₁)) := (linear_map.eq_on_span' h).closure f.continuous g.continuous /-- If the submodule generated by a set `s` is dense in the ambient module, then two continuous linear maps equal on `s` are equal. -/ lemma ext_on [t2_space M₂] {s : set M₁} (hs : dense (submodule.span R₁ s : set M₁)) {f g : M₁ →SL[σ₁₂] M₂} (h : set.eq_on f g s) : f = g := ext $ λ x, eq_on_closure_span h (hs x) /-- Under a continuous linear map, the image of the `topological_closure` of a submodule is contained in the `topological_closure` of its image. -/ lemma _root_.submodule.topological_closure_map [ring_hom_surjective σ₁₂] [topological_space R₁] [topological_space R₂] [has_continuous_smul R₁ M₁] [has_continuous_add M₁] [has_continuous_smul R₂ M₂] [has_continuous_add M₂] (f : M₁ →SL[σ₁₂] M₂) (s : submodule R₁ M₁) : (s.topological_closure.map (f : M₁ →ₛₗ[σ₁₂] M₂)) ≤ (s.map (f : M₁ →ₛₗ[σ₁₂] M₂)).topological_closure := image_closure_subset_closure_image f.continuous /-- Under a dense continuous linear map, a submodule whose `topological_closure` is `⊤` is sent to another such submodule. That is, the image of a dense set under a map with dense range is dense. -/ lemma _root_.dense_range.topological_closure_map_submodule [ring_hom_surjective σ₁₂] [topological_space R₁] [topological_space R₂] [has_continuous_smul R₁ M₁] [has_continuous_add M₁] [has_continuous_smul R₂ M₂] [has_continuous_add M₂] {f : M₁ →SL[σ₁₂] M₂} (hf' : dense_range f) {s : submodule R₁ M₁} (hs : s.topological_closure = ⊤) : (s.map (f : M₁ →ₛₗ[σ₁₂] M₂)).topological_closure = ⊤ := begin rw set_like.ext'_iff at hs ⊢, simp only [submodule.topological_closure_coe, submodule.top_coe, ← dense_iff_closure_eq] at hs ⊢, exact hf'.dense_image f.continuous hs end /-- The continuous map that is constantly zero. -/ instance: has_zero (M₁ →SL[σ₁₂] M₂) := ⟨⟨0, continuous_zero⟩⟩ instance : inhabited (M₁ →SL[σ₁₂] M₂) := ⟨0⟩ @[simp] lemma default_def : default (M₁ →SL[σ₁₂] M₂) = 0 := rfl @[simp] lemma zero_apply : (0 : M₁ →SL[σ₁₂] M₂) x = 0 := rfl @[simp, norm_cast] lemma coe_zero : ((0 : M₁ →SL[σ₁₂] M₂) : M₁ →ₛₗ[σ₁₂] M₂) = 0 := rfl /- no simp attribute on the next line as simp does not always simplify `0 x` to `0` when `0` is the zero function, while it does for the zero continuous linear map, and this is the most important property we care about. -/ @[norm_cast] lemma coe_zero' : ((0 : M₁ →SL[σ₁₂] M₂) : M₁ → M₂) = 0 := rfl instance unique_of_left [subsingleton M₁] : unique (M₁ →SL[σ₁₂] M₂) := coe_injective.unique instance unique_of_right [subsingleton M₂] : unique (M₁ →SL[σ₁₂] M₂) := coe_injective.unique section variables (R₁ M₁) /-- the identity map as a continuous linear map. -/ def id : M₁ →L[R₁] M₁ := ⟨linear_map.id, continuous_id⟩ end instance : has_one (M₁ →L[R₁] M₁) := ⟨id R₁ M₁⟩ lemma one_def : (1 : M₁ →L[R₁] M₁) = id R₁ M₁ := rfl lemma id_apply : id R₁ M₁ x = x := rfl @[simp, norm_cast] lemma coe_id : (id R₁ M₁ : M₁ →ₗ[R₁] M₁) = linear_map.id := rfl @[simp, norm_cast] lemma coe_id' : (id R₁ M₁ : M₁ → M₁) = _root_.id := rfl @[simp, norm_cast] lemma coe_eq_id {f : M₁ →L[R₁] M₁} : (f : M₁ →ₗ[R₁] M₁) = linear_map.id ↔ f = id _ _ := by rw [← coe_id, coe_inj] @[simp] lemma one_apply : (1 : M₁ →L[R₁] M₁) x = x := rfl section add variables [has_continuous_add M₂] instance : has_add (M₁ →SL[σ₁₂] M₂) := ⟨λ f g, ⟨f + g, f.2.add g.2⟩⟩ lemma continuous_nsmul (n : ℕ) : continuous (λ (x : M₂), n • x) := begin induction n with n ih, { simp [continuous_const] }, { simp [nat.succ_eq_add_one, add_smul], exact ih.add continuous_id } end @[continuity] lemma continuous.nsmul {α : Type*} [topological_space α] {n : ℕ} {f : α → M₂} (hf : continuous f) : continuous (λ (x : α), n • (f x)) := (continuous_nsmul n).comp hf @[simp] lemma add_apply : (f + g) x = f x + g x := rfl @[simp, norm_cast] lemma coe_add : (((f + g) : M₁ →SL[σ₁₂] M₂) : M₁ →ₛₗ[σ₁₂] M₂) = f + g := rfl @[norm_cast] lemma coe_add' : (((f + g) : M₁ →SL[σ₁₂] M₂) : M₁ → M₂) = (f : M₁ → M₂) + g := rfl instance : add_comm_monoid (M₁ →SL[σ₁₂] M₂) := { zero := (0 : M₁ →SL[σ₁₂] M₂), add := (+), zero_add := by intros; ext; apply_rules [zero_add, add_assoc, add_zero, add_left_neg, add_comm], add_zero := by intros; ext; apply_rules [zero_add, add_assoc, add_zero, add_left_neg, add_comm], add_comm := by intros; ext; apply_rules [zero_add, add_assoc, add_zero, add_left_neg, add_comm], add_assoc := by intros; ext; apply_rules [zero_add, add_assoc, add_zero, add_left_neg, add_comm], nsmul := λ n f, { to_fun := λ x, n • (f x), map_add' := by simp, map_smul' := by simp [smul_comm n] }, nsmul_zero' := λ f, by { ext, simp }, nsmul_succ' := λ n f, by { ext, simp [nat.succ_eq_one_add, add_smul] } } @[simp, norm_cast] lemma coe_sum {ι : Type*} (t : finset ι) (f : ι → M₁ →SL[σ₁₂] M₂) : ↑(∑ d in t, f d) = (∑ d in t, f d : M₁ →ₛₗ[σ₁₂] M₂) := (add_monoid_hom.mk (coe : (M₁ →SL[σ₁₂] M₂) → (M₁ →ₛₗ[σ₁₂] M₂)) rfl (λ _ _, rfl)).map_sum _ _ @[simp, norm_cast] lemma coe_sum' {ι : Type*} (t : finset ι) (f : ι → M₁ →SL[σ₁₂] M₂) : ⇑(∑ d in t, f d) = ∑ d in t, f d := by simp only [← coe_coe, coe_sum, linear_map.coe_fn_sum] lemma sum_apply {ι : Type*} (t : finset ι) (f : ι → M₁ →SL[σ₁₂] M₂) (b : M₁) : (∑ d in t, f d) b = ∑ d in t, f d b := by simp only [coe_sum', finset.sum_apply] end add variables {σ₁₃ : R₁ →+* R₃} [ring_hom_comp_triple σ₁₂ σ₂₃ σ₁₃] /-- Composition of bounded linear maps. -/ def comp (g : M₂ →SL[σ₂₃] M₃) (f : M₁ →SL[σ₁₂] M₂) : M₁ →SL[σ₁₃] M₃ := ⟨(g : M₂ →ₛₗ[σ₂₃] M₃).comp ↑f, g.2.comp f.2⟩ infixr ` ∘L `:80 := @continuous_linear_map.comp _ _ _ _ _ _ (ring_hom.id _) (ring_hom.id _) _ _ _ _ _ _ _ _ _ _ _ _ (ring_hom.id _) ring_hom_comp_triple.ids @[simp, norm_cast] lemma coe_comp : ((h.comp f) : (M₁ →ₛₗ[σ₁₃] M₃)) = (h : M₂ →ₛₗ[σ₂₃] M₃).comp (f : M₁ →ₛₗ[σ₁₂] M₂) := rfl include σ₁₃ @[simp, norm_cast] lemma coe_comp' : ((h.comp f) : (M₁ → M₃)) = (h : M₂ → M₃) ∘ f := rfl lemma comp_apply (g : M₂ →SL[σ₂₃] M₃) (f : M₁ →SL[σ₁₂] M₂) (x : M₁) : (g.comp f) x = g (f x) := rfl omit σ₁₃ @[simp] theorem comp_id : f.comp (id R₁ M₁) = f := ext $ λ x, rfl @[simp] theorem id_comp : (id R₂ M₂).comp f = f := ext $ λ x, rfl include σ₁₃ @[simp] theorem comp_zero (g : M₂ →SL[σ₂₃] M₃) : g.comp (0 : M₁ →SL[σ₁₂] M₂) = 0 := by { ext, simp } @[simp] theorem zero_comp : (0 : M₂ →SL[σ₂₃] M₃).comp f = 0 := by { ext, simp } @[simp] lemma comp_add [has_continuous_add M₂] [has_continuous_add M₃] (g : M₂ →SL[σ₂₃] M₃) (f₁ f₂ : M₁ →SL[σ₁₂] M₂) : g.comp (f₁ + f₂) = g.comp f₁ + g.comp f₂ := by { ext, simp } @[simp] lemma add_comp [has_continuous_add M₃] (g₁ g₂ : M₂ →SL[σ₂₃] M₃) (f : M₁ →SL[σ₁₂] M₂) : (g₁ + g₂).comp f = g₁.comp f + g₂.comp f := by { ext, simp } omit σ₁₃ theorem comp_assoc {R₄ : Type*} [semiring R₄] [module R₄ M₄] {σ₁₄ : R₁ →+* R₄} {σ₂₄ : R₂ →+* R₄} {σ₃₄ : R₃ →+* R₄} [ring_hom_comp_triple σ₁₃ σ₃₄ σ₁₄] [ring_hom_comp_triple σ₂₃ σ₃₄ σ₂₄] [ring_hom_comp_triple σ₁₂ σ₂₄ σ₁₄] (h : M₃ →SL[σ₃₄] M₄) (g : M₂ →SL[σ₂₃] M₃) (f : M₁ →SL[σ₁₂] M₂) : (h.comp g).comp f = h.comp (g.comp f) := rfl instance : has_mul (M₁ →L[R₁] M₁) := ⟨comp⟩ lemma mul_def (f g : M₁ →L[R₁] M₁) : f * g = f.comp g := rfl @[simp] lemma coe_mul (f g : M₁ →L[R₁] M₁) : ⇑(f * g) = f ∘ g := rfl lemma mul_apply (f g : M₁ →L[R₁] M₁) (x : M₁) : (f * g) x = f (g x) := rfl /-- The cartesian product of two bounded linear maps, as a bounded linear map. -/ protected def prod [module R₁ M₂] [module R₁ M₃] (f₁ : M₁ →L[R₁] M₂) (f₂ : M₁ →L[R₁] M₃) : M₁ →L[R₁] (M₂ × M₃) := ⟨(f₁ : M₁ →ₗ[R₁] M₂).prod f₂, f₁.2.prod_mk f₂.2⟩ @[simp, norm_cast] lemma coe_prod [module R₁ M₂] [module R₁ M₃] (f₁ : M₁ →L[R₁] M₂) (f₂ : M₁ →L[R₁] M₃) : (f₁.prod f₂ : M₁ →ₗ[R₁] M₂ × M₃) = linear_map.prod f₁ f₂ := rfl @[simp, norm_cast] lemma prod_apply [module R₁ M₂] [module R₁ M₃] (f₁ : M₁ →L[R₁] M₂) (f₂ : M₁ →L[R₁] M₃) (x : M₁) : f₁.prod f₂ x = (f₁ x, f₂ x) := rfl section variables (R₁ M₁ M₂) /-- The left injection into a product is a continuous linear map. -/ def inl [module R₁ M₂] : M₁ →L[R₁] M₁ × M₂ := (id R₁ M₁).prod 0 /-- The right injection into a product is a continuous linear map. -/ def inr [module R₁ M₂] : M₂ →L[R₁] M₁ × M₂ := (0 : M₂ →L[R₁] M₁).prod (id R₁ M₂) end @[simp] lemma inl_apply [module R₁ M₂] (x : M₁) : inl R₁ M₁ M₂ x = (x, 0) := rfl @[simp] lemma inr_apply [module R₁ M₂] (x : M₂) : inr R₁ M₁ M₂ x = (0, x) := rfl @[simp, norm_cast] lemma coe_inl [module R₁ M₂] : (inl R₁ M₁ M₂ : M₁ →ₗ[R₁] M₁ × M₂) = linear_map.inl R₁ M₁ M₂ := rfl @[simp, norm_cast] lemma coe_inr [module R₁ M₂] : (inr R₁ M₁ M₂ : M₂ →ₗ[R₁] M₁ × M₂) = linear_map.inr R₁ M₁ M₂ := rfl /-- Kernel of a continuous linear map. -/ def ker (f : M₁ →SL[σ₁₂] M₂) : submodule R₁ M₁ := (f : M₁ →ₛₗ[σ₁₂] M₂).ker @[norm_cast] lemma ker_coe : (f : M₁ →ₛₗ[σ₁₂] M₂).ker = f.ker := rfl @[simp] lemma mem_ker {f : M₁ →SL[σ₁₂] M₂} {x} : x ∈ f.ker ↔ f x = 0 := linear_map.mem_ker lemma is_closed_ker [t1_space M₂] : is_closed (f.ker : set M₁) := continuous_iff_is_closed.1 f.cont _ is_closed_singleton @[simp] lemma apply_ker (x : f.ker) : f x = 0 := mem_ker.1 x.2 lemma is_complete_ker {M' : Type*} [uniform_space M'] [complete_space M'] [add_comm_monoid M'] [module R₁ M'] [t1_space M₂] (f : M' →SL[σ₁₂] M₂) : is_complete (f.ker : set M') := f.is_closed_ker.is_complete instance complete_space_ker {M' : Type*} [uniform_space M'] [complete_space M'] [add_comm_monoid M'] [module R₁ M'] [t1_space M₂] (f : M' →SL[σ₁₂] M₂) : complete_space f.ker := f.is_closed_ker.complete_space_coe @[simp] lemma ker_prod [module R₁ M₂] [module R₁ M₃] (f : M₁ →L[R₁] M₂) (g : M₁ →L[R₁] M₃) : ker (f.prod g) = ker f ⊓ ker g := linear_map.ker_prod f g /-- Range of a continuous linear map. -/ def range [ring_hom_surjective σ₁₂] (f : M₁ →SL[σ₁₂] M₂) : submodule R₂ M₂ := (f : M₁ →ₛₗ[σ₁₂] M₂).range lemma range_coe [ring_hom_surjective σ₁₂] : (f.range : set M₂) = set.range f := linear_map.range_coe _ lemma mem_range [ring_hom_surjective σ₁₂] {f : M₁ →SL[σ₁₂] M₂} {y} : y ∈ f.range ↔ ∃ x, f x = y := linear_map.mem_range lemma mem_range_self [ring_hom_surjective σ₁₂] (f : M₁ →SL[σ₁₂] M₂) (x : M₁) : f x ∈ f.range := mem_range.2 ⟨x, rfl⟩ lemma range_prod_le [module R₁ M₂] [module R₁ M₃] (f : M₁ →L[R₁] M₂) (g : M₁ →L[R₁] M₃) : range (f.prod g) ≤ (range f).prod (range g) := (f : M₁ →ₗ[R₁] M₂).range_prod_le g /-- Restrict codomain of a continuous linear map. -/ def cod_restrict (f : M₁ →SL[σ₁₂] M₂) (p : submodule R₂ M₂) (h : ∀ x, f x ∈ p) : M₁ →SL[σ₁₂] p := { cont := continuous_subtype_mk h f.continuous, to_linear_map := (f : M₁ →ₛₗ[σ₁₂] M₂).cod_restrict p h} @[norm_cast] lemma coe_cod_restrict (f : M₁ →SL[σ₁₂] M₂) (p : submodule R₂ M₂) (h : ∀ x, f x ∈ p) : (f.cod_restrict p h : M₁ →ₛₗ[σ₁₂] p) = (f : M₁ →ₛₗ[σ₁₂] M₂).cod_restrict p h := rfl @[simp] lemma coe_cod_restrict_apply (f : M₁ →SL[σ₁₂] M₂) (p : submodule R₂ M₂) (h : ∀ x, f x ∈ p) (x) : (f.cod_restrict p h x : M₂) = f x := rfl @[simp] lemma ker_cod_restrict (f : M₁ →SL[σ₁₂] M₂) (p : submodule R₂ M₂) (h : ∀ x, f x ∈ p) : ker (f.cod_restrict p h) = ker f := (f : M₁ →ₛₗ[σ₁₂] M₂).ker_cod_restrict p h /-- Embedding of a submodule into the ambient space as a continuous linear map. -/ def subtype_val (p : submodule R₁ M₁) : p →L[R₁] M₁ := { cont := continuous_subtype_val, to_linear_map := p.subtype } @[simp, norm_cast] lemma coe_subtype_val (p : submodule R₁ M₁) : (subtype_val p : p →ₗ[R₁] M₁) = p.subtype := rfl @[simp, norm_cast] lemma subtype_val_apply (p : submodule R₁ M₁) (x : p) : (subtype_val p : p → M₁) x = x := rfl variables (R₁ M₁ M₂) /-- `prod.fst` as a `continuous_linear_map`. -/ def fst [module R₁ M₂] : M₁ × M₂ →L[R₁] M₁ := { cont := continuous_fst, to_linear_map := linear_map.fst R₁ M₁ M₂ } /-- `prod.snd` as a `continuous_linear_map`. -/ def snd [module R₁ M₂] : M₁ × M₂ →L[R₁] M₂ := { cont := continuous_snd, to_linear_map := linear_map.snd R₁ M₁ M₂ } variables {R₁ M₁ M₂} @[simp, norm_cast] lemma coe_fst [module R₁ M₂] : (fst R₁ M₁ M₂ : M₁ × M₂ →ₗ[R₁] M₁) = linear_map.fst R₁ M₁ M₂ := rfl @[simp, norm_cast] lemma coe_fst' [module R₁ M₂] : (fst R₁ M₁ M₂ : M₁ × M₂ → M₁) = prod.fst := rfl @[simp, norm_cast] lemma coe_snd [module R₁ M₂] : (snd R₁ M₁ M₂ : M₁ × M₂ →ₗ[R₁] M₂) = linear_map.snd R₁ M₁ M₂ := rfl @[simp, norm_cast] lemma coe_snd' [module R₁ M₂] : (snd R₁ M₁ M₂ : M₁ × M₂ → M₂) = prod.snd := rfl @[simp] lemma fst_prod_snd [module R₁ M₂] : (fst R₁ M₁ M₂).prod (snd R₁ M₁ M₂) = id R₁ (M₁ × M₂) := ext $ λ ⟨x, y⟩, rfl @[simp] lemma fst_comp_prod [module R₁ M₂] [module R₁ M₃] (f : M₁ →L[R₁] M₂) (g : M₁ →L[R₁] M₃) : (fst R₁ M₂ M₃).comp (f.prod g) = f := ext $ λ x, rfl @[simp] lemma snd_comp_prod [module R₁ M₂] [module R₁ M₃] (f : M₁ →L[R₁] M₂) (g : M₁ →L[R₁] M₃) : (snd R₁ M₂ M₃).comp (f.prod g) = g := ext $ λ x, rfl /-- `prod.map` of two continuous linear maps. -/ def prod_map [module R₁ M₂] [module R₁ M₃] [module R₁ M₄] (f₁ : M₁ →L[R₁] M₂) (f₂ : M₃ →L[R₁] M₄) : (M₁ × M₃) →L[R₁] (M₂ × M₄) := (f₁.comp (fst R₁ M₁ M₃)).prod (f₂.comp (snd R₁ M₁ M₃)) @[simp, norm_cast] lemma coe_prod_map [module R₁ M₂] [module R₁ M₃] [module R₁ M₄] (f₁ : M₁ →L[R₁] M₂) (f₂ : M₃ →L[R₁] M₄) : (f₁.prod_map f₂ : (M₁ × M₃) →ₗ[R₁] (M₂ × M₄)) = ((f₁ : M₁ →ₗ[R₁] M₂).prod_map (f₂ : M₃ →ₗ[R₁] M₄)) := rfl @[simp, norm_cast] lemma coe_prod_map' [module R₁ M₂] [module R₁ M₃] [module R₁ M₄] (f₁ : M₁ →L[R₁] M₂) (f₂ : M₃ →L[R₁] M₄) : ⇑(f₁.prod_map f₂) = prod.map f₁ f₂ := rfl /-- The continuous linear map given by `(x, y) ↦ f₁ x + f₂ y`. -/ def coprod [module R₁ M₂] [module R₁ M₃] [has_continuous_add M₃] (f₁ : M₁ →L[R₁] M₃) (f₂ : M₂ →L[R₁] M₃) : (M₁ × M₂) →L[R₁] M₃ := ⟨linear_map.coprod f₁ f₂, (f₁.cont.comp continuous_fst).add (f₂.cont.comp continuous_snd)⟩ @[norm_cast, simp] lemma coe_coprod [module R₁ M₂] [module R₁ M₃] [has_continuous_add M₃] (f₁ : M₁ →L[R₁] M₃) (f₂ : M₂ →L[R₁] M₃) : (f₁.coprod f₂ : (M₁ × M₂) →ₗ[R₁] M₃) = linear_map.coprod f₁ f₂ := rfl @[simp] lemma coprod_apply [module R₁ M₂] [module R₁ M₃] [has_continuous_add M₃] (f₁ : M₁ →L[R₁] M₃) (f₂ : M₂ →L[R₁] M₃) (x) : f₁.coprod f₂ x = f₁ x.1 + f₂ x.2 := rfl lemma range_coprod [module R₁ M₂] [module R₁ M₃] [has_continuous_add M₃] (f₁ : M₁ →L[R₁] M₃) (f₂ : M₂ →L[R₁] M₃) : (f₁.coprod f₂).range = f₁.range ⊔ f₂.range := linear_map.range_coprod _ _ section variables {R S : Type*} [semiring R] [semiring S] [module R M₁] [module R M₂] [module R S] [module S M₂] [is_scalar_tower R S M₂] [topological_space S] [has_continuous_smul S M₂] /-- The linear map `λ x, c x • f`. Associates to a scalar-valued linear map and an element of `M₂` the `M₂`-valued linear map obtained by multiplying the two (a.k.a. tensoring by `M₂`). See also `continuous_linear_map.smul_rightₗ` and `continuous_linear_map.smul_rightL`. -/ def smul_right (c : M₁ →L[R] S) (f : M₂) : M₁ →L[R] M₂ := { cont := c.2.smul continuous_const, ..c.to_linear_map.smul_right f } @[simp] lemma smul_right_apply {c : M₁ →L[R] S} {f : M₂} {x : M₁} : (smul_right c f : M₁ → M₂) x = c x • f := rfl end variables [module R₁ M₂] [topological_space R₁] [has_continuous_smul R₁ M₂] @[simp] lemma smul_right_one_one (c : R₁ →L[R₁] M₂) : smul_right (1 : R₁ →L[R₁] R₁) (c 1) = c := by ext; simp [← continuous_linear_map.map_smul_of_tower] @[simp] lemma smul_right_one_eq_iff {f f' : M₂} : smul_right (1 : R₁ →L[R₁] R₁) f = smul_right (1 : R₁ →L[R₁] R₁) f' ↔ f = f' := by simp only [ext_ring_iff, smul_right_apply, one_apply, one_smul] lemma smul_right_comp [has_continuous_mul R₁] {x : M₂} {c : R₁} : (smul_right (1 : R₁ →L[R₁] R₁) x).comp (smul_right (1 : R₁ →L[R₁] R₁) c) = smul_right (1 : R₁ →L[R₁] R₁) (c • x) := by { ext, simp [mul_smul] } end semiring section pi variables {R : Type*} [semiring R] {M : Type*} [topological_space M] [add_comm_monoid M] [module R M] {M₂ : Type*} [topological_space M₂] [add_comm_monoid M₂] [module R M₂] {ι : Type*} {φ : ι → Type*} [∀i, topological_space (φ i)] [∀i, add_comm_monoid (φ i)] [∀i, module R (φ i)] /-- `pi` construction for continuous linear functions. From a family of continuous linear functions it produces a continuous linear function into a family of topological modules. -/ def pi (f : Πi, M →L[R] φ i) : M →L[R] (Πi, φ i) := ⟨linear_map.pi (λ i, f i), continuous_pi (λ i, (f i).continuous)⟩ @[simp] lemma coe_pi' (f : Π i, M →L[R] φ i) : ⇑(pi f) = λ c i, f i c := rfl @[simp] lemma coe_pi (f : Π i, M →L[R] φ i) : (pi f : M →ₗ[R] Π i, φ i) = linear_map.pi (λ i, f i) := rfl lemma pi_apply (f : Πi, M →L[R] φ i) (c : M) (i : ι) : pi f c i = f i c := rfl lemma pi_eq_zero (f : Πi, M →L[R] φ i) : pi f = 0 ↔ (∀i, f i = 0) := by { simp only [ext_iff, pi_apply, function.funext_iff], exact forall_swap } lemma pi_zero : pi (λi, 0 : Πi, M →L[R] φ i) = 0 := ext $ λ _, rfl lemma pi_comp (f : Πi, M →L[R] φ i) (g : M₂ →L[R] M) : (pi f).comp g = pi (λi, (f i).comp g) := rfl /-- The projections from a family of topological modules are continuous linear maps. -/ def proj (i : ι) : (Πi, φ i) →L[R] φ i := ⟨linear_map.proj i, continuous_apply _⟩ @[simp] lemma proj_apply (i : ι) (b : Πi, φ i) : (proj i : (Πi, φ i) →L[R] φ i) b = b i := rfl lemma proj_pi (f : Πi, M₂ →L[R] φ i) (i : ι) : (proj i).comp (pi f) = f i := ext $ assume c, rfl lemma infi_ker_proj : (⨅i, ker (proj i) : submodule R (Πi, φ i)) = ⊥ := linear_map.infi_ker_proj variables (R φ) /-- If `I` and `J` are complementary index sets, the product of the kernels of the `J`th projections of `φ` is linearly equivalent to the product over `I`. -/ def infi_ker_proj_equiv {I J : set ι} [decidable_pred (λi, i ∈ I)] (hd : disjoint I J) (hu : set.univ ⊆ I ∪ J) : (⨅i ∈ J, ker (proj i) : submodule R (Πi, φ i)) ≃L[R] (Πi:I, φ i) := ⟨ linear_map.infi_ker_proj_equiv R φ hd hu, continuous_pi (λ i, begin have := @continuous_subtype_coe _ _ (λ x, x ∈ (⨅i ∈ J, ker (proj i) : submodule R (Πi, φ i))), have := continuous.comp (by exact continuous_apply i) this, exact this end), continuous_subtype_mk _ (continuous_pi (λ i, begin dsimp, split_ifs; [apply continuous_apply, exact continuous_zero] end)) ⟩ end pi section ring variables {R : Type*} [ring R] {R₂ : Type*} [ring R₂] {M : Type*} [topological_space M] [add_comm_group M] {M₂ : Type*} [topological_space M₂] [add_comm_group M₂] {M₃ : Type*} [topological_space M₃] [add_comm_group M₃] {M₄ : Type*} [topological_space M₄] [add_comm_group M₄] [module R M] [module R₂ M₂] {σ₁₂ : R →+* R₂} section variables (f g : M →SL[σ₁₂] M₂) (x y : M) @[simp] lemma map_neg : f (-x) = - (f x) := (to_linear_map _).map_neg _ @[simp] lemma map_sub : f (x - y) = f x - f y := (to_linear_map _).map_sub _ _ @[simp] lemma sub_apply' (x : M) : ((f : M →ₛₗ[σ₁₂] M₂) - g) x = f x - g x := rfl end section variables [module R M₂] [module R M₃] [module R M₄] variables (c : R) (f g : M →L[R] M₂) (h : M₂ →L[R] M₃) (x y z : M) lemma range_prod_eq {f : M →L[R] M₂} {g : M →L[R] M₃} (h : ker f ⊔ ker g = ⊤) : range (f.prod g) = (range f).prod (range g) := linear_map.range_prod_eq h lemma ker_prod_ker_le_ker_coprod [has_continuous_add M₃] (f : M →L[R] M₃) (g : M₂ →L[R] M₃) : (ker f).prod (ker g) ≤ ker (f.coprod g) := linear_map.ker_prod_ker_le_ker_coprod f.to_linear_map g.to_linear_map lemma ker_coprod_of_disjoint_range [has_continuous_add M₃] (f : M →L[R] M₃) (g : M₂ →L[R] M₃) (hd : disjoint f.range g.range) : ker (f.coprod g) = (ker f).prod (ker g) := linear_map.ker_coprod_of_disjoint_range f.to_linear_map g.to_linear_map hd end section variables [topological_add_group M₂] variables (f g : M →SL[σ₁₂] M₂) (x y : M) instance : has_neg (M →SL[σ₁₂] M₂) := ⟨λ f, ⟨-f, f.2.neg⟩⟩ @[simp] lemma neg_apply : (-f) x = - (f x) := rfl @[simp, norm_cast] lemma coe_neg : (((-f) : M →SL[σ₁₂] M₂) : M →ₛₗ[σ₁₂] M₂) = -(f : M →ₛₗ[σ₁₂] M₂) := rfl @[norm_cast] lemma coe_neg' : (((-f) : M →SL[σ₁₂] M₂) : M → M₂) = -(f : M → M₂) := rfl instance : has_sub (M →SL[σ₁₂] M₂) := ⟨λ f g, ⟨f - g, f.2.sub g.2⟩⟩ lemma continuous_gsmul : ∀ (n : ℤ), continuous (λ (x : M₂), n • x) | (n : ℕ) := by { simp only [gsmul_coe_nat], exact continuous_nsmul _ } | -[1+ n] := by { simp only [gsmul_neg_succ_of_nat], exact (continuous_nsmul _).neg } @[continuity] lemma continuous.gsmul {α : Type*} [topological_space α] {n : ℤ} {f : α → M₂} (hf : continuous f) : continuous (λ (x : α), n • (f x)) := (continuous_gsmul n).comp hf instance : add_comm_group (M →SL[σ₁₂] M₂) := by refine { zero := 0, add := (+), neg := has_neg.neg, sub := has_sub.sub, sub_eq_add_neg := _, nsmul := λ n f, { to_fun := λ x, n • (f x), map_add' := by simp, map_smul' := by simp [smul_comm n] }, gsmul := λ n f, { to_fun := λ x, n • (f x), map_add' := by simp, map_smul' := by simp [smul_comm n] }, gsmul_zero' := λ f, by { ext, simp }, gsmul_succ' := λ n f, by { ext, simp [add_smul, add_comm] }, gsmul_neg' := λ n f, by { ext, simp [nat.succ_eq_add_one, add_smul] }, .. continuous_linear_map.add_comm_monoid, .. }; intros; ext; apply_rules [zero_add, add_assoc, add_zero, add_left_neg, add_comm, sub_eq_add_neg] lemma sub_apply (x : M) : (f - g) x = f x - g x := rfl @[simp, norm_cast] lemma coe_sub : (((f - g) : M →SL[σ₁₂] M₂) : M →ₛₗ[σ₁₂] M₂) = f - g := rfl @[simp, norm_cast] lemma coe_sub' : (((f - g) : M →SL[σ₁₂] M₂) : M → M₂) = (f : M → M₂) - g := rfl end instance [topological_add_group M] : ring (M →L[R] M) := { mul := (*), one := 1, mul_one := λ _, ext $ λ _, rfl, one_mul := λ _, ext $ λ _, rfl, mul_assoc := λ _ _ _, ext $ λ _, rfl, left_distrib := λ _ _ _, ext $ λ _, map_add _ _ _, right_distrib := λ _ _ _, ext $ λ _, linear_map.add_apply _ _ _, ..continuous_linear_map.add_comm_group } lemma smul_right_one_pow [topological_space R] [topological_ring R] (c : R) (n : ℕ) : (smul_right (1 : R →L[R] R) c)^n = smul_right (1 : R →L[R] R) (c^n) := begin induction n with n ihn, { ext, simp }, { rw [pow_succ, ihn, mul_def, smul_right_comp, smul_eq_mul, pow_succ'] } end section variables {σ₂₁ : R₂ →+* R} [ring_hom_inv_pair σ₁₂ σ₂₁] /-- Given a right inverse `f₂ : M₂ →L[R] M` to `f₁ : M →L[R] M₂`, `proj_ker_of_right_inverse f₁ f₂ h` is the projection `M →L[R] f₁.ker` along `f₂.range`. -/ def proj_ker_of_right_inverse [topological_add_group M] (f₁ : M →SL[σ₁₂] M₂) (f₂ : M₂ →SL[σ₂₁] M) (h : function.right_inverse f₂ f₁) : M →L[R] f₁.ker := (id R M - f₂.comp f₁).cod_restrict f₁.ker $ λ x, by simp [h (f₁ x)] @[simp] lemma coe_proj_ker_of_right_inverse_apply [topological_add_group M] (f₁ : M →SL[σ₁₂] M₂) (f₂ : M₂ →SL[σ₂₁] M) (h : function.right_inverse f₂ f₁) (x : M) : (f₁.proj_ker_of_right_inverse f₂ h x : M) = x - f₂ (f₁ x) := rfl @[simp] lemma proj_ker_of_right_inverse_apply_idem [topological_add_group M] (f₁ : M →SL[σ₁₂] M₂) (f₂ : M₂ →SL[σ₂₁] M) (h : function.right_inverse f₂ f₁) (x : f₁.ker) : f₁.proj_ker_of_right_inverse f₂ h x = x := subtype.ext_iff_val.2 $ by simp @[simp] lemma proj_ker_of_right_inverse_comp_inv [topological_add_group M] (f₁ : M →SL[σ₁₂] M₂) (f₂ : M₂ →SL[σ₂₁] M) (h : function.right_inverse f₂ f₁) (y : M₂) : f₁.proj_ker_of_right_inverse f₂ h (f₂ y) = 0 := subtype.ext_iff_val.2 $ by simp [h y] end end ring section smul variables {R S : Type*} [semiring R] [semiring S] [topological_space S] {M : Type*} [topological_space M] [add_comm_monoid M] [module R M] {M₂ : Type*} [topological_space M₂] [add_comm_monoid M₂] [module R M₂] {M₃ : Type*} [topological_space M₃] [add_comm_monoid M₃] [module R M₃] [module S M₃] [smul_comm_class R S M₃] [has_continuous_smul S M₃] instance : has_scalar S (M →L[R] M₃) := ⟨λ c f, ⟨c • f, (continuous_const.smul f.2 : continuous (λ x, c • f x))⟩⟩ variables (c : S) (h : M₂ →L[R] M₃) (f g : M →L[R] M₂) (x y z : M) @[simp] lemma smul_comp : (c • h).comp f = c • (h.comp f) := rfl variables [module S M₂] [has_continuous_smul S M₂] [smul_comm_class R S M₂] lemma smul_apply : (c • f) x = c • (f x) := rfl @[simp, norm_cast] lemma coe_smul : (((c • f) : M →L[R] M₂) : M →ₗ[R] M₂) = c • f := rfl @[simp, norm_cast] lemma coe_smul' : (((c • f) : M →L[R] M₂) : M → M₂) = c • f := rfl @[simp] lemma comp_smul [linear_map.compatible_smul M₂ M₃ S R] : h.comp (c • f) = c • (h.comp f) := by { ext x, exact h.map_smul_of_tower c (f x) } /-- `continuous_linear_map.prod` as an `equiv`. -/ @[simps apply] def prod_equiv : ((M →L[R] M₂) × (M →L[R] M₃)) ≃ (M →L[R] M₂ × M₃) := { to_fun := λ f, f.1.prod f.2, inv_fun := λ f, ⟨(fst _ _ _).comp f, (snd _ _ _).comp f⟩, left_inv := λ f, by ext; refl, right_inv := λ f, by ext; refl } lemma prod_ext_iff {f g : M × M₂ →L[R] M₃} : f = g ↔ f.comp (inl _ _ _) = g.comp (inl _ _ _) ∧ f.comp (inr _ _ _) = g.comp (inr _ _ _) := by { simp only [← coe_inj, linear_map.prod_ext_iff], refl } @[ext] lemma prod_ext {f g : M × M₂ →L[R] M₃} (hl : f.comp (inl _ _ _) = g.comp (inl _ _ _)) (hr : f.comp (inr _ _ _) = g.comp (inr _ _ _)) : f = g := prod_ext_iff.2 ⟨hl, hr⟩ variables [has_continuous_add M₂] instance : module S (M →L[R] M₂) := { smul_zero := λ _, ext $ λ _, smul_zero _, zero_smul := λ _, ext $ λ _, zero_smul _ _, one_smul := λ _, ext $ λ _, by exact one_smul _ _, mul_smul := λ _ _ _, ext $ λ _, mul_smul _ _ _, add_smul := λ _ _ _, ext $ λ _, add_smul _ _ _, smul_add := λ _ _ _, ext $ λ _, smul_add _ _ _ } variables (S) [has_continuous_add M₃] /-- `continuous_linear_map.prod` as a `linear_equiv`. -/ @[simps apply] def prodₗ : ((M →L[R] M₂) × (M →L[R] M₃)) ≃ₗ[S] (M →L[R] M₂ × M₃) := { map_add' := λ f g, rfl, map_smul' := λ c f, rfl, .. prod_equiv } end smul section smul_rightₗ variables {R S T M M₂ : Type*} [ring R] [ring S] [ring T] [module R S] [add_comm_group M₂] [module R M₂] [module S M₂] [is_scalar_tower R S M₂] [topological_space S] [topological_space M₂] [has_continuous_smul S M₂] [topological_space M] [add_comm_group M] [module R M] [topological_add_group M₂] [topological_space T] [module T M₂] [has_continuous_smul T M₂] [smul_comm_class R T M₂] [smul_comm_class S T M₂] /-- Given `c : E →L[𝕜] 𝕜`, `c.smul_rightₗ` is the linear map from `F` to `E →L[𝕜] F` sending `f` to `λ e, c e • f`. See also `continuous_linear_map.smul_rightL`. -/ def smul_rightₗ (c : M →L[R] S) : M₂ →ₗ[T] (M →L[R] M₂) := { to_fun := c.smul_right, map_add' := λ x y, by { ext e, apply smul_add }, map_smul' := λ a x, by { ext e, dsimp, apply smul_comm } } @[simp] lemma coe_smul_rightₗ (c : M →L[R] S) : ⇑(smul_rightₗ c : M₂ →ₗ[T] (M →L[R] M₂)) = c.smul_right := rfl end smul_rightₗ section comm_ring variables {R : Type*} [comm_ring R] [topological_space R] {M : Type*} [topological_space M] [add_comm_group M] {M₂ : Type*} [topological_space M₂] [add_comm_group M₂] {M₃ : Type*} [topological_space M₃] [add_comm_group M₃] [module R M] [module R M₂] [module R M₃] [has_continuous_smul R M₃] variables [topological_add_group M₂] [has_continuous_smul R M₂] instance : algebra R (M₂ →L[R] M₂) := algebra.of_module smul_comp (λ _ _ _, comp_smul _ _ _) end comm_ring section restrict_scalars variables {A M M₂ : Type*} [ring A] [add_comm_group M] [add_comm_group M₂] [module A M] [module A M₂] [topological_space M] [topological_space M₂] (R : Type*) [ring R] [module R M] [module R M₂] [linear_map.compatible_smul M M₂ R A] /-- If `A` is an `R`-algebra, then a continuous `A`-linear map can be interpreted as a continuous `R`-linear map. We assume `linear_map.compatible_smul M M₂ R A` to match assumptions of `linear_map.map_smul_of_tower`. -/ def restrict_scalars (f : M →L[A] M₂) : M →L[R] M₂ := ⟨(f : M →ₗ[A] M₂).restrict_scalars R, f.continuous⟩ variable {R} @[simp, norm_cast] lemma coe_restrict_scalars (f : M →L[A] M₂) : (f.restrict_scalars R : M →ₗ[R] M₂) = (f : M →ₗ[A] M₂).restrict_scalars R := rfl @[simp] lemma coe_restrict_scalars' (f : M →L[A] M₂) : ⇑(f.restrict_scalars R) = f := rfl @[simp] lemma restrict_scalars_zero : (0 : M →L[A] M₂).restrict_scalars R = 0 := rfl section variable [topological_add_group M₂] @[simp] lemma restrict_scalars_add (f g : M →L[A] M₂) : (f + g).restrict_scalars R = f.restrict_scalars R + g.restrict_scalars R := rfl @[simp] lemma restrict_scalars_neg (f : M →L[A] M₂) : (-f).restrict_scalars R = -f.restrict_scalars R := rfl end variables {S : Type*} [ring S] [topological_space S] [module S M₂] [has_continuous_smul S M₂] [smul_comm_class A S M₂] [smul_comm_class R S M₂] @[simp] lemma restrict_scalars_smul (c : S) (f : M →L[A] M₂) : (c • f).restrict_scalars R = c • f.restrict_scalars R := rfl variables (A M M₂ R S) [topological_add_group M₂] /-- `continuous_linear_map.restrict_scalars` as a `linear_map`. See also `continuous_linear_map.restrict_scalarsL`. -/ def restrict_scalarsₗ : (M →L[A] M₂) →ₗ[S] (M →L[R] M₂) := { to_fun := restrict_scalars R, map_add' := restrict_scalars_add, map_smul' := restrict_scalars_smul } variables {A M M₂ R S} @[simp] lemma coe_restrict_scalarsₗ : ⇑(restrict_scalarsₗ A M M₂ R S) = restrict_scalars R := rfl end restrict_scalars end continuous_linear_map namespace continuous_linear_equiv section add_comm_monoid variables {R₁ : Type*} [semiring R₁] {R₂ : Type*} [semiring R₂] {R₃ : Type*} [semiring R₃] {M₁ : Type*} [topological_space M₁] [add_comm_monoid M₁] {M₂ : Type*} [topological_space M₂] [add_comm_monoid M₂] {M₃ : Type*} [topological_space M₃] [add_comm_monoid M₃] {M₄ : Type*} [topological_space M₄] [add_comm_monoid M₄] [module R₁ M₁] [module R₂ M₂] [module R₃ M₃] {σ₁₂ : R₁ →+* R₂} {σ₂₁ : R₂ →+* R₁} [ring_hom_inv_pair σ₁₂ σ₂₁] [ring_hom_inv_pair σ₂₁ σ₁₂] {σ₂₃ : R₂ →+* R₃} {σ₃₂ : R₃ →+* R₂} [ring_hom_inv_pair σ₂₃ σ₃₂] [ring_hom_inv_pair σ₃₂ σ₂₃] {σ₁₃ : R₁ →+* R₃} {σ₃₁ : R₃ →+* R₁} [ring_hom_inv_pair σ₁₃ σ₃₁] [ring_hom_inv_pair σ₃₁ σ₁₃] [ring_hom_comp_triple σ₁₂ σ₂₃ σ₁₃] [ring_hom_comp_triple σ₃₂ σ₂₁ σ₃₁] include σ₂₁ /-- A continuous linear equivalence induces a continuous linear map. -/ def to_continuous_linear_map (e : M₁ ≃SL[σ₁₂] M₂) : M₁ →SL[σ₁₂] M₂ := { cont := e.continuous_to_fun, ..e.to_linear_equiv.to_linear_map } /-- Coerce continuous linear equivs to continuous linear maps. -/ instance : has_coe (M₁ ≃SL[σ₁₂] M₂) (M₁ →SL[σ₁₂] M₂) := ⟨to_continuous_linear_map⟩ /-- Coerce continuous linear equivs to maps. -/ -- see Note [function coercion] instance : has_coe_to_fun (M₁ ≃SL[σ₁₂] M₂) (λ _, M₁ → M₂) := ⟨λ f, f⟩ @[simp] theorem coe_def_rev (e : M₁ ≃SL[σ₁₂] M₂) : e.to_continuous_linear_map = e := rfl theorem coe_apply (e : M₁ ≃SL[σ₁₂] M₂) (b : M₁) : (e : M₁ →SL[σ₁₂] M₂) b = e b := rfl @[simp] lemma coe_to_linear_equiv (f : M₁ ≃SL[σ₁₂] M₂) : ⇑f.to_linear_equiv = f := rfl @[simp, norm_cast] lemma coe_coe (e : M₁ ≃SL[σ₁₂] M₂) : ((e : M₁ →SL[σ₁₂] M₂) : M₁ → M₂) = e := rfl lemma to_linear_equiv_injective : function.injective (to_linear_equiv : (M₁ ≃SL[σ₁₂] M₂) → (M₁ ≃ₛₗ[σ₁₂] M₂)) | ⟨e, _, _⟩ ⟨e', _, _⟩ rfl := rfl @[ext] lemma ext {f g : M₁ ≃SL[σ₁₂] M₂} (h : (f : M₁ → M₂) = g) : f = g := to_linear_equiv_injective $ linear_equiv.ext $ congr_fun h lemma coe_injective : function.injective (coe : (M₁ ≃SL[σ₁₂] M₂) → (M₁ →SL[σ₁₂] M₂)) := λ e e' h, ext $ funext $ continuous_linear_map.ext_iff.1 h @[simp, norm_cast] lemma coe_inj {e e' : M₁ ≃SL[σ₁₂] M₂} : (e : M₁ →SL[σ₁₂] M₂) = e' ↔ e = e' := coe_injective.eq_iff /-- A continuous linear equivalence induces a homeomorphism. -/ def to_homeomorph (e : M₁ ≃SL[σ₁₂] M₂) : M₁ ≃ₜ M₂ := { to_equiv := e.to_linear_equiv.to_equiv, ..e } @[simp] lemma coe_to_homeomorph (e : M₁ ≃SL[σ₁₂] M₂) : ⇑e.to_homeomorph = e := rfl lemma image_closure (e : M₁ ≃SL[σ₁₂] M₂) (s : set M₁) : e '' closure s = closure (e '' s) := e.to_homeomorph.image_closure s lemma preimage_closure (e : M₁ ≃SL[σ₁₂] M₂) (s : set M₂) : e ⁻¹' closure s = closure (e ⁻¹' s) := e.to_homeomorph.preimage_closure s @[simp] lemma is_closed_image (e : M₁ ≃SL[σ₁₂] M₂) {s : set M₁} : is_closed (e '' s) ↔ is_closed s := e.to_homeomorph.is_closed_image lemma map_nhds_eq (e : M₁ ≃SL[σ₁₂] M₂) (x : M₁) : map e (𝓝 x) = 𝓝 (e x) := e.to_homeomorph.map_nhds_eq x -- Make some straightforward lemmas available to `simp`. @[simp] lemma map_zero (e : M₁ ≃SL[σ₁₂] M₂) : e (0 : M₁) = 0 := (e : M₁ →SL[σ₁₂] M₂).map_zero @[simp] lemma map_add (e : M₁ ≃SL[σ₁₂] M₂) (x y : M₁) : e (x + y) = e x + e y := (e : M₁ →SL[σ₁₂] M₂).map_add x y @[simp] lemma map_smulₛₗ (e : M₁ ≃SL[σ₁₂] M₂) (c : R₁) (x : M₁) : e (c • x) = σ₁₂ c • (e x) := (e : M₁ →SL[σ₁₂] M₂).map_smulₛₗ c x omit σ₂₁ @[simp] lemma map_smul [module R₁ M₂] (e : M₁ ≃L[R₁] M₂) (c : R₁) (x : M₁) : e (c • x) = c • (e x) := (e : M₁ →L[R₁] M₂).map_smul c x include σ₂₁ @[simp] lemma map_eq_zero_iff (e : M₁ ≃SL[σ₁₂] M₂) {x : M₁} : e x = 0 ↔ x = 0 := e.to_linear_equiv.map_eq_zero_iff attribute [continuity] continuous_linear_equiv.continuous_to_fun continuous_linear_equiv.continuous_inv_fun @[continuity] protected lemma continuous (e : M₁ ≃SL[σ₁₂] M₂) : continuous (e : M₁ → M₂) := e.continuous_to_fun protected lemma continuous_on (e : M₁ ≃SL[σ₁₂] M₂) {s : set M₁} : continuous_on (e : M₁ → M₂) s := e.continuous.continuous_on protected lemma continuous_at (e : M₁ ≃SL[σ₁₂] M₂) {x : M₁} : continuous_at (e : M₁ → M₂) x := e.continuous.continuous_at protected lemma continuous_within_at (e : M₁ ≃SL[σ₁₂] M₂) {s : set M₁} {x : M₁} : continuous_within_at (e : M₁ → M₂) s x := e.continuous.continuous_within_at lemma comp_continuous_on_iff {α : Type*} [topological_space α] (e : M₁ ≃SL[σ₁₂] M₂) {f : α → M₁} {s : set α} : continuous_on (e ∘ f) s ↔ continuous_on f s := e.to_homeomorph.comp_continuous_on_iff _ _ lemma comp_continuous_iff {α : Type*} [topological_space α] (e : M₁ ≃SL[σ₁₂] M₂) {f : α → M₁} : continuous (e ∘ f) ↔ continuous f := e.to_homeomorph.comp_continuous_iff omit σ₂₁ /-- An extensionality lemma for `R ≃L[R] M`. -/ lemma ext₁ [topological_space R₁] {f g : R₁ ≃L[R₁] M₁} (h : f 1 = g 1) : f = g := ext $ funext $ λ x, mul_one x ▸ by rw [← smul_eq_mul, map_smul, h, map_smul] section variables (R₁ M₁) /-- The identity map as a continuous linear equivalence. -/ @[refl] protected def refl : M₁ ≃L[R₁] M₁ := { continuous_to_fun := continuous_id, continuous_inv_fun := continuous_id, .. linear_equiv.refl R₁ M₁ } end @[simp, norm_cast] lemma coe_refl : (continuous_linear_equiv.refl R₁ M₁ : M₁ →L[R₁] M₁) = continuous_linear_map.id R₁ M₁ := rfl @[simp, norm_cast] lemma coe_refl' : (continuous_linear_equiv.refl R₁ M₁ : M₁ → M₁) = id := rfl /-- The inverse of a continuous linear equivalence as a continuous linear equivalence-/ @[symm] protected def symm (e : M₁ ≃SL[σ₁₂] M₂) : M₂ ≃SL[σ₂₁] M₁ := { continuous_to_fun := e.continuous_inv_fun, continuous_inv_fun := e.continuous_to_fun, .. e.to_linear_equiv.symm } include σ₂₁ @[simp] lemma symm_to_linear_equiv (e : M₁ ≃SL[σ₁₂] M₂) : e.symm.to_linear_equiv = e.to_linear_equiv.symm := by { ext, refl } @[simp] lemma symm_to_homeomorph (e : M₁ ≃SL[σ₁₂] M₂) : e.to_homeomorph.symm = e.symm.to_homeomorph := rfl lemma symm_map_nhds_eq (e : M₁ ≃SL[σ₁₂] M₂) (x : M₁) : map e.symm (𝓝 (e x)) = 𝓝 x := e.to_homeomorph.symm_map_nhds_eq x omit σ₂₁ include σ₂₁ σ₃₂ σ₃₁ /-- The composition of two continuous linear equivalences as a continuous linear equivalence. -/ @[trans] protected def trans (e₁ : M₁ ≃SL[σ₁₂] M₂) (e₂ : M₂ ≃SL[σ₂₃] M₃) : M₁ ≃SL[σ₁₃] M₃ := { continuous_to_fun := e₂.continuous_to_fun.comp e₁.continuous_to_fun, continuous_inv_fun := e₁.continuous_inv_fun.comp e₂.continuous_inv_fun, .. e₁.to_linear_equiv.trans e₂.to_linear_equiv } include σ₁₃ @[simp] lemma trans_to_linear_equiv (e₁ : M₁ ≃SL[σ₁₂] M₂) (e₂ : M₂ ≃SL[σ₂₃] M₃) : (e₁.trans e₂).to_linear_equiv = e₁.to_linear_equiv.trans e₂.to_linear_equiv := by { ext, refl } omit σ₁₃ σ₂₁ σ₃₂ σ₃₁ /-- Product of two continuous linear equivalences. The map comes from `equiv.prod_congr`. -/ def prod [module R₁ M₂] [module R₁ M₃] [module R₁ M₄] (e : M₁ ≃L[R₁] M₂) (e' : M₃ ≃L[R₁] M₄) : (M₁ × M₃) ≃L[R₁] (M₂ × M₄) := { continuous_to_fun := e.continuous_to_fun.prod_map e'.continuous_to_fun, continuous_inv_fun := e.continuous_inv_fun.prod_map e'.continuous_inv_fun, .. e.to_linear_equiv.prod e'.to_linear_equiv } @[simp, norm_cast] lemma prod_apply [module R₁ M₂] [module R₁ M₃] [module R₁ M₄] (e : M₁ ≃L[R₁] M₂) (e' : M₃ ≃L[R₁] M₄) (x) : e.prod e' x = (e x.1, e' x.2) := rfl @[simp, norm_cast] lemma coe_prod [module R₁ M₂] [module R₁ M₃] [module R₁ M₄] (e : M₁ ≃L[R₁] M₂) (e' : M₃ ≃L[R₁] M₄) : (e.prod e' : (M₁ × M₃) →L[R₁] (M₂ × M₄)) = (e : M₁ →L[R₁] M₂).prod_map (e' : M₃ →L[R₁] M₄) := rfl include σ₂₁ theorem bijective (e : M₁ ≃SL[σ₁₂] M₂) : function.bijective e := e.to_linear_equiv.to_equiv.bijective theorem injective (e : M₁ ≃SL[σ₁₂] M₂) : function.injective e := e.to_linear_equiv.to_equiv.injective theorem surjective (e : M₁ ≃SL[σ₁₂] M₂) : function.surjective e := e.to_linear_equiv.to_equiv.surjective include σ₃₂ σ₃₁ σ₁₃ @[simp] theorem trans_apply (e₁ : M₁ ≃SL[σ₁₂] M₂) (e₂ : M₂ ≃SL[σ₂₃] M₃) (c : M₁) : (e₁.trans e₂) c = e₂ (e₁ c) := rfl omit σ₃₂ σ₃₁ σ₁₃ @[simp] theorem apply_symm_apply (e : M₁ ≃SL[σ₁₂] M₂) (c : M₂) : e (e.symm c) = c := e.1.right_inv c @[simp] theorem symm_apply_apply (e : M₁ ≃SL[σ₁₂] M₂) (b : M₁) : e.symm (e b) = b := e.1.left_inv b include σ₁₂ σ₂₃ σ₁₃ σ₃₁ @[simp] theorem symm_trans_apply (e₁ : M₂ ≃SL[σ₂₁] M₁) (e₂ : M₃ ≃SL[σ₃₂] M₂) (c : M₁) : (e₂.trans e₁).symm c = e₂.symm (e₁.symm c) := rfl omit σ₁₂ σ₂₃ σ₁₃ σ₃₁ @[simp] theorem symm_image_image (e : M₁ ≃SL[σ₁₂] M₂) (s : set M₁) : e.symm '' (e '' s) = s := e.to_linear_equiv.to_equiv.symm_image_image s @[simp] theorem image_symm_image (e : M₁ ≃SL[σ₁₂] M₂) (s : set M₂) : e '' (e.symm '' s) = s := e.symm.symm_image_image s include σ₃₂ σ₃₁ @[simp, norm_cast] lemma comp_coe (f : M₁ ≃SL[σ₁₂] M₂) (f' : M₂ ≃SL[σ₂₃] M₃) : (f' : M₂ →SL[σ₂₃] M₃).comp (f : M₁ →SL[σ₁₂] M₂) = (f.trans f' : M₁ →SL[σ₁₃] M₃) := rfl omit σ₃₂ σ₃₁ σ₂₁ @[simp] theorem coe_comp_coe_symm (e : M₁ ≃SL[σ₁₂] M₂) : (e : M₁ →SL[σ₁₂] M₂).comp (e.symm : M₂ →SL[σ₂₁] M₁) = continuous_linear_map.id R₂ M₂ := continuous_linear_map.ext e.apply_symm_apply @[simp] theorem coe_symm_comp_coe (e : M₁ ≃SL[σ₁₂] M₂) : (e.symm : M₂ →SL[σ₂₁] M₁).comp (e : M₁ →SL[σ₁₂] M₂) = continuous_linear_map.id R₁ M₁ := continuous_linear_map.ext e.symm_apply_apply include σ₂₁ @[simp] lemma symm_comp_self (e : M₁ ≃SL[σ₁₂] M₂) : (e.symm : M₂ → M₁) ∘ (e : M₁ → M₂) = id := by{ ext x, exact symm_apply_apply e x } @[simp] lemma self_comp_symm (e : M₁ ≃SL[σ₁₂] M₂) : (e : M₁ → M₂) ∘ (e.symm : M₂ → M₁) = id := by{ ext x, exact apply_symm_apply e x } @[simp] theorem symm_symm (e : M₁ ≃SL[σ₁₂] M₂) : e.symm.symm = e := by { ext x, refl } omit σ₂₁ @[simp] lemma refl_symm : (continuous_linear_equiv.refl R₁ M₁).symm = continuous_linear_equiv.refl R₁ M₁ := rfl include σ₂₁ theorem symm_symm_apply (e : M₁ ≃SL[σ₁₂] M₂) (x : M₁) : e.symm.symm x = e x := rfl lemma symm_apply_eq (e : M₁ ≃SL[σ₁₂] M₂) {x y} : e.symm x = y ↔ x = e y := e.to_linear_equiv.symm_apply_eq lemma eq_symm_apply (e : M₁ ≃SL[σ₁₂] M₂) {x y} : y = e.symm x ↔ e y = x := e.to_linear_equiv.eq_symm_apply protected lemma image_eq_preimage (e : M₁ ≃SL[σ₁₂] M₂) (s : set M₁) : e '' s = e.symm ⁻¹' s := e.to_linear_equiv.to_equiv.image_eq_preimage s protected lemma image_symm_eq_preimage (e : M₁ ≃SL[σ₁₂] M₂) (s : set M₂) : e.symm '' s = e ⁻¹' s := by rw [e.symm.image_eq_preimage, e.symm_symm] omit σ₂₁ /-- Create a `continuous_linear_equiv` from two `continuous_linear_map`s that are inverse of each other. -/ def equiv_of_inverse (f₁ : M₁ →SL[σ₁₂] M₂) (f₂ : M₂ →SL[σ₂₁] M₁) (h₁ : function.left_inverse f₂ f₁) (h₂ : function.right_inverse f₂ f₁) : M₁ ≃SL[σ₁₂] M₂ := { to_fun := f₁, continuous_to_fun := f₁.continuous, inv_fun := f₂, continuous_inv_fun := f₂.continuous, left_inv := h₁, right_inv := h₂, .. f₁ } include σ₂₁ @[simp] lemma equiv_of_inverse_apply (f₁ : M₁ →SL[σ₁₂] M₂) (f₂ h₁ h₂ x) : equiv_of_inverse f₁ f₂ h₁ h₂ x = f₁ x := rfl @[simp] lemma symm_equiv_of_inverse (f₁ : M₁ →SL[σ₁₂] M₂) (f₂ h₁ h₂) : (equiv_of_inverse f₁ f₂ h₁ h₂).symm = equiv_of_inverse f₂ f₁ h₂ h₁ := rfl omit σ₂₁ variable (M₁) /-- The continuous linear equivalences from `M` to itself form a group under composition. -/ instance automorphism_group : group (M₁ ≃L[R₁] M₁) := { mul := λ f g, g.trans f, one := continuous_linear_equiv.refl R₁ M₁, inv := λ f, f.symm, mul_assoc := λ f g h, by {ext, refl}, mul_one := λ f, by {ext, refl}, one_mul := λ f, by {ext, refl}, mul_left_inv := λ f, by {ext, exact f.left_inv x} } end add_comm_monoid section add_comm_group variables {R : Type*} [semiring R] {M : Type*} [topological_space M] [add_comm_group M] {M₂ : Type*} [topological_space M₂] [add_comm_group M₂] {M₃ : Type*} [topological_space M₃] [add_comm_group M₃] {M₄ : Type*} [topological_space M₄] [add_comm_group M₄] [module R M] [module R M₂] [module R M₃] [module R M₄] variables [topological_add_group M₄] /-- Equivalence given by a block lower diagonal matrix. `e` and `e'` are diagonal square blocks, and `f` is a rectangular block below the diagonal. -/ def skew_prod (e : M ≃L[R] M₂) (e' : M₃ ≃L[R] M₄) (f : M →L[R] M₄) : (M × M₃) ≃L[R] M₂ × M₄ := { continuous_to_fun := (e.continuous_to_fun.comp continuous_fst).prod_mk ((e'.continuous_to_fun.comp continuous_snd).add $ f.continuous.comp continuous_fst), continuous_inv_fun := (e.continuous_inv_fun.comp continuous_fst).prod_mk (e'.continuous_inv_fun.comp $ continuous_snd.sub $ f.continuous.comp $ e.continuous_inv_fun.comp continuous_fst), .. e.to_linear_equiv.skew_prod e'.to_linear_equiv ↑f } @[simp] lemma skew_prod_apply (e : M ≃L[R] M₂) (e' : M₃ ≃L[R] M₄) (f : M →L[R] M₄) (x) : e.skew_prod e' f x = (e x.1, e' x.2 + f x.1) := rfl @[simp] lemma skew_prod_symm_apply (e : M ≃L[R] M₂) (e' : M₃ ≃L[R] M₄) (f : M →L[R] M₄) (x) : (e.skew_prod e' f).symm x = (e.symm x.1, e'.symm (x.2 - f (e.symm x.1))) := rfl end add_comm_group section ring variables {R : Type*} [ring R] {R₂ : Type*} [ring R₂] {M : Type*} [topological_space M] [add_comm_group M] [module R M] {M₂ : Type*} [topological_space M₂] [add_comm_group M₂] [module R₂ M₂] variables {σ₁₂ : R →+* R₂} {σ₂₁ : R₂ →+* R} [ring_hom_inv_pair σ₁₂ σ₂₁] [ring_hom_inv_pair σ₂₁ σ₁₂] include σ₂₁ @[simp] lemma map_sub (e : M ≃SL[σ₁₂] M₂) (x y : M) : e (x - y) = e x - e y := (e : M →SL[σ₁₂] M₂).map_sub x y @[simp] lemma map_neg (e : M ≃SL[σ₁₂] M₂) (x : M) : e (-x) = -e x := (e : M →SL[σ₁₂] M₂).map_neg x omit σ₂₁ section /-! The next theorems cover the identification between `M ≃L[𝕜] M`and the group of units of the ring `M →L[R] M`. -/ variables [topological_add_group M] /-- An invertible continuous linear map `f` determines a continuous equivalence from `M` to itself. -/ def of_unit (f : units (M →L[R] M)) : (M ≃L[R] M) := { to_linear_equiv := { to_fun := f.val, map_add' := by simp, map_smul' := by simp, inv_fun := f.inv, left_inv := λ x, show (f.inv * f.val) x = x, by {rw f.inv_val, simp}, right_inv := λ x, show (f.val * f.inv) x = x, by {rw f.val_inv, simp}, }, continuous_to_fun := f.val.continuous, continuous_inv_fun := f.inv.continuous } /-- A continuous equivalence from `M` to itself determines an invertible continuous linear map. -/ def to_unit (f : (M ≃L[R] M)) : units (M →L[R] M) := { val := f, inv := f.symm, val_inv := by {ext, simp}, inv_val := by {ext, simp} } variables (R M) /-- The units of the algebra of continuous `R`-linear endomorphisms of `M` is multiplicatively equivalent to the type of continuous linear equivalences between `M` and itself. -/ def units_equiv : units (M →L[R] M) ≃* (M ≃L[R] M) := { to_fun := of_unit, inv_fun := to_unit, left_inv := λ f, by {ext, refl}, right_inv := λ f, by {ext, refl}, map_mul' := λ x y, by {ext, refl} } @[simp] lemma units_equiv_apply (f : units (M →L[R] M)) (x : M) : units_equiv R M f x = f x := rfl end section variables (R) [topological_space R] [has_continuous_mul R] /-- Continuous linear equivalences `R ≃L[R] R` are enumerated by `units R`. -/ def units_equiv_aut : units R ≃ (R ≃L[R] R) := { to_fun := λ u, equiv_of_inverse (continuous_linear_map.smul_right (1 : R →L[R] R) ↑u) (continuous_linear_map.smul_right (1 : R →L[R] R) ↑u⁻¹) (λ x, by simp) (λ x, by simp), inv_fun := λ e, ⟨e 1, e.symm 1, by rw [← smul_eq_mul, ← map_smul, smul_eq_mul, mul_one, symm_apply_apply], by rw [← smul_eq_mul, ← map_smul, smul_eq_mul, mul_one, apply_symm_apply]⟩, left_inv := λ u, units.ext $ by simp, right_inv := λ e, ext₁ $ by simp } variable {R} @[simp] lemma units_equiv_aut_apply (u : units R) (x : R) : units_equiv_aut R u x = x * u := rfl @[simp] lemma units_equiv_aut_apply_symm (u : units R) (x : R) : (units_equiv_aut R u).symm x = x * ↑u⁻¹ := rfl @[simp] lemma units_equiv_aut_symm_apply (e : R ≃L[R] R) : ↑((units_equiv_aut R).symm e) = e 1 := rfl end variables [module R M₂] [topological_add_group M] open _root_.continuous_linear_map (id fst snd subtype_val mem_ker) /-- A pair of continuous linear maps such that `f₁ ∘ f₂ = id` generates a continuous linear equivalence `e` between `M` and `M₂ × f₁.ker` such that `(e x).2 = x` for `x ∈ f₁.ker`, `(e x).1 = f₁ x`, and `(e (f₂ y)).2 = 0`. The map is given by `e x = (f₁ x, x - f₂ (f₁ x))`. -/ def equiv_of_right_inverse (f₁ : M →L[R] M₂) (f₂ : M₂ →L[R] M) (h : function.right_inverse f₂ f₁) : M ≃L[R] M₂ × f₁.ker := equiv_of_inverse (f₁.prod (f₁.proj_ker_of_right_inverse f₂ h)) (f₂.coprod (subtype_val f₁.ker)) (λ x, by simp) (λ ⟨x, y⟩, by simp [h x]) @[simp] lemma fst_equiv_of_right_inverse (f₁ : M →L[R] M₂) (f₂ : M₂ →L[R] M) (h : function.right_inverse f₂ f₁) (x : M) : (equiv_of_right_inverse f₁ f₂ h x).1 = f₁ x := rfl @[simp] lemma snd_equiv_of_right_inverse (f₁ : M →L[R] M₂) (f₂ : M₂ →L[R] M) (h : function.right_inverse f₂ f₁) (x : M) : ((equiv_of_right_inverse f₁ f₂ h x).2 : M) = x - f₂ (f₁ x) := rfl @[simp] lemma equiv_of_right_inverse_symm_apply (f₁ : M →L[R] M₂) (f₂ : M₂ →L[R] M) (h : function.right_inverse f₂ f₁) (y : M₂ × f₁.ker) : (equiv_of_right_inverse f₁ f₂ h).symm y = f₂ y.1 + y.2 := rfl end ring section variables (ι R M : Type*) [unique ι] [semiring R] [add_comm_monoid M] [module R M] [topological_space M] /-- If `ι` has a unique element, then `ι → M` is continuously linear equivalent to `M`. -/ def fun_unique : (ι → M) ≃L[R] M := { to_linear_equiv := linear_equiv.fun_unique ι R M, .. homeomorph.fun_unique ι M } variables {ι R M} @[simp] lemma coe_fun_unique : ⇑(fun_unique ι R M) = function.eval (default ι) := rfl @[simp] lemma coe_fun_unique_symm : ⇑(fun_unique ι R M).symm = function.const ι := rfl end end continuous_linear_equiv namespace continuous_linear_map open_locale classical variables {R : Type*} {M : Type*} {M₂ : Type*} [topological_space M] [topological_space M₂] section variables [semiring R] variables [add_comm_monoid M₂] [module R M₂] variables [add_comm_monoid M] [module R M] /-- Introduce a function `inverse` from `M →L[R] M₂` to `M₂ →L[R] M`, which sends `f` to `f.symm` if `f` is a continuous linear equivalence and to `0` otherwise. This definition is somewhat ad hoc, but one needs a fully (rather than partially) defined inverse function for some purposes, including for calculus. -/ noncomputable def inverse : (M →L[R] M₂) → (M₂ →L[R] M) := λ f, if h : ∃ (e : M ≃L[R] M₂), (e : M →L[R] M₂) = f then ((classical.some h).symm : M₂ →L[R] M) else 0 /-- By definition, if `f` is invertible then `inverse f = f.symm`. -/ @[simp] lemma inverse_equiv (e : M ≃L[R] M₂) : inverse (e : M →L[R] M₂) = e.symm := begin have h : ∃ (e' : M ≃L[R] M₂), (e' : M →L[R] M₂) = ↑e := ⟨e, rfl⟩, simp only [inverse, dif_pos h], congr, exact_mod_cast (classical.some_spec h) end /-- By definition, if `f` is not invertible then `inverse f = 0`. -/ @[simp] lemma inverse_non_equiv (f : M →L[R] M₂) (h : ¬∃ (e' : M ≃L[R] M₂), ↑e' = f) : inverse f = 0 := dif_neg h end section variables [ring R] variables [add_comm_group M] [topological_add_group M] [module R M] variables [add_comm_group M₂] [module R M₂] @[simp] lemma ring_inverse_equiv (e : M ≃L[R] M) : ring.inverse ↑e = inverse (e : M →L[R] M) := begin suffices : ring.inverse ((((continuous_linear_equiv.units_equiv _ _).symm e) : M →L[R] M)) = inverse ↑e, { convert this }, simp, refl, end /-- The function `continuous_linear_equiv.inverse` can be written in terms of `ring.inverse` for the ring of self-maps of the domain. -/ lemma to_ring_inverse (e : M ≃L[R] M₂) (f : M →L[R] M₂) : inverse f = (ring.inverse ((e.symm : (M₂ →L[R] M)).comp f)) ∘L ↑e.symm := begin by_cases h₁ : ∃ (e' : M ≃L[R] M₂), ↑e' = f, { obtain ⟨e', he'⟩ := h₁, rw ← he', change _ = (ring.inverse ↑(e'.trans e.symm)) ∘L ↑e.symm, ext, simp }, { suffices : ¬is_unit ((e.symm : M₂ →L[R] M).comp f), { simp [this, h₁] }, contrapose! h₁, rcases h₁ with ⟨F, hF⟩, use (continuous_linear_equiv.units_equiv _ _ F).trans e, ext, dsimp, rw [coe_fn_coe_base' F, hF], simp } end lemma ring_inverse_eq_map_inverse : ring.inverse = @inverse R M M _ _ _ _ _ _ _ := begin ext, simp [to_ring_inverse (continuous_linear_equiv.refl R M)], end end end continuous_linear_map namespace submodule variables {R : Type*} [ring R] {M : Type*} [topological_space M] [add_comm_group M] [module R M] {M₂ : Type*} [topological_space M₂] [add_comm_group M₂] [module R M₂] open continuous_linear_map /-- A submodule `p` is called *complemented* if there exists a continuous projection `M →ₗ[R] p`. -/ def closed_complemented (p : submodule R M) : Prop := ∃ f : M →L[R] p, ∀ x : p, f x = x lemma closed_complemented.has_closed_complement {p : submodule R M} [t1_space p] (h : closed_complemented p) : ∃ (q : submodule R M) (hq : is_closed (q : set M)), is_compl p q := exists.elim h $ λ f hf, ⟨f.ker, f.is_closed_ker, linear_map.is_compl_of_proj hf⟩ protected lemma closed_complemented.is_closed [topological_add_group M] [t1_space M] {p : submodule R M} (h : closed_complemented p) : is_closed (p : set M) := begin rcases h with ⟨f, hf⟩, have : ker (id R M - (subtype_val p).comp f) = p := linear_map.ker_id_sub_eq_of_proj hf, exact this ▸ (is_closed_ker _) end @[simp] lemma closed_complemented_bot : closed_complemented (⊥ : submodule R M) := ⟨0, λ x, by simp only [zero_apply, eq_zero_of_bot_submodule x]⟩ @[simp] lemma closed_complemented_top : closed_complemented (⊤ : submodule R M) := ⟨(id R M).cod_restrict ⊤ (λ x, trivial), λ x, subtype.ext_iff_val.2 $ by simp⟩ end submodule lemma continuous_linear_map.closed_complemented_ker_of_right_inverse {R : Type*} [ring R] {M : Type*} [topological_space M] [add_comm_group M] {M₂ : Type*} [topological_space M₂] [add_comm_group M₂] [module R M] [module R M₂] [topological_add_group M] (f₁ : M →L[R] M₂) (f₂ : M₂ →L[R] M) (h : function.right_inverse f₂ f₁) : f₁.ker.closed_complemented := ⟨f₁.proj_ker_of_right_inverse f₂ h, f₁.proj_ker_of_right_inverse_apply_idem f₂ h⟩
1cc7cf3acd5d8c4ad3fed6ce364f74c5d063bad2
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/tests/lean/safeShadowing.lean
0c129465035e6470a551f1bf4ebe7b65c8fafff0
[ "Apache-2.0" ]
permissive
WojciechKarpiel/lean4
7f89706b8e3c1f942b83a2c91a3a00b05da0e65b
f6e1314fa08293dea66a329e05b6c196a0189163
refs/heads/master
1,686,633,402,214
1,625,821,189,000
1,625,821,258,000
384,640,886
0
0
Apache-2.0
1,625,903,617,000
1,625,903,026,000
null
UTF-8
Lean
false
false
308
lean
def f (x x : Nat) := match x with | 0 => x + 1 | Nat.succ _ => x + 2 variable {α : Type} #check fun (a : α) => a #check fun {α} (a : α) => a #check fun (x x : Nat) => x #print f set_option pp.safe_shadowing false #check fun {α} (a : α) => a #check fun (x x : Nat) => x #print f
dac9bedfbfe8200afb9ea560f6f606e58d62bc62
c777c32c8e484e195053731103c5e52af26a25d1
/src/algebra/dual_quaternion.lean
863840d77d885d956980767de8b9606dda48deaa
[ "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
4,154
lean
/- Copyright (c) 2023 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import algebra.dual_number import algebra.quaternion /-! # Dual quaternions Similar to the way that rotations in 3D space can be represented by quaternions of unit length, rigid motions in 3D space can be represented by dual quaternions of unit length. ## Main results * `quaternion.dual_number_equiv`: quaternions over dual numbers or dual numbers over quaternions are equivalent constructions. ## References * <https://en.wikipedia.org/wiki/Dual_quaternion> -/ variables {R : Type*} [comm_ring R] namespace quaternion /-- The dual quaternions can be equivalently represented as a quaternion with dual coefficients, or as a dual number with quaternion coefficients. See also `matrix.dual_number_equiv` for a similar result. -/ def dual_number_equiv : quaternion (dual_number R) ≃ₐ[R] dual_number (quaternion R) := { to_fun := λ q, (⟨q.re.fst, q.im_i.fst, q.im_j.fst, q.im_k.fst⟩, ⟨q.re.snd, q.im_i.snd, q.im_j.snd, q.im_k.snd⟩), inv_fun := λ d, ⟨(d.fst.re, d.snd.re), (d.fst.im_i, d.snd.im_i), (d.fst.im_j, d.snd.im_j), (d.fst.im_k, d.snd.im_k)⟩, left_inv := λ ⟨⟨r, rε⟩, ⟨i, iε⟩, ⟨j, jε⟩, ⟨k, kε⟩⟩, rfl, right_inv := λ ⟨⟨r, i, j, k⟩, ⟨rε, iε, jε, kε⟩⟩, rfl, map_mul' := begin rintros ⟨⟨xr, xrε⟩, ⟨xi, xiε⟩, ⟨xj, xjε⟩, ⟨xk, xkε⟩⟩, rintros ⟨⟨yr, yrε⟩, ⟨yi, yiε⟩, ⟨yj, yjε⟩, ⟨yk, ykε⟩⟩, ext : 1, { refl }, { dsimp, congr' 1; ring }, end, map_add' := begin rintros ⟨⟨xr, xrε⟩, ⟨xi, xiε⟩, ⟨xj, xjε⟩, ⟨xk, xkε⟩⟩, rintros ⟨⟨yr, yrε⟩, ⟨yi, yiε⟩, ⟨yj, yjε⟩, ⟨yk, ykε⟩⟩, refl end, commutes' := λ r, rfl } /-! Lemmas characterizing `quaternion.dual_number_equiv`. -/ -- `simps` can't work on `dual_number` because it's not a structure @[simp] lemma re_fst_dual_number_equiv (q : quaternion (dual_number R)) : (dual_number_equiv q).fst.re = q.re.fst := rfl @[simp] lemma im_i_fst_dual_number_equiv (q : quaternion (dual_number R)) : (dual_number_equiv q).fst.im_i = q.im_i.fst := rfl @[simp] lemma im_j_fst_dual_number_equiv (q : quaternion (dual_number R)) : (dual_number_equiv q).fst.im_j = q.im_j.fst := rfl @[simp] lemma im_k_fst_dual_number_equiv (q : quaternion (dual_number R)) : (dual_number_equiv q).fst.im_k = q.im_k.fst := rfl @[simp] lemma re_snd_dual_number_equiv (q : quaternion (dual_number R)) : (dual_number_equiv q).snd.re = q.re.snd := rfl @[simp] lemma im_i_snd_dual_number_equiv (q : quaternion (dual_number R)) : (dual_number_equiv q).snd.im_i = q.im_i.snd := rfl @[simp] lemma im_j_snd_dual_number_equiv (q : quaternion (dual_number R)) : (dual_number_equiv q).snd.im_j = q.im_j.snd := rfl @[simp] lemma im_k_snd_dual_number_equiv (q : quaternion (dual_number R)) : (dual_number_equiv q).snd.im_k = q.im_k.snd := rfl @[simp] lemma fst_re_dual_number_equiv_symm (d : dual_number (quaternion R)) : (dual_number_equiv.symm d).re.fst = d.fst.re := rfl @[simp] lemma fst_im_i_dual_number_equiv_symm (d : dual_number (quaternion R)) : (dual_number_equiv.symm d).im_i.fst = d.fst.im_i := rfl @[simp] lemma fst_im_j_dual_number_equiv_symm (d : dual_number (quaternion R)) : (dual_number_equiv.symm d).im_j.fst = d.fst.im_j := rfl @[simp] lemma fst_im_k_dual_number_equiv_symm (d : dual_number (quaternion R)) : (dual_number_equiv.symm d).im_k.fst = d.fst.im_k := rfl @[simp] lemma snd_re_dual_number_equiv_symm (d : dual_number (quaternion R)) : (dual_number_equiv.symm d).re.snd = d.snd.re := rfl @[simp] lemma snd_im_i_dual_number_equiv_symm (d : dual_number (quaternion R)) : (dual_number_equiv.symm d).im_i.snd = d.snd.im_i := rfl @[simp] lemma snd_im_j_dual_number_equiv_symm (d : dual_number (quaternion R)) : (dual_number_equiv.symm d).im_j.snd = d.snd.im_j := rfl @[simp] lemma snd_im_k_dual_number_equiv_symm (d : dual_number (quaternion R)) : (dual_number_equiv.symm d).im_k.snd = d.snd.im_k := rfl end quaternion
bb10364216df593824d051e8a031885071bef5e1
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/algebra/gcd_monoid/finset.lean
7aa6d8e24bbe758fd2f7650a378440ecab6040ba
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
6,868
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 data.finset.fold import algebra.gcd_monoid.multiset /-! # GCD and LCM operations on finsets ## Main definitions - `finset.gcd` - the greatest common denominator of a `finset` of elements of a `gcd_monoid` - `finset.lcm` - the least common multiple of a `finset` of elements of a `gcd_monoid` ## Implementation notes Many of the proofs use the lemmas `gcd.def` and `lcm.def`, which relate `finset.gcd` and `finset.lcm` to `multiset.gcd` and `multiset.lcm`. TODO: simplify with a tactic and `data.finset.lattice` ## Tags finset, gcd -/ variables {α β γ : Type*} namespace finset open multiset variables [comm_cancel_monoid_with_zero α] [normalized_gcd_monoid α] /-! ### lcm -/ section lcm /-- Least common multiple of a finite set -/ def lcm (s : finset β) (f : β → α) : α := s.fold gcd_monoid.lcm 1 f variables {s s₁ s₂ : finset β} {f : β → α} lemma lcm_def : s.lcm f = (s.1.map f).lcm := rfl @[simp] lemma lcm_empty : (∅ : finset β).lcm f = 1 := fold_empty @[simp] lemma lcm_dvd_iff {a : α} : s.lcm f ∣ a ↔ (∀b ∈ s, f b ∣ a) := begin apply iff.trans multiset.lcm_dvd, simp only [multiset.mem_map, and_imp, exists_imp_distrib], exact ⟨λ k b hb, k _ _ hb rfl, λ k a' b hb h, h ▸ k _ hb⟩, end lemma lcm_dvd {a : α} : (∀b ∈ s, f b ∣ a) → s.lcm f ∣ a := lcm_dvd_iff.2 lemma dvd_lcm {b : β} (hb : b ∈ s) : f b ∣ s.lcm f := lcm_dvd_iff.1 dvd_rfl _ hb @[simp] lemma lcm_insert [decidable_eq β] {b : β} : (insert b s : finset β).lcm f = gcd_monoid.lcm (f b) (s.lcm f) := begin by_cases h : b ∈ s, { rw [insert_eq_of_mem h, (lcm_eq_right_iff (f b) (s.lcm f) (multiset.normalize_lcm (s.1.map f))).2 (dvd_lcm h)] }, apply fold_insert h, end @[simp] lemma lcm_singleton {b : β} : ({b} : finset β).lcm f = normalize (f b) := multiset.lcm_singleton @[simp] lemma normalize_lcm : normalize (s.lcm f) = s.lcm f := by simp [lcm_def] lemma lcm_union [decidable_eq β] : (s₁ ∪ s₂).lcm f = gcd_monoid.lcm (s₁.lcm f) (s₂.lcm f) := finset.induction_on s₁ (by rw [empty_union, lcm_empty, lcm_one_left, normalize_lcm]) $ λ a s has ih, by rw [insert_union, lcm_insert, lcm_insert, ih, lcm_assoc] theorem lcm_congr {f g : β → α} (hs : s₁ = s₂) (hfg : ∀a ∈ s₂, f a = g a) : s₁.lcm f = s₂.lcm g := by { subst hs, exact finset.fold_congr hfg } lemma lcm_mono_fun {g : β → α} (h : ∀ b ∈ s, f b ∣ g b) : s.lcm f ∣ s.lcm g := lcm_dvd (λ b hb, (h b hb).trans (dvd_lcm hb)) lemma lcm_mono (h : s₁ ⊆ s₂) : s₁.lcm f ∣ s₂.lcm f := lcm_dvd $ assume b hb, dvd_lcm (h hb) end lcm /-! ### gcd -/ section gcd /-- Greatest common divisor of a finite set -/ def gcd (s : finset β) (f : β → α) : α := s.fold gcd_monoid.gcd 0 f variables {s s₁ s₂ : finset β} {f : β → α} lemma gcd_def : s.gcd f = (s.1.map f).gcd := rfl @[simp] lemma gcd_empty : (∅ : finset β).gcd f = 0 := fold_empty lemma dvd_gcd_iff {a : α} : a ∣ s.gcd f ↔ ∀b ∈ s, a ∣ f b := begin apply iff.trans multiset.dvd_gcd, simp only [multiset.mem_map, and_imp, exists_imp_distrib], exact ⟨λ k b hb, k _ _ hb rfl, λ k a' b hb h, h ▸ k _ hb⟩, end lemma gcd_dvd {b : β} (hb : b ∈ s) : s.gcd f ∣ f b := dvd_gcd_iff.1 dvd_rfl _ hb lemma dvd_gcd {a : α} : (∀b ∈ s, a ∣ f b) → a ∣ s.gcd f := dvd_gcd_iff.2 @[simp] lemma gcd_insert [decidable_eq β] {b : β} : (insert b s : finset β).gcd f = gcd_monoid.gcd (f b) (s.gcd f) := begin by_cases h : b ∈ s, { rw [insert_eq_of_mem h, (gcd_eq_right_iff (f b) (s.gcd f) (multiset.normalize_gcd (s.1.map f))).2 (gcd_dvd h)] ,}, apply fold_insert h, end @[simp] lemma gcd_singleton {b : β} : ({b} : finset β).gcd f = normalize (f b) := multiset.gcd_singleton @[simp] lemma normalize_gcd : normalize (s.gcd f) = s.gcd f := by simp [gcd_def] lemma gcd_union [decidable_eq β] : (s₁ ∪ s₂).gcd f = gcd_monoid.gcd (s₁.gcd f) (s₂.gcd f) := finset.induction_on s₁ (by rw [empty_union, gcd_empty, gcd_zero_left, normalize_gcd]) $ λ a s has ih, by rw [insert_union, gcd_insert, gcd_insert, ih, gcd_assoc] theorem gcd_congr {f g : β → α} (hs : s₁ = s₂) (hfg : ∀a ∈ s₂, f a = g a) : s₁.gcd f = s₂.gcd g := by { subst hs, exact finset.fold_congr hfg } lemma gcd_mono_fun {g : β → α} (h : ∀ b ∈ s, f b ∣ g b) : s.gcd f ∣ s.gcd g := dvd_gcd (λ b hb, (gcd_dvd hb).trans (h b hb)) lemma gcd_mono (h : s₁ ⊆ s₂) : s₂.gcd f ∣ s₁.gcd f := dvd_gcd $ assume b hb, gcd_dvd (h hb) theorem gcd_eq_zero_iff : s.gcd f = 0 ↔ ∀ (x : β), x ∈ s → f x = 0 := begin rw [gcd_def, multiset.gcd_eq_zero_iff], split; intro h, { intros b bs, apply h (f b), simp only [multiset.mem_map, mem_def.1 bs], use b, simp [mem_def.1 bs] }, { intros a as, rw multiset.mem_map at as, rcases as with ⟨b, ⟨bs, rfl⟩⟩, apply h b (mem_def.1 bs) } end lemma gcd_eq_gcd_filter_ne_zero [decidable_pred (λ (x : β), f x = 0)] : s.gcd f = (s.filter (λ x, f x ≠ 0)).gcd f := begin classical, transitivity ((s.filter (λ x, f x = 0)) ∪ (s.filter (λ x, f x ≠ 0))).gcd f, { rw filter_union_filter_neg_eq }, rw gcd_union, transitivity gcd_monoid.gcd (0 : α) _, { refine congr (congr rfl _) rfl, apply s.induction_on, { simp }, intros a s has h, rw filter_insert, split_ifs with h1; simp [h, h1], }, simp [gcd_zero_left, normalize_gcd], end lemma gcd_mul_left {a : α} : s.gcd (λ x, a * f x) = normalize a * s.gcd f := begin classical, apply s.induction_on, { simp }, intros b t hbt h, rw [gcd_insert, gcd_insert, h, ← gcd_mul_left], apply ((normalize_associated a).mul_right _).gcd_eq_right end lemma gcd_mul_right {a : α} : s.gcd (λ x, f x * a) = s.gcd f * normalize a := begin classical, apply s.induction_on, { simp }, intros b t hbt h, rw [gcd_insert, gcd_insert, h, ← gcd_mul_right], apply ((normalize_associated a).mul_left _).gcd_eq_right end end gcd end finset namespace finset section is_domain variables [comm_ring α] [is_domain α] [normalized_gcd_monoid α] lemma gcd_eq_of_dvd_sub {s : finset β} {f g : β → α} {a : α} (h : ∀ x : β, x ∈ s → a ∣ f x - g x) : gcd_monoid.gcd a (s.gcd f) = gcd_monoid.gcd a (s.gcd g) := begin classical, revert h, apply s.induction_on, { simp }, intros b s bs hi h, rw [gcd_insert, gcd_insert, gcd_comm (f b), ← gcd_assoc, hi (λ x hx, h _ (mem_insert_of_mem hx)), gcd_comm a, gcd_assoc, gcd_comm a (gcd_monoid.gcd _ _), gcd_comm (g b), gcd_assoc _ _ a, gcd_comm _ a], exact congr_arg _ (gcd_eq_of_dvd_sub_right (h _ (mem_insert_self _ _))) end end is_domain end finset
a5b4a7471fc6306df35c6bb660237be9ec559db3
32317185abf7e7c963f4c67c190aec61af6b3628
/hott/algebra/field.hlean
298aeb1122fee6281d4a29c02aec304d626effad
[ "Apache-2.0" ]
permissive
Andrew-Zipperer-unorganized/lean
198a2317f21198cd8d26e7085e484b86277f17f7
dcb35008e1474a0abebe632b1dced120e5f8c009
refs/heads/master
1,622,526,520,945
1,453,576,559,000
1,454,612,842,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
21,829
hlean
/- Copyright (c) 2014 Robert Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Lewis Structures with multiplicative and additive components, including division rings and fields. The development is modeled after Isabelle's library. -/ import algebra.binary algebra.group algebra.ring open eq eq.ops algebra set_option class.force_new true variable {A : Type} namespace algebra structure division_ring [class] (A : Type) extends ring A, has_inv A, zero_ne_one_class A := (mul_inv_cancel : Π{a}, a ≠ zero → mul a (inv a) = one) (inv_mul_cancel : Π{a}, a ≠ zero → mul (inv a) a = one) section division_ring variables [s : division_ring A] {a b c : A} include s protected definition algebra.div (a b : A) : A := a * b⁻¹ definition division_ring_has_div [reducible] [instance] : has_div A := has_div.mk algebra.div lemma division.def (a b : A) : a / b = a * b⁻¹ := rfl theorem mul_inv_cancel (H : a ≠ 0) : a * a⁻¹ = 1 := division_ring.mul_inv_cancel H theorem inv_mul_cancel (H : a ≠ 0) : a⁻¹ * a = 1 := division_ring.inv_mul_cancel H theorem inv_eq_one_div (a : A) : a⁻¹ = 1 / a := !one_mul⁻¹ theorem div_eq_mul_one_div (a b : A) : a / b = a * (1 / b) := by rewrite [*division.def, one_mul] theorem mul_one_div_cancel (H : a ≠ 0) : a * (1 / a) = 1 := by rewrite [-inv_eq_one_div, (mul_inv_cancel H)] theorem one_div_mul_cancel (H : a ≠ 0) : (1 / a) * a = 1 := by rewrite [-inv_eq_one_div, (inv_mul_cancel H)] theorem div_self (H : a ≠ 0) : a / a = 1 := mul_inv_cancel H theorem one_div_one : 1 / 1 = (1:A) := div_self (ne.symm zero_ne_one) theorem mul_div_assoc (a b : A) : (a * b) / c = a * (b / c) := !mul.assoc theorem one_div_ne_zero (H : a ≠ 0) : 1 / a ≠ 0 := assume H2 : 1 / a = 0, have C1 : 0 = (1:A), from symm (by rewrite [-(mul_one_div_cancel H), H2, mul_zero]), absurd C1 zero_ne_one theorem one_inv_eq : 1⁻¹ = (1:A) := by rewrite [-mul_one, inv_mul_cancel (ne.symm (@zero_ne_one A _))] theorem div_one (a : A) : a / 1 = a := by rewrite [*division.def, one_inv_eq, mul_one] theorem zero_div (a : A) : 0 / a = 0 := !zero_mul -- note: integral domain has a "mul_ne_zero". A commutative division ring is an integral -- domain, but let's not define that class for now. theorem division_ring.mul_ne_zero (Ha : a ≠ 0) (Hb : b ≠ 0) : a * b ≠ 0 := assume H : a * b = 0, have C1 : a = 0, by rewrite [-mul_one, -(mul_one_div_cancel Hb), -mul.assoc, H, zero_mul], absurd C1 Ha theorem mul_ne_zero_comm (H : a * b ≠ 0) : b * a ≠ 0 := have H2 : a ≠ 0 × b ≠ 0, from ne_zero_prod_ne_zero_of_mul_ne_zero H, division_ring.mul_ne_zero (prod.pr2 H2) (prod.pr1 H2) theorem eq_one_div_of_mul_eq_one (H : a * b = 1) : b = 1 / a := have a ≠ 0, from (suppose a = 0, have 0 = (1:A), by rewrite [-(zero_mul b), -this, H], absurd this zero_ne_one), show b = 1 / a, from symm (calc 1 / a = (1 / a) * 1 : mul_one ... = (1 / a) * (a * b) : H ... = (1 / a) * a * b : mul.assoc ... = 1 * b : one_div_mul_cancel this ... = b : one_mul) theorem eq_one_div_of_mul_eq_one_left (H : b * a = 1) : b = 1 / a := have a ≠ 0, from (suppose a = 0, have 0 = 1, from symm (calc 1 = b * a : symm H ... = b * 0 : this ... = 0 : mul_zero), absurd this zero_ne_one), show b = 1 / a, from symm (calc 1 / a = 1 * (1 / a) : one_mul ... = b * a * (1 / a) : H ... = b * (a * (1 / a)) : mul.assoc ... = b * 1 : mul_one_div_cancel this ... = b : mul_one) theorem division_ring.one_div_mul_one_div (Ha : a ≠ 0) (Hb : b ≠ 0) : (1 / a) * (1 / b) = 1 / (b * a) := have (b * a) * ((1 / a) * (1 / b)) = 1, by rewrite [mul.assoc, -(mul.assoc a), (mul_one_div_cancel Ha), one_mul, (mul_one_div_cancel Hb)], eq_one_div_of_mul_eq_one this theorem one_div_neg_one_eq_neg_one : (1:A) / (-1) = -1 := have (-1) * (-1) = (1:A), by rewrite [-neg_eq_neg_one_mul, neg_neg], symm (eq_one_div_of_mul_eq_one this) theorem division_ring.one_div_neg_eq_neg_one_div (H : a ≠ 0) : 1 / (- a) = - (1 / a) := have -1 ≠ 0, from (suppose -1 = 0, absurd (symm (calc 1 = -(-1) : neg_neg ... = -0 : this ... = (0:A) : neg_zero)) zero_ne_one), calc 1 / (- a) = 1 / ((-1) * a) : neg_eq_neg_one_mul ... = (1 / a) * (1 / (- 1)) : division_ring.one_div_mul_one_div H this ... = (1 / a) * (-1) : one_div_neg_one_eq_neg_one ... = - (1 / a) : mul_neg_one_eq_neg theorem div_neg_eq_neg_div (b : A) (Ha : a ≠ 0) : b / (- a) = - (b / a) := calc b / (- a) = b * (1 / (- a)) : by rewrite -inv_eq_one_div ... = b * -(1 / a) : division_ring.one_div_neg_eq_neg_one_div Ha ... = -(b * (1 / a)) : neg_mul_eq_mul_neg ... = - (b * a⁻¹) : inv_eq_one_div theorem neg_div (a b : A) : (-b) / a = - (b / a) := by rewrite [neg_eq_neg_one_mul, mul_div_assoc, -neg_eq_neg_one_mul] theorem division_ring.neg_div_neg_eq (a : A) {b : A} (Hb : b ≠ 0) : (-a) / (-b) = a / b := by rewrite [(div_neg_eq_neg_div _ Hb), neg_div, neg_neg] theorem division_ring.one_div_one_div (H : a ≠ 0) : 1 / (1 / a) = a := symm (eq_one_div_of_mul_eq_one_left (mul_one_div_cancel H)) theorem division_ring.eq_of_one_div_eq_one_div (Ha : a ≠ 0) (Hb : b ≠ 0) (H : 1 / a = 1 / b) : a = b := by rewrite [-(division_ring.one_div_one_div Ha), H, (division_ring.one_div_one_div Hb)] theorem mul_inv_eq (Ha : a ≠ 0) (Hb : b ≠ 0) : (b * a)⁻¹ = a⁻¹ * b⁻¹ := inverse (calc a⁻¹ * b⁻¹ = (1 / a) * b⁻¹ : inv_eq_one_div ... = (1 / a) * (1 / b) : inv_eq_one_div ... = (1 / (b * a)) : division_ring.one_div_mul_one_div Ha Hb ... = (b * a)⁻¹ : inv_eq_one_div) theorem mul_div_cancel (a : A) {b : A} (Hb : b ≠ 0) : a * b / b = a := by rewrite [*division.def, mul.assoc, (mul_inv_cancel Hb), mul_one] theorem div_mul_cancel (a : A) {b : A} (Hb : b ≠ 0) : a / b * b = a := by rewrite [*division.def, mul.assoc, (inv_mul_cancel Hb), mul_one] theorem div_add_div_same (a b c : A) : a / c + b / c = (a + b) / c := !right_distrib⁻¹ theorem div_sub_div_same (a b c : A) : (a / c) - (b / c) = (a - b) / c := by rewrite [sub_eq_add_neg, -neg_div, div_add_div_same] theorem one_div_mul_add_mul_one_div_eq_one_div_add_one_div (Ha : a ≠ 0) (Hb : b ≠ 0) : (1 / a) * (a + b) * (1 / b) = 1 / a + 1 / b := by rewrite [(left_distrib (1 / a)), (one_div_mul_cancel Ha), right_distrib, one_mul, mul.assoc, (mul_one_div_cancel Hb), mul_one, add.comm] theorem one_div_mul_sub_mul_one_div_eq_one_div_add_one_div (Ha : a ≠ 0) (Hb : b ≠ 0) : (1 / a) * (b - a) * (1 / b) = 1 / a - 1 / b := by rewrite [(mul_sub_left_distrib (1 / a)), (one_div_mul_cancel Ha), mul_sub_right_distrib, one_mul, mul.assoc, (mul_one_div_cancel Hb), mul_one] theorem div_eq_one_iff_eq (a : A) {b : A} (Hb : b ≠ 0) : a / b = 1 ↔ a = b := iff.intro (suppose a / b = 1, symm (calc b = 1 * b : one_mul ... = a / b * b : this ... = a : div_mul_cancel _ Hb)) (suppose a = b, calc a / b = b / b : this ... = 1 : div_self Hb) theorem eq_of_div_eq_one (a : A) {b : A} (Hb : b ≠ 0) : a / b = 1 → a = b := iff.mp (!div_eq_one_iff_eq Hb) theorem eq_div_iff_mul_eq (a : A) {b : A} (Hc : c ≠ 0) : a = b / c ↔ a * c = b := iff.intro (suppose a = b / c, by rewrite [this, (!div_mul_cancel Hc)]) (suppose a * c = b, by rewrite [-(!mul_div_cancel Hc), this]) theorem eq_div_of_mul_eq (a b : A) {c : A} (Hc : c ≠ 0) : a * c = b → a = b / c := iff.mpr (!eq_div_iff_mul_eq Hc) theorem mul_eq_of_eq_div (a b: A) {c : A} (Hc : c ≠ 0) : a = b / c → a * c = b := iff.mp (!eq_div_iff_mul_eq Hc) theorem add_div_eq_mul_add_div (a b : A) {c : A} (Hc : c ≠ 0) : a + b / c = (a * c + b) / c := have (a + b / c) * c = a * c + b, by rewrite [right_distrib, (!div_mul_cancel Hc)], (iff.elim_right (!eq_div_iff_mul_eq Hc)) this theorem mul_mul_div (a : A) {c : A} (Hc : c ≠ 0) : a = a * c * (1 / c) := calc a = a * 1 : mul_one ... = a * (c * (1 / c)) : mul_one_div_cancel Hc ... = a * c * (1 / c) : mul.assoc -- There are many similar rules to these last two in the Isabelle library -- that haven't been ported yet. Do as necessary. end division_ring structure field [class] (A : Type) extends division_ring A, comm_ring A section field variables [s : field A] {a b c d: A} include s theorem field.one_div_mul_one_div (Ha : a ≠ 0) (Hb : b ≠ 0) : (1 / a) * (1 / b) = 1 / (a * b) := by rewrite [(division_ring.one_div_mul_one_div Ha Hb), mul.comm b] theorem field.div_mul_right (Hb : b ≠ 0) (H : a * b ≠ 0) : a / (a * b) = 1 / b := have a ≠ 0, from prod.pr1 (ne_zero_prod_ne_zero_of_mul_ne_zero H), symm (calc 1 / b = 1 * (1 / b) : one_mul ... = (a * a⁻¹) * (1 / b) : mul_inv_cancel this ... = a * (a⁻¹ * (1 / b)) : mul.assoc ... = a * ((1 / a) * (1 / b)) : inv_eq_one_div ... = a * (1 / (b * a)) : division_ring.one_div_mul_one_div this Hb ... = a * (1 / (a * b)) : mul.comm ... = a * (a * b)⁻¹ : inv_eq_one_div) theorem field.div_mul_left (Ha : a ≠ 0) (H : a * b ≠ 0) : b / (a * b) = 1 / a := let H1 : b * a ≠ 0 := mul_ne_zero_comm H in by rewrite [mul.comm a, (field.div_mul_right Ha H1)] theorem mul_div_cancel_left (Ha : a ≠ 0) : a * b / a = b := by rewrite [mul.comm a, (!mul_div_cancel Ha)] theorem mul_div_cancel' (Hb : b ≠ 0) : b * (a / b) = a := by rewrite [mul.comm, (!div_mul_cancel Hb)] theorem one_div_add_one_div (Ha : a ≠ 0) (Hb : b ≠ 0) : 1 / a + 1 / b = (a + b) / (a * b) := assert a * b ≠ 0, from (division_ring.mul_ne_zero Ha Hb), by rewrite [add.comm, -(field.div_mul_left Ha this), -(field.div_mul_right Hb this), *division.def, -right_distrib] theorem field.div_mul_div (a : A) {b : A} (c : A) {d : A} (Hb : b ≠ 0) (Hd : d ≠ 0) : (a / b) * (c / d) = (a * c) / (b * d) := by rewrite [*division.def, 2 mul.assoc, (mul.comm b⁻¹), mul.assoc, (mul_inv_eq Hd Hb)] theorem mul_div_mul_left (a : A) {b c : A} (Hb : b ≠ 0) (Hc : c ≠ 0) : (c * a) / (c * b) = a / b := by rewrite [-(!field.div_mul_div Hc Hb), (div_self Hc), one_mul] theorem mul_div_mul_right (a : A) {b c : A} (Hb : b ≠ 0) (Hc : c ≠ 0) : (a * c) / (b * c) = a / b := by rewrite [(mul.comm a), (mul.comm b), (!mul_div_mul_left Hb Hc)] theorem div_mul_eq_mul_div (a b c : A) : (b / c) * a = (b * a) / c := by rewrite [*division.def, mul.assoc, (mul.comm c⁻¹), -mul.assoc] theorem field.div_mul_eq_mul_div_comm (a b : A) {c : A} (Hc : c ≠ 0) : (b / c) * a = b * (a / c) := by rewrite [(div_mul_eq_mul_div), -(one_mul c), -(!field.div_mul_div (ne.symm zero_ne_one) Hc), div_one, one_mul] theorem div_add_div (a : A) {b : A} (c : A) {d : A} (Hb : b ≠ 0) (Hd : d ≠ 0) : (a / b) + (c / d) = ((a * d) + (b * c)) / (b * d) := by rewrite [-(!mul_div_mul_right Hb Hd), -(!mul_div_mul_left Hd Hb), div_add_div_same] theorem div_sub_div (a : A) {b : A} (c : A) {d : A} (Hb : b ≠ 0) (Hd : d ≠ 0) : (a / b) - (c / d) = ((a * d) - (b * c)) / (b * d) := by rewrite [*sub_eq_add_neg, neg_eq_neg_one_mul, -mul_div_assoc, (!div_add_div Hb Hd), -mul.assoc, (mul.comm b), mul.assoc, -neg_eq_neg_one_mul] theorem mul_eq_mul_of_div_eq_div (a : A) {b : A} (c : A) {d : A} (Hb : b ≠ 0) (Hd : d ≠ 0) (H : a / b = c / d) : a * d = c * b := by rewrite [-mul_one, mul.assoc, (mul.comm d), -mul.assoc, -(div_self Hb), -(!field.div_mul_eq_mul_div_comm Hb), H, (div_mul_eq_mul_div), (!div_mul_cancel Hd)] theorem field.one_div_div (Ha : a ≠ 0) (Hb : b ≠ 0) : 1 / (a / b) = b / a := have (a / b) * (b / a) = 1, from calc (a / b) * (b / a) = (a * b) / (b * a) : !field.div_mul_div Hb Ha ... = (a * b) / (a * b) : mul.comm ... = 1 : div_self (division_ring.mul_ne_zero Ha Hb), symm (eq_one_div_of_mul_eq_one this) theorem field.div_div_eq_mul_div (a : A) {b c : A} (Hb : b ≠ 0) (Hc : c ≠ 0) : a / (b / c) = (a * c) / b := by rewrite [div_eq_mul_one_div, (field.one_div_div Hb Hc), -mul_div_assoc] theorem field.div_div_eq_div_mul (a : A) {b c : A} (Hb : b ≠ 0) (Hc : c ≠ 0) : (a / b) / c = a / (b * c) := by rewrite [div_eq_mul_one_div, (!field.div_mul_div Hb Hc), mul_one] theorem field.div_div_div_div_eq (a : A) {b c d : A} (Hb : b ≠ 0) (Hc : c ≠ 0) (Hd : d ≠ 0) : (a / b) / (c / d) = (a * d) / (b * c) := by rewrite [(!field.div_div_eq_mul_div Hc Hd), (div_mul_eq_mul_div), (!field.div_div_eq_div_mul Hb Hc)] theorem field.div_mul_eq_div_mul_one_div (a : A) {b c : A} (Hb : b ≠ 0) (Hc : c ≠ 0) : a / (b * c) = (a / b) * (1 / c) := by rewrite [-!field.div_div_eq_div_mul Hb Hc, -div_eq_mul_one_div] theorem eq_of_mul_eq_mul_of_nonzero_left {a b c : A} (H : a ≠ 0) (H2 : a * b = a * c) : b = c := by rewrite [-one_mul b, -div_self H, div_mul_eq_mul_div, H2, mul_div_cancel_left H] theorem eq_of_mul_eq_mul_of_nonzero_right {a b c : A} (H : c ≠ 0) (H2 : a * c = b * c) : a = b := by rewrite [-mul_one a, -div_self H, -mul_div_assoc, H2, mul_div_cancel _ H] end field structure discrete_field [class] (A : Type) extends field A := (has_decidable_eq : decidable_eq A) (inv_zero : inv zero = zero) attribute discrete_field.has_decidable_eq [instance] section discrete_field variable [s : discrete_field A] include s variables {a b c d : A} -- many of the theorems in discrete_field are the same as theorems in field sum division ring, -- but with fewer hypotheses since 0⁻¹ = 0 and equality is decidable. theorem discrete_field.eq_zero_sum_eq_zero_of_mul_eq_zero (x y : A) (H : x * y = 0) : x = 0 ⊎ y = 0 := decidable.by_cases (suppose x = 0, sum.inl this) (suppose x ≠ 0, sum.inr (by rewrite [-one_mul, -(inv_mul_cancel this), mul.assoc, H, mul_zero])) definition discrete_field.to_integral_domain [trans_instance] [reducible] : integral_domain A := ⦃ integral_domain, s, eq_zero_sum_eq_zero_of_mul_eq_zero := discrete_field.eq_zero_sum_eq_zero_of_mul_eq_zero⦄ theorem inv_zero : 0⁻¹ = (0:A) := !discrete_field.inv_zero theorem one_div_zero : 1 / 0 = (0:A) := calc 1 / 0 = 1 * 0⁻¹ : refl ... = 1 * 0 : inv_zero ... = 0 : mul_zero theorem div_zero (a : A) : a / 0 = 0 := by rewrite [div_eq_mul_one_div, one_div_zero, mul_zero] theorem ne_zero_of_one_div_ne_zero (H : 1 / a ≠ 0) : a ≠ 0 := assume Ha : a = 0, absurd (Ha⁻¹ ▸ one_div_zero) H theorem eq_zero_of_one_div_eq_zero (H : 1 / a = 0) : a = 0 := decidable.by_cases (assume Ha, Ha) (assume Ha, empty.elim ((one_div_ne_zero Ha) H)) variables (a b) theorem one_div_mul_one_div' : (1 / a) * (1 / b) = 1 / (b * a) := decidable.by_cases (suppose a = 0, by rewrite [this, div_zero, zero_mul, -(@div_zero A s 1), mul_zero b]) (assume Ha : a ≠ 0, decidable.by_cases (suppose b = 0, by rewrite [this, div_zero, mul_zero, -(@div_zero A s 1), zero_mul a]) (suppose b ≠ 0, division_ring.one_div_mul_one_div Ha this)) theorem one_div_neg_eq_neg_one_div : 1 / (- a) = - (1 / a) := decidable.by_cases (suppose a = 0, by rewrite [this, neg_zero, 2 div_zero, neg_zero]) (suppose a ≠ 0, division_ring.one_div_neg_eq_neg_one_div this) theorem neg_div_neg_eq : (-a) / (-b) = a / b := decidable.by_cases (assume Hb : b = 0, by rewrite [Hb, neg_zero, 2 div_zero]) (assume Hb : b ≠ 0, !division_ring.neg_div_neg_eq Hb) theorem one_div_one_div : 1 / (1 / a) = a := decidable.by_cases (assume Ha : a = 0, by rewrite [Ha, 2 div_zero]) (assume Ha : a ≠ 0, division_ring.one_div_one_div Ha) variables {a b} theorem eq_of_one_div_eq_one_div (H : 1 / a = 1 / b) : a = b := decidable.by_cases (assume Ha : a = 0, have Hb : b = 0, from eq_zero_of_one_div_eq_zero (by rewrite [-H, Ha, div_zero]), Hb⁻¹ ▸ Ha) (assume Ha : a ≠ 0, have Hb : b ≠ 0, from ne_zero_of_one_div_ne_zero (H ▸ (one_div_ne_zero Ha)), division_ring.eq_of_one_div_eq_one_div Ha Hb H) variables (a b) theorem mul_inv' : (b * a)⁻¹ = a⁻¹ * b⁻¹ := decidable.by_cases (assume Ha : a = 0, by rewrite [Ha, mul_zero, 2 inv_zero, zero_mul]) (assume Ha : a ≠ 0, decidable.by_cases (assume Hb : b = 0, by rewrite [Hb, zero_mul, 2 inv_zero, mul_zero]) (assume Hb : b ≠ 0, mul_inv_eq Ha Hb)) -- the following are specifically for fields theorem one_div_mul_one_div : (1 / a) * (1 / b) = 1 / (a * b) := by rewrite [one_div_mul_one_div', mul.comm b] variable {a} theorem div_mul_right (Ha : a ≠ 0) : a / (a * b) = 1 / b := decidable.by_cases (assume Hb : b = 0, by rewrite [Hb, mul_zero, 2 div_zero]) (assume Hb : b ≠ 0, field.div_mul_right Hb (mul_ne_zero Ha Hb)) variables (a) {b} theorem div_mul_left (Hb : b ≠ 0) : b / (a * b) = 1 / a := by rewrite [mul.comm a, div_mul_right _ Hb] variables (a b c) theorem div_mul_div : (a / b) * (c / d) = (a * c) / (b * d) := decidable.by_cases (assume Hb : b = 0, by rewrite [Hb, div_zero, zero_mul, -(@div_zero A s (a * c)), zero_mul]) (assume Hb : b ≠ 0, decidable.by_cases (assume Hd : d = 0, by rewrite [Hd, div_zero, mul_zero, -(@div_zero A s (a * c)), mul_zero]) (assume Hd : d ≠ 0, !field.div_mul_div Hb Hd)) variable {c} theorem mul_div_mul_left' (Hc : c ≠ 0) : (c * a) / (c * b) = a / b := decidable.by_cases (assume Hb : b = 0, by rewrite [Hb, mul_zero, 2 div_zero]) (assume Hb : b ≠ 0, !mul_div_mul_left Hb Hc) theorem mul_div_mul_right' (Hc : c ≠ 0) : (a * c) / (b * c) = a / b := by rewrite [(mul.comm a), (mul.comm b), (!mul_div_mul_left' Hc)] variables (a b c d) theorem div_mul_eq_mul_div_comm : (b / c) * a = b * (a / c) := decidable.by_cases (assume Hc : c = 0, by rewrite [Hc, div_zero, zero_mul, -(mul_zero b), -(@div_zero A s a)]) (assume Hc : c ≠ 0, !field.div_mul_eq_mul_div_comm Hc) theorem one_div_div : 1 / (a / b) = b / a := decidable.by_cases (assume Ha : a = 0, by rewrite [Ha, zero_div, 2 div_zero]) (assume Ha : a ≠ 0, decidable.by_cases (assume Hb : b = 0, by rewrite [Hb, 2 div_zero, zero_div]) (assume Hb : b ≠ 0, field.one_div_div Ha Hb)) theorem div_div_eq_mul_div : a / (b / c) = (a * c) / b := by rewrite [div_eq_mul_one_div, one_div_div, -mul_div_assoc] theorem div_div_eq_div_mul : (a / b) / c = a / (b * c) := by rewrite [div_eq_mul_one_div, div_mul_div, mul_one] theorem div_div_div_div_eq : (a / b) / (c / d) = (a * d) / (b * c) := by rewrite [div_div_eq_mul_div, div_mul_eq_mul_div, div_div_eq_div_mul] variable {a} theorem div_helper (H : a ≠ 0) : (1 / (a * b)) * a = 1 / b := by rewrite [div_mul_eq_mul_div, one_mul, !div_mul_right H] variable (a) theorem div_mul_eq_div_mul_one_div : a / (b * c) = (a / b) * (1 / c) := by rewrite [-div_div_eq_div_mul, -div_eq_mul_one_div] end discrete_field namespace norm_num theorem div_add_helper [s : field A] (n d b c val : A) (Hd : d ≠ 0) (H : n + b * d = val) (H2 : c * d = val) : n / d + b = c := begin apply eq_of_mul_eq_mul_of_nonzero_right Hd, rewrite [H2, -H, right_distrib, div_mul_cancel _ Hd] end theorem add_div_helper [s : field A] (n d b c val : A) (Hd : d ≠ 0) (H : d * b + n = val) (H2 : d * c = val) : b + n / d = c := begin apply eq_of_mul_eq_mul_of_nonzero_left Hd, rewrite [H2, -H, left_distrib, mul_div_cancel' Hd] end theorem div_mul_helper [s : field A] (n d c v : A) (Hd : d ≠ 0) (H : (n * c) / d = v) : (n / d) * c = v := by rewrite [-H, field.div_mul_eq_mul_div_comm _ _ Hd, mul_div_assoc] theorem mul_div_helper [s : field A] (a n d v : A) (Hd : d ≠ 0) (H : (a * n) / d = v) : a * (n / d) = v := by rewrite [-H, mul_div_assoc] theorem nonzero_of_div_helper [s : field A] (a b : A) (Ha : a ≠ 0) (Hb : b ≠ 0) : a / b ≠ 0 := begin intro Hab, have Habb : (a / b) * b = 0, by rewrite [Hab, zero_mul], rewrite [div_mul_cancel _ Hb at Habb], exact Ha Habb end theorem div_helper [s : field A] (n d v : A) (Hd : d ≠ 0) (H : v * d = n) : n / d = v := begin apply eq_of_mul_eq_mul_of_nonzero_right Hd, rewrite (div_mul_cancel _ Hd), exact inverse H end theorem div_eq_div_helper [s : field A] (a b c d v : A) (H1 : a * d = v) (H2 : c * b = v) (Hb : b ≠ 0) (Hd : d ≠ 0) : a / b = c / d := begin apply eq_div_of_mul_eq, exact Hd, rewrite div_mul_eq_mul_div, apply inverse, apply eq_div_of_mul_eq, exact Hb, rewrite [H1, H2] end theorem subst_into_div [s : has_div A] (a₁ b₁ a₂ b₂ v : A) (H : a₁ / b₁ = v) (H1 : a₂ = a₁) (H2 : b₂ = b₁) : a₂ / b₂ = v := by rewrite [H1, H2, H] end norm_num end algebra
ca5875526971be9f20d4b8a4e6b6644595863853
57c233acf9386e610d99ed20ef139c5f97504ba3
/test/lint.lean
8da9779438cabeda383c9e7323bb17ff5199acd8
[ "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,542
lean
import tactic.lint import algebra.ring.basic open tactic def foo1 (n m : ℕ) : ℕ := n + 1 def foo2 (n m : ℕ) : m = m := by refl lemma foo3 (n m : ℕ) : ℕ := n - m lemma foo.foo (n m : ℕ) : n ≥ n := le_refl n instance bar.bar : has_add ℕ := by apply_instance -- we don't check the name of instances lemma foo.bar (ε > 0) : ε = ε := rfl -- >/≥ is allowed in binders (and in fact, in all hypotheses) /-- Test exception in `def_lemma` linter. -/ @[pattern] def my_exists_intro := @Exists.intro meta def fold_over_with_cond {α} (l : list declaration) (tac : declaration → tactic (option α)) : tactic (list (declaration × α)) := l.mmap_filter $ λ d, option.map (λ x, (d, x)) <$> tac d run_cmd do let t := name × list ℕ, e ← get_env, let l := e.filter (λ d, e.in_current_file d.to_name ∧ ¬ d.is_auto_or_internal e), l2 ← fold_over_with_cond l (return ∘ check_unused_arguments), guard (l2.length = 4) <|> fail "wrong length", let l2 : list (name × list ℕ) := l2.map (λ x, ⟨x.1.to_name, x.2⟩), guard ((⟨`foo1, [2]⟩ : t) ∈ l2) <|> fail "foo1", guard ((⟨`foo2, [1]⟩ : t) ∈ l2) <|> fail "foo2", guard ((⟨`foo.foo, [2]⟩ : t) ∈ l2) <|> fail "foofoo", guard ((⟨`foo.bar, [2]⟩ : t) ∈ l2) <|> fail "foobar", l2 ← fold_over_with_cond l linter.def_lemma.test, guard $ l2.length = 2, let l2 : list (name × _) := l2.map $ λ x, ⟨x.1.to_name, x.2⟩, guard $ ∃(x ∈ l2), (x : name × _).1 = `foo2, guard $ ∃(x ∈ l2), (x : name × _).1 = `foo3, l3 ← fold_over_with_cond l linter.dup_namespace.test, guard $ l3.length = 1, guard $ ∃(x ∈ l3), (x : declaration × _).1.to_name = `foo.foo, l4 ← fold_over_with_cond l linter.ge_or_gt.test, guard $ l4.length = 1, guard $ ∃(x ∈ l4), (x : declaration × _).1.to_name = `foo.foo, -- guard $ ∃(x ∈ l4), (x : declaration × _).1.to_name = `foo4, (_, s) ← lint ff, guard $ "/- (slow tests skipped) -/\n".is_suffix_of s.to_string, (_, s2) ← lint tt, guard $ s.to_string ≠ s2.to_string, skip /- check customizability and nolint -/ meta def dummy_check (d : declaration) : tactic (option string) := return $ if d.to_name.last = "foo" then some "gotcha!" else none meta def linter.dummy_linter : linter := { test := dummy_check, auto_decls := ff, no_errors_found := "found nothing.", errors_found := "found something:" } @[nolint dummy_linter] def bar.foo : (if 3 = 3 then 1 else 2) = 1 := if_pos (by refl) run_cmd do (_, s) ← lint tt lint_verbosity.medium [`linter.dummy_linter] tt, guard $ "/- found something: -/\n#check @foo.foo /- gotcha! -/\n".is_suffix_of s.to_string def incorrect_type_class_argument_test {α : Type} (x : α) [x = x] [decidable_eq α] [group α] : unit := () run_cmd do d ← get_decl `incorrect_type_class_argument_test, x ← linter.incorrect_type_class_argument.test d, guard $ x = some "These are not classes. argument 3: [_inst_1 : x = x]" section def impossible_instance_test {α β : Type} [add_group α] : has_add α := infer_instance local attribute [instance] impossible_instance_test run_cmd do d ← get_decl `impossible_instance_test, x ← linter.impossible_instance.test d, guard $ x = some "Impossible to infer argument 2: {β : Type}" def dangerous_instance_test {α β γ : Type} [ring α] [add_comm_group β] [has_coe α β] [has_inv γ] : has_add β := infer_instance local attribute [instance] dangerous_instance_test run_cmd do d ← get_decl `dangerous_instance_test, x ← linter.dangerous_instance.test d, guard $ x = some "The following arguments become metavariables. argument 1: {α : Type}, argument 3: {γ : Type}" end section def foo_has_mul {α} [has_mul α] : has_mul α := infer_instance local attribute [instance, priority 1] foo_has_mul run_cmd do d ← get_decl `foo_has_mul, some s ← fails_quickly 20 d, guard $ "type-class inference timed out".is_prefix_of s local attribute [instance, priority 10000] foo_has_mul run_cmd do d ← get_decl `foo_has_mul, some s ← fails_quickly 3000 d, guard $ "maximum class-instance resolution depth has been reached".is_prefix_of s end instance beta_redex_test {α} [monoid α] : (λ (X : Type), has_mul X) α := ⟨(*)⟩ run_cmd do d ← get_decl `beta_redex_test, x ← linter.instance_priority.test d, guard $ x = some "set priority below 1000" /- Test exception in `def_lemma` linter. -/ run_cmd do d ← get_decl `my_exists_intro, t ← linter.def_lemma.test d, guard $ t = none
b4ac97a1216092c7708674ce61062019aa24de69
fcf3ffa92a3847189ca669cb18b34ef6b2ec2859
/src/world3/level9.lean
f24b72030931d22a871f3185c97350ff7cabc683
[ "Apache-2.0" ]
permissive
nomoid/lean-proofs
4a80a97888699dee42b092b7b959b22d9aa0c066
b9f03a24623d1a1d111d6c2bbf53c617e2596d6a
refs/heads/master
1,674,955,317,080
1,607,475,706,000
1,607,475,706,000
314,104,281
0
0
null
null
null
null
UTF-8
Lean
false
false
421
lean
import mynat.definition import mynat.mul import world3.level5 import world3.level8 namespace mynat lemma mul_left_comm (a b c : mynat) : a * (b * c) = b * (a * c) := begin [nat_num_game] induction b with d hd, { rw mul_comm 0, rw mul_comm 0, repeat {rw mul_zero}, }, { rw ← mul_assoc, rw ← mul_assoc, rw mul_comm a, refl, }, end end mynat
58a4eb4af6b3c0857e03706843de5c48bd12e72c
26bff4ed296b8373c92b6b025f5d60cdf02104b9
/hott/types/trunc.hlean
a7c0e05c8aefb270e8afc7a2a056ad6699ef37fe
[ "Apache-2.0" ]
permissive
guiquanz/lean
b8a878ea24f237b84b0e6f6be2f300e8bf028229
242f8ba0486860e53e257c443e965a82ee342db3
refs/heads/master
1,526,680,092,098
1,427,492,833,000
1,427,493,281,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,384
hlean
/- Copyright (c) 2015 Jakob von Raumer. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Module: types.trunc Authors: Jakob von Raumer, Floris van Doorn Properties of is_trunc -/ import types.pi types.eq open sigma sigma.ops pi function eq equiv eq funext namespace is_trunc definition is_contr.sigma_char (A : Type) : (Σ (center : A), Π (a : A), center = a) ≃ (is_contr A) := begin fapply equiv.mk, {intro S, apply is_contr.mk, exact S.2}, {fapply is_equiv.adjointify, {intro H, apply sigma.mk, exact (@contr A H)}, {intro H, apply (is_trunc.rec_on H), intro Hint, apply (contr_internal.rec_on Hint), intros (H1, H2), apply idp}, {intro S, cases S, apply idp}} end definition is_trunc.pi_char (n : trunc_index) (A : Type) : (Π (x y : A), is_trunc n (x = y)) ≃ (is_trunc (n .+1) A) := begin fapply equiv.MK, {intro H, apply is_trunc_succ_intro}, {intros (H, x, y), apply is_trunc_eq}, {intro H, apply (is_trunc.rec_on H), intro Hint, apply idp}, {intro P, apply eq_of_homotopy, intro a, apply eq_of_homotopy, intro b, esimp {function.id,compose,is_trunc_succ_intro,is_trunc_eq}, generalize (P a b), intro H, apply (is_trunc.rec_on H), intro H', apply idp}, end definition is_hprop_is_trunc [instance] (n : trunc_index) : Π (A : Type), is_hprop (is_trunc n A) := begin apply (trunc_index.rec_on n), {intro A, apply is_trunc_is_equiv_closed, apply equiv.to_is_equiv, apply is_contr.sigma_char, apply (@is_hprop.mk), intros, fapply sigma_eq, apply x.2, apply (@is_hprop.elim), apply is_trunc_pi, intro a, apply is_hprop.mk, intros (w, z), have H : is_hset A, begin apply is_trunc_succ, apply is_trunc_succ, apply is_contr.mk, exact y.2 end, fapply (@is_hset.elim A _ _ _ w z)}, {intros (n', IH, A), apply is_trunc_is_equiv_closed, apply equiv.to_is_equiv, apply is_trunc.pi_char}, end definition is_trunc_succ_of_imp_is_trunc_succ {A : Type} {n : trunc_index} (H : A → is_trunc (n.+1) A) : is_trunc (n.+1) A := @is_trunc_succ_intro _ _ (λx y, @is_trunc_eq _ _ (H x) x y) definition is_trunc_of_imp_is_trunc_of_leq {A : Type} {n : trunc_index} (Hn : -1 ≤ n) (H : A → is_trunc n A) : is_trunc n A := trunc_index.rec_on n (λHn H, empty.rec _ Hn) (λn IH Hn, is_trunc_succ_of_imp_is_trunc_succ) Hn H definition is_hset_of_axiom_K {A : Type} (K : Π{a : A} (p : a = a), p = idp) : is_hset A := is_hset.mk _ (λa b p q, eq.rec_on q K p) theorem is_hset_of_relation.{u} {A : Type.{u}} (R : A → A → Type.{u}) (mere : Π(a b : A), is_hprop (R a b)) (refl : Π(a : A), R a a) (imp : Π{a b : A}, R a b → a = b) : is_hset A := is_hset_of_axiom_K (λa p, have H2 : transport (λx, R a x → a = x) p (@imp a a) = @imp a a, from !apD, have H3 : Π(r : R a a), transport (λx, a = x) p (imp r) = imp (transport (λx, R a x) p r), from to_fun (equiv.symm !heq_pi) H2, have H4 : imp (refl a) ⬝ p = imp (refl a), from calc imp (refl a) ⬝ p = transport (λx, a = x) p (imp (refl a)) : transport_eq_r ... = imp (transport (λx, R a x) p (refl a)) : H3 ... = imp (refl a) : is_hprop.elim, cancel_left (imp (refl a)) _ _ H4) definition relation_equiv_eq {A : Type} (R : A → A → Type) (mere : Π(a b : A), is_hprop (R a b)) (refl : Π(a : A), R a a) (imp : Π{a b : A}, R a b → a = b) (a b : A) : R a b ≃ a = b := @equiv_of_is_hprop _ _ _ (@is_trunc_eq _ _ (is_hset_of_relation R mere refl @imp) a b) imp (λp, p ▹ refl a) local attribute not [reducible] definition is_hset_of_double_neg_elim {A : Type} (H : Π(a b : A), ¬¬a = b → a = b) : is_hset A := is_hset_of_relation (λa b, ¬¬a = b) _ (λa n, n idp) H section open decidable --this is proven differently in init.hedberg definition is_hset_of_decidable_eq (A : Type) [H : decidable_eq A] : is_hset A := is_hset_of_double_neg_elim (λa b, by_contradiction) end definition is_trunc_of_axiom_K_of_leq {A : Type} (n : trunc_index) (H : -1 ≤ n) (K : Π(a : A), is_trunc n (a = a)) : is_trunc (n.+1) A := @is_trunc_succ_intro _ _ (λa b, is_trunc_of_imp_is_trunc_of_leq H (λp, eq.rec_on p !K)) open trunctype equiv equiv.ops protected definition trunctype.sigma_char.{l} (n : trunc_index) : (trunctype.{l} n) ≃ (Σ (A : Type.{l}), is_trunc n A) := begin fapply equiv.MK, /--/ intro A, exact (⟨carrier A, struct A⟩), /--/ intro S, exact (trunctype.mk S.1 S.2), /--/ intro S, apply (sigma.rec_on S), intros (S1, S2), apply idp, intro A, apply (trunctype.rec_on A), intros (A1, A2), apply idp, end -- set_option pp.notation false protected definition trunctype.eq (n : trunc_index) (A B : n-Type) : (A = B) ≃ (carrier A = carrier B) := calc (A = B) ≃ (trunctype.sigma_char n A = trunctype.sigma_char n B) : eq_equiv_fn_eq_of_equiv ... ≃ ((trunctype.sigma_char n A).1 = (trunctype.sigma_char n B).1) : equiv.symm (!equiv_subtype) ... ≃ (carrier A = carrier B) : equiv.refl end is_trunc
32f5a56fde0597ba9d8c4cd762d576d756eedaa7
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/set/sigma.lean
76edf176d89defd02be087d45f4466a0ce615334
[ "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,112
lean
/- Copyright (c) 2022 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import data.set.image /-! # Sets in sigma types > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines `set.sigma`, the indexed sum of sets. -/ namespace set variables {ι ι' : Type*} {α β : ι → Type*} {s s₁ s₂ : set ι} {t t₁ t₂ : Π i, set (α i)} {u : set (Σ i, α i)} {x : Σ i, α i} {i j : ι} {a : α i} @[simp] theorem range_sigma_mk (i : ι) : range (sigma.mk i : α i → sigma α) = sigma.fst ⁻¹' {i} := begin apply subset.antisymm, { rintros _ ⟨b, rfl⟩, simp }, { rintros ⟨x, y⟩ (rfl|_), exact mem_range_self y } end theorem preimage_image_sigma_mk_of_ne (h : i ≠ j) (s : set (α j)) : sigma.mk i ⁻¹' (sigma.mk j '' s) = ∅ := by { ext x, simp [h.symm] } lemma image_sigma_mk_preimage_sigma_map_subset {β : ι' → Type*} (f : ι → ι') (g : Π i, α i → β (f i)) (i : ι) (s : set (β (f i))) : sigma.mk i '' (g i ⁻¹' s) ⊆ sigma.map f g ⁻¹' (sigma.mk (f i) '' s) := image_subset_iff.2 $ λ x hx, ⟨g i x, hx, rfl⟩ lemma image_sigma_mk_preimage_sigma_map {β : ι' → Type*} {f : ι → ι'} (hf : function.injective f) (g : Π i, α i → β (f i)) (i : ι) (s : set (β (f i))) : sigma.mk i '' (g i ⁻¹' s) = sigma.map f g ⁻¹' (sigma.mk (f i) '' s) := begin refine (image_sigma_mk_preimage_sigma_map_subset f g i s).antisymm _, rintro ⟨j, x⟩ ⟨y, hys, hxy⟩, simp only [hf.eq_iff, sigma.map] at hxy, rcases hxy with ⟨rfl, hxy⟩, rw [heq_iff_eq] at hxy, subst y, exact ⟨x, hys, rfl⟩ end /-- Indexed sum of sets. `s.sigma t` is the set of dependent pairs `⟨i, a⟩` such that `i ∈ s` and `a ∈ t i`.-/ protected def sigma (s : set ι) (t : Π i, set (α i)) : set (Σ i, α i) := {x | x.1 ∈ s ∧ x.2 ∈ t x.1} @[simp] lemma mem_sigma_iff : x ∈ s.sigma t ↔ x.1 ∈ s ∧ x.2 ∈ t x.1 := iff.rfl @[simp] lemma mk_sigma_iff : (⟨i, a⟩ : Σ i, α i) ∈ s.sigma t ↔ i ∈ s ∧ a ∈ t i := iff.rfl lemma mk_mem_sigma (hi : i ∈ s) (ha : a ∈ t i) : (⟨i, a⟩ : Σ i, α i) ∈ s.sigma t := ⟨hi, ha⟩ lemma sigma_mono (hs : s₁ ⊆ s₂) (ht : ∀ i, t₁ i ⊆ t₂ i) : s₁.sigma t₁ ⊆ s₂.sigma t₂ := λ x hx, ⟨hs hx.1, ht _ hx.2⟩ lemma sigma_subset_iff : s.sigma t ⊆ u ↔ ∀ ⦃i⦄, i ∈ s → ∀ ⦃a⦄, a ∈ t i → (⟨i, a⟩ : Σ i, α i) ∈ u := ⟨λ h i hi a ha, h $ mk_mem_sigma hi ha, λ h ⟨i, a⟩ ha, h ha.1 ha.2⟩ lemma forall_sigma_iff {p : (Σ i, α i) → Prop} : (∀ x ∈ s.sigma t, p x) ↔ ∀ ⦃i⦄, i ∈ s → ∀ ⦃a⦄, a ∈ t i → p ⟨i, a⟩ := sigma_subset_iff lemma exists_sigma_iff {p : (Σ i, α i) → Prop} : (∃ x ∈ s.sigma t, p x) ↔ ∃ (i ∈ s) (a ∈ t i), p ⟨i, a⟩ := ⟨λ ⟨⟨i, a⟩, ha, h⟩, ⟨i, ha.1, a, ha.2, h⟩, λ ⟨i, hi, a, ha, h⟩, ⟨⟨i, a⟩, ⟨hi, ha⟩, h⟩⟩ @[simp] lemma sigma_empty : s.sigma (λ i, (∅ : set (α i))) = ∅ := ext $ λ _, and_false _ @[simp] lemma empty_sigma : (∅ : set ι).sigma t = ∅ := ext $ λ _, false_and _ lemma univ_sigma_univ : (@univ ι).sigma (λ _, @univ (α i)) = univ := ext $ λ _, true_and _ @[simp] lemma sigma_univ : s.sigma (λ _, univ : Π i, set (α i)) = sigma.fst ⁻¹' s := ext $ λ _, and_true _ @[simp] lemma singleton_sigma : ({i} : set ι).sigma t = sigma.mk i '' t i := ext $ λ x, begin split, { obtain ⟨j, a⟩ := x, rintro ⟨(rfl : j = i), ha⟩, exact mem_image_of_mem _ ha }, { rintro ⟨b, hb, rfl⟩, exact ⟨rfl, hb⟩ } end @[simp] lemma sigma_singleton {a : Π i, α i} : s.sigma (λ i, ({a i} : set (α i))) = (λ i, sigma.mk i $ a i) '' s := by { ext ⟨x, y⟩, simp [and.left_comm, eq_comm] } lemma singleton_sigma_singleton {a : Π i, α i} : ({i} : set ι).sigma (λ i, ({a i} : set (α i))) = {⟨i, a i⟩} := by rw [sigma_singleton, image_singleton] @[simp] lemma union_sigma : (s₁ ∪ s₂).sigma t = s₁.sigma t ∪ s₂.sigma t := ext $ λ _, or_and_distrib_right @[simp] lemma sigma_union : s.sigma (λ i, t₁ i ∪ t₂ i) = s.sigma t₁ ∪ s.sigma t₂ := ext $ λ _, and_or_distrib_left lemma sigma_inter_sigma : s₁.sigma t₁ ∩ s₂.sigma t₂ = (s₁ ∩ s₂).sigma (λ i, t₁ i ∩ t₂ i) := by { ext ⟨x, y⟩, simp [and_assoc, and.left_comm] } lemma insert_sigma : (insert i s).sigma t = (sigma.mk i '' t i) ∪ s.sigma t := by rw [insert_eq, union_sigma, singleton_sigma] lemma sigma_insert {a : Π i, α i} : s.sigma (λ i, insert (a i) (t i)) = ((λ i, ⟨i, a i⟩) '' s) ∪ s.sigma t := by simp_rw [insert_eq, sigma_union, sigma_singleton] lemma sigma_preimage_eq {f : ι' → ι} {g : Π i, β i → α i} : (f ⁻¹' s).sigma (λ i, g (f i) ⁻¹' t (f i)) = (λ p : Σ i, β (f i), sigma.mk _ (g _ p.2)) ⁻¹' (s.sigma t) := rfl lemma sigma_preimage_left {f : ι' → ι} : (f ⁻¹' s).sigma (λ i, t (f i)) = (λ p : Σ i, α (f i), sigma.mk _ p.2) ⁻¹' (s.sigma t) := rfl lemma sigma_preimage_right {g : Π i, β i → α i} : s.sigma (λ i, g i ⁻¹' t i) = (λ p : Σ i, β i, sigma.mk p.1 (g _ p.2)) ⁻¹' (s.sigma t) := rfl lemma preimage_sigma_map_sigma {α' : ι' → Type*} (f : ι → ι') (g : Π i, α i → α' (f i)) (s : set ι') (t : Π i, set (α' i)) : sigma.map f g ⁻¹' (s.sigma t) = (f ⁻¹' s).sigma (λ i, g i ⁻¹' t (f i)) := rfl @[simp] lemma mk_preimage_sigma (hi : i ∈ s) : sigma.mk i ⁻¹' s.sigma t = t i := ext $ λ _, and_iff_right hi @[simp] lemma mk_preimage_sigma_eq_empty (hi : i ∉ s) : sigma.mk i ⁻¹' s.sigma t = ∅ := ext $ λ _, iff_of_false (hi ∘ and.left) id lemma mk_preimage_sigma_eq_if [decidable_pred (∈ s)] : sigma.mk i ⁻¹' s.sigma t = if i ∈ s then t i else ∅ := by split_ifs; simp [h] lemma mk_preimage_sigma_fn_eq_if {β : Type*} [decidable_pred (∈ s)] (g : β → α i) : (λ b, sigma.mk i (g b)) ⁻¹' s.sigma t = if i ∈ s then g ⁻¹' t i else ∅ := ext $ λ _, by split_ifs; simp [h] lemma sigma_univ_range_eq {f : Π i, α i → β i} : (univ : set ι).sigma (λ i, range (f i)) = range (λ x : Σ i, α i, ⟨x.1, f _ x.2⟩) := ext $ by simp [range] protected lemma nonempty.sigma : s.nonempty → (∀ i, (t i).nonempty) → (s.sigma t : set _).nonempty := λ ⟨i, hi⟩ h, let ⟨a, ha⟩ := h i in ⟨⟨i, a⟩, hi, ha⟩ lemma nonempty.sigma_fst : (s.sigma t : set _).nonempty → s.nonempty := λ ⟨x, hx⟩, ⟨x.1, hx.1⟩ lemma nonempty.sigma_snd : (s.sigma t : set _).nonempty → ∃ i ∈ s, (t i).nonempty := λ ⟨x, hx⟩, ⟨x.1, hx.1, x.2, hx.2⟩ lemma sigma_nonempty_iff : (s.sigma t : set _).nonempty ↔ ∃ i ∈ s, (t i).nonempty := ⟨nonempty.sigma_snd, λ ⟨i, hi, a, ha⟩, ⟨⟨i, a⟩, hi, ha⟩⟩ lemma sigma_eq_empty_iff : s.sigma t = ∅ ↔ ∀ i ∈ s, t i = ∅ := not_nonempty_iff_eq_empty.symm.trans $ sigma_nonempty_iff.not.trans $ by simp only [not_nonempty_iff_eq_empty, not_exists] lemma image_sigma_mk_subset_sigma_left {a : Π i, α i} (ha : ∀ i, a i ∈ t i) : (λ i, sigma.mk i (a i)) '' s ⊆ s.sigma t := image_subset_iff.2 $ λ i hi, ⟨hi, ha _⟩ lemma image_sigma_mk_subset_sigma_right (hi : i ∈ s) : sigma.mk i '' t i ⊆ s.sigma t := image_subset_iff.2 $ λ a, and.intro hi lemma sigma_subset_preimage_fst (s : set ι) (t : Π i, set (α i)) : s.sigma t ⊆ sigma.fst ⁻¹' s := λ a, and.left lemma fst_image_sigma_subset (s : set ι) (t : Π i, set (α i)) : sigma.fst '' s.sigma t ⊆ s := image_subset_iff.2 $ λ a, and.left lemma fst_image_sigma (s : set ι) (ht : ∀ i, (t i).nonempty) : sigma.fst '' s.sigma t = s := (fst_image_sigma_subset _ _).antisymm $ λ i hi, let ⟨a, ha⟩ := ht i in ⟨⟨i, a⟩, ⟨hi, ha⟩, rfl⟩ lemma sigma_diff_sigma : s₁.sigma t₁ \ s₂.sigma t₂ = s₁.sigma (t₁ \ t₂) ∪ (s₁ \ s₂).sigma t₁ := ext $ λ x, by by_cases h₁ : x.1 ∈ s₁; by_cases h₂ : x.2 ∈ t₁ x.1; simp [*, ←imp_iff_or_not] end set
df17c4f2bda6f4aa76378274aa309805a26b9a35
649957717d58c43b5d8d200da34bf374293fe739
/src/algebra/group/conj.lean
969ccdd8b804c00ae2c09b82ae202db25a907008
[ "Apache-2.0" ]
permissive
Vtec234/mathlib
b50c7b21edea438df7497e5ed6a45f61527f0370
fb1848bbbfce46152f58e219dc0712f3289d2b20
refs/heads/master
1,592,463,095,113
1,562,737,749,000
1,562,737,749,000
196,202,858
0
0
Apache-2.0
1,562,762,338,000
1,562,762,337,000
null
UTF-8
Lean
false
false
1,975
lean
/- Copyright (c) 2018 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Chris Hughes, Michael Howes Conjugacy of group elements -/ import tactic.basic algebra.group.hom universes u v variables {α : Type u} {β : Type v} variables [group α] [group β] def is_conj (a b : α) := ∃ c : α, c * a * c⁻¹ = b @[refl] lemma is_conj_refl (a : α) : is_conj a a := ⟨1, by rw [one_mul, one_inv, mul_one]⟩ @[symm] lemma is_conj_symm {a b : α} : is_conj a b → is_conj b a | ⟨c, hc⟩ := ⟨c⁻¹, by rw [← hc, mul_assoc, mul_inv_cancel_right, inv_mul_cancel_left]⟩ @[trans] lemma is_conj_trans {a b c : α} : is_conj a b → is_conj b c → is_conj a c | ⟨c₁, hc₁⟩ ⟨c₂, hc₂⟩ := ⟨c₂ * c₁, by rw [← hc₂, ← hc₁, mul_inv_rev]; simp only [mul_assoc]⟩ @[simp] lemma is_conj_one_right {a : α} : is_conj 1 a ↔ a = 1 := ⟨by simp [is_conj, is_conj_refl] {contextual := tt}, by simp [is_conj_refl] {contextual := tt}⟩ @[simp] lemma is_conj_one_left {a : α} : is_conj a 1 ↔ a = 1 := calc is_conj a 1 ↔ is_conj 1 a : ⟨is_conj_symm, is_conj_symm⟩ ... ↔ a = 1 : is_conj_one_right @[simp] lemma conj_inv {a b : α} : (b * a * b⁻¹)⁻¹ = b * a⁻¹ * b⁻¹ := begin rw [mul_inv_rev _ b⁻¹, mul_inv_rev b _, inv_inv, mul_assoc], end @[simp] lemma conj_mul {a b c : α} : (b * a * b⁻¹) * (b * c * b⁻¹) = b * (a * c) * b⁻¹ := begin assoc_rw inv_mul_cancel_right, repeat {rw mul_assoc}, end @[simp] lemma is_conj_iff_eq {α : Type*} [comm_group α] {a b : α} : is_conj a b ↔ a = b := ⟨λ ⟨c, hc⟩, by rw [← hc, mul_right_comm, mul_inv_self, one_mul], λ h, by rw h⟩ protected lemma is_group_hom.is_conj (f : α → β) [is_group_hom f] {a b : α} : is_conj a b → is_conj (f a) (f b) | ⟨c, hc⟩ := ⟨f c, by rw [← is_group_hom.map_mul f, ← is_group_hom.map_inv f, ← is_group_hom.map_mul f, hc]⟩
de38ffa1b47fe9985a48cbccc0313ef13ee6d360
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/data/seq/computation.lean
d158335fbe52e495ae9d606484126990b0333bb8
[ "Apache-2.0" ]
permissive
hikari0108/mathlib
b7ea2b7350497ab1a0b87a09d093ecc025a50dfa
a9e7d333b0cfd45f13a20f7b96b7d52e19fa2901
refs/heads/master
1,690,483,608,260
1,631,541,580,000
1,631,541,580,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
37,941
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro Coinductive formalization of unbounded computations. -/ import data.stream import tactic.basic open function universes u v w /- coinductive computation (α : Type u) : Type u | return : α → computation α | think : computation α → computation α -/ /-- `computation α` is the type of unbounded computations returning `α`. An element of `computation α` is an infinite sequence of `option α` such that if `f n = some a` for some `n` then it is constantly `some a` after that. -/ def computation (α : Type u) : Type u := { f : stream (option α) // ∀ {n a}, f n = some a → f (n+1) = some a } namespace computation variables {α : Type u} {β : Type v} {γ : Type w} -- constructors /-- `return a` is the computation that immediately terminates with result `a`. -/ def return (a : α) : computation α := ⟨stream.const (some a), λn a', id⟩ instance : has_coe_t α (computation α) := ⟨return⟩ -- note [use has_coe_t] /-- `think c` is the computation that delays for one "tick" and then performs computation `c`. -/ def think (c : computation α) : computation α := ⟨none :: c.1, λn a h, by {cases n with n, contradiction, exact c.2 h}⟩ /-- `thinkN c n` is the computation that delays for `n` ticks and then performs computation `c`. -/ def thinkN (c : computation α) : ℕ → computation α | 0 := c | (n+1) := think (thinkN n) -- check for immediate result /-- `head c` is the first step of computation, either `some a` if `c = return a` or `none` if `c = think c'`. -/ def head (c : computation α) : option α := c.1.head -- one step of computation /-- `tail c` is the remainder of computation, either `c` if `c = return a` or `c'` if `c = think c'`. -/ def tail (c : computation α) : computation α := ⟨c.1.tail, λ n a, let t := c.2 in t⟩ /-- `empty α` is the computation that never returns, an infinite sequence of `think`s. -/ def empty (α) : computation α := ⟨stream.const none, λn a', id⟩ instance : inhabited (computation α) := ⟨empty _⟩ /-- `run_for c n` evaluates `c` for `n` steps and returns the result, or `none` if it did not terminate after `n` steps. -/ def run_for : computation α → ℕ → option α := subtype.val /-- `destruct c` is the destructor for `computation α` as a coinductive type. It returns `inl a` if `c = return a` and `inr c'` if `c = think c'`. -/ def destruct (c : computation α) : α ⊕ computation α := match c.1 0 with | none := sum.inr (tail c) | some a := sum.inl a end /-- `run c` is an unsound meta function that runs `c` to completion, possibly resulting in an infinite loop in the VM. -/ meta def run : computation α → α | c := match destruct c with | sum.inl a := a | sum.inr ca := run ca end theorem destruct_eq_ret {s : computation α} {a : α} : destruct s = sum.inl a → s = return a := begin dsimp [destruct], induction f0 : s.1 0; intro h, { contradiction }, { apply subtype.eq, funext n, induction n with n IH, { injection h with h', rwa h' at f0 }, { exact s.2 IH } } end theorem destruct_eq_think {s : computation α} {s'} : destruct s = sum.inr s' → s = think s' := begin dsimp [destruct], induction f0 : s.1 0 with a'; intro h, { injection h with h', rw ←h', cases s with f al, apply subtype.eq, dsimp [think, tail], rw ←f0, exact (stream.eta f).symm }, { contradiction } end @[simp] theorem destruct_ret (a : α) : destruct (return a) = sum.inl a := rfl @[simp] theorem destruct_think : ∀ s : computation α, destruct (think s) = sum.inr s | ⟨f, al⟩ := rfl @[simp] theorem destruct_empty : destruct (empty α) = sum.inr (empty α) := rfl @[simp] theorem head_ret (a : α) : head (return a) = some a := rfl @[simp] theorem head_think (s : computation α) : head (think s) = none := rfl @[simp] theorem head_empty : head (empty α) = none := rfl @[simp] theorem tail_ret (a : α) : tail (return a) = return a := rfl @[simp] theorem tail_think (s : computation α) : tail (think s) = s := by cases s with f al; apply subtype.eq; dsimp [tail, think]; rw [stream.tail_cons] @[simp] theorem tail_empty : tail (empty α) = empty α := rfl theorem think_empty : empty α = think (empty α) := destruct_eq_think destruct_empty def cases_on {C : computation α → Sort v} (s : computation α) (h1 : ∀ a, C (return a)) (h2 : ∀ s, C (think s)) : C s := begin induction H : destruct s with v v, { rw destruct_eq_ret H, apply h1 }, { cases v with a s', rw destruct_eq_think H, apply h2 } end def corec.F (f : β → α ⊕ β) : α ⊕ β → option α × (α ⊕ β) | (sum.inl a) := (some a, sum.inl a) | (sum.inr b) := (match f b with | sum.inl a := some a | sum.inr b' := none end, f b) /-- `corec f b` is the corecursor for `computation α` as a coinductive type. If `f b = inl a` then `corec f b = return a`, and if `f b = inl b'` then `corec f b = think (corec f b')`. -/ def corec (f : β → α ⊕ β) (b : β) : computation α := begin refine ⟨stream.corec' (corec.F f) (sum.inr b), λn a' h, _⟩, rw stream.corec'_eq, change stream.corec' (corec.F f) (corec.F f (sum.inr b)).2 n = some a', revert h, generalize : sum.inr b = o, revert o, induction n with n IH; intro o, { change (corec.F f o).1 = some a' → (corec.F f (corec.F f o).2).1 = some a', cases o with a b; intro h, { exact h }, dsimp [corec.F] at h, dsimp [corec.F], cases f b with a b', { exact h }, { contradiction } }, { rw [stream.corec'_eq (corec.F f) (corec.F f o).2, stream.corec'_eq (corec.F f) o], exact IH (corec.F f o).2 } end /-- left map of `⊕` -/ def lmap (f : α → β) : α ⊕ γ → β ⊕ γ | (sum.inl a) := sum.inl (f a) | (sum.inr b) := sum.inr b /-- right map of `⊕` -/ def rmap (f : β → γ) : α ⊕ β → α ⊕ γ | (sum.inl a) := sum.inl a | (sum.inr b) := sum.inr (f b) attribute [simp] lmap rmap @[simp] lemma corec_eq (f : β → α ⊕ β) (b : β) : destruct (corec f b) = rmap (corec f) (f b) := begin dsimp [corec, destruct], change stream.corec' (corec.F f) (sum.inr b) 0 with corec.F._match_1 (f b), induction h : f b with a b', { refl }, dsimp [corec.F, destruct], apply congr_arg, apply subtype.eq, dsimp [corec, tail], rw [stream.corec'_eq, stream.tail_cons], dsimp [corec.F], rw h end section bisim variable (R : computation α → computation α → Prop) local infix ` ~ `:50 := R def bisim_o : α ⊕ computation α → α ⊕ computation α → Prop | (sum.inl a) (sum.inl a') := a = a' | (sum.inr s) (sum.inr s') := R s s' | _ _ := false attribute [simp] bisim_o def is_bisimulation := ∀ ⦃s₁ s₂⦄, s₁ ~ s₂ → bisim_o R (destruct s₁) (destruct s₂) -- If two computations are bisimilar, then they are equal theorem eq_of_bisim (bisim : is_bisimulation R) {s₁ s₂} (r : s₁ ~ s₂) : s₁ = s₂ := begin apply subtype.eq, apply stream.eq_of_bisim (λx y, ∃ s s' : computation α, s.1 = x ∧ s'.1 = y ∧ R s s'), dsimp [stream.is_bisimulation], intros t₁ t₂ e, exact match t₁, t₂, e with ._, ._, ⟨s, s', rfl, rfl, r⟩ := suffices head s = head s' ∧ R (tail s) (tail s'), from and.imp id (λr, ⟨tail s, tail s', by cases s; refl, by cases s'; refl, r⟩) this, begin have := bisim r, revert r this, apply cases_on s _ _; intros; apply cases_on s' _ _; intros; intros r this, { constructor, dsimp at this, rw this, assumption }, { rw [destruct_ret, destruct_think] at this, exact false.elim this }, { rw [destruct_ret, destruct_think] at this, exact false.elim this }, { simp at this, simp [*] } end end, exact ⟨s₁, s₂, rfl, rfl, r⟩ end end bisim -- It's more of a stretch to use ∈ for this relation, but it -- asserts that the computation limits to the given value. protected def mem (a : α) (s : computation α) := some a ∈ s.1 instance : has_mem α (computation α) := ⟨computation.mem⟩ theorem le_stable (s : computation α) {a m n} (h : m ≤ n) : s.1 m = some a → s.1 n = some a := by {cases s with f al, induction h with n h IH, exacts [id, λ h2, al (IH h2)]} theorem mem_unique {s : computation α} {a b : α} : a ∈ s → b ∈ s → a = b | ⟨m, ha⟩ ⟨n, hb⟩ := by injection (le_stable s (le_max_left m n) ha.symm).symm.trans (le_stable s (le_max_right m n) hb.symm) theorem mem.left_unique : relator.left_unique ((∈) : α → computation α → Prop) := ⟨λ a s b, mem_unique⟩ /-- `terminates s` asserts that the computation `s` eventually terminates with some value. -/ class terminates (s : computation α) : Prop := (term : ∃ a, a ∈ s) theorem terminates_iff (s : computation α) : terminates s ↔ ∃ a, a ∈ s := ⟨λ h, h.1, terminates.mk⟩ theorem terminates_of_mem {s : computation α} {a : α} (h : a ∈ s) : terminates s := ⟨⟨a, h⟩⟩ theorem terminates_def (s : computation α) : terminates s ↔ ∃ n, (s.1 n).is_some := ⟨λ ⟨⟨a, n, h⟩⟩, ⟨n, by {dsimp [stream.nth] at h, rw ←h, exact rfl}⟩, λ ⟨n, h⟩, ⟨⟨option.get h, n, (option.eq_some_of_is_some h).symm⟩⟩⟩ theorem ret_mem (a : α) : a ∈ return a := exists.intro 0 rfl theorem eq_of_ret_mem {a a' : α} (h : a' ∈ return a) : a' = a := mem_unique h (ret_mem _) instance ret_terminates (a : α) : terminates (return a) := terminates_of_mem (ret_mem _) theorem think_mem {s : computation α} {a} : a ∈ s → a ∈ think s | ⟨n, h⟩ := ⟨n+1, h⟩ instance think_terminates (s : computation α) : ∀ [terminates s], terminates (think s) | ⟨⟨a, n, h⟩⟩ := ⟨⟨a, n+1, h⟩⟩ theorem of_think_mem {s : computation α} {a} : a ∈ think s → a ∈ s | ⟨n, h⟩ := by {cases n with n', contradiction, exact ⟨n', h⟩} theorem of_think_terminates {s : computation α} : terminates (think s) → terminates s | ⟨⟨a, h⟩⟩ := ⟨⟨a, of_think_mem h⟩⟩ theorem not_mem_empty (a : α) : a ∉ empty α := λ ⟨n, h⟩, by clear _fun_match; contradiction theorem not_terminates_empty : ¬ terminates (empty α) := λ ⟨⟨a, h⟩⟩, not_mem_empty a h theorem eq_empty_of_not_terminates {s} (H : ¬ terminates s) : s = empty α := begin apply subtype.eq, funext n, induction h : s.val n, {refl}, refine absurd _ H, exact ⟨⟨_, _, h.symm⟩⟩ end theorem thinkN_mem {s : computation α} {a} : ∀ n, a ∈ thinkN s n ↔ a ∈ s | 0 := iff.rfl | (n+1) := iff.trans ⟨of_think_mem, think_mem⟩ (thinkN_mem n) instance thinkN_terminates (s : computation α) : ∀ [terminates s] n, terminates (thinkN s n) | ⟨⟨a, h⟩⟩ n := ⟨⟨a, (thinkN_mem n).2 h⟩⟩ theorem of_thinkN_terminates (s : computation α) (n) : terminates (thinkN s n) → terminates s | ⟨⟨a, h⟩⟩ := ⟨⟨a, (thinkN_mem _).1 h⟩⟩ /-- `promises s a`, or `s ~> a`, asserts that although the computation `s` may not terminate, if it does, then the result is `a`. -/ def promises (s : computation α) (a : α) : Prop := ∀ ⦃a'⦄, a' ∈ s → a = a' infix ` ~> `:50 := promises theorem mem_promises {s : computation α} {a : α} : a ∈ s → s ~> a := λ h a', mem_unique h theorem empty_promises (a : α) : empty α ~> a := λ a' h, absurd h (not_mem_empty _) section get variables (s : computation α) [h : terminates s] include s h /-- `length s` gets the number of steps of a terminating computation -/ def length : ℕ := nat.find ((terminates_def _).1 h) /-- `get s` returns the result of a terminating computation -/ def get : α := option.get (nat.find_spec $ (terminates_def _).1 h) theorem get_mem : get s ∈ s := exists.intro (length s) (option.eq_some_of_is_some _).symm theorem get_eq_of_mem {a} : a ∈ s → get s = a := mem_unique (get_mem _) theorem mem_of_get_eq {a} : get s = a → a ∈ s := by intro h; rw ←h; apply get_mem @[simp] theorem get_think : get (think s) = get s := get_eq_of_mem _ $ let ⟨n, h⟩ := get_mem s in ⟨n+1, h⟩ @[simp] theorem get_thinkN (n) : get (thinkN s n) = get s := get_eq_of_mem _ $ (thinkN_mem _).2 (get_mem _) theorem get_promises : s ~> get s := λ a, get_eq_of_mem _ theorem mem_of_promises {a} (p : s ~> a) : a ∈ s := by { casesI h, cases h with a' h, rw p h, exact h } theorem get_eq_of_promises {a} : s ~> a → get s = a := get_eq_of_mem _ ∘ mem_of_promises _ end get /-- `results s a n` completely characterizes a terminating computation: it asserts that `s` terminates after exactly `n` steps, with result `a`. -/ def results (s : computation α) (a : α) (n : ℕ) := ∃ (h : a ∈ s), @length _ s (terminates_of_mem h) = n theorem results_of_terminates (s : computation α) [T : terminates s] : results s (get s) (length s) := ⟨get_mem _, rfl⟩ theorem results_of_terminates' (s : computation α) [T : terminates s] {a} (h : a ∈ s) : results s a (length s) := by rw ←get_eq_of_mem _ h; apply results_of_terminates theorem results.mem {s : computation α} {a n} : results s a n → a ∈ s | ⟨m, _⟩ := m theorem results.terminates {s : computation α} {a n} (h : results s a n) : terminates s := terminates_of_mem h.mem theorem results.length {s : computation α} {a n} [T : terminates s] : results s a n → length s = n | ⟨_, h⟩ := h theorem results.val_unique {s : computation α} {a b m n} (h1 : results s a m) (h2 : results s b n) : a = b := mem_unique h1.mem h2.mem theorem results.len_unique {s : computation α} {a b m n} (h1 : results s a m) (h2 : results s b n) : m = n := by haveI := h1.terminates; haveI := h2.terminates; rw [←h1.length, h2.length] theorem exists_results_of_mem {s : computation α} {a} (h : a ∈ s) : ∃ n, results s a n := by haveI := terminates_of_mem h; exact ⟨_, results_of_terminates' s h⟩ @[simp] theorem get_ret (a : α) : get (return a) = a := get_eq_of_mem _ ⟨0, rfl⟩ @[simp] theorem length_ret (a : α) : length (return a) = 0 := let h := computation.ret_terminates a in nat.eq_zero_of_le_zero $ nat.find_min' ((terminates_def (return a)).1 h) rfl theorem results_ret (a : α) : results (return a) a 0 := ⟨_, length_ret _⟩ @[simp] theorem length_think (s : computation α) [h : terminates s] : length (think s) = length s + 1 := begin apply le_antisymm, { exact nat.find_min' _ (nat.find_spec ((terminates_def _).1 h)) }, { have : (option.is_some ((think s).val (length (think s))) : Prop) := nat.find_spec ((terminates_def _).1 s.think_terminates), cases length (think s) with n, { contradiction }, { apply nat.succ_le_succ, apply nat.find_min', apply this } } end theorem results_think {s : computation α} {a n} (h : results s a n) : results (think s) a (n + 1) := by haveI := h.terminates; exact ⟨think_mem h.mem, by rw [length_think, h.length]⟩ theorem of_results_think {s : computation α} {a n} (h : results (think s) a n) : ∃ m, results s a m ∧ n = m + 1 := begin haveI := of_think_terminates h.terminates, have := results_of_terminates' _ (of_think_mem h.mem), exact ⟨_, this, results.len_unique h (results_think this)⟩, end @[simp] theorem results_think_iff {s : computation α} {a n} : results (think s) a (n + 1) ↔ results s a n := ⟨λ h, let ⟨n', r, e⟩ := of_results_think h in by injection e with h'; rwa h', results_think⟩ theorem results_thinkN {s : computation α} {a m} : ∀ n, results s a m → results (thinkN s n) a (m + n) | 0 h := h | (n+1) h := results_think (results_thinkN n h) theorem results_thinkN_ret (a : α) (n) : results (thinkN (return a) n) a n := by have := results_thinkN n (results_ret a); rwa nat.zero_add at this @[simp] theorem length_thinkN (s : computation α) [h : terminates s] (n) : length (thinkN s n) = length s + n := (results_thinkN n (results_of_terminates _)).length theorem eq_thinkN {s : computation α} {a n} (h : results s a n) : s = thinkN (return a) n := begin revert s, induction n with n IH; intro s; apply cases_on s (λ a', _) (λ s, _); intro h, { rw ←eq_of_ret_mem h.mem, refl }, { cases of_results_think h with n h, cases h, contradiction }, { have := h.len_unique (results_ret _), contradiction }, { rw IH (results_think_iff.1 h), refl } end theorem eq_thinkN' (s : computation α) [h : terminates s] : s = thinkN (return (get s)) (length s) := eq_thinkN (results_of_terminates _) def mem_rec_on {C : computation α → Sort v} {a s} (M : a ∈ s) (h1 : C (return a)) (h2 : ∀ s, C s → C (think s)) : C s := begin haveI T := terminates_of_mem M, rw [eq_thinkN' s, get_eq_of_mem s M], generalize : length s = n, induction n with n IH, exacts [h1, h2 _ IH] end def terminates_rec_on {C : computation α → Sort v} (s) [terminates s] (h1 : ∀ a, C (return a)) (h2 : ∀ s, C s → C (think s)) : C s := mem_rec_on (get_mem s) (h1 _) h2 /-- Map a function on the result of a computation. -/ def map (f : α → β) : computation α → computation β | ⟨s, al⟩ := ⟨s.map (λo, option.cases_on o none (some ∘ f)), λn b, begin dsimp [stream.map, stream.nth], induction e : s n with a; intro h, { contradiction }, { rw [al e, ←h] } end⟩ def bind.G : β ⊕ computation β → β ⊕ computation α ⊕ computation β | (sum.inl b) := sum.inl b | (sum.inr cb') := sum.inr $ sum.inr cb' def bind.F (f : α → computation β) : computation α ⊕ computation β → β ⊕ computation α ⊕ computation β | (sum.inl ca) := match destruct ca with | sum.inl a := bind.G $ destruct (f a) | sum.inr ca' := sum.inr $ sum.inl ca' end | (sum.inr cb) := bind.G $ destruct cb /-- Compose two computations into a monadic `bind` operation. -/ def bind (c : computation α) (f : α → computation β) : computation β := corec (bind.F f) (sum.inl c) instance : has_bind computation := ⟨@bind⟩ theorem has_bind_eq_bind {β} (c : computation α) (f : α → computation β) : c >>= f = bind c f := rfl /-- Flatten a computation of computations into a single computation. -/ def join (c : computation (computation α)) : computation α := c >>= id @[simp] theorem map_ret (f : α → β) (a) : map f (return a) = return (f a) := rfl @[simp] theorem map_think (f : α → β) : ∀ s, map f (think s) = think (map f s) | ⟨s, al⟩ := by apply subtype.eq; dsimp [think, map]; rw stream.map_cons @[simp] theorem destruct_map (f : α → β) (s) : destruct (map f s) = lmap f (rmap (map f) (destruct s)) := by apply s.cases_on; intro; simp @[simp] theorem map_id : ∀ (s : computation α), map id s = s | ⟨f, al⟩ := begin apply subtype.eq; simp [map, function.comp], have e : (@option.rec α (λ_, option α) none some) = id, { ext ⟨⟩; refl }, simp [e, stream.map_id] end theorem map_comp (f : α → β) (g : β → γ) : ∀ (s : computation α), map (g ∘ f) s = map g (map f s) | ⟨s, al⟩ := begin apply subtype.eq; dsimp [map], rw stream.map_map, apply congr_arg (λ f : _ → option γ, stream.map f s), ext ⟨⟩; refl end @[simp] theorem ret_bind (a) (f : α → computation β) : bind (return a) f = f a := begin apply eq_of_bisim (λc₁ c₂, c₁ = bind (return a) f ∧ c₂ = f a ∨ c₁ = corec (bind.F f) (sum.inr c₂)), { intros c₁ c₂ h, exact match c₁, c₂, h with | ._, ._, or.inl ⟨rfl, rfl⟩ := begin simp [bind, bind.F], cases destruct (f a) with b cb; simp [bind.G] end | ._, c, or.inr rfl := begin simp [bind.F], cases destruct c with b cb; simp [bind.G] end end }, { simp } end @[simp] theorem think_bind (c) (f : α → computation β) : bind (think c) f = think (bind c f) := destruct_eq_think $ by simp [bind, bind.F] @[simp] theorem bind_ret (f : α → β) (s) : bind s (return ∘ f) = map f s := begin apply eq_of_bisim (λc₁ c₂, c₁ = c₂ ∨ ∃ s, c₁ = bind s (return ∘ f) ∧ c₂ = map f s), { intros c₁ c₂ h, exact match c₁, c₂, h with | _, _, or.inl (eq.refl c) := begin cases destruct c with b cb; simp end | _, _, or.inr ⟨s, rfl, rfl⟩ := begin apply cases_on s; intros s; simp, exact or.inr ⟨s, rfl, rfl⟩ end end }, { exact or.inr ⟨s, rfl, rfl⟩ } end @[simp] theorem bind_ret' (s : computation α) : bind s return = s := by rw bind_ret; change (λ x : α, x) with @id α; rw map_id @[simp] theorem bind_assoc (s : computation α) (f : α → computation β) (g : β → computation γ) : bind (bind s f) g = bind s (λ (x : α), bind (f x) g) := begin apply eq_of_bisim (λc₁ c₂, c₁ = c₂ ∨ ∃ s, c₁ = bind (bind s f) g ∧ c₂ = bind s (λ (x : α), bind (f x) g)), { intros c₁ c₂ h, exact match c₁, c₂, h with | _, _, or.inl (eq.refl c) := by cases destruct c with b cb; simp | ._, ._, or.inr ⟨s, rfl, rfl⟩ := begin apply cases_on s; intros s; simp, { generalize : f s = fs, apply cases_on fs; intros t; simp, { cases destruct (g t) with b cb; simp } }, { exact or.inr ⟨s, rfl, rfl⟩ } end end }, { exact or.inr ⟨s, rfl, rfl⟩ } end theorem results_bind {s : computation α} {f : α → computation β} {a b m n} (h1 : results s a m) (h2 : results (f a) b n) : results (bind s f) b (n + m) := begin have := h1.mem, revert m, apply mem_rec_on this _ (λ s IH, _); intros m h1, { rw [ret_bind], rw h1.len_unique (results_ret _), exact h2 }, { rw [think_bind], cases of_results_think h1 with m' h, cases h with h1 e, rw e, exact results_think (IH h1) } end theorem mem_bind {s : computation α} {f : α → computation β} {a b} (h1 : a ∈ s) (h2 : b ∈ f a) : b ∈ bind s f := let ⟨m, h1⟩ := exists_results_of_mem h1, ⟨n, h2⟩ := exists_results_of_mem h2 in (results_bind h1 h2).mem instance terminates_bind (s : computation α) (f : α → computation β) [terminates s] [terminates (f (get s))] : terminates (bind s f) := terminates_of_mem (mem_bind (get_mem s) (get_mem (f (get s)))) @[simp] theorem get_bind (s : computation α) (f : α → computation β) [terminates s] [terminates (f (get s))] : get (bind s f) = get (f (get s)) := get_eq_of_mem _ (mem_bind (get_mem s) (get_mem (f (get s)))) @[simp] theorem length_bind (s : computation α) (f : α → computation β) [T1 : terminates s] [T2 : terminates (f (get s))] : length (bind s f) = length (f (get s)) + length s := (results_of_terminates _).len_unique $ results_bind (results_of_terminates _) (results_of_terminates _) theorem of_results_bind {s : computation α} {f : α → computation β} {b k} : results (bind s f) b k → ∃ a m n, results s a m ∧ results (f a) b n ∧ k = n + m := begin induction k with n IH generalizing s; apply cases_on s (λ a, _) (λ s', _); intro e, { simp [thinkN] at e, refine ⟨a, _, _, results_ret _, e, rfl⟩ }, { have := congr_arg head (eq_thinkN e), contradiction }, { simp at e, refine ⟨a, _, n+1, results_ret _, e, rfl⟩ }, { simp at e, exact let ⟨a, m, n', h1, h2, e'⟩ := IH e in by rw e'; exact ⟨a, m.succ, n', results_think h1, h2, rfl⟩ } end theorem exists_of_mem_bind {s : computation α} {f : α → computation β} {b} (h : b ∈ bind s f) : ∃ a ∈ s, b ∈ f a := let ⟨k, h⟩ := exists_results_of_mem h, ⟨a, m, n, h1, h2, e⟩ := of_results_bind h in ⟨a, h1.mem, h2.mem⟩ theorem bind_promises {s : computation α} {f : α → computation β} {a b} (h1 : s ~> a) (h2 : f a ~> b) : bind s f ~> b := λ b' bB, begin rcases exists_of_mem_bind bB with ⟨a', a's, ba'⟩, rw ←h1 a's at ba', exact h2 ba' end instance : monad computation := { map := @map, pure := @return, bind := @bind } instance : is_lawful_monad computation := { id_map := @map_id, bind_pure_comp_eq_map := @bind_ret, pure_bind := @ret_bind, bind_assoc := @bind_assoc } theorem has_map_eq_map {β} (f : α → β) (c : computation α) : f <$> c = map f c := rfl @[simp] theorem return_def (a) : (_root_.return a : computation α) = return a := rfl @[simp] theorem map_ret' {α β} : ∀ (f : α → β) (a), f <$> return a = return (f a) := map_ret @[simp] theorem map_think' {α β} : ∀ (f : α → β) s, f <$> think s = think (f <$> s) := map_think theorem mem_map (f : α → β) {a} {s : computation α} (m : a ∈ s) : f a ∈ map f s := by rw ←bind_ret; apply mem_bind m; apply ret_mem theorem exists_of_mem_map {f : α → β} {b : β} {s : computation α} (h : b ∈ map f s) : ∃ a, a ∈ s ∧ f a = b := by rw ←bind_ret at h; exact let ⟨a, as, fb⟩ := exists_of_mem_bind h in ⟨a, as, mem_unique (ret_mem _) fb⟩ instance terminates_map (f : α → β) (s : computation α) [terminates s] : terminates (map f s) := by rw ←bind_ret; apply_instance theorem terminates_map_iff (f : α → β) (s : computation α) : terminates (map f s) ↔ terminates s := ⟨λ ⟨⟨a, h⟩⟩, let ⟨b, h1, _⟩ := exists_of_mem_map h in ⟨⟨_, h1⟩⟩, @computation.terminates_map _ _ _ _⟩ -- Parallel computation /-- `c₁ <|> c₂` calculates `c₁` and `c₂` simultaneously, returning the first one that gives a result. -/ def orelse (c₁ c₂ : computation α) : computation α := @computation.corec α (computation α × computation α) (λ⟨c₁, c₂⟩, match destruct c₁ with | sum.inl a := sum.inl a | sum.inr c₁' := match destruct c₂ with | sum.inl a := sum.inl a | sum.inr c₂' := sum.inr (c₁', c₂') end end) (c₁, c₂) instance : alternative computation := { orelse := @orelse, failure := @empty, ..computation.monad } @[simp] theorem ret_orelse (a : α) (c₂ : computation α) : (return a <|> c₂) = return a := destruct_eq_ret $ by unfold has_orelse.orelse; simp [orelse] @[simp] theorem orelse_ret (c₁ : computation α) (a : α) : (think c₁ <|> return a) = return a := destruct_eq_ret $ by unfold has_orelse.orelse; simp [orelse] @[simp] theorem orelse_think (c₁ c₂ : computation α) : (think c₁ <|> think c₂) = think (c₁ <|> c₂) := destruct_eq_think $ by unfold has_orelse.orelse; simp [orelse] @[simp] theorem empty_orelse (c) : (empty α <|> c) = c := begin apply eq_of_bisim (λc₁ c₂, (empty α <|> c₂) = c₁) _ rfl, intros s' s h, rw ←h, apply cases_on s; intros s; rw think_empty; simp, rw ←think_empty, end @[simp] theorem orelse_empty (c : computation α) : (c <|> empty α) = c := begin apply eq_of_bisim (λc₁ c₂, (c₂ <|> empty α) = c₁) _ rfl, intros s' s h, rw ←h, apply cases_on s; intros s; rw think_empty; simp, rw←think_empty, end /-- `c₁ ~ c₂` asserts that `c₁` and `c₂` either both terminate with the same result, or both loop forever. -/ def equiv (c₁ c₂ : computation α) : Prop := ∀ a, a ∈ c₁ ↔ a ∈ c₂ infix ` ~ `:50 := equiv @[refl] theorem equiv.refl (s : computation α) : s ~ s := λ_, iff.rfl @[symm] theorem equiv.symm {s t : computation α} : s ~ t → t ~ s := λh a, (h a).symm @[trans] theorem equiv.trans {s t u : computation α} : s ~ t → t ~ u → s ~ u := λh1 h2 a, (h1 a).trans (h2 a) theorem equiv.equivalence : equivalence (@equiv α) := ⟨@equiv.refl _, @equiv.symm _, @equiv.trans _⟩ theorem equiv_of_mem {s t : computation α} {a} (h1 : a ∈ s) (h2 : a ∈ t) : s ~ t := λa', ⟨λma, by rw mem_unique ma h1; exact h2, λma, by rw mem_unique ma h2; exact h1⟩ theorem terminates_congr {c₁ c₂ : computation α} (h : c₁ ~ c₂) : terminates c₁ ↔ terminates c₂ := by simp only [terminates_iff, exists_congr h] theorem promises_congr {c₁ c₂ : computation α} (h : c₁ ~ c₂) (a) : c₁ ~> a ↔ c₂ ~> a := forall_congr (λa', imp_congr (h a') iff.rfl) theorem get_equiv {c₁ c₂ : computation α} (h : c₁ ~ c₂) [terminates c₁] [terminates c₂] : get c₁ = get c₂ := get_eq_of_mem _ $ (h _).2 $ get_mem _ theorem think_equiv (s : computation α) : think s ~ s := λ a, ⟨of_think_mem, think_mem⟩ theorem thinkN_equiv (s : computation α) (n) : thinkN s n ~ s := λ a, thinkN_mem n theorem bind_congr {s1 s2 : computation α} {f1 f2 : α → computation β} (h1 : s1 ~ s2) (h2 : ∀ a, f1 a ~ f2 a) : bind s1 f1 ~ bind s2 f2 := λ b, ⟨λh, let ⟨a, ha, hb⟩ := exists_of_mem_bind h in mem_bind ((h1 a).1 ha) ((h2 a b).1 hb), λh, let ⟨a, ha, hb⟩ := exists_of_mem_bind h in mem_bind ((h1 a).2 ha) ((h2 a b).2 hb)⟩ theorem equiv_ret_of_mem {s : computation α} {a} (h : a ∈ s) : s ~ return a := equiv_of_mem h (ret_mem _) /-- `lift_rel R ca cb` is a generalization of `equiv` to relations other than equality. It asserts that if `ca` terminates with `a`, then `cb` terminates with some `b` such that `R a b`, and if `cb` terminates with `b` then `ca` terminates with some `a` such that `R a b`. -/ def lift_rel (R : α → β → Prop) (ca : computation α) (cb : computation β) : Prop := (∀ {a}, a ∈ ca → ∃ {b}, b ∈ cb ∧ R a b) ∧ ∀ {b}, b ∈ cb → ∃ {a}, a ∈ ca ∧ R a b theorem lift_rel.swap (R : α → β → Prop) (ca : computation α) (cb : computation β) : lift_rel (swap R) cb ca ↔ lift_rel R ca cb := and_comm _ _ theorem lift_eq_iff_equiv (c₁ c₂ : computation α) : lift_rel (=) c₁ c₂ ↔ c₁ ~ c₂ := ⟨λ⟨h1, h2⟩ a, ⟨λ a1, let ⟨b, b2, ab⟩ := h1 a1 in by rwa ab, λ a2, let ⟨b, b1, ab⟩ := h2 a2 in by rwa ←ab⟩, λe, ⟨λ a a1, ⟨a, (e _).1 a1, rfl⟩, λ a a2, ⟨a, (e _).2 a2, rfl⟩⟩⟩ theorem lift_rel.refl (R : α → α → Prop) (H : reflexive R) : reflexive (lift_rel R) := λ s, ⟨λ a as, ⟨a, as, H a⟩, λ b bs, ⟨b, bs, H b⟩⟩ theorem lift_rel.symm (R : α → α → Prop) (H : symmetric R) : symmetric (lift_rel R) := λ s1 s2 ⟨l, r⟩, ⟨λ a a2, let ⟨b, b1, ab⟩ := r a2 in ⟨b, b1, H ab⟩, λ a a1, let ⟨b, b2, ab⟩ := l a1 in ⟨b, b2, H ab⟩⟩ theorem lift_rel.trans (R : α → α → Prop) (H : transitive R) : transitive (lift_rel R) := λ s1 s2 s3 ⟨l1, r1⟩ ⟨l2, r2⟩, ⟨λ a a1, let ⟨b, b2, ab⟩ := l1 a1, ⟨c, c3, bc⟩ := l2 b2 in ⟨c, c3, H ab bc⟩, λ c c3, let ⟨b, b2, bc⟩ := r2 c3, ⟨a, a1, ab⟩ := r1 b2 in ⟨a, a1, H ab bc⟩⟩ theorem lift_rel.equiv (R : α → α → Prop) : equivalence R → equivalence (lift_rel R) | ⟨refl, symm, trans⟩ := ⟨lift_rel.refl R refl, lift_rel.symm R symm, lift_rel.trans R trans⟩ theorem lift_rel.imp {R S : α → β → Prop} (H : ∀ {a b}, R a b → S a b) (s t) : lift_rel R s t → lift_rel S s t | ⟨l, r⟩ := ⟨λ a as, let ⟨b, bt, ab⟩ := l as in ⟨b, bt, H ab⟩, λ b bt, let ⟨a, as, ab⟩ := r bt in ⟨a, as, H ab⟩⟩ theorem terminates_of_lift_rel {R : α → β → Prop} {s t} : lift_rel R s t → (terminates s ↔ terminates t) | ⟨l, r⟩ := ⟨λ ⟨⟨a, as⟩⟩, let ⟨b, bt, ab⟩ := l as in ⟨⟨b, bt⟩⟩, λ ⟨⟨b, bt⟩⟩, let ⟨a, as, ab⟩ := r bt in ⟨⟨a, as⟩⟩⟩ theorem rel_of_lift_rel {R : α → β → Prop} {ca cb} : lift_rel R ca cb → ∀ {a b}, a ∈ ca → b ∈ cb → R a b | ⟨l, r⟩ a b ma mb := let ⟨b', mb', ab'⟩ := l ma in by rw mem_unique mb mb'; exact ab' theorem lift_rel_of_mem {R : α → β → Prop} {a b ca cb} (ma : a ∈ ca) (mb : b ∈ cb) (ab : R a b) : lift_rel R ca cb := ⟨λ a' ma', by rw mem_unique ma' ma; exact ⟨b, mb, ab⟩, λ b' mb', by rw mem_unique mb' mb; exact ⟨a, ma, ab⟩⟩ theorem exists_of_lift_rel_left {R : α → β → Prop} {ca cb} (H : lift_rel R ca cb) {a} (h : a ∈ ca) : ∃ {b}, b ∈ cb ∧ R a b := H.left h theorem exists_of_lift_rel_right {R : α → β → Prop} {ca cb} (H : lift_rel R ca cb) {b} (h : b ∈ cb) : ∃ {a}, a ∈ ca ∧ R a b := H.right h theorem lift_rel_def {R : α → β → Prop} {ca cb} : lift_rel R ca cb ↔ (terminates ca ↔ terminates cb) ∧ ∀ {a b}, a ∈ ca → b ∈ cb → R a b := ⟨λh, ⟨terminates_of_lift_rel h, λ a b ma mb, let ⟨b', mb', ab⟩ := h.left ma in by rwa mem_unique mb mb'⟩, λ⟨l, r⟩, ⟨λ a ma, let ⟨⟨b, mb⟩⟩ := l.1 ⟨⟨_, ma⟩⟩ in ⟨b, mb, r ma mb⟩, λ b mb, let ⟨⟨a, ma⟩⟩ := l.2 ⟨⟨_, mb⟩⟩ in ⟨a, ma, r ma mb⟩⟩⟩ theorem lift_rel_bind {δ} (R : α → β → Prop) (S : γ → δ → Prop) {s1 : computation α} {s2 : computation β} {f1 : α → computation γ} {f2 : β → computation δ} (h1 : lift_rel R s1 s2) (h2 : ∀ {a b}, R a b → lift_rel S (f1 a) (f2 b)) : lift_rel S (bind s1 f1) (bind s2 f2) := let ⟨l1, r1⟩ := h1 in ⟨λ c cB, let ⟨a, a1, c₁⟩ := exists_of_mem_bind cB, ⟨b, b2, ab⟩ := l1 a1, ⟨l2, r2⟩ := h2 ab, ⟨d, d2, cd⟩ := l2 c₁ in ⟨_, mem_bind b2 d2, cd⟩, λ d dB, let ⟨b, b1, d1⟩ := exists_of_mem_bind dB, ⟨a, a2, ab⟩ := r1 b1, ⟨l2, r2⟩ := h2 ab, ⟨c, c₂, cd⟩ := r2 d1 in ⟨_, mem_bind a2 c₂, cd⟩⟩ @[simp] theorem lift_rel_return_left (R : α → β → Prop) (a : α) (cb : computation β) : lift_rel R (return a) cb ↔ ∃ {b}, b ∈ cb ∧ R a b := ⟨λ⟨l, r⟩, l (ret_mem _), λ⟨b, mb, ab⟩, ⟨λ a' ma', by rw eq_of_ret_mem ma'; exact ⟨b, mb, ab⟩, λ b' mb', ⟨_, ret_mem _, by rw mem_unique mb' mb; exact ab⟩⟩⟩ @[simp] theorem lift_rel_return_right (R : α → β → Prop) (ca : computation α) (b : β) : lift_rel R ca (return b) ↔ ∃ {a}, a ∈ ca ∧ R a b := by rw [lift_rel.swap, lift_rel_return_left] @[simp] theorem lift_rel_return (R : α → β → Prop) (a : α) (b : β) : lift_rel R (return a) (return b) ↔ R a b := by rw [lift_rel_return_left]; exact ⟨λ⟨b', mb', ab'⟩, by rwa eq_of_ret_mem mb' at ab', λab, ⟨_, ret_mem _, ab⟩⟩ @[simp] theorem lift_rel_think_left (R : α → β → Prop) (ca : computation α) (cb : computation β) : lift_rel R (think ca) cb ↔ lift_rel R ca cb := and_congr (forall_congr $ λb, imp_congr ⟨of_think_mem, think_mem⟩ iff.rfl) (forall_congr $ λb, imp_congr iff.rfl $ exists_congr $ λ b, and_congr ⟨of_think_mem, think_mem⟩ iff.rfl) @[simp] theorem lift_rel_think_right (R : α → β → Prop) (ca : computation α) (cb : computation β) : lift_rel R ca (think cb) ↔ lift_rel R ca cb := by rw [←lift_rel.swap R, ←lift_rel.swap R]; apply lift_rel_think_left theorem lift_rel_mem_cases {R : α → β → Prop} {ca cb} (Ha : ∀ a ∈ ca, lift_rel R ca cb) (Hb : ∀ b ∈ cb, lift_rel R ca cb) : lift_rel R ca cb := ⟨λ a ma, (Ha _ ma).left ma, λ b mb, (Hb _ mb).right mb⟩ theorem lift_rel_congr {R : α → β → Prop} {ca ca' : computation α} {cb cb' : computation β} (ha : ca ~ ca') (hb : cb ~ cb') : lift_rel R ca cb ↔ lift_rel R ca' cb' := and_congr (forall_congr $ λ a, imp_congr (ha _) $ exists_congr $ λ b, and_congr (hb _) iff.rfl) (forall_congr $ λ b, imp_congr (hb _) $ exists_congr $ λ a, and_congr (ha _) iff.rfl) theorem lift_rel_map {δ} (R : α → β → Prop) (S : γ → δ → Prop) {s1 : computation α} {s2 : computation β} {f1 : α → γ} {f2 : β → δ} (h1 : lift_rel R s1 s2) (h2 : ∀ {a b}, R a b → S (f1 a) (f2 b)) : lift_rel S (map f1 s1) (map f2 s2) := by rw [←bind_ret, ←bind_ret]; apply lift_rel_bind _ _ h1; simp; exact @h2 theorem map_congr (R : α → α → Prop) (S : β → β → Prop) {s1 s2 : computation α} {f : α → β} (h1 : s1 ~ s2) : map f s1 ~ map f s2 := by rw [←lift_eq_iff_equiv]; exact lift_rel_map eq _ ((lift_eq_iff_equiv _ _).2 h1) (λ a b, congr_arg _) def lift_rel_aux (R : α → β → Prop) (C : computation α → computation β → Prop) : α ⊕ computation α → β ⊕ computation β → Prop | (sum.inl a) (sum.inl b) := R a b | (sum.inl a) (sum.inr cb) := ∃ {b}, b ∈ cb ∧ R a b | (sum.inr ca) (sum.inl b) := ∃ {a}, a ∈ ca ∧ R a b | (sum.inr ca) (sum.inr cb) := C ca cb attribute [simp] lift_rel_aux @[simp] lemma lift_rel_aux.ret_left (R : α → β → Prop) (C : computation α → computation β → Prop) (a cb) : lift_rel_aux R C (sum.inl a) (destruct cb) ↔ ∃ {b}, b ∈ cb ∧ R a b := begin apply cb.cases_on (λ b, _) (λ cb, _), { exact ⟨λ h, ⟨_, ret_mem _, h⟩, λ ⟨b', mb, h⟩, by rw [mem_unique (ret_mem _) mb]; exact h⟩ }, { rw [destruct_think], exact ⟨λ ⟨b, h, r⟩, ⟨b, think_mem h, r⟩, λ ⟨b, h, r⟩, ⟨b, of_think_mem h, r⟩⟩ } end theorem lift_rel_aux.swap (R : α → β → Prop) (C) (a b) : lift_rel_aux (swap R) (swap C) b a = lift_rel_aux R C a b := by cases a with a ca; cases b with b cb; simp only [lift_rel_aux] @[simp] lemma lift_rel_aux.ret_right (R : α → β → Prop) (C : computation α → computation β → Prop) (b ca) : lift_rel_aux R C (destruct ca) (sum.inl b) ↔ ∃ {a}, a ∈ ca ∧ R a b := by rw [←lift_rel_aux.swap, lift_rel_aux.ret_left] theorem lift_rel_rec.lem {R : α → β → Prop} (C : computation α → computation β → Prop) (H : ∀ {ca cb}, C ca cb → lift_rel_aux R C (destruct ca) (destruct cb)) (ca cb) (Hc : C ca cb) (a) (ha : a ∈ ca) : lift_rel R ca cb := begin revert cb, refine mem_rec_on ha _ (λ ca' IH, _); intros cb Hc; have h := H Hc, { simp at h, simp [h] }, { have h := H Hc, simp, revert h, apply cb.cases_on (λ b, _) (λ cb', _); intro h; simp at h; simp [h], exact IH _ h } end theorem lift_rel_rec {R : α → β → Prop} (C : computation α → computation β → Prop) (H : ∀ {ca cb}, C ca cb → lift_rel_aux R C (destruct ca) (destruct cb)) (ca cb) (Hc : C ca cb) : lift_rel R ca cb := lift_rel_mem_cases (lift_rel_rec.lem C @H ca cb Hc) (λ b hb, (lift_rel.swap _ _ _).2 $ lift_rel_rec.lem (swap C) (λ cb ca h, cast (lift_rel_aux.swap _ _ _ _).symm $ H h) cb ca Hc b hb) end computation
1f4817f5af71f00dc6de8ce34b2ae1d4d61a0515
737dc4b96c97368cb66b925eeea3ab633ec3d702
/src/Lean/Elab/Term.lean
69cdf35a559e97a028f9461a46dc6cdd9d71840a
[ "Apache-2.0" ]
permissive
Bioye97/lean4
1ace34638efd9913dc5991443777b01a08983289
bc3900cbb9adda83eed7e6affeaade7cfd07716d
refs/heads/master
1,690,589,820,211
1,631,051,000,000
1,631,067,598,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
69,537
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Sebastian Ullrich -/ import Lean.ResolveName import Lean.Util.Sorry import Lean.Util.ReplaceExpr import Lean.Structure import Lean.Meta.ExprDefEq import Lean.Meta.AppBuilder import Lean.Meta.SynthInstance import Lean.Meta.CollectMVars import Lean.Meta.Coe import Lean.Meta.Tactic.Util import Lean.Hygiene import Lean.Util.RecDepth import Lean.Elab.Log import Lean.Elab.Level import Lean.Elab.Attributes import Lean.Elab.AutoBound import Lean.Elab.InfoTree import Lean.Elab.Open import Lean.Elab.SetOption namespace Lean.Elab.Term /- Set isDefEq configuration for the elaborator. Note that we enable all approximations but `quasiPatternApprox` In Lean3 and Lean 4, we used to use the quasi-pattern approximation during elaboration. The example: ``` def ex : StateT δ (StateT σ Id) σ := monadLift (get : StateT σ Id σ) ``` demonstrates why it produces counterintuitive behavior. We have the `Monad-lift` application: ``` @monadLift ?m ?n ?c ?α (get : StateT σ id σ) : ?n ?α ``` It produces the following unification problem when we process the expected type: ``` ?n ?α =?= StateT δ (StateT σ id) σ ==> (approximate using first-order unification) ?n := StateT δ (StateT σ id) ?α := σ ``` Then, we need to solve: ``` ?m ?α =?= StateT σ id σ ==> instantiate metavars ?m σ =?= StateT σ id σ ==> (approximate since it is a quasi-pattern unification constraint) ?m := fun σ => StateT σ id σ ``` Note that the constraint is not a Milner pattern because σ is in the local context of `?m`. We are ignoring the other possible solutions: ``` ?m := fun σ' => StateT σ id σ ?m := fun σ' => StateT σ' id σ ?m := fun σ' => StateT σ id σ' ``` We need the quasi-pattern approximation for elaborating recursor-like expressions (e.g., dependent `match with` expressions). If we had use first-order unification, then we would have produced the right answer: `?m := StateT σ id` Haskell would work on this example since it always uses first-order unification. -/ def setElabConfig (cfg : Meta.Config) : Meta.Config := { cfg with foApprox := true, ctxApprox := true, constApprox := false, quasiPatternApprox := false } structure Context where fileName : String fileMap : FileMap declName? : Option Name := none macroStack : MacroStack := [] currMacroScope : MacroScope := firstFrontendMacroScope /- When `mayPostpone == true`, an elaboration function may interrupt its execution by throwing `Exception.postpone`. The function `elabTerm` catches this exception and creates fresh synthetic metavariable `?m`, stores `?m` in the list of pending synthetic metavariables, and returns `?m`. -/ mayPostpone : Bool := true /- When `errToSorry` is set to true, the method `elabTerm` catches exceptions and converts them into synthetic `sorry`s. The implementation of choice nodes and overloaded symbols rely on the fact that when `errToSorry` is set to false for an elaboration function `F`, then `errToSorry` remains `false` for all elaboration functions invoked by `F`. That is, it is safe to transition `errToSorry` from `true` to `false`, but we must not set `errToSorry` to `true` when it is currently set to `false`. -/ errToSorry : Bool := true /- When `autoBoundImplicit` is set to true, instead of producing an "unknown identifier" error for unbound variables, we generate an internal exception. This exception is caught at `elabBinders` and `elabTypeWithUnboldImplicit`. Both methods add implicit declarations for the unbound variable and try again. -/ autoBoundImplicit : Bool := false autoBoundImplicits : Std.PArray Expr := {} /-- Map from user name to internal unique name -/ sectionVars : NameMap Name := {} /-- Map from internal name to fvar -/ sectionFVars : NameMap Expr := {} /-- Enable/disable implicit lambdas feature. -/ implicitLambda : Bool := true /-- Saved context for postponed terms and tactics to be executed. -/ structure SavedContext where declName? : Option Name options : Options openDecls : List OpenDecl macroStack : MacroStack errToSorry : Bool /-- We use synthetic metavariables as placeholders for pending elaboration steps. -/ inductive SyntheticMVarKind where -- typeclass instance search | typeClass /- Similar to typeClass, but error messages are different. if `f?` is `some f`, we produce an application type mismatch error message. Otherwise, if `header?` is `some header`, we generate the error `(header ++ "has type" ++ eType ++ "but it is expected to have type" ++ expectedType)` Otherwise, we generate the error `("type mismatch" ++ e ++ "has type" ++ eType ++ "but it is expected to have type" ++ expectedType)` -/ | coe (header? : Option String) (eNew : Expr) (expectedType : Expr) (eType : Expr) (e : Expr) (f? : Option Expr) -- tactic block execution | tactic (tacticCode : Syntax) (ctx : SavedContext) -- `elabTerm` call that threw `Exception.postpone` (input is stored at `SyntheticMVarDecl.ref`) | postponed (ctx : SavedContext) instance : ToString SyntheticMVarKind where toString | SyntheticMVarKind.typeClass => "typeclass" | SyntheticMVarKind.coe .. => "coe" | SyntheticMVarKind.tactic .. => "tactic" | SyntheticMVarKind.postponed .. => "postponed" structure SyntheticMVarDecl where mvarId : MVarId stx : Syntax kind : SyntheticMVarKind inductive MVarErrorKind where | implicitArg (ctx : Expr) | hole | custom (msgData : MessageData) instance : ToString MVarErrorKind where toString | MVarErrorKind.implicitArg ctx => "implicitArg" | MVarErrorKind.hole => "hole" | MVarErrorKind.custom msg => "custom" structure MVarErrorInfo where mvarId : MVarId ref : Syntax kind : MVarErrorKind structure LetRecToLift where ref : Syntax fvarId : FVarId attrs : Array Attribute shortDeclName : Name declName : Name lctx : LocalContext localInstances : LocalInstances type : Expr val : Expr mvarId : MVarId structure State where levelNames : List Name := [] syntheticMVars : List SyntheticMVarDecl := [] mvarErrorInfos : List MVarErrorInfo := [] messages : MessageLog := {} letRecsToLift : List LetRecToLift := [] infoState : InfoState := {} deriving Inhabited abbrev TermElabM := ReaderT Context $ StateRefT State MetaM abbrev TermElab := Syntax → Option Expr → TermElabM Expr -- 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 TermElabM := let i := inferInstanceAs (Monad TermElabM); { pure := i.pure, bind := i.bind } open Meta instance : Inhabited (TermElabM α) where default := throw arbitrary structure SavedState where meta : Meta.SavedState «elab» : State deriving Inhabited protected def saveState : TermElabM SavedState := do pure { meta := (← Meta.saveState), «elab» := (← get) } def SavedState.restore (s : SavedState) (restoreInfo : Bool := false) : TermElabM Unit := do let traceState ← getTraceState -- We never backtrack trace message let infoState := (← get).infoState -- We also do not backtrack the info nodes when `restoreInfo == false` s.meta.restore set s.elab setTraceState traceState unless restoreInfo do modify fun s => { s with infoState := infoState } instance : MonadBacktrack SavedState TermElabM where saveState := Term.saveState restoreState b := b.restore abbrev TermElabResult (α : Type) := EStateM.Result Exception SavedState α instance [Inhabited α] : Inhabited (TermElabResult α) where default := EStateM.Result.ok arbitrary arbitrary def setMessageLog (messages : MessageLog) : TermElabM Unit := modify fun s => { s with messages := messages } def resetMessageLog : TermElabM Unit := setMessageLog {} def getMessageLog : TermElabM MessageLog := return (← get).messages /-- Execute `x`, save resulting expression and new state. We remove any `Info` created by `x`. The info nodes are committed when we execute `applyResult`. We use `observing` to implement overloaded notation and decls. We want to save `Info` nodes for the chosen alternative. -/ def observing (x : TermElabM α) : TermElabM (TermElabResult α) := do let s ← saveState try let e ← x let sNew ← saveState s.restore (restoreInfo := true) pure (EStateM.Result.ok e sNew) catch | ex@(Exception.error _ _) => let sNew ← saveState s.restore (restoreInfo := true) pure (EStateM.Result.error ex sNew) | ex@(Exception.internal id _) => if id == postponeExceptionId then s.restore (restoreInfo := true) throw ex /-- Apply the result/exception and state captured with `observing`. We use this method to implement overloaded notation and symbols. -/ def applyResult (result : TermElabResult α) : TermElabM α := match result with | EStateM.Result.ok a r => do r.restore (restoreInfo := true); pure a | EStateM.Result.error ex r => do r.restore (restoreInfo := true); throw ex /-- Execute `x`, but keep state modifications only if `x` did not postpone. This method is useful to implement elaboration functions that cannot decide whether they need to postpone or not without updating the state. -/ def commitIfDidNotPostpone (x : TermElabM α) : TermElabM α := do -- We just reuse the implementation of `observing` and `applyResult`. let r ← observing x applyResult r def getLevelNames : TermElabM (List Name) := return (← get).levelNames def getFVarLocalDecl! (fvar : Expr) : TermElabM LocalDecl := do match (← getLCtx).find? fvar.fvarId! with | some d => pure d | none => unreachable! instance : AddErrorMessageContext TermElabM where add ref msg := do let ctx ← read let ref := getBetterRef ref ctx.macroStack let msg ← addMessageContext msg let msg ← addMacroStack msg ctx.macroStack pure (ref, msg) instance : MonadLog TermElabM where getRef := getRef getFileMap := return (← read).fileMap getFileName := return (← read).fileName logMessage msg := do let ctx ← readThe Core.Context let msg := { msg with data := MessageData.withNamingContext { currNamespace := ctx.currNamespace, openDecls := ctx.openDecls } msg.data }; modify fun s => { s with messages := s.messages.add msg } protected def getCurrMacroScope : TermElabM MacroScope := do pure (← read).currMacroScope protected def getMainModule : TermElabM Name := do pure (← getEnv).mainModule protected def withFreshMacroScope (x : TermElabM α) : TermElabM α := do let fresh ← modifyGetThe Core.State (fun st => (st.nextMacroScope, { st with nextMacroScope := st.nextMacroScope + 1 })) withReader (fun ctx => { ctx with currMacroScope := fresh }) x instance : MonadQuotation TermElabM where getCurrMacroScope := Term.getCurrMacroScope getMainModule := Term.getMainModule withFreshMacroScope := Term.withFreshMacroScope instance : MonadInfoTree TermElabM where getInfoState := return (← get).infoState modifyInfoState f := modify fun s => { s with infoState := f s.infoState } /-- Execute `x` but discard changes performed at `Term.State` and `Meta.State`. Recall that the environment is at `Core.State`. Thus, any updates to it will be preserved. This method is useful for performing computations where all metavariable must be resolved or discarded. The info trees are not discarded, however, and wrapped in `InfoTree.Context` to store their metavariable context. -/ def withoutModifyingElabMetaStateWithInfo (x : TermElabM α) : TermElabM α := do let s ← get let sMeta ← getThe Meta.State try withSaveInfoContext x finally modify ({ s with infoState := ·.infoState }) set sMeta /-- Execute `x` bud discard changes performed to the state. However, the info trees and messages are not discarded. -/ private def withoutModifyingStateWithInfoAndMessagesImpl (x : TermElabM α) : TermElabM α := do let saved ← saveState try x finally let s ← get let saved := { saved with elab.infoState := s.infoState, elab.messages := s.messages } restoreState saved unsafe def mkTermElabAttributeUnsafe : IO (KeyedDeclsAttribute TermElab) := mkElabAttribute TermElab `Lean.Elab.Term.termElabAttribute `builtinTermElab `termElab `Lean.Parser.Term `Lean.Elab.Term.TermElab "term" @[implementedBy mkTermElabAttributeUnsafe] constant mkTermElabAttribute : IO (KeyedDeclsAttribute TermElab) builtin_initialize termElabAttribute : KeyedDeclsAttribute TermElab ← mkTermElabAttribute /-- Auxiliary datatatype for presenting a Lean lvalue modifier. We represent a unelaborated lvalue as a `Syntax` (or `Expr`) and `List LVal`. Example: `a.foo[i].1` is represented as the `Syntax` `a` and the list `[LVal.fieldName "foo", LVal.getOp i, LVal.fieldIdx 1]`. Recall that the notation `a[i]` is not just for accessing arrays in Lean. -/ inductive LVal where | fieldIdx (ref : Syntax) (i : Nat) /- Field `suffix?` is for producing better error messages because `x.y` may be a field access or a hierachical/composite name. `ref` is the syntax object representing the field. `targetStx` is the target object being accessed. -/ | fieldName (ref : Syntax) (name : String) (suffix? : Option Name) (targetStx : Syntax) | getOp (ref : Syntax) (idx : Syntax) def LVal.getRef : LVal → Syntax | LVal.fieldIdx ref _ => ref | LVal.fieldName ref .. => ref | LVal.getOp ref _ => ref def LVal.isFieldName : LVal → Bool | LVal.fieldName .. => true | _ => false instance : ToString LVal where toString | LVal.fieldIdx _ i => toString i | LVal.fieldName _ n .. => n | LVal.getOp _ idx => "[" ++ toString idx ++ "]" def getDeclName? : TermElabM (Option Name) := return (← read).declName? def getLetRecsToLift : TermElabM (List LetRecToLift) := return (← get).letRecsToLift def isExprMVarAssigned (mvarId : MVarId) : TermElabM Bool := return (← getMCtx).isExprAssigned mvarId def getMVarDecl (mvarId : MVarId) : TermElabM MetavarDecl := return (← getMCtx).getDecl mvarId def assignLevelMVar (mvarId : MVarId) (val : Level) : TermElabM Unit := modifyThe Meta.State fun s => { s with mctx := s.mctx.assignLevel mvarId val } def withDeclName (name : Name) (x : TermElabM α) : TermElabM α := withReader (fun ctx => { ctx with declName? := name }) x def setLevelNames (levelNames : List Name) : TermElabM Unit := modify fun s => { s with levelNames := levelNames } def withLevelNames (levelNames : List Name) (x : TermElabM α) : TermElabM α := do let levelNamesSaved ← getLevelNames setLevelNames levelNames try x finally setLevelNames levelNamesSaved def withoutErrToSorry (x : TermElabM α) : TermElabM α := withReader (fun ctx => { ctx with errToSorry := false }) x /-- For testing `TermElabM` methods. The #eval command will sign the error. -/ def throwErrorIfErrors : TermElabM Unit := do if (← get).messages.hasErrors then throwError "Error(s)" def traceAtCmdPos (cls : Name) (msg : Unit → MessageData) : TermElabM Unit := withRef Syntax.missing $ trace cls msg def ppGoal (mvarId : MVarId) : TermElabM Format := Meta.ppGoal mvarId open Level (LevelElabM) def liftLevelM (x : LevelElabM α) : TermElabM α := do let ctx ← read let mctx ← getMCtx let ngen ← getNGen let lvlCtx : Level.Context := { options := (← getOptions), ref := (← getRef), autoBoundImplicit := ctx.autoBoundImplicit } match (x lvlCtx).run { ngen := ngen, mctx := mctx, levelNames := (← getLevelNames) } with | EStateM.Result.ok a newS => setMCtx newS.mctx; setNGen newS.ngen; setLevelNames newS.levelNames; pure a | EStateM.Result.error ex _ => throw ex def elabLevel (stx : Syntax) : TermElabM Level := liftLevelM $ Level.elabLevel stx /- Elaborate `x` with `stx` on the macro stack -/ def withMacroExpansion (beforeStx afterStx : Syntax) (x : TermElabM α) : TermElabM α := withMacroExpansionInfo beforeStx afterStx do withReader (fun ctx => { ctx with macroStack := { before := beforeStx, after := afterStx } :: ctx.macroStack }) x /- Add the given metavariable to the list of pending synthetic metavariables. The method `synthesizeSyntheticMVars` is used to process the metavariables on this list. -/ def registerSyntheticMVar (stx : Syntax) (mvarId : MVarId) (kind : SyntheticMVarKind) : TermElabM Unit := do modify fun s => { s with syntheticMVars := { mvarId := mvarId, stx := stx, kind := kind } :: s.syntheticMVars } def registerSyntheticMVarWithCurrRef (mvarId : MVarId) (kind : SyntheticMVarKind) : TermElabM Unit := do registerSyntheticMVar (← getRef) mvarId kind def registerMVarErrorHoleInfo (mvarId : MVarId) (ref : Syntax) : TermElabM Unit := do modify fun s => { s with mvarErrorInfos := { mvarId := mvarId, ref := ref, kind := MVarErrorKind.hole } :: s.mvarErrorInfos } def registerMVarErrorImplicitArgInfo (mvarId : MVarId) (ref : Syntax) (app : Expr) : TermElabM Unit := do modify fun s => { s with mvarErrorInfos := { mvarId := mvarId, ref := ref, kind := MVarErrorKind.implicitArg app } :: s.mvarErrorInfos } def registerMVarErrorCustomInfo (mvarId : MVarId) (ref : Syntax) (msgData : MessageData) : TermElabM Unit := do modify fun s => { s with mvarErrorInfos := { mvarId := mvarId, ref := ref, kind := MVarErrorKind.custom msgData } :: s.mvarErrorInfos } def registerCustomErrorIfMVar (e : Expr) (ref : Syntax) (msgData : MessageData) : TermElabM Unit := match e.getAppFn with | Expr.mvar mvarId _ => registerMVarErrorCustomInfo mvarId ref msgData | _ => pure () /- Auxiliary method for reporting errors of the form "... contains metavariables ...". This kind of error is thrown, for example, at `Match.lean` where elaboration cannot continue if there are metavariables in patterns. We only want to log it if we haven't logged any error so far. -/ def throwMVarError (m : MessageData) : TermElabM α := do if (← get).messages.hasErrors then throwAbortTerm else throwError m def MVarErrorInfo.logError (mvarErrorInfo : MVarErrorInfo) (extraMsg? : Option MessageData) : TermElabM Unit := do match mvarErrorInfo.kind with | MVarErrorKind.implicitArg app => do let app ← instantiateMVars app let msg : MessageData := m!"don't know how to synthesize implicit argument{indentExpr app.setAppPPExplicitForExposingMVars}" let msg := msg ++ Format.line ++ "context:" ++ Format.line ++ MessageData.ofGoal mvarErrorInfo.mvarId logErrorAt mvarErrorInfo.ref (appendExtra msg) | MVarErrorKind.hole => do let msg : MessageData := "don't know how to synthesize placeholder" let msg := msg ++ Format.line ++ "context:" ++ Format.line ++ MessageData.ofGoal mvarErrorInfo.mvarId logErrorAt mvarErrorInfo.ref (MessageData.tagged `Elab.synthPlaceholder <| appendExtra msg) | MVarErrorKind.custom msg => logErrorAt mvarErrorInfo.ref (appendExtra msg) where appendExtra (msg : MessageData) : MessageData := match extraMsg? with | none => msg | some extraMsg => msg ++ extraMsg /-- Try to log errors for the unassigned metavariables `pendingMVarIds`. Return `true` if there were "unfilled holes", and we should "abort" declaration. TODO: try to fill "all" holes using synthetic "sorry's" Remark: We only log the "unfilled holes" as new errors if no error has been logged so far. -/ def logUnassignedUsingErrorInfos (pendingMVarIds : Array MVarId) (extraMsg? : Option MessageData := none) : TermElabM Bool := do let s ← get let hasOtherErrors := s.messages.hasErrors let mut hasNewErrors := false let mut alreadyVisited : MVarIdSet := {} for mvarErrorInfo in s.mvarErrorInfos do let mvarId := mvarErrorInfo.mvarId unless alreadyVisited.contains mvarId do alreadyVisited := alreadyVisited.insert mvarId let foundError ← withMVarContext mvarId do /- The metavariable `mvarErrorInfo.mvarId` may have been assigned or delayed assigned to another metavariable that is unassigned. -/ let mvarDeps ← getMVars (mkMVar mvarId) if mvarDeps.any pendingMVarIds.contains then do unless hasOtherErrors do mvarErrorInfo.logError extraMsg? pure true else pure false if foundError then hasNewErrors := true return hasNewErrors /-- Ensure metavariables registered using `registerMVarErrorInfos` (and used in the given declaration) have been assigned. -/ def ensureNoUnassignedMVars (decl : Declaration) : TermElabM Unit := do let pendingMVarIds ← getMVarsAtDecl decl if (← logUnassignedUsingErrorInfos pendingMVarIds) then throwAbortCommand /- Execute `x` without allowing it to postpone elaboration tasks. That is, `tryPostpone` is a noop. -/ def withoutPostponing (x : TermElabM α) : TermElabM α := withReader (fun ctx => { ctx with mayPostpone := false }) x /-- Creates syntax for `(` <ident> `:` <type> `)` -/ def mkExplicitBinder (ident : Syntax) (type : Syntax) : Syntax := mkNode ``Lean.Parser.Term.explicitBinder #[mkAtom "(", mkNullNode #[ident], mkNullNode #[mkAtom ":", type], mkNullNode, mkAtom ")"] /-- Convert unassigned universe level metavariables into parameters. The new parameter names are of the form `u_i` where `i >= nextParamIdx`. The method returns the updated expression and new `nextParamIdx`. Remark: we make sure the generated parameter names do not clash with the universe at `ctx.levelNames`. -/ def levelMVarToParam (e : Expr) (nextParamIdx : Nat := 1) : TermElabM (Expr × Nat) := do let mctx ← getMCtx let levelNames ← getLevelNames let r := mctx.levelMVarToParam (fun n => levelNames.elem n) e `u nextParamIdx setMCtx r.mctx pure (r.expr, r.nextParamIdx) /-- Variant of `levelMVarToParam` where `nextParamIdx` is stored in a state monad. -/ def levelMVarToParam' (e : Expr) : StateRefT Nat TermElabM Expr := do let nextParamIdx ← get let (e, nextParamIdx) ← levelMVarToParam e nextParamIdx set nextParamIdx pure e /-- Auxiliary method for creating fresh binder names. Do not confuse with the method for creating fresh free/meta variable ids. -/ def mkFreshBinderName [Monad m] [MonadQuotation m] : m Name := withFreshMacroScope $ MonadQuotation.addMacroScope `x /-- Auxiliary method for creating a `Syntax.ident` containing a fresh name. This method is intended for creating fresh binder names. It is just a thin layer on top of `mkFreshUserName`. -/ def mkFreshIdent [Monad m] [MonadQuotation m] (ref : Syntax) : m Syntax := return mkIdentFrom ref (← mkFreshBinderName) private def applyAttributesCore (declName : Name) (attrs : Array Attribute) (applicationTime? : Option AttributeApplicationTime) : TermElabM Unit := for attr in attrs do let env ← getEnv match getAttributeImpl env attr.name with | Except.error errMsg => throwError errMsg | Except.ok attrImpl => match applicationTime? with | none => attrImpl.add declName attr.stx attr.kind | some applicationTime => if applicationTime == attrImpl.applicationTime then attrImpl.add declName attr.stx attr.kind /-- Apply given attributes **at** a given application time -/ def applyAttributesAt (declName : Name) (attrs : Array Attribute) (applicationTime : AttributeApplicationTime) : TermElabM Unit := applyAttributesCore declName attrs applicationTime def applyAttributes (declName : Name) (attrs : Array Attribute) : TermElabM Unit := applyAttributesCore declName attrs none def mkTypeMismatchError (header? : Option String) (e : Expr) (eType : Expr) (expectedType : Expr) : TermElabM MessageData := do let header : MessageData := match header? with | some header => m!"{header} " | none => m!"type mismatch{indentExpr e}\n" return m!"{header}{← mkHasTypeButIsExpectedMsg eType expectedType}" def throwTypeMismatchError (header? : Option String) (expectedType : Expr) (eType : Expr) (e : Expr) (f? : Option Expr := none) (extraMsg? : Option MessageData := none) : TermElabM α := do /- We ignore `extraMsg?` for now. In all our tests, it contained no useful information. It was always of the form: ``` failed to synthesize instance CoeT <eType> <e> <expectedType> ``` We should revisit this decision in the future and decide whether it may contain useful information or not. -/ let extraMsg := Format.nil /- let extraMsg : MessageData := match extraMsg? with | none => Format.nil | some extraMsg => Format.line ++ extraMsg; -/ match f? with | none => throwError "{← mkTypeMismatchError header? e eType expectedType}{extraMsg}" | some f => Meta.throwAppTypeMismatch f e extraMsg def withoutMacroStackAtErr (x : TermElabM α) : TermElabM α := withTheReader Core.Context (fun (ctx : Core.Context) => { ctx with options := pp.macroStack.set ctx.options false }) x namespace ContainsPendingMVar abbrev M := MonadCacheT Expr Unit (OptionT TermElabM) /-- See `containsPostponedTerm` -/ partial def visit (e : Expr) : M Unit := do checkCache e fun _ => do match e with | Expr.forallE _ d b _ => visit d; visit b | Expr.lam _ d b _ => visit d; visit b | Expr.letE _ t v b _ => visit t; visit v; visit b | Expr.app f a _ => visit f; visit a | Expr.mdata _ b _ => visit b | Expr.proj _ _ b _ => visit b | Expr.fvar fvarId .. => match (← getLocalDecl fvarId) with | LocalDecl.cdecl .. => return () | LocalDecl.ldecl (value := v) .. => visit v | Expr.mvar mvarId .. => let e' ← instantiateMVars e if e' != e then visit e' else match (← getDelayedAssignment? mvarId) with | some d => visit d.val | none => failure | _ => return () end ContainsPendingMVar /-- Return `true` if `e` contains a pending metavariable. Remark: it also visits let-declarations. -/ def containsPendingMVar (e : Expr) : TermElabM Bool := do match (← ContainsPendingMVar.visit e |>.run.run) with | some _ => return false | none => return true /- Try to synthesize metavariable using type class resolution. This method assumes the local context and local instances of `instMVar` coincide with the current local context and local instances. Return `true` if the instance was synthesized successfully, and `false` if the instance contains unassigned metavariables that are blocking the type class resolution procedure. Throw an exception if resolution or assignment irrevocably fails. -/ def synthesizeInstMVarCore (instMVar : MVarId) (maxResultSize? : Option Nat := none) : TermElabM Bool := do let instMVarDecl ← getMVarDecl instMVar let type := instMVarDecl.type let type ← instantiateMVars type let result ← trySynthInstance type maxResultSize? match result with | LOption.some val => if (← isExprMVarAssigned instMVar) then let oldVal ← instantiateMVars (mkMVar instMVar) unless (← isDefEq oldVal val) do if (← containsPendingMVar oldVal <||> containsPendingMVar val) then /- If `val` or `oldVal` contains metavariables directly or indirectly (e.g., in a let-declaration), we return `false` to indicate we should try again later. This is very course grain since the metavariable may not be responsible for the failure. We should refine the test in the future if needed. This check has been added to address dependencies between postponed metavariables. The following example demonstrates the issue fixed by this test. ``` structure Point where x : Nat y : Nat def Point.compute (p : Point) : Point := let p := { p with x := 1 } let p := { p with y := 0 } if (p.x - p.y) > p.x then p else p ``` The `isDefEq` test above fails for `Decidable (p.x - p.y ≤ p.x)` when the structure instance assigned to `p` has not been elaborated yet. -/ return false -- we will try again later let oldValType ← inferType oldVal let valType ← inferType val unless (← isDefEq oldValType valType) do throwError "synthesized type class instance type is not definitionally equal to expected type, synthesized{indentExpr val}\nhas type{indentExpr valType}\nexpected{indentExpr oldValType}" throwError "synthesized type class instance is not definitionally equal to expression inferred by typing rules, synthesized{indentExpr val}\ninferred{indentExpr oldVal}" else unless (← isDefEq (mkMVar instMVar) val) do throwError "failed to assign synthesized type class instance{indentExpr val}" pure true | LOption.undef => pure false -- we will try later | LOption.none => throwError "failed to synthesize instance{indentExpr type}" register_builtin_option autoLift : Bool := { defValue := true descr := "insert monadic lifts (i.e., `liftM` and `liftCoeM`) when needed" } register_builtin_option maxCoeSize : Nat := { defValue := 16 descr := "maximum number of instances used to construct an automatic coercion" } def synthesizeCoeInstMVarCore (instMVar : MVarId) : TermElabM Bool := do synthesizeInstMVarCore instMVar (some (maxCoeSize.get (← getOptions))) /- The coercion from `α` to `Thunk α` cannot be implemented using an instance because it would eagerly evaluate `e` -/ def tryCoeThunk? (expectedType : Expr) (eType : Expr) (e : Expr) : TermElabM (Option Expr) := do match expectedType with | Expr.app (Expr.const ``Thunk u _) arg _ => if (← isDefEq eType arg) then pure (some (mkApp2 (mkConst ``Thunk.mk u) arg (mkSimpleThunk e))) else pure none | _ => pure none def mkCoe (expectedType : Expr) (eType : Expr) (e : Expr) (f? : Option Expr := none) (errorMsgHeader? : Option String := none) : TermElabM Expr := do let u ← getLevel eType let v ← getLevel expectedType let coeTInstType := mkAppN (mkConst ``CoeT [u, v]) #[eType, e, expectedType] let mvar ← mkFreshExprMVar coeTInstType MetavarKind.synthetic let eNew := mkAppN (mkConst ``coe [u, v]) #[eType, expectedType, e, mvar] let mvarId := mvar.mvarId! try withoutMacroStackAtErr do if (← synthesizeCoeInstMVarCore mvarId) then expandCoe eNew else -- We create an auxiliary metavariable to represent the result, because we need to execute `expandCoe` -- after we syntheze `mvar` let mvarAux ← mkFreshExprMVar expectedType MetavarKind.syntheticOpaque registerSyntheticMVarWithCurrRef mvarAux.mvarId! (SyntheticMVarKind.coe errorMsgHeader? eNew expectedType eType e f?) return mvarAux catch | Exception.error _ msg => throwTypeMismatchError errorMsgHeader? expectedType eType e f? msg | _ => throwTypeMismatchError errorMsgHeader? expectedType eType e f? /-- Try to apply coercion to make sure `e` has type `expectedType`. Relevant definitions: ``` class CoeT (α : Sort u) (a : α) (β : Sort v) abbrev coe {α : Sort u} {β : Sort v} (a : α) [CoeT α a β] : β ``` -/ private def tryCoe (errorMsgHeader? : Option String) (expectedType : Expr) (eType : Expr) (e : Expr) (f? : Option Expr) : TermElabM Expr := do if (← isDefEq expectedType eType) then return e else match (← tryCoeThunk? expectedType eType e) with | some r => return r | none => mkCoe expectedType eType e f? errorMsgHeader? def isTypeApp? (type : Expr) : TermElabM (Option (Expr × Expr)) := do let type ← withReducible $ whnf type match type with | Expr.app m α _ => pure (some ((← instantiateMVars m), (← instantiateMVars α))) | _ => pure none def synthesizeInst (type : Expr) : TermElabM Expr := do let type ← instantiateMVars type match (← trySynthInstance type) with | LOption.some val => pure val | LOption.undef => throwError "failed to synthesize instance{indentExpr type}" | LOption.none => throwError "failed to synthesize instance{indentExpr type}" def isMonadApp (type : Expr) : TermElabM Bool := do let some (m, _) ← isTypeApp? type | pure false return (← isMonad? m) |>.isSome /-- Try to coerce `a : α` into `m β` by first coercing `a : α` into ‵β`, and then using `pure`. The method is only applied if `α` is not monadic (e.g., `Nat → IO Unit`), and the head symbol of the resulting type is not a metavariable (e.g., `?m Unit` or `Bool → ?m Nat`). The main limitation of the approach above is polymorphic code. As usual, coercions and polymorphism do not interact well. In the example above, the lift is successfully applied to `true`, `false` and `!y` since none of them is polymorphic ``` def f (x : Bool) : IO Bool := do let y ← if x == 0 then IO.println "hello"; true else false; !y ``` On the other hand, the following fails since `+` is polymorphic ``` def f (x : Bool) : IO Nat := do IO.prinln x x + x -- Error: failed to synthesize `Add (IO Nat)` ``` -/ private def tryPureCoe? (errorMsgHeader? : Option String) (m β α a : Expr) : TermElabM (Option Expr) := commitWhenSome? do let doIt : TermElabM (Option Expr) := do try let aNew ← tryCoe errorMsgHeader? β α a none let aNew ← mkPure m aNew pure (some aNew) catch _ => pure none forallTelescope α fun _ α => do if (← isMonadApp α) then pure none else if !α.getAppFn.isMVar then doIt else pure none /- Try coercions and monad lifts to make sure `e` has type `expectedType`. If `expectedType` is of the form `n β`, we try monad lifts and other extensions. Otherwise, we just use the basic `tryCoe`. Extensions for monads. Given an expected type of the form `n β`, if `eType` is of the form `α`, but not `m α` 1 - Try to coerce ‵α` into ‵β`, and use `pure` to lift it to `n α`. It only works if `n` implements `Pure` If `eType` is of the form `m α`. We use the following approaches. 1- Try to unify `n` and `m`. If it succeeds, then we use ``` coeM {m : Type u → Type v} {α β : Type u} [∀ a, CoeT α a β] [Monad m] (x : m α) : m β ``` `n` must be a `Monad` to use this one. 2- If there is monad lift from `m` to `n` and we can unify `α` and `β`, we use ``` liftM : ∀ {m : Type u_1 → Type u_2} {n : Type u_1 → Type u_3} [self : MonadLiftT m n] {α : Type u_1}, m α → n α ``` Note that `n` may not be a `Monad` in this case. This happens quite a bit in code such as ``` def g (x : Nat) : IO Nat := do IO.println x pure x def f {m} [MonadLiftT IO m] : m Nat := g 10 ``` 3- If there is a monad lif from `m` to `n` and a coercion from `α` to `β`, we use ``` liftCoeM {m : Type u → Type v} {n : Type u → Type w} {α β : Type u} [MonadLiftT m n] [∀ a, CoeT α a β] [Monad n] (x : m α) : n β ``` Note that approach 3 does not subsume 1 because it is only applicable if there is a coercion from `α` to `β` for all values in `α`. This is not the case for example for `pure $ x > 0` when the expected type is `IO Bool`. The given type is `IO Prop`, and we only have a coercion from decidable propositions. Approach 1 works because it constructs the coercion `CoeT (m Prop) (pure $ x > 0) (m Bool)` using the instance `pureCoeDepProp`. Note that, approach 2 is more powerful than `tryCoe`. Recall that type class resolution never assigns metavariables created by other modules. Now, consider the following scenario ```lean def g (x : Nat) : IO Nat := ... deg h (x : Nat) : StateT Nat IO Nat := do v ← g x; IO.Println v; ... ``` Let's assume there is no other occurrence of `v` in `h`. Thus, we have that the expected of `g x` is `StateT Nat IO ?α`, and the given type is `IO Nat`. So, even if we add a coercion. ``` instance {α m n} [MonadLiftT m n] {α} : Coe (m α) (n α) := ... ``` It is not applicable because TC would have to assign `?α := Nat`. On the other hand, TC can easily solve `[MonadLiftT IO (StateT Nat IO)]` since this goal does not contain any metavariables. And then, we convert `g x` into `liftM $ g x`. -/ private def tryLiftAndCoe (errorMsgHeader? : Option String) (expectedType : Expr) (eType : Expr) (e : Expr) (f? : Option Expr) : TermElabM Expr := do let expectedType ← instantiateMVars expectedType let eType ← instantiateMVars eType let throwMismatch {α} : TermElabM α := throwTypeMismatchError errorMsgHeader? expectedType eType e f? let tryCoeSimple : TermElabM Expr := tryCoe errorMsgHeader? expectedType eType e f? let some (n, β) ← isTypeApp? expectedType | tryCoeSimple let tryPureCoeAndSimple : TermElabM Expr := do if autoLift.get (← getOptions) then match (← tryPureCoe? errorMsgHeader? n β eType e) with | some eNew => pure eNew | none => tryCoeSimple else tryCoeSimple let some (m, α) ← isTypeApp? eType | tryPureCoeAndSimple if (← isDefEq m n) then let some monadInst ← isMonad? n | tryCoeSimple try expandCoe (← mkAppOptM ``coeM #[m, α, β, none, monadInst, e]) catch _ => throwMismatch else if autoLift.get (← getOptions) then try -- Construct lift from `m` to `n` let monadLiftType ← mkAppM ``MonadLiftT #[m, n] let monadLiftVal ← synthesizeInst monadLiftType let u_1 ← getDecLevel α let u_2 ← getDecLevel eType let u_3 ← getDecLevel expectedType let eNew := mkAppN (Lean.mkConst ``liftM [u_1, u_2, u_3]) #[m, n, monadLiftVal, α, e] let eNewType ← inferType eNew if (← isDefEq expectedType eNewType) then return eNew -- approach 2 worked else let some monadInst ← isMonad? n | tryCoeSimple let u ← getLevel α let v ← getLevel β let coeTInstType := Lean.mkForall `a BinderInfo.default α $ mkAppN (mkConst ``CoeT [u, v]) #[α, mkBVar 0, β] let coeTInstVal ← synthesizeInst coeTInstType let eNew ← expandCoe (← mkAppN (Lean.mkConst ``liftCoeM [u_1, u_2, u_3]) #[m, n, α, β, monadLiftVal, coeTInstVal, monadInst, e]) let eNewType ← inferType eNew unless (← isDefEq expectedType eNewType) do throwMismatch return eNew -- approach 3 worked catch _ => /- If `m` is not a monad, then we try to use `tryPureCoe?` and then `tryCoe?`. Otherwise, we just try `tryCoe?`. -/ match (← isMonad? m) with | none => tryPureCoeAndSimple | some _ => tryCoeSimple else tryCoeSimple /-- If `expectedType?` is `some t`, then ensure `t` and `eType` are definitionally equal. If they are not, then try coercions. Argument `f?` is used only for generating error messages. -/ def ensureHasTypeAux (expectedType? : Option Expr) (eType : Expr) (e : Expr) (f? : Option Expr := none) (errorMsgHeader? : Option String := none) : TermElabM Expr := do match expectedType? with | none => pure e | some expectedType => if (← isDefEq eType expectedType) then pure e else tryLiftAndCoe errorMsgHeader? expectedType eType e f? /-- If `expectedType?` is `some t`, then ensure `t` and type of `e` are definitionally equal. If they are not, then try coercions. -/ def ensureHasType (expectedType? : Option Expr) (e : Expr) (errorMsgHeader? : Option String := none) : TermElabM Expr := match expectedType? with | none => pure e | _ => do let eType ← inferType e ensureHasTypeAux expectedType? eType e none errorMsgHeader? private def mkSyntheticSorryFor (expectedType? : Option Expr) : TermElabM Expr := do let expectedType ← match expectedType? with | none => mkFreshTypeMVar | some expectedType => pure expectedType mkSyntheticSorry expectedType private def exceptionToSorry (ex : Exception) (expectedType? : Option Expr) : TermElabM Expr := do let syntheticSorry ← mkSyntheticSorryFor expectedType? logException ex pure syntheticSorry /-- If `mayPostpone == true`, throw `Expection.postpone`. -/ def tryPostpone : TermElabM Unit := do if (← read).mayPostpone then throwPostpone /-- If `mayPostpone == true` and `e`'s head is a metavariable, throw `Exception.postpone`. -/ def tryPostponeIfMVar (e : Expr) : TermElabM Unit := do if e.getAppFn.isMVar then let e ← instantiateMVars e if e.getAppFn.isMVar then tryPostpone def tryPostponeIfNoneOrMVar (e? : Option Expr) : TermElabM Unit := match e? with | some e => tryPostponeIfMVar e | none => tryPostpone def tryPostponeIfHasMVars (expectedType? : Option Expr) (msg : String) : TermElabM Expr := do tryPostponeIfNoneOrMVar expectedType? let some expectedType ← pure expectedType? | throwError "{msg}, expected type must be known" let expectedType ← instantiateMVars expectedType if expectedType.hasExprMVar then tryPostpone throwError "{msg}, expected type contains metavariables{indentExpr expectedType}" pure expectedType def saveContext : TermElabM SavedContext := return { macroStack := (← read).macroStack declName? := (← read).declName? options := (← getOptions) openDecls := (← getOpenDecls) errToSorry := (← read).errToSorry } def withSavedContext (savedCtx : SavedContext) (x : TermElabM α) : TermElabM α := do withReader (fun ctx => { ctx with declName? := savedCtx.declName?, macroStack := savedCtx.macroStack, errToSorry := savedCtx.errToSorry }) <| withTheReader Core.Context (fun ctx => { ctx with options := savedCtx.options, openDecls := savedCtx.openDecls }) x private def postponeElabTerm (stx : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do trace[Elab.postpone] "{stx} : {expectedType?}" let mvar ← mkFreshExprMVar expectedType? MetavarKind.syntheticOpaque let ctx ← read registerSyntheticMVar stx mvar.mvarId! (SyntheticMVarKind.postponed (← saveContext)) pure mvar def getSyntheticMVarDecl? (mvarId : MVarId) : TermElabM (Option SyntheticMVarDecl) := return (← get).syntheticMVars.find? fun d => d.mvarId == mvarId def mkTermInfo (elaborator : Name) (stx : Syntax) (e : Expr) (expectedType? : Option Expr := none) (lctx? : Option LocalContext := none) (isBinder := false) : TermElabM (Sum Info MVarId) := do let isHole? : TermElabM (Option MVarId) := do match e with | Expr.mvar mvarId _ => match (← getSyntheticMVarDecl? mvarId) with | some { kind := SyntheticMVarKind.tactic .., .. } => return mvarId | some { kind := SyntheticMVarKind.postponed .., .. } => return mvarId | _ => return none | _ => pure none match (← isHole?) with | none => return Sum.inl <| Info.ofTermInfo { elaborator, lctx := lctx?.getD (← getLCtx), expr := e, stx, expectedType?, isBinder } | some mvarId => return Sum.inr mvarId def addTermInfo (stx : Syntax) (e : Expr) (expectedType? : Option Expr := none) (lctx? : Option LocalContext := none) (elaborator := Name.anonymous) (isBinder := false) : TermElabM Unit := do withInfoContext' (pure ()) (fun _ => mkTermInfo elaborator stx e expectedType? lctx? isBinder) |> discard /- Helper function for `elabTerm` is tries the registered elaboration functions for `stxNode` kind until it finds one that supports the syntax or an error is found. -/ private def elabUsingElabFnsAux (s : SavedState) (stx : Syntax) (expectedType? : Option Expr) (catchExPostpone : Bool) : List (KeyedDeclsAttribute.AttributeEntry TermElab) → TermElabM Expr | [] => do throwError "unexpected syntax{indentD stx}" | (elabFn::elabFns) => try -- record elaborator in info tree, but only when not backtracking to other elaborators (outer `try`) withInfoContext' (mkInfo := mkTermInfo elabFn.decl (expectedType? := expectedType?) stx) (try elabFn.value stx expectedType? catch ex => match ex with | Exception.error ref msg => if (← read).errToSorry then exceptionToSorry ex expectedType? else throw ex | Exception.internal id _ => if (← read).errToSorry && id == abortTermExceptionId then exceptionToSorry ex expectedType? else if id == unsupportedSyntaxExceptionId then throw ex -- to outer try else if catchExPostpone && id == postponeExceptionId then /- If `elab` threw `Exception.postpone`, we reset any state modifications. For example, we want to make sure pending synthetic metavariables created by `elab` before it threw `Exception.postpone` are discarded. Note that we are also discarding the messages created by `elab`. For example, consider the expression. `((f.x a1).x a2).x a3` Now, suppose the elaboration of `f.x a1` produces an `Exception.postpone`. Then, a new metavariable `?m` is created. Then, `?m.x a2` also throws `Exception.postpone` because the type of `?m` is not yet known. Then another, metavariable `?n` is created, and finally `?n.x a3` also throws `Exception.postpone`. If we did not restore the state, we would keep "dead" metavariables `?m` and `?n` on the pending synthetic metavariable list. This is wasteful because when we resume the elaboration of `((f.x a1).x a2).x a3`, we start it from scratch and new metavariables are created for the nested functions. -/ s.restore postponeElabTerm stx expectedType? else throw ex) catch ex => match ex with | Exception.internal id _ => if id == unsupportedSyntaxExceptionId then s.restore -- also removes the info tree created above elabUsingElabFnsAux s stx expectedType? catchExPostpone elabFns else throw ex | _ => throw ex private def elabUsingElabFns (stx : Syntax) (expectedType? : Option Expr) (catchExPostpone : Bool) : TermElabM Expr := do let s ← saveState let k := stx.getKind match termElabAttribute.getEntries (← getEnv) k with | [] => throwError "elaboration function for '{k}' has not been implemented{indentD stx}" | elabFns => elabUsingElabFnsAux s stx expectedType? catchExPostpone elabFns instance : MonadMacroAdapter TermElabM where getCurrMacroScope := getCurrMacroScope getNextMacroScope := return (← getThe Core.State).nextMacroScope setNextMacroScope next := modifyThe Core.State fun s => { s with nextMacroScope := next } private def isExplicit (stx : Syntax) : Bool := match stx with | `(@$f) => true | _ => false private def isExplicitApp (stx : Syntax) : Bool := stx.getKind == ``Lean.Parser.Term.app && isExplicit stx[0] /-- Return true if `stx` if a lambda abstraction containing a `{}` or `[]` binder annotation. Example: `fun {α} (a : α) => a` -/ private def isLambdaWithImplicit (stx : Syntax) : Bool := match stx with | `(fun $binders* => $body) => binders.any fun b => b.isOfKind ``Lean.Parser.Term.implicitBinder || b.isOfKind `Lean.Parser.Term.instBinder | _ => false private partial def dropTermParens : Syntax → Syntax := fun stx => match stx with | `(($stx)) => dropTermParens stx | _ => stx private def isHole (stx : Syntax) : Bool := match stx with | `(_) => true | `(? _) => true | `(? $x:ident) => true | _ => false private def isTacticBlock (stx : Syntax) : Bool := match stx with | `(by $x:tacticSeq) => true | _ => false private def isNoImplicitLambda (stx : Syntax) : Bool := match stx with | `(noImplicitLambda% $x:term) => true | _ => false private def isTypeAscription (stx : Syntax) : Bool := match stx with | `(($e : $type)) => true | _ => false def mkNoImplicitLambdaAnnotation (type : Expr) : Expr := mkAnnotation `noImplicitLambda type def hasNoImplicitLambdaAnnotation (type : Expr) : Bool := annotation? `noImplicitLambda type |>.isSome /-- Block usage of implicit lambdas if `stx` is `@f` or `@f arg1 ...` or `fun` with an implicit binder annotation. -/ def blockImplicitLambda (stx : Syntax) : Bool := let stx := dropTermParens stx -- TODO: make it extensible isExplicit stx || isExplicitApp stx || isLambdaWithImplicit stx || isHole stx || isTacticBlock stx || isNoImplicitLambda stx || isTypeAscription stx /-- Return normalized expected type if it is of the form `{a : α} → β` or `[a : α] → β` and `blockImplicitLambda stx` is not true, else return `none`. Remark: implicit lambdas are not triggered by the strict implicit binder annotation `{{a : α}} → β` -/ private def useImplicitLambda? (stx : Syntax) (expectedType? : Option Expr) : TermElabM (Option Expr) := if blockImplicitLambda stx then return none else match expectedType? with | some expectedType => do if hasNoImplicitLambdaAnnotation expectedType then return none else let expectedType ← whnfForall expectedType match expectedType with | Expr.forallE _ _ _ c => if c.binderInfo.isImplicit || c.binderInfo.isInstImplicit then return some expectedType else return none | _ => return none | _ => return none private def decorateErrorMessageWithLambdaImplicitVars (ex : Exception) (impFVars : Array Expr) : TermElabM Exception := do match ex with | Exception.error ref msg => if impFVars.isEmpty then return Exception.error ref msg else let mut msg := m!"{msg}\nthe following variables have been introduced by the implicit lamda feature" for impFVar in impFVars do let auxMsg := m!"{impFVar} : {← inferType impFVar}" let auxMsg ← addMessageContext auxMsg msg := m!"{msg}{indentD auxMsg}" msg := m!"{msg}\nyou can disable implict lambdas using `@` or writing a lambda expression with `\{}` or `[]` binder annotations." return Exception.error ref msg | _ => return ex private def elabImplicitLambdaAux (stx : Syntax) (catchExPostpone : Bool) (expectedType : Expr) (impFVars : Array Expr) : TermElabM Expr := do let body ← elabUsingElabFns stx expectedType catchExPostpone try let body ← ensureHasType expectedType body let r ← mkLambdaFVars impFVars body trace[Elab.implicitForall] r pure r catch ex => throw (← decorateErrorMessageWithLambdaImplicitVars ex impFVars) private partial def elabImplicitLambda (stx : Syntax) (catchExPostpone : Bool) (type : Expr) : TermElabM Expr := loop type #[] where loop | type@(Expr.forallE n d b c), fvars => if c.binderInfo.isExplicit then elabImplicitLambdaAux stx catchExPostpone type fvars else withFreshMacroScope do let n ← MonadQuotation.addMacroScope n withLocalDecl n c.binderInfo d fun fvar => do let type ← whnfForall (b.instantiate1 fvar) loop type (fvars.push fvar) | type, fvars => elabImplicitLambdaAux stx catchExPostpone type fvars /- Main loop for `elabTerm` -/ private partial def elabTermAux (expectedType? : Option Expr) (catchExPostpone : Bool) (implicitLambda : Bool) : Syntax → TermElabM Expr | Syntax.missing => mkSyntheticSorryFor expectedType? | stx => withFreshMacroScope <| withIncRecDepth do trace[Elab.step] "expected type: {expectedType?}, term\n{stx}" checkMaxHeartbeats "elaborator" withNestedTraces do let env ← getEnv match (← liftMacroM (expandMacroImpl? env stx)) with | some (decl, stxNew) => withInfoContext' (mkInfo := mkTermInfo decl (expectedType? := expectedType?) stx) <| withMacroExpansion stx stxNew <| withRef stxNew <| elabTermAux expectedType? catchExPostpone implicitLambda stxNew | _ => let implicit? ← if implicitLambda && (← read).implicitLambda then useImplicitLambda? stx expectedType? else pure none match implicit? with | some expectedType => elabImplicitLambda stx catchExPostpone expectedType | none => elabUsingElabFns stx expectedType? catchExPostpone /-- Store in the `InfoTree` that `e` is a "dot"-completion target. -/ def addDotCompletionInfo (stx : Syntax) (e : Expr) (expectedType? : Option Expr) (field? : Option Syntax := none) : TermElabM Unit := do addCompletionInfo <| CompletionInfo.dot { expr := e, stx, lctx := (← getLCtx), elaborator := Name.anonymous, expectedType? } (field? := field?) (expectedType? := expectedType?) /-- Main function for elaborating terms. It extracts the elaboration methods from the environment using the node kind. Recall that the environment has a mapping from `SyntaxNodeKind` to `TermElab` methods. It creates a fresh macro scope for executing the elaboration method. All unlogged trace messages produced by the elaboration method are logged using the position information at `stx`. If the elaboration method throws an `Exception.error` and `errToSorry == true`, the error is logged and a synthetic sorry expression is returned. If the elaboration throws `Exception.postpone` and `catchExPostpone == true`, a new synthetic metavariable of kind `SyntheticMVarKind.postponed` is created, registered, and returned. The option `catchExPostpone == false` is used to implement `resumeElabTerm` to prevent the creation of another synthetic metavariable when resuming the elaboration. If `implicitLambda == true`, then disable implicit lambdas feature for the given syntax, but not for its subterms. We use this flag to implement, for example, the `@` modifier. If `Context.implicitLambda == false`, then this parameter has no effect. -/ def elabTerm (stx : Syntax) (expectedType? : Option Expr) (catchExPostpone := true) (implicitLambda := true) : TermElabM Expr := withRef stx <| elabTermAux expectedType? catchExPostpone implicitLambda stx def elabTermEnsuringType (stx : Syntax) (expectedType? : Option Expr) (catchExPostpone := true) (implicitLambda := true) (errorMsgHeader? : Option String := none) : TermElabM Expr := do let e ← elabTerm stx expectedType? catchExPostpone implicitLambda withRef stx <| ensureHasType expectedType? e errorMsgHeader? /-- Execute `x` and then restore `syntheticMVars`, `levelNames`, `mvarErrorInfos`, and `letRecsToLift`. We use this combinator when we don't want the pending problems created by `x` to persist after its execution. -/ def withoutPending (x : TermElabM α) : TermElabM α := do let saved ← get try x finally modify fun s => { s with syntheticMVars := saved.syntheticMVars, levelNames := saved.levelNames, letRecsToLift := saved.letRecsToLift, mvarErrorInfos := saved.mvarErrorInfos } /-- Execute `x` and return `some` if no new errors were recorded or exceptions was thrown. Otherwise, return `none` -/ def commitIfNoErrors? (x : TermElabM α) : TermElabM (Option α) := do let saved ← saveState modify fun s => { s with messages := {} } try let a ← x if (← get).messages.hasErrors then restoreState saved return none else modify fun s => { s with messages := saved.elab.messages ++ s.messages } return a catch _ => restoreState saved return none /-- Adapt a syntax transformation to a regular, term-producing elaborator. -/ def adaptExpander (exp : Syntax → TermElabM Syntax) : TermElab := fun stx expectedType? => do let stx' ← exp stx withMacroExpansion stx stx' $ elabTerm stx' expectedType? def mkInstMVar (type : Expr) : TermElabM Expr := do let mvar ← mkFreshExprMVar type MetavarKind.synthetic let mvarId := mvar.mvarId! unless (← synthesizeInstMVarCore mvarId) do registerSyntheticMVarWithCurrRef mvarId SyntheticMVarKind.typeClass pure mvar /- Relevant definitions: ``` class CoeSort (α : Sort u) (β : outParam (Sort v)) abbrev coeSort {α : Sort u} {β : Sort v} (a : α) [CoeSort α β] : β ``` -/ private def tryCoeSort (α : Expr) (a : Expr) : TermElabM Expr := do let β ← mkFreshTypeMVar let u ← getLevel α let v ← getLevel β let coeSortInstType := mkAppN (Lean.mkConst ``CoeSort [u, v]) #[α, β] let mvar ← mkFreshExprMVar coeSortInstType MetavarKind.synthetic let mvarId := mvar.mvarId! try withoutMacroStackAtErr do if (← synthesizeCoeInstMVarCore mvarId) then let result ← expandCoe <| mkAppN (Lean.mkConst ``coeSort [u, v]) #[α, β, a, mvar] unless (← isType result) do throwError "failed to coerse{indentExpr a}\nto a type, after applying `coeSort`, result is still not a type{indentExpr result}\nthis is often due to incorrect `CoeSort` instances, the synthesized value for{indentExpr coeSortInstType}\nwas{indentExpr mvar}" return result else throwError "type expected" catch | Exception.error _ msg => throwError "type expected\n{msg}" | _ => throwError "type expected" /-- Make sure `e` is a type by inferring its type and making sure it is a `Expr.sort` or is unifiable with `Expr.sort`, or can be coerced into one. -/ def ensureType (e : Expr) : TermElabM Expr := do if (← isType e) then pure e else let eType ← inferType e let u ← mkFreshLevelMVar if (← isDefEq eType (mkSort u)) then pure e else tryCoeSort eType e /-- Elaborate `stx` and ensure result is a type. -/ def elabType (stx : Syntax) : TermElabM Expr := do let u ← mkFreshLevelMVar let type ← elabTerm stx (mkSort u) withRef stx $ ensureType type /-- Enable auto-bound implicits, and execute `k` while catching auto bound implicit exceptions. When an exception is caught, a new local declaration is created, registered, and `k` is tried to be executed again. -/ partial def withAutoBoundImplicit (k : TermElabM α) : TermElabM α := do let flag := autoBoundImplicitLocal.get (← getOptions) if flag then withReader (fun ctx => { ctx with autoBoundImplicit := flag, autoBoundImplicits := {} }) do let rec loop (s : SavedState) : TermElabM α := do try k catch | ex => match isAutoBoundImplicitLocalException? ex with | some n => -- Restore state, declare `n`, and try again s.restore withLocalDecl n BinderInfo.implicit (← mkFreshTypeMVar) fun x => withReader (fun ctx => { ctx with autoBoundImplicits := ctx.autoBoundImplicits.push x } ) do loop (← saveState) | none => throw ex loop (← saveState) else k def withoutAutoBoundImplicit (k : TermElabM α) : TermElabM α := do withReader (fun ctx => { ctx with autoBoundImplicit := false, autoBoundImplicits := {} }) k /-- Return `autoBoundImplicits ++ xs. This methoid throws an error if a variable in `autoBoundImplicits` depends on some `x` in `xs` -/ def addAutoBoundImplicits (xs : Array Expr) : TermElabM (Array Expr) := do let autoBoundImplicits := (← read).autoBoundImplicits for auto in autoBoundImplicits do let localDecl ← getLocalDecl auto.fvarId! for x in xs do if (← getMCtx).localDeclDependsOn localDecl x.fvarId! then throwError "invalid auto implicit argument '{auto}', it depends on explicitly provided argument '{x}'" return autoBoundImplicits.toArray ++ xs def mkAuxName (suffix : Name) : TermElabM Name := do match (← read).declName? with | none => throwError "auxiliary declaration cannot be created when declaration name is not available" | some declName => Lean.mkAuxName (declName ++ suffix) 1 builtin_initialize registerTraceClass `Elab.letrec /- Return true if mvarId is an auxiliary metavariable created for compiling `let rec` or it is delayed assigned to one. -/ def isLetRecAuxMVar (mvarId : MVarId) : TermElabM Bool := do trace[Elab.letrec] "mvarId: {mkMVar mvarId} letrecMVars: {(← get).letRecsToLift.map (mkMVar $ ·.mvarId)}" let mvarId := (← getMCtx).getDelayedRoot mvarId trace[Elab.letrec] "mvarId root: {mkMVar mvarId}" return (← get).letRecsToLift.any (·.mvarId == mvarId) def resolveLocalName (n : Name) : TermElabM (Option (Expr × List String)) := do let lctx ← getLCtx let view := extractMacroScopes n let rec loop (n : Name) (projs : List String) := match lctx.findFromUserName? { view with name := n }.review with | some decl => if decl.isAuxDecl && !projs.isEmpty then /- We do not consider dot notation for local decls corresponding to recursive functions being defined. The following example would not be elaborated correctly without this case. ``` def foo.aux := 1 def foo : Nat → Nat | n => foo.aux -- should not be interpreted as `(foo).bar` ``` -/ none else some (decl.toExpr, projs) | none => match n with | Name.str pre s _ => loop pre (s::projs) | _ => none return loop view.name [] /- Return true iff `stx` is a `Syntax.ident`, and it is a local variable. -/ def isLocalIdent? (stx : Syntax) : TermElabM (Option Expr) := match stx with | Syntax.ident _ _ val _ => do let r? ← resolveLocalName val match r? with | some (fvar, []) => pure (some fvar) | _ => pure none | _ => pure none /-- Create an `Expr.const` using the given name and explicit levels. Remark: fresh universe metavariables are created if the constant has more universe parameters than `explicitLevels`. -/ def mkConst (constName : Name) (explicitLevels : List Level := []) : TermElabM Expr := do let cinfo ← getConstInfo constName if explicitLevels.length > cinfo.levelParams.length then throwError "too many explicit universe levels for '{constName}'" else let numMissingLevels := cinfo.levelParams.length - explicitLevels.length let us ← mkFreshLevelMVars numMissingLevels pure $ Lean.mkConst constName (explicitLevels ++ us) private def mkConsts (candidates : List (Name × List String)) (explicitLevels : List Level) : TermElabM (List (Expr × List String)) := do candidates.foldlM (init := []) fun result (constName, projs) => do -- TODO: better suppor for `mkConst` failure. We may want to cache the failures, and report them if all candidates fail. let const ← mkConst constName explicitLevels return (const, projs) :: result def resolveName (stx : Syntax) (n : Name) (preresolved : List (Name × List String)) (explicitLevels : List Level) (expectedType? : Option Expr := none) : TermElabM (List (Expr × List String)) := do try if let some (e, projs) ← resolveLocalName n then unless explicitLevels.isEmpty do throwError "invalid use of explicit universe parameters, '{e}' is a local" return [(e, projs)] -- check for section variable capture by a quotation let ctx ← read if let some (e, projs) := preresolved.findSome? fun (n, projs) => ctx.sectionFVars.find? n |>.map (·, projs) then return [(e, projs)] -- section variables should shadow global decls if preresolved.isEmpty then process (← resolveGlobalName n) else process preresolved catch ex => if preresolved.isEmpty && explicitLevels.isEmpty then addCompletionInfo <| CompletionInfo.id stx stx.getId (danglingDot := false) (← getLCtx) expectedType? throw ex where process (candidates : List (Name × List String)) : TermElabM (List (Expr × List String)) := do if candidates.isEmpty then if (← read).autoBoundImplicit && isValidAutoBoundImplicitName n then throwAutoBoundImplicitLocal n else throwError "unknown identifier '{Lean.mkConst n}'" if preresolved.isEmpty && explicitLevels.isEmpty then addCompletionInfo <| CompletionInfo.id stx stx.getId (danglingDot := false) (← getLCtx) expectedType? mkConsts candidates explicitLevels /-- Similar to `resolveName`, but creates identifiers for the main part and each projection with position information derived from `ident`. Example: Assume resolveName `v.head.bla.boo` produces `(v.head, ["bla", "boo"])`, then this method produces `(v.head, id, [f₁, f₂])` where `id` is an identifier for `v.head`, and `f₁` and `f₂` are identifiers for fields `"bla"` and `"boo"`. -/ def resolveName' (ident : Syntax) (explicitLevels : List Level) (expectedType? : Option Expr := none) : TermElabM (List (Expr × Syntax × List Syntax)) := do match ident with | Syntax.ident info rawStr n preresolved => let r ← resolveName ident n preresolved explicitLevels expectedType? r.mapM fun (c, fields) => do let ids := ident.identComponents (nFields? := fields.length) return (c, ids.head!, ids.tail!) | _ => throwError "identifier expected" def resolveId? (stx : Syntax) (kind := "term") (withInfo := false) : TermElabM (Option Expr) := match stx with | Syntax.ident _ _ val preresolved => do let rs ← try resolveName stx val preresolved [] catch _ => pure [] let rs := rs.filter fun ⟨f, projs⟩ => projs.isEmpty let fs := rs.map fun (f, _) => f match fs with | [] => pure none | [f] => if withInfo then addTermInfo stx f pure (some f) | _ => throwError "ambiguous {kind}, use fully qualified name, possible interpretations {fs}" | _ => throwError "identifier expected" private def mkSomeContext : Context := { fileName := "<TermElabM>" fileMap := arbitrary } def TermElabM.run (x : TermElabM α) (ctx : Context := mkSomeContext) (s : State := {}) : MetaM (α × State) := withConfig setElabConfig (x ctx |>.run s) @[inline] def TermElabM.run' (x : TermElabM α) (ctx : Context := mkSomeContext) (s : State := {}) : MetaM α := (·.1) <$> x.run ctx s def TermElabM.toIO (x : TermElabM α) (ctxCore : Core.Context) (sCore : Core.State) (ctxMeta : Meta.Context) (sMeta : Meta.State) (ctx : Context) (s : State) : IO (α × Core.State × Meta.State × State) := do let ((a, s), sCore, sMeta) ← (x.run ctx s).toIO ctxCore sCore ctxMeta sMeta pure (a, sCore, sMeta, s) instance [MetaEval α] : MetaEval (TermElabM α) where eval env opts x _ := let x : TermElabM α := do try x finally let s ← get s.messages.forM fun msg => do IO.println (← msg.toString) MetaEval.eval env opts (hideUnit := true) $ x.run' mkSomeContext unsafe def evalExpr (α) (typeName : Name) (value : Expr) : TermElabM α := withoutModifyingEnv do let name ← mkFreshUserName `_tmp let type ← inferType value let type ← whnfD type unless type.isConstOf typeName do throwError "unexpected type at evalExpr{indentExpr type}" let decl := Declaration.defnDecl { name := name, levelParams := [], type := type, value := value, hints := ReducibilityHints.opaque, safety := DefinitionSafety.unsafe } ensureNoUnassignedMVars decl addAndCompile decl evalConst α name private def throwStuckAtUniverseCnstr : TermElabM Unit := do -- This code assumes `entries` is not empty. Note that `processPostponed` uses `exceptionOnFailure` to guarantee this property let entries ← getPostponed let mut found : Std.HashSet (Level × Level) := {} let mut uniqueEntries := #[] for entry in entries do let mut lhs := entry.lhs let mut rhs := entry.rhs if Level.normLt rhs lhs then (lhs, rhs) := (rhs, lhs) unless found.contains (lhs, rhs) do found := found.insert (lhs, rhs) uniqueEntries := uniqueEntries.push entry for i in [1:uniqueEntries.size] do logErrorAt uniqueEntries[i].ref (← mkLevelStuckErrorMessage uniqueEntries[i]) throwErrorAt uniqueEntries[0].ref (← mkLevelStuckErrorMessage uniqueEntries[0]) def withoutPostponingUniverseConstraints (x : TermElabM α) : TermElabM α := do let postponed ← getResetPostponed try let a ← x unless (← processPostponed (mayPostpone := false) (exceptionOnFailure := true)) do throwStuckAtUniverseCnstr setPostponed postponed return a catch ex => setPostponed postponed throw ex end Term open Term in def withoutModifyingStateWithInfoAndMessages [MonadControlT TermElabM m] [Monad m] (x : m α) : m α := do controlAt TermElabM fun runInBase => withoutModifyingStateWithInfoAndMessagesImpl <| runInBase x builtin_initialize registerTraceClass `Elab.postpone registerTraceClass `Elab.coe registerTraceClass `Elab.debug export Term (TermElabM) end Lean.Elab
0f96ac630118f27d7e5de9cdf9044bf297d28f33
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/analysis/hofer_auto.lean
ebcb46e837a8adf53a3ed4f0e2120328af0b386a
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
1,247
lean
/- Copyright (c) 2020 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.analysis.specific_limits import Mathlib.PostPort universes u_1 namespace Mathlib /-! # Hofer's lemma This is an elementary lemma about complete metric spaces. It is motivated by an application to the bubbling-off analysis for holomorphic curves in symplectic topology. We are *very* far away from having these applications, but the proof here is a nice example of a proof needing to construct a sequence by induction in the middle of the proof. ## References: * H. Hofer and C. Viterbo, *The Weinstein conjecture in the presence of holomorphic spheres* -/ theorem hofer {X : Type u_1} [metric_space X] [complete_space X] (x : X) (ε : ℝ) (ε_pos : 0 < ε) {ϕ : X → ℝ} (cont : continuous ϕ) (nonneg : ∀ (y : X), 0 ≤ ϕ y) : ∃ (ε' : ℝ), ∃ (H : ε' > 0), ∃ (x' : X), ε' ≤ ε ∧ dist x' x ≤ bit0 1 * ε ∧ ε * ϕ x ≤ ε' * ϕ x' ∧ ∀ (y : X), dist x' y ≤ ε' → ϕ y ≤ bit0 1 * ϕ x' := sorry end Mathlib
287b3cabe715081ad8b184b797df475de4d223eb
6b10c15e653d49d146378acda9f3692e9b5b1950
/examples/basic_skills/unnamed_790.lean
9dd7c1c3da7f1c48ebd7b0bb385e69e2d8687ff1
[]
no_license
gebner/mathematics_in_lean
3cf7f18767208ea6c3307ec3a67c7ac266d8514d
6d1462bba46d66a9b948fc1aef2714fd265cde0b
refs/heads/master
1,655,301,945,565
1,588,697,505,000
1,588,697,505,000
261,523,603
0
0
null
1,588,695,611,000
1,588,695,610,000
null
UTF-8
Lean
false
false
125
lean
namespace my_ring variables {R : Type*} [ring R] -- BEGIN theorem self_sub (a : R) : a - a = 0 := sorry -- END end my_ring
4826466e95157ffb959e97e5547fb89ec71bc20d
4727251e0cd73359b15b664c3170e5d754078599
/archive/imo/imo2008_q4.lean
3ccccb23b5d75bca8eae0938eba3cf31adc368b6
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
4,598
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 import data.real.sqrt import data.real.nnreal import tactic.linear_combination /-! # IMO 2008 Q4 Find all functions `f : (0,∞) → (0,∞)` (so, `f` is a function from the positive real numbers to the positive real numbers) such that ``` (f(w)^2 + f(x)^2)/(f(y^2) + f(z^2)) = (w^2 + x^2)/(y^2 + z^2) ``` for all positive real numbers `w`, `x`, `y`, `z`, satisfying `wx = yz`. # Solution The desired theorem is that either `f = λ x, x` or `f = λ x, 1/x` -/ open real lemma abs_eq_one_of_pow_eq_one (x : ℝ) (n : ℕ) (hn : n ≠ 0) (h : x ^ n = 1) : |x| = 1 := by rw [← pow_left_inj (abs_nonneg x) zero_le_one (pos_iff_ne_zero.2 hn), one_pow, pow_abs, h, abs_one] theorem imo2008_q4 (f : ℝ → ℝ) (H₁ : ∀ x > 0, f(x) > 0) : (∀ w x y z : ℝ, 0 < w → 0 < x → 0 < y → 0 < z → w * x = y * z → (f(w) ^ 2 + f(x) ^ 2) / (f(y ^ 2) + f(z ^ 2)) = (w ^ 2 + x ^ 2) / (y ^ 2 + z ^ 2)) ↔ ((∀ x > 0, f(x) = x) ∨ (∀ x > 0, f(x) = 1 / x)) := begin split, swap, -- proof that f(x) = x and f(x) = 1/x satisfy the condition { rintros (h | h), { intros w x y z hw hx hy hz hprod, rw [h w hw, h x hx, h (y ^ 2) (pow_pos hy 2), h (z ^ 2) (pow_pos hz 2)] }, { intros w x y z hw hx hy hz hprod, rw [h w hw, h x hx, h (y ^ 2) (pow_pos hy 2), h (z ^ 2) (pow_pos hz 2)], have hy2z2 : y ^ 2 + z ^ 2 ≠ 0 := ne_of_gt (add_pos (pow_pos hy 2) (pow_pos hz 2)), have hz2y2 : z ^ 2 + y ^ 2 ≠ 0 := ne_of_gt (add_pos (pow_pos hz 2) (pow_pos hy 2)), have hp2 : w ^ 2 * x ^ 2 = y ^ 2 * z ^ 2, { linear_combination (hprod, w * x + y * z) }, field_simp [ne_of_gt hw, ne_of_gt hx, ne_of_gt hy, ne_of_gt hz, hy2z2, hz2y2, hp2], ring } }, -- proof that the only solutions are f(x) = x or f(x) = 1/x intro H₂, have h₀ : f(1) ≠ 0, { specialize H₁ 1 zero_lt_one, exact ne_of_gt H₁ }, have h₁ : f(1) = 1, { specialize H₂ 1 1 1 1 zero_lt_one zero_lt_one zero_lt_one zero_lt_one rfl, norm_num [← two_mul] at H₂, rw mul_div_mul_left (f(1) ^ 2) (f 1) two_ne_zero at H₂, rwa ← (div_eq_iff h₀).mpr (sq (f 1)) }, have h₂ : ∀ x > 0, (f(x) - x) * (f(x) - 1 / x) = 0, { intros x hx, have h1xss : 1 * x = (sqrt x) * (sqrt x), { rw [one_mul, mul_self_sqrt (le_of_lt hx)] }, specialize H₂ 1 x (sqrt x) (sqrt x) zero_lt_one hx (sqrt_pos.mpr hx) (sqrt_pos.mpr hx) h1xss, rw [h₁, one_pow 2, sq_sqrt (le_of_lt hx), ← two_mul (f(x)), ← two_mul x] at H₂, have hx_ne_0 : x ≠ 0 := ne_of_gt hx, have hfx_ne_0 : f(x) ≠ 0, { specialize H₁ x hx, exact ne_of_gt H₁ }, field_simp at H₂ ⊢, linear_combination (H₂, 1/2) }, have h₃ : ∀ x > 0, f(x) = x ∨ f(x) = 1 / x, { simpa [sub_eq_zero] using h₂ }, by_contra' h, rcases h with ⟨⟨b, hb, hfb₁⟩, ⟨a, ha, hfa₁⟩⟩, obtain hfa₂ := or.resolve_right (h₃ a ha) hfa₁, -- f(a) ≠ 1/a, f(a) = a obtain hfb₂ := or.resolve_left (h₃ b hb) hfb₁, -- f(b) ≠ b, f(b) = 1/b have hab : a * b > 0 := mul_pos ha hb, have habss : a * b = sqrt(a * b) * sqrt(a * b) := (mul_self_sqrt (le_of_lt hab)).symm, specialize H₂ a b (sqrt (a * b)) (sqrt (a * b)) ha hb (sqrt_pos.mpr hab) (sqrt_pos.mpr hab) habss, rw [sq_sqrt (le_of_lt hab), ← two_mul (f(a * b)), ← two_mul (a * b)] at H₂, rw [hfa₂, hfb₂] at H₂, have h2ab_ne_0 : 2 * (a * b) ≠ 0 := mul_ne_zero two_ne_zero (ne_of_gt hab), specialize h₃ (a * b) hab, cases h₃ with hab₁ hab₂, -- f(ab) = ab → b^4 = 1 → b = 1 → f(b) = b → false { field_simp [hab₁] at H₂, field_simp [ne_of_gt hb] at H₂, have hb₁ : b ^ 4 = 1 := by linear_combination (H₂, -1), obtain hb₂ := abs_eq_one_of_pow_eq_one b 4 (show 4 ≠ 0, by norm_num) hb₁, rw abs_of_pos hb at hb₂, rw hb₂ at hfb₁, exact hfb₁ h₁ }, -- f(ab) = 1/ab → a^4 = 1 → a = 1 → f(a) = 1/a → false { have hb_ne_0 : b ≠ 0 := ne_of_gt hb, field_simp [hab₂] at H₂, have H₃ : 2 * b ^ 4 * (a ^ 4 - 1) = 0 := by linear_combination H₂, have h2b4_ne_0 : 2 * (b ^ 4) ≠ 0 := mul_ne_zero two_ne_zero (pow_ne_zero 4 hb_ne_0), have ha₁ : a ^ 4 = 1, { simpa [sub_eq_zero, h2b4_ne_0] using H₃ }, obtain ha₂ := abs_eq_one_of_pow_eq_one a 4 (show 4 ≠ 0, by norm_num) ha₁, rw abs_of_pos ha at ha₂, rw ha₂ at hfa₁, norm_num at hfa₁ }, end
b9fcaff012670fa4970825566101dd613f98162b
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/group_theory/archimedean.lean
1aba4767f124497aeff62ca79835b4650e96db39
[ "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
3,272
lean
/- Copyright (c) 2020 Heather Macbeth, Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Heather Macbeth, Patrick Massot -/ import group_theory.subgroup.basic import algebra.archimedean /-! # Archimedean groups This file proves a few facts about ordered groups which satisfy the `archimedean` property, that is: `class archimedean (α) [ordered_add_comm_monoid α] : Prop :=` `(arch : ∀ (x : α) {y}, 0 < y → ∃ n : ℕ, x ≤ n • y)` They are placed here in a separate file (rather than incorporated as a continuation of `algebra.archimedean`) because they rely on some imports from `group_theory` -- bundled subgroups in particular. The main result is `add_subgroup.cyclic_of_min`: a subgroup of a decidable archimedean abelian group is cyclic, if its set of positive elements has a minimal element. This result is used in this file to deduce `int.subgroup_cyclic`, proving that every subgroup of `ℤ` is cyclic. (There are several other methods one could use to prove this fact, including more purely algebraic methods, but none seem to exist in mathlib as of writing. The closest is `subgroup.is_cyclic`, but that has not been transferred to `add_subgroup`.) The result is also used in `topology.instances.real` as an ingredient in the classification of subgroups of `ℝ`. -/ variables {G : Type*} [linear_ordered_add_comm_group G] [archimedean G] open linear_ordered_add_comm_group /-- Given a subgroup `H` of a decidable linearly ordered archimedean abelian group `G`, if there exists a minimal element `a` of `H ∩ G_{>0}` then `H` is generated by `a`. -/ lemma add_subgroup.cyclic_of_min {H : add_subgroup G} {a : G} (ha : is_least {g : G | g ∈ H ∧ 0 < g} a) : H = add_subgroup.closure {a} := begin obtain ⟨⟨a_in, a_pos⟩, a_min⟩ := ha, refine le_antisymm _ (H.closure_le.mpr $ by simp [a_in]), intros g g_in, obtain ⟨k, nonneg, lt⟩ : ∃ k, 0 ≤ g - k • a ∧ g - k • a < a := exists_int_smul_near_of_pos' a_pos g, have h_zero : g - k • a = 0, { by_contra h, have h : a ≤ g - k • a, { refine a_min ⟨_, _⟩, { exact add_subgroup.sub_mem H g_in (add_subgroup.gsmul_mem H a_in k) }, { exact lt_of_le_of_ne nonneg (ne.symm h) } }, have h' : ¬ (a ≤ g - k • a) := not_le.mpr lt, contradiction }, simp [sub_eq_zero.mp h_zero, add_subgroup.mem_closure_singleton], end /-- Every subgroup of `ℤ` is cyclic. -/ lemma int.subgroup_cyclic (H : add_subgroup ℤ) : ∃ a, H = add_subgroup.closure {a} := begin cases add_subgroup.bot_or_exists_ne_zero H with h h, { use 0, rw h, exact add_subgroup.closure_singleton_zero.symm }, let s := {g : ℤ | g ∈ H ∧ 0 < g}, have h_bdd : ∀ g ∈ s, (0 : ℤ) ≤ g := λ _ h, le_of_lt h.2, obtain ⟨g₀, g₀_in, g₀_ne⟩ := h, obtain ⟨g₁, g₁_in, g₁_pos⟩ : ∃ g₁ : ℤ, g₁ ∈ H ∧ 0 < g₁, { cases lt_or_gt_of_ne g₀_ne with Hg₀ Hg₀, { exact ⟨-g₀, H.neg_mem g₀_in, neg_pos.mpr Hg₀⟩ }, { exact ⟨g₀, g₀_in, Hg₀⟩ } }, obtain ⟨a, ha, ha'⟩ := int.exists_least_of_bdd ⟨(0 : ℤ), h_bdd⟩ ⟨g₁, g₁_in, g₁_pos⟩, exact ⟨a, add_subgroup.cyclic_of_min ⟨ha, ha'⟩⟩, end
639ac3f3d09d77e8b09cac3a9f69f3a7868e5e62
8930e38ac0fae2e5e55c28d0577a8e44e2639a6d
/set_theory/zfc.lean
af12f4ff636aaae4f39790ed4c8227ab61678334
[ "Apache-2.0" ]
permissive
SG4316/mathlib
3d64035d02a97f8556ad9ff249a81a0a51a3321a
a7846022507b531a8ab53b8af8a91953fceafd3a
refs/heads/master
1,584,869,960,527
1,530,718,645,000
1,530,724,110,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
29,853
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.rec_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.set_eq_def _ _).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 theorem 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
4e0a541aec35d39dcd0c9772d73e28935e6275b4
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/geometry/manifold/conformal_groupoid.lean
7ea9bc0fe5c176aeaf24d25855f26fdb59218c8e
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
1,078
lean
/- Copyright (c) 2021 Yourong Zang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yourong Zang -/ import analysis.calculus.conformal.normed_space import geometry.manifold.charted_space /-! # Conformal Groupoid In this file we define the groupoid of conformal maps on normed spaces. ## Main definitions * `conformal_groupoid`: the groupoid of conformal local homeomorphisms. ## Tags conformal, groupoid -/ variables {X : Type*} [normed_add_comm_group X] [normed_space ℝ X] /-- The pregroupoid of conformal maps. -/ def conformal_pregroupoid : pregroupoid X := { property := λ f u, ∀ x, x ∈ u → conformal_at f x, comp := λ f g u v hf hg hu hv huv x hx, (hg (f x) hx.2).comp x (hf x hx.1), id_mem := λ x hx, conformal_at_id x, locality := λ f u hu h x hx, let ⟨v, h₁, h₂, h₃⟩ := h x hx in h₃ x ⟨hx, h₂⟩, congr := λ f g u hu h hf x hx, (hf x hx).congr hx hu h, } /-- The groupoid of conformal maps. -/ def conformal_groupoid : structure_groupoid X := conformal_pregroupoid.groupoid
899a02c5b52a51a2bb1411ece59f75365afd09e1
b561a44b48979a98df50ade0789a21c79ee31288
/stage0/src/Lean/Elab/Quotation.lean
e12c578e140367f6917ff6f1fdd87c217f61e222
[ "Apache-2.0" ]
permissive
3401ijk/lean4
97659c475ebd33a034fed515cb83a85f75ccfb06
a5b1b8de4f4b038ff752b9e607b721f15a9a4351
refs/heads/master
1,693,933,007,651
1,636,424,845,000
1,636,424,845,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
24,873
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich Elaboration of syntax quotations as terms and patterns (in `match_syntax`). See also `./Hygiene.lean` for the basic hygiene workings and data types. -/ import Lean.Syntax import Lean.ResolveName import Lean.Elab.Term import Lean.Elab.Quotation.Util import Lean.Elab.Quotation.Precheck import Lean.Parser.Term namespace Lean.Elab.Term.Quotation open Lean.Parser.Term open Lean.Syntax open Meta /-- `C[$(e)]` ~> `let a := e; C[$a]`. Used in the implementation of antiquot splices. -/ private partial def floatOutAntiquotTerms : Syntax → StateT (Syntax → TermElabM Syntax) TermElabM Syntax | stx@(Syntax.node i k args) => do if isAntiquot stx && !isEscapedAntiquot stx then let e := getAntiquotTerm stx if !e.isIdent || !e.getId.isAtomic then return ← withFreshMacroScope do let a ← `(a) modify (fun cont stx => (`(let $a:ident := $e; $stx) : TermElabM _)) stx.setArg 2 a Syntax.node i k (← args.mapM floatOutAntiquotTerms) | stx => pure stx private def getSepFromSplice (splice : Syntax) : Syntax := do if let Syntax.atom _ sep := getAntiquotSpliceSuffix splice then Syntax.mkStrLit (sep.dropRight 1) else unreachable! partial def mkTuple : Array Syntax → TermElabM Syntax | #[] => `(Unit.unit) | #[e] => e | es => do let stx ← mkTuple (es.eraseIdx 0) `(Prod.mk $(es[0]) $stx) def resolveSectionVariable (sectionVars : NameMap Name) (id : Name) : List (Name × List String) := -- decode macro scopes from name before recursion let extractionResult := extractMacroScopes id let rec loop : Name → List String → List (Name × List String) | id@(Name.str p s _), projs => -- NOTE: we assume that macro scopes always belong to the projected constant, not the projections let id := { extractionResult with name := id }.review match sectionVars.find? id with | some newId => [(newId, projs)] | none => loop p (s::projs) | _, _ => [] loop extractionResult.name [] /-- Transform sequence of pushes and appends into acceptable code -/ def ArrayStxBuilder := Sum (Array Syntax) Syntax namespace ArrayStxBuilder def empty : ArrayStxBuilder := Sum.inl #[] def build : ArrayStxBuilder → Syntax | Sum.inl elems => quote elems | Sum.inr arr => arr def push (b : ArrayStxBuilder) (elem : Syntax) : ArrayStxBuilder := match b with | Sum.inl elems => Sum.inl <| elems.push elem | Sum.inr arr => Sum.inr <| mkCApp ``Array.push #[arr, elem] def append (b : ArrayStxBuilder) (arr : Syntax) (appendName := ``Array.append) : ArrayStxBuilder := Sum.inr <| mkCApp appendName #[b.build, arr] end ArrayStxBuilder -- Elaborate the content of a syntax quotation term private partial def quoteSyntax : Syntax → TermElabM Syntax | Syntax.ident info rawVal val preresolved => do if !hygiene.get (← getOptions) then return ← `(Syntax.ident info $(quote rawVal) $(quote val) $(quote preresolved)) -- Add global scopes at compilation time (now), add macro scope at runtime (in the quotation). -- See the paper for details. let r ← resolveGlobalName val -- extension of the paper algorithm: also store unique section variable names as top-level scopes -- so they can be captured and used inside the section, but not outside let r' := resolveSectionVariable (← read).sectionVars val let preresolved := r ++ r' ++ preresolved let val := quote val -- `scp` is bound in stxQuot.expand `(Syntax.ident info $(quote rawVal) (addMacroScope mainModule $val scp) $(quote preresolved)) -- if antiquotation, insert contents as-is, else recurse | stx@(Syntax.node _ k _) => do if isAntiquot stx && !isEscapedAntiquot stx then getAntiquotTerm stx else if isTokenAntiquot stx && !isEscapedAntiquot stx then match stx[0] with | Syntax.atom _ val => `(Syntax.atom (Option.getD (getHeadInfo? $(getAntiquotTerm stx)) info) $(quote val)) | _ => throwErrorAt stx "expected token" else if isAntiquotSuffixSplice stx && !isEscapedAntiquot stx then -- splices must occur in a `many` node throwErrorAt stx "unexpected antiquotation splice" else if isAntiquotSplice stx && !isEscapedAntiquot stx then throwErrorAt stx "unexpected antiquotation splice" else -- if escaped antiquotation, decrement by one escape level let stx := unescapeAntiquot stx let mut args := ArrayStxBuilder.empty let appendName := if (← getEnv).contains ``Array.append then ``Array.append else ``Array.appendCore for arg in stx.getArgs do if k == nullKind && isAntiquotSuffixSplice arg then let antiquot := getAntiquotSuffixSpliceInner arg args := args.append (appendName := appendName) <| ← match antiquotSuffixSplice? arg with | `optional => `(match $(getAntiquotTerm antiquot):term with | some x => Array.empty.push x | none => Array.empty) | `many => getAntiquotTerm antiquot | `sepBy => `(@SepArray.elemsAndSeps $(getSepFromSplice arg) $(getAntiquotTerm antiquot)) | k => throwErrorAt arg "invalid antiquotation suffix splice kind '{k}'" else if k == nullKind && isAntiquotSplice arg then let k := antiquotSpliceKind? arg let (arg, bindLets) ← floatOutAntiquotTerms arg |>.run pure let inner ← (getAntiquotSpliceContents arg).mapM quoteSyntax let ids ← getAntiquotationIds arg if ids.isEmpty then throwErrorAt stx "antiquotation splice must contain at least one antiquotation" let arr ← match k with | `optional => `(match $[$ids:ident],* with | $[some $ids:ident],* => $(quote inner) | none => Array.empty) | _ => let arr ← ids[:ids.size-1].foldrM (fun id arr => `(Array.zip $id $arr)) ids.back `(Array.map (fun $(← mkTuple ids) => $(inner[0])) $arr) let arr ← if k == `sepBy then `(mkSepArray $arr (mkAtom $(getSepFromSplice arg))) else arr let arr ← bindLets arr args := args.append arr else do let arg ← quoteSyntax arg args := args.push arg `(Syntax.node SourceInfo.none $(quote k) $(args.build)) | Syntax.atom _ val => `(Syntax.atom info $(quote val)) | Syntax.missing => throwUnsupportedSyntax def stxQuot.expand (stx : Syntax) : TermElabM Syntax := do /- Syntax quotations are monadic values depending on the current macro scope. For efficiency, we bind the macro scope once for each quotation, then build the syntax tree in a completely pure computation depending on this binding. Note that regular function calls do not introduce a new macro scope (i.e. we preserve referential transparency), so we can refer to this same `scp` inside `quoteSyntax` by including it literally in a syntax quotation. -/ -- TODO: simplify to `(do scp ← getCurrMacroScope; pure $(quoteSyntax quoted)) let stx ← quoteSyntax stx.getQuotContent; `(Bind.bind MonadRef.mkInfoFromRefPos (fun info => Bind.bind getCurrMacroScope (fun scp => Bind.bind getMainModule (fun mainModule => Pure.pure $stx)))) /- NOTE: It may seem like the newly introduced binding `scp` may accidentally capture identifiers in an antiquotation introduced by `quoteSyntax`. However, note that the syntax quotation above enjoys the same hygiene guarantees as anywhere else in Lean; that is, we implement hygienic quotations by making use of the hygienic quotation support of the bootstrapped Lean compiler! Aside: While this might sound "dangerous", it is in fact less reliant on a "chain of trust" than other bootstrapping parts of Lean: because this implementation itself never uses `scp` (or any other identifier) both inside and outside quotations, it can actually correctly be compiled by an unhygienic (but otherwise correct) implementation of syntax quotations. As long as it is then compiled again with the resulting executable (i.e. up to stage 2), the result is a correct hygienic implementation. In this sense the implementation is "self-stabilizing". It was in fact originally compiled by an unhygienic prototype implementation. -/ macro "elab_stx_quot" kind:ident : command => `(@[builtinTermElab $kind:ident] def elabQuot : TermElab := adaptExpander stxQuot.expand) -- elab_stx_quot Parser.Level.quot elab_stx_quot Parser.Term.quot elab_stx_quot Parser.Term.funBinder.quot elab_stx_quot Parser.Term.bracketedBinder.quot elab_stx_quot Parser.Term.matchDiscr.quot elab_stx_quot Parser.Tactic.quot elab_stx_quot Parser.Tactic.quotSeq elab_stx_quot Parser.Term.stx.quot elab_stx_quot Parser.Term.prec.quot elab_stx_quot Parser.Term.attr.quot elab_stx_quot Parser.Term.prio.quot elab_stx_quot Parser.Term.doElem.quot elab_stx_quot Parser.Term.dynamicQuot /- match -/ -- an "alternative" of patterns plus right-hand side private abbrev Alt := List Syntax × Syntax /-- In a single match step, we match the first discriminant against the "head" of the first pattern of the first alternative. This datatype describes what kind of check this involves, which helps other patterns decide if they are covered by the same check and don't have to be checked again (see also `MatchResult`). -/ inductive HeadCheck where -- match step that always succeeds: _, x, `($x), ... | unconditional -- match step based on kind and, optionally, arity of discriminant -- If `arity` is given, that number of new discriminants is introduced. `covered` patterns should then introduce the -- same number of new patterns. -- We actually check the arity at run time only in the case of `null` nodes since it should otherwise by implied by -- the node kind. -- without arity: `($x:k) -- with arity: any quotation without an antiquotation head pattern | shape (k : SyntaxNodeKind) (arity : Option Nat) -- Match step that succeeds on `null` nodes of arity at least `numPrefix + numSuffix`, introducing discriminants -- for the first `numPrefix` children, one `null` node for those in between, and for the `numSuffix` last children. -- example: `([$x, $xs,*, $y]) is `slice 2 2` | slice (numPrefix numSuffix : Nat) -- other, complicated match step that will probably only cover identical patterns -- example: antiquotation splices `($[...]*) | other (pat : Syntax) open HeadCheck /-- Describe whether a pattern is covered by a head check (induced by the pattern itself or a different pattern). -/ inductive MatchResult where -- Pattern agrees with head check, remove and transform remaining alternative. -- If `exhaustive` is `false`, *also* include unchanged alternative in the "no" branch. | covered (f : Alt → TermElabM Alt) (exhaustive : Bool) -- Pattern disagrees with head check, include in "no" branch only | uncovered -- Pattern is not quite sure yet; include unchanged in both branches | undecided open MatchResult /-- All necessary information on a pattern head. -/ structure HeadInfo where -- check induced by the pattern check : HeadCheck -- compute compatibility of pattern with given head check onMatch (taken : HeadCheck) : MatchResult -- actually run the specified head check, with the discriminant bound to `discr` doMatch (yes : (newDiscrs : List Syntax) → TermElabM Syntax) (no : TermElabM Syntax) : TermElabM Syntax /-- Adapt alternatives that do not introduce new discriminants in `doMatch`, but are covered by those that do so. -/ private def noOpMatchAdaptPats : HeadCheck → Alt → Alt | shape k (some sz), (pats, rhs) => (List.replicate sz (Unhygienic.run `(_)) ++ pats, rhs) | slice p s, (pats, rhs) => (List.replicate (p + 1 + s) (Unhygienic.run `(_)) ++ pats, rhs) | _, alt => alt private def adaptRhs (fn : Syntax → TermElabM Syntax) : Alt → TermElabM Alt | (pats, rhs) => do (pats, ← fn rhs) private partial def getHeadInfo (alt : Alt) : TermElabM HeadInfo := let pat := alt.fst.head! let unconditionally (rhsFn) := pure { check := unconditional, doMatch := fun yes no => yes [], onMatch := fun taken => covered (adaptRhs rhsFn ∘ noOpMatchAdaptPats taken) (match taken with | unconditional => true | _ => false) } -- quotation pattern if isQuot pat then let quoted := getQuotContent pat if quoted.isAtom then -- We assume that atoms are uniquely determined by the node kind and never have to be checked unconditionally pure else if quoted.isTokenAntiquot then unconditionally (`(let $(quoted.getAntiquotTerm) := discr; $(·))) else if isAntiquot quoted && !isEscapedAntiquot quoted then -- quotation contains a single antiquotation let k := antiquotKind? quoted |>.get! let rhsFn := match getAntiquotTerm quoted with | `(_) => pure | `($id:ident) => fun stx => `(let $id := discr; $(stx)) | anti => fun _ => throwErrorAt anti "unsupported antiquotation kind in pattern" -- Antiquotation kinds like `$id:ident` influence the parser, but also need to be considered by -- `match` (but not by quotation terms). For example, `($id:ident) and `($e) are not -- distinguishable without checking the kind of the node to be captured. Note that some -- antiquotations like the latter one for terms do not correspond to any actual node kind -- (signified by `k == Name.anonymous`), so we would only check for `ident` here. -- -- if stx.isOfKind `ident then -- let id := stx; let e := stx; ... -- else -- let e := stx; ... if k == Name.anonymous then unconditionally rhsFn else pure { check := shape k none, onMatch := fun | other _ => undecided | taken@(shape k' sz) => if k' == k then covered (adaptRhs rhsFn ∘ noOpMatchAdaptPats taken) (exhaustive := sz.isNone) else uncovered | _ => uncovered, doMatch := fun yes no => do `(cond (Syntax.isOfKind discr $(quote k)) $(← yes []) $(← no)), } else if isAntiquotSuffixSplice quoted then throwErrorAt quoted "unexpected antiquotation splice" else if isAntiquotSplice quoted then throwErrorAt quoted "unexpected antiquotation splice" else if quoted.getArgs.size == 1 && isAntiquotSuffixSplice quoted[0] then let anti := getAntiquotTerm (getAntiquotSuffixSpliceInner quoted[0]) unconditionally fun rhs => match antiquotSuffixSplice? quoted[0] with | `optional => `(let $anti := Syntax.getOptional? discr; $rhs) | `many => `(let $anti := Syntax.getArgs discr; $rhs) | `sepBy => `(let $anti := @SepArray.mk $(getSepFromSplice quoted[0]) (Syntax.getArgs discr); $rhs) | k => throwErrorAt quoted "invalid antiquotation suffix splice kind '{k}'" else if quoted.getArgs.size == 1 && isAntiquotSplice quoted[0] then pure { check := other pat, onMatch := fun | other pat' => if pat' == pat then covered pure (exhaustive := true) else undecided | _ => undecided, doMatch := fun yes no => do let splice := quoted[0] let k := antiquotSpliceKind? splice let contents := getAntiquotSpliceContents splice let ids ← getAntiquotationIds splice let yes ← yes [] let no ← no match k with | `optional => let nones := mkArray ids.size (← `(none)) `(let_delayed yes _ $ids* := $yes; if discr.isNone then yes () $[ $nones]* else match discr with | `($(mkNullNode contents)) => yes () $[ (some $ids)]* | _ => $no) | _ => let mut discrs ← `(Syntax.getArgs discr) if k == `sepBy then discrs ← `(Array.getSepElems $discrs) let tuple ← mkTuple ids let mut yes := yes let resId ← match ids with | #[id] => id | _ => for id in ids do yes ← `(let $id := tuples.map (fun $tuple => $id); $yes) `(tuples) let contents := if contents.size == 1 then contents[0] else mkNullNode contents `(match OptionM.run ($(discrs).sequenceMap fun | `($contents) => some $tuple | _ => none) with | some $resId => $yes | none => $no) } else if let some idx := quoted.getArgs.findIdx? (fun arg => isAntiquotSuffixSplice arg || isAntiquotSplice arg) then do /- pattern of the form `match discr, ... with | `(pat_0 ... pat_(idx-1) $[...]* pat_(idx+1) ...), ...` transform to ``` if discr.getNumArgs >= $quoted.getNumArgs - 1 then match discr[0], ..., discr[idx-1], mkNullNode (discr.getArgs.extract idx (discr.getNumArgs - $numSuffix))), ..., discr[quoted.getNumArgs - 1] with | `(pat_0), ... `(pat_(idx-1)), `($[...])*, `(pat_(idx+1)), ... ``` -/ let numSuffix := quoted.getNumArgs - 1 - idx pure { check := slice idx numSuffix onMatch := fun | other _ => undecided | slice p s => if p == idx && s == numSuffix then let argPats := quoted.getArgs.mapIdx fun i arg => let arg := if (i : Nat) == idx then mkNullNode #[arg] else arg Unhygienic.run `(`($(arg))) covered (fun (pats, rhs) => (argPats.toList ++ pats, rhs)) (exhaustive := true) else uncovered | _ => uncovered doMatch := fun yes no => do let prefixDiscrs ← (List.range idx).mapM (`(Syntax.getArg discr $(quote ·))) let sliceDiscr ← `(mkNullNode (discr.getArgs.extract $(quote idx) (discr.getNumArgs - $(quote numSuffix)))) let suffixDiscrs ← (List.range numSuffix).mapM fun i => `(Syntax.getArg discr (discr.getNumArgs - $(quote (numSuffix - i)))) `(ite (GE.ge discr.getNumArgs $(quote (quoted.getNumArgs - 1))) $(← yes (prefixDiscrs ++ sliceDiscr :: suffixDiscrs)) $(← no)) } else -- not an antiquotation, or an escaped antiquotation: match head shape let quoted := unescapeAntiquot quoted let kind := quoted.getKind let argPats := quoted.getArgs.map fun arg => Unhygienic.run `(`($(arg))) pure { check := if quoted.isIdent then -- identifiers only match identical identifiers -- NOTE: We could make this case more precise by including the matched identifier, -- if any, in the `shape` constructor, but matching on literal identifiers is quite -- rare. other quoted else shape kind argPats.size, onMatch := fun | other stx' => if quoted.isIdent && quoted == stx' then covered pure (exhaustive := true) else uncovered | shape k' sz => if k' == kind && sz == argPats.size then covered (fun (pats, rhs) => (argPats.toList ++ pats, rhs)) (exhaustive := true) else uncovered | _ => uncovered, doMatch := fun yes no => do let cond ← match kind with | `null => `(Syntax.matchesNull discr $(quote argPats.size)) | `ident => `(Syntax.matchesIdent discr $(quote quoted.getId)) | _ => `(Syntax.isOfKind discr $(quote kind)) let newDiscrs ← (List.range argPats.size).mapM fun i => `(Syntax.getArg discr $(quote i)) `(ite (Eq $cond true) $(← yes newDiscrs) $(← no)) } else match pat with | `(_) => unconditionally pure | `($id:ident) => unconditionally (`(let $id := discr; $(·))) | `($id:ident@$pat) => do let info ← getHeadInfo (pat::alt.1.tail!, alt.2) { info with onMatch := fun taken => match info.onMatch taken with | covered f exh => covered (fun alt => f alt >>= adaptRhs (`(let $id := discr; $(·)))) exh | r => r } | _ => throwErrorAt pat "match (syntax) : unexpected pattern kind {pat}" -- Bind right-hand side to new `let_delayed` decl in order to prevent code duplication private def deduplicate (floatedLetDecls : Array Syntax) : Alt → TermElabM (Array Syntax × Alt) -- NOTE: new macro scope so that introduced bindings do not collide | (pats, rhs) => do if let `($f:ident $[ $args:ident]*) := rhs then -- looks simple enough/created by this function, skip return (floatedLetDecls, (pats, rhs)) withFreshMacroScope do match (← getPatternsVars pats.toArray) with | #[] => -- no antiquotations => introduce Unit parameter to preserve evaluation order let rhs' ← `(rhs Unit.unit) (floatedLetDecls.push (← `(letDecl|rhs _ := $rhs)), (pats, rhs')) | vars => let rhs' ← `(rhs $vars*) (floatedLetDecls.push (← `(letDecl|rhs $vars:ident* := $rhs)), (pats, rhs')) private partial def compileStxMatch (discrs : List Syntax) (alts : List Alt) : TermElabM Syntax := do trace[Elab.match_syntax] "match {discrs} with {alts}" match discrs, alts with | [], ([], rhs)::_ => pure rhs -- nothing left to match | _, [] => logError "non-exhaustive 'match' (syntax)" pure Syntax.missing | discr::discrs, alt::alts => do let info ← getHeadInfo alt let pat := alt.1.head! let alts ← (alt::alts).mapM fun alt => do ((← getHeadInfo alt).onMatch info.check, alt) let mut yesAlts := #[] let mut undecidedAlts := #[] let mut nonExhaustiveAlts := #[] let mut floatedLetDecls := #[] for alt in alts do let mut alt := alt match alt with | (covered f exh, alt') => -- we can only factor out a common check if there are no undecided patterns in between; -- otherwise we would change the order of alternatives if undecidedAlts.isEmpty then yesAlts ← yesAlts.push <$> f (alt'.1.tail!, alt'.2) if !exh then nonExhaustiveAlts := nonExhaustiveAlts.push alt' else (floatedLetDecls, alt) ← deduplicate floatedLetDecls alt' undecidedAlts := undecidedAlts.push alt nonExhaustiveAlts := nonExhaustiveAlts.push alt | (undecided, alt') => (floatedLetDecls, alt) ← deduplicate floatedLetDecls alt' undecidedAlts := undecidedAlts.push alt nonExhaustiveAlts := nonExhaustiveAlts.push alt | (uncovered, alt') => nonExhaustiveAlts := nonExhaustiveAlts.push alt' let mut stx ← info.doMatch (yes := fun newDiscrs => do let mut yesAlts := yesAlts if !undecidedAlts.isEmpty then -- group undecided alternatives in a new default case `| discr2, ... => match discr, discr2, ... with ...` let vars ← discrs.mapM fun _ => withFreshMacroScope `(discr) let pats := List.replicate newDiscrs.length (Unhygienic.run `(_)) ++ vars let alts ← undecidedAlts.mapM fun alt => `(matchAltExpr| | $(alt.1.toArray),* => $(alt.2)) let rhs ← `(match discr, $[$(vars.toArray):term],* with $alts:matchAlt*) yesAlts := yesAlts.push (pats, rhs) withFreshMacroScope $ compileStxMatch (newDiscrs ++ discrs) yesAlts.toList) (no := withFreshMacroScope $ compileStxMatch (discr::discrs) nonExhaustiveAlts.toList) for d in floatedLetDecls do stx ← `(let_delayed $d:letDecl; $stx) `(let discr := $discr; $stx) | _, _ => unreachable! def match_syntax.expand (stx : Syntax) : TermElabM Syntax := do match stx with | `(match $[$discrs:term],* with $[| $[$patss],* => $rhss]*) => do if !patss.any (·.any (fun | `($id@$pat) => pat.isQuot | pat => pat.isQuot)) then -- no quotations => fall back to regular `match` throwUnsupportedSyntax let stx ← compileStxMatch discrs.toList (patss.map (·.toList) |>.zip rhss).toList trace[Elab.match_syntax.result] "{stx}" stx | _ => throwUnsupportedSyntax @[builtinTermElab «match»] def elabMatchSyntax : TermElab := adaptExpander match_syntax.expand builtin_initialize registerTraceClass `Elab.match_syntax registerTraceClass `Elab.match_syntax.result end Lean.Elab.Term.Quotation