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
3a2fff59f2f73d34d7152a27332b67c9a3469fb1
f5f7e6fae601a5fe3cac7cc3ed353ed781d62419
/src/analysis/normed_space/bounded_linear_maps.lean
98b49ea84bc43a2065b61564549b7490b4de6409
[ "Apache-2.0" ]
permissive
EdAyers/mathlib
9ecfb2f14bd6caad748b64c9c131befbff0fb4e0
ca5d4c1f16f9c451cf7170b10105d0051db79e1b
refs/heads/master
1,626,189,395,845
1,555,284,396,000
1,555,284,396,000
144,004,030
0
0
Apache-2.0
1,533,727,664,000
1,533,727,663,000
null
UTF-8
Lean
false
false
6,917
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.basic import analysis.asymptotics @[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) open metric 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 k 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 k L) (M : ℝ) (h : ∀ x : E, ∥ L x ∥ ≤ M * ∥ x ∥) : is_bounded_linear_map k 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 def to_linear_map (f : E → F) (h : is_bounded_linear_map k f) : E →ₗ[k] F := (is_linear_map.mk' _ h.to_is_linear_map) lemma zero : is_bounded_linear_map k (λ (x:E), (0:F)) := (0 : E →ₗ F).is_linear.with_bound 0 $ by simp [le_refl] lemma id : is_bounded_linear_map k (λ (x:E), x) := linear_map.id.is_linear.with_bound 1 $ by simp [le_refl] set_option class.instance_max_depth 43 lemma smul {f : E → F} (c : k) : is_bounded_linear_map k f → is_bounded_linear_map k (λ 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 k f) : is_bounded_linear_map k (λ e, -f e) := begin rw show (λ e, -f e) = (λ e, (-1 : k) • f e), { funext, simp }, exact smul (-1) hf end lemma add {f : E → F} {g : E → F} : is_bounded_linear_map k f → is_bounded_linear_map k g → is_bounded_linear_map k (λ 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 k f) (hg : is_bounded_linear_map k g) : is_bounded_linear_map k (λ e, f e - g e) := add hf (neg hg) lemma comp {f : E → F} {g : F → G} : is_bounded_linear_map k g → is_bounded_linear_map k f → is_bounded_linear_map k (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 k 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 k L) : continuous L := continuous_iff_continuous_at.2 $ assume x, hL.tendsto x lemma lim_zero_bounded_linear_map {L : E → F} (H : is_bounded_linear_map k L) : (L →_{0} 0) := (H.1.mk' _).map_zero ▸ continuous_iff_continuous_at.1 H.continuous 0 section open asymptotics filter theorem is_O_id {L : E → F} (h : is_bounded_linear_map k L) (l : filter E) : is_O L (λ x, x) l := let ⟨M, Mpos, hM⟩ := h.bound in ⟨M, Mpos, mem_sets_of_superset univ_mem_sets (λ x _, hM x)⟩ theorem is_O_comp {L : F → G} (h : is_bounded_linear_map k L) {f : E → F} (l : filter E) : is_O (λ x', L (f x')) f l := ((h.is_O_id ⊤).comp _).mono (map_le_iff_le_comap.mp lattice.le_top) theorem is_O_sub {L : E → F} (h : is_bounded_linear_map k L) (l : filter E) (x : E) : is_O (λ x', L (x' - x)) (λ x', x' - x) l := is_O_comp h l end end is_bounded_linear_map set_option class.instance_max_depth 60 /-- A continuous linear map between normed spaces is bounded when the field is nondiscrete. The continuity ensures boundedness on a ball of some radius δ. The nondiscreteness is then used to rescale any element into an element of norm in [δ/C, δ], whose image has a controlled norm. The norm control for the original element follows by rescaling. -/ theorem is_linear_map.bounded_of_continuous_at {k : Type*} [nondiscrete_normed_field k] {E : Type*} [normed_space k E] {F : Type*} [normed_space k F] {L : E → F} {x₀ : E} (lin : is_linear_map k L) (cont : continuous_at L x₀) : is_bounded_linear_map k L := begin rcases tendsto_nhds_nhds.1 cont 1 zero_lt_one with ⟨ε, ε_pos, hε⟩, let δ := ε/2, have δ_pos : δ > 0 := half_pos ε_pos, have H : ∀{a}, ∥a∥ ≤ δ → ∥L a∥ ≤ 1, { assume a ha, have : dist (L (x₀+a)) (L x₀) ≤ 1, { apply le_of_lt (hε _), have : dist x₀ (x₀ + a) = ∥a∥, by { rw dist_eq_norm, simp }, rw [dist_comm, this], exact lt_of_le_of_lt ha (half_lt_self ε_pos) }, simpa [dist_eq_norm, lin.add] using this }, rcases exists_one_lt_norm k with ⟨c, hc⟩, refine lin.with_bound (δ⁻¹ * ∥c∥) (λx, _), by_cases h : x = 0, { simp only [h, lin.map_zero, norm_zero, mul_zero] }, { rcases rescale_to_shell hc δ_pos h with ⟨d, hd, dxle, ledx, dinv⟩, calc ∥L x∥ = ∥L ((d⁻¹ * d) • x)∥ : by rwa [inv_mul_cancel, one_smul] ... = ∥d∥⁻¹ * ∥L (d • x)∥ : by rw [mul_smul, lin.smul, norm_smul, norm_inv] ... ≤ ∥d∥⁻¹ * 1 : mul_le_mul_of_nonneg_left (H dxle) (by { rw ← norm_inv, exact norm_nonneg _ }) ... ≤ δ⁻¹ * ∥c∥ * ∥x∥ : by { rw mul_one, exact dinv } } end
e2e3b00b70d387ba1f842d40d1ca5f5a29abfbe6
626e312b5c1cb2d88fca108f5933076012633192
/src/algebra/category/Module/monoidal.lean
1ea5c13e4fbdb473c823c38c98ffd1058437715c
[ "Apache-2.0" ]
permissive
Bioye97/mathlib
9db2f9ee54418d29dd06996279ba9dc874fd6beb
782a20a27ee83b523f801ff34efb1a9557085019
refs/heads/master
1,690,305,956,488
1,631,067,774,000
1,631,067,774,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
9,011
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Buzzard, Scott Morrison -/ import category_theory.monoidal.braided import algebra.category.Module.basic import linear_algebra.tensor_product /-! # The symmetric monoidal category structure on R-modules Mostly this uses existing machinery in `linear_algebra.tensor_product`. We just need to provide a few small missing pieces to build the `monoidal_category` instance and then the `symmetric_category` instance. If you're happy using the bundled `Module R`, it may be possible to mostly use this as an interface and not need to interact much with the implementation details. -/ universes u open category_theory namespace Module variables {R : Type u} [comm_ring R] namespace monoidal_category -- The definitions inside this namespace are essentially private. -- After we build the `monoidal_category (Module R)` instance, -- you should use that API. open_locale tensor_product local attribute [ext] tensor_product.ext /-- (implementation) tensor product of R-modules -/ def tensor_obj (M N : Module R) : Module R := Module.of R (M ⊗[R] N) /-- (implementation) tensor product of morphisms R-modules -/ def tensor_hom {M N M' N' : Module R} (f : M ⟶ N) (g : M' ⟶ N') : tensor_obj M M' ⟶ tensor_obj N N' := tensor_product.map f g lemma tensor_id (M N : Module R) : tensor_hom (𝟙 M) (𝟙 N) = 𝟙 (Module.of R (↥M ⊗ ↥N)) := by tidy lemma tensor_comp {X₁ Y₁ Z₁ X₂ Y₂ Z₂ : Module R} (f₁ : X₁ ⟶ Y₁) (f₂ : X₂ ⟶ Y₂) (g₁ : Y₁ ⟶ Z₁) (g₂ : Y₂ ⟶ Z₂) : tensor_hom (f₁ ≫ g₁) (f₂ ≫ g₂) = tensor_hom f₁ f₂ ≫ tensor_hom g₁ g₂ := by tidy /-- (implementation) the associator for R-modules -/ def associator (M N K : Module R) : tensor_obj (tensor_obj M N) K ≅ tensor_obj M (tensor_obj N K) := linear_equiv.to_Module_iso (tensor_product.assoc R M N K) section /-! The `associator_naturality` and `pentagon` lemmas below are very slow to elaborate. We give them some help by expressing the lemmas first non-categorically, then using `convert _aux using 1` to have the elaborator work as little as possible. -/ open tensor_product (assoc map) private lemma associator_naturality_aux {X₁ X₂ X₃ : Type*} [add_comm_monoid X₁] [add_comm_monoid X₂] [add_comm_monoid X₃] [module R X₁] [module R X₂] [module R X₃] {Y₁ Y₂ Y₃ : Type*} [add_comm_monoid Y₁] [add_comm_monoid Y₂] [add_comm_monoid Y₃] [module R Y₁] [module R Y₂] [module R Y₃] (f₁ : X₁ →ₗ[R] Y₁) (f₂ : X₂ →ₗ[R] Y₂) (f₃ : X₃ →ₗ[R] Y₃) : (↑(assoc R Y₁ Y₂ Y₃) ∘ₗ (map (map f₁ f₂) f₃)) = ((map f₁ (map f₂ f₃)) ∘ₗ ↑(assoc R X₁ X₂ X₃)) := begin apply tensor_product.ext_threefold, intros x y z, refl end variables (R) private lemma pentagon_aux (W X Y Z : Type*) [add_comm_monoid W] [add_comm_monoid X] [add_comm_monoid Y] [add_comm_monoid Z] [module R W] [module R X] [module R Y] [module R Z] : ((map (1 : W →ₗ[R] W) (assoc R X Y Z).to_linear_map).comp (assoc R W (X ⊗[R] Y) Z).to_linear_map) .comp (map ↑(assoc R W X Y) (1 : Z →ₗ[R] Z)) = (assoc R W X (Y ⊗[R] Z)).to_linear_map.comp (assoc R (W ⊗[R] X) Y Z).to_linear_map := begin apply tensor_product.ext_fourfold, intros w x y z, refl end end lemma associator_naturality {X₁ X₂ X₃ Y₁ Y₂ Y₃ : Module R} (f₁ : X₁ ⟶ Y₁) (f₂ : X₂ ⟶ Y₂) (f₃ : X₃ ⟶ Y₃) : tensor_hom (tensor_hom f₁ f₂) f₃ ≫ (associator Y₁ Y₂ Y₃).hom = (associator X₁ X₂ X₃).hom ≫ tensor_hom f₁ (tensor_hom f₂ f₃) := by convert associator_naturality_aux f₁ f₂ f₃ using 1 lemma pentagon (W X Y Z : Module R) : tensor_hom (associator W X Y).hom (𝟙 Z) ≫ (associator W (tensor_obj X Y) Z).hom ≫ tensor_hom (𝟙 W) (associator X Y Z).hom = (associator (tensor_obj W X) Y Z).hom ≫ (associator W X (tensor_obj Y Z)).hom := by convert pentagon_aux R W X Y Z using 1 /-- (implementation) the left unitor for R-modules -/ def left_unitor (M : Module.{u} R) : Module.of R (R ⊗[R] M) ≅ M := (linear_equiv.to_Module_iso (tensor_product.lid R M) : of R (R ⊗ M) ≅ of R M).trans (of_self_iso M) lemma left_unitor_naturality {M N : Module R} (f : M ⟶ N) : tensor_hom (𝟙 (Module.of R R)) f ≫ (left_unitor N).hom = (left_unitor M).hom ≫ f := begin ext x y, simp, erw [tensor_product.lid_tmul, tensor_product.lid_tmul], rw linear_map.map_smul, refl, end /-- (implementation) the right unitor for R-modules -/ def right_unitor (M : Module.{u} R) : Module.of R (M ⊗[R] R) ≅ M := (linear_equiv.to_Module_iso (tensor_product.rid R M) : of R (M ⊗ R) ≅ of R M).trans (of_self_iso M) lemma right_unitor_naturality {M N : Module R} (f : M ⟶ N) : tensor_hom f (𝟙 (Module.of R R)) ≫ (right_unitor N).hom = (right_unitor M).hom ≫ f := begin ext x y, simp, erw [tensor_product.rid_tmul, tensor_product.rid_tmul], rw linear_map.map_smul, refl, end lemma triangle (M N : Module.{u} R) : (associator M (Module.of R R) N).hom ≫ tensor_hom (𝟙 M) (left_unitor N).hom = tensor_hom (right_unitor M).hom (𝟙 N) := begin apply tensor_product.ext_threefold, intros x y z, change R at y, dsimp [tensor_hom, associator], erw [tensor_product.lid_tmul, tensor_product.rid_tmul], exact (tensor_product.smul_tmul _ _ _).symm end end monoidal_category open monoidal_category instance monoidal_category : monoidal_category (Module.{u} R) := { -- data tensor_obj := tensor_obj, tensor_hom := @tensor_hom _ _, tensor_unit := Module.of R R, associator := associator, left_unitor := left_unitor, right_unitor := right_unitor, -- properties tensor_id' := λ M N, tensor_id M N, tensor_comp' := λ M N K M' N' K' f g h, tensor_comp f g h, associator_naturality' := λ M N K M' N' K' f g h, associator_naturality f g h, left_unitor_naturality' := λ M N f, left_unitor_naturality f, right_unitor_naturality' := λ M N f, right_unitor_naturality f, pentagon' := λ M N K L, pentagon M N K L, triangle' := λ M N, triangle M N, } /-- Remind ourselves that the monoidal unit, being just `R`, is still a commutative ring. -/ instance : comm_ring ((𝟙_ (Module.{u} R) : Module.{u} R) : Type u) := (by apply_instance : comm_ring R) namespace monoidal_category @[simp] lemma hom_apply {K L M N : Module.{u} R} (f : K ⟶ L) (g : M ⟶ N) (k : K) (m : M) : (f ⊗ g) (k ⊗ₜ m) = f k ⊗ₜ g m := rfl @[simp] lemma left_unitor_hom_apply {M : Module.{u} R} (r : R) (m : M) : ((λ_ M).hom : 𝟙_ (Module R) ⊗ M ⟶ M) (r ⊗ₜ[R] m) = r • m := tensor_product.lid_tmul m r @[simp] lemma right_unitor_hom_apply {M : Module.{u} R} (m : M) (r : R) : ((ρ_ M).hom : M ⊗ 𝟙_ (Module R) ⟶ M) (m ⊗ₜ r) = r • m := tensor_product.rid_tmul m r @[simp] lemma associator_hom_apply {M N K : Module.{u} R} (m : M) (n : N) (k : K) : ((α_ M N K).hom : (M ⊗ N) ⊗ K ⟶ M ⊗ (N ⊗ K)) ((m ⊗ₜ n) ⊗ₜ k) = (m ⊗ₜ (n ⊗ₜ k)) := rfl end monoidal_category /-- (implementation) the braiding for R-modules -/ def braiding (M N : Module R) : tensor_obj M N ≅ tensor_obj N M := linear_equiv.to_Module_iso (tensor_product.comm R M N) @[simp] lemma braiding_naturality {X₁ X₂ Y₁ Y₂ : Module.{u} R} (f : X₁ ⟶ Y₁) (g : X₂ ⟶ Y₂) : (f ⊗ g) ≫ (Y₁.braiding Y₂).hom = (X₁.braiding X₂).hom ≫ (g ⊗ f) := begin apply tensor_product.ext', intros x y, refl end @[simp] lemma hexagon_forward (X Y Z : Module.{u} R) : (α_ X Y Z).hom ≫ (braiding X _).hom ≫ (α_ Y Z X).hom = ((braiding X Y).hom ⊗ 𝟙 Z) ≫ (α_ Y X Z).hom ≫ (𝟙 Y ⊗ (braiding X Z).hom) := begin apply tensor_product.ext_threefold, intros x y z, refl, end @[simp] lemma hexagon_reverse (X Y Z : Module.{u} R) : (α_ X Y Z).inv ≫ (braiding _ Z).hom ≫ (α_ Z X Y).inv = (𝟙 X ⊗ (Y.braiding Z).hom) ≫ (α_ X Z Y).inv ≫ ((X.braiding Z).hom ⊗ 𝟙 Y) := begin apply (cancel_epi (α_ X Y Z).hom).1, apply tensor_product.ext_threefold, intros x y z, refl, end local attribute [ext] tensor_product.ext /-- The symmetric monoidal structure on `Module R`. -/ instance symmetric_category : symmetric_category (Module.{u} R) := { braiding := braiding, braiding_naturality' := λ X₁ X₂ Y₁ Y₂ f g, braiding_naturality f g, hexagon_forward' := hexagon_forward, hexagon_reverse' := hexagon_reverse, } namespace monoidal_category @[simp] lemma braiding_hom_apply {M N : Module.{u} R} (m : M) (n : N) : ((β_ M N).hom : M ⊗ N ⟶ N ⊗ M) (m ⊗ₜ n) = n ⊗ₜ m := rfl @[simp] lemma braiding_inv_apply {M N : Module.{u} R} (m : M) (n : N) : ((β_ M N).inv : N ⊗ M ⟶ M ⊗ N) (n ⊗ₜ m) = m ⊗ₜ n := rfl end monoidal_category end Module
c2d9f5aecbf2f4707e1c0b3fe499b8e3a6951d58
957a80ea22c5abb4f4670b250d55534d9db99108
/tests/lean/param.lean
3eb77067a8d16314c1cab41c9330c3d4189f8251
[ "Apache-2.0" ]
permissive
GaloisInc/lean
aa1e64d604051e602fcf4610061314b9a37ab8cd
f1ec117a24459b59c6ff9e56a1d09d9e9e60a6c0
refs/heads/master
1,592,202,909,807
1,504,624,387,000
1,504,624,387,000
75,319,626
2
1
Apache-2.0
1,539,290,164,000
1,480,616,104,000
C++
UTF-8
Lean
false
false
494
lean
-- definition foo1 a b c := a + b + (c:nat) definition foo2 (a : nat) b c := a + b + c definition foo3 a b (c : nat) := a + b + c definition foo4 (a b c : nat) := a + b + c definition foo5 (a b c) : nat := a + b + c definition foo6 {a b c} : nat := a + b + c -- definition foo7 a b c : nat := a + b + c -- Error definition foo8 (a b c : nat) : nat := a + b + c definition foo9 (a : nat) (b : nat) (c : nat) : nat := a + b + c definition foo10 (a : nat) b (c : nat) : nat := a + b + c
827f3d67164e80b061cfc768317a0871d60bfe14
ce6917c5bacabee346655160b74a307b4a5ab620
/src/ch4/ex0604.lean
613ca24dc7cd8694a4bff96ee0e7a80724f4da67
[]
no_license
Ailrun/Theorem_Proving_in_Lean
ae6a23f3c54d62d401314d6a771e8ff8b4132db2
2eb1b5caf93c6a5a555c79e9097cf2ba5a66cf68
refs/heads/master
1,609,838,270,467
1,586,846,743,000
1,586,846,743,000
240,967,761
1
0
null
null
null
null
UTF-8
Lean
false
false
1,031
lean
namespace hidden def divides (m n : ℕ) : Prop := ∃ k, m * k = n instance : has_dvd nat := ⟨divides⟩ def even (n : ℕ) : Prop := 2 ∣ n -- You can enter the '∣' character by typing \mid section variables m n : ℕ #check m ∣ n #check m^n #check even (m^n +3) end def prime (n : ℕ) : Prop := ∀ m : ℕ, m > 1 ∧ m < n → ¬ (m ∣ n) def infinitely_many_primes : Prop := ∀ n : ℕ, ∃ p : ℕ, prime p ∧ p > n def Fermat_prime (n : ℕ) : Prop := (∃ m : ℕ, 2^(2^m) = n) ∧ prime n def infinitely_many_Fermat_primes : Prop := ∀ n : ℕ, ∃ p : ℕ, Fermat_prime p ∧ p > n def goldbach_conjecture : Prop := ∀ n : ℕ, n > 2 → even n → (∃ a b : ℕ, prime a ∧ prime b ∧ a + b = n) def Goldbach's_weak_conjecture : Prop := ∀ n : ℕ, n > 5 → ¬ even n → (∃ a b c : ℕ, prime a ∧ prime b ∧ prime c ∧ a + b + c = n) def Fermat's_last_theorem : Prop := ∀ n : ℕ, n > 2 → ¬ (∃ a b c : ℕ, a^n + b^n = c^n) end hidden
6bd085fba085ea96154fc30388aac6f3a3946036
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/algebra/module/basic.lean
51a41c8c7fc5c376527c76b52038b8551e90d7b8
[ "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
22,182
lean
/- Copyright (c) 2015 Nathaniel Thomas. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Nathaniel Thomas, Jeremy Avigad, Johannes Hölzl, Mario Carneiro -/ import group_theory.group_action /-! # Modules over a ring In this file we define * `semimodule R M` : an additive commutative monoid `M` is a `semimodule` over a `semiring` `R` if for `r : R` and `x : M` their "scalar multiplication `r • x : M` is defined, and the operation `•` satisfies some natural associativity and distributivity axioms similar to those on a ring. * `module R M` : same as `semimodule R M` but assumes that `R` is a `ring` and `M` is an additive commutative group. * `vector_space k M` : same as `semimodule k M` and `module k M` but assumes that `k` is a `field` and `M` is an additive commutative group. * `linear_map R M M₂`, `M →ₗ[R] M₂` : a linear map between two R-`semimodule`s. * `is_linear_map R f` : predicate saying that `f : M → M₂` is a linear map. ## Implementation notes * `vector_space` and `module` are abbreviations for `semimodule R M`. ## Tags semimodule, module, vector space, linear map -/ open function open_locale big_operators universes u u' v w x y z variables {R : Type u} {k : Type u'} {S : Type v} {M : Type w} {M₂ : Type x} {M₃ : Type y} {ι : Type z} /-- A semimodule is a generalization of vector spaces to a scalar semiring. It consists of a scalar semiring `R` and an additive monoid of "vectors" `M`, connected by a "scalar multiplication" operation `r • x : M` (where `r : R` and `x : M`) with some natural associativity and distributivity axioms similar to those on a ring. -/ @[protect_proj] class semimodule (R : Type u) (M : Type v) [semiring R] [add_comm_monoid M] extends distrib_mul_action R M := (add_smul : ∀(r s : R) (x : M), (r + s) • x = r • x + s • x) (zero_smul : ∀x : M, (0 : R) • x = 0) section add_comm_monoid variables [semiring R] [add_comm_monoid M] [semimodule R M] (r s : R) (x y : M) theorem add_smul : (r + s) • x = r • x + s • x := semimodule.add_smul r s x variables (R) @[simp] theorem zero_smul : (0 : R) • x = 0 := semimodule.zero_smul x theorem two_smul : (2 : R) • x = x + x := by rw [bit0, add_smul, one_smul] /-- Pullback a `semimodule` structure along an injective additive monoid homomorphism. -/ protected def function.injective.semimodule [add_comm_monoid M₂] [has_scalar R M₂] (f : M₂ →+ M) (hf : injective f) (smul : ∀ (c : R) x, f (c • x) = c • f x) : semimodule R M₂ := { smul := (•), add_smul := λ c₁ c₂ x, hf $ by simp only [smul, f.map_add, add_smul], zero_smul := λ x, hf $ by simp only [smul, zero_smul, f.map_zero], .. hf.distrib_mul_action f smul } /-- Pushforward a `semimodule` structure along a surjective additive monoid homomorphism. -/ protected def function.surjective.semimodule [add_comm_monoid M₂] [has_scalar R M₂] (f : M →+ M₂) (hf : surjective f) (smul : ∀ (c : R) x, f (c • x) = c • f x) : semimodule R M₂ := { smul := (•), add_smul := λ c₁ c₂ x, by { rcases hf x with ⟨x, rfl⟩, simp only [add_smul, ← smul, ← f.map_add] }, zero_smul := λ x, by { rcases hf x with ⟨x, rfl⟩, simp only [← f.map_zero, ← smul, zero_smul] }, .. hf.distrib_mul_action f smul } variable (M) /-- `(•)` as an `add_monoid_hom`. -/ def smul_add_hom : R →+ M →+ M := { to_fun := const_smul_hom M, map_zero' := add_monoid_hom.ext $ λ r, by simp, map_add' := λ x y, add_monoid_hom.ext $ λ r, by simp [add_smul] } variables {R M} @[simp] lemma smul_add_hom_apply (r : R) (x : M) : smul_add_hom R M r x = r • x := rfl lemma semimodule.eq_zero_of_zero_eq_one (zero_eq_one : (0 : R) = 1) : x = 0 := by rw [←one_smul R x, ←zero_eq_one, zero_smul] lemma list.sum_smul {l : list R} {x : M} : l.sum • x = (l.map (λ r, r • x)).sum := ((smul_add_hom R M).flip x).map_list_sum l lemma multiset.sum_smul {l : multiset R} {x : M} : l.sum • x = (l.map (λ r, r • x)).sum := ((smul_add_hom R M).flip x).map_multiset_sum l lemma finset.sum_smul {f : ι → R} {s : finset ι} {x : M} : (∑ i in s, f i) • x = (∑ i in s, (f i) • x) := ((smul_add_hom R M).flip x).map_sum f s end add_comm_monoid section add_comm_group variables (R M) [semiring R] [add_comm_group M] /-- A structure containing most informations as in a semimodule, except the fields `zero_smul` and `smul_zero`. As these fields can be deduced from the other ones when `M` is an `add_comm_group`, this provides a way to construct a semimodule structure by checking less properties, in `semimodule.of_core`. -/ @[nolint has_inhabited_instance] structure semimodule.core extends has_scalar R M := (smul_add : ∀(r : R) (x y : M), r • (x + y) = r • x + r • y) (add_smul : ∀(r s : R) (x : M), (r + s) • x = r • x + s • x) (mul_smul : ∀(r s : R) (x : M), (r * s) • x = r • s • x) (one_smul : ∀x : M, (1 : R) • x = x) variables {R M} /-- Define `semimodule` without proving `zero_smul` and `smul_zero` by using an auxiliary structure `semimodule.core`, when the underlying space is an `add_comm_group`. -/ def semimodule.of_core (H : semimodule.core R M) : semimodule R M := by letI := H.to_has_scalar; exact { zero_smul := λ x, (add_monoid_hom.mk' (λ r : R, r • x) (λ r s, H.add_smul r s x)).map_zero, smul_zero := λ r, (add_monoid_hom.mk' ((•) r) (H.smul_add r)).map_zero, ..H } end add_comm_group /-- Modules are defined as an `abbreviation` for semimodules, if the base semiring is a ring. (A previous definition made `module` a structure defined to be `semimodule`.) This has as advantage that modules are completely transparent for type class inference, which means that all instances for semimodules are immediately picked up for modules as well. A cosmetic disadvantage is that one can not extend modules as such, in definitions such as `normed_space`. The solution is to extend `semimodule` instead. -/ library_note "module definition" /-- A module is the same as a semimodule, except the scalar semiring is actually a ring. This is the traditional generalization of spaces like `ℤ^n`, which have a natural addition operation and a way to multiply them by elements of a ring, but no multiplication operation between vectors. -/ abbreviation module (R : Type u) (M : Type v) [ring R] [add_comm_group M] := semimodule R M /-- To prove two module structures on a fixed `add_comm_group` agree, it suffices to check the scalar multiplications agree. -/ -- We'll later use this to show `module ℤ M` is a subsingleton. @[ext] lemma module_ext {R : Type*} [ring R] {M : Type*} [add_comm_group M] (P Q : module R M) (w : ∀ (r : R) (m : M), by { haveI := P, exact r • m } = by { haveI := Q, exact r • m }) : P = Q := begin unfreezingI { rcases P with ⟨⟨⟨⟨P⟩⟩⟩⟩, rcases Q with ⟨⟨⟨⟨Q⟩⟩⟩⟩ }, congr, funext r m, exact w r m, all_goals { apply proof_irrel_heq }, end section module variables [ring R] [add_comm_group M] [module R M] (r s : R) (x y : M) @[simp] theorem neg_smul : -r • x = - (r • x) := eq_neg_of_add_eq_zero (by rw [← add_smul, add_left_neg, zero_smul]) variables (R) theorem neg_one_smul (x : M) : (-1 : R) • x = -x := by simp variables {R} theorem sub_smul (r s : R) (y : M) : (r - s) • y = r • y - s • y := by simp [add_smul, sub_eq_add_neg] theorem smul_eq_zero {R E : Type*} [division_ring R] [add_comm_group E] [module R E] {c : R} {x : E} : c • x = 0 ↔ c = 0 ∨ x = 0 := ⟨λ h, or_iff_not_imp_left.2 $ λ hc, (units.mk0 c hc).smul_eq_zero.1 h, λ h, h.elim (λ hc, hc.symm ▸ zero_smul R x) (λ hx, hx.symm ▸ smul_zero c)⟩ end module @[priority 910] -- see Note [lower instance priority] instance semiring.to_semimodule [semiring R] : semimodule R R := { smul := (*), smul_add := mul_add, add_smul := add_mul, mul_smul := mul_assoc, one_smul := one_mul, zero_smul := zero_mul, smul_zero := mul_zero } @[simp] lemma smul_eq_mul [semiring R] {a a' : R} : a • a' = a * a' := rfl /-- A ring homomorphism `f : R →+* M` defines a module structure by `r • x = f r * x`. -/ def ring_hom.to_semimodule [semiring R] [semiring S] (f : R →+* S) : semimodule R S := { smul := λ r x, f r * x, smul_add := λ r x y, by unfold has_scalar.smul; rw [mul_add], add_smul := λ r s x, by unfold has_scalar.smul; rw [f.map_add, add_mul], mul_smul := λ r s x, by unfold has_scalar.smul; rw [f.map_mul, mul_assoc], one_smul := λ x, show f 1 * x = _, by rw [f.map_one, one_mul], zero_smul := λ x, show f 0 * x = 0, by rw [f.map_zero, zero_mul], smul_zero := λ r, mul_zero (f r) } /-- A map `f` between semimodules over a semiring is linear if it satisfies the two properties `f (x + y) = f x + f y` and `f (c • x) = c • f x`. The predicate `is_linear_map R f` asserts this property. A bundled version is available with `linear_map`, and should be favored over `is_linear_map` most of the time. -/ structure is_linear_map (R : Type u) {M : Type v} {M₂ : Type w} [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [semimodule R M] [semimodule R M₂] (f : M → M₂) : Prop := (map_add : ∀ x y, f (x + y) = f x + f y) (map_smul : ∀ (c : R) x, f (c • x) = c • f x) /-- A map `f` between semimodules over a semiring is linear if it satisfies the two properties `f (x + y) = f x + f y` and `f (c • x) = c • f x`. Elements of `linear_map R M M₂` (available under the notation `M →ₗ[R] M₂`) are bundled versions of such maps. An unbundled version is available with the predicate `is_linear_map`, but it should be avoided most of the time. -/ structure linear_map (R : Type u) (M : Type v) (M₂ : Type w) [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [semimodule R M] [semimodule R M₂] := (to_fun : M → M₂) (map_add' : ∀x y, to_fun (x + y) = to_fun x + to_fun y) (map_smul' : ∀(c : R) x, to_fun (c • x) = c • to_fun x) infixr ` →ₗ `:25 := linear_map _ notation M ` →ₗ[`:25 R:25 `] `:0 M₂:0 := linear_map R M M₂ namespace linear_map section add_comm_monoid variables [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] section variables [semimodule R M] [semimodule R M₂] instance : has_coe_to_fun (M →ₗ[R] M₂) := ⟨_, to_fun⟩ @[simp] lemma coe_mk (f : M → M₂) (h₁ h₂) : ((linear_map.mk f h₁ h₂ : M →ₗ[R] M₂) : M → M₂) = f := rfl /-- Identity map as a `linear_map` -/ def id : M →ₗ[R] M := ⟨id, λ _ _, rfl, λ _ _, rfl⟩ lemma id_apply (x : M) : @id R M _ _ _ x = x := rfl @[simp, norm_cast] lemma id_coe : ((linear_map.id : M →ₗ[R] M) : M → M) = _root_.id := by { ext x, refl } end section -- We can infer the module structure implicitly from the linear maps, -- rather than via typeclass resolution. variables {semimodule_M : semimodule R M} {semimodule_M₂ : semimodule R M₂} variables (f g : M →ₗ[R] M₂) @[simp] lemma to_fun_eq_coe : f.to_fun = ⇑f := rfl theorem is_linear : is_linear_map R f := ⟨f.2, f.3⟩ variables {f g} theorem coe_inj (h : (f : M → M₂) = g) : f = g := by cases f; cases g; cases h; refl @[ext] theorem ext (H : ∀ x, f x = g x) : f = g := coe_inj $ funext H lemma coe_fn_congr : Π {x x' : M}, x = x' → f x = f x' | _ _ rfl := rfl theorem ext_iff : f = g ↔ ∀ x, f x = g x := ⟨by { rintro rfl x, refl } , ext⟩ /-- If two linear maps are equal, they are equal at each point. -/ lemma lcongr_fun (h : f = g) (m : M) : f m = g m := congr_fun (congr_arg linear_map.to_fun h) m variables (f g) @[simp] lemma map_add (x y : M) : f (x + y) = f x + f y := f.map_add' x y @[simp] lemma map_smul (c : R) (x : M) : f (c • x) = c • f x := f.map_smul' c x @[simp] lemma map_zero : f 0 = 0 := by rw [← zero_smul R, map_smul f 0 0, zero_smul] instance : is_add_monoid_hom f := { map_add := map_add f, map_zero := map_zero f } /-- convert a linear map to an additive map -/ def to_add_monoid_hom : M →+ M₂ := { to_fun := f, map_zero' := f.map_zero, map_add' := f.map_add } @[simp] lemma to_add_monoid_hom_coe : ((f.to_add_monoid_hom) : M → M₂) = f := rfl @[simp] lemma map_sum {ι} {t : finset ι} {g : ι → M} : f (∑ i in t, g i) = (∑ i in t, f (g i)) := f.to_add_monoid_hom.map_sum _ _ end section variables {semimodule_M : semimodule R M} {semimodule_M₂ : semimodule R M₂} {semimodule_M₃ : semimodule R M₃} variables (f : M₂ →ₗ[R] M₃) (g : M →ₗ[R] M₂) /-- Composition of two linear maps is a linear map -/ def comp : M →ₗ[R] M₃ := ⟨f ∘ g, by simp, by simp⟩ @[simp] lemma comp_apply (x : M) : f.comp g x = f (g x) := rfl @[norm_cast] lemma comp_coe : (f : M₂ → M₃) ∘ (g : M → M₂) = f.comp g := rfl end end add_comm_monoid section add_comm_group variables [semiring R] [add_comm_group M] [add_comm_group M₂] variables {semimodule_M : semimodule R M} {semimodule_M₂ : semimodule R M₂} variables (f : M →ₗ[R] M₂) @[simp] lemma map_neg (x : M) : f (- x) = - f x := f.to_add_monoid_hom.map_neg x @[simp] lemma map_sub (x y : M) : f (x - y) = f x - f y := f.to_add_monoid_hom.map_sub x y instance : is_add_group_hom f := { map_add := map_add f} end add_comm_group end linear_map namespace is_linear_map section add_comm_monoid variables [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] variables [semimodule R M] [semimodule R M₂] include R /-- Convert an `is_linear_map` predicate to a `linear_map` -/ def mk' (f : M → M₂) (H : is_linear_map R f) : M →ₗ M₂ := ⟨f, H.1, H.2⟩ @[simp] theorem mk'_apply {f : M → M₂} (H : is_linear_map R f) (x : M) : mk' f H x = f x := rfl lemma is_linear_map_smul {R M : Type*} [comm_semiring R] [add_comm_monoid M] [semimodule R M] (c : R) : is_linear_map R (λ (z : M), c • z) := begin refine is_linear_map.mk (smul_add c) _, intros _ _, simp only [smul_smul, mul_comm] end --TODO: move lemma is_linear_map_smul' {R M : Type*} [semiring R] [add_comm_monoid M] [semimodule R M] (a : M) : is_linear_map R (λ (c : R), c • a) := is_linear_map.mk (λ x y, add_smul x y a) (λ x y, mul_smul x y a) variables {f : M → M₂} (lin : is_linear_map R f) include M M₂ lin lemma map_zero : f (0 : M) = (0 : M₂) := (lin.mk' f).map_zero end add_comm_monoid section add_comm_group variables [semiring R] [add_comm_group M] [add_comm_group M₂] variables [semimodule R M] [semimodule R M₂] include R lemma is_linear_map_neg : is_linear_map R (λ (z : M), -z) := is_linear_map.mk neg_add (λ x y, (smul_neg x y).symm) variables {f : M → M₂} (lin : is_linear_map R f) include M M₂ lin lemma map_neg (x : M) : f (- x) = - f x := (lin.mk' f).map_neg x lemma map_sub (x y) : f (x - y) = f x - f y := (lin.mk' f).map_sub x y end add_comm_group end is_linear_map /-- Ring of linear endomorphismsms of a module. -/ abbreviation module.End (R : Type u) (M : Type v) [semiring R] [add_comm_monoid M] [semimodule R M] := M →ₗ[R] M /-- Vector spaces are defined as an `abbreviation` for semimodules, if the base ring is a field. (A previous definition made `vector_space` a structure defined to be `module`.) This has as advantage that vector spaces are completely transparent for type class inference, which means that all instances for semimodules are immediately picked up for vector spaces as well. A cosmetic disadvantage is that one can not extend vector spaces as such, in definitions such as `normed_space`. The solution is to extend `semimodule` instead. -/ library_note "vector space definition" /-- A vector space is the same as a module, except the scalar ring is actually a field. (This adds commutativity of the multiplication and existence of inverses.) This is the traditional generalization of spaces like `ℝ^n`, which have a natural addition operation and a way to multiply them by real numbers, but no multiplication operation between vectors. -/ abbreviation vector_space (R : Type u) (M : Type v) [field R] [add_comm_group M] := semimodule R M namespace add_comm_monoid open add_monoid variables [add_comm_monoid M] /-- The natural ℕ-semimodule structure on any `add_comm_monoid`. -/ -- We don't make this a global instance, as it results in too many instances, -- and confusing ambiguity in the notation `n • x` when `n : ℕ`. def nat_semimodule : semimodule ℕ M := { smul := nsmul, smul_add := λ _ _ _, nsmul_add _ _ _, add_smul := λ _ _ _, add_nsmul _ _ _, mul_smul := λ _ _ _, mul_nsmul _ _ _, one_smul := one_nsmul, zero_smul := zero_nsmul, smul_zero := nsmul_zero } end add_comm_monoid namespace add_comm_group variables [add_comm_group M] /-- The natural ℤ-module structure on any `add_comm_group`. -/ -- We don't immediately make this a global instance, as it results in too many instances, -- and confusing ambiguity in the notation `n • x` when `n : ℤ`. -- We do turn it into a global instance, but only at the end of this file, -- and I remain dubious whether this is a good idea. def int_module : module ℤ M := { smul := gsmul, smul_add := λ _ _ _, gsmul_add _ _ _, add_smul := λ _ _ _, add_gsmul _ _ _, mul_smul := λ _ _ _, gsmul_mul _ _ _, one_smul := one_gsmul, zero_smul := zero_gsmul, smul_zero := gsmul_zero } instance : subsingleton (module ℤ M) := begin split, intros P Q, ext, -- isn't that lovely: `r • m = r • m` have one_smul : by { haveI := P, exact (1 : ℤ) • m } = by { haveI := Q, exact (1 : ℤ) • m }, begin rw [@one_smul ℤ _ _ (by { haveI := P, apply_instance, }) m], rw [@one_smul ℤ _ _ (by { haveI := Q, apply_instance, }) m], end, have nat_smul : ∀ n : ℕ, by { haveI := P, exact (n : ℤ) • m } = by { haveI := Q, exact (n : ℤ) • m }, begin intro n, induction n with n ih, { erw [zero_smul, zero_smul], }, { rw [int.coe_nat_succ, add_smul, add_smul], erw ih, rw [one_smul], } end, cases r, { rw [int.of_nat_eq_coe, nat_smul], }, { rw [int.neg_succ_of_nat_coe, neg_smul, neg_smul, nat_smul], } end end add_comm_group section local attribute [instance] add_comm_monoid.nat_semimodule lemma semimodule.smul_eq_smul (R : Type*) [semiring R] {M : Type*} [add_comm_monoid M] [semimodule R M] (n : ℕ) (b : M) : n • b = (n : R) • b := begin induction n with n ih, { rw [nat.cast_zero, zero_smul, zero_smul] }, { change (n + 1) • b = (n + 1 : R) • b, rw [add_smul, add_smul, one_smul, ih, one_smul] } end lemma semimodule.nsmul_eq_smul (R : Type*) [semiring R] {M : Type*} [add_comm_monoid M] [semimodule R M] (n : ℕ) (b : M) : n •ℕ b = (n : R) • b := semimodule.smul_eq_smul R n b lemma nat.smul_def {M : Type*} [add_comm_monoid M] (n : ℕ) (x : M) : n • x = n •ℕ x := rfl end section local attribute [instance] add_comm_group.int_module lemma gsmul_eq_smul {M : Type*} [add_comm_group M] (n : ℤ) (x : M) : gsmul n x = n • x := rfl lemma module.gsmul_eq_smul_cast (R : Type*) [ring R] {M : Type*} [add_comm_group M] [module R M] (n : ℤ) (b : M) : gsmul n b = (n : R) • b := begin cases n, { apply semimodule.nsmul_eq_smul, }, { dsimp, rw semimodule.nsmul_eq_smul R, push_cast, rw neg_smul, } end lemma module.gsmul_eq_smul {M : Type*} [add_comm_group M] [module ℤ M] (n : ℤ) (b : M) : gsmul n b = n • b := by rw [module.gsmul_eq_smul_cast ℤ, int.cast_id] end -- We prove this without using the `add_comm_group.int_module` instance, so the `•`s here -- come from whatever the local `module ℤ` structure actually is. lemma add_monoid_hom.map_int_module_smul [add_comm_group M] [add_comm_group M₂] [module ℤ M] [module ℤ M₂] (f : M →+ M₂) (x : ℤ) (a : M) : f (x • a) = x • f a := by simp only [← module.gsmul_eq_smul, f.map_gsmul] lemma add_monoid_hom.map_int_cast_smul [ring R] [add_comm_group M] [add_comm_group M₂] [module R M] [module R M₂] (f : M →+ M₂) (x : ℤ) (a : M) : f ((x : R) • a) = (x : R) • f a := by simp only [← module.gsmul_eq_smul_cast, f.map_gsmul] lemma add_monoid_hom.map_nat_cast_smul [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [semimodule R M] [semimodule R M₂] (f : M →+ M₂) (x : ℕ) (a : M) : f ((x : R) • a) = (x : R) • f a := by simp only [← semimodule.nsmul_eq_smul, f.map_nsmul] lemma add_monoid_hom.map_rat_cast_smul {R : Type*} [division_ring R] [char_zero R] {E : Type*} [add_comm_group E] [module R E] {F : Type*} [add_comm_group F] [module R F] (f : E →+ F) (c : ℚ) (x : E) : f ((c : R) • x) = (c : R) • f x := begin have : ∀ (x : E) (n : ℕ), 0 < n → f (((n⁻¹ : ℚ) : R) • x) = ((n⁻¹ : ℚ) : R) • f x, { intros x n hn, replace hn : (n : R) ≠ 0 := nat.cast_ne_zero.2 (ne_of_gt hn), conv_rhs { congr, skip, rw [← one_smul R x, ← mul_inv_cancel hn, mul_smul] }, rw [f.map_nat_cast_smul, smul_smul, rat.cast_inv, rat.cast_coe_nat, inv_mul_cancel hn, one_smul] }, refine c.num_denom_cases_on (λ m n hn hmn, _), rw [rat.mk_eq_div, div_eq_mul_inv, rat.cast_mul, int.cast_coe_nat, mul_smul, mul_smul, rat.cast_coe_int, f.map_int_cast_smul, this _ n hn] end lemma add_monoid_hom.map_rat_module_smul {E : Type*} [add_comm_group E] [vector_space ℚ E] {F : Type*} [add_comm_group F] [module ℚ F] (f : E →+ F) (c : ℚ) (x : E) : f (c • x) = c • f x := rat.cast_id c ▸ f.map_rat_cast_smul c x -- We finally turn on these instances globally: attribute [instance] add_comm_monoid.nat_semimodule add_comm_group.int_module /-- Reinterpret an additive homomorphism as a `ℤ`-linear map. -/ def add_monoid_hom.to_int_linear_map [add_comm_group M] [add_comm_group M₂] (f : M →+ M₂) : M →ₗ[ℤ] M₂ := ⟨f, f.map_add, f.map_int_module_smul⟩ /-- Reinterpret an additive homomorphism as a `ℚ`-linear map. -/ def add_monoid_hom.to_rat_linear_map [add_comm_group M] [vector_space ℚ M] [add_comm_group M₂] [vector_space ℚ M₂] (f : M →+ M₂) : M →ₗ[ℚ] M₂ := ⟨f, f.map_add, f.map_rat_module_smul⟩
5c9b67ed12326091394a56cdf855eead53951bf4
3f7026ea8bef0825ca0339a275c03b911baef64d
/src/category_theory/limits/shapes/products.lean
e43e6f5aadb6d9485fd960002d09006488a6e727
[ "Apache-2.0" ]
permissive
rspencer01/mathlib
b1e3afa5c121362ef0881012cc116513ab09f18c
c7d36292c6b9234dc40143c16288932ae38fdc12
refs/heads/master
1,595,010,346,708
1,567,511,503,000
1,567,511,503,000
206,071,681
0
0
Apache-2.0
1,567,513,643,000
1,567,513,643,000
null
UTF-8
Lean
false
false
3,126
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.limits.limits import category_theory.discrete_category universes v u open category_theory namespace category_theory.limits variables {β : Type v} variables {C : Type u} [𝒞 : category.{v+1} C] include 𝒞 -- We don't need an analogue of `pair` (for binary products), `parallel_pair` (for equalizers), -- or `(co)span`, since we already have `functor.of_function`. abbreviation fan (f : β → C) := cone (functor.of_function f) abbreviation cofan (f : β → C) := cocone (functor.of_function f) def fan.mk {f : β → C} {P : C} (p : Π b, P ⟶ f b) : fan f := { X := P, π := { app := p } } def cofan.mk {f : β → C} {P : C} (p : Π b, f b ⟶ P) : cofan f := { X := P, ι := { app := p } } @[simp] lemma fan.mk_π_app {f : β → C} {P : C} (p : Π b, P ⟶ f b) (b : β) : (fan.mk p).π.app b = p b := rfl @[simp] lemma cofan.mk_π_app {f : β → C} {P : C} (p : Π b, f b ⟶ P) (b : β) : (cofan.mk p).ι.app b = p b := rfl /-- `pi_obj f` computes the product of a family of elements `f`. (It is defined as an abbreviation for `limit (functor.of_function f)`, so for most facts about `pi_obj f`, you will just use general facts about limits.) -/ abbreviation pi_obj (f : β → C) [has_limit (functor.of_function f)] := limit (functor.of_function f) /-- `sigma_obj f` computes the coproduct of a family of elements `f`. (It is defined as an abbreviation for `colimit (functor.of_function f)`, so for most facts about `sigma_obj f`, you will just use general facts about colimits.) -/ abbreviation sigma_obj (f : β → C) [has_colimit (functor.of_function f)] := colimit (functor.of_function f) notation `∏ ` f:20 := pi_obj f notation `∐ ` f:20 := sigma_obj f abbreviation pi.π (f : β → C) [has_limit (functor.of_function f)] (b : β) : ∏ f ⟶ f b := limit.π (functor.of_function f) b abbreviation sigma.ι (f : β → C) [has_colimit (functor.of_function f)] (b : β) : f b ⟶ ∐ f := colimit.ι (functor.of_function f) b abbreviation pi.lift {f : β → C} [has_limit (functor.of_function f)] {P : C} (p : Π b, P ⟶ f b) : P ⟶ ∏ f := limit.lift _ (fan.mk p) abbreviation sigma.desc {f : β → C} [has_colimit (functor.of_function f)] {P : C} (p : Π b, f b ⟶ P) : ∐ f ⟶ P := colimit.desc _ (cofan.mk p) abbreviation pi.map {f g : β → C} [has_limits_of_shape.{v} (discrete β) C] (p : Π b, f b ⟶ g b) : ∏ f ⟶ ∏ g := lim.map (nat_trans.of_function p) abbreviation sigma.map {f g : β → C} [has_colimits_of_shape.{v} (discrete β) C] (p : Π b, f b ⟶ g b) : ∐ f ⟶ ∐ g := colim.map (nat_trans.of_function p) variables (C) class has_products := (has_limits_of_shape : Π (J : Type v), has_limits_of_shape.{v} (discrete J) C) class has_coproducts := (has_colimits_of_shape : Π (J : Type v), has_colimits_of_shape.{v} (discrete J) C) attribute [instance] has_products.has_limits_of_shape has_coproducts.has_colimits_of_shape end category_theory.limits
17b66c2b4d1cde0ca98d14207d05963f0dd99ae0
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/1985.lean
b4e99347c6377833fac476e27982a8071b845880
[ "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
632
lean
import Lean.Data.Json open Lean deriving instance BEq for Except example : Json.parse "\"\\u7406\\u79d1\"" == .ok "理科" := by native_decide example : Json.parse "\"\\u7406\\u79D1\"" == .ok "理科" := by native_decide example : Json.pretty "\x0b" == "\"\\u000b\"" := by native_decide example : Json.pretty "\x1b" == "\"\\u001b\"" := by native_decide example : Json.parse "\"\\u000b\"" == .ok "\x0b" := by native_decide example : Json.parse "\"\\u001b\"" == .ok "\x1b" := by native_decide example : Json.parse "\"\\u000B\"" == .ok "\x0b" := by native_decide example : Json.parse "\"\\u001B\"" == .ok "\x1b" := by native_decide
e3e6fd52415f2bcd28f2992a4c1f738b8e8bf4c9
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/linear_algebra/finsupp_vector_space.lean
efc5670b9683f69230cf0c838d207403ca394bc4
[ "Apache-2.0" ]
permissive
ramonfmir/mathlib
c5dc8b33155473fab97c38bd3aa6723dc289beaa
14c52e990c17f5a00c0cc9e09847af16fabbed25
refs/heads/master
1,661,979,343,526
1,660,830,384,000
1,660,830,384,000
182,072,989
0
0
null
1,555,585,876,000
1,555,585,876,000
null
UTF-8
Lean
false
false
7,537
lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import linear_algebra.dimension import linear_algebra.finite_dimensional import linear_algebra.std_basis /-! # Linear structures on function with finite support `ι →₀ M` This file contains results on the `R`-module structure on functions of finite support from a type `ι` to an `R`-module `M`, in particular in the case that `R` is a field. Furthermore, it contains some facts about isomorphisms of vector spaces from equality of dimension as well as the cardinality of finite dimensional vector spaces. ## TODO Move the second half of this file to more appropriate other files. -/ noncomputable theory local attribute [instance, priority 100] classical.prop_decidable open set linear_map submodule open_locale cardinal universes u v w namespace finsupp section ring variables {R : Type*} {M : Type*} {ι : Type*} variables [ring R] [add_comm_group M] [module R M] lemma linear_independent_single {φ : ι → Type*} {f : Π ι, φ ι → M} (hf : ∀i, linear_independent R (f i)) : linear_independent R (λ ix : Σ i, φ i, single ix.1 (f ix.1 ix.2)) := begin apply @linear_independent_Union_finite R _ _ _ _ ι φ (λ i x, single i (f i x)), { assume i, have h_disjoint : disjoint (span R (range (f i))) (ker (lsingle i)), { rw ker_lsingle, exact disjoint_bot_right }, apply (hf i).map h_disjoint }, { intros i t ht hit, refine (disjoint_lsingle_lsingle {i} t (disjoint_singleton_left.2 hit)).mono _ _, { rw span_le, simp only [supr_singleton], rw range_coe, apply range_comp_subset_range }, { refine supr₂_mono (λ i hi, _), rw [span_le, range_coe], apply range_comp_subset_range } } end end ring section semiring variables {R : Type*} {M : Type*} {ι : Type*} variables [semiring R] [add_comm_monoid M] [module R M] open linear_map submodule /-- The basis on `ι →₀ M` with basis vectors `λ ⟨i, x⟩, single i (b i x)`. -/ protected def basis {φ : ι → Type*} (b : ∀ i, basis (φ i) R M) : basis (Σ i, φ i) R (ι →₀ M) := basis.of_repr { to_fun := λ g, { to_fun := λ ix, (b ix.1).repr (g ix.1) ix.2, support := g.support.sigma (λ i, ((b i).repr (g i)).support), mem_support_to_fun := λ ix, by { simp only [finset.mem_sigma, mem_support_iff, and_iff_right_iff_imp, ne.def], intros b hg, simpa [hg] using b } }, inv_fun := λ g, { to_fun := λ i, (b i).repr.symm (g.comap_domain _ (set.inj_on_of_injective sigma_mk_injective _)), support := g.support.image sigma.fst, mem_support_to_fun := λ i, by { rw [ne.def, ← (b i).repr.injective.eq_iff, (b i).repr.apply_symm_apply, ext_iff], simp only [exists_prop, linear_equiv.map_zero, comap_domain_apply, zero_apply, exists_and_distrib_right, mem_support_iff, exists_eq_right, sigma.exists, finset.mem_image, not_forall] } }, left_inv := λ g, by { ext i, rw ← (b i).repr.injective.eq_iff, ext x, simp only [coe_mk, linear_equiv.apply_symm_apply, comap_domain_apply] }, right_inv := λ g, by { ext ⟨i, x⟩, simp only [coe_mk, linear_equiv.apply_symm_apply, comap_domain_apply] }, map_add' := λ g h, by { ext ⟨i, x⟩, simp only [coe_mk, add_apply, linear_equiv.map_add] }, map_smul' := λ c h, by { ext ⟨i, x⟩, simp only [coe_mk, smul_apply, linear_equiv.map_smul, ring_hom.id_apply] } } @[simp] lemma basis_repr {φ : ι → Type*} (b : ∀ i, basis (φ i) R M) (g : ι →₀ M) (ix) : (finsupp.basis b).repr g ix = (b ix.1).repr (g ix.1) ix.2 := rfl @[simp] lemma coe_basis {φ : ι → Type*} (b : ∀ i, basis (φ i) R M) : ⇑(finsupp.basis b) = λ (ix : Σ i, φ i), single ix.1 (b ix.1 ix.2) := funext $ λ ⟨i, x⟩, basis.apply_eq_iff.mpr $ begin ext ⟨j, y⟩, by_cases h : i = j, { cases h, simp only [basis_repr, single_eq_same, basis.repr_self, basis.finsupp.single_apply_left sigma_mk_injective] }, simp only [basis_repr, single_apply, h, false_and, if_false, linear_equiv.map_zero, zero_apply] end /-- The basis on `ι →₀ M` with basis vectors `λ i, single i 1`. -/ @[simps] protected def basis_single_one : basis ι R (ι →₀ R) := basis.of_repr (linear_equiv.refl _ _) @[simp] lemma coe_basis_single_one : (finsupp.basis_single_one : ι → (ι →₀ R)) = λ i, finsupp.single i 1 := funext $ λ i, basis.apply_eq_iff.mpr rfl end semiring section dim variables {K : Type u} {V : Type v} {ι : Type v} variables [field K] [add_comm_group V] [module K V] lemma dim_eq : module.rank K (ι →₀ V) = #ι * module.rank K V := begin let bs := basis.of_vector_space K V, rw [← bs.mk_eq_dim'', ← (finsupp.basis (λa:ι, bs)).mk_eq_dim'', cardinal.mk_sigma, cardinal.sum_const'] end end dim end finsupp section module variables {K : Type u} {V V₁ V₂ : Type v} {V' : Type w} variables [field K] variables [add_comm_group V] [module K V] variables [add_comm_group V₁] [module K V₁] variables [add_comm_group V₂] [module K V₂] variables [add_comm_group V'] [module K V'] open module lemma equiv_of_dim_eq_lift_dim (h : cardinal.lift.{w} (module.rank K V) = cardinal.lift.{v} (module.rank K V')) : nonempty (V ≃ₗ[K] V') := begin haveI := classical.dec_eq V, haveI := classical.dec_eq V', let m := basis.of_vector_space K V, let m' := basis.of_vector_space K V', rw [←cardinal.lift_inj.1 m.mk_eq_dim, ←cardinal.lift_inj.1 m'.mk_eq_dim] at h, rcases quotient.exact h with ⟨e⟩, let e := (equiv.ulift.symm.trans e).trans equiv.ulift, exact ⟨(m.repr ≪≫ₗ (finsupp.dom_lcongr e)) ≪≫ₗ m'.repr.symm⟩ end /-- Two `K`-vector spaces are equivalent if their dimension is the same. -/ def equiv_of_dim_eq_dim (h : module.rank K V₁ = module.rank K V₂) : V₁ ≃ₗ[K] V₂ := begin classical, exact classical.choice (equiv_of_dim_eq_lift_dim (cardinal.lift_inj.2 h)) end /-- An `n`-dimensional `K`-vector space is equivalent to `fin n → K`. -/ def fin_dim_vectorspace_equiv (n : ℕ) (hn : (module.rank K V) = n) : V ≃ₗ[K] (fin n → K) := begin have : cardinal.lift.{u} (n : cardinal.{v}) = cardinal.lift.{v} (n : cardinal.{u}), by simp, have hn := cardinal.lift_inj.{v u}.2 hn, rw this at hn, rw ←@dim_fin_fun K _ n at hn, exact classical.choice (equiv_of_dim_eq_lift_dim hn), end end module section module open module variables (K V : Type u) [field K] [add_comm_group V] [module K V] lemma cardinal_mk_eq_cardinal_mk_field_pow_dim [finite_dimensional K V] : #V = #K ^ module.rank K V := begin let s := basis.of_vector_space_index K V, let hs := basis.of_vector_space K V, calc #V = #(s →₀ K) : quotient.sound ⟨hs.repr.to_equiv⟩ ... = #(s → K) : quotient.sound ⟨finsupp.equiv_fun_on_fintype⟩ ... = _ : by rw [← cardinal.lift_inj.1 hs.mk_eq_dim, cardinal.power_def] end lemma cardinal_lt_aleph_0_of_finite_dimensional [fintype K] [finite_dimensional K V] : #V < ℵ₀ := begin letI : is_noetherian K V := is_noetherian.iff_fg.2 infer_instance, rw cardinal_mk_eq_cardinal_mk_field_pow_dim K V, exact cardinal.power_lt_aleph_0 (cardinal.lt_aleph_0_of_finite K) (is_noetherian.dim_lt_aleph_0 K V), end end module
d6caa979ad92ee1112e481f4458b1da468b2e39f
c9ba4946202cfd1e2586e71960dfed00503dcdf4
/src/meta_k/sort_schemas.lean
079054db4b89b56c22136663fdc60ce9f5fc0427
[]
no_license
ammkrn/learning_semantics_of_k
f55f669b369e32ef8407c16521b21ac5c106dc4d
c1487b538e1decc0f1fd389cd36bc36d2da012ab
refs/heads/master
1,588,081,593,954
1,552,449,093,000
1,552,449,093,000
175,315,800
0
0
null
null
null
null
UTF-8
Lean
false
false
657
lean
import .meta_sort import .meta_symbol import .meta_pattern -- List {s} def List : #Sort → #Sort | s := #sort "List" (lift [s]) def Set : #Sort → #Sort | carrier := #sort ( "Set") (lift [carrier]) def Bag : #Sort → #Sort | carrier := #sort ( "Bag") (lift [carrier]) def Bag_p (s : #Sort) (h : meta_sort_name s ≠ ( "Bag_p")) : #Sort := #sort ( "Bag_p") (lift [s]) def Map : #Sort → #Sort → #Sort | s s' := #sort ("Map") (lift [s, s']) def Map_p (s : #Sort) (h : meta_sort_name s ≠ ( "Map_p")) : #Sort := #sort ( "Map_p") (lift [s]) def Context : #Sort → #Sort → #Sort | s s' := #sort ( "Context") (lift [s, s'])
aa94ddb952e39159c57631d4734b379104956b4f
c9ba4946202cfd1e2586e71960dfed00503dcdf4
/src/object_k/object_sort.lean
542fe3b5e08fdc6c7e414d8a91c00430aca992b5
[]
no_license
ammkrn/learning_semantics_of_k
f55f669b369e32ef8407c16521b21ac5c106dc4d
c1487b538e1decc0f1fd389cd36bc36d2da012ab
refs/heads/master
1,588,081,593,954
1,552,449,093,000
1,552,449,093,000
175,315,800
0
0
null
null
null
null
UTF-8
Lean
false
false
3,686
lean
import meta_k.meta_sort import meta_k.meta_pattern import meta_k.meta_symbol @[reducible] def object_identifier := string inductive object_sort_constructor | mk : object_identifier → object_sort_constructor inductive object_sort_variable | mk : object_identifier → object_sort_variable mutual inductive object_sort, object_sort_list with object_sort : Type | mk : object_sort_constructor → object_sort_list → object_sort with object_sort_list : Type | nil : object_sort_list | cons : object_sort → object_sort_list → object_sort_list open object_sort_constructor open object_sort_variable open object_sort open object_sort_list instance : decidable_eq object_sort_constructor := by tactic.mk_dec_eq_instance instance : decidable_eq object_sort_variable := by tactic.mk_dec_eq_instance instance : decidable_eq object_sort := by tactic.mk_dec_eq_instance instance : decidable_eq object_sort_list := by tactic.mk_dec_eq_instance def object_sort_constructor.to_string : object_sort_constructor → string | (mk str) := str def object_sort_variable.to_string : object_sort_variable → string | (mk str) := str instance : has_repr object_sort_constructor := ⟨ object_sort_constructor.to_string ⟩ instance : has_repr object_sort_variable := ⟨ object_sort_variable.to_string ⟩ -- ######################### notation `~Sort` := object_sort notation `~SortList` := list object_sort notation `~nilSortList` := object_sort_list.nil notation `~consSortList` := object_sort_list.cons notation `~sort` := object_sort.mk class object_has_sort (α : Type) := (get_sort : α → object_sort) def object_sort_list.to_list_object_sort : object_sort_list → ~SortList | nil := [] | (cons hd tl) := hd :: (object_sort_list.to_list_object_sort tl) mutual def object_sort_to_string, object_sort_list_to_string with object_sort_to_string : object_sort → string | (object_sort.mk ident L) := "Sort : (" ++ repr ident ++ ", " ++ (object_sort_list_to_string L) ++ "), " with object_sort_list_to_string : object_sort_list → string | (object_sort_list.nil) := "sort_ε" | (object_sort_list.cons s l) := object_sort_to_string s ++ object_sort_list_to_string l def pretty_object_sort_list_to_string : object_sort_list → string | object_sort_list.nil := "" | l := "[" ++ string.popn_back (object_sort_list_to_string l) 7 ++ "]" instance : has_repr object_sort_list := ⟨ pretty_object_sort_list_to_string ⟩ def pretty_object_sort_to_string : object_sort → string | (object_sort.mk ident object_sort_list.nil) := (repr ident) | (object_sort.mk ident L) := (repr ident) ++ " : " ++ repr L def object_sort_get_name : object_sort → string | (object_sort.mk ident _) := (repr ident) instance : has_repr object_sort := ⟨ pretty_object_sort_to_string ⟩ def list_object_sort.to_object_sort_list : ~SortList → object_sort_list | [] := object_sort_list.nil | (hd :: tl) := object_sort_list.cons hd (list_object_sort.to_object_sort_list tl) instance object_sort_list_to_list_object_sort_lift : has_lift object_sort_list (list object_sort) := ⟨ object_sort_list.to_list_object_sort ⟩ instance list_object_sort_to_object_sort_list_lift : has_lift (list object_sort) (object_sort_list) := ⟨ list_object_sort.to_object_sort_list ⟩ def object_sort_params_for_class : object_sort → ~SortList | (object_sort.mk ident L) := lift L instance : is_Sort object_sort := ⟨ object_sort_params_for_class ⟩ instance : inhabited object_sort := ⟨ object_sort.mk ⟨"Nat"⟩ ~nilSortList ⟩ def name_fn : string → string | "O" := "zero" | "S" := "succ" | "+" := "plus" | "ε" := "nil" | "::" := "cons" | "@" := "append" | s := s
f8bd7414f0ce4693ad1da5456a21ec820b66b4db
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/algebra/group/with_one.lean
72154a18de66bacddbee3122746c01afd9e2a164
[ "Apache-2.0" ]
permissive
gebner/mathlib
eab0150cc4f79ec45d2016a8c21750244a2e7ff0
cc6a6edc397c55118df62831e23bfbd6e6c6b4ab
refs/heads/master
1,625,574,853,976
1,586,712,827,000
1,586,712,827,000
99,101,412
1
0
Apache-2.0
1,586,716,389,000
1,501,667,958,000
Lean
UTF-8
Lean
false
false
7,500
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Johan Commelin -/ import algebra.group.to_additive algebra.group.basic algebra.group.hom universes u v variable {α : Type u} @[to_additive] def with_one (α) := option α namespace with_one @[to_additive] instance : monad with_one := option.monad @[to_additive] instance : has_one (with_one α) := ⟨none⟩ @[to_additive] instance : inhabited (with_one α) := ⟨1⟩ @[to_additive] instance : has_coe_t α (with_one α) := ⟨some⟩ @[simp, to_additive] lemma one_ne_coe {a : α} : (1 : with_one α) ≠ a := λ h, option.no_confusion h @[simp, to_additive] lemma coe_ne_one {a : α} : (a : with_one α) ≠ (1 : with_one α) := λ h, option.no_confusion h @[to_additive] lemma ne_one_iff_exists : ∀ {x : with_one α}, x ≠ 1 ↔ ∃ (a : α), x = a | 1 := ⟨λ h, false.elim $ h rfl, by { rintros ⟨a,ha⟩ h, simpa using h }⟩ | (a : α) := ⟨λ h, ⟨a, rfl⟩, λ h, with_one.coe_ne_one⟩ @[to_additive] lemma coe_inj {a b : α} : (a : with_one α) = b ↔ a = b := option.some_inj @[elab_as_eliminator, to_additive] protected lemma cases_on {P : with_one α → Prop} : ∀ (x : with_one α), P 1 → (∀ a : α, P a) → P x := option.cases_on @[to_additive] instance [has_mul α] : has_mul (with_one α) := { mul := option.lift_or_get (*) } @[simp, to_additive] lemma mul_coe [has_mul α] (a b : α) : (a : with_one α) * b = (a * b : α) := rfl @[to_additive add_monoid] instance [semigroup α] : monoid (with_one α) := { mul_assoc := (option.lift_or_get_assoc _).1, one_mul := (option.lift_or_get_is_left_id _).1, mul_one := (option.lift_or_get_is_right_id _).1, ..with_one.has_one, ..with_one.has_mul } @[to_additive add_comm_monoid] instance [comm_semigroup α] : comm_monoid (with_one α) := { mul_comm := (option.lift_or_get_comm _).1, ..with_one.monoid } section lift variables [semigroup α] {β : Type v} [monoid β] /-- Lift a semigroup homomorphism `f` to a bundled monoid homorphism. We have no bundled semigroup homomorphisms, so this function takes `∀ x y, f (x * y) = f x * f y` as an explicit argument. -/ @[to_additive] def lift (f : α → β) (hf : ∀ x y, f (x * y) = f x * f y) : (with_one α) →* β := { to_fun := λ x, option.cases_on x 1 f, map_one' := rfl, map_mul' := λ x y, with_one.cases_on x (by { rw one_mul, exact (one_mul _).symm }) $ λ x, with_one.cases_on y (by { rw mul_one, exact (mul_one _).symm }) $ λ y, hf x y } variables (f : α → β) (hf : ∀ x y, f (x * y) = f x * f y) @[simp, to_additive] lemma lift_coe (x : α) : lift f hf x = f x := rfl @[simp, to_additive] lemma lift_one : lift f hf 1 = 1 := rfl @[to_additive] theorem lift_unique (f : with_one α →* β) : f = lift (f ∘ coe) (λ x y, f.map_mul x y) := monoid_hom.ext $ λ x, with_one.cases_on x f.map_one $ λ x, rfl end lift section map variables {β : Type v} [semigroup α] [semigroup β] @[to_additive] def map (f : α → β) (hf : ∀ x y, f (x * y) = f x * f y) : with_one α →* with_one β := lift (coe ∘ f) (λ x y, coe_inj.2 $ hf x y) end map end with_one namespace with_zero instance [one : has_one α] : has_one (with_zero α) := { ..one } instance [has_one α] : zero_ne_one_class (with_zero α) := { zero_ne_one := λ h, option.no_confusion h, ..with_zero.has_zero, ..with_zero.has_one } lemma coe_one [has_one α] : ((1 : α) : with_zero α) = 1 := rfl instance [has_mul α] : mul_zero_class (with_zero α) := { mul := λ o₁ o₂, o₁.bind (λ a, option.map (λ b, a * b) o₂), zero_mul := λ a, rfl, mul_zero := λ a, by cases a; refl, ..with_zero.has_zero } @[simp] lemma mul_coe [has_mul α] (a b : α) : (a : with_zero α) * b = (a * b : α) := rfl instance [semigroup α] : semigroup (with_zero α) := { mul_assoc := λ a b c, match a, b, c with | none, _, _ := rfl | some a, none, _ := rfl | some a, some b, none := rfl | some a, some b, some c := congr_arg some (mul_assoc _ _ _) end, ..with_zero.mul_zero_class } instance [comm_semigroup α] : comm_semigroup (with_zero α) := { mul_comm := λ a b, match a, b with | none, _ := (mul_zero _).symm | some a, none := rfl | some a, some b := congr_arg some (mul_comm _ _) end, ..with_zero.semigroup } instance [monoid α] : monoid (with_zero α) := { one_mul := λ a, match a with | none := rfl | some a := congr_arg some $ one_mul _ end, mul_one := λ a, match a with | none := rfl | some a := congr_arg some $ mul_one _ end, ..with_zero.zero_ne_one_class, ..with_zero.semigroup } instance [comm_monoid α] : comm_monoid (with_zero α) := { ..with_zero.monoid, ..with_zero.comm_semigroup } definition inv [has_inv α] (x : with_zero α) : with_zero α := do a ← x, return a⁻¹ instance [has_inv α] : has_inv (with_zero α) := ⟨with_zero.inv⟩ @[simp] lemma inv_coe [has_inv α] (a : α) : (a : with_zero α)⁻¹ = (a⁻¹ : α) := rfl @[simp] lemma inv_zero [has_inv α] : (0 : with_zero α)⁻¹ = 0 := rfl section group variables [group α] @[simp] lemma inv_one : (1 : with_zero α)⁻¹ = 1 := show ((1⁻¹ : α) : with_zero α) = 1, by simp [coe_one] definition div (x y : with_zero α) : with_zero α := x * y⁻¹ instance : has_div (with_zero α) := ⟨with_zero.div⟩ @[simp] lemma zero_div (a : with_zero α) : 0 / a = 0 := rfl @[simp] lemma div_zero (a : with_zero α) : a / 0 = 0 := by change a * _ = _; simp lemma div_coe (a b : α) : (a : with_zero α) / b = (a * b⁻¹ : α) := rfl lemma one_div (x : with_zero α) : 1 / x = x⁻¹ := one_mul _ @[simp] lemma div_one : ∀ (x : with_zero α), x / 1 = x | 0 := rfl | (a : α) := show _ * _ = _, by simp @[simp] lemma mul_right_inv : ∀ (x : with_zero α) (h : x ≠ 0), x * x⁻¹ = 1 | 0 h := false.elim $ h rfl | (a : α) h := by simp [coe_one] @[simp] lemma mul_left_inv : ∀ (x : with_zero α) (h : x ≠ 0), x⁻¹ * x = 1 | 0 h := false.elim $ h rfl | (a : α) h := by simp [coe_one] @[simp] lemma mul_inv_rev : ∀ (x y : with_zero α), (x * y)⁻¹ = y⁻¹ * x⁻¹ | 0 0 := rfl | 0 (b : α) := rfl | (a : α) 0 := rfl | (a : α) (b : α) := by simp @[simp] lemma mul_div_cancel {a b : with_zero α} (hb : b ≠ 0) : a * b / b = a := show _ * _ * _ = _, by simp [mul_assoc, hb] @[simp] lemma div_mul_cancel {a b : with_zero α} (hb : b ≠ 0) : a / b * b = a := show _ * _ * _ = _, by simp [mul_assoc, hb] lemma div_eq_iff_mul_eq {a b c : with_zero α} (hb : b ≠ 0) : a / b = c ↔ c * b = a := by split; intro h; simp [h.symm, hb] end group section comm_group variables [comm_group α] {a b c d : with_zero α} lemma div_eq_div (hb : b ≠ 0) (hd : d ≠ 0) : a / b = c / d ↔ a * d = b * c := begin rw ne_zero_iff_exists at hb hd, rcases hb with ⟨b, rfl⟩, rcases hd with ⟨d, rfl⟩, induction a using with_zero.cases_on; induction c using with_zero.cases_on, { refl }, { simp [div_coe] }, { simp [div_coe] }, erw [with_zero.coe_inj, with_zero.coe_inj], show a * b⁻¹ = c * d⁻¹ ↔ a * d = b * c, split; intro H, { rw mul_inv_eq_iff_eq_mul at H, rw [H, mul_right_comm, inv_mul_cancel_right, mul_comm] }, { rw [mul_inv_eq_iff_eq_mul, mul_right_comm, mul_comm c, ← H, mul_inv_cancel_right] } end end comm_group end with_zero
173e8c1981ba2f8c98cdad3695f0d13dd02e3d13
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/06_Inductive_Types.org.20.lean
b1e606100a682f06adbd90334769a9297e371b03
[]
no_license
cjmazey/lean-tutorial
ba559a49f82aa6c5848b9bf17b7389bf7f4ba645
381f61c9fcac56d01d959ae0fa6e376f2c4e3b34
refs/heads/master
1,610,286,098,832
1,447,124,923,000
1,447,124,923,000
43,082,433
0
0
null
null
null
null
UTF-8
Lean
false
false
154
lean
/- page 83 -/ import standard namespace hide -- BEGIN inductive sigma {A : Type} (B : A → Type) := dpair : Π a : A, B a → sigma B -- END end hide
8ea20558a9c74b44d22ab287d146632369f1ea59
75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2
/tests/lean/extra/597a.hlean
4bed4467497f2bc2de31359431a89f6c9207358a
[ "Apache-2.0" ]
permissive
jroesch/lean
30ef0860fa905d35b9ad6f76de1a4f65c9af6871
3de4ec1a6ce9a960feb2a48eeea8b53246fa34f2
refs/heads/master
1,586,090,835,348
1,455,142,203,000
1,455,142,277,000
51,536,958
1
0
null
1,455,215,811,000
1,455,215,811,000
null
UTF-8
Lean
false
false
96
hlean
open equiv open equiv.ops constants (A B : Type₀) (f : A ≃ B) definition foo : A → B := f
8a19f1343c8270aadd675e84cef3568df0982cbd
e0f9ba56b7fedc16ef8697f6caeef5898b435143
/src/algebra/direct_sum.lean
ff425fec3fed0a4bd2c834810e97eac99cc12277
[ "Apache-2.0" ]
permissive
anrddh/mathlib
6a374da53c7e3a35cb0298b0cd67824efef362b4
a4266a01d2dcb10de19369307c986d038c7bb6a6
refs/heads/master
1,656,710,827,909
1,589,560,456,000
1,589,560,456,000
264,271,800
0
0
Apache-2.0
1,589,568,062,000
1,589,568,061,000
null
UTF-8
Lean
false
false
6,315
lean
/- Copyright (c) 2019 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau Direct sum of abelian groups, indexed by a discrete type. -/ import data.dfinsupp universes u v w u₁ variables (ι : Type v) [decidable_eq ι] (β : ι → Type w) [Π i, add_comm_group (β i)] def direct_sum : Type* := Π₀ i, β i namespace direct_sum variables {ι β} instance : add_comm_group (direct_sum ι β) := dfinsupp.add_comm_group instance : inhabited (direct_sum ι β) := ⟨0⟩ variables β def mk : Π s : finset ι, (Π i : (↑s : set ι), β i.1) → direct_sum ι β := dfinsupp.mk def of : Π i : ι, β i → direct_sum ι β := dfinsupp.single variables {β} instance mk.is_add_group_hom (s : finset ι) : is_add_group_hom (mk β s) := { map_add := λ _ _, dfinsupp.mk_add } @[simp] lemma mk_zero (s : finset ι) : mk β s 0 = 0 := is_add_group_hom.map_zero _ @[simp] lemma mk_add (s : finset ι) (x y) : mk β s (x + y) = mk β s x + mk β s y := is_add_hom.map_add _ x y @[simp] lemma mk_neg (s : finset ι) (x) : mk β s (-x) = -mk β s x := is_add_group_hom.map_neg _ x @[simp] lemma mk_sub (s : finset ι) (x y) : mk β s (x - y) = mk β s x - mk β s y := is_add_group_hom.map_sub _ x y instance of.is_add_group_hom (i : ι) : is_add_group_hom (of β i) := { map_add := λ _ _, dfinsupp.single_add } @[simp] lemma of_zero (i : ι) : of β i 0 = 0 := is_add_group_hom.map_zero _ @[simp] lemma of_add (i : ι) (x y) : of β i (x + y) = of β i x + of β i y := is_add_hom.map_add _ x y @[simp] lemma of_neg (i : ι) (x) : of β i (-x) = -of β i x := is_add_group_hom.map_neg _ x @[simp] lemma of_sub (i : ι) (x y) : of β i (x - y) = of β i x - of β i y := is_add_group_hom.map_sub _ x y theorem mk_inj (s : finset ι) : function.injective (mk β s) := dfinsupp.mk_inj s theorem of_inj (i : ι) : function.injective (of β i) := λ x y H, congr_fun (mk_inj _ H) ⟨i, by simp⟩ @[elab_as_eliminator] protected theorem induction_on {C : direct_sum ι β → Prop} (x : direct_sum ι β) (H_zero : C 0) (H_basic : ∀ (i : ι) (x : β i), C (of β i x)) (H_plus : ∀ x y, C x → C y → C (x + y)) : C x := begin apply dfinsupp.induction x H_zero, intros i b f h1 h2 ih, solve_by_elim end variables {γ : Type u₁} [add_comm_group γ] variables (φ : Π i, β i → γ) [Π i, is_add_group_hom (φ i)] variables (φ) def to_group (f : direct_sum ι β) : γ := quotient.lift_on f (λ x, x.2.to_finset.sum $ λ i, φ i (x.1 i)) $ λ x y H, begin have H1 : x.2.to_finset ∩ y.2.to_finset ⊆ x.2.to_finset, from finset.inter_subset_left _ _, have H2 : x.2.to_finset ∩ y.2.to_finset ⊆ y.2.to_finset, from finset.inter_subset_right _ _, refine (finset.sum_subset H1 _).symm.trans ((finset.sum_congr rfl _).trans (finset.sum_subset H2 _)), { intros i H1 H2, rw finset.mem_inter at H2, rw H i, simp only [multiset.mem_to_finset] at H1 H2, rw [(y.3 i).resolve_left (mt (and.intro H1) H2), is_add_group_hom.map_zero (φ i)] }, { intros i H1, rw H i }, { intros i H1 H2, rw finset.mem_inter at H2, rw ← H i, simp only [multiset.mem_to_finset] at H1 H2, rw [(x.3 i).resolve_left (mt (λ H3, and.intro H3 H1) H2), is_add_group_hom.map_zero (φ i)] } end variables {φ} instance to_group.is_add_group_hom : is_add_group_hom (to_group φ) := { map_add := assume f g, begin refine quotient.induction_on f (λ x, _), refine quotient.induction_on g (λ y, _), change finset.sum _ _ = finset.sum _ _ + finset.sum _ _, simp only, conv { to_lhs, congr, skip, funext, rw is_add_hom.map_add (φ i) }, simp only [finset.sum_add_distrib], congr' 1, { refine (finset.sum_subset _ _).symm, { intro i, simp only [multiset.mem_to_finset, multiset.mem_add], exact or.inl }, { intros i H1 H2, simp only [multiset.mem_to_finset, multiset.mem_add] at H2, rw [(x.3 i).resolve_left H2, is_add_group_hom.map_zero (φ i)] } }, { refine (finset.sum_subset _ _).symm, { intro i, simp only [multiset.mem_to_finset, multiset.mem_add], exact or.inr }, { intros i H1 H2, simp only [multiset.mem_to_finset, multiset.mem_add] at H2, rw [(y.3 i).resolve_left H2, is_add_group_hom.map_zero (φ i)] } } end } variables (φ) @[simp] lemma to_group_zero : to_group φ 0 = 0 := is_add_group_hom.map_zero _ @[simp] lemma to_group_add (x y) : to_group φ (x + y) = to_group φ x + to_group φ y := is_add_hom.map_add _ x y @[simp] lemma to_group_neg (x) : to_group φ (-x) = -to_group φ x := is_add_group_hom.map_neg _ x @[simp] lemma to_group_sub (x y) : to_group φ (x - y) = to_group φ x - to_group φ y := is_add_group_hom.map_sub _ x y @[simp] lemma to_group_of (i) (x : β i) : to_group φ (of β i x) = φ i x := (add_zero _).trans $ congr_arg (φ i) $ show (if H : i ∈ finset.singleton i then x else 0) = x, from dif_pos $ finset.mem_singleton_self i variables (ψ : direct_sum ι β → γ) [is_add_group_hom ψ] theorem to_group.unique (f : direct_sum ι β) : ψ f = @to_group _ _ _ _ _ _ (λ i, ψ ∘ of β i) (λ i, is_add_group_hom.comp (of β i) ψ) f := by haveI : ∀ i, is_add_group_hom (ψ ∘ of β i) := (λ _, is_add_group_hom.comp _ _); exact direct_sum.induction_on f (by rw [is_add_group_hom.map_zero ψ, is_add_group_hom.map_zero (to_group (λ i, ψ ∘ of β i))]) (λ i x, by rw [to_group_of]) (λ x y ihx ihy, by rw [is_add_hom.map_add ψ, is_add_hom.map_add (to_group (λ i, ψ ∘ of β i)), ihx, ihy]) variables (β) def set_to_set (S T : set ι) (H : S ⊆ T) : direct_sum S (β ∘ subtype.val) → direct_sum T (β ∘ subtype.val) := to_group $ λ i, of (β ∘ @subtype.val _ T) ⟨i.1, H i.2⟩ variables {β} instance (S T : set ι) (H : S ⊆ T) : is_add_group_hom (set_to_set β S T H) := to_group.is_add_group_hom protected def id (M : Type v) [add_comm_group M] : direct_sum punit (λ _, M) ≃ M := { to_fun := direct_sum.to_group (λ _, id), inv_fun := of (λ _, M) punit.star, left_inv := λ x, direct_sum.induction_on x (by rw [to_group_zero, of_zero]) (λ ⟨⟩ x, by rw [to_group_of]; refl) (λ x y ihx ihy, by rw [to_group_add, of_add, ihx, ihy]), right_inv := λ x, to_group_of _ _ _ } instance : has_coe_to_fun (direct_sum ι β) := dfinsupp.has_coe_to_fun end direct_sum
c28fcdba82cf27a8b3add344b8ff04881a41ddb5
4727251e0cd73359b15b664c3170e5d754078599
/src/category_theory/category/Kleisli.lean
2dd2d7d5c431a09397e07364ca7a6a511d73b611
[ "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
1,626
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import category_theory.category.basic /-! # The Kleisli construction on the Type category Define the Kleisli category for (control) monads. `category_theory/monad/kleisli` defines the general version for a monad on `C`, and demonstrates the equivalence between the two. ## TODO Generalise this to work with category_theory.monad -/ universes u v namespace category_theory /-- The Kleisli category on the (type-)monad `m`. Note that the monad is not assumed to be lawful yet. -/ @[nolint unused_arguments] def Kleisli (m : Type u → Type v) := Type u /-- Construct an object of the Kleisli category from a type. -/ def Kleisli.mk (m) (α : Type u) : Kleisli m := α instance Kleisli.category_struct {m} [monad.{u v} m] : category_struct (Kleisli m) := { hom := λ α β, α → m β, id := λ α x, pure x, comp := λ X Y Z f g, f >=> g } instance Kleisli.category {m} [monad.{u v} m] [is_lawful_monad m] : category (Kleisli m) := by refine { id_comp' := _, comp_id' := _, assoc' := _ }; intros; ext; unfold_projs; simp only [(>=>)] with functor_norm @[simp] lemma Kleisli.id_def {m} [monad m] (α : Kleisli m) : 𝟙 α = @pure m _ α := rfl lemma Kleisli.comp_def {m} [monad m] (α β γ : Kleisli m) (xs : α ⟶ β) (ys : β ⟶ γ) (a : α) : (xs ≫ ys) a = xs a >>= ys := rfl instance : inhabited (Kleisli id) := ⟨punit⟩ instance {α : Type u} [inhabited α] : inhabited (Kleisli.mk id α) := ⟨show α, from default⟩ end category_theory
ee473633260002ab49f4a9f96d53d5e7296abd32
5749d8999a76f3a8fddceca1f6941981e33aaa96
/src/topology/algebra/module.lean
cb81ce0d47112e19bd51b4a8cb5f2e599a55561c
[ "Apache-2.0" ]
permissive
jdsalchow/mathlib
13ab43ef0d0515a17e550b16d09bd14b76125276
497e692b946d93906900bb33a51fd243e7649406
refs/heads/master
1,585,819,143,348
1,580,072,892,000
1,580,072,892,000
154,287,128
0
0
Apache-2.0
1,540,281,610,000
1,540,281,609,000
null
UTF-8
Lean
false
false
18,432
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 -/ import topology.algebra.ring linear_algebra.basic ring_theory.algebra /-! # Theory of topological modules and continuous linear maps. We define classes `topological_semimodule`, `topological_module` and `topological_vector_spaces`, as extensions of the corresponding algebraic classes where the algebraic operations are continuous. We also define continuous linear maps, as linear maps between topological modules which are continuous. The set of continuous linear maps between the topological `R`-modules `M` and `M₂` is denoted by `M →L[R] M₂`. Continuous linear equivalences are denoted by `M ≃L[R] M₂`. ## Implementation notes Topological vector spaces are defined as an `abbreviation` for topological modules, if the base ring is a field. This has as advantage that topological vector spaces are completely transparent for type class inference, which means that all instances for topological modules are immediately picked up for vector spaces as well. A cosmetic disadvantage is that one can not extend topological vector spaces. The solution is to extend `topological_module` instead. -/ open topological_space universes u v w u' section prio set_option default_priority 100 -- see Note [default priority] /-- A topological semimodule, over a semiring which is also a topological space, is a semimodule in which scalar multiplication is continuous. In applications, R will be a topological semiring and M a topological additive semigroup, but this is not needed for the definition -/ class topological_semimodule (R : Type u) (M : Type v) [semiring R] [topological_space R] [topological_space M] [add_comm_monoid M] [semimodule R M] : Prop := (continuous_smul : continuous (λp : R × M, p.1 • p.2)) end prio section variables {R : Type u} {M : Type v} [semiring R] [topological_space R] [topological_space M] [add_comm_monoid M] [semimodule R M] [topological_semimodule R M] lemma continuous_smul : continuous (λp:R×M, p.1 • p.2) := topological_semimodule.continuous_smul R M lemma continuous.smul {M₂ : Type*} [topological_space M₂] {f : M₂ → R} {g : M₂ → M} (hf : continuous f) (hg : continuous g) : continuous (λp, f p • g p) := continuous_smul.comp (hf.prod_mk hg) end section prio set_option default_priority 100 -- see Note [default priority] /-- A topological module, over a ring which is also a topological space, is a module in which scalar multiplication is continuous. In applications, `R` will be a topological ring and `M` a topological additive group, but this is not needed for the definition -/ class topological_module (R : Type u) (M : Type v) [ring R] [topological_space R] [topological_space M] [add_comm_group M] [module R M] extends topological_semimodule R M : Prop /-- A topological vector space is a topological module over a field. -/ abbreviation topological_vector_space (R : Type u) (M : Type v) [discrete_field R] [topological_space R] [topological_space M] [add_comm_group M] [module R M] := topological_module R M end prio section variables {R : Type*} {M : Type*} [ring R] [topological_space R] [topological_space M] [add_comm_group M] [module R M] [topological_module R M] /-- Scalar multiplication by a unit is a homeomorphism from a topological module onto itself. -/ protected def homeomorph.smul_of_unit (a : units R) : M ≃ₜ M := { to_fun := λ x, (a : R) • x, inv_fun := λ x, ((a⁻¹ : units R) : R) • x, right_inv := λ x, calc (a : R) • ((a⁻¹ : units R) : R) • x = x : by rw [smul_smul, units.mul_inv, one_smul], left_inv := λ x, calc ((a⁻¹ : units R) : R) • (a : R) • x = x : by rw [smul_smul, units.inv_mul, one_smul], continuous_to_fun := continuous_const.smul continuous_id, continuous_inv_fun := continuous_const.smul continuous_id } lemma is_open_map_smul_of_unit (a : units R) : is_open_map (λ (x : M), (a : R) • x) := (homeomorph.smul_of_unit a).is_open_map lemma is_closed_map_smul_of_unit (a : units R) : is_closed_map (λ (x : M), (a : R) • x) := (homeomorph.smul_of_unit a).is_closed_map end section variables {R : Type*} {M : Type*} {a : R} [discrete_field R] [topological_space R] [topological_space M] [add_comm_group M] [vector_space R M] [topological_vector_space R M] set_option class.instance_max_depth 36 /-- Scalar multiplication by a non-zero field element is a homeomorphism from a topological vector space onto itself. -/ protected def homeomorph.smul_of_ne_zero (ha : a ≠ 0) : M ≃ₜ M := {.. homeomorph.smul_of_unit ((equiv.units_equiv_ne_zero _).inv_fun ⟨_, ha⟩)} lemma is_open_map_smul_of_ne_zero (ha : a ≠ 0) : is_open_map (λ (x : M), a • x) := (homeomorph.smul_of_ne_zero ha).is_open_map lemma is_closed_map_smul_of_ne_zero (ha : a ≠ 0) : is_closed_map (λ (x : M), a • x) := (homeomorph.smul_of_ne_zero ha).is_closed_map end /-- 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*) [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₂] extends linear_map R M M₂ := (cont : continuous to_fun) notation M ` →L[`:25 R `] ` M₂ := continuous_linear_map 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`. -/ structure continuous_linear_equiv (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₂] extends linear_equiv R M M₂ := (continuous_to_fun : continuous to_fun) (continuous_inv_fun : continuous inv_fun) notation M ` ≃L[`:50 R `] ` M₂ := continuous_linear_equiv R M M₂ namespace continuous_linear_map section general_ring /- Properties that hold for non-necessarily commutative rings. -/ variables {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₃] [module R M] [module R M₂] [module R M₃] /-- Coerce continuous linear maps to linear maps. -/ instance : has_coe (M →L[R] M₂) (M →ₗ[R] M₂) := ⟨to_linear_map⟩ protected lemma continuous (f : M →L[R] M₂) : continuous f := f.2 /-- Coerce continuous linear maps to functions. -/ instance to_fun : has_coe_to_fun $ M →L[R] M₂ := ⟨_, λ f, f.to_fun⟩ @[ext] theorem ext {f g : M →L[R] M₂} (h : ∀ x, f x = g x) : f = g := by cases f; cases g; congr' 1; ext x; apply h theorem ext_iff {f g : M →L[R] M₂} : f = g ↔ ∀ x, f x = g x := ⟨λ h x, by rw h, by ext⟩ variables (c : R) (f g : M →L[R] M₂) (h : M₂ →L[R] 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_sub : f (x - y) = f x - f y := (to_linear_map _).map_sub _ _ @[simp] lemma map_smul : f (c • x) = c • f x := (to_linear_map _).map_smul _ _ @[simp] lemma map_neg : f (-x) = - (f x) := (to_linear_map _).map_neg _ @[simp, squash_cast] lemma coe_coe : ((f : M →ₗ[R] M₂) : (M → M₂)) = (f : M → M₂) := rfl /-- The continuous map that is constantly zero. -/ def zero : M →L[R] M₂ := ⟨0, by exact continuous_const⟩ instance: has_zero (M →L[R] M₂) := ⟨zero⟩ @[simp] lemma zero_apply : (0 : M →L[R] M₂) x = 0 := rfl @[simp, elim_cast] lemma coe_zero : ((0 : M →L[R] M₂) : M →ₗ[R] 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. -/ @[elim_cast] lemma coe_zero' : ((0 : M →L[R] M₂) : M → M₂) = 0 := rfl /-- the identity map as a continuous linear map. -/ def id : M →L[R] M := ⟨linear_map.id, continuous_id⟩ instance : has_one (M →L[R] M) := ⟨id⟩ @[simp] lemma id_apply : (id : M →L[R] M) x = x := rfl @[simp, elim_cast] lemma coe_id : ((id : M →L[R] M) : M →ₗ[R] M) = linear_map.id := rfl @[simp, elim_cast] lemma coe_id' : ((id : M →L[R] M) : M → M) = _root_.id := rfl @[simp] lemma one_apply : (1 : M →L[R] M) x = x := rfl section add variables [topological_add_group M₂] instance : has_add (M →L[R] M₂) := ⟨λ f g, ⟨f + g, f.2.add g.2⟩⟩ @[simp] lemma add_apply : (f + g) x = f x + g x := rfl @[simp, move_cast] lemma coe_add : (((f + g) : M →L[R] M₂) : M →ₗ[R] M₂) = (f : M →ₗ[R] M₂) + g := rfl @[move_cast] lemma coe_add' : (((f + g) : M →L[R] M₂) : M → M₂) = (f : M → M₂) + g := rfl instance : has_neg (M →L[R] M₂) := ⟨λ f, ⟨-f, f.2.neg⟩⟩ @[simp] lemma neg_apply : (-f) x = - (f x) := rfl @[simp, move_cast] lemma coe_neg : (((-f) : M →L[R] M₂) : M →ₗ[R] M₂) = -(f : M →ₗ[R] M₂) := rfl @[move_cast] lemma coe_neg' : (((-f) : M →L[R] M₂) : M → M₂) = -(f : M → M₂) := rfl instance : add_comm_group (M →L[R] M₂) := by refine {zero := 0, add := (+), neg := has_neg.neg, ..}; intros; ext; simp @[simp] lemma sub_apply (x : M) : (f - g) x = f x - g x := rfl @[simp, move_cast] lemma coe_sub : (((f - g) : M →L[R] M₂) : M →ₗ[R] M₂) = (f : M →ₗ[R] M₂) - g := rfl @[simp, move_cast] lemma coe_sub' : (((f - g) : M →L[R] M₂) : M → M₂) = (f : M → M₂) - g := rfl end add /-- Composition of bounded linear maps. -/ def comp (g : M₂ →L[R] M₃) (f : M →L[R] M₂) : M →L[R] M₃ := ⟨linear_map.comp g.to_linear_map f.to_linear_map, g.2.comp f.2⟩ @[simp, move_cast] lemma coe_comp : ((h.comp f) : (M →ₗ[R] M₃)) = (h : M₂ →ₗ[R] M₃).comp f := rfl @[simp, move_cast] lemma coe_comp' : ((h.comp f) : (M → M₃)) = (h : M₂ → M₃) ∘ f := rfl @[simp] theorem comp_id : f.comp id = f := ext $ λ x, rfl @[simp] theorem id_comp : id.comp f = f := ext $ λ x, rfl @[simp] theorem comp_zero : f.comp (0 : M₃ →L[R] M) = 0 := by { ext, simp } @[simp] theorem zero_comp : (0 : M₂ →L[R] M₃).comp f = 0 := by { ext, simp } @[simp] lemma comp_add [topological_add_group M₂] [topological_add_group M₃] (g : M₂ →L[R] M₃) (f₁ f₂ : M →L[R] M₂) : g.comp (f₁ + f₂) = g.comp f₁ + g.comp f₂ := by { ext, simp } @[simp] lemma add_comp [topological_add_group M₃] (g₁ g₂ : M₂ →L[R] M₃) (f : M →L[R] M₂) : (g₁ + g₂).comp f = g₁.comp f + g₂.comp f := by { ext, simp } instance : has_mul (M →L[R] M) := ⟨comp⟩ 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 } /-- The cartesian product of two bounded linear maps, as a bounded linear map. -/ def prod (f₁ : M →L[R] M₂) (f₂ : M →L[R] M₃) : M →L[R] (M₂ × M₃) := { cont := f₁.2.prod_mk f₂.2, ..f₁.to_linear_map.prod f₂.to_linear_map } end general_ring 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₃] [topological_module R M₃] instance : has_scalar R (M →L[R] M₃) := ⟨λ c f, ⟨c • f, continuous_const.smul f.2⟩⟩ variables (c : R) (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 variable [topological_module R M₂] @[simp] lemma smul_apply : (c • f) x = c • (f x) := rfl @[simp, move_cast] lemma coe_apply : (((c • f) : M →L[R] M₂) : M →ₗ[R] M₂) = c • (f : M →ₗ[R] M₂) := rfl @[move_cast] lemma coe_apply' : (((c • f) : M →L[R] M₂) : M → M₂) = c • (f : M → M₂) := rfl @[simp] lemma comp_smul : h.comp (c • f) = c • (h.comp f) := by { ext, simp } /-- 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₂`) -/ def smul_right (c : M →L[R] R) (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] R} {f : M₂} {x : M} : (smul_right c f : M → M₂) x = (c : M → R) x • f := rfl @[simp] lemma smul_right_one_one (c : R →L[R] M₂) : smul_right 1 ((c : R → M₂) 1) = c := by ext; simp [-continuous_linear_map.map_smul, (continuous_linear_map.map_smul _ _ _).symm] @[simp] lemma smul_right_one_eq_iff {f f' : M₂} : smul_right (1 : R →L[R] R) f = smul_right 1 f' ↔ f = f' := ⟨λ h, have (smul_right (1 : R →L[R] R) f : R → M₂) 1 = (smul_right (1 : R →L[R] R) f' : R → M₂) 1, by rw h, by simp at this; assumption, by cc⟩ variable [topological_add_group M₂] instance : module R (M →L[R] M₂) := { smul_zero := λ _, ext $ λ _, smul_zero _, zero_smul := λ _, ext $ λ _, zero_smul _ _, one_smul := λ _, ext $ λ _, one_smul _ _, mul_smul := λ _ _ _, ext $ λ _, mul_smul _ _ _, add_smul := λ _ _ _, ext $ λ _, add_smul _ _ _, smul_add := λ _ _ _, ext $ λ _, smul_add _ _ _ } set_option class.instance_max_depth 55 instance : is_ring_hom (λ c : R, c • (1 : M₂ →L[R] M₂)) := { map_one := one_smul _ _, map_add := λ _ _, ext $ λ _, add_smul _ _ _, map_mul := λ _ _, ext $ λ _, mul_smul _ _ _ } instance : algebra R (M₂ →L[R] M₂) := { to_fun := λ c, c • 1, smul_def' := λ _ _, rfl, commutes' := λ _ _, ext $ λ _, map_smul _ _ _ } end comm_ring end continuous_linear_map namespace continuous_linear_equiv variables {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₃] [module R M] [module R M₂] [module R M₃] /-- A continuous linear equivalence induces a continuous linear map. -/ def to_continuous_linear_map (e : M ≃L[R] M₂) : M →L[R] 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 ≃L[R] M₂) (M →L[R] M₂) := ⟨to_continuous_linear_map⟩ /-- Coerce continuous linear equivs to maps. -/ instance : has_coe_to_fun (M ≃L[R] M₂) := ⟨_, λ f, ((f : M →L[R] M₂) : M → M₂)⟩ @[simp] theorem coe_apply (e : M ≃L[R] M₂) (b : M) : (e : M →L[R] M₂) b = e b := rfl @[squash_cast] lemma coe_coe (e : M ≃L[R] M₂) : ((e : M →L[R] M₂) : M → M₂) = e := rfl @[ext] lemma ext {f g : M ≃L[R] M₂} (h : (f : M → M₂) = g) : f = g := begin cases f; cases g, simp only [], ext x, simp only [coe_fn_coe_base] at h, induction h, refl end /-- A continuous linear equivalence induces a homeomorphism. -/ def to_homeomorph (e : M ≃L[R] M₂) : M ≃ₜ M₂ := { ..e } -- Make some straightforward lemmas available to `simp`. @[simp] lemma map_zero (e : M ≃L[R] M₂) : e (0 : M) = 0 := (e : M →L[R] M₂).map_zero @[simp] lemma map_add (e : M ≃L[R] M₂) (x y : M) : e (x + y) = e x + e y := (e : M →L[R] M₂).map_add x y @[simp] lemma map_sub (e : M ≃L[R] M₂) (x y : M) : e (x - y) = e x - e y := (e : M →L[R] M₂).map_sub x y @[simp] lemma map_smul (e : M ≃L[R] M₂) (c : R) (x : M) : e (c • x) = c • (e x) := (e : M →L[R] M₂).map_smul c x @[simp] lemma map_neg (e : M ≃L[R] M₂) (x : M) : e (-x) = -e x := (e : M →L[R] M₂).map_neg x @[simp] lemma map_eq_zero_iff (e : M ≃L[R] M₂) {x : M} : e x = 0 ↔ x = 0 := e.to_linear_equiv.map_eq_zero_iff section variable (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 M } end /-- The inverse of a continuous linear equivalence as a continuous linear equivalence-/ @[symm] protected def symm (e : M ≃L[R] M₂) : M₂ ≃L[R] M := { continuous_to_fun := e.continuous_inv_fun, continuous_inv_fun := e.continuous_to_fun, .. e.to_linear_equiv.symm } @[simp] lemma symm_to_linear_equiv (e : M ≃L[R] M₂) : e.symm.to_linear_equiv = e.to_linear_equiv.symm := by { ext, refl } /-- The composition of two continuous linear equivalences as a continuous linear equivalence. -/ @[trans] protected def trans (e₁ : M ≃L[R] M₂) (e₂ : M₂ ≃L[R] M₃) : M ≃L[R] 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 } @[simp] lemma trans_to_linear_equiv (e₁ : M ≃L[R] M₂) (e₂ : M₂ ≃L[R] M₃) : (e₁.trans e₂).to_linear_equiv = e₁.to_linear_equiv.trans e₂.to_linear_equiv := by { ext, refl } @[simp] theorem apply_symm_apply (e : M ≃L[R] M₂) (c : M₂) : e (e.symm c) = c := e.1.6 c @[simp] theorem symm_apply_apply (e : M ≃L[R] M₂) (b : M) : e.symm (e b) = b := e.1.5 b @[simp] theorem coe_comp_coe_symm (e : M ≃L[R] M₂) : (e : M →L[R] M₂).comp (e.symm : M₂ →L[R] M) = continuous_linear_map.id := continuous_linear_map.ext e.apply_symm_apply @[simp] theorem coe_symm_comp_coe (e : M ≃L[R] M₂) : (e.symm : M₂ →L[R] M).comp (e : M →L[R] M₂) = continuous_linear_map.id := continuous_linear_map.ext e.symm_apply_apply end continuous_linear_equiv
c9d73a2fb1a4dba62a8e73981717ae88d2265a80
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/nat/with_bot.lean
1b043f024d88fb327da79a071b7ba843036b5c30
[]
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,007
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.nat.basic import Mathlib.algebra.ordered_group import Mathlib.PostPort namespace Mathlib /-! # `with_bot ℕ` Lemmas about the type of natural numbers with a bottom element adjoined. -/ namespace nat theorem with_bot.add_eq_zero_iff {n : with_bot ℕ} {m : with_bot ℕ} : n + m = 0 ↔ n = 0 ∧ m = 0 := sorry theorem with_bot.add_eq_one_iff {n : with_bot ℕ} {m : with_bot ℕ} : n + m = 1 ↔ n = 0 ∧ m = 1 ∨ n = 1 ∧ m = 0 := sorry @[simp] theorem with_bot.coe_nonneg {n : ℕ} : 0 ≤ ↑n := eq.mpr (id (Eq._oldrec (Eq.refl (0 ≤ ↑n)) (Eq.symm with_bot.coe_zero))) (eq.mpr (id (Eq._oldrec (Eq.refl (↑0 ≤ ↑n)) (propext with_bot.coe_le_coe))) (zero_le n)) @[simp] theorem with_bot.lt_zero_iff (n : with_bot ℕ) : n < 0 ↔ n = ⊥ := sorry
c3eb9a0bac9928cbbf91f8569d3c7488bbffd846
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/group_theory/abelianization.lean
bf32cb1c68bc00368d5695216d8e087f812781cc
[ "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,351
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Michael Howes -/ import data.finite.card import group_theory.commutator import group_theory.finiteness /-! # The abelianization of a group This file defines the commutator and the abelianization of a group. It furthermore prepares for the result that the abelianization is left adjoint to the forgetful functor from abelian groups to groups, which can be found in `algebra/category/Group/adjunctions`. ## Main definitions * `commutator`: defines the commutator of a group `G` as a subgroup of `G`. * `abelianization`: defines the abelianization of a group `G` as the quotient of a group by its commutator subgroup. * `abelianization.map`: lifts a group homomorphism to a homomorphism between the abelianizations * `mul_equiv.abelianization_congr`: Equivalent groups have equivalent abelianizations -/ universes u v w -- Let G be a group. variables (G : Type u) [group G] /-- The commutator subgroup of a group G is the normal subgroup generated by the commutators [p,q]=`p*q*p⁻¹*q⁻¹`. -/ @[derive subgroup.normal] def commutator : subgroup G := ⁅(⊤ : subgroup G), ⊤⁆ lemma commutator_def : commutator G = ⁅(⊤ : subgroup G), ⊤⁆ := rfl lemma commutator_eq_closure : commutator G = subgroup.closure (commutator_set G) := by simp [commutator, subgroup.commutator_def, commutator_set] lemma commutator_eq_normal_closure : commutator G = subgroup.normal_closure (commutator_set G) := by simp [commutator, subgroup.commutator_def', commutator_set] instance commutator_characteristic : (commutator G).characteristic := subgroup.commutator_characteristic ⊤ ⊤ instance [finite (commutator_set G)] : group.fg (commutator G) := begin rw commutator_eq_closure, apply group.closure_finite_fg, end lemma rank_commutator_le_card [finite (commutator_set G)] : group.rank (commutator G) ≤ nat.card (commutator_set G) := begin rw subgroup.rank_congr (commutator_eq_closure G), apply subgroup.rank_closure_finite_le_nat_card, end lemma commutator_centralizer_commutator_le_center : ⁅(commutator G).centralizer, (commutator G).centralizer⁆ ≤ subgroup.center G := begin rw [←subgroup.centralizer_top, ←subgroup.commutator_eq_bot_iff_le_centralizer], suffices : ⁅⁅⊤, (commutator G).centralizer⁆, (commutator G).centralizer⁆ = ⊥, { refine subgroup.commutator_commutator_eq_bot_of_rotate _ this, rwa subgroup.commutator_comm (commutator G).centralizer }, rw [subgroup.commutator_comm, subgroup.commutator_eq_bot_iff_le_centralizer], exact set.centralizer_subset (subgroup.commutator_mono le_top le_top), end /-- The abelianization of G is the quotient of G by its commutator subgroup. -/ def abelianization : Type u := G ⧸ (commutator G) namespace abelianization local attribute [instance] quotient_group.left_rel instance : comm_group (abelianization G) := { mul_comm := λ x y, quotient.induction_on₂' x y $ λ a b, quotient.sound' $ quotient_group.left_rel_apply.mpr $ subgroup.subset_closure ⟨b⁻¹, subgroup.mem_top b⁻¹, a⁻¹, subgroup.mem_top a⁻¹, by group⟩, .. quotient_group.quotient.group _ } instance : inhabited (abelianization G) := ⟨1⟩ instance [fintype G] [decidable_pred (∈ commutator G)] : fintype (abelianization G) := quotient_group.fintype (commutator G) instance [finite G] : finite (abelianization G) := quotient.finite _ variable {G} /-- `of` is the canonical projection from G to its abelianization. -/ def of : G →* abelianization G := { to_fun := quotient_group.mk, map_one' := rfl, map_mul' := λ x y, rfl } @[simp] lemma mk_eq_of (a : G) : quot.mk _ a = of a := rfl section lift -- So far we have built Gᵃᵇ and proved it's an abelian group. -- Furthremore we defined the canonical projection `of : G → Gᵃᵇ` -- Let `A` be an abelian group and let `f` be a group homomorphism from `G` to `A`. variables {A : Type v} [comm_group A] (f : G →* A) lemma commutator_subset_ker : commutator G ≤ f.ker := begin rw [commutator_eq_closure, subgroup.closure_le], rintros x ⟨p, q, rfl⟩, simp [monoid_hom.mem_ker, mul_right_comm (f p) (f q), commutator_element_def], end /-- If `f : G → A` is a group homomorphism to an abelian group, then `lift f` is the unique map from the abelianization of a `G` to `A` that factors through `f`. -/ def lift : (G →* A) ≃ (abelianization G →* A) := { to_fun := λ f, quotient_group.lift _ f (λ x h, f.mem_ker.2 $ commutator_subset_ker _ h), inv_fun := λ F, F.comp of, left_inv := λ f, monoid_hom.ext $ λ x, rfl, right_inv := λ F, monoid_hom.ext $ λ x, quotient_group.induction_on x $ λ z, rfl } @[simp] lemma lift.of (x : G) : lift f (of x) = f x := rfl theorem lift.unique (φ : abelianization G →* A) -- hφ : φ agrees with f on the image of G in Gᵃᵇ (hφ : ∀ (x : G), φ (of x) = f x) {x : abelianization G} : φ x = lift f x := quotient_group.induction_on x hφ @[simp] lemma lift_of : lift of = monoid_hom.id (abelianization G) := lift.apply_symm_apply $ monoid_hom.id _ end lift variables {A : Type v} [monoid A] /-- See note [partially-applied ext lemmas]. -/ @[ext] theorem hom_ext (φ ψ : abelianization G →* A) (h : φ.comp of = ψ.comp of) : φ = ψ := monoid_hom.ext $ λ x, quotient_group.induction_on x $ monoid_hom.congr_fun h section map variables {H : Type v} [group H] (f : G →* H) /-- The map operation of the `abelianization` functor -/ def map : abelianization G →* abelianization H := lift (of.comp f) @[simp] lemma map_of (x : G) : map f (of x) = of (f x) := rfl @[simp] lemma map_id : map (monoid_hom.id G) = monoid_hom.id (abelianization G) := hom_ext _ _ rfl @[simp] lemma map_comp {I : Type w} [group I] (g : H →* I) : (map g).comp (map f) = map (g.comp f) := hom_ext _ _ rfl @[simp] lemma map_map_apply {I : Type w} [group I] {g : H →* I} {x : abelianization G}: map g (map f x) = map (g.comp f) x := monoid_hom.congr_fun (map_comp _ _) x end map end abelianization section abelianization_congr variables {G} {H : Type v} [group H] (e : G ≃* H) /-- Equivalent groups have equivalent abelianizations -/ def mul_equiv.abelianization_congr : abelianization G ≃* abelianization H := { to_fun := abelianization.map e.to_monoid_hom, inv_fun := abelianization.map e.symm.to_monoid_hom, left_inv := by { rintros ⟨a⟩, simp }, right_inv := by { rintros ⟨a⟩, simp }, map_mul' := monoid_hom.map_mul _ } @[simp] lemma abelianization_congr_of (x : G) : (e.abelianization_congr) (abelianization.of x) = abelianization.of (e x) := rfl @[simp] lemma abelianization_congr_refl : (mul_equiv.refl G).abelianization_congr = mul_equiv.refl (abelianization G) := mul_equiv.to_monoid_hom_injective abelianization.lift_of @[simp] lemma abelianization_congr_symm : e.abelianization_congr.symm = e.symm.abelianization_congr := rfl @[simp] lemma abelianization_congr_trans {I : Type v} [group I] (e₂ : H ≃* I) : e.abelianization_congr.trans e₂.abelianization_congr = (e.trans e₂).abelianization_congr := mul_equiv.to_monoid_hom_injective (abelianization.hom_ext _ _ rfl) end abelianization_congr /-- An Abelian group is equivalent to its own abelianization. -/ @[simps] def abelianization.equiv_of_comm {H : Type*} [comm_group H] : H ≃* abelianization H := { to_fun := abelianization.of, inv_fun := abelianization.lift (monoid_hom.id H), left_inv := λ a, rfl, right_inv := by { rintros ⟨a⟩, refl, }, .. abelianization.of } section commutator_representatives open subgroup /-- Representatives `(g₁, g₂) : G × G` of commutator_set `⁅g₁, g₂⁆ ∈ G`. -/ def commutator_representatives : set (G × G) := set.range (λ g : commutator_set G, (g.2.some, g.2.some_spec.some)) instance [finite (commutator_set G)] : finite (commutator_representatives G) := set.finite_coe_iff.mpr (set.finite_range _) /-- Subgroup generated by representatives `g₁ g₂ : G` of commutators `⁅g₁, g₂⁆ ∈ G`. -/ def closure_commutator_representatives : subgroup G := closure (prod.fst '' commutator_representatives G ∪ prod.snd '' commutator_representatives G) instance closure_commutator_representatives_fg [finite (commutator_set G)] : group.fg (closure_commutator_representatives G) := group.closure_finite_fg _ lemma rank_closure_commutator_representations_le [finite (commutator_set G)] : group.rank (closure_commutator_representatives G) ≤ 2 * nat.card (commutator_set G) := begin rw two_mul, exact (subgroup.rank_closure_finite_le_nat_card _).trans ((set.card_union_le _ _).trans (add_le_add ((finite.card_image_le _).trans (finite.card_range_le _)) ((finite.card_image_le _).trans (finite.card_range_le _ )))), end lemma image_commutator_set_closure_commutator_representatives : (closure_commutator_representatives G).subtype '' (commutator_set (closure_commutator_representatives G)) = commutator_set G := begin apply set.subset.antisymm, { rintros - ⟨-, ⟨g₁, g₂, rfl⟩, rfl⟩, exact ⟨g₁, g₂, rfl⟩ }, { exact λ g hg, ⟨_, ⟨⟨_, subset_closure (or.inl ⟨_, ⟨⟨g, hg⟩, rfl⟩, rfl⟩)⟩, ⟨_, subset_closure (or.inr ⟨_, ⟨⟨g, hg⟩, rfl⟩, rfl⟩)⟩, rfl⟩, hg.some_spec.some_spec⟩ }, end lemma card_commutator_set_closure_commutator_representatives : nat.card (commutator_set (closure_commutator_representatives G)) = nat.card (commutator_set G) := begin rw ← image_commutator_set_closure_commutator_representatives G, exact nat.card_congr (equiv.set.image _ _ (subtype_injective _)), end lemma card_commutator_closure_commutator_representatives : nat.card (commutator (closure_commutator_representatives G)) = nat.card (commutator G) := begin rw [commutator_eq_closure G, ←image_commutator_set_closure_commutator_representatives, ←monoid_hom.map_closure, ←commutator_eq_closure], exact nat.card_congr (equiv.set.image _ _ (subtype_injective _)), end instance [finite (commutator_set G)] : finite (commutator_set (closure_commutator_representatives G)) := begin apply nat.finite_of_card_ne_zero, rw card_commutator_set_closure_commutator_representatives, exact finite.card_pos.ne', end end commutator_representatives
ae54fbf44b61faf31335da884f2f9f9b0f9676ca
dd36d7be956e3782ca434f598130c3243b02e195
/Bench.lean
7a7208fb60a54190fc9cd490426676ef4fb4950f
[]
no_license
joehendrix/lean-benchmark-experiments
81c48322aa2b269af9078308b069e8e10788899e
604815837cace1fc9ef8c36408c0abb377518aaa
refs/heads/master
1,681,529,683,023
1,618,939,900,000
1,618,939,900,000
350,514,794
1
0
null
null
null
null
UTF-8
Lean
false
false
5,565
lean
import Lean.Elab.Frontend open Lean -- Time with seconds and nanoseconds. structure Timespec where sec: UInt64 nsec: UInt64 @[extern 1 "lean_clock_monotonic_raw_gettime"] constant clockMonotonicRawGettime : IO Timespec /-- - @binAddBench n@ builds a balanced binary tree of height @n@ using additions of 1, - and reduces them. It can be used to validate that reduction memoizes shared subterms. -/ def binAddBench (n:Nat) : MetaM Unit := do let z := mkConst `Nat.zero let s := mkConst `Nat.succ let p := mkConst `Nat.add let mut r := mkApp s z for i in [0:n] do r := mkApp (mkApp p r) r let r ← Lean.Meta.reduce r pure () open IO section open Lean.Elab -- Create environment from file def environmentFromFile (fname:String) (moduleName:String) (opts : Options := {}) : IO (MessageLog × Environment) := do let input ← IO.FS.readFile fname let inputCtx := Parser.mkInputContext input fname let (header, parserState, messages) ← Parser.parseHeader inputCtx let (env, messages) ← processHeader header opts messages inputCtx let env := env.setMainModule moduleName let s ← IO.processCommands inputCtx parserState (Command.mkState env messages opts) pure (s.commandState.messages, s.commandState.env) end def msecDiff (e s : Timespec) : String := do let en : Nat := e.sec.toNat * 10^9 + e.nsec.toNat let sn : Nat := s.sec.toNat * 10^9 + s.nsec.toNat let musec := (en - sn) / 1000 let musecFrac := s!"{musec%1000}" let musecPadding := "".pushn '0' (3 - musecFrac.length) pure s!"{musec/1000}.{musecPadding}{musecFrac}" -- This outputs how long it takes to run the given meta option in the -- context created from the filename. def benchmarkC (fname:String) (testName:String) (action:MetaM Unit) : IO Unit := do let (msgs, env) ← environmentFromFile fname "Test" if (← msgs.hasErrors) then IO.println s!"Errors loading {fname}..." for msg in msgs.toList do IO.print s!" {← msg.toString (includeEndPos := Lean.Elab.getPrintMessageEndPos {})}" else IO.print s!"{testName} " let s ← clockMonotonicRawGettime let a ← (action.run.run {} {env := env}).toIO' let e ← clockMonotonicRawGettime IO.println s!"{msecDiff e s}ms" match a with | Except.error msg => do IO.println s!" Error: {←msg.toMessageData.toString}" | Except.ok _ => pure () @[extern "leanclock_io_timeit"] constant cppTime (fn : IO α) : IO (α × UInt64) -- This outputs how long it takes to run the given meta option in the -- context created from the filename. def benchmarkCPP (fname:String) (testName:String) (action:MetaM Unit) : IO Unit := do let (msgs, env) ← environmentFromFile fname "Test" if (← msgs.hasErrors) then IO.println s!"Errors loading {fname}..." for msg in msgs.toList do IO.print s!" {← msg.toString (includeEndPos := Lean.Elab.getPrintMessageEndPos {})}" else IO.print s!"{testName} " let (a,t) ← cppTime (action.run.run {} {env := env}).toIO' let musecFrac := s!"{t%1000}" let musecPadding := "".pushn '0' (3 - musecFrac.length) IO.println s!"{t/1000}.{musecPadding}{musecFrac}" match a with | Except.error msg => do IO.println s!" Error: {←msg.toMessageData.toString}" | Except.ok _ => pure () @[extern "leanclock_io_rusttime"] constant rustTime (fn : IO α) : IO (α × UInt64) -- This outputs how long it takes to run the given meta option in the -- context created from the filename. def benchmarkRust (fname:String) (testName:String) (action:MetaM Unit) : IO Unit := do let (msgs, env) ← environmentFromFile fname "Test" if (← msgs.hasErrors) then IO.println s!"Errors loading {fname}..." for msg in msgs.toList do IO.print s!" {← msg.toString (includeEndPos := Lean.Elab.getPrintMessageEndPos {})}" else IO.print s!"{testName} " let (a,t) ← rustTime (action.run.run {} {env := env}).toIO' let musecFrac := s!"{t%1000}" let musecPadding := "".pushn '0' (3 - musecFrac.length) IO.println s!"{t/1000}.{musecPadding}{musecFrac}" match a with | Except.error msg => do IO.println s!" Error: {←msg.toMessageData.toString}" | Except.ok _ => pure () -- This outputs how long it takes to run the given meta option in the -- context created from the filename. def benchmarkOrig (fname:String) (testName:String) (action:MetaM Unit) : IO Unit := do let (msgs, env) ← environmentFromFile fname "Test" if (← msgs.hasErrors) then IO.println s!"Errors loading {fname}..." for msg in msgs.toList do IO.print s!" {← msg.toString (includeEndPos := Lean.Elab.getPrintMessageEndPos {})}" else IO.print s!"{testName} " match ← timeit s!"{testName}" (action.run.run {} {env := env}).toIO' with | Except.error msg => do IO.println s!" Error: {←msg.toMessageData.toString}" | Except.ok _ => pure () def benchmark := benchmarkRust def main (args:List String) : IO Unit := do match args with | [path] => do Lean.initSearchPath (some path) benchmark "environments/initial.lean" "Binary add 30" (binAddBench 1) benchmark "environments/initial.lean" "Binary add 60" (binAddBench 60) benchmark "environments/initial.lean" "Binary add 200" (binAddBench 200) benchmark "environments/initial.lean" "Binary add 2000" (binAddBench 2000) | _ => do IO.println "Please provide path to standard library, For example:" IO.println " ./build/bin/Bench $HOME/.elan/toolchains/leanprover-lean4-nightly-2021-03-14/lib/lean"
8c5e06b2e7539988d6fe2dd5c9eb3816ed2bc226
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/analysis/calculus/local_extr.lean
3e9e12996ac8e2527c0d7cc0918520245212e80c
[]
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
13,844
lean
/- Copyright (c) 2019 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.topology.local_extr import Mathlib.analysis.calculus.deriv import Mathlib.PostPort universes u namespace Mathlib /-! # Local extrema of smooth functions ## Main definitions In a real normed space `E` we define `pos_tangent_cone_at (s : set E) (x : E)`. This would be the same as `tangent_cone_at ℝ≥0 s x` if we had a theory of normed semifields. This set is used in the proof of Fermat's Theorem (see below), and can be used to formalize [Lagrange multipliers](https://en.wikipedia.org/wiki/Lagrange_multiplier) and/or [Karush–Kuhn–Tucker conditions](https://en.wikipedia.org/wiki/Karush–Kuhn–Tucker_conditions). ## Main statements For each theorem name listed below, we also prove similar theorems for `min`, `extr` (if applicable)`, and `(f)deriv` instead of `has_fderiv`. * `is_local_max_on.has_fderiv_within_at_nonpos` : `f' y ≤ 0` whenever `a` is a local maximum of `f` on `s`, `f` has derivative `f'` at `a` within `s`, and `y` belongs to the positive tangent cone of `s` at `a`. * `is_local_max_on.has_fderiv_within_at_eq_zero` : In the settings of the previous theorem, if both `y` and `-y` belong to the positive tangent cone, then `f' y = 0`. * `is_local_max.has_fderiv_at_eq_zero` : [Fermat's Theorem](https://en.wikipedia.org/wiki/Fermat's_theorem_(stationary_points)), the derivative of a differentiable function at a local extremum point equals zero. * `exists_has_deriv_at_eq_zero` : [Rolle's Theorem](https://en.wikipedia.org/wiki/Rolle's_theorem): given a function `f` continuous on `[a, b]` and differentiable on `(a, b)`, there exists `c ∈ (a, b)` such that `f' c = 0`. ## Implementation notes For each mathematical fact we prove several versions of its formalization: * for maxima and minima; * using `has_fderiv*`/`has_deriv*` or `fderiv*`/`deriv*`. For the `fderiv*`/`deriv*` versions we omit the differentiability condition whenever it is possible due to the fact that `fderiv` and `deriv` are defined to be zero for non-differentiable functions. ## References * [Fermat's Theorem](https://en.wikipedia.org/wiki/Fermat's_theorem_(stationary_points)); * [Rolle's Theorem](https://en.wikipedia.org/wiki/Rolle's_theorem); * [Tangent cone](https://en.wikipedia.org/wiki/Tangent_cone); ## Tags local extremum, Fermat's Theorem, Rolle's Theorem -/ /-- "Positive" tangent cone to `s` at `x`; the only difference from `tangent_cone_at` is that we require `c n → ∞` instead of `∥c n∥ → ∞`. One can think about `pos_tangent_cone_at` as `tangent_cone_at nnreal` but we have no theory of normed semifields yet. -/ def pos_tangent_cone_at {E : Type u} [normed_group E] [normed_space ℝ E] (s : set E) (x : E) : set E := set_of fun (y : E) => ∃ (c : ℕ → ℝ), ∃ (d : ℕ → E), filter.eventually (fun (n : ℕ) => x + d n ∈ s) filter.at_top ∧ filter.tendsto c filter.at_top filter.at_top ∧ filter.tendsto (fun (n : ℕ) => c n • d n) filter.at_top (nhds y) theorem pos_tangent_cone_at_mono {E : Type u} [normed_group E] [normed_space ℝ E] {a : E} : monotone fun (s : set E) => pos_tangent_cone_at s a := sorry theorem mem_pos_tangent_cone_at_of_segment_subset {E : Type u} [normed_group E] [normed_space ℝ E] {s : set E} {x : E} {y : E} (h : segment x y ⊆ s) : y - x ∈ pos_tangent_cone_at s x := sorry theorem pos_tangent_cone_at_univ {E : Type u} [normed_group E] [normed_space ℝ E] {a : E} : pos_tangent_cone_at set.univ a = set.univ := sorry /-- If `f` has a local max on `s` at `a`, `f'` is the derivative of `f` at `a` within `s`, and `y` belongs to the positive tangent cone of `s` at `a`, then `f' y ≤ 0`. -/ theorem is_local_max_on.has_fderiv_within_at_nonpos {E : Type u} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {a : E} {f' : continuous_linear_map ℝ E ℝ} {s : set E} (h : is_local_max_on f s a) (hf : has_fderiv_within_at f f' s a) {y : E} (hy : y ∈ pos_tangent_cone_at s a) : coe_fn f' y ≤ 0 := sorry /-- If `f` has a local max on `s` at `a` and `y` belongs to the positive tangent cone of `s` at `a`, then `f' y ≤ 0`. -/ theorem is_local_max_on.fderiv_within_nonpos {E : Type u} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {a : E} {s : set E} (h : is_local_max_on f s a) {y : E} (hy : y ∈ pos_tangent_cone_at s a) : coe_fn (fderiv_within ℝ f s a) y ≤ 0 := sorry /-- If `f` has a local max on `s` at `a`, `f'` is a derivative of `f` at `a` within `s`, and both `y` and `-y` belong to the positive tangent cone of `s` at `a`, then `f' y ≤ 0`. -/ theorem is_local_max_on.has_fderiv_within_at_eq_zero {E : Type u} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {a : E} {f' : continuous_linear_map ℝ E ℝ} {s : set E} (h : is_local_max_on f s a) (hf : has_fderiv_within_at f f' s a) {y : E} (hy : y ∈ pos_tangent_cone_at s a) (hy' : -y ∈ pos_tangent_cone_at s a) : coe_fn f' y = 0 := sorry /-- If `f` has a local max on `s` at `a` and both `y` and `-y` belong to the positive tangent cone of `s` at `a`, then `f' y = 0`. -/ theorem is_local_max_on.fderiv_within_eq_zero {E : Type u} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {a : E} {s : set E} (h : is_local_max_on f s a) {y : E} (hy : y ∈ pos_tangent_cone_at s a) (hy' : -y ∈ pos_tangent_cone_at s a) : coe_fn (fderiv_within ℝ f s a) y = 0 := sorry /-- If `f` has a local min on `s` at `a`, `f'` is the derivative of `f` at `a` within `s`, and `y` belongs to the positive tangent cone of `s` at `a`, then `0 ≤ f' y`. -/ theorem is_local_min_on.has_fderiv_within_at_nonneg {E : Type u} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {a : E} {f' : continuous_linear_map ℝ E ℝ} {s : set E} (h : is_local_min_on f s a) (hf : has_fderiv_within_at f f' s a) {y : E} (hy : y ∈ pos_tangent_cone_at s a) : 0 ≤ coe_fn f' y := sorry /-- If `f` has a local min on `s` at `a` and `y` belongs to the positive tangent cone of `s` at `a`, then `0 ≤ f' y`. -/ theorem is_local_min_on.fderiv_within_nonneg {E : Type u} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {a : E} {s : set E} (h : is_local_min_on f s a) {y : E} (hy : y ∈ pos_tangent_cone_at s a) : 0 ≤ coe_fn (fderiv_within ℝ f s a) y := sorry /-- If `f` has a local max on `s` at `a`, `f'` is a derivative of `f` at `a` within `s`, and both `y` and `-y` belong to the positive tangent cone of `s` at `a`, then `f' y ≤ 0`. -/ theorem is_local_min_on.has_fderiv_within_at_eq_zero {E : Type u} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {a : E} {f' : continuous_linear_map ℝ E ℝ} {s : set E} (h : is_local_min_on f s a) (hf : has_fderiv_within_at f f' s a) {y : E} (hy : y ∈ pos_tangent_cone_at s a) (hy' : -y ∈ pos_tangent_cone_at s a) : coe_fn f' y = 0 := sorry /-- If `f` has a local min on `s` at `a` and both `y` and `-y` belong to the positive tangent cone of `s` at `a`, then `f' y = 0`. -/ theorem is_local_min_on.fderiv_within_eq_zero {E : Type u} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {a : E} {s : set E} (h : is_local_min_on f s a) {y : E} (hy : y ∈ pos_tangent_cone_at s a) (hy' : -y ∈ pos_tangent_cone_at s a) : coe_fn (fderiv_within ℝ f s a) y = 0 := sorry /-- Fermat's Theorem: the derivative of a function at a local minimum equals zero. -/ theorem is_local_min.has_fderiv_at_eq_zero {E : Type u} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {a : E} {f' : continuous_linear_map ℝ E ℝ} (h : is_local_min f a) (hf : has_fderiv_at f f' a) : f' = 0 := sorry /-- Fermat's Theorem: the derivative of a function at a local minimum equals zero. -/ theorem is_local_min.fderiv_eq_zero {E : Type u} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {a : E} (h : is_local_min f a) : fderiv ℝ f a = 0 := dite (differentiable_at ℝ f a) (fun (hf : differentiable_at ℝ f a) => is_local_min.has_fderiv_at_eq_zero h (differentiable_at.has_fderiv_at hf)) fun (hf : ¬differentiable_at ℝ f a) => fderiv_zero_of_not_differentiable_at hf /-- Fermat's Theorem: the derivative of a function at a local maximum equals zero. -/ theorem is_local_max.has_fderiv_at_eq_zero {E : Type u} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {a : E} {f' : continuous_linear_map ℝ E ℝ} (h : is_local_max f a) (hf : has_fderiv_at f f' a) : f' = 0 := iff.mp neg_eq_zero (is_local_min.has_fderiv_at_eq_zero (is_local_max.neg h) (has_fderiv_at.neg hf)) /-- Fermat's Theorem: the derivative of a function at a local maximum equals zero. -/ theorem is_local_max.fderiv_eq_zero {E : Type u} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {a : E} (h : is_local_max f a) : fderiv ℝ f a = 0 := dite (differentiable_at ℝ f a) (fun (hf : differentiable_at ℝ f a) => is_local_max.has_fderiv_at_eq_zero h (differentiable_at.has_fderiv_at hf)) fun (hf : ¬differentiable_at ℝ f a) => fderiv_zero_of_not_differentiable_at hf /-- Fermat's Theorem: the derivative of a function at a local extremum equals zero. -/ theorem is_local_extr.has_fderiv_at_eq_zero {E : Type u} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {a : E} {f' : continuous_linear_map ℝ E ℝ} (h : is_local_extr f a) : has_fderiv_at f f' a → f' = 0 := is_local_extr.elim h is_local_min.has_fderiv_at_eq_zero is_local_max.has_fderiv_at_eq_zero /-- Fermat's Theorem: the derivative of a function at a local extremum equals zero. -/ theorem is_local_extr.fderiv_eq_zero {E : Type u} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {a : E} (h : is_local_extr f a) : fderiv ℝ f a = 0 := is_local_extr.elim h is_local_min.fderiv_eq_zero is_local_max.fderiv_eq_zero /-- Fermat's Theorem: the derivative of a function at a local minimum equals zero. -/ theorem is_local_min.has_deriv_at_eq_zero {f : ℝ → ℝ} {f' : ℝ} {a : ℝ} (h : is_local_min f a) (hf : has_deriv_at f f' a) : f' = 0 := sorry /-- Fermat's Theorem: the derivative of a function at a local minimum equals zero. -/ theorem is_local_min.deriv_eq_zero {f : ℝ → ℝ} {a : ℝ} (h : is_local_min f a) : deriv f a = 0 := dite (differentiable_at ℝ f a) (fun (hf : differentiable_at ℝ f a) => is_local_min.has_deriv_at_eq_zero h (differentiable_at.has_deriv_at hf)) fun (hf : ¬differentiable_at ℝ f a) => deriv_zero_of_not_differentiable_at hf /-- Fermat's Theorem: the derivative of a function at a local maximum equals zero. -/ theorem is_local_max.has_deriv_at_eq_zero {f : ℝ → ℝ} {f' : ℝ} {a : ℝ} (h : is_local_max f a) (hf : has_deriv_at f f' a) : f' = 0 := iff.mp neg_eq_zero (is_local_min.has_deriv_at_eq_zero (is_local_max.neg h) (has_deriv_at.neg hf)) /-- Fermat's Theorem: the derivative of a function at a local maximum equals zero. -/ theorem is_local_max.deriv_eq_zero {f : ℝ → ℝ} {a : ℝ} (h : is_local_max f a) : deriv f a = 0 := dite (differentiable_at ℝ f a) (fun (hf : differentiable_at ℝ f a) => is_local_max.has_deriv_at_eq_zero h (differentiable_at.has_deriv_at hf)) fun (hf : ¬differentiable_at ℝ f a) => deriv_zero_of_not_differentiable_at hf /-- Fermat's Theorem: the derivative of a function at a local extremum equals zero. -/ theorem is_local_extr.has_deriv_at_eq_zero {f : ℝ → ℝ} {f' : ℝ} {a : ℝ} (h : is_local_extr f a) : has_deriv_at f f' a → f' = 0 := is_local_extr.elim h is_local_min.has_deriv_at_eq_zero is_local_max.has_deriv_at_eq_zero /-- Fermat's Theorem: the derivative of a function at a local extremum equals zero. -/ theorem is_local_extr.deriv_eq_zero {f : ℝ → ℝ} {a : ℝ} (h : is_local_extr f a) : deriv f a = 0 := is_local_extr.elim h is_local_min.deriv_eq_zero is_local_max.deriv_eq_zero /-- A continuous function on a closed interval with `f a = f b` takes either its maximum or its minimum value at a point in the interior of the interval. -/ theorem exists_Ioo_extr_on_Icc (f : ℝ → ℝ) {a : ℝ} {b : ℝ} (hab : a < b) (hfc : continuous_on f (set.Icc a b)) (hfI : f a = f b) : ∃ (c : ℝ), ∃ (H : c ∈ set.Ioo a b), is_extr_on f (set.Icc a b) c := sorry /-- A continuous function on a closed interval with `f a = f b` has a local extremum at some point of the corresponding open interval. -/ theorem exists_local_extr_Ioo (f : ℝ → ℝ) {a : ℝ} {b : ℝ} (hab : a < b) (hfc : continuous_on f (set.Icc a b)) (hfI : f a = f b) : ∃ (c : ℝ), ∃ (H : c ∈ set.Ioo a b), is_local_extr f c := sorry /-- Rolle's Theorem `has_deriv_at` version -/ theorem exists_has_deriv_at_eq_zero (f : ℝ → ℝ) (f' : ℝ → ℝ) {a : ℝ} {b : ℝ} (hab : a < b) (hfc : continuous_on f (set.Icc a b)) (hfI : f a = f b) (hff' : ∀ (x : ℝ), x ∈ set.Ioo a b → has_deriv_at f (f' x) x) : ∃ (c : ℝ), ∃ (H : c ∈ set.Ioo a b), f' c = 0 := sorry /-- Rolle's Theorem `deriv` version -/ theorem exists_deriv_eq_zero (f : ℝ → ℝ) {a : ℝ} {b : ℝ} (hab : a < b) (hfc : continuous_on f (set.Icc a b)) (hfI : f a = f b) : ∃ (c : ℝ), ∃ (H : c ∈ set.Ioo a b), deriv f c = 0 := sorry theorem exists_has_deriv_at_eq_zero' {f : ℝ → ℝ} {f' : ℝ → ℝ} {a : ℝ} {b : ℝ} (hab : a < b) {l : ℝ} (hfa : filter.tendsto f (nhds_within a (set.Ioi a)) (nhds l)) (hfb : filter.tendsto f (nhds_within b (set.Iio b)) (nhds l)) (hff' : ∀ (x : ℝ), x ∈ set.Ioo a b → has_deriv_at f (f' x) x) : ∃ (c : ℝ), ∃ (H : c ∈ set.Ioo a b), f' c = 0 := sorry theorem exists_deriv_eq_zero' {f : ℝ → ℝ} {a : ℝ} {b : ℝ} (hab : a < b) {l : ℝ} (hfa : filter.tendsto f (nhds_within a (set.Ioi a)) (nhds l)) (hfb : filter.tendsto f (nhds_within b (set.Iio b)) (nhds l)) : ∃ (c : ℝ), ∃ (H : c ∈ set.Ioo a b), deriv f c = 0 := sorry
dfbe902dde4b184e283e5425f90b9f2809686528
367134ba5a65885e863bdc4507601606690974c1
/src/algebra/lie/skew_adjoint.lean
9b31a8b5af9a4517b541d5d80e3eda10a57dc3d7
[ "Apache-2.0" ]
permissive
kodyvajjha/mathlib
9bead00e90f68269a313f45f5561766cfd8d5cad
b98af5dd79e13a38d84438b850a2e8858ec21284
refs/heads/master
1,624,350,366,310
1,615,563,062,000
1,615,563,062,000
162,666,963
0
0
Apache-2.0
1,545,367,651,000
1,545,367,651,000
null
UTF-8
Lean
false
false
7,203
lean
/- Copyright (c) 2020 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import algebra.lie.matrix import linear_algebra.bilinear_form /-! # Lie algebras of skew-adjoint endomorphisms of a bilinear form When a module carries a bilinear form, the Lie algebra of endomorphisms of the module contains a distinguished Lie subalgebra: the skew-adjoint endomorphisms. Such subalgebras are important because they provide a simple, explicit construction of the so-called classical Lie algebras. This file defines the Lie subalgebra of skew-adjoint endomorphims cut out by a bilinear form on a module and proves some basic related results. It also provides the corresponding definitions and results for the Lie algebra of square matrices. ## Main definitions * `skew_adjoint_lie_subalgebra` * `skew_adjoint_lie_subalgebra_equiv` * `skew_adjoint_matrices_lie_subalgebra` * `skew_adjoint_matrices_lie_subalgebra_equiv` ## Tags lie algebra, skew-adjoint, bilinear form -/ universes u v w w₁ section skew_adjoint_endomorphisms open bilin_form variables {R : Type u} {M : Type v} [comm_ring R] [add_comm_group M] [module R M] variables (B : bilin_form R M) lemma bilin_form.is_skew_adjoint_bracket (f g : module.End R M) (hf : f ∈ B.skew_adjoint_submodule) (hg : g ∈ B.skew_adjoint_submodule) : ⁅f, g⁆ ∈ B.skew_adjoint_submodule := begin rw mem_skew_adjoint_submodule at *, have hfg : is_adjoint_pair B B (f * g) (g * f), { rw ←neg_mul_neg g f, exact hf.mul hg, }, have hgf : is_adjoint_pair B B (g * f) (f * g), { rw ←neg_mul_neg f g, exact hg.mul hf, }, change bilin_form.is_adjoint_pair B B (f * g - g * f) (-(f * g - g * f)), rw neg_sub, exact hfg.sub hgf, end /-- Given an `R`-module `M`, equipped with a bilinear form, the skew-adjoint endomorphisms form a Lie subalgebra of the Lie algebra of endomorphisms. -/ def skew_adjoint_lie_subalgebra : lie_subalgebra R (module.End R M) := { lie_mem' := B.is_skew_adjoint_bracket, ..B.skew_adjoint_submodule } variables {N : Type w} [add_comm_group N] [module R N] (e : N ≃ₗ[R] M) /-- An equivalence of modules with bilinear forms gives equivalence of Lie algebras of skew-adjoint endomorphisms. -/ def skew_adjoint_lie_subalgebra_equiv : skew_adjoint_lie_subalgebra (B.comp (↑e : N →ₗ[R] M) ↑e) ≃ₗ⁅R⁆ skew_adjoint_lie_subalgebra B := begin apply lie_equiv.of_subalgebras _ _ e.lie_conj, ext f, simp only [lie_subalgebra.mem_coe, submodule.mem_map_equiv, lie_subalgebra.mem_map_submodule, coe_coe], exact (bilin_form.is_pair_self_adjoint_equiv (-B) B e f).symm, end @[simp] lemma skew_adjoint_lie_subalgebra_equiv_apply (f : skew_adjoint_lie_subalgebra (B.comp ↑e ↑e)) : ↑(skew_adjoint_lie_subalgebra_equiv B e f) = e.lie_conj f := by simp [skew_adjoint_lie_subalgebra_equiv] @[simp] lemma skew_adjoint_lie_subalgebra_equiv_symm_apply (f : skew_adjoint_lie_subalgebra B) : ↑((skew_adjoint_lie_subalgebra_equiv B e).symm f) = e.symm.lie_conj f := by simp [skew_adjoint_lie_subalgebra_equiv] end skew_adjoint_endomorphisms section skew_adjoint_matrices open_locale matrix variables {R : Type u} {n : Type w} [comm_ring R] [decidable_eq n] [fintype n] variables (J : matrix n n R) lemma matrix.lie_transpose (A B : matrix n n R) : ⁅A, B⁆ᵀ = ⁅Bᵀ, Aᵀ⁆ := show (A * B - B * A)ᵀ = (Bᵀ * Aᵀ - Aᵀ * Bᵀ), by simp lemma matrix.is_skew_adjoint_bracket (A B : matrix n n R) (hA : A ∈ skew_adjoint_matrices_submodule J) (hB : B ∈ skew_adjoint_matrices_submodule J) : ⁅A, B⁆ ∈ skew_adjoint_matrices_submodule J := begin simp only [mem_skew_adjoint_matrices_submodule] at *, change ⁅A, B⁆ᵀ ⬝ J = J ⬝ -⁅A, B⁆, change Aᵀ ⬝ J = J ⬝ -A at hA, change Bᵀ ⬝ J = J ⬝ -B at hB, simp only [←matrix.mul_eq_mul] at *, rw [matrix.lie_transpose, lie_ring.of_associative_ring_bracket, lie_ring.of_associative_ring_bracket, sub_mul, mul_assoc, mul_assoc, hA, hB, ←mul_assoc, ←mul_assoc, hA, hB], noncomm_ring, end /-- The Lie subalgebra of skew-adjoint square matrices corresponding to a square matrix `J`. -/ def skew_adjoint_matrices_lie_subalgebra : lie_subalgebra R (matrix n n R) := { lie_mem' := J.is_skew_adjoint_bracket, ..(skew_adjoint_matrices_submodule J) } @[simp] lemma mem_skew_adjoint_matrices_lie_subalgebra (A : matrix n n R) : A ∈ skew_adjoint_matrices_lie_subalgebra J ↔ A ∈ skew_adjoint_matrices_submodule J := iff.rfl /-- An invertible matrix `P` gives a Lie algebra equivalence between those endomorphisms that are skew-adjoint with respect to a square matrix `J` and those with respect to `PᵀJP`. -/ noncomputable def skew_adjoint_matrices_lie_subalgebra_equiv (P : matrix n n R) (h : is_unit P) : skew_adjoint_matrices_lie_subalgebra J ≃ₗ⁅R⁆ skew_adjoint_matrices_lie_subalgebra (Pᵀ ⬝ J ⬝ P) := lie_equiv.of_subalgebras _ _ (P.lie_conj h).symm begin ext A, suffices : P.lie_conj h A ∈ skew_adjoint_matrices_submodule J ↔ A ∈ skew_adjoint_matrices_submodule (Pᵀ ⬝ J ⬝ P), { simp only [lie_subalgebra.mem_coe, submodule.mem_map_equiv, lie_subalgebra.mem_map_submodule, coe_coe], exact this, }, simp [matrix.is_skew_adjoint, J.is_adjoint_pair_equiv _ _ P h], end lemma skew_adjoint_matrices_lie_subalgebra_equiv_apply (P : matrix n n R) (h : is_unit P) (A : skew_adjoint_matrices_lie_subalgebra J) : ↑(skew_adjoint_matrices_lie_subalgebra_equiv J P h A) = P⁻¹ ⬝ ↑A ⬝ P := by simp [skew_adjoint_matrices_lie_subalgebra_equiv] /-- An equivalence of matrix algebras commuting with the transpose endomorphisms restricts to an equivalence of Lie algebras of skew-adjoint matrices. -/ def skew_adjoint_matrices_lie_subalgebra_equiv_transpose {m : Type w} [decidable_eq m] [fintype m] (e : matrix n n R ≃ₐ[R] matrix m m R) (h : ∀ A, (e A)ᵀ = e (Aᵀ)) : skew_adjoint_matrices_lie_subalgebra J ≃ₗ⁅R⁆ skew_adjoint_matrices_lie_subalgebra (e J) := lie_equiv.of_subalgebras _ _ e.to_lie_equiv begin ext A, suffices : J.is_skew_adjoint (e.symm A) ↔ (e J).is_skew_adjoint A, by simpa [this], simp [matrix.is_skew_adjoint, matrix.is_adjoint_pair, ← matrix.mul_eq_mul, ← h, ← function.injective.eq_iff e.injective], end @[simp] lemma skew_adjoint_matrices_lie_subalgebra_equiv_transpose_apply {m : Type w} [decidable_eq m] [fintype m] (e : matrix n n R ≃ₐ[R] matrix m m R) (h : ∀ A, (e A)ᵀ = e (Aᵀ)) (A : skew_adjoint_matrices_lie_subalgebra J) : (skew_adjoint_matrices_lie_subalgebra_equiv_transpose J e h A : matrix m m R) = e A := rfl lemma mem_skew_adjoint_matrices_lie_subalgebra_unit_smul (u : units R) (J A : matrix n n R) : A ∈ skew_adjoint_matrices_lie_subalgebra ((u : R) • J) ↔ A ∈ skew_adjoint_matrices_lie_subalgebra J := begin change A ∈ skew_adjoint_matrices_submodule ((u : R) • J) ↔ A ∈ skew_adjoint_matrices_submodule J, simp only [mem_skew_adjoint_matrices_submodule, matrix.is_skew_adjoint, matrix.is_adjoint_pair], split; intros h, { simpa using congr_arg (λ B, (↑u⁻¹ : R) • B) h, }, { simp [h], }, end end skew_adjoint_matrices
cf7a20ddb5cd7651665f7ee0cb7f7053e9889daa
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/bin_oct_hex.lean
413f15261dc08190a45d30bc0f10000926bbd56c
[ "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
108
lean
example : 0xf = 15 := rfl example : 3 = 0b11 := rfl example : 5 = 0b101 := rfl example : 8 = 0o10 := rfl
e9ca33bfd49a4530b1e551959bc5c66ea5fce569
ae1e94c332e17c7dc7051ce976d5a9eebe7ab8a5
/stage0/src/Lean/Data/Trie.lean
c95446cc78348449463d2a6a8d4be10abeff50ac
[ "Apache-2.0" ]
permissive
dupuisf/lean4
d082d13b01243e1de29ae680eefb476961221eef
6a39c65bd28eb0e28c3870188f348c8914502718
refs/heads/master
1,676,948,755,391
1,610,665,114,000
1,610,665,114,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,755
lean
/- Copyright (c) 2018 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Sebastian Ullrich, Leonardo de Moura Trie for tokenizing the Lean language -/ import Lean.Data.Format namespace Lean namespace Parser open Std (RBNode RBNode.leaf RBNode.singleton RBNode.find RBNode.insert) inductive Trie (α : Type) where | Node : Option α → RBNode Char (fun _ => Trie α) → Trie α namespace Trie variables {α : Type} def empty : Trie α := ⟨none, RBNode.leaf⟩ instance : EmptyCollection (Trie α) := ⟨empty⟩ instance : Inhabited (Trie α) where default := Node none RBNode.leaf partial def insert (t : Trie α) (s : String) (val : α) : Trie α := let rec insertEmpty (i : String.Pos) : Trie α := match s.atEnd i with | true => Trie.Node (some val) RBNode.leaf | false => let c := s.get i let t := insertEmpty (s.next i) Trie.Node none (RBNode.singleton c t) let rec loop | Trie.Node v m, i => match s.atEnd i with | true => Trie.Node (some val) m -- overrides old value | false => let c := s.get i let i := s.next i let t := match RBNode.find Char.lt m c with | none => insertEmpty i | some t => loop t i Trie.Node v (RBNode.insert Char.lt m c t) loop t 0 partial def find? (t : Trie α) (s : String) : Option α := let rec loop | Trie.Node val m, i => match s.atEnd i with | true => val | false => let c := s.get i let i := s.next i match RBNode.find Char.lt m c with | none => none | some t => loop t i loop t 0 private def updtAcc (v : Option α) (i : String.Pos) (acc : String.Pos × Option α) : String.Pos × Option α := match v, acc with | some v, (j, w) => (i, some v) -- we pattern match on `acc` to enable memory reuse | none, acc => acc partial def matchPrefix (s : String) (t : Trie α) (i : String.Pos) : String.Pos × Option α := let rec loop | Trie.Node v m, i, acc => match s.atEnd i with | true => updtAcc v i acc | false => let acc := updtAcc v i acc let c := s.get i let i := s.next i match RBNode.find Char.lt m c with | some t => loop t i acc | none => acc loop t i (i, none) private partial def toStringAux {α : Type} : Trie α → List Format | Trie.Node val map => map.fold (fun Fs c t => format (repr c) :: (Format.group $ Format.nest 2 $ flip Format.joinSep Format.line $ toStringAux t) :: Fs) [] instance {α : Type} : ToString (Trie α) := ⟨fun t => (flip Format.joinSep Format.line $ toStringAux t).pretty⟩ end Trie end Parser end Lean
01da3e06d2d82abc79820ff23c95cecec6ea4f63
05b503addd423dd68145d68b8cde5cd595d74365
/src/category_theory/graded_object.lean
d82c711124be5b486e2438de4ad9baebf70daf2a
[ "Apache-2.0" ]
permissive
aestriplex/mathlib
77513ff2b176d74a3bec114f33b519069788811d
e2fa8b2b1b732d7c25119229e3cdfba8370cb00f
refs/heads/master
1,621,969,960,692
1,586,279,279,000
1,586,279,279,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
6,759
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.shift import category_theory.limits.shapes.zero /-! # The category of graded objects For any type `β`, a `β`-graded object over some category `C` is just a function `β → C` into the objects of `C`. We define the category structure on these. We describe the `comap` functors obtained by precomposing with functions `β → γ`. As a consequence a fixed element (e.g. `1`) in an additive group `β` provides a shift functor on `β`-graded objects When `C` has coproducts we construct the `total` functor `graded_object β C ⥤ C`, show that it is faithful, and deduce that when `C` is concrete so is `graded_object β C`. -/ open category_theory.limits namespace category_theory universes w v u /-- A type synonym for `β → C`, used for `β`-graded objects in a category `C`. -/ def graded_object (β : Type w) (C : Type u) : Type (max w u) := β → C -- Satisfying the inhabited linter... instance inhabited_graded_object (β : Type w) (C : Type u) [inhabited C] : inhabited (graded_object β C) := ⟨λ b, inhabited.default C⟩ /-- A type synonym for `β → C`, used for `β`-graded objects in a category `C` with a shift functor given by translation by `s`. -/ @[nolint unused_arguments] -- `s` is here to distinguish type synonyms asking for different shifts abbreviation graded_object_with_shift {β : Type w} [add_comm_group β] (s : β) (C : Type u) : Type (max w u) := graded_object β C namespace graded_object variables {C : Type u} [𝒞 : category.{v} C] include 𝒞 instance category_of_graded_objects (β : Type w) : category.{(max w v)} (graded_object β C) := { hom := λ X Y, Π b : β, X b ⟶ Y b, id := λ X b, 𝟙 (X b), comp := λ X Y Z f g b, f b ≫ g b, } @[simp] lemma id_apply {β : Type w} (X : graded_object β C) (b : β) : ((𝟙 X) : Π b, X b ⟶ X b) b = 𝟙 (X b) := rfl @[simp] lemma comp_apply {β : Type w} {X Y Z : graded_object β C} (f : X ⟶ Y) (g : Y ⟶ Z) (b : β) : ((f ≫ g) : Π b, X b ⟶ Z b) b = f b ≫ g b := rfl section variable (C) /-- Pull back a graded object along a change-of-grading function. -/ @[simps] def comap {β γ : Type w} (f : β → γ) : (graded_object γ C) ⥤ (graded_object β C) := { obj := λ X, X ∘ f, map := λ X Y g b, g (f b) } /-- The natural isomorphism between pulling back a grading along the identity function, and the identity functor. -/ @[simps] def comap_id (β : Type w) : comap C (id : β → β) ≅ 𝟭 (graded_object β C) := { hom := { app := λ X, 𝟙 X }, inv := { app := λ X, 𝟙 X } }. /-- The natural isomorphism comparing between pulling back along two successive functions, and pulling back along their composition -/ @[simps] def comap_comp {β γ δ : Type w} (f : β → γ) (g : γ → δ) : comap C g ⋙ comap C f ≅ comap C (g ∘ f) := { hom := { app := λ X b, 𝟙 (X (g (f b))) }, inv := { app := λ X b, 𝟙 (X (g (f b))) } } /-- The natural isomorphism comparing between pulling back along two propositionally equal functions. -/ @[simps] def comap_eq {β γ : Type w} {f g : β → γ} (h : f = g) : comap C f ≅ comap C g := { hom := { app := λ X b, eq_to_hom begin dsimp [comap], subst h, end }, inv := { app := λ X b, eq_to_hom begin dsimp [comap], subst h, end }, } @[simp] lemma comap_eq_symm {β γ : Type w} {f g : β → γ} (h : f = g) : comap_eq C h.symm = (comap_eq C h).symm := by tidy @[simp] lemma comap_eq_trans {β γ : Type w} {f g h : β → γ} (k : f = g) (l : g = h) : comap_eq C (k.trans l) = comap_eq C k ≪≫ comap_eq C l := begin ext X b, simp, end /-- The equivalence between β-graded objects and γ-graded objects, given an equivalence between β and γ. -/ @[simps] def comap_equiv {β γ : Type w} (e : β ≃ γ) : (graded_object β C) ≌ (graded_object γ C) := { functor := comap C (e.symm : γ → β), inverse := comap C (e : β → γ), counit_iso := (comap_comp C _ _).trans (comap_eq C (by { ext, simp } )), unit_iso := (comap_eq C (by { ext, simp} )).trans (comap_comp _ _ _).symm, functor_unit_iso_comp' := λ X, begin ext b, dsimp, simp, end, } end instance has_shift {β : Type} [add_comm_group β] (s : β) : has_shift.{v} (graded_object_with_shift s C) := { shift := comap_equiv C { to_fun := λ b, b-s, inv_fun := λ b, b+s, left_inv := λ x, (by simp), right_inv := λ x, (by simp), } } instance has_zero_morphisms [has_zero_morphisms.{v} C] (β : Type w) : has_zero_morphisms.{(max w v)} (graded_object β C) := { has_zero := λ X Y, { zero := λ b, 0 } }. section local attribute [instance] has_zero_object.has_zero instance has_zero_object [has_zero_object.{v} C] [has_zero_morphisms.{v} C] (β : Type w) : has_zero_object.{(max w v)} (graded_object β C) := { zero := λ b, (0 : C), unique_to := λ X, ⟨⟨λ b, 0⟩, λ f, (by ext)⟩, unique_from := λ X, ⟨⟨λ b, 0⟩, λ f, (by ext)⟩, } end end graded_object namespace graded_object -- The universes get a little hairy here, so we restrict the universe level for the grading to 0. -- Since we're typically interested in grading by ℤ or a finite group, this should be okay. -- If you're grading by things in higher universes, have fun! variables (β : Type) variables (C : Type u) [𝒞 : category.{v} C] include 𝒞 variables [has_coproducts.{v} C] /-- The total object of a graded object is the coproduct of the graded components. -/ def total : graded_object β C ⥤ C := { obj := λ X, ∐ (λ i : ulift.{v} β, X i.down), map := λ X Y f, limits.sigma.map (λ i, f i.down) }. variables [decidable_eq β] [has_zero_morphisms.{v} C] /-- The `total` functor taking a graded object to the coproduct of its graded components is faithful. To prove this, we need to know that the coprojections into the coproduct are monomorphisms, which follows from the fact we have zero morphisms and decidable equality for the grading. -/ instance : faithful.{v} (total.{v u} β C) := { injectivity' := λ X Y f g w, begin ext i, replace w := sigma.ι (λ i : ulift β, X i.down) ⟨i⟩ ≫= w, erw [colimit.ι_map, colimit.ι_map] at w, exact mono.right_cancellation _ _ w, end } end graded_object namespace graded_object variables (β : Type) [decidable_eq β] variables (C : Type (u+1)) [large_category C] [𝒞 : concrete_category C] [has_coproducts.{u} C] [has_zero_morphisms.{u} C] include 𝒞 instance : concrete_category (graded_object β C) := { forget := total β C ⋙ forget C } instance : has_forget₂ (graded_object β C) C := { forget₂ := total β C } end graded_object end category_theory
88d5c54eeeac2c5e94893c6eceddaf6ee60fce56
c3f2fcd060adfa2ca29f924839d2d925e8f2c685
/tests/lean/run/pquot.lean
8d9587e7b635fcf782aba27cd94279f565840d32
[ "Apache-2.0" ]
permissive
respu/lean
6582d19a2f2838a28ecd2b3c6f81c32d07b5341d
8c76419c60b63d0d9f7bc04ebb0b99812d0ec654
refs/heads/master
1,610,882,451,231
1,427,747,084,000
1,427,747,429,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,415
lean
import logic.cast data.list data.sigma -- The (pre-)quotient type kernel extension would add the following constants -- quot, pquot.mk, pquot.eqv and pquot.rec -- and a computational rule, which we call pquot.comp here. -- Note that, these constants do not assume the environment contains = constant pquot.{l} {A : Type.{l}} (R : A → A → Prop) : Type.{l} constant pquot.abs {A : Type} (R : A → A → Prop) : A → pquot R -- pquot.eqv is a way to say R a b → (pquot.abs R a) = (pquot.abs R b) without mentioning equality constant pquot.eqv {A : Type} (R : A → A → Prop) {a b : A} : R a b → ∀ (P : pquot R → Prop), P (pquot.abs R a) → P (pquot.abs R b) constant pquot.rec {A : Type} {R : A → A → Prop} {C : pquot R → Type} (f : Π a, C (pquot.abs R a)) -- sound is essentially saying: ∀ (a b : A) (H : R a b), f a == f b -- H makes sure we can only define a function on (quot R) if for all a b : A -- R a b → f a == f b (sound : ∀ a b, R a b → ∀ P : (Π (q : pquot R), C q → Prop), P (pquot.abs R a) (f a) → P (pquot.abs R b) (f b)) (q : pquot R) : C q -- We would also get the following computational rule: -- pquot.rec R H₁ H₂ (pquot.abs R a) ==> H₁ a constant pquot.comp {A : Type} {R : A → A → Prop} {C : pquot R → Type} (f : Π a, C (pquot.abs R a)) (sound : ∀ a b, R a b → ∀ P : (Π (q : pquot R), C q → Prop), P (pquot.abs R a) (f a) → P (pquot.abs R b) (f b)) (a : A) -- In the implementation this would be a computational rule : pquot.rec f sound (pquot.abs R a) = f a -- If the environment contains = and ==, then we can define definition pquot.eq {A : Type} (R : A → A → Prop) {a b : A} (H : R a b) : pquot.abs R a = pquot.abs R b := have aux : ∀ (P : pquot R → Prop), P (pquot.abs R a) → P (pquot.abs R b), from pquot.eqv R H, aux (λ x : pquot R, pquot.abs R a = x) rfl definition pquot.rec_on {A : Type} {R : A → A → Prop} {C : pquot R → Type} (q : pquot R) (f : Π a, C (pquot.abs R a)) (sound : ∀ (a b : A), R a b → f a == f b) : C q := pquot.rec f (λ (a b : A) (H : R a b) (P : Π (q : pquot R), C q → Prop) (Ha : P (pquot.abs R a) (f a)), have aux₁ : f a == f b, from sound a b H, have aux₂ : pquot.abs R a = pquot.abs R b, from pquot.eq R H, have aux₃ : ∀ (c₁ c₂ : C (pquot.abs R a)) (e : c₁ == c₂), P (pquot.abs R a) c₁ → P (pquot.abs R a) c₂, from λ c₁ c₂ e H, eq.rec_on (heq.to_eq e) H, have aux₄ : ∀ (c₁ : C (pquot.abs R a)) (c₂ : C (pquot.abs R b)) (e : c₁ == c₂), P (pquot.abs R a) c₁ → P (pquot.abs R b) c₂, from eq.rec_on aux₂ aux₃, show P (pquot.abs R b) (f b), from aux₄ (f a) (f b) aux₁ Ha) q definition pquot.lift {A : Type} {R : A → A → Prop} {B : Type} (f : A → B) (sound : ∀ (a b : A), R a b → f a = f b) (q : pquot R) : B := pquot.rec_on q f (λ (a b : A) (H : R a b), heq.of_eq (sound a b H)) theorem pquot.induction_on {A : Type} {R : A → A → Prop} {P : pquot R → Prop} (q : pquot R) (f : ∀ a, P (pquot.abs R a)) : P q := pquot.rec_on q f (λ (a b : A) (H : R a b), have aux₁ : pquot.abs R a = pquot.abs R b, from pquot.eq R H, have aux₂ : P (pquot.abs R a) = P (pquot.abs R b), from congr_arg P aux₁, have aux₃ : cast aux₂ (f a) = f b, from proof_irrel (cast aux₂ (f a)) (f b), show f a == f b, from @cast_to_heq _ _ _ _ aux₂ aux₃) theorem pquot.abs.surjective {A : Type} {R : A → A → Prop} : ∀ q : pquot R, ∃ x : A, pquot.abs R x = q := take q, pquot.induction_on q (take a, exists.intro a rfl) definition pquot.exact {A : Type} (R : A → A → Prop) := ∀ a b : A, pquot.abs R a = pquot.abs R b → R a b -- Definable quotient structure dquot {A : Type} (R : A → A → Prop) := mk :: (rep : pquot R → A) (complete : ∀a, R (rep (pquot.abs R a)) a) -- (stable : ∀q, pquot.abs R (rep q) = q) structure is_equiv {A : Type} (R : A → A → Prop) := mk :: (refl : ∀x, R x x) (symm : ∀{x y}, R x y → R y x) (trans : ∀{x y z}, R x y → R y z → R x z) -- Definiable quotients are exact if R is an equivalence relation theorem quot.exact {A : Type} {R : A → A → Prop} (eqv : is_equiv R) (q : dquot R) : pquot.exact R := λ (a b : A) (H : pquot.abs R a = pquot.abs R b), have H₁ : pquot.abs R a = pquot.abs R a → R (dquot.rep q (pquot.abs R a)) (dquot.rep q (pquot.abs R a)), from λH, is_equiv.refl eqv _, have H₂ : pquot.abs R a = pquot.abs R b → R (dquot.rep q (pquot.abs R a)) (dquot.rep q (pquot.abs R b)), from eq.subst H H₁, have H₃ : R (dquot.rep q (pquot.abs R a)) (dquot.rep q (pquot.abs R b)), from H₂ H, have H₄ : R a (dquot.rep q (pquot.abs R a)), from is_equiv.symm eqv (dquot.complete q a), have H₅ : R (dquot.rep q (pquot.abs R b)) b, from dquot.complete q b, is_equiv.trans eqv H₄ (is_equiv.trans eqv H₃ H₅)
6a420f62fc337b9417926e2e515679c01c8747cb
cf39355caa609c0f33405126beee2739aa3cb77e
/library/init/meta/has_reflect.lean
98f15d70b410dbfb79c284aca7b5178f00806041
[ "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
1,797
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich -/ prelude import init.meta.expr init.util universes u v /-- `has_reflect α` lets you produce an `expr` from an instance of α. That is, it is a function from α to expr such that the expr has type α. -/ @[reducible] meta def has_reflect (α : Sort u) := Π a : α, reflected _ a meta structure reflected_value (α : Type u) := (val : α) [reflect : reflected _ val] namespace reflected_value meta def expr {α : Type u} (v : reflected_value α) : expr := v.reflect meta def subst {α : Type u} {β : Type v} (f : α → β) [rf : reflected _ f] (a : reflected_value α) : reflected_value β := @mk _ (f a.val) (rf.subst a.reflect) end reflected_value section local attribute [semireducible] reflected meta instance nat.reflect : has_reflect ℕ | n := if n = 0 then `(0 : ℕ) else if n = 1 then `(1 : ℕ) else if n % 2 = 0 then `(bit0 %%(nat.reflect (n / 2)) : ℕ) else `(bit1 %%(nat.reflect (n / 2)) : ℕ) meta instance unsigned.reflect : has_reflect unsigned | ⟨n, pr⟩ := `(unsigned.of_nat' n) end /-! Instances that [derive] depends on. All other basic instances are defined at the end of derive.lean. -/ meta instance name.reflect : has_reflect name | name.anonymous := `(name.anonymous) | (name.mk_string s n) := `(λ n, name.mk_string s n).subst (name.reflect n) | (name.mk_numeral i n) := `(λ n, name.mk_numeral i n).subst (name.reflect n) meta instance list.reflect {α : Type} [has_reflect α] [reflected _ α] : has_reflect (list α) | [] := `([]) | (h::t) := `(λ t, h :: t).subst (list.reflect t) meta instance punit.reflect : has_reflect punit | () := `(_)
3eff138fef21a9255686af1fe285b3e8eb25a957
8cb37a089cdb4af3af9d8bf1002b417e407a8e9e
/library/init/util.lean
9aa655f18eef6a3181c87da6bcf5ab63bd14143a
[ "Apache-2.0" ]
permissive
kbuzzard/lean
ae3c3db4bb462d750dbf7419b28bafb3ec983ef7
ed1788fd674bb8991acffc8fca585ec746711928
refs/heads/master
1,620,983,366,617
1,618,937,600,000
1,618,937,600,000
359,886,396
1
0
Apache-2.0
1,618,936,987,000
1,618,936,987,000
null
UTF-8
Lean
false
false
1,989
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.meta.format universes u /-- This function has a native implementation that tracks time. -/ def timeit {α : Type u} (s : string) (f : thunk α) : α := f () /-- This function has a native implementation that displays the given string in the regular output stream. -/ def trace {α : Type u} (s : string) (f : thunk α) : α := f () meta def trace_val {α : Type u} [has_to_format α] (f : α) : α := trace (to_fmt f).to_string f /-- This function has a native implementation that shows the VM call stack. -/ def trace_call_stack {α : Type u} (f : thunk α) : α := f () /-- This function has a native implementation that displays in the given position all trace messages used in f. The arguments line and col are filled by the elaborator. -/ def scope_trace {α : Type u} {line col: nat} (f : thunk α) : α := f () /-- This function has a native implementation where the thunk is interrupted if it takes more than 'max' "heartbeats" to compute it. The heartbeat is approx. the maximum number of memory allocations (in thousands) performed by 'f ()'. This is a deterministic way of interrupting long running tasks. -/ meta def try_for {α : Type u} (max : nat) (f : thunk α) : option α := some (f ()) /-- This function has a native implementation where the thunk is interrupted if it takes more than `max` milliseconds to compute it. This is useful due to the variance in the number of heartbeats used by tactics. -/ meta def try_for_time {α : Type u} (max : ℕ) (f : thunk α) : option α := some (f ()) /-- Throws an exception when it is evaluated. -/ meta constant undefined_core {α : Sort u} (message : string) : α meta def undefined {α : Sort u} : α := undefined_core "undefined" meta def unchecked_cast {α : Sort u} {β : Sort u} : α → β := cast undefined
149c19d103079d8f2849b8b0f2041e55a707d3a1
4fa118f6209450d4e8d058790e2967337811b2b5
/src/for_mathlib/topological_field.lean
2f52bbbe57b6ed192922b7b0cec3f4c4d03aa0bf
[ "Apache-2.0" ]
permissive
leanprover-community/lean-perfectoid-spaces
16ab697a220ed3669bf76311daa8c466382207f7
95a6520ce578b30a80b4c36e36ab2d559a842690
refs/heads/master
1,639,557,829,139
1,638,797,866,000
1,638,797,866,000
135,769,296
96
10
Apache-2.0
1,638,797,866,000
1,527,892,754,000
Lean
UTF-8
Lean
false
false
4,910
lean
import tactic.converter.interactive import topology.algebra.ring import for_mathlib.data.set.basic import for_mathlib.topology import for_mathlib.rings open topological_space namespace topological_space variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} variables [topological_space β] [topological_space δ] /-- A product of induced topologies is induced by the product map -/ lemma prod_induced_induced (f : α → β) (g : γ → δ) : @prod.topological_space _ _ (induced f ‹_›) (induced g ‹_›) = induced (λ p, (f p.1, g p.2)) prod.topological_space := begin letI := induced f ‹_›, letI := induced g ‹_›, set fxg := (λ p : α × γ, (f p.1, g p.2)), have key1 : f ∘ (prod.fst : α × γ → α) = (prod.fst : β × δ → β) ∘ fxg, from rfl, have key2 : g ∘ (prod.snd : α × γ → γ) = (prod.snd : β × δ → δ) ∘ fxg, from rfl, unfold prod.topological_space, -- product topology is a sup of induced topologies -- so let's be functorial conv_lhs { rw [induced_compose, induced_compose, key1, key2], congr, rw ← induced_compose, skip, rw ← induced_compose, }, rw induced_inf end end topological_space @[simp] lemma division_ring.inv_val_eq_inv {α : Type*} [division_ring α] (x : units α) :(x : α)⁻¹ = x.inv := begin rw (show x.inv = (x⁻¹ : units α), from rfl), rw ←one_div_eq_inv, symmetry, apply eq_one_div_of_mul_eq_one, exact x.mul_inv end namespace topological_ring open topological_space function variables (R : Type*) [ring R] lemma units.coe_inj : injective (coe : units R → R) := λ x y h, units.ext h variables [topological_space R] -- This is not a global instance. Instead we introduced a class `induced_units` asserting -- something equivalent to this construction holds def topological_space_units : topological_space (units R) := induced units.val ‹_› class induced_units (R : Type*) [ring R] [topological_space R] [t : topological_space $ units R] : Prop := (top_eq : t = induced (coe : units R → R) ‹_›) variables [ring R] [topological_space R] [topological_space $ units R] lemma induced_units.continuous_coe [induced_units R] : continuous (coe : units R → R) := (induced_units.top_eq R).symm ▸ continuous_induced_dom lemma units_embedding [topological_space $ units R] [induced_units R] : embedding (units.val : units R → R) := { induced := induced_units.top_eq R, inj := units.coe_inj _ } instance top_monoid_units [topological_ring R] [topological_space $ units R] [induced_units R] : topological_monoid (units R) := ⟨begin let mulR := (λ (p : R × R), p.1*p.2), let mulRx := (λ (p : units R × units R), p.1*p.2), have key : coe ∘ mulRx = mulR ∘ (λ p, (p.1.val, p.2.val)), from rfl, rw [continuous_iff_le_induced, induced_units.top_eq R, prod_induced_induced, induced_compose, key, ← induced_compose], apply induced_mono, rw ← continuous_iff_le_induced, exact continuous_mul, end⟩ end topological_ring variables (K : Type*) [division_ring K] [topological_space K] /-- A topological division ring is a division ring with a topology where all operations are continuous, including inversion. -/ class topological_division_ring extends topological_ring K : Prop := (continuous_inv : ∀ x : K, x ≠ 0 → continuous_at (λ x : K, x⁻¹ : K → K) x) namespace topological_division_ring open filter set /- In this section, we show that units of a topological division ring endowed with the induced topology form a topological group. These are not global instances because one could want another topology on units. To turn on this feature, use: ```lean local attribute [instance] topological_ring.topological_space_units topological_division_ring.units_top_group ``` -/ variables [topological_division_ring K] local attribute [instance] topological_ring.topological_space_units def induced_units : topological_ring.induced_units K := ⟨rfl⟩ local attribute [instance] induced_units def units_top_group : topological_group (units K) := { continuous_inv := begin have : (units.val : units K → K) ∘ (λx, x⁻¹ : units K → units K) = (λx, x⁻¹ : K → K) ∘ (coe : units K → K), by { ext, apply units.inv_eq_inv }, rw continuous_iff_continuous_at, intros x, rw [continuous_at, nhds_induced, nhds_induced, tendsto_iff_comap, comap_comm this], apply comap_mono, rw ← tendsto_iff_comap, convert topological_division_ring.continuous_inv x.val x.ne_zero, exact x.inv_eq_inv end , ..topological_ring.top_monoid_units K} local attribute [instance] units_top_group lemma continuous_units_inv : continuous (λ x, x.inv : units K → K) := begin change continuous (coe ∘ (λ x, x⁻¹ : units K → units K)), refine (topological_ring.induced_units.continuous_coe K).comp _, exact _root_.continuous_inv, end end topological_division_ring
04f1deb3982ed4d497a56ac480af8916b58ccb5e
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/order/filter/indicator_function_auto.lean
3d68db43963ebcf2fe282492b8eee054141103f6
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
2,815
lean
/- Copyright (c) 2020 Zhouhang Zhou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Zhouhang Zhou, Yury Kudryashov -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.indicator_function import Mathlib.order.filter.at_top_bot import Mathlib.PostPort universes u_1 u_3 u_2 namespace Mathlib /-! # Indicator function and filters Properties of indicator functions involving `=ᶠ` and `≤ᶠ`. ## Tags indicator, characteristic, filter -/ theorem indicator_eventually_eq {α : Type u_1} {M : Type u_3} [HasZero M] {s : set α} {t : set α} {f : α → M} {g : α → M} {l : filter α} (hf : filter.eventually_eq (l ⊓ filter.principal s) f g) (hs : filter.eventually_eq l s t) : filter.eventually_eq l (set.indicator s f) (set.indicator t g) := sorry theorem indicator_union_eventually_eq {α : Type u_1} {M : Type u_3} [add_monoid M] {s : set α} {t : set α} {f : α → M} {l : filter α} (h : filter.eventually (fun (a : α) => ¬a ∈ s ∩ t) l) : filter.eventually_eq l (set.indicator (s ∪ t) f) (set.indicator s f + set.indicator t f) := filter.eventually.mono h fun (a : α) (ha : ¬a ∈ s ∩ t) => set.indicator_union_of_not_mem_inter ha f theorem indicator_eventually_le_indicator {α : Type u_1} {β : Type u_2} [HasZero β] [preorder β] {s : set α} {f : α → β} {g : α → β} {l : filter α} (h : filter.eventually_le (l ⊓ filter.principal s) f g) : filter.eventually_le l (set.indicator s f) (set.indicator s g) := filter.eventually.mono (iff.mp filter.eventually_inf_principal h) fun (a : α) (h : a ∈ s → f a ≤ g a) => set.indicator_rel_indicator (le_refl 0) h theorem tendsto_indicator_of_monotone {α : Type u_1} {β : Type u_2} {ι : Type u_3} [preorder ι] [HasZero β] (s : ι → set α) (hs : monotone s) (f : α → β) (a : α) : filter.tendsto (fun (i : ι) => set.indicator (s i) f a) filter.at_top (pure (set.indicator (set.Union fun (i : ι) => s i) f a)) := sorry theorem tendsto_indicator_of_antimono {α : Type u_1} {β : Type u_2} {ι : Type u_3} [preorder ι] [HasZero β] (s : ι → set α) (hs : ∀ {i j : ι}, i ≤ j → s j ⊆ s i) (f : α → β) (a : α) : filter.tendsto (fun (i : ι) => set.indicator (s i) f a) filter.at_top (pure (set.indicator (set.Inter fun (i : ι) => s i) f a)) := sorry theorem tendsto_indicator_bUnion_finset {α : Type u_1} {β : Type u_2} {ι : Type u_3} [HasZero β] (s : ι → set α) (f : α → β) (a : α) : filter.tendsto (fun (n : finset ι) => set.indicator (set.Union fun (i : ι) => set.Union fun (H : i ∈ n) => s i) f a) filter.at_top (pure (set.indicator (set.Union s) f a)) := sorry end Mathlib
a1e60bb847ec443586343325ed5ca728079ee415
e94d3f31e48d06d252ee7307fe71efe1d500f274
/hott/init/funext.hlean
48e38ce1cee61232fead9ded6ea2eeb6782cc9ec
[ "Apache-2.0" ]
permissive
GallagherCommaJack/lean
e4471240a069d82f97cb361d2bf1a029de3f4256
226f8bafeb9baaa5a2ac58000c83d6beb29991e2
refs/heads/master
1,610,725,100,482
1,459,194,829,000
1,459,195,377,000
55,377,224
0
0
null
1,459,731,701,000
1,459,731,700,000
null
UTF-8
Lean
false
false
10,750
hlean
/- Copyright (c) 2014 Jakob von Raumer. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jakob von Raumer, Floris van Doorn Ported from Coq HoTT -/ prelude import .trunc .equiv .ua open eq is_trunc sigma function is_equiv equiv prod unit prod.ops lift /- We now prove that funext follows from a couple of weaker-looking forms of function extensionality. This proof is originally due to Voevodsky; it has since been simplified by Peter Lumsdaine and Michael Shulman. -/ definition funext.{l k} := Π ⦃A : Type.{l}⦄ {P : A → Type.{k}} (f g : Π x, P x), is_equiv (@apd10 A P f g) -- Naive funext is the simple assertion that pointwise equal functions are equal. definition naive_funext := Π ⦃A : Type⦄ {P : A → Type} (f g : Πx, P x), (f ~ g) → f = g -- Weak funext says that a product of contractible types is contractible. definition weak_funext := Π ⦃A : Type⦄ (P : A → Type) [H: Πx, is_contr (P x)], is_contr (Πx, P x) definition weak_funext_of_naive_funext : naive_funext → weak_funext := (λ nf A P (Pc : Πx, is_contr (P x)), let c := λx, center (P x) in is_contr.mk c (λ f, have eq' : (λx, center (P x)) ~ f, from (λx, center_eq (f x)), have eq : (λx, center (P x)) = f, from nf A P (λx, center (P x)) f eq', eq ) ) /- The less obvious direction is that weak_funext implies funext (and hence all three are logically equivalent). The point is that under weak funext, the space of "pointwise homotopies" has the same universal property as the space of paths. -/ section universe variables l k parameters [wf : weak_funext.{l k}] {A : Type.{l}} {B : A → Type.{k}} (f : Π x, B x) definition is_contr_sigma_homotopy : is_contr (Σ (g : Π x, B x), f ~ g) := is_contr.mk (sigma.mk f (homotopy.refl f)) (λ dp, sigma.rec_on dp (λ (g : Π x, B x) (h : f ~ g), let r := λ (k : Π x, Σ y, f x = y), @sigma.mk _ (λg, f ~ g) (λx, pr1 (k x)) (λx, pr2 (k x)) in let s := λ g h x, @sigma.mk _ (λy, f x = y) (g x) (h x) in have t1 : Πx, is_contr (Σ y, f x = y), from (λx, !is_contr_sigma_eq), have t2 : is_contr (Πx, Σ y, f x = y), from !wf, have t3 : (λ x, @sigma.mk _ (λ y, f x = y) (f x) idp) = s g h, from @eq_of_is_contr (Π x, Σ y, f x = y) t2 _ _, have t4 : r (λ x, sigma.mk (f x) idp) = r (s g h), from ap r t3, have endt : sigma.mk f (homotopy.refl f) = sigma.mk g h, from t4, endt ) ) local attribute is_contr_sigma_homotopy [instance] parameters (Q : Π g (h : f ~ g), Type) (d : Q f (homotopy.refl f)) definition homotopy_ind (g : Πx, B x) (h : f ~ g) : Q g h := @transport _ (λ gh, Q (pr1 gh) (pr2 gh)) (sigma.mk f (homotopy.refl f)) (sigma.mk g h) (@eq_of_is_contr _ is_contr_sigma_homotopy _ _) d local attribute weak_funext [reducible] local attribute homotopy_ind [reducible] definition homotopy_ind_comp : homotopy_ind f (homotopy.refl f) = d := (@prop_eq_of_is_contr _ _ _ _ !eq_of_is_contr idp)⁻¹ ▸ idp end /- Now the proof is fairly easy; we can just use the same induction principle on both sides. -/ section universe variables l k local attribute weak_funext [reducible] theorem funext_of_weak_funext (wf : weak_funext.{l k}) : funext.{l k} := λ A B f g, let eq_to_f := (λ g' x, f = g') in let sim2path := homotopy_ind f eq_to_f idp in have t1 : sim2path f (homotopy.refl f) = idp, proof homotopy_ind_comp f eq_to_f idp qed, have t2 : apd10 (sim2path f (homotopy.refl f)) = (homotopy.refl f), proof ap apd10 t1 qed, have left_inv : apd10 ∘ (sim2path g) ~ id, proof (homotopy_ind f (λ g' x, apd10 (sim2path g' x) = x) t2) g qed, have right_inv : (sim2path g) ∘ apd10 ~ id, from (λ h, eq.rec_on h (homotopy_ind_comp f _ idp)), is_equiv.adjointify apd10 (sim2path g) left_inv right_inv definition funext_from_naive_funext : naive_funext → funext := compose funext_of_weak_funext weak_funext_of_naive_funext end section universe variables l private theorem ua_isequiv_postcompose {A B : Type.{l}} {C : Type} {w : A → B} [H0 : is_equiv w] : is_equiv (@compose C A B w) := let w' := equiv.mk w H0 in let eqinv : A = B := ((@is_equiv.inv _ _ _ (univalence A B)) w') in let eq' := equiv_of_eq eqinv in is_equiv.adjointify (@compose C A B w) (@compose C B A (is_equiv.inv w)) (λ (x : C → B), have eqretr : eq' = w', from (@right_inv _ _ (@equiv_of_eq A B) (univalence A B) w'), have invs_eq : (to_fun eq')⁻¹ = (to_fun w')⁻¹, from inv_eq eq' w' eqretr, have eqfin : (to_fun eq') ∘ ((to_fun eq')⁻¹ ∘ x) = x, from (λ p, (@eq.rec_on Type.{l} A (λ B' p', Π (x' : C → B'), (to_fun (equiv_of_eq p')) ∘ ((to_fun (equiv_of_eq p'))⁻¹ ∘ x') = x') B p (λ x', idp)) ) eqinv x, have eqfin' : (to_fun w') ∘ ((to_fun eq')⁻¹ ∘ x) = x, from eqretr ▸ eqfin, have eqfin'' : (to_fun w') ∘ ((to_fun w')⁻¹ ∘ x) = x, from invs_eq ▸ eqfin', eqfin'' ) (λ (x : C → A), have eqretr : eq' = w', from (@right_inv _ _ (@equiv_of_eq A B) (univalence A B) w'), have invs_eq : (to_fun eq')⁻¹ = (to_fun w')⁻¹, from inv_eq eq' w' eqretr, have eqfin : (to_fun eq')⁻¹ ∘ ((to_fun eq') ∘ x) = x, from (λ p, eq.rec_on p idp) eqinv, have eqfin' : (to_fun eq')⁻¹ ∘ ((to_fun w') ∘ x) = x, from eqretr ▸ eqfin, have eqfin'' : (to_fun w')⁻¹ ∘ ((to_fun w') ∘ x) = x, from invs_eq ▸ eqfin', eqfin'' ) -- We are ready to prove functional extensionality, -- starting with the naive non-dependent version. private definition diagonal [reducible] (B : Type) : Type := Σ xy : B × B, pr₁ xy = pr₂ xy private definition isequiv_src_compose {A B : Type} : @is_equiv (A → diagonal B) (A → B) (compose (pr₁ ∘ pr1)) := @ua_isequiv_postcompose _ _ _ (pr₁ ∘ pr1) (is_equiv.adjointify (pr₁ ∘ pr1) (λ x, sigma.mk (x , x) idp) (λx, idp) (λ x, sigma.rec_on x (λ xy, prod.rec_on xy (λ b c p, eq.rec_on p idp)))) private definition isequiv_tgt_compose {A B : Type} : is_equiv (compose (pr₂ ∘ pr1) : (A → diagonal B) → (A → B)) := begin refine @ua_isequiv_postcompose _ _ _ (pr2 ∘ pr1) _, fapply adjointify, { intro b, exact ⟨(b, b), idp⟩}, { intro b, reflexivity}, { intro a, induction a with q p, induction q, esimp at *, induction p, reflexivity} end theorem nondep_funext_from_ua {A : Type} {B : Type} : Π {f g : A → B}, f ~ g → f = g := (λ (f g : A → B) (p : f ~ g), let d := λ (x : A), @sigma.mk (B × B) (λ (xy : B × B), xy.1 = xy.2) (f x , f x) (eq.refl (f x, f x).1) in let e := λ (x : A), @sigma.mk (B × B) (λ (xy : B × B), xy.1 = xy.2) (f x , g x) (p x) in let precomp1 := compose (pr₁ ∘ sigma.pr1) in have equiv1 : is_equiv precomp1, from @isequiv_src_compose A B, have equiv2 : Π (x y : A → diagonal B), is_equiv (ap precomp1), from is_equiv.is_equiv_ap precomp1, have H' : Π (x y : A → diagonal B), pr₁ ∘ pr1 ∘ x = pr₁ ∘ pr1 ∘ y → x = y, from (λ x y, is_equiv.inv (ap precomp1)), have eq2 : pr₁ ∘ pr1 ∘ d = pr₁ ∘ pr1 ∘ e, from idp, have eq0 : d = e, from H' d e eq2, have eq1 : (pr₂ ∘ pr1) ∘ d = (pr₂ ∘ pr1) ∘ e, from ap _ eq0, eq1 ) end -- Now we use this to prove weak funext, which as we know -- implies (with dependent eta) also the strong dependent funext. theorem weak_funext_of_ua : weak_funext := (λ (A : Type) (P : A → Type) allcontr, let U := (λ (x : A), lift unit) in have pequiv : Π (x : A), P x ≃ unit, from (λ x, @equiv_unit_of_is_contr (P x) (allcontr x)), have psim : Π (x : A), P x = U x, from (λ x, eq_of_equiv_lift (pequiv x)), have p : P = U, from @nondep_funext_from_ua A Type P U psim, have tU' : is_contr (A → lift unit), from is_contr.mk (λ x, up ⋆) (λ f, nondep_funext_from_ua (λa, by induction (f a) with u;induction u;reflexivity)), have tU : is_contr (Π x, U x), from tU', have tlast : is_contr (Πx, P x), from p⁻¹ ▸ tU, tlast) -- we have proven function extensionality from the univalence axiom definition funext_of_ua : funext := funext_of_weak_funext (@weak_funext_of_ua) /- We still take funext as an axiom, so that when you write "print axioms foo", you can see whether it uses only function extensionality, and not also univalence. -/ axiom function_extensionality : funext variables {A : Type} {P : A → Type} {f g : Π x, P x} namespace funext theorem is_equiv_apd [instance] (f g : Π x, P x) : is_equiv (@apd10 A P f g) := function_extensionality f g end funext open funext definition eq_equiv_homotopy : (f = g) ≃ (f ~ g) := equiv.mk apd10 _ definition eq_of_homotopy [reducible] : f ~ g → f = g := (@apd10 A P f g)⁻¹ definition apd10_eq_of_homotopy (p : f ~ g) : apd10 (eq_of_homotopy p) = p := right_inv apd10 p definition eq_of_homotopy_apd10 (p : f = g) : eq_of_homotopy (apd10 p) = p := left_inv apd10 p definition eq_of_homotopy_idp (f : Π x, P x) : eq_of_homotopy (λx : A, idpath (f x)) = idpath f := is_equiv.left_inv apd10 idp definition naive_funext_of_ua : naive_funext := λ A P f g h, eq_of_homotopy h protected definition homotopy.rec_on [recursor] {Q : (f ~ g) → Type} (p : f ~ g) (H : Π(q : f = g), Q (apd10 q)) : Q p := right_inv apd10 p ▸ H (eq_of_homotopy p) protected definition homotopy.rec_on_idp [recursor] {Q : Π{g}, (f ~ g) → Type} {g : Π x, P x} (p : f ~ g) (H : Q (homotopy.refl f)) : Q p := homotopy.rec_on p (λq, eq.rec_on q H) definition eq_of_homotopy_inv {f g : Π x, P x} (H : f ~ g) : eq_of_homotopy (λx, (H x)⁻¹) = (eq_of_homotopy H)⁻¹ := begin apply homotopy.rec_on_idp H, rewrite [+eq_of_homotopy_idp] end definition eq_of_homotopy_con {f g h : Π x, P x} (H1 : f ~ g) (H2 : g ~ h) : eq_of_homotopy (λx, H1 x ⬝ H2 x) = eq_of_homotopy H1 ⬝ eq_of_homotopy H2 := begin apply homotopy.rec_on_idp H1, apply homotopy.rec_on_idp H2, rewrite [+eq_of_homotopy_idp] end
1d7b768d5bf41a41a6f0c806cfe980a4973df002
1b8f093752ba748c5ca0083afef2959aaa7dace5
/src/category_theory/coyoneda.lean
45d0c19fba2fd3ce9fd656cb84680cd9b13c00c8
[]
no_license
khoek/lean-category-theory
7ec4cda9cc64a5a4ffeb84712ac7d020dbbba386
63dcb598e9270a3e8b56d1769eb4f825a177cd95
refs/heads/master
1,585,251,725,759
1,539,344,445,000
1,539,344,445,000
145,281,070
0
0
null
1,534,662,376,000
1,534,662,376,000
null
UTF-8
Lean
false
false
739
lean
import category_theory.yoneda import category_theory.tactics.obviously universes u₁ v₁ open category_theory variables (C : Type u₁) [𝒞 : category.{u₁ v₁} C] include 𝒞 def coyoneda : (Cᵒᵖ) ⥤ (C ⥤ (Type v₁)) := { obj := λ X : C, { obj := λ Y, X ⟶ Y, map' := λ Y Y' f g, g ≫ f }, map' := λ X X' f, { app := λ Y g, f ≫ g } } @[simp] lemma coyoneda_obj_obj (X Y : C) : ((coyoneda C) X) Y = (X ⟶ Y) := rfl @[simp] lemma coyoneda_obj_map (X : C) {Y Y' : C} (f : Y ⟶ Y') : ((coyoneda C) X).map f = λ g, g ≫ f := rfl @[simp] lemma coyoneda_map_app {X X' : C} (f : X ⟶ X') (Y : C) : ((coyoneda C).map f) Y = λ g, f ≫ g := rfl -- Does anyone need the coyoneda lemma as well?
7a681aaada391b8c3d29fcf7dc42ddfc509c3a8b
6afa22d5eee6e9a56b6a2f1210eca8f7a1067466
/library/data/buffer/parser.lean
24b7221e09b4e2b93c02c47b27617169862c20d7
[ "Apache-2.0" ]
permissive
giordano/lean
72a1fabfeb2f1ccfd38673e2719a719cd6ffbb40
56f8877f1efa22215aca0b82f1c0ce2ff975b9c3
refs/heads/master
1,663,091,511,168
1,590,688,082,000
1,590,688,082,000
268,183,678
0
0
Apache-2.0
1,590,885,425,000
1,590,885,424,000
null
UTF-8
Lean
false
false
7,599
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner -/ import data.buffer data.dlist inductive parse_result (α : Type) | done (pos : ℕ) (result : α) : parse_result | fail (pos : ℕ) (expected : dlist string) : parse_result /-- The parser monad. If you are familiar with the Parsec library in Haskell, you will understand this. -/ def parser (α : Type) := ∀ (input : char_buffer) (start : ℕ), parse_result α namespace parser variables {α β γ : Type} protected def bind (p : parser α) (f : α → parser β) : parser β := λ input pos, match p input pos with | parse_result.done pos a := f a input pos | parse_result.fail pos expected := parse_result.fail pos expected end protected def pure (a : α) : parser α := λ input pos, parse_result.done pos a private lemma parser.id_map (p : parser α) : parser.bind p parser.pure = p := begin apply funext, intro input, apply funext, intro pos, dunfold parser.bind, cases (p input pos); exact rfl end private lemma parser.bind_assoc (p : parser α) (q : α → parser β) (r : β → parser γ) : parser.bind (parser.bind p q) r = parser.bind p (λ a, parser.bind (q a) r) := begin apply funext, intro input, apply funext, intro pos, dunfold parser.bind, cases (p input pos); try {dunfold bind}, cases (q result input pos_1); try {dunfold bind}, all_goals {refl} end protected def fail (msg : string) : parser α := λ _ pos, parse_result.fail pos (dlist.singleton msg) instance : monad parser := { pure := @parser.pure, bind := @parser.bind } instance : is_lawful_monad parser := { id_map := @parser.id_map, pure_bind := λ _ _ _ _, rfl, bind_assoc := @parser.bind_assoc } instance : monad_fail parser := { fail := @parser.fail, ..parser.monad } protected def failure : parser α := λ _ pos, parse_result.fail pos dlist.empty protected def orelse (p q : parser α) : parser α := λ input pos, match p input pos with | parse_result.fail pos₁ expected₁ := if pos₁ ≠ pos then parse_result.fail pos₁ expected₁ else match q input pos with | parse_result.fail pos₂ expected₂ := if pos₁ < pos₂ then parse_result.fail pos₁ expected₁ else if pos₂ < pos₁ then parse_result.fail pos₂ expected₂ else -- pos₁ = pos₂ parse_result.fail pos₁ (expected₁ ++ expected₂) | ok := ok end | ok := ok end instance : alternative parser := { failure := @parser.failure, orelse := @parser.orelse } instance : inhabited (parser α) := ⟨parser.failure⟩ /-- Overrides the expected token name, and does not consume input on failure. -/ def decorate_errors (msgs : thunk (list string)) (p : parser α) : parser α := λ input pos, match p input pos with | parse_result.fail _ expected := parse_result.fail pos (dlist.lazy_of_list (msgs ())) | ok := ok end /-- Overrides the expected token name, and does not consume input on failure. -/ def decorate_error (msg : thunk string) (p : parser α) : parser α := decorate_errors [msg ()] p /-- Matches a single character satisfying the given predicate. -/ def sat (p : char → Prop) [decidable_pred p] : parser char := λ input pos, if h : pos < input.size then let c := input.read ⟨pos, h⟩ in if p c then parse_result.done (pos+1) $ input.read ⟨pos, h⟩ else parse_result.fail pos dlist.empty else parse_result.fail pos dlist.empty /-- Matches the empty word. -/ def eps : parser unit := return () /-- Matches the given character. -/ def ch (c : char) : parser unit := decorate_error c.to_string $ sat (= c) >> eps /-- Matches a whole char_buffer. Does not consume input in case of failure. -/ def char_buf (s : char_buffer) : parser unit := decorate_error s.to_string $ s.to_list.mmap' ch /-- Matches one out of a list of characters. -/ def one_of (cs : list char) : parser char := decorate_errors (do c ← cs, return c.to_string) $ sat (∈ cs) def one_of' (cs : list char) : parser unit := one_of cs >> eps /-- Matches a string. Does not consume input in case of failure. -/ def str (s : string) : parser unit := decorate_error s $ s.to_list.mmap' ch /-- Number of remaining input characters. -/ def remaining : parser ℕ := λ input pos, parse_result.done pos (input.size - pos) /-- Matches the end of the input. -/ def eof : parser unit := decorate_error "<end-of-file>" $ do rem ← remaining, guard $ rem = 0 def foldr_core (f : α → β → β) (p : parser α) (b : β) : ∀ (reps : ℕ), parser β | 0 := failure | (reps+1) := (do x ← p, xs ← foldr_core reps, return (f x xs)) <|> return b /-- Matches zero or more occurrences of `p`, and folds the result. -/ def foldr (f : α → β → β) (p : parser α) (b : β) : parser β := λ input pos, foldr_core f p b (input.size - pos + 1) input pos def foldl_core (f : α → β → α) : ∀ (a : α) (p : parser β) (reps : ℕ), parser α | a p 0 := failure | a p (reps+1) := (do x ← p, foldl_core (f a x) p reps) <|> return a /-- Matches zero or more occurrences of `p`, and folds the result. -/ def foldl (f : α → β → α) (a : α) (p : parser β) : parser α := λ input pos, foldl_core f a p (input.size - pos + 1) input pos /-- Matches zero or more occurrences of `p`. -/ def many (p : parser α) : parser (list α) := foldr list.cons p [] def many_char (p : parser char) : parser string := list.as_string <$> many p /-- Matches zero or more occurrences of `p`. -/ def many' (p : parser α) : parser unit := many p >> eps /-- Matches one or more occurrences of `p`. -/ def many1 (p : parser α) : parser (list α) := list.cons <$> p <*> many p /-- Matches one or more occurences of the char parser `p` and implodes them into a string. -/ def many_char1 (p : parser char) : parser string := list.as_string <$> many1 p /-- Matches one or more occurrences of `p`, separated by `sep`. -/ def sep_by1 (sep : parser unit) (p : parser α) : parser (list α) := list.cons <$> p <*> many (sep >> p) /-- Matches zero or more occurrences of `p`, separated by `sep`. -/ def sep_by (sep : parser unit) (p : parser α) : parser (list α) := sep_by1 sep p <|> return [] def fix_core (F : parser α → parser α) : ∀ (max_depth : ℕ), parser α | 0 := failure | (max_depth+1) := F (fix_core max_depth) /-- Fixpoint combinator satisfying `fix F = F (fix F)`. -/ def fix (F : parser α → parser α) : parser α := λ input pos, fix_core F (input.size - pos + 1) input pos private def make_monospaced : char → char | '\n' := ' ' | '\t' := ' ' | '\x0d' := ' ' | c := c def mk_error_msg (input : char_buffer) (pos : ℕ) (expected : dlist string) : char_buffer := let left_ctx := (input.take pos).take_right 10, right_ctx := (input.drop pos).take 10 in left_ctx.map make_monospaced ++ right_ctx.map make_monospaced ++ "\n".to_char_buffer ++ left_ctx.map (λ _, ' ') ++ "^\n".to_char_buffer ++ "\n".to_char_buffer ++ "expected: ".to_char_buffer ++ string.to_char_buffer (" | ".intercalate expected.to_list) ++ "\n".to_char_buffer /-- Runs a parser on the given input. The parser needs to match the complete input. -/ def run (p : parser α) (input : char_buffer) : sum string α := match (p <* eof) input 0 with | parse_result.done pos res := sum.inr res | parse_result.fail pos expected := sum.inl $ buffer.to_string $ mk_error_msg input pos expected end /-- Runs a parser on the given input. The parser needs to match the complete input. -/ def run_string (p : parser α) (input : string) : sum string α := run p input.to_char_buffer end parser
45a24b6e40ae3eb186cd3e456ee7a8d99be05032
d1a52c3f208fa42c41df8278c3d280f075eb020c
/stage0/src/Init/Meta.lean
020723340d858f576d1cb44ec501feb29321cc9c
[ "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
34,980
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 and Sebastian Ullrich Additional goodies for writing macros -/ prelude import Init.Data.Array.Basic namespace Lean @[extern c inline "lean_box(LEAN_VERSION_MAJOR)"] private constant version.getMajor (u : Unit) : Nat def version.major : Nat := version.getMajor () @[extern c inline "lean_box(LEAN_VERSION_MINOR)"] private constant version.getMinor (u : Unit) : Nat def version.minor : Nat := version.getMinor () @[extern c inline "lean_box(LEAN_VERSION_PATCH)"] private constant version.getPatch (u : Unit) : Nat def version.patch : Nat := version.getPatch () @[extern "lean_get_githash"] constant getGithash (u : Unit) : String def githash : String := getGithash () @[extern c inline "LEAN_VERSION_IS_RELEASE"] constant version.getIsRelease (u : Unit) : Bool def version.isRelease : Bool := version.getIsRelease () /-- Additional version description like "nightly-2018-03-11" -/ @[extern c inline "lean_mk_string(LEAN_SPECIAL_VERSION_DESC)"] constant version.getSpecialDesc (u : Unit) : String def version.specialDesc : String := version.getSpecialDesc () def versionStringCore := toString version.major ++ "." ++ toString Lean.version.minor ++ "." ++ toString Lean.version.patch def versionString := if version.isRelease then versionStringCore else if version.specialDesc ≠ "" then version.specialDesc else "master (" ++ versionStringCore ++ ", commit " ++ getGithash () ++ ")" /- Valid identifier names -/ def isGreek (c : Char) : Bool := 0x391 ≤ c.val && c.val ≤ 0x3dd def isLetterLike (c : Char) : Bool := (0x3b1 ≤ c.val && c.val ≤ 0x3c9 && c.val ≠ 0x3bb) || -- Lower greek, but lambda (0x391 ≤ c.val && c.val ≤ 0x3A9 && c.val ≠ 0x3A0 && c.val ≠ 0x3A3) || -- Upper greek, but Pi and Sigma (0x3ca ≤ c.val && c.val ≤ 0x3fb) || -- Coptic letters (0x1f00 ≤ c.val && c.val ≤ 0x1ffe) || -- Polytonic Greek Extended Character Set (0x2100 ≤ c.val && c.val ≤ 0x214f) || -- Letter like block (0x1d49c ≤ c.val && c.val ≤ 0x1d59f) -- Latin letters, Script, Double-struck, Fractur def isNumericSubscript (c : Char) : Bool := 0x2080 ≤ c.val && c.val ≤ 0x2089 def isSubScriptAlnum (c : Char) : Bool := isNumericSubscript c || (0x2090 ≤ c.val && c.val ≤ 0x209c) || (0x1d62 ≤ c.val && c.val ≤ 0x1d6a) def isIdFirst (c : Char) : Bool := c.isAlpha || c = '_' || isLetterLike c def isIdRest (c : Char) : Bool := c.isAlphanum || c = '_' || c = '\'' || c == '!' || c == '?' || isLetterLike c || isSubScriptAlnum c def idBeginEscape := '«' def idEndEscape := '»' def isIdBeginEscape (c : Char) : Bool := c = idBeginEscape def isIdEndEscape (c : Char) : Bool := c = idEndEscape namespace Name def getRoot : Name → Name | anonymous => anonymous | n@(str anonymous _ _) => n | n@(num anonymous _ _) => n | str n _ _ => getRoot n | num n _ _ => getRoot n @[export lean_is_inaccessible_user_name] def isInaccessibleUserName : Name → Bool | Name.str _ s _ => s.contains '✝' || s == "_inaccessible" | Name.num p idx _ => isInaccessibleUserName p | _ => false def escapePart (s : String) : Option String := if s.length > 0 && isIdFirst s[0] && (s.toSubstring.drop 1).all isIdRest then s else if s.any isIdEndEscape then none else some <| idBeginEscape.toString ++ s ++ idEndEscape.toString -- NOTE: does not roundtrip even with `escape = true` if name is anonymous or contains numeric part or `idEndEscape` variable (sep : String) (escape : Bool) def toStringWithSep : Name → String | anonymous => "[anonymous]" | str anonymous s _ => maybeEscape s | num anonymous v _ => toString v | str n s _ => toStringWithSep n ++ sep ++ maybeEscape s | num n v _ => toStringWithSep n ++ sep ++ Nat.repr v where maybeEscape s := if escape then escapePart s |>.getD s else s protected def toString (n : Name) (escape := true) : String := -- never escape "prettified" inaccessible names or macro scopes or pseudo-syntax introduced by the delaborator toStringWithSep "." (escape && !n.isInaccessibleUserName && !n.hasMacroScopes && !maybePseudoSyntax) n where maybePseudoSyntax := if let Name.str _ s _ := n.getRoot then -- could be pseudo-syntax for loose bvar or universe mvar, output as is "#".isPrefixOf s || "?".isPrefixOf s else false instance : ToString Name where toString n := n.toString private def hasNum : Name → Bool | anonymous => false | num .. => true | str p .. => hasNum p protected def reprPrec (n : Name) (prec : Nat) : Std.Format := match n with | anonymous => Std.Format.text "Lean.Name.anonymous" | num p i _ => Repr.addAppParen ("Lean.Name.mkNum " ++ Name.reprPrec p max_prec ++ " " ++ repr i) prec | str p s _ => if p.hasNum then Repr.addAppParen ("Lean.Name.mkStr " ++ Name.reprPrec p max_prec ++ " " ++ repr s) prec else Std.Format.text "`" ++ n.toString instance : Repr Name where reprPrec := Name.reprPrec deriving instance Repr for Syntax def capitalize : Name → Name | Name.str p s _ => Name.mkStr p s.capitalize | n => n def replacePrefix : Name → Name → Name → Name | anonymous, anonymous, newP => newP | anonymous, _, _ => anonymous | n@(str p s _), queryP, newP => if n == queryP then newP else Name.mkStr (p.replacePrefix queryP newP) s | n@(num p s _), queryP, newP => if n == queryP then newP else Name.mkNum (p.replacePrefix queryP newP) s /-- Remove macros scopes, apply `f`, and put them back -/ @[inline] def modifyBase (n : Name) (f : Name → Name) : Name := if n.hasMacroScopes then let view := extractMacroScopes n { view with name := f view.name }.review else f n @[export lean_name_append_after] def appendAfter (n : Name) (suffix : String) : Name := n.modifyBase fun | str p s _ => Name.mkStr p (s ++ suffix) | n => Name.mkStr n suffix @[export lean_name_append_index_after] def appendIndexAfter (n : Name) (idx : Nat) : Name := n.modifyBase fun | str p s _ => Name.mkStr p (s ++ "_" ++ toString idx) | n => Name.mkStr n ("_" ++ toString idx) @[export lean_name_append_before] def appendBefore (n : Name) (pre : String) : Name := n.modifyBase fun | anonymous => Name.mkStr anonymous pre | str p s _ => Name.mkStr p (pre ++ s) | num p n _ => Name.mkNum (Name.mkStr p pre) n end Name structure NameGenerator where namePrefix : Name := `_uniq idx : Nat := 1 deriving Inhabited namespace NameGenerator @[inline] def curr (g : NameGenerator) : Name := Name.mkNum g.namePrefix g.idx @[inline] def next (g : NameGenerator) : NameGenerator := { g with idx := g.idx + 1 } @[inline] def mkChild (g : NameGenerator) : NameGenerator × NameGenerator := ({ namePrefix := Name.mkNum g.namePrefix g.idx, idx := 1 }, { g with idx := g.idx + 1 }) end NameGenerator class MonadNameGenerator (m : Type → Type) where getNGen : m NameGenerator setNGen : NameGenerator → m Unit export MonadNameGenerator (getNGen setNGen) def mkFreshId {m : Type → Type} [Monad m] [MonadNameGenerator m] : m Name := do let ngen ← getNGen let r := ngen.curr setNGen ngen.next pure r instance monadNameGeneratorLift (m n : Type → Type) [MonadLift m n] [MonadNameGenerator m] : MonadNameGenerator n := { getNGen := liftM (getNGen : m _), setNGen := fun ngen => liftM (setNGen ngen : m _) } namespace Syntax partial def structEq : Syntax → Syntax → Bool | Syntax.missing, Syntax.missing => true | Syntax.node _ k args, Syntax.node _ k' args' => k == k' && args.isEqv args' structEq | Syntax.atom _ val, Syntax.atom _ val' => val == val' | Syntax.ident _ rawVal val preresolved, Syntax.ident _ rawVal' val' preresolved' => rawVal == rawVal' && val == val' && preresolved == preresolved' | _, _ => false instance : BEq Lean.Syntax := ⟨structEq⟩ partial def getTailInfo? : Syntax → Option SourceInfo | atom info _ => info | ident info .. => info | node SourceInfo.none _ args => args.findSomeRev? getTailInfo? | node info _ args => info | _ => none def getTailInfo (stx : Syntax) : SourceInfo := stx.getTailInfo?.getD SourceInfo.none def getTrailingSize (stx : Syntax) : Nat := match stx.getTailInfo? with | some (SourceInfo.original (trailing := trailing) ..) => trailing.bsize | _ => 0 /-- Return substring of original input covering `stx`. Result is meaningful only if all involved `SourceInfo.original`s refer to the same string (as is the case after parsing). -/ def getSubstring? (stx : Syntax) (withLeading := true) (withTrailing := true) : Option Substring := match stx.getHeadInfo, stx.getTailInfo with | SourceInfo.original lead startPos _ _, SourceInfo.original _ _ trail stopPos => some { str := lead.str startPos := if withLeading then lead.startPos else startPos stopPos := if withTrailing then trail.stopPos else stopPos } | _, _ => none @[specialize] private partial def updateLast {α} [Inhabited α] (a : Array α) (f : α → Option α) (i : Nat) : Option (Array α) := if i == 0 then none else let i := i - 1 let v := a[i] match f v with | some v => some <| a.set! i v | none => updateLast a f i partial def setTailInfoAux (info : SourceInfo) : Syntax → Option Syntax | atom _ val => some <| atom info val | ident _ rawVal val pre => some <| ident info rawVal val pre | node info k args => match updateLast args (setTailInfoAux info) args.size with | some args => some <| node info k args | none => none | stx => none def setTailInfo (stx : Syntax) (info : SourceInfo) : Syntax := match setTailInfoAux info stx with | some stx => stx | none => stx def unsetTrailing (stx : Syntax) : Syntax := match stx.getTailInfo with | SourceInfo.original lead pos trail endPos => stx.setTailInfo (SourceInfo.original lead pos "".toSubstring endPos) | _ => stx @[specialize] private partial def updateFirst {α} [Inhabited α] (a : Array α) (f : α → Option α) (i : Nat) : Option (Array α) := if h : i < a.size then let v := a.get ⟨i, h⟩; match f v with | some v => some <| a.set ⟨i, h⟩ v | none => updateFirst a f (i+1) else none partial def setHeadInfoAux (info : SourceInfo) : Syntax → Option Syntax | atom _ val => some <| atom info val | ident _ rawVal val pre => some <| ident info rawVal val pre | node i k args => match updateFirst args (setHeadInfoAux info) 0 with | some args => some <| node i k args | noxne => none | stx => none def setHeadInfo (stx : Syntax) (info : SourceInfo) : Syntax := match setHeadInfoAux info stx with | some stx => stx | none => stx def setInfo (info : SourceInfo) : Syntax → Syntax | atom _ val => atom info val | ident _ rawVal val pre => ident info rawVal val pre | node _ kind args => node info kind args | missing => missing /-- Return the first atom/identifier that has position information -/ partial def getHead? : Syntax → Option Syntax | stx@(atom info ..) => info.getPos?.map fun _ => stx | stx@(ident info ..) => info.getPos?.map fun _ => stx | node SourceInfo.none _ args => args.findSome? getHead? | stx@(node info _ _) => stx | _ => none def copyHeadTailInfoFrom (target source : Syntax) : Syntax := target.setHeadInfo source.getHeadInfo |>.setTailInfo source.getTailInfo end Syntax /-- Use the head atom/identifier of the current `ref` as the `ref` -/ @[inline] def withHeadRefOnly {m : Type → Type} [Monad m] [MonadRef m] {α} (x : m α) : m α := do match (← getRef).getHead? with | none => x | some ref => withRef ref x @[inline] def mkNode (k : SyntaxNodeKind) (args : Array Syntax) : Syntax := Syntax.node SourceInfo.none k args /- Syntax objects for a Lean module. -/ structure Module where header : Syntax commands : Array Syntax /-- Expand all macros in the given syntax -/ partial def expandMacros : Syntax → MacroM Syntax | stx@(Syntax.node info k args) => do match (← expandMacro? stx) with | some stxNew => expandMacros stxNew | none => do let args ← Macro.withIncRecDepth stx <| args.mapM expandMacros pure <| Syntax.node info k args | stx => pure stx /- Helper functions for processing Syntax programmatically -/ /-- Create an identifier copying the position from `src`. To refer to a specific constant, use `mkCIdentFrom` instead. -/ def mkIdentFrom (src : Syntax) (val : Name) : Syntax := Syntax.ident (SourceInfo.fromRef src) (toString val).toSubstring val [] def mkIdentFromRef [Monad m] [MonadRef m] (val : Name) : m Syntax := do return mkIdentFrom (← getRef) val /-- Create an identifier referring to a constant `c` copying the position from `src`. This variant of `mkIdentFrom` makes sure that the identifier cannot accidentally be captured. -/ def mkCIdentFrom (src : Syntax) (c : Name) : Syntax := -- Remark: We use the reserved macro scope to make sure there are no accidental collision with our frontend let id := addMacroScope `_internal c reservedMacroScope Syntax.ident (SourceInfo.fromRef src) (toString id).toSubstring id [(c, [])] def mkCIdentFromRef [Monad m] [MonadRef m] (c : Name) : m Syntax := do return mkCIdentFrom (← getRef) c def mkCIdent (c : Name) : Syntax := mkCIdentFrom Syntax.missing c @[export lean_mk_syntax_ident] def mkIdent (val : Name) : Syntax := Syntax.ident SourceInfo.none (toString val).toSubstring val [] @[inline] def mkNullNode (args : Array Syntax := #[]) : Syntax := mkNode nullKind args @[inline] def mkGroupNode (args : Array Syntax := #[]) : Syntax := mkNode groupKind args def mkSepArray (as : Array Syntax) (sep : Syntax) : Array Syntax := Id.run <| do let mut i := 0 let mut r := #[] for a in as do if i > 0 then r := r.push sep |>.push a else r := r.push a i := i + 1 return r def mkOptionalNode (arg : Option Syntax) : Syntax := match arg with | some arg => mkNullNode #[arg] | none => mkNullNode #[] def mkHole (ref : Syntax) : Syntax := mkNode `Lean.Parser.Term.hole #[mkAtomFrom ref "_"] namespace Syntax def mkSep (a : Array Syntax) (sep : Syntax) : Syntax := mkNullNode <| mkSepArray a sep def SepArray.ofElems {sep} (elems : Array Syntax) : SepArray sep := ⟨mkSepArray elems (mkAtom sep)⟩ def SepArray.ofElemsUsingRef [Monad m] [MonadRef m] {sep} (elems : Array Syntax) : m (SepArray sep) := do let ref ← getRef; return ⟨mkSepArray elems (mkAtomFrom ref sep)⟩ instance (sep) : Coe (Array Syntax) (SepArray sep) where coe := SepArray.ofElems /-- Create syntax representing a Lean term application, but avoid degenerate empty applications. -/ def mkApp (fn : Syntax) : (args : Array Syntax) → Syntax | #[] => fn | args => mkNode `Lean.Parser.Term.app #[fn, mkNullNode args] def mkCApp (fn : Name) (args : Array Syntax) : Syntax := mkApp (mkCIdent fn) args def mkLit (kind : SyntaxNodeKind) (val : String) (info := SourceInfo.none) : Syntax := let atom : Syntax := Syntax.atom info val mkNode kind #[atom] def mkStrLit (val : String) (info := SourceInfo.none) : Syntax := mkLit strLitKind (String.quote val) info def mkNumLit (val : String) (info := SourceInfo.none) : Syntax := mkLit numLitKind val info def mkScientificLit (val : String) (info := SourceInfo.none) : Syntax := mkLit scientificLitKind val info def mkNameLit (val : String) (info := SourceInfo.none) : Syntax := mkLit nameLitKind val info /- Recall that we don't have special Syntax constructors for storing numeric and string atoms. The idea is to have an extensible approach where embedded DSLs may have new kind of atoms and/or different ways of representing them. So, our atoms contain just the parsed string. The main Lean parser uses the kind `numLitKind` for storing natural numbers that can be encoded in binary, octal, decimal and hexadecimal format. `isNatLit` implements a "decoder" for Syntax objects representing these numerals. -/ private partial def decodeBinLitAux (s : String) (i : String.Pos) (val : Nat) : Option Nat := if s.atEnd i then some val else let c := s.get i if c == '0' then decodeBinLitAux s (s.next i) (2*val) else if c == '1' then decodeBinLitAux s (s.next i) (2*val + 1) else none private partial def decodeOctalLitAux (s : String) (i : String.Pos) (val : Nat) : Option Nat := if s.atEnd i then some val else let c := s.get i if '0' ≤ c && c ≤ '7' then decodeOctalLitAux s (s.next i) (8*val + c.toNat - '0'.toNat) else none private def decodeHexDigit (s : String) (i : String.Pos) : Option (Nat × String.Pos) := let c := s.get i let i := s.next i if '0' ≤ c && c ≤ '9' then some (c.toNat - '0'.toNat, i) else if 'a' ≤ c && c ≤ 'f' then some (10 + c.toNat - 'a'.toNat, i) else if 'A' ≤ c && c ≤ 'F' then some (10 + c.toNat - 'A'.toNat, i) else none private partial def decodeHexLitAux (s : String) (i : String.Pos) (val : Nat) : Option Nat := if s.atEnd i then some val else match decodeHexDigit s i with | some (d, i) => decodeHexLitAux s i (16*val + d) | none => none private partial def decodeDecimalLitAux (s : String) (i : String.Pos) (val : Nat) : Option Nat := if s.atEnd i then some val else let c := s.get i if '0' ≤ c && c ≤ '9' then decodeDecimalLitAux s (s.next i) (10*val + c.toNat - '0'.toNat) else none def decodeNatLitVal? (s : String) : Option Nat := let len := s.length if len == 0 then none else let c := s.get 0 if c == '0' then if len == 1 then some 0 else let c := s.get 1 if c == 'x' || c == 'X' then decodeHexLitAux s 2 0 else if c == 'b' || c == 'B' then decodeBinLitAux s 2 0 else if c == 'o' || c == 'O' then decodeOctalLitAux s 2 0 else if c.isDigit then decodeDecimalLitAux s 0 0 else none else if c.isDigit then decodeDecimalLitAux s 0 0 else none def isLit? (litKind : SyntaxNodeKind) (stx : Syntax) : Option String := match stx with | Syntax.node _ k args => if k == litKind && args.size == 1 then match args.get! 0 with | (Syntax.atom _ val) => some val | _ => none else none | _ => none private def isNatLitAux (litKind : SyntaxNodeKind) (stx : Syntax) : Option Nat := match isLit? litKind stx with | some val => decodeNatLitVal? val | _ => none def isNatLit? (s : Syntax) : Option Nat := isNatLitAux numLitKind s def isFieldIdx? (s : Syntax) : Option Nat := isNatLitAux fieldIdxKind s partial def decodeScientificLitVal? (s : String) : Option (Nat × Bool × Nat) := let len := s.length if len == 0 then none else let c := s.get 0 if c.isDigit then decode 0 0 else none where decodeAfterExp (i : String.Pos) (val : Nat) (e : Nat) (sign : Bool) (exp : Nat) : Option (Nat × Bool × Nat) := if s.atEnd i then if sign then some (val, sign, exp + e) else if exp >= e then some (val, sign, exp - e) else some (val, true, e - exp) else let c := s.get i if '0' ≤ c && c ≤ '9' then decodeAfterExp (s.next i) val e sign (10*exp + c.toNat - '0'.toNat) else none decodeExp (i : String.Pos) (val : Nat) (e : Nat) : Option (Nat × Bool × Nat) := let c := s.get i if c == '-' then decodeAfterExp (s.next i) val e true 0 else decodeAfterExp i val e false 0 decodeAfterDot (i : String.Pos) (val : Nat) (e : Nat) : Option (Nat × Bool × Nat) := if s.atEnd i then some (val, true, e) else let c := s.get i if '0' ≤ c && c ≤ '9' then decodeAfterDot (s.next i) (10*val + c.toNat - '0'.toNat) (e+1) else if c == 'e' || c == 'E' then decodeExp (s.next i) val e else none decode (i : String.Pos) (val : Nat) : Option (Nat × Bool × Nat) := if s.atEnd i then none else let c := s.get i if '0' ≤ c && c ≤ '9' then decode (s.next i) (10*val + c.toNat - '0'.toNat) else if c == '.' then decodeAfterDot (s.next i) val 0 else if c == 'e' || c == 'E' then decodeExp (s.next i) val 0 else none def isScientificLit? (stx : Syntax) : Option (Nat × Bool × Nat) := match isLit? scientificLitKind stx with | some val => decodeScientificLitVal? val | _ => none def isIdOrAtom? : Syntax → Option String | Syntax.atom _ val => some val | Syntax.ident _ rawVal _ _ => some rawVal.toString | _ => none def toNat (stx : Syntax) : Nat := match stx.isNatLit? with | some val => val | none => 0 def decodeQuotedChar (s : String) (i : String.Pos) : Option (Char × String.Pos) := OptionM.run do let c := s.get i let i := s.next i if c == '\\' then pure ('\\', i) else if c = '\"' then pure ('\"', i) else if c = '\'' then pure ('\'', i) else if c = 'r' then pure ('\r', i) else if c = 'n' then pure ('\n', i) else if c = 't' then pure ('\t', i) else if c = 'x' then let (d₁, i) ← decodeHexDigit s i let (d₂, i) ← decodeHexDigit s i pure (Char.ofNat (16*d₁ + d₂), i) else if c = 'u' then do let (d₁, i) ← decodeHexDigit s i let (d₂, i) ← decodeHexDigit s i let (d₃, i) ← decodeHexDigit s i let (d₄, i) ← decodeHexDigit s i pure (Char.ofNat (16*(16*(16*d₁ + d₂) + d₃) + d₄), i) else none partial def decodeStrLitAux (s : String) (i : String.Pos) (acc : String) : Option String := OptionM.run do let c := s.get i let i := s.next i if c == '\"' then pure acc else if s.atEnd i then none else if c == '\\' then do let (c, i) ← decodeQuotedChar s i decodeStrLitAux s i (acc.push c) else decodeStrLitAux s i (acc.push c) def decodeStrLit (s : String) : Option String := decodeStrLitAux s 1 "" def isStrLit? (stx : Syntax) : Option String := match isLit? strLitKind stx with | some val => decodeStrLit val | _ => none def decodeCharLit (s : String) : Option Char := OptionM.run do let c := s.get 1 if c == '\\' then do let (c, _) ← decodeQuotedChar s 2 pure c else pure c def isCharLit? (stx : Syntax) : Option Char := match isLit? charLitKind stx with | some val => decodeCharLit val | _ => none private partial def splitNameLitAux (ss : Substring) (acc : List Substring) : List Substring := let splitRest (ss : Substring) (acc : List Substring) : List Substring := if ss.front == '.' then splitNameLitAux (ss.drop 1) acc else if ss.isEmpty then acc else [] if ss.isEmpty then [] else let curr := ss.front if isIdBeginEscape curr then let escapedPart := ss.takeWhile (!isIdEndEscape ·) let escapedPart := { escapedPart with stopPos := ss.stopPos.min (escapedPart.str.next escapedPart.stopPos) } if !isIdEndEscape (escapedPart.get <| escapedPart.prev escapedPart.bsize) then [] else splitRest (ss.extract escapedPart.bsize ss.bsize) (escapedPart :: acc) else if isIdFirst curr then let idPart := ss.takeWhile isIdRest splitRest (ss.extract idPart.bsize ss.bsize) (idPart :: acc) else if curr.isDigit then let idPart := ss.takeWhile Char.isDigit splitRest (ss.extract idPart.bsize ss.bsize) (idPart :: acc) else [] /-- Split a name literal (without the backtick) into its dot-separated components. For example, `foo.bla.«bo.o»` ↦ `["foo", "bla", "«bo.o»"]`. If the literal cannot be parsed, return `[]`. -/ def splitNameLit (ss : Substring) : List Substring := splitNameLitAux ss [] |>.reverse def decodeNameLit (s : String) : Option Name := if s.get 0 == '`' then match splitNameLitAux (s.toSubstring.drop 1) [] with | [] => none | comps => some <| comps.foldr (init := Name.anonymous) fun comp n => let comp := comp.toString if isIdBeginEscape comp.front then Name.mkStr n (comp.drop 1 |>.dropRight 1) else if comp.front.isDigit then if let some k := decodeNatLitVal? comp then Name.mkNum n k else unreachable! else Name.mkStr n comp else none def isNameLit? (stx : Syntax) : Option Name := match isLit? nameLitKind stx with | some val => decodeNameLit val | _ => none def hasArgs : Syntax → Bool | Syntax.node _ _ args => args.size > 0 | _ => false def isAtom : Syntax → Bool | atom _ _ => true | _ => false def isToken (token : String) : Syntax → Bool | atom _ val => val.trim == token.trim | _ => false def isNone (stx : Syntax) : Bool := match stx with | Syntax.node _ k args => k == nullKind && args.size == 0 -- when elaborating partial syntax trees, it's reasonable to interpret missing parts as `none` | Syntax.missing => true | _ => false def getOptional? (stx : Syntax) : Option Syntax := match stx with | Syntax.node _ k args => if k == nullKind && args.size == 1 then some (args.get! 0) else none | _ => none def getOptionalIdent? (stx : Syntax) : Option Name := match stx.getOptional? with | some stx => some stx.getId | none => none partial def findAux (p : Syntax → Bool) : Syntax → Option Syntax | stx@(Syntax.node _ _ args) => if p stx then some stx else args.findSome? (findAux p) | stx => if p stx then some stx else none def find? (stx : Syntax) (p : Syntax → Bool) : Option Syntax := findAux p stx end Syntax /-- Reflect a runtime datum back to surface syntax (best-effort). -/ class Quote (α : Type) where quote : α → Syntax export Quote (quote) instance : Quote Syntax := ⟨id⟩ instance : Quote Bool := ⟨fun | true => mkCIdent `Bool.true | false => mkCIdent `Bool.false⟩ instance : Quote String := ⟨Syntax.mkStrLit⟩ instance : Quote Nat := ⟨fun n => Syntax.mkNumLit <| toString n⟩ instance : Quote Substring := ⟨fun s => Syntax.mkCApp `String.toSubstring #[quote s.toString]⟩ -- in contrast to `Name.toString`, we can, and want to be, precise here private def getEscapedNameParts? (acc : List String) : Name → OptionM (List String) | Name.anonymous => acc | Name.str n s _ => do let s ← Name.escapePart s getEscapedNameParts? (s::acc) n | Name.num n i _ => none private def quoteNameMk : Name → Syntax | Name.anonymous => mkCIdent ``Name.anonymous | Name.str n s _ => Syntax.mkCApp ``Name.mkStr #[quoteNameMk n, quote s] | Name.num n i _ => Syntax.mkCApp ``Name.mkNum #[quoteNameMk n, quote i] instance : Quote Name where quote n := match getEscapedNameParts? [] n with | some ss => mkNode `Lean.Parser.Term.quotedName #[Syntax.mkNameLit ("`" ++ ".".intercalate ss)] | none => quoteNameMk n instance {α β : Type} [Quote α] [Quote β] : Quote (α × β) where quote | ⟨a, b⟩ => Syntax.mkCApp ``Prod.mk #[quote a, quote b] private def quoteList {α : Type} [Quote α] : List α → Syntax | [] => mkCIdent ``List.nil | (x::xs) => Syntax.mkCApp ``List.cons #[quote x, quoteList xs] instance {α : Type} [Quote α] : Quote (List α) where quote := quoteList instance {α : Type} [Quote α] : Quote (Array α) where quote xs := Syntax.mkCApp ``List.toArray #[quote xs.toList] private def quoteOption {α : Type} [Quote α] : Option α → Syntax | none => mkIdent ``none | (some x) => Syntax.mkCApp ``some #[quote x] instance Option.hasQuote {α : Type} [Quote α] : Quote (Option α) where quote := quoteOption /- Evaluator for `prec` DSL -/ def evalPrec (stx : Syntax) : MacroM Nat := Macro.withIncRecDepth stx do let stx ← expandMacros stx match stx with | `(prec| $num:numLit) => return num.isNatLit?.getD 0 | _ => Macro.throwErrorAt stx "unexpected precedence" macro_rules | `(prec| $a + $b) => do `(prec| $(quote <| (← evalPrec a) + (← evalPrec b)):numLit) macro_rules | `(prec| $a - $b) => do `(prec| $(quote <| (← evalPrec a) - (← evalPrec b)):numLit) macro "eval_prec " p:prec:max : term => return quote (← evalPrec p) /- Evaluator for `prio` DSL -/ def evalPrio (stx : Syntax) : MacroM Nat := Macro.withIncRecDepth stx do let stx ← expandMacros stx match stx with | `(prio| $num:numLit) => return num.isNatLit?.getD 0 | _ => Macro.throwErrorAt stx "unexpected priority" macro_rules | `(prio| $a + $b) => do `(prio| $(quote <| (← evalPrio a) + (← evalPrio b)):numLit) macro_rules | `(prio| $a - $b) => do `(prio| $(quote <| (← evalPrio a) - (← evalPrio b)):numLit) macro "eval_prio " p:prio:max : term => return quote (← evalPrio p) def evalOptPrio : Option Syntax → MacroM Nat | some prio => evalPrio prio | none => return eval_prio default end Lean namespace Array abbrev getSepElems := @getEvenElems open Lean private partial def filterSepElemsMAux {m : Type → Type} [Monad m] (a : Array Syntax) (p : Syntax → m Bool) (i : Nat) (acc : Array Syntax) : m (Array Syntax) := do if h : i < a.size then let stx := a.get ⟨i, h⟩ if (← p stx) then if acc.isEmpty then filterSepElemsMAux a p (i+2) (acc.push stx) else if hz : i ≠ 0 then have : i.pred < i := Nat.pred_lt hz let sepStx := a.get ⟨i.pred, Nat.lt_trans this h⟩ filterSepElemsMAux a p (i+2) ((acc.push sepStx).push stx) else filterSepElemsMAux a p (i+2) (acc.push stx) else filterSepElemsMAux a p (i+2) acc else pure acc def filterSepElemsM {m : Type → Type} [Monad m] (a : Array Syntax) (p : Syntax → m Bool) : m (Array Syntax) := filterSepElemsMAux a p 0 #[] def filterSepElems (a : Array Syntax) (p : Syntax → Bool) : Array Syntax := Id.run <| a.filterSepElemsM p private partial def mapSepElemsMAux {m : Type → Type} [Monad m] (a : Array Syntax) (f : Syntax → m Syntax) (i : Nat) (acc : Array Syntax) : m (Array Syntax) := do if h : i < a.size then let stx := a.get ⟨i, h⟩ if i % 2 == 0 then do let stx ← f stx mapSepElemsMAux a f (i+1) (acc.push stx) else mapSepElemsMAux a f (i+1) (acc.push stx) else pure acc def mapSepElemsM {m : Type → Type} [Monad m] (a : Array Syntax) (f : Syntax → m Syntax) : m (Array Syntax) := mapSepElemsMAux a f 0 #[] def mapSepElems (a : Array Syntax) (f : Syntax → Syntax) : Array Syntax := Id.run <| a.mapSepElemsM f end Array namespace Lean.Syntax.SepArray def getElems {sep} (sa : SepArray sep) : Array Syntax := sa.elemsAndSeps.getSepElems /- We use `CoeTail` here instead of `Coe` to avoid a "loop" when computing `CoeTC`. The "loop" is interrupted using the maximum instance size threshold, but it is a performance bottleneck. The loop occurs because the predicate `isNewAnswer` is too imprecise. -/ instance (sep) : CoeTail (SepArray sep) (Array Syntax) where coe := getElems end Lean.Syntax.SepArray /-- Gadget for automatic parameter support. This is similar to the `optParam` gadget, but it uses the given tactic. Like `optParam`, this gadget only affects elaboration. For example, the tactic will *not* be invoked during type class resolution. -/ abbrev autoParam.{u} (α : Sort u) (tactic : Lean.Syntax) : Sort u := α /- Helper functions for manipulating interpolated strings -/ namespace Lean.Syntax private def decodeInterpStrQuotedChar (s : String) (i : String.Pos) : Option (Char × String.Pos) := OptionM.run do match decodeQuotedChar s i with | some r => some r | none => let c := s.get i let i := s.next i if c == '{' then pure ('{', i) else none private partial def decodeInterpStrLit (s : String) : Option String := let rec loop (i : String.Pos) (acc : String) : OptionM String := let c := s.get i let i := s.next i if c == '\"' || c == '{' then pure acc else if s.atEnd i then none else if c == '\\' then do let (c, i) ← decodeInterpStrQuotedChar s i loop i (acc.push c) else loop i (acc.push c) loop 1 "" partial def isInterpolatedStrLit? (stx : Syntax) : Option String := match isLit? interpolatedStrLitKind stx with | none => none | some val => decodeInterpStrLit val def expandInterpolatedStrChunks (chunks : Array Syntax) (mkAppend : Syntax → Syntax → MacroM Syntax) (mkElem : Syntax → MacroM Syntax) : MacroM Syntax := do let mut i := 0 let mut result := Syntax.missing for elem in chunks do let elem ← match elem.isInterpolatedStrLit? with | none => mkElem elem | some str => mkElem (Syntax.mkStrLit str) if i == 0 then result := elem else result ← mkAppend result elem i := i+1 return result def expandInterpolatedStr (interpStr : Syntax) (type : Syntax) (toTypeFn : Syntax) : MacroM Syntax := do let ref := interpStr let r ← expandInterpolatedStrChunks interpStr.getArgs (fun a b => `($a ++ $b)) (fun a => `($toTypeFn $a)) `(($r : $type)) def getSepArgs (stx : Syntax) : Array Syntax := stx.getArgs.getSepElems end Syntax namespace Meta inductive TransparencyMode where | all | default | reducible | instances deriving Inhabited, BEq, Repr namespace Simp def defaultMaxSteps := 100000 structure Config where maxSteps : Nat := defaultMaxSteps maxDischargeDepth : Nat := 2 contextual : Bool := false memoize : Bool := true singlePass : Bool := false zeta : Bool := true beta : Bool := true eta : Bool := true etaStruct : Bool := true iota : Bool := true proj : Bool := true decide : Bool := true deriving Inhabited, BEq, Repr -- Configuration object for `simp_all` structure ConfigCtx extends Config where contextual := true end Simp namespace Rewrite structure Config where transparency : TransparencyMode := TransparencyMode.reducible offsetCnstrs : Bool := true end Rewrite end Meta namespace Parser.Tactic macro "erw " s:rwRuleSeq loc:(location)? : tactic => `(rw (config := { transparency := Lean.Meta.TransparencyMode.default }) $s:rwRuleSeq $[$(loc.getOptional?):location]?) end Parser.Tactic end Lean
a12a2804eb43a6da263ce3a5713f28c49021e80b
f5f7e6fae601a5fe3cac7cc3ed353ed781d62419
/src/algebra/char_p.lean
f5c20337acf2478a4de90a43da1d48bf03af63c0
[ "Apache-2.0" ]
permissive
EdAyers/mathlib
9ecfb2f14bd6caad748b64c9c131befbff0fb4e0
ca5d4c1f16f9c451cf7170b10105d0051db79e1b
refs/heads/master
1,626,189,395,845
1,555,284,396,000
1,555,284,396,000
144,004,030
0
0
Apache-2.0
1,533,727,664,000
1,533,727,663,000
null
UTF-8
Lean
false
false
8,716
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Kenny Lau, Joey van Langen, Casper Putz Characteristic of semirings. -/ import data.padics.padic_norm data.nat.choose data.fintype data.set import data.zmod.basic algebra.module universes u v /-- The generator of the kernel of the unique homomorphism ℤ → α for a semiring α -/ class char_p (α : Type u) [semiring α] (p : ℕ) : Prop := (cast_eq_zero_iff : ∀ x:ℕ, (x:α) = 0 ↔ p ∣ x) theorem char_p.cast_eq_zero (α : Type u) [semiring α] (p : ℕ) [char_p α p] : (p:α) = 0 := (char_p.cast_eq_zero_iff α p p).2 (dvd_refl p) theorem char_p.eq (α : Type u) [semiring α] {p q : ℕ} (c1 : char_p α p) (c2 : char_p α q) : p = q := nat.dvd_antisymm ((char_p.cast_eq_zero_iff α p q).1 (char_p.cast_eq_zero _ _)) ((char_p.cast_eq_zero_iff α q p).1 (char_p.cast_eq_zero _ _)) instance char_p.of_char_zero (α : Type u) [semiring α] [char_zero α] : char_p α 0 := ⟨λ x, by rw [zero_dvd_iff, ← nat.cast_zero, nat.cast_inj]⟩ theorem char_p.exists (α : Type u) [semiring α] : ∃ p, char_p α p := by letI := classical.dec_eq α; exact classical.by_cases (assume H : ∀ p:ℕ, (p:α) = 0 → p = 0, ⟨0, ⟨λ x, by rw [zero_dvd_iff]; exact ⟨H x, by rintro rfl; refl⟩⟩⟩) (λ H, ⟨nat.find (classical.not_forall.1 H), ⟨λ x, ⟨λ H1, nat.dvd_of_mod_eq_zero (by_contradiction $ λ H2, nat.find_min (classical.not_forall.1 H) (nat.mod_lt x $ nat.pos_of_ne_zero $ not_of_not_imp $ nat.find_spec (classical.not_forall.1 H)) (not_imp_of_and_not ⟨by rwa [← nat.mod_add_div x (nat.find (classical.not_forall.1 H)), nat.cast_add, nat.cast_mul, of_not_not (not_not_of_not_imp $ nat.find_spec (classical.not_forall.1 H)), zero_mul, add_zero] at H1, H2⟩)), λ H1, by rw [← nat.mul_div_cancel' H1, nat.cast_mul, of_not_not (not_not_of_not_imp $ nat.find_spec (classical.not_forall.1 H)), zero_mul]⟩⟩⟩) theorem char_p.exists_unique (α : Type u) [semiring α] : ∃! p, char_p α p := let ⟨c, H⟩ := char_p.exists α in ⟨c, H, λ y H2, char_p.eq α H2 H⟩ /-- Noncomuptable function that outputs the unique characteristic of a semiring. -/ noncomputable def ring_char (α : Type u) [semiring α] : ℕ := classical.some (char_p.exists_unique α) theorem ring_char.spec (α : Type u) [semiring α] : ∀ x:ℕ, (x:α) = 0 ↔ ring_char α ∣ x := by letI := (classical.some_spec (char_p.exists_unique α)).1; unfold ring_char; exact char_p.cast_eq_zero_iff α (ring_char α) theorem ring_char.eq (α : Type u) [semiring α] {p : ℕ} (C : char_p α p) : p = ring_char α := (classical.some_spec (char_p.exists_unique α)).2 p C theorem add_pow_char (α : Type u) [comm_ring α] {p : ℕ} (hp : nat.prime p) [char_p α p] (x y : α) : (x + y)^p = x^p + y^p := begin rw [add_pow, finset.sum_range_succ, nat.sub_self, pow_zero, choose_self], rw [nat.cast_one, mul_one, mul_one, add_left_inj], transitivity, { refine finset.sum_eq_single 0 _ _, { intros b h1 h2, have := nat.prime.dvd_choose (nat.pos_of_ne_zero h2) (finset.mem_range.1 h1) hp, rw [← nat.div_mul_cancel this, nat.cast_mul, char_p.cast_eq_zero α p], simp only [mul_zero] }, { intro H, exfalso, apply H, exact finset.mem_range.2 hp.pos } }, rw [pow_zero, nat.sub_zero, one_mul, choose_zero_right, nat.cast_one, mul_one] end /-- The frobenius map that sends x to x^p -/ def frobenius (α : Type u) [monoid α] (p : ℕ) (x : α) : α := x^p theorem frobenius_def (α : Type u) [monoid α] (p : ℕ) (x : α) : frobenius α p x = x ^ p := rfl theorem frobenius_mul (α : Type u) [comm_monoid α] (p : ℕ) (x y : α) : frobenius α p (x * y) = frobenius α p x * frobenius α p y := mul_pow x y p theorem frobenius_one (α : Type u) [monoid α] (p : ℕ) : frobenius α p 1 = 1 := one_pow _ theorem is_monoid_hom.map_frobenius {α : Type u} {β : Type v} [monoid α] [monoid β] (f : α → β) [is_monoid_hom f] (p : ℕ) (x : α) : f (frobenius α p x) = frobenius β p (f x) := by unfold frobenius; induction p; simp only [pow_zero, pow_succ, is_monoid_hom.map_one f, is_monoid_hom.map_mul f, *] instance {α : Type u} [comm_ring α] (p : ℕ) [hp : nat.prime p] [char_p α p] : is_ring_hom (frobenius α p) := { map_one := frobenius_one α p, map_mul := frobenius_mul α p, map_add := add_pow_char α hp } section variables (α : Type u) [comm_ring α] (p : ℕ) [hp : nat.prime p] theorem frobenius_zero : frobenius α p 0 = 0 := zero_pow hp.pos variables [char_p α p] (x y : α) include hp theorem frobenius_add : frobenius α p (x + y) = frobenius α p x + frobenius α p y := is_ring_hom.map_add _ theorem frobenius_neg : frobenius α p (-x) = -frobenius α p x := is_ring_hom.map_neg _ theorem frobenius_sub : frobenius α p (x - y) = frobenius α p x - frobenius α p y := is_ring_hom.map_sub _ end theorem frobenius_inj (α : Type u) [integral_domain α] (p : ℕ) [nat.prime p] [char_p α p] (x y : α) (H : frobenius α p x = frobenius α p y) : x = y := by rw ← sub_eq_zero at H ⊢; rw ← frobenius_sub at H; exact pow_eq_zero H theorem frobenius_nat_cast (α : Type u) [comm_ring α] (p : ℕ) [nat.prime p] [char_p α p] (x : ℕ) : frobenius α p x = x := by induction x; simp only [nat.cast_zero, nat.cast_succ, frobenius_zero, frobenius_one, frobenius_add, *] namespace char_p section variables (α : Type u) [ring α] lemma char_p_to_char_zero [char_p α 0] : char_zero α := add_group.char_zero_of_inj_zero $ λ n h0, eq_zero_of_zero_dvd ((cast_eq_zero_iff α 0 n).mp h0) lemma cast_eq_mod (p : ℕ) [char_p α p] (k : ℕ) : (k : α) = (k % p : ℕ) := calc (k : α) = ↑(k % p + p * (k / p)) : by rw [nat.mod_add_div] ... = ↑(k % p) : by simp[cast_eq_zero] theorem char_ne_zero_of_fintype (p : ℕ) [hc : char_p α p] [fintype α] [decidable_eq α] : p ≠ 0 := assume h : p = 0, have char_zero α := @char_p_to_char_zero α _ (h ▸ hc), absurd (@nat.cast_injective α _ _ this) (@set.not_injective_nat_fintype α _ _ _) end section integral_domain open nat variables (α : Type u) [integral_domain α] theorem char_ne_one (p : ℕ) [hc : char_p α p] : p ≠ 1 := assume hp : p = 1, have ( 1 : α) = 0, by simpa using (cast_eq_zero_iff α p 1).mpr (hp ▸ dvd_refl p), absurd this one_ne_zero theorem char_is_prime_of_ge_two (p : ℕ) [hc : char_p α p] (hp : p ≥ 2) : nat.prime p := suffices ∀d ∣ p, d = 1 ∨ d = p, from ⟨hp, this⟩, assume (d : ℕ) (hdvd : ∃ e, p = d * e), let ⟨e, hmul⟩ := hdvd in have (p : α) = 0, from (cast_eq_zero_iff α p p).mpr (dvd_refl p), have (d : α) * e = 0, from (@cast_mul α _ d e) ▸ (hmul ▸ this), or.elim (no_zero_divisors.eq_zero_or_eq_zero_of_mul_eq_zero (d : α) e this) (assume hd : (d : α) = 0, have p ∣ d, from (cast_eq_zero_iff α p d).mp hd, show d = 1 ∨ d = p, from or.inr (dvd_antisymm ⟨e, hmul⟩ this)) (assume he : (e : α) = 0, have p ∣ e, from (cast_eq_zero_iff α p e).mp he, have e ∣ p, from dvd_of_mul_left_eq d (eq.symm hmul), have e = p, from dvd_antisymm ‹e ∣ p› ‹p ∣ e›, have h₀ : p > 0, from gt_of_ge_of_gt hp (nat.zero_lt_succ 1), have d * p = 1 * p, by rw ‹e = p› at hmul; rw [one_mul]; exact eq.symm hmul, show d = 1 ∨ d = p, from or.inl (eq_of_mul_eq_mul_right h₀ this)) theorem char_is_prime_or_zero (p : ℕ) [hc : char_p α p] : nat.prime p ∨ p = 0 := match p, hc with | 0, _ := or.inr rfl | 1, hc := absurd (eq.refl (1 : ℕ)) (@char_ne_one α _ (1 : ℕ) hc) | (m+2), hc := or.inl (@char_is_prime_of_ge_two α _ (m+2) hc (nat.le_add_left 2 m)) end theorem char_is_prime [fintype α] [decidable_eq α] (p : ℕ) [char_p α p] : nat.prime p := or.resolve_right (char_is_prime_or_zero α p) (char_ne_zero_of_fintype α p) end integral_domain end char_p namespace zmod variables {α : Type u} [ring α] {n : ℕ+} instance cast_is_ring_hom [char_p α n] : is_ring_hom (cast : zmod n → α) := { map_one := by rw ←@nat.cast_one α _ _; exact eq.symm (char_p.cast_eq_mod α n 1), map_mul := assume x y : zmod n, show ↑((x * y).val) = ↑(x.val) * ↑(y.val), by rw [zmod.mul_val, ←char_p.cast_eq_mod, nat.cast_mul], map_add := assume x y : zmod n, show ↑((x + y).val) = ↑(x.val) + ↑(y.val), by rw [zmod.add_val, ←char_p.cast_eq_mod, nat.cast_add] } instance to_module [char_p α n] : module (zmod n) α := is_ring_hom.to_module cast instance to_module' {m : ℕ} {hm : m > 0} [hc : char_p α m] : module (zmod ⟨m, hm⟩) α := @zmod.to_module α _ ⟨m, hm⟩ hc end zmod
eb0553a3d9839479e3721d1bc44d064be8b0d456
2eab05920d6eeb06665e1a6df77b3157354316ad
/src/tactic/suggest.lean
4ac72a6d1b73d2714be6297895c9266d4f741d6a
[ "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
21,933
lean
/- Copyright (c) 2019 Lucas Allen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Lucas Allen, Scott Morrison -/ import data.mllist import tactic.solve_by_elim /-! # `suggest` and `library_search` `suggest` and `library_search` are a pair of tactics for applying lemmas from the library to the current goal. * `suggest` prints a list of `exact ...` or `refine ...` statements, which may produce new goals * `library_search` prints a single `exact ...` which closes the goal, or fails -/ namespace tactic open native namespace suggest open solve_by_elim /-- Map a name (typically a head symbol) to a "canonical" definitional synonym. Given a name `n`, we want a name `n'` such that a sufficiently applied expression with head symbol `n` is always definitionally equal to an expression with head symbol `n'`. Thus, we can search through all lemmas with a result type of `n'` to solve a goal with head symbol `n`. For example, `>` is mapped to `<` because `a > b` is definitionally equal to `b < a`, and `not` is mapped to `false` because `¬ a` is definitionally equal to `p → false` The default is that the original argument is returned, so `<` is just mapped to `<`. `normalize_synonym` is called for every lemma in the library, so it needs to be fast. -/ -- TODO this is a hack; if you suspect more cases here would help, please report them meta def normalize_synonym : name → name | `gt := `has_lt.lt | `ge := `has_le.le | `monotone := `has_le.le | `not := `false | n := n /-- Compute the head symbol of an expression, then normalise synonyms. This is only used when analysing the goal, so it is okay to do more expensive analysis here. -/ -- We may want to tweak this further? meta def allowed_head_symbols : expr → list name -- We first have a various "customisations": -- Because in `ℕ` `a.succ ≤ b` is definitionally `a < b`, -- we add some special cases to allow looking for `<` lemmas even when the goal has a `≤`. -- Note we only do this in the `ℕ` case, for performance. | `(@has_le.le ℕ _ (nat.succ _) _) := [`has_le.le, `has_lt.lt] | `(@ge ℕ _ _ (nat.succ _)) := [`has_le.le, `has_lt.lt] | `(@has_le.le ℕ _ 1 _) := [`has_le.le, `has_lt.lt] | `(@ge ℕ _ _ 1) := [`has_le.le, `has_lt.lt] -- And then the generic cases: | (expr.pi _ _ _ t) := allowed_head_symbols t | (expr.app f _) := allowed_head_symbols f | (expr.const n _) := [normalize_synonym n] | _ := [`_] . /-- A declaration can match the head symbol of the current goal in four possible ways: * `ex` : an exact match * `mp` : the declaration returns an `iff`, and the right hand side matches the goal * `mpr` : the declaration returns an `iff`, and the left hand side matches the goal * `both`: the declaration returns an `iff`, and the both sides match the goal -/ @[derive decidable_eq, derive inhabited] inductive head_symbol_match | ex | mp | mpr | both open head_symbol_match /-- a textual representation of a `head_symbol_match`, for trace debugging. -/ def head_symbol_match.to_string : head_symbol_match → string | ex := "exact" | mp := "iff.mp" | mpr := "iff.mpr" | both := "iff.mp and iff.mpr" /-- Determine if, and in which way, a given expression matches the specified head symbol. -/ meta def match_head_symbol (hs : name_set) : expr → option head_symbol_match | (expr.pi _ _ _ t) := match_head_symbol t | `(%%a ↔ %%b) := if hs.contains `iff then some ex else match (match_head_symbol a, match_head_symbol b) with | (some ex, some ex) := some both | (some ex, _) := some mpr | (_, some ex) := some mp | _ := none end | (expr.app f _) := match_head_symbol f | (expr.const n _) := if hs.contains (normalize_synonym n) then some ex else none | _ := if hs.contains `_ then some ex else none /-- A package of `declaration` metadata, including the way in which its type matches the head symbol which we are searching for. -/ meta structure decl_data := (d : declaration) (n : name) (m : head_symbol_match) (l : ℕ) -- cached length of name /-- Generate a `decl_data` from the given declaration if it matches the head symbol `hs` for the current goal. -/ -- We used to check here for private declarations, or declarations with certain suffixes. -- It turns out `apply` is so fast, it's better to just try them all. meta def process_declaration (hs : name_set) (d : declaration) : option decl_data := let n := d.to_name in if !d.is_trusted || n.is_internal then none else (λ m, ⟨d, n, m, n.length⟩) <$> match_head_symbol hs d.type /-- Retrieve all library definitions with a given head symbol. -/ meta def library_defs (hs : name_set) : tactic (list decl_data) := do trace_if_enabled `suggest format!"Looking for lemmas with head symbols {hs}.", env ← get_env, let defs := env.decl_filter_map (process_declaration hs), -- Sort by length; people like short proofs let defs := defs.qsort(λ d₁ d₂, d₁.l ≤ d₂.l), trace_if_enabled `suggest format!"Found {defs.length} relevant lemmas:", trace_if_enabled `suggest $ defs.map (λ ⟨d, n, m, l⟩, (n, m.to_string)), return defs /-- We unpack any element of a list of `decl_data` corresponding to an `↔` statement that could apply in both directions into two separate elements. This ensures that both directions can be independently returned by `suggest`, and avoids a problem where the application of one direction prevents the application of the other direction. (See `exp_le_exp` in the tests.) -/ meta def unpack_iff_both : list decl_data → list decl_data | [] := [] | (⟨d, n, both, l⟩ :: L) := ⟨d, n, mp, l⟩ :: ⟨d, n, mpr, l⟩ :: unpack_iff_both L | (⟨d, n, m, l⟩ :: L) := ⟨d, n, m, l⟩ :: unpack_iff_both L /-- An extension to the option structure for `solve_by_elim`, to specify a list of local hypotheses which must appear in any solution. These are useful for constraining the results from `library_search` and `suggest`. -/ meta structure suggest_opt extends opt := (compulsory_hyps : list expr := []) /-- Convert a `suggest_opt` structure to a `opt` structure suitable for `solve_by_elim`, by setting the `accept` parameter to require that all complete solutions use everything in `compulsory_hyps`. -/ meta def suggest_opt.mk_accept (o : suggest_opt) : opt := { accept := λ gs, o.accept gs >> (guard $ o.compulsory_hyps.all (λ h, gs.any (λ g, g.contains_expr_or_mvar h))), ..o } /-- Apply the lemma `e`, then attempt to close all goals using `solve_by_elim opt`, failing if `close_goals = tt` and there are any goals remaining. Returns the number of subgoals which were closed using `solve_by_elim`. -/ -- Implementation note: as this is used by both `library_search` and `suggest`, -- we first run `solve_by_elim` separately on the independent goals, -- whether or not `close_goals` is set, -- and then run `solve_by_elim { all_goals := tt }`, -- requiring that it succeeds if `close_goals = tt`. meta def apply_and_solve (close_goals : bool) (opt : suggest_opt := { }) (e : expr) : tactic ℕ := do trace_if_enabled `suggest format!"Trying to apply lemma: {e}", apply e opt.to_apply_cfg, trace_if_enabled `suggest format!"Applied lemma: {e}", ng ← num_goals, -- Phase 1 -- Run `solve_by_elim` on each "safe" goal separately, not worrying about failures. -- (We only attempt the "safe" goals in this way in Phase 1. -- In Phase 2 we will do backtracking search across all goals, -- allowing us to guess solutions that involve data or unify metavariables, -- but only as long as we can finish all goals.) -- If `compulsory_hyps` is non-empty, we skip this phase and defer to phase 2. try (guard (opt.compulsory_hyps = []) >> any_goals (independent_goal >> solve_by_elim opt.to_opt)), -- Phase 2 (done >> return ng) <|> (do -- If there were any goals that we did not attempt solving in the first phase -- (because they weren't propositional, or contained a metavariable) -- as a second phase we attempt to solve all remaining goals at once -- (with backtracking across goals). ((guard (opt.compulsory_hyps ≠ []) <|> any_goals (success_if_fail independent_goal) >> skip) >> solve_by_elim { backtrack_all_goals := tt, ..opt.mk_accept }) <|> -- and fail unless `close_goals = ff` guard ¬ close_goals, ng' ← num_goals, return (ng - ng')) /-- Apply the declaration `d` (or the forward and backward implications separately, if it is an `iff`), and then attempt to solve the subgoal using `apply_and_solve`. Returns the number of subgoals successfully closed. -/ meta def apply_declaration (close_goals : bool) (opt : suggest_opt := { }) (d : decl_data) : tactic ℕ := let tac := apply_and_solve close_goals opt in do (e, t) ← decl_mk_const d.d, match d.m with | ex := tac e | mp := do l ← iff_mp_core e t, tac l | mpr := do l ← iff_mpr_core e t, tac l | both := undefined -- we use `unpack_iff_both` to ensure this isn't reachable end /-- An `application` records the result of a successful application of a library lemma. -/ meta structure application := (state : tactic_state) (script : string) (decl : option declaration) (num_goals : ℕ) (hyps_used : list expr) end suggest open solve_by_elim open suggest declare_trace suggest -- Trace a list of all relevant lemmas -- Call `apply_declaration`, then prepare the tactic script and -- count the number of local hypotheses used. private meta def apply_declaration_script (g : expr) (hyps : list expr) (opt : suggest_opt := { }) (d : decl_data) : tactic application := -- (This tactic block is only executed when we evaluate the mllist, -- so we need to do the `focus1` here.) retrieve $ focus1 $ do apply_declaration ff opt d, -- This `instantiate_mvars` is necessary so that we count used hypotheses correctly. g ← instantiate_mvars g, guard $ (opt.compulsory_hyps.all (λ h, h.occurs g)), ng ← num_goals, s ← read, m ← tactic_statement g, return { application . state := s, decl := d.d, script := m, num_goals := ng, hyps_used := hyps.filter (λ h, h.occurs g) } -- implementation note: we produce a `tactic (mllist tactic application)` first, -- because it's easier to work in the tactic monad, but in a moment we squash this -- down to an `mllist tactic application`. private meta def suggest_core' (opt : suggest_opt := { }) : tactic (mllist tactic application) := do g :: _ ← get_goals, hyps ← local_context, -- Check if `solve_by_elim` can solve the goal immediately: (retrieve (do focus1 $ solve_by_elim opt.mk_accept, s ← read, m ← tactic_statement g, -- This `instantiate_mvars` is necessary so that we count used hypotheses correctly. g ← instantiate_mvars g, guard (opt.compulsory_hyps.all (λ h, h.occurs g)), return $ mllist.of_list [⟨s, m, none, 0, hyps.filter (λ h, h.occurs g)⟩])) <|> -- Otherwise, let's actually try applying library lemmas. (do -- Collect all definitions with the correct head symbol t ← infer_type g, defs ← unpack_iff_both <$> library_defs (name_set.of_list $ allowed_head_symbols t), let defs : mllist tactic _ := mllist.of_list defs, -- Try applying each lemma against the goal, -- recording the tactic script as a string, -- the number of remaining goals, -- and number of local hypotheses used. let results := defs.mfilter_map (apply_declaration_script g hyps opt), -- Now call `symmetry` and try again. -- (Because we are using `mllist`, this is essentially free if we've already found a lemma.) symm_state ← retrieve $ try_core $ symmetry >> read, let results_symm := match symm_state with | (some s) := defs.mfilter_map (λ d, retrieve $ set_state s >> apply_declaration_script g hyps opt d) | none := mllist.nil end, return (results.append results_symm)) /-- The core `suggest` tactic. It attempts to apply a declaration from the library, then solve new goals using `solve_by_elim`. It returns a list of `application`s consisting of fields: * `state`, a tactic state resulting from the successful application of a declaration from the library, * `script`, a string of the form `Try this: refine ...` or `Try this: exact ...` which will reproduce that tactic state, * `decl`, an `option declaration` indicating the declaration that was applied (or none, if `solve_by_elim` succeeded), * `num_goals`, the number of remaining goals, and * `hyps_used`, the number of local hypotheses used in the solution. -/ meta def suggest_core (opt : suggest_opt := { }) : mllist tactic application := (mllist.monad_lift (suggest_core' opt)).join /-- See `suggest_core`. Returns a list of at most `limit` `application`s, sorted by number of goals, and then (reverse) number of hypotheses used. -/ meta def suggest (limit : option ℕ := none) (opt : suggest_opt := { }) : tactic (list application) := do let results := suggest_core opt, -- Get the first n elements of the successful lemmas L ← if h : limit.is_some then results.take (option.get h) else results.force, -- Sort by number of remaining goals, then by number of hypotheses used. return $ L.qsort (λ d₁ d₂, d₁.num_goals < d₂.num_goals ∨ (d₁.num_goals = d₂.num_goals ∧ d₁.hyps_used.length ≥ d₂.hyps_used.length)) /-- Returns a list of at most `limit` strings, of the form `Try this: exact ...` or `Try this: refine ...`, which make progress on the current goal using a declaration from the library. -/ meta def suggest_scripts (limit : option ℕ := none) (opt : suggest_opt := { }) : tactic (list string) := do L ← suggest limit opt, return $ L.map application.script /-- Returns a string of the form `Try this: exact ...`, which closes the current goal. -/ meta def library_search (opt : suggest_opt := { }) : tactic string := (suggest_core opt).mfirst (λ a, do guard (a.num_goals = 0), write a.state, return a.script) namespace interactive setup_tactic_parser open solve_by_elim declare_trace silence_suggest -- Turn off `Try this: exact/refine ...` trace messages for `suggest` /-- `suggest` tries to apply suitable theorems/defs from the library, and generates a list of `exact ...` or `refine ...` scripts that could be used at this step. It leaves the tactic state unchanged. It is intended as a complement of the search function in your editor, the `#find` tactic, and `library_search`. `suggest` takes an optional natural number `num` as input and returns the first `num` (or less, if all possibilities are exhausted) possibilities ordered by length of lemma names. The default for `num` is `50`. For performance reasons `suggest` uses monadic lazy lists (`mllist`). This means that `suggest` might miss some results if `num` is not large enough. However, because `suggest` uses monadic lazy lists, smaller values of `num` run faster than larger values. You can add additional lemmas to be used along with local hypotheses after the application of a library lemma, using the same syntax as for `solve_by_elim`, e.g. ``` example {a b c d: nat} (h₁ : a < c) (h₂ : b < d) : max (c + d) (a + b) = (c + d) := begin suggest [add_lt_add], -- Says: `Try this: exact max_eq_left_of_lt (add_lt_add h₁ h₂)` end ``` You can also use `suggest with attr` to include all lemmas with the attribute `attr`. -/ meta def suggest (n : parse (with_desc "n" small_nat)?) (hs : parse simp_arg_list) (attr_names : parse with_ident_list) (use : parse $ (tk "using" *> many ident_) <|> return []) (opt : opt := { }) : tactic unit := do (lemma_thunks, ctx_thunk) ← mk_assumption_set ff hs attr_names, use ← use.mmap get_local, L ← tactic.suggest_scripts (n.get_or_else 50) { compulsory_hyps := use, lemma_thunks := some lemma_thunks, ctx_thunk := ctx_thunk, ..opt }, if is_trace_enabled_for `silence_suggest then skip else if L.length = 0 then fail "There are no applicable declarations" else L.mmap trace >> skip /-- `suggest` lists possible usages of the `refine` tactic and leaves the tactic state unchanged. It is intended as a complement of the search function in your editor, the `#find` tactic, and `library_search`. `suggest` takes an optional natural number `num` as input and returns the first `num` (or less, if all possibilities are exhausted) possibilities ordered by length of lemma names. The default for `num` is `50`. `suggest using h₁ h₂` will only show solutions that make use of the local hypotheses `h₁` and `h₂`. For performance reasons `suggest` uses monadic lazy lists (`mllist`). This means that `suggest` might miss some results if `num` is not large enough. However, because `suggest` uses monadic lazy lists, smaller values of `num` run faster than larger values. An example of `suggest` in action, ```lean example (n : nat) : n < n + 1 := begin suggest, sorry end ``` prints the list, ```lean Try this: exact nat.lt.base n Try this: exact nat.lt_succ_self n Try this: refine not_le.mp _ Try this: refine gt_iff_lt.mp _ Try this: refine nat.lt.step _ Try this: refine lt_of_not_ge _ ... ``` -/ add_tactic_doc { name := "suggest", category := doc_category.tactic, decl_names := [`tactic.interactive.suggest], tags := ["search", "Try this"] } -- Turn off `Try this: exact ...` trace message for `library_search` declare_trace silence_library_search /-- `library_search` is a tactic to identify existing lemmas in the library. It tries to close the current goal by applying a lemma from the library, then discharging any new goals using `solve_by_elim`. If it succeeds, it prints a trace message `exact ...` which can replace the invocation of `library_search`. Typical usage is: ```lean example (n m k : ℕ) : n * (m - k) = n * m - n * k := by library_search -- Try this: exact mul_tsub n m k ``` `library_search using h₁ h₂` will only show solutions that make use of the local hypotheses `h₁` and `h₂`. By default `library_search` only unfolds `reducible` definitions when attempting to match lemmas against the goal. Previously, it would unfold most definitions, sometimes giving surprising answers, or slow answers. The old behaviour is still available via `library_search!`. You can add additional lemmas to be used along with local hypotheses after the application of a library lemma, using the same syntax as for `solve_by_elim`, e.g. ``` example {a b c d: nat} (h₁ : a < c) (h₂ : b < d) : max (c + d) (a + b) = (c + d) := begin library_search [add_lt_add], -- Says: `Try this: exact max_eq_left_of_lt (add_lt_add h₁ h₂)` end ``` You can also use `library_search with attr` to include all lemmas with the attribute `attr`. -/ meta def library_search (semireducible : parse $ optional (tk "!")) (hs : parse simp_arg_list) (attr_names : parse with_ident_list) (use : parse $ (tk "using" *> many ident_) <|> return []) (opt : opt := { }) : tactic unit := do (lemma_thunks, ctx_thunk) ← mk_assumption_set ff hs attr_names, use ← use.mmap get_local, (tactic.library_search { compulsory_hyps := use, backtrack_all_goals := tt, lemma_thunks := some lemma_thunks, ctx_thunk := ctx_thunk, md := if semireducible.is_some then tactic.transparency.semireducible else tactic.transparency.reducible, ..opt } >>= if is_trace_enabled_for `silence_library_search then (λ _, skip) else trace) <|> fail "`library_search` failed. If you aren't sure what to do next, you can also try `library_search!`, `suggest`, or `hint`. Possible reasons why `library_search` failed: * `library_search` will only apply a single lemma from the library, and then try to fill in its hypotheses from local hypotheses. * If you haven't already, try stating the theorem you want in its own lemma. * Sometimes the library has one version of a lemma but not a very similar version obtained by permuting arguments. Try replacing `a + b` with `b + a`, or `a - b < c` with `a < b + c`, to see if maybe the lemma exists but isn't stated quite the way you would like. * Make sure that you have all the side conditions for your theorem to be true. For example you won't find `a - b + b = a` for natural numbers in the library because it's false! Search for `b ≤ a → a - b + b = a` instead. * If a definition you made is in the goal, you won't find any theorems about it in the library. Try unfolding the definition using `unfold my_definition`. * If all else fails, ask on https://leanprover.zulipchat.com/, and maybe we can improve the library and/or `library_search` for next time." add_tactic_doc { name := "library_search", category := doc_category.tactic, decl_names := [`tactic.interactive.library_search], tags := ["search", "Try this"] } end interactive /-- Invoking the hole command `library_search` ("Use `library_search` to complete the goal") calls the tactic `library_search` to produce a proof term with the type of the hole. Running it on ```lean example : 0 < 1 := {!!} ``` produces ```lean example : 0 < 1 := nat.one_pos ``` -/ @[hole_command] meta def library_search_hole_cmd : hole_command := { name := "library_search", descr := "Use `library_search` to complete the goal.", action := λ _, do script ← library_search, -- Is there a better API for dropping the 'Try this: exact ' prefix on this string? return [((script.get_rest "Try this: exact ").get_or_else script, "by library_search")] } add_tactic_doc { name := "library_search", category := doc_category.hole_cmd, decl_names := [`tactic.library_search_hole_cmd], tags := ["search", "Try this"] } end tactic
b56bfd2600ca65446a3296bb5ae3b5eb193f6951
491068d2ad28831e7dade8d6dff871c3e49d9431
/tests/lean/unfoldf.lean
95bd708db2e041e7c4159a9bd43f285b4b408d23
[ "Apache-2.0" ]
permissive
davidmueller13/lean
65a3ed141b4088cd0a268e4de80eb6778b21a0e9
c626e2e3c6f3771e07c32e82ee5b9e030de5b050
refs/heads/master
1,611,278,313,401
1,444,021,177,000
1,444,021,177,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
481
lean
open nat definition id [unfold-full] {A : Type} (a : A) := a definition compose {A B C : Type} (g : B → C) (f : A → B) (a : A) := g (f a) notation g ∘ f := compose g f example (a b : nat) (H : a = b) : id a = b := begin esimp, state, exact H end example (a b : nat) (H : a = b) : (id ∘ id) a = b := begin esimp, state, exact H end attribute compose [unfold-full] example (a b : nat) (H : a = b) : (id ∘ id) a = b := begin esimp, state, exact H end
bc5de9caa3f8a507c11dc65ac8199fca8730b721
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/ring_theory/unique_factorization_domain.lean
22b977fe326ff17c957f4200b1b931516e79ab9b
[ "Apache-2.0" ]
permissive
agjftucker/mathlib
d634cd0d5256b6325e3c55bb7fb2403548371707
87fe50de17b00af533f72a102d0adefe4a2285e8
refs/heads/master
1,625,378,131,941
1,599,166,526,000
1,599,166,526,000
160,748,509
0
0
Apache-2.0
1,544,141,789,000
1,544,141,789,000
null
UTF-8
Lean
false
false
23,114
lean
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Jens Wagemaker Theory of unique factorization domains. @TODO: setup the complete lattice structure on `factor_set`. -/ import algebra.gcd_monoid import ring_theory.integral_domain variables {α : Type*} local infix ` ~ᵤ ` : 50 := associated /-- Unique factorization domains. In a unique factorization domain each element (except zero) is uniquely represented as a multiset of irreducible factors. Uniqueness is only up to associated elements. This is equivalent to defining a unique factorization domain as a domain in which each element (except zero) is non-uniquely represented as a multiset of prime factors. This definition is used. To define a UFD using the traditional definition in terms of multisets of irreducible factors, use the definition `of_unique_irreducible_factorization` -/ class unique_factorization_domain (α : Type*) [integral_domain α] := (factors : α → multiset α) (factors_prod : ∀{a : α}, a ≠ 0 → (factors a).prod ~ᵤ a) (prime_factors : ∀{a : α}, a ≠ 0 → ∀x∈factors a, prime x) namespace unique_factorization_domain variables [integral_domain α] [unique_factorization_domain α] @[elab_as_eliminator] lemma induction_on_prime {P : α → Prop} (a : α) (h₁ : P 0) (h₂ : ∀ x : α, is_unit x → P x) (h₃ : ∀ a p : α, a ≠ 0 → prime p → P a → P (p * a)) : P a := by haveI := classical.dec_eq α; exact if ha0 : a = 0 then ha0.symm ▸ h₁ else @multiset.induction_on _ (λ s : multiset α, ∀ (a : α), a ≠ 0 → s.prod ~ᵤ a → (∀ p ∈ s, prime p) → P a) (factors a) (λ _ _ h _, h₂ _ ((is_unit_iff_of_associated h.symm).2 is_unit_one)) (λ p s ih a ha0 ⟨u, hu⟩ hsp, have ha : a = (p * u) * s.prod, by simp [hu.symm, mul_comm, mul_assoc], have hs0 : s.prod ≠ 0, from λ _ : s.prod = 0, by simp * at *, ha.symm ▸ h₃ _ _ hs0 (prime_of_associated ⟨u, rfl⟩ (hsp p (multiset.mem_cons_self _ _))) (ih _ hs0 (by refl) (λ p hp, hsp p (multiset.mem_cons.2 (or.inr hp))))) _ ha0 (factors_prod ha0) (prime_factors ha0) lemma factors_irreducible {a : α} (ha : irreducible a) : ∃ p, a ~ᵤ p ∧ factors a = p :: 0 := by haveI := classical.dec_eq α; exact multiset.induction_on (factors a) (λ h, (ha.1 (associated_one_iff_is_unit.1 h.symm)).elim) (λ p s _ hp hs, let ⟨u, hu⟩ := hp in ⟨p, have hs0 : s = 0, from classical.by_contradiction (λ hs0, let ⟨q, hq⟩ := multiset.exists_mem_of_ne_zero hs0 in (hs q (by simp [hq])).2.1 $ (ha.2 ((p * u) * (s.erase q).prod) _ (by rw [mul_right_comm _ _ q, mul_assoc, ← multiset.prod_cons, multiset.cons_erase hq]; simp [hu.symm, mul_comm, mul_assoc])).resolve_left $ mt is_unit_of_mul_is_unit_left $ mt is_unit_of_mul_is_unit_left (hs p (multiset.mem_cons_self _ _)).2.1), ⟨associated.symm (by clear _let_match; simp * at *), hs0 ▸ rfl⟩⟩) (factors_prod ha.ne_zero) (prime_factors ha.ne_zero) lemma irreducible_iff_prime {p : α} : irreducible p ↔ prime p := by letI := classical.dec_eq α; exact if hp0 : p = 0 then by simp [hp0] else ⟨λ h, let ⟨q, hq⟩ := factors_irreducible h in have prime q, from hq.2 ▸ prime_factors hp0 _ (by simp [hq.2]), suffices prime (factors p).prod, from prime_of_associated (factors_prod hp0) this, hq.2.symm ▸ by simp [this], irreducible_of_prime⟩ lemma irreducible_factors : ∀{a : α}, a ≠ 0 → ∀x∈factors a, irreducible x := by simp only [irreducible_iff_prime]; exact @prime_factors _ _ _ lemma unique : ∀{f g : multiset α}, (∀x∈f, irreducible x) → (∀x∈g, irreducible x) → f.prod ~ᵤ g.prod → multiset.rel associated f g := by haveI := classical.dec_eq α; exact λ f, multiset.induction_on f (λ g _ hg h, multiset.rel_zero_left.2 $ multiset.eq_zero_of_forall_not_mem (λ x hx, have is_unit g.prod, by simpa [associated_one_iff_is_unit] using h.symm, (hg x hx).1 (is_unit_iff_dvd_one.2 (dvd.trans (multiset.dvd_prod hx) (is_unit_iff_dvd_one.1 this))))) (λ p f ih g hf hg hfg, let ⟨b, hbg, hb⟩ := exists_associated_mem_of_dvd_prod (irreducible_iff_prime.1 (hf p (by simp))) (λ q hq, irreducible_iff_prime.1 (hg _ hq)) $ (dvd_iff_dvd_of_rel_right hfg).1 (show p ∣ (p :: f).prod, by simp) in begin rw ← multiset.cons_erase hbg, exact multiset.rel.cons hb (ih (λ q hq, hf _ (by simp [hq])) (λ q (hq : q ∈ g.erase b), hg q (multiset.mem_of_mem_erase hq)) (associated_mul_left_cancel (by rwa [← multiset.prod_cons, ← multiset.prod_cons, multiset.cons_erase hbg]) hb (hf p (by simp)).ne_zero)) end) end unique_factorization_domain structure unique_irreducible_factorization (α : Type*) [integral_domain α] := (factors : α → multiset α) (factors_prod : ∀{a : α}, a ≠ 0 → (factors a).prod ~ᵤ a) (irreducible_factors : ∀{a : α}, a ≠ 0 → ∀x∈factors a, irreducible x) (unique : ∀{f g : multiset α}, (∀x∈f, irreducible x) → (∀x∈g, irreducible x) → f.prod ~ᵤ g.prod → multiset.rel associated f g) namespace unique_factorization_domain open unique_factorization_domain associated variables [integral_domain α] [unique_factorization_domain α] lemma exists_mem_factors_of_dvd {a p : α} (ha0 : a ≠ 0) (hp : irreducible p) : p ∣ a → ∃ q ∈ factors a, p ~ᵤ q := λ ⟨b, hb⟩, have hb0 : b ≠ 0, from λ hb0, by simp * at *, have multiset.rel associated (p :: factors b) (factors a), from unique (λ x hx, (multiset.mem_cons.1 hx).elim (λ h, h.symm ▸ hp) (irreducible_factors hb0 _)) (irreducible_factors ha0) (associated.symm $ calc multiset.prod (factors a) ~ᵤ a : factors_prod ha0 ... = p * b : hb ... ~ᵤ multiset.prod (p :: factors b) : by rw multiset.prod_cons; exact associated_mul_mul (associated.refl _) (associated.symm (factors_prod hb0))), multiset.exists_mem_of_rel_of_mem this (by simp) def of_unique_irreducible_factorization {α : Type*} [integral_domain α] (o : unique_irreducible_factorization α) : unique_factorization_domain α := { prime_factors := by letI := classical.dec_eq α; exact λ a h p (hpa : p ∈ o.factors a), have hpi : irreducible p, from o.irreducible_factors h _ hpa, ⟨hpi.ne_zero, hpi.1, λ a b ⟨x, hx⟩, if hab0 : a * b = 0 then (eq_zero_or_eq_zero_of_mul_eq_zero hab0).elim (λ ha0, by simp [ha0]) (λ hb0, by simp [hb0]) else have hx0 : x ≠ 0, from λ hx0, by simp * at *, have ha0 : a ≠ 0, from left_ne_zero_of_mul hab0, have hb0 : b ≠ 0, from right_ne_zero_of_mul hab0, have multiset.rel associated (p :: o.factors x) (o.factors a + o.factors b), from o.unique (λ i hi, (multiset.mem_cons.1 hi).elim (λ hip, hip.symm ▸ hpi) (o.irreducible_factors hx0 _)) (show ∀ x ∈ o.factors a + o.factors b, irreducible x, from λ x hx, (multiset.mem_add.1 hx).elim (o.irreducible_factors ha0 _) (o.irreducible_factors hb0 _)) $ calc multiset.prod (p :: o.factors x) ~ᵤ a * b : by rw [hx, multiset.prod_cons]; exact associated_mul_mul (by refl) (o.factors_prod hx0) ... ~ᵤ (o.factors a).prod * (o.factors b).prod : associated_mul_mul (o.factors_prod ha0).symm (o.factors_prod hb0).symm ... = _ : by rw multiset.prod_add, let ⟨q, hqf, hq⟩ := multiset.exists_mem_of_rel_of_mem this (multiset.mem_cons_self p _) in (multiset.mem_add.1 hqf).elim (λ hqa, or.inl $ (dvd_iff_dvd_of_rel_left hq).2 $ (dvd_iff_dvd_of_rel_right (o.factors_prod ha0)).1 (multiset.dvd_prod hqa)) (λ hqb, or.inr $ (dvd_iff_dvd_of_rel_left hq).2 $ (dvd_iff_dvd_of_rel_right (o.factors_prod hb0)).1 (multiset.dvd_prod hqb))⟩, ..o } end unique_factorization_domain namespace associates open unique_factorization_domain associated variables [integral_domain α] /-- `factor_set α` representation elements of unique factorization domain as multisets. `multiset α` produced by `factors` are only unique up to associated elements, while the multisets in `factor_set α` are unqiue by equality and restricted to irreducible elements. This gives us a representation of each element as a unique multisets (or the added ⊤ for 0), which has a complete lattice struture. Infimum is the greatest common divisor and supremum is the least common multiple. -/ @[reducible] def {u} factor_set (α : Type u) [integral_domain α] : Type u := with_top (multiset { a : associates α // irreducible a }) local attribute [instance] associated.setoid theorem factor_set.coe_add {a b : multiset { a : associates α // irreducible a }} : (↑(a + b) : factor_set α) = a + b := by norm_cast lemma factor_set.sup_add_inf_eq_add [decidable_eq (associates α)] : ∀(a b : factor_set α), a ⊔ b + a ⊓ b = a + b | none b := show ⊤ ⊔ b + ⊤ ⊓ b = ⊤ + b, by simp | a none := show a ⊔ ⊤ + a ⊓ ⊤ = a + ⊤, by simp | (some a) (some b) := show (a : factor_set α) ⊔ b + a ⊓ b = a + b, from begin rw [← with_top.coe_sup, ← with_top.coe_inf, ← with_top.coe_add, ← with_top.coe_add, with_top.coe_eq_coe], exact multiset.union_add_inter _ _ end def factor_set.prod : factor_set α → associates α | none := 0 | (some s) := (s.map coe).prod @[simp] theorem prod_top : (⊤ : factor_set α).prod = 0 := rfl @[simp] theorem prod_coe {s : multiset { a : associates α // irreducible a }} : (s : factor_set α).prod = (s.map coe).prod := rfl @[simp] theorem prod_add : ∀(a b : factor_set α), (a + b).prod = a.prod * b.prod | none b := show (⊤ + b).prod = (⊤:factor_set α).prod * b.prod, by simp | a none := show (a + ⊤).prod = a.prod * (⊤:factor_set α).prod, by simp | (some a) (some b) := show (↑a + ↑b:factor_set α).prod = (↑a:factor_set α).prod * (↑b:factor_set α).prod, by rw [← factor_set.coe_add, prod_coe, prod_coe, prod_coe, multiset.map_add, multiset.prod_add] theorem prod_mono : ∀{a b : factor_set α}, a ≤ b → a.prod ≤ b.prod | none b h := have b = ⊤, from top_unique h, by rw [this, prod_top]; exact le_refl _ | a none h := show a.prod ≤ (⊤ : factor_set α).prod, by simp; exact le_top | (some a) (some b) h := prod_le_prod $ multiset.map_le_map $ with_top.coe_le_coe.1 $ h variable [unique_factorization_domain α] theorem unique' {p q : multiset (associates α)} : (∀a∈p, irreducible a) → (∀a∈q, irreducible a) → p.prod = q.prod → p = q := begin apply multiset.induction_on_multiset_quot p, apply multiset.induction_on_multiset_quot q, assume s t hs ht eq, refine multiset.map_mk_eq_map_mk_of_rel (unique_factorization_domain.unique _ _ _), { exact assume a ha, ((irreducible_mk_iff _).1 $ hs _ $ multiset.mem_map_of_mem _ ha) }, { exact assume a ha, ((irreducible_mk_iff _).1 $ ht _ $ multiset.mem_map_of_mem _ ha) }, simpa [quot_mk_eq_mk, prod_mk, mk_eq_mk_iff_associated] using eq end private theorem forall_map_mk_factors_irreducible (x : α) (hx : x ≠ 0) : ∀(a : associates α), a ∈ multiset.map associates.mk (factors x) → irreducible a := begin assume a ha, rcases multiset.mem_map.1 ha with ⟨c, hc, rfl⟩, exact (irreducible_mk_iff c).2 (irreducible_factors hx _ hc) end theorem prod_le_prod_iff_le {p q : multiset (associates α)} (hp : ∀a∈p, irreducible a) (hq : ∀a∈q, irreducible a) : p.prod ≤ q.prod ↔ p ≤ q := iff.intro begin rintros ⟨⟨c⟩, eqc⟩, have : c ≠ 0, from (mt mk_eq_zero.2 $ assume (hc : quot.mk setoid.r c = 0), have (0 : associates α) ∈ q, from prod_eq_zero_iff.1 $ eqc.symm ▸ hc.symm ▸ mul_zero _, not_irreducible_zero ((irreducible_mk_iff 0).1 $ hq _ this)), have : associates.mk (factors c).prod = quot.mk setoid.r c, from mk_eq_mk_iff_associated.2 (factors_prod this), refine le_iff_exists_add.2 ⟨(factors c).map associates.mk, unique' hq _ _⟩, { assume x hx, rcases multiset.mem_add.1 hx with h | h, exact hp x h, exact forall_map_mk_factors_irreducible c ‹c ≠ 0› _ h }, { simp [multiset.prod_add, prod_mk, *] at * } end prod_le_prod def factors' (a : α) (ha : a ≠ 0) : multiset { a : associates α // irreducible a } := (factors a).pmap (λa ha, ⟨associates.mk a, (irreducible_mk_iff _).2 ha⟩) (irreducible_factors $ ha) @[simp] theorem map_subtype_coe_factors' {a : α} (ha : a ≠ 0) : (factors' a ha).map coe = (factors a).map associates.mk := by simp [factors', multiset.map_pmap, multiset.pmap_eq_map] theorem factors'_cong {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) (h : a ~ᵤ b) : factors' a ha = factors' b hb := have multiset.rel associated (factors a) (factors b), from unique (irreducible_factors ha) (irreducible_factors hb) ((factors_prod ha).trans $ h.trans $ (factors_prod hb).symm), by simpa [(multiset.map_eq_map subtype.coe_injective).symm, rel_associated_iff_map_eq_map.symm] variable [dec : decidable_eq (associates α)] include dec def factors (a : associates α) : factor_set α := begin refine (if h : a = 0 then ⊤ else quotient.hrec_on a (λx h, some $ factors' x (mt mk_eq_zero.2 h)) _ h), assume a b hab, apply function.hfunext, { have : a ~ᵤ 0 ↔ b ~ᵤ 0, from iff.intro (assume ha0, hab.symm.trans ha0) (assume hb0, hab.trans hb0), simp only [associated_zero_iff_eq_zero] at this, simp only [quotient_mk_eq_mk, this, mk_eq_zero] }, exact (assume ha hb eq, heq_of_eq $ congr_arg some $ factors'_cong _ _ hab) end @[simp] theorem factors_0 : (0 : associates α).factors = ⊤ := dif_pos rfl @[simp] theorem factors_mk (a : α) (h : a ≠ 0) : (associates.mk a).factors = factors' a h := dif_neg (mt mk_eq_zero.1 h) theorem prod_factors : ∀(s : factor_set α), s.prod.factors = s | none := by simp [factor_set.prod]; refl | (some s) := begin unfold factor_set.prod, generalize eq_a : (s.map coe).prod = a, rcases a with ⟨a⟩, rw quot_mk_eq_mk at *, have : (s.map (coe : _ → associates α)).prod ≠ 0, from assume ha, let ⟨⟨a, ha⟩, h, eq⟩ := multiset.mem_map.1 (prod_eq_zero_iff.1 ha) in have irreducible (0 : associates α), from eq ▸ ha, not_irreducible_zero ((irreducible_mk_iff _).1 this), have ha : a ≠ 0, by simp [*] at *, suffices : (unique_factorization_domain.factors a).map associates.mk = s.map coe, { rw [factors_mk a ha], apply congr_arg some _, simpa [(multiset.map_eq_map subtype.coe_injective).symm] }, refine unique' (forall_map_mk_factors_irreducible _ ha) (assume a ha, let ⟨⟨x, hx⟩, ha, eq⟩ := multiset.mem_map.1 ha in eq ▸ hx) _, rw [prod_mk, eq_a, mk_eq_mk_iff_associated], exact factors_prod ha end theorem factors_prod (a : associates α) : a.factors.prod = a := quotient.induction_on a $ assume a, decidable.by_cases (assume : associates.mk a = 0, by simp [quotient_mk_eq_mk, this]) (assume : associates.mk a ≠ 0, have a ≠ 0, by simp * at *, by simp [this, quotient_mk_eq_mk, prod_mk, mk_eq_mk_iff_associated.2 (factors_prod this)]) theorem eq_of_factors_eq_factors {a b : associates α} (h : a.factors = b.factors) : a = b := have a.factors.prod = b.factors.prod, by rw h, by rwa [factors_prod, factors_prod] at this omit dec theorem eq_of_prod_eq_prod {a b : factor_set α} (h : a.prod = b.prod) : a = b := begin classical, have : a.prod.factors = b.prod.factors, by rw h, rwa [prod_factors, prod_factors] at this end include dec @[simp] theorem factors_mul (a b : associates α) : (a * b).factors = a.factors + b.factors := eq_of_prod_eq_prod $ eq_of_factors_eq_factors $ by rw [prod_add, factors_prod, factors_prod, factors_prod] theorem factors_mono : ∀{a b : associates α}, a ≤ b → a.factors ≤ b.factors | s t ⟨d, rfl⟩ := by rw [factors_mul] ; exact le_add_of_nonneg_right bot_le theorem factors_le {a b : associates α} : a.factors ≤ b.factors ↔ a ≤ b := iff.intro (assume h, have a.factors.prod ≤ b.factors.prod, from prod_mono h, by rwa [factors_prod, factors_prod] at this) factors_mono omit dec theorem prod_le {a b : factor_set α} : a.prod ≤ b.prod ↔ a ≤ b := begin classical, exact iff.intro (assume h, have a.prod.factors ≤ b.prod.factors, from factors_mono h, by rwa [prod_factors, prod_factors] at this) prod_mono end include dec instance : has_sup (associates α) := ⟨λa b, (a.factors ⊔ b.factors).prod⟩ instance : has_inf (associates α) := ⟨λa b, (a.factors ⊓ b.factors).prod⟩ instance : bounded_lattice (associates α) := { sup := (⊔), inf := (⊓), sup_le := assume a b c hac hbc, factors_prod c ▸ prod_mono (sup_le (factors_mono hac) (factors_mono hbc)), le_sup_left := assume a b, le_trans (le_of_eq (factors_prod a).symm) $ prod_mono $ le_sup_left, le_sup_right := assume a b, le_trans (le_of_eq (factors_prod b).symm) $ prod_mono $ le_sup_right, le_inf := assume a b c hac hbc, factors_prod a ▸ prod_mono (le_inf (factors_mono hac) (factors_mono hbc)), inf_le_left := assume a b, le_trans (prod_mono inf_le_left) (le_of_eq (factors_prod a)), inf_le_right := assume a b, le_trans (prod_mono inf_le_right) (le_of_eq (factors_prod b)), .. associates.partial_order, .. associates.order_top, .. associates.order_bot } lemma sup_mul_inf (a b : associates α) : (a ⊔ b) * (a ⊓ b) = a * b := show (a.factors ⊔ b.factors).prod * (a.factors ⊓ b.factors).prod = a * b, begin refine eq_of_factors_eq_factors _, rw [← prod_add, prod_factors, factors_mul, factor_set.sup_add_inf_eq_add] end end associates section open associates unique_factorization_domain /-- `to_gcd_monoid` constructs a GCD monoid out of a normalization on a unique factorization domain. -/ def unique_factorization_domain.to_gcd_monoid (α : Type*) [integral_domain α] [unique_factorization_domain α] [normalization_monoid α] [decidable_eq (associates α)] : gcd_monoid α := { gcd := λa b, (associates.mk a ⊓ associates.mk b).out, lcm := λa b, (associates.mk a ⊔ associates.mk b).out, gcd_dvd_left := assume a b, (out_dvd_iff a (associates.mk a ⊓ associates.mk b)).2 $ inf_le_left, gcd_dvd_right := assume a b, (out_dvd_iff b (associates.mk a ⊓ associates.mk b)).2 $ inf_le_right, dvd_gcd := assume a b c hac hab, show a ∣ (associates.mk c ⊓ associates.mk b).out, by rw [dvd_out_iff, le_inf_iff, mk_le_mk_iff_dvd_iff, mk_le_mk_iff_dvd_iff]; exact ⟨hac, hab⟩, lcm_zero_left := assume a, show (⊤ ⊔ associates.mk a).out = 0, by simp, lcm_zero_right := assume a, show (associates.mk a ⊔ ⊤).out = 0, by simp, gcd_mul_lcm := assume a b, show (associates.mk a ⊓ associates.mk b).out * (associates.mk a ⊔ associates.mk b).out = normalize (a * b), by rw [← out_mk, ← out_mul, mul_comm, sup_mul_inf]; refl, normalize_gcd := assume a b, by convert normalize_out _, .. ‹normalization_monoid α› } end namespace unique_factorization_domain variables {R : Type*} [integral_domain R] [unique_factorization_domain R] lemma no_factors_of_no_prime_factors {a b : R} (ha : a ≠ 0) (h : (∀ {d}, d ∣ a → d ∣ b → ¬ prime d)) : ∀ {d}, d ∣ a → d ∣ b → is_unit d := λ d, induction_on_prime d (by { simp only [zero_dvd_iff], intros, contradiction }) (λ x hx _ _, hx) (λ d q hp hq ih dvd_a dvd_b, absurd hq (h (dvd_of_mul_right_dvd dvd_a) (dvd_of_mul_right_dvd dvd_b))) /-- Euclid's lemma: if `a ∣ b * c` and `a` and `c` have no common prime factors, `a ∣ b`. Compare `is_coprime.dvd_of_dvd_mul_left`. -/ lemma dvd_of_dvd_mul_left_of_no_prime_factors {a b c : R} (ha : a ≠ 0) : (∀ {d}, d ∣ a → d ∣ c → ¬ prime d) → a ∣ b * c → a ∣ b := begin refine induction_on_prime c _ _ _, { intro no_factors, simp only [dvd_zero, mul_zero, forall_prop_of_true], haveI := classical.prop_decidable, exact is_unit_iff_forall_dvd.mp (no_factors_of_no_prime_factors ha @no_factors (dvd_refl a) (dvd_zero a)) _ }, { rintros _ ⟨x, rfl⟩ _ a_dvd_bx, apply units.dvd_mul_right.mp a_dvd_bx }, { intros c p hc hp ih no_factors a_dvd_bpc, apply ih (λ q dvd_a dvd_c hq, no_factors dvd_a (dvd_mul_of_dvd_right dvd_c _) hq), rw mul_left_comm at a_dvd_bpc, refine or.resolve_left (left_dvd_or_dvd_right_of_dvd_prime_mul hp a_dvd_bpc) (λ h, _), exact no_factors h (dvd_mul_right p c) hp } end /-- Euclid's lemma: if `a ∣ b * c` and `a` and `b` have no common prime factors, `a ∣ c`. Compare `is_coprime.dvd_of_dvd_mul_right`. -/ lemma dvd_of_dvd_mul_right_of_no_prime_factors {a b c : R} (ha : a ≠ 0) (no_factors : ∀ {d}, d ∣ a → d ∣ b → ¬ prime d) : a ∣ b * c → a ∣ c := by simpa [mul_comm b c] using dvd_of_dvd_mul_left_of_no_prime_factors ha @no_factors /-- If `a ≠ 0, b` are elements of a unique factorization domain, then dividing out their common factor `c'` gives `a'` and `b'` with no factors in common. -/ lemma exists_reduced_factors : ∀ (a ≠ (0 : R)) b, ∃ a' b' c', (∀ {d}, d ∣ a' → d ∣ b' → is_unit d) ∧ c' * a' = a ∧ c' * b' = b := begin haveI := classical.prop_decidable, intros a, refine induction_on_prime a _ _ _, { intros, contradiction }, { intros a a_unit a_ne_zero b, use [a, b, 1], split, { intros p p_dvd_a _, exact is_unit_of_dvd_unit p_dvd_a a_unit }, { simp } }, { intros a p a_ne_zero p_prime ih_a pa_ne_zero b, by_cases p ∣ b, { rcases h with ⟨b, rfl⟩, obtain ⟨a', b', c', no_factor, ha', hb'⟩ := ih_a a_ne_zero b, refine ⟨a', b', p * c', @no_factor, _, _⟩, { rw [mul_assoc, ha'] }, { rw [mul_assoc, hb'] } }, { obtain ⟨a', b', c', coprime, rfl, rfl⟩ := ih_a a_ne_zero b, refine ⟨p * a', b', c', _, mul_left_comm _ _ _, rfl⟩, intros q q_dvd_pa' q_dvd_b', cases left_dvd_or_dvd_right_of_dvd_prime_mul p_prime q_dvd_pa' with p_dvd_q q_dvd_a', { have : p ∣ c' * b' := dvd_mul_of_dvd_right (dvd_trans p_dvd_q q_dvd_b') _, contradiction }, exact coprime q_dvd_a' q_dvd_b' } } end lemma exists_reduced_factors' (a b : R) (hb : b ≠ 0) : ∃ a' b' c', (∀ {d}, d ∣ a' → d ∣ b' → is_unit d) ∧ c' * a' = a ∧ c' * b' = b := let ⟨b', a', c', no_factor, hb, ha⟩ := exists_reduced_factors b hb a in ⟨a', b', c', λ _ hpb hpa, no_factor hpa hpb, ha, hb⟩ end unique_factorization_domain
4d57eba7b4fbb555aee5deaa909a3fdc9009e52c
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/deprecated/ring.lean
c3df8ff072fb5d6564d46f653797813b9a48250d
[ "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,654
lean
/- Copyright (c) 2020 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import deprecated.group /-! # Unbundled semiring and ring homomorphisms (deprecated) This file defines typeclasses for unbundled semiring and ring homomorphisms. Though these classes are deprecated, they are still widely used in mathlib, and probably will not go away before Lean 4 because Lean 3 often fails to coerce a bundled homomorphism to a function. ## main definitions is_semiring_hom (deprecated), is_ring_hom (deprecated) ## Tags is_semiring_hom, is_ring_hom -/ universes u v w variable {α : Type u} /-- Predicate for semiring homomorphisms (deprecated -- use the bundled `ring_hom` version). -/ class is_semiring_hom {α : Type u} {β : Type v} [semiring α] [semiring β] (f : α → β) : Prop := (map_zero [] : f 0 = 0) (map_one [] : f 1 = 1) (map_add [] : ∀ {x y}, f (x + y) = f x + f y) (map_mul [] : ∀ {x y}, f (x * y) = f x * f y) namespace is_semiring_hom variables {β : Type v} [semiring α] [semiring β] variables (f : α → β) [is_semiring_hom f] {x y : α} /-- The identity map is a semiring homomorphism. -/ instance id : is_semiring_hom (@id α) := by refine {..}; intros; refl /-- The composition of two semiring homomorphisms is a semiring homomorphism. -/ -- see Note [no instance on morphisms] lemma comp {γ} [semiring γ] (g : β → γ) [is_semiring_hom g] : is_semiring_hom (g ∘ f) := { map_zero := by simp [map_zero f]; exact map_zero g, map_one := by simp [map_one f]; exact map_one g, map_add := λ x y, by simp [map_add f]; rw map_add g; refl, map_mul := λ x y, by simp [map_mul f]; rw map_mul g; refl } /-- A semiring homomorphism is an additive monoid homomorphism. -/ @[priority 100] -- see Note [lower instance priority] instance : is_add_monoid_hom f := { ..‹is_semiring_hom f› } /-- A semiring homomorphism is a monoid homomorphism. -/ @[priority 100] -- see Note [lower instance priority] instance : is_monoid_hom f := { ..‹is_semiring_hom f› } end is_semiring_hom /-- Predicate for ring homomorphisms (deprecated -- use the bundled `ring_hom` version). -/ class is_ring_hom {α : Type u} {β : Type v} [ring α] [ring β] (f : α → β) : Prop := (map_one [] : f 1 = 1) (map_mul [] : ∀ {x y}, f (x * y) = f x * f y) (map_add [] : ∀ {x y}, f (x + y) = f x + f y) namespace is_ring_hom variables {β : Type v} [ring α] [ring β] /-- A map of rings that is a semiring homomorphism is also a ring homomorphism. -/ lemma of_semiring (f : α → β) [H : is_semiring_hom f] : is_ring_hom f := {..H} variables (f : α → β) [is_ring_hom f] {x y : α} /-- Ring homomorphisms map zero to zero. -/ lemma map_zero : f 0 = 0 := calc f 0 = f (0 + 0) - f 0 : by rw [map_add f]; simp ... = 0 : by simp /-- Ring homomorphisms preserve additive inverses. -/ lemma map_neg : f (-x) = -f x := calc f (-x) = f (-x + x) - f x : by rw [map_add f]; simp ... = -f x : by simp [map_zero f] /-- Ring homomorphisms preserve subtraction. -/ lemma map_sub : f (x - y) = f x - f y := by simp [sub_eq_add_neg, map_add f, map_neg f] /-- The identity map is a ring homomorphism. -/ instance id : is_ring_hom (@id α) := by refine {..}; intros; refl /-- The composition of two ring homomorphisms is a ring homomorphism. -/ -- see Note [no instance on morphisms] lemma comp {γ} [ring γ] (g : β → γ) [is_ring_hom g] : is_ring_hom (g ∘ f) := { map_add := λ x y, by simp [map_add f]; rw map_add g; refl, map_mul := λ x y, by simp [map_mul f]; rw map_mul g; refl, map_one := by simp [map_one f]; exact map_one g } /-- A ring homomorphism is also a semiring homomorphism. -/ @[priority 100] -- see Note [lower instance priority] instance : is_semiring_hom f := { map_zero := map_zero f, ..‹is_ring_hom f› } @[priority 100] -- see Note [lower instance priority] instance : is_add_group_hom f := { } end is_ring_hom variables {β : Type v} {γ : Type w} [rα : semiring α] [rβ : semiring β] namespace ring_hom section include rα rβ /-- Interpret `f : α → β` with `is_semiring_hom f` as a ring homomorphism. -/ def of (f : α → β) [is_semiring_hom f] : α →+* β := { to_fun := f, .. monoid_hom.of f, .. add_monoid_hom.of f } @[simp] lemma coe_of (f : α → β) [is_semiring_hom f] : ⇑(of f) = f := rfl instance (f : α →+* β) : is_semiring_hom f := { map_zero := f.map_zero, map_one := f.map_one, map_add := f.map_add, map_mul := f.map_mul } end instance {α γ} [ring α] [ring γ] (g : α →+* γ) : is_ring_hom g := is_ring_hom.of_semiring g end ring_hom
fc187726ef2f771eba94f15d2555e72f20ad38cb
b7f22e51856f4989b970961f794f1c435f9b8f78
/hott/algebra/category/constructions/set.hlean
fc51ac1bc0253af70b45d2a67a2220153f6dc0b0
[ "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
3,572
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, Jakob von Raumer Category of sets -/ import ..functor.basic ..category types.equiv types.lift open eq category equiv iso is_equiv is_trunc function sigma namespace category definition precategory_Set.{u} [reducible] [constructor] : precategory Set.{u} := precategory.mk (λx y : Set, x → y) (λx y z g f a, g (f a)) (λx a, a) (λx y z w h g f, eq_of_homotopy (λa, idp)) (λx y f, eq_of_homotopy (λa, idp)) (λx y f, eq_of_homotopy (λa, idp)) definition Precategory_Set [reducible] [constructor] : Precategory := Precategory.mk Set precategory_Set abbreviation set [constructor] := Precategory_Set namespace set local attribute is_equiv_subtype_eq [instance] definition iso_of_equiv [constructor] {A B : set} (f : A ≃ B) : A ≅ B := iso.MK (to_fun f) (to_inv f) (eq_of_homotopy (left_inv (to_fun f))) (eq_of_homotopy (right_inv (to_fun f))) definition equiv_of_iso [constructor] {A B : set} (f : A ≅ B) : A ≃ B := begin apply equiv.MK (to_hom f) (iso.to_inv f), exact ap10 (to_right_inverse f), exact ap10 (to_left_inverse f) end definition is_equiv_iso_of_equiv [constructor] (A B : set) : is_equiv (@iso_of_equiv A B) := adjointify _ (λf, equiv_of_iso f) (λf, proof iso_eq idp qed) (λf, equiv_eq' idp) local attribute is_equiv_iso_of_equiv [instance] definition iso_of_eq_eq_compose (A B : Set) : @iso_of_eq _ _ A B = @iso_of_equiv A B ∘ @equiv_of_eq A B ∘ subtype_eq_inv _ _ ∘ @ap _ _ (to_fun (trunctype.sigma_char 0)) A B := eq_of_homotopy (λp, eq.rec_on p idp) definition equiv_equiv_iso (A B : set) : (A ≃ B) ≃ (A ≅ B) := equiv.MK (λf, iso_of_equiv f) (λf, proof equiv.MK (to_hom f) (iso.to_inv f) (ap10 (to_right_inverse f)) (ap10 (to_left_inverse f)) qed) (λf, proof iso_eq idp qed) (λf, proof equiv_eq' idp qed) definition equiv_eq_iso (A B : set) : (A ≃ B) = (A ≅ B) := ua !equiv_equiv_iso definition is_univalent_Set (A B : set) : is_equiv (iso_of_eq : A = B → A ≅ B) := have H₁ : is_equiv (@iso_of_equiv A B ∘ @equiv_of_eq A B ∘ subtype_eq_inv _ _ ∘ @ap _ _ (to_fun (trunctype.sigma_char 0)) A B), from @is_equiv_compose _ _ _ _ _ (@is_equiv_compose _ _ _ _ _ (@is_equiv_compose _ _ _ _ _ _ (@is_equiv_subtype_eq_inv _ _ _ _ _)) !univalence) !is_equiv_iso_of_equiv, let H₂ := (iso_of_eq_eq_compose A B)⁻¹ in begin rewrite H₂ at H₁, assumption end end set definition category_Set [instance] [constructor] : category Set := category.mk precategory_Set set.is_univalent_Set definition Category_Set [reducible] [constructor] : Category := Category.mk Set category_Set abbreviation cset [constructor] := Category_Set open functor lift definition functor_lift.{u v} [constructor] : set.{u} ⇒ set.{max u v} := functor.mk tlift (λa b, lift_functor) (λa, eq_of_homotopy (λx, by induction x; reflexivity)) (λa b c g f, eq_of_homotopy (λx, by induction x; reflexivity)) end category
e47dfcaf3f2d77432a1513ca72b55e1c34e11c25
649957717d58c43b5d8d200da34bf374293fe739
/src/algebra/archimedean.lean
88caa3bc9c3bbe3a28e2188679359830b2a8715c
[ "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
15,761
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro Archimedean groups and fields. -/ import algebra.group_power algebra.field_power import data.rat.basic tactic.linarith tactic.abel local infix ` • ` := add_monoid.smul variables {α : Type*} class floor_ring (α) [linear_ordered_ring α] := (floor : α → ℤ) (le_floor : ∀ (z : ℤ) (x : α), z ≤ floor x ↔ (z : α) ≤ x) instance : floor_ring ℤ := { floor := id, le_floor := λ _ _, by rw int.cast_id; refl } instance : floor_ring ℚ := { floor := rat.floor, le_floor := @rat.le_floor } section variables [linear_ordered_ring α] [floor_ring α] def floor : α → ℤ := floor_ring.floor notation `⌊` x `⌋` := floor x theorem le_floor : ∀ {z : ℤ} {x : α}, z ≤ ⌊x⌋ ↔ (z : α) ≤ x := floor_ring.le_floor theorem floor_lt {x : α} {z : ℤ} : ⌊x⌋ < z ↔ x < z := lt_iff_lt_of_le_iff_le le_floor theorem floor_le (x : α) : (⌊x⌋ : α) ≤ x := le_floor.1 (le_refl _) theorem floor_nonneg {x : α} : 0 ≤ ⌊x⌋ ↔ 0 ≤ x := by rw [le_floor]; refl theorem lt_succ_floor (x : α) : x < ⌊x⌋.succ := floor_lt.1 $ int.lt_succ_self _ theorem lt_floor_add_one (x : α) : x < ⌊x⌋ + 1 := by simpa only [int.succ, int.cast_add, int.cast_one] using lt_succ_floor x theorem sub_one_lt_floor (x : α) : x - 1 < ⌊x⌋ := sub_lt_iff_lt_add.2 (lt_floor_add_one x) @[simp] theorem floor_coe (z : ℤ) : ⌊(z:α)⌋ = z := eq_of_forall_le_iff $ λ a, by rw [le_floor, int.cast_le] @[simp] theorem floor_zero : ⌊(0:α)⌋ = 0 := floor_coe 0 @[simp] theorem floor_one : ⌊(1:α)⌋ = 1 := by rw [← int.cast_one, floor_coe] theorem floor_mono {a b : α} (h : a ≤ b) : ⌊a⌋ ≤ ⌊b⌋ := le_floor.2 (le_trans (floor_le _) h) @[simp] theorem floor_add_int (x : α) (z : ℤ) : ⌊x + z⌋ = ⌊x⌋ + z := eq_of_forall_le_iff $ λ a, by rw [le_floor, ← sub_le_iff_le_add, ← sub_le_iff_le_add, le_floor, int.cast_sub] theorem floor_sub_int (x : α) (z : ℤ) : ⌊x - z⌋ = ⌊x⌋ - z := eq.trans (by rw [int.cast_neg]; refl) (floor_add_int _ _) lemma abs_sub_lt_one_of_floor_eq_floor {α : Type*} [decidable_linear_ordered_comm_ring α] [floor_ring α] {x y : α} (h : ⌊x⌋ = ⌊y⌋) : abs (x - y) < 1 := begin have : x < ⌊x⌋ + 1 := lt_floor_add_one x, have : y < ⌊y⌋ + 1 := lt_floor_add_one y, have : (⌊x⌋ : α) = ⌊y⌋ := int.cast_inj.2 h, have : (⌊x⌋: α) ≤ x := floor_le x, have : (⌊y⌋ : α) ≤ y := floor_le y, exact abs_sub_lt_iff.2 ⟨by linarith, by linarith⟩ end lemma floor_eq_iff {r : α} {z : ℤ} : ⌊r⌋ = z ↔ ↑z ≤ r ∧ r < (z + 1) := by rw [←le_floor, ←int.cast_one, ←int.cast_add, ←floor_lt, int.lt_add_one_iff, le_antisymm_iff, and.comm] /-- The fractional part fract r of r is just r - ⌊r⌋ -/ def fract (r : α) : α := r - ⌊r⌋ -- Mathematical notation is usually {r}. Let's not even go there. @[simp] lemma floor_add_fract (r : α) : (⌊r⌋ : α) + fract r = r := by unfold fract; simp @[simp] lemma fract_add_floor (r : α) : fract r + ⌊r⌋ = r := sub_add_cancel _ _ theorem fract_nonneg (r : α) : 0 ≤ fract r := sub_nonneg.2 $ floor_le _ theorem fract_lt_one (r : α) : fract r < 1 := sub_lt.1 $ sub_one_lt_floor _ @[simp] lemma fract_zero : fract (0 : α) = 0 := by unfold fract; simp @[simp] lemma fract_coe (z : ℤ) : fract (z : α) = 0 := by unfold fract; rw floor_coe; exact sub_self _ @[simp] lemma fract_floor (r : α) : fract (⌊r⌋ : α) = 0 := fract_coe _ @[simp] lemma floor_fract (r : α) : ⌊fract r⌋ = 0 := by rw floor_eq_iff; exact ⟨fract_nonneg _, by rw [int.cast_zero, zero_add]; exact fract_lt_one r⟩ theorem fract_eq_iff {r s : α} : fract r = s ↔ 0 ≤ s ∧ s < 1 ∧ ∃ z : ℤ, r - s = z := ⟨λ h, by rw ←h; exact ⟨fract_nonneg _, fract_lt_one _, ⟨⌊r⌋, sub_sub_cancel _ _⟩⟩, begin intro h, show r - ⌊r⌋ = s, apply eq.symm, rw [eq_sub_iff_add_eq, add_comm, ←eq_sub_iff_add_eq], rcases h with ⟨hge, hlt, ⟨z, hz⟩⟩, rw [hz, int.cast_inj, floor_eq_iff, ←hz], clear hz, split; linarith {discharger := `[simp]} end⟩ theorem fract_eq_fract {r s : α} : fract r = fract s ↔ ∃ z : ℤ, r - s = z := ⟨λ h, ⟨⌊r⌋ - ⌊s⌋, begin unfold fract at h, rw [int.cast_sub, sub_eq_sub_iff_sub_eq_sub.1 h], end⟩, λ h, begin rcases h with ⟨z, hz⟩, rw fract_eq_iff, split, exact fract_nonneg _, split, exact fract_lt_one _, use z + ⌊s⌋, rw [eq_add_of_sub_eq hz, int.cast_add], unfold fract, simp end⟩ @[simp] lemma fract_fract (r : α) : fract (fract r) = fract r := by rw fract_eq_fract; exact ⟨-⌊r⌋, by unfold fract;simp⟩ theorem fract_add (r s : α) : ∃ z : ℤ, fract (r + s) - fract r - fract s = z := ⟨⌊r⌋ + ⌊s⌋ - ⌊r + s⌋, by unfold fract; simp⟩ theorem fract_mul_nat (r : α) (b : ℕ) : ∃ z : ℤ, fract r * b - fract (r * b) = z := begin induction b with c hc, use 0, simp, rcases hc with ⟨z, hz⟩, rw [nat.succ_eq_add_one, nat.cast_add, mul_add, mul_add, nat.cast_one, mul_one, mul_one], rcases fract_add (r * c) r with ⟨y, hy⟩, use z - y, rw [int.cast_sub, ←hz, ←hy], abel end /-- `ceil x` is the smallest integer `z` such that `x ≤ z` -/ def ceil (x : α) : ℤ := -⌊-x⌋ notation `⌈` x `⌉` := ceil x theorem ceil_le {z : ℤ} {x : α} : ⌈x⌉ ≤ z ↔ x ≤ z := by rw [ceil, neg_le, le_floor, int.cast_neg, neg_le_neg_iff] theorem lt_ceil {x : α} {z : ℤ} : z < ⌈x⌉ ↔ (z:α) < x := lt_iff_lt_of_le_iff_le ceil_le theorem le_ceil (x : α) : x ≤ ⌈x⌉ := ceil_le.1 (le_refl _) @[simp] theorem ceil_coe (z : ℤ) : ⌈(z:α)⌉ = z := by rw [ceil, ← int.cast_neg, floor_coe, neg_neg] theorem ceil_mono {a b : α} (h : a ≤ b) : ⌈a⌉ ≤ ⌈b⌉ := ceil_le.2 (le_trans h (le_ceil _)) @[simp] theorem ceil_add_int (x : α) (z : ℤ) : ⌈x + z⌉ = ⌈x⌉ + z := by rw [ceil, neg_add', floor_sub_int, neg_sub, sub_eq_neg_add]; refl theorem ceil_sub_int (x : α) (z : ℤ) : ⌈x - z⌉ = ⌈x⌉ - z := eq.trans (by rw [int.cast_neg]; refl) (ceil_add_int _ _) theorem ceil_lt_add_one (x : α) : (⌈x⌉ : α) < x + 1 := by rw [← lt_ceil, ← int.cast_one, ceil_add_int]; apply lt_add_one lemma ceil_pos {a : α} : 0 < ⌈a⌉ ↔ 0 < a := ⟨ λ h, have ⌊-a⌋ < 0, from neg_of_neg_pos h, pos_of_neg_neg $ lt_of_not_ge $ (not_iff_not_of_iff floor_nonneg).1 $ not_le_of_gt this, λ h, have -a < 0, from neg_neg_of_pos h, neg_pos_of_neg $ lt_of_not_ge $ (not_iff_not_of_iff floor_nonneg).2 $ not_le_of_gt this ⟩ @[simp] theorem ceil_zero : ⌈(0 : α)⌉ = 0 := by simp [ceil] lemma ceil_nonneg [decidable_rel ((<) : α → α → Prop)] {q : α} (hq : q ≥ 0) : ⌈q⌉ ≥ 0 := if h : q > 0 then le_of_lt $ ceil_pos.2 h else by rw [le_antisymm (le_of_not_lt h) hq, ceil_zero]; trivial end class archimedean (α) [ordered_comm_monoid α] : Prop := (arch : ∀ (x : α) {y}, 0 < y → ∃ n : ℕ, x ≤ n • y) theorem exists_nat_gt [linear_ordered_semiring α] [archimedean α] (x : α) : ∃ n : ℕ, x < n := let ⟨n, h⟩ := archimedean.arch x zero_lt_one in ⟨n+1, lt_of_le_of_lt (by rwa ← add_monoid.smul_one) (nat.cast_lt.2 (nat.lt_succ_self _))⟩ section linear_ordered_ring variables [linear_ordered_ring α] [archimedean α] lemma pow_unbounded_of_gt_one (x : α) {y : α} (hy1 : 1 < y) : ∃ n : ℕ, x < y ^ n := have hy0 : 0 < y - 1 := sub_pos_of_lt hy1, let ⟨n, h⟩ := archimedean.arch x hy0 in ⟨n, calc x ≤ n • (y - 1) : h ... < 1 + n • (y - 1) : by rw add_comm; exact lt_add_one _ ... ≤ y ^ n : pow_ge_one_add_sub_mul (le_of_lt hy1) _⟩ lemma exists_nat_pow_near {x : α} {y : α} (hx : 1 < x) (hy : 1 < y) : ∃ n : ℕ, y ^ n ≤ x ∧ x < y ^ (n + 1) := have h : ∃ n : ℕ, x < y ^ n, from pow_unbounded_of_gt_one _ hy, by classical; exact let n := nat.find h in have hn : x < y ^ n, from nat.find_spec h, have hnp : 0 < n, from nat.pos_iff_ne_zero.2 (λ hn0, by rw [hn0, pow_zero] at hn; exact (not_lt_of_gt hn hx)), have hnsp : nat.pred n + 1 = n, from nat.succ_pred_eq_of_pos hnp, have hltn : nat.pred n < n, from nat.pred_lt (ne_of_gt hnp), ⟨nat.pred n, le_of_not_lt (nat.find_min h hltn), by rwa hnsp⟩ theorem exists_int_gt (x : α) : ∃ n : ℤ, x < n := let ⟨n, h⟩ := exists_nat_gt x in ⟨n, by rwa ← coe_coe⟩ theorem exists_int_lt (x : α) : ∃ n : ℤ, (n : α) < x := let ⟨n, h⟩ := exists_int_gt (-x) in ⟨-n, by rw int.cast_neg; exact neg_lt.1 h⟩ theorem exists_floor (x : α) : ∃ (fl : ℤ), ∀ (z : ℤ), z ≤ fl ↔ (z : α) ≤ x := begin haveI := classical.prop_decidable, have : ∃ (ub : ℤ), (ub:α) ≤ x ∧ ∀ (z : ℤ), (z:α) ≤ x → z ≤ ub := int.exists_greatest_of_bdd (let ⟨n, hn⟩ := exists_int_gt x in ⟨n, λ z h', int.cast_le.1 $ le_trans h' $ le_of_lt hn⟩) (let ⟨n, hn⟩ := exists_int_lt x in ⟨n, le_of_lt hn⟩), refine this.imp (λ fl h z, _), cases h with h₁ h₂, exact ⟨λ h, le_trans (int.cast_le.2 h) h₁, h₂ z⟩, end end linear_ordered_ring section linear_ordered_field lemma exists_int_pow_near [discrete_linear_ordered_field α] [archimedean α] {x : α} {y : α} (hx : 0 < x) (hy : 1 < y) : ∃ n : ℤ, y ^ n ≤ x ∧ x < y ^ (n + 1) := by classical; exact let ⟨N, hN⟩ := pow_unbounded_of_gt_one x⁻¹ hy in have he: ∃ m : ℤ, y ^ m ≤ x, from ⟨-N, le_of_lt (by rw [(fpow_neg y (↑N)), one_div_eq_inv]; exact (inv_lt hx (lt_trans (inv_pos hx) hN)).1 hN)⟩, let ⟨M, hM⟩ := pow_unbounded_of_gt_one x hy in have hb: ∃ b : ℤ, ∀ m, y ^ m ≤ x → m ≤ b, from ⟨M, λ m hm, le_of_not_lt (λ hlt, not_lt_of_ge (fpow_le_of_le (le_of_lt hy) (le_of_lt hlt)) (lt_of_le_of_lt hm hM))⟩, let ⟨n, hn₁, hn₂⟩ := int.exists_greatest_of_bdd hb he in ⟨n, hn₁, lt_of_not_ge (λ hge, not_le_of_gt (int.lt_succ _) (hn₂ _ hge))⟩ variables [linear_ordered_field α] [floor_ring α] lemma sub_floor_div_mul_nonneg (x : α) {y : α} (hy : 0 < y) : 0 ≤ x - ⌊x / y⌋ * y := begin conv in x {rw ← div_mul_cancel x (ne_of_lt hy).symm}, rw ← sub_mul, exact mul_nonneg (sub_nonneg.2 (floor_le _)) (le_of_lt hy) end lemma sub_floor_div_mul_lt (x : α) {y : α} (hy : 0 < y) : x - ⌊x / y⌋ * y < y := sub_lt_iff_lt_add.2 begin conv in y {rw ← one_mul y}, conv in x {rw ← div_mul_cancel x (ne_of_lt hy).symm}, rw ← add_mul, exact (mul_lt_mul_right hy).2 (by rw add_comm; exact lt_floor_add_one _), end end linear_ordered_field instance : archimedean ℕ := ⟨λ n m m0, ⟨n, by simpa only [mul_one, nat.smul_eq_mul] using nat.mul_le_mul_left n m0⟩⟩ instance : archimedean ℤ := ⟨λ n m m0, ⟨n.to_nat, le_trans (int.le_to_nat _) $ by simpa only [add_monoid.smul_eq_mul, int.nat_cast_eq_coe_nat, zero_add, mul_one] using mul_le_mul_of_nonneg_left (int.add_one_le_iff.2 m0) (int.coe_zero_le n.to_nat)⟩⟩ noncomputable def archimedean.floor_ring (α) [linear_ordered_ring α] [archimedean α] : floor_ring α := { floor := λ x, classical.some (exists_floor x), le_floor := λ z x, classical.some_spec (exists_floor x) z } section linear_ordered_field variables [linear_ordered_field α] theorem archimedean_iff_nat_lt : archimedean α ↔ ∀ x : α, ∃ n : ℕ, x < n := ⟨@exists_nat_gt α _, λ H, ⟨λ x y y0, (H (x / y)).imp $ λ n h, le_of_lt $ by rwa [div_lt_iff y0, ← add_monoid.smul_eq_mul] at h⟩⟩ theorem archimedean_iff_nat_le : archimedean α ↔ ∀ x : α, ∃ n : ℕ, x ≤ n := archimedean_iff_nat_lt.trans ⟨λ H x, (H x).imp $ λ _, le_of_lt, λ H x, let ⟨n, h⟩ := H x in ⟨n+1, lt_of_le_of_lt h (nat.cast_lt.2 (lt_add_one _))⟩⟩ theorem exists_rat_gt [archimedean α] (x : α) : ∃ q : ℚ, x < q := let ⟨n, h⟩ := exists_nat_gt x in ⟨n, by rwa rat.cast_coe_nat⟩ theorem archimedean_iff_rat_lt : archimedean α ↔ ∀ x : α, ∃ q : ℚ, x < q := ⟨@exists_rat_gt α _, λ H, archimedean_iff_nat_lt.2 $ λ x, let ⟨q, h⟩ := H x in ⟨rat.nat_ceil q, lt_of_lt_of_le h $ by simpa only [rat.cast_coe_nat] using (@rat.cast_le α _ _ _).2 (rat.le_nat_ceil _)⟩⟩ theorem archimedean_iff_rat_le : archimedean α ↔ ∀ x : α, ∃ q : ℚ, x ≤ q := archimedean_iff_rat_lt.trans ⟨λ H x, (H x).imp $ λ _, le_of_lt, λ H x, let ⟨n, h⟩ := H x in ⟨n+1, lt_of_le_of_lt h (rat.cast_lt.2 (lt_add_one _))⟩⟩ variable [archimedean α] theorem exists_rat_lt (x : α) : ∃ q : ℚ, (q : α) < x := let ⟨n, h⟩ := exists_int_lt x in ⟨n, by rwa rat.cast_coe_int⟩ theorem exists_rat_btwn {x y : α} (h : x < y) : ∃ q : ℚ, x < q ∧ (q:α) < y := begin cases exists_nat_gt (y - x)⁻¹ with n nh, cases exists_floor (x * n) with z zh, refine ⟨(z + 1 : ℤ) / n, _⟩, have n0 := nat.cast_pos.1 (lt_trans (inv_pos (sub_pos.2 h)) nh), have n0' := (@nat.cast_pos α _ _).2 n0, rw [rat.cast_div_of_ne_zero, rat.cast_coe_nat, rat.cast_coe_int, div_lt_iff n0'], refine ⟨(lt_div_iff n0').2 $ (lt_iff_lt_of_le_iff_le (zh _)).1 (lt_add_one _), _⟩, rw [int.cast_add, int.cast_one], refine lt_of_le_of_lt (add_le_add_right ((zh _).1 (le_refl _)) _) _, rwa [← lt_sub_iff_add_lt', ← sub_mul, ← div_lt_iff' (sub_pos.2 h), one_div_eq_inv], { rw [rat.coe_int_denom, nat.cast_one], exact one_ne_zero }, { intro H, rw [rat.coe_nat_num, ← coe_coe, nat.cast_eq_zero] at H, subst H, cases n0 }, { rw [rat.coe_nat_denom, nat.cast_one], exact one_ne_zero } end theorem exists_nat_one_div_lt {ε : α} (hε : ε > 0) : ∃ n : ℕ, 1 / (n + 1: α) < ε := begin cases archimedean_iff_nat_lt.1 (by apply_instance) (1/ε) with n hn, existsi n, apply div_lt_of_mul_lt_of_pos, { simp, apply add_pos_of_pos_of_nonneg zero_lt_one, apply nat.cast_nonneg }, { apply (div_lt_iff' hε).1, transitivity, { exact hn }, { simp [zero_lt_one] }} end theorem exists_pos_rat_lt {x : α} (x0 : 0 < x) : ∃ q : ℚ, 0 < q ∧ (q : α) < x := by simpa only [rat.cast_pos] using exists_rat_btwn x0 include α @[simp] theorem rat.cast_floor (x : ℚ) : by haveI := archimedean.floor_ring α; exact ⌊(x:α)⌋ = ⌊x⌋ := begin haveI := archimedean.floor_ring α, apply le_antisymm, { rw [le_floor, ← @rat.cast_le α, rat.cast_coe_int], apply floor_le }, { rw [le_floor, ← rat.cast_coe_int, rat.cast_le], apply floor_le } end /-- `round` rounds a number to the nearest integer. `round (1 / 2) = 1` -/ def round [floor_ring α] (x : α) : ℤ := ⌊x + 1 / 2⌋ end linear_ordered_field section variables [discrete_linear_ordered_field α] [archimedean α] theorem exists_rat_near (x : α) {ε : α} (ε0 : ε > 0) : ∃ q : ℚ, abs (x - q) < ε := let ⟨q, h₁, h₂⟩ := exists_rat_btwn $ lt_trans ((sub_lt_self_iff x).2 ε0) ((lt_add_iff_pos_left x).2 ε0) in ⟨q, abs_sub_lt_iff.2 ⟨sub_lt.1 h₁, sub_lt_iff_lt_add.2 h₂⟩⟩ lemma abs_sub_round [floor_ring α] (x : α) : abs (x - round x) ≤ 1 / 2 := begin rw [round, abs_sub_le_iff], have := floor_le (x + 1 / 2), have := lt_floor_add_one (x + 1 / 2), split; linarith end instance : archimedean ℚ := archimedean_iff_rat_le.2 $ λ q, ⟨q, by rw rat.cast_id⟩ @[simp] theorem rat.cast_round {α : Type*} [discrete_linear_ordered_field α] [archimedean α] (x : ℚ) : by haveI := archimedean.floor_ring α; exact round (x:α) = round x := have ((x + (1 : ℚ) / (2 : ℚ) : ℚ) : α) = x + 1 / 2, by simp, by rw [round, round, ← this, rat.cast_floor] end
22f19ac5d7f9748f1241533bbaf8cd2b5a383831
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/order/interval.lean
bdaa1250c6a6ddabd4fa69577bb1d66607b51f19
[ "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
18,557
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.intervals.basic import data.set.lattice import data.set_like.basic /-! # Order intervals > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines (nonempty) closed intervals in an order (see `set.Icc`). This is a prototype for interval arithmetic. ## Main declarations * `nonempty_interval`: Nonempty intervals. Pairs where the second element is greater than the first. * `interval`: Intervals. Either `∅` or a nonempty interval. -/ open function order_dual set variables {α β γ δ : Type*} {ι : Sort*} {κ : ι → Sort*} /-- The nonempty closed intervals in an order. We define intervals by the pair of endpoints `fst`, `snd`. To convert intervals to the set of elements between these endpoints, use the coercion `nonempty_interval α → set α`. -/ @[ext] structure nonempty_interval (α : Type*) [has_le α] extends α × α := (fst_le_snd : fst ≤ snd) namespace nonempty_interval section has_le variables [has_le α] {s t : nonempty_interval α} lemma to_prod_injective : injective (to_prod : nonempty_interval α → α × α) := λ s t, (ext_iff _ _).2 /-- The injection that induces the order on intervals. -/ def to_dual_prod : nonempty_interval α → αᵒᵈ × α := to_prod @[simp] lemma to_dual_prod_apply (s : nonempty_interval α) : s.to_dual_prod = (to_dual s.fst, s.snd) := prod.mk.eta.symm lemma to_dual_prod_injective : injective (to_dual_prod : nonempty_interval α → αᵒᵈ × α) := to_prod_injective instance [is_empty α] : is_empty (nonempty_interval α) := ⟨λ s, is_empty_elim s.fst⟩ instance [subsingleton α] : subsingleton (nonempty_interval α) := to_dual_prod_injective.subsingleton instance : has_le (nonempty_interval α) := ⟨λ s t, t.fst ≤ s.fst ∧ s.snd ≤ t.snd⟩ lemma le_def : s ≤ t ↔ t.fst ≤ s.fst ∧ s.snd ≤ t.snd := iff.rfl /-- `to_dual_prod` as an order embedding. -/ @[simps] def to_dual_prod_hom : nonempty_interval α ↪o αᵒᵈ × α := { to_fun := to_dual_prod, inj' := to_dual_prod_injective, map_rel_iff' := λ _ _, iff.rfl } /-- Turn an interval into an interval in the dual order. -/ def dual : nonempty_interval α ≃ nonempty_interval αᵒᵈ := { to_fun := λ s, ⟨s.to_prod.swap, s.fst_le_snd⟩, inv_fun := λ s, ⟨s.to_prod.swap, s.fst_le_snd⟩, left_inv := λ s, ext _ _ $ prod.swap_swap _, right_inv := λ s, ext _ _ $ prod.swap_swap _ } @[simp] lemma fst_dual (s : nonempty_interval α) : s.dual.fst = to_dual s.snd := rfl @[simp] lemma snd_dual (s : nonempty_interval α) : s.dual.snd = to_dual s.fst := rfl end has_le section preorder variables [preorder α] [preorder β] [preorder γ] [preorder δ] {s : nonempty_interval α} {x : α × α} {a : α} instance : preorder (nonempty_interval α) := preorder.lift to_dual_prod instance : has_coe_t (nonempty_interval α) (set α) := ⟨λ s, Icc s.fst s.snd⟩ @[priority 100] instance : has_mem α (nonempty_interval α) := ⟨λ a s, a ∈ (s : set α)⟩ @[simp] lemma mem_mk {hx : x.1 ≤ x.2} : a ∈ mk x hx ↔ x.1 ≤ a ∧ a ≤ x.2 := iff.rfl lemma mem_def : a ∈ s ↔ s.fst ≤ a ∧ a ≤ s.snd := iff.rfl @[simp] lemma coe_nonempty (s : nonempty_interval α) : (s : set α).nonempty := nonempty_Icc.2 s.fst_le_snd /-- `{a}` as an interval. -/ @[simps] def pure (a : α) : nonempty_interval α := ⟨⟨a, a⟩, le_rfl⟩ lemma mem_pure_self (a : α) : a ∈ pure a := ⟨le_rfl, le_rfl⟩ lemma pure_injective : injective (pure : α → nonempty_interval α) := λ s t, congr_arg $ prod.fst ∘ to_prod @[simp] lemma dual_pure (a : α) : (pure a).dual = pure (to_dual a) := rfl instance [inhabited α] : inhabited (nonempty_interval α) := ⟨pure default⟩ instance : ∀ [nonempty α], nonempty (nonempty_interval α) := nonempty.map pure instance [nontrivial α] : nontrivial (nonempty_interval α) := pure_injective.nontrivial /-- Pushforward of nonempty intervals. -/ @[simps] def map (f : α →o β) (a : nonempty_interval α) : nonempty_interval β := ⟨a.to_prod.map f f, f.mono a.fst_le_snd⟩ @[simp] lemma map_pure (f : α →o β) (a : α) : (pure a).map f = pure (f a) := rfl @[simp] lemma map_map (g : β →o γ) (f : α →o β) (a : nonempty_interval α) : (a.map f).map g = a.map (g.comp f) := rfl @[simp] lemma dual_map (f : α →o β) (a : nonempty_interval α) : (a.map f).dual = a.dual.map f.dual := rfl /-- Binary pushforward of nonempty intervals. -/ @[simps] def map₂ (f : α → β → γ) (h₀ : ∀ b, monotone (λ a, f a b)) (h₁ : ∀ a, monotone (f a)) : nonempty_interval α → nonempty_interval β → nonempty_interval γ := λ s t, ⟨(f s.fst t.fst, f s.snd t.snd), (h₀ _ s.fst_le_snd).trans $ h₁ _ t.fst_le_snd⟩ @[simp] lemma map₂_pure (f : α → β → γ) (h₀ h₁) (a : α) (b : β) : map₂ f h₀ h₁ (pure a) (pure b) = pure (f a b) := rfl @[simp] lemma dual_map₂ (f : α → β → γ) (h₀ h₁ s t) : (map₂ f h₀ h₁ s t).dual = map₂ (λ a b, to_dual $ f (of_dual a) $ of_dual b) (λ _, (h₀ _).dual) (λ _, (h₁ _).dual) s.dual t.dual := rfl variables [bounded_order α] instance : order_top (nonempty_interval α) := { top := ⟨⟨⊥, ⊤⟩, bot_le⟩, le_top := λ a, ⟨bot_le, le_top⟩ } @[simp] lemma dual_top : (⊤ : nonempty_interval α).dual = ⊤ := rfl end preorder section partial_order variables [partial_order α] [partial_order β] {s t : nonempty_interval α} {x : α × α} {a b : α} instance : partial_order (nonempty_interval α) := partial_order.lift _ to_dual_prod_injective /-- Consider a nonempty interval `[a, b]` as the set `[a, b]`. -/ def coe_hom : nonempty_interval α ↪o set α := order_embedding.of_map_le_iff (λ s, Icc s.fst s.snd) (λ s t, Icc_subset_Icc_iff s.fst_le_snd) instance : set_like (nonempty_interval α) α := { coe := λ s, Icc s.fst s.snd, coe_injective' := coe_hom.injective } @[simp, norm_cast] lemma coe_subset_coe : (s : set α) ⊆ t ↔ s ≤ t := (@coe_hom α _).le_iff_le @[simp, norm_cast] lemma coe_ssubset_coe : (s : set α) ⊂ t ↔ s < t := (@coe_hom α _).lt_iff_lt @[simp] lemma coe_coe_hom : (coe_hom : nonempty_interval α → set α) = coe := rfl @[simp, norm_cast] lemma coe_pure (a : α) : (pure a : set α) = {a} := Icc_self _ @[simp] lemma mem_pure : b ∈ pure a ↔ b = a := by rw [←set_like.mem_coe, coe_pure, mem_singleton_iff] @[simp, norm_cast] lemma coe_top [bounded_order α] : ((⊤ : nonempty_interval α) : set α) = univ := Icc_bot_top @[simp, norm_cast] lemma coe_dual (s : nonempty_interval α) : (s.dual : set αᵒᵈ) = of_dual ⁻¹' s := dual_Icc lemma subset_coe_map (f : α →o β) (s : nonempty_interval α) : f '' s ⊆ s.map f := image_subset_iff.2 $ λ a ha, ⟨f.mono ha.1, f.mono ha.2⟩ end partial_order section lattice variables [lattice α] instance : has_sup (nonempty_interval α) := ⟨λ s t, ⟨⟨s.fst ⊓ t.fst, s.snd ⊔ t.snd⟩, inf_le_left.trans $ s.fst_le_snd.trans le_sup_left⟩⟩ instance : semilattice_sup (nonempty_interval α) := to_dual_prod_injective.semilattice_sup _ $ λ _ _, rfl @[simp] lemma fst_sup (s t : nonempty_interval α) : (s ⊔ t).fst = s.fst ⊓ t.fst := rfl @[simp] lemma snd_sup (s t : nonempty_interval α) : (s ⊔ t).snd = s.snd ⊔ t.snd := rfl end lattice end nonempty_interval /-- The closed intervals in an order. We represent intervals either as `⊥` or a nonempty interval given by its endpoints `fst`, `snd`. To convert intervals to the set of elements between these endpoints, use the coercion `interval α → set α`. -/ @[derive [inhabited, has_le, order_bot]] def interval (α : Type*) [has_le α] := with_bot (nonempty_interval α) namespace interval section has_le variables [has_le α] {s t : interval α} instance : has_coe_t (nonempty_interval α) (interval α) := with_bot.has_coe_t instance can_lift : can_lift (interval α) (nonempty_interval α) coe (λ r, r ≠ ⊥) := with_bot.can_lift lemma coe_injective : injective (coe : nonempty_interval α → interval α) := with_bot.coe_injective @[simp, norm_cast] lemma coe_inj {s t : nonempty_interval α} : (s : interval α) = t ↔ s = t := with_bot.coe_inj @[protected] lemma «forall» {p : interval α → Prop} : (∀ s, p s) ↔ p ⊥ ∧ ∀ s : nonempty_interval α, p s := option.forall @[protected] lemma «exists» {p : interval α → Prop} : (∃ s, p s) ↔ p ⊥ ∨ ∃ s : nonempty_interval α, p s := option.exists instance [is_empty α] : unique (interval α) := option.unique /-- Turn an interval into an interval in the dual order. -/ def dual : interval α ≃ interval αᵒᵈ := nonempty_interval.dual.option_congr end has_le section preorder variables [preorder α] [preorder β] [preorder γ] instance : preorder (interval α) := with_bot.preorder /-- `{a}` as an interval. -/ def pure (a : α) : interval α := nonempty_interval.pure a lemma pure_injective : injective (pure : α → interval α) := coe_injective.comp nonempty_interval.pure_injective @[simp] lemma dual_pure (a : α) : (pure a).dual = pure (to_dual a) := rfl @[simp] lemma dual_bot : (⊥ : interval α).dual = ⊥ := rfl @[simp] lemma pure_ne_bot {a : α} : pure a ≠ ⊥ := with_bot.coe_ne_bot @[simp] lemma bot_ne_pure {a : α} : ⊥ ≠ pure a := with_bot.bot_ne_coe instance [nonempty α] : nontrivial (interval α) := option.nontrivial /-- Pushforward of intervals. -/ def map (f : α →o β) : interval α → interval β := with_bot.map (nonempty_interval.map f) @[simp] lemma map_pure (f : α →o β) (a : α) : (pure a).map f = pure (f a) := rfl @[simp] lemma map_map (g : β →o γ) (f : α →o β) (s : interval α) : (s.map f).map g = s.map (g.comp f) := option.map_map _ _ _ @[simp] lemma dual_map (f : α →o β) (s : interval α) : (s.map f).dual = s.dual.map f.dual := by { cases s, { refl }, { exact with_bot.map_comm rfl _ } } variables [bounded_order α] instance : bounded_order (interval α) := with_bot.bounded_order @[simp] lemma dual_top : (⊤ : interval α).dual = ⊤ := rfl end preorder section partial_order variables [partial_order α] [partial_order β] {s t : interval α} {a b : α} instance : partial_order (interval α) := with_bot.partial_order /-- Consider a interval `[a, b]` as the set `[a, b]`. -/ def coe_hom : interval α ↪o set α := order_embedding.of_map_le_iff (λ s, match s with | ⊥ := ∅ | some s := s end) (λ s t, match s, t with | ⊥, t := iff_of_true bot_le bot_le | some s, ⊥ := iff_of_false (λ h, s.coe_nonempty.ne_empty $ le_bot_iff.1 h) (with_bot.not_coe_le_bot _) | some s, some t := (@nonempty_interval.coe_hom α _).le_iff_le.trans with_bot.some_le_some.symm end) instance : set_like (interval α) α := { coe := coe_hom, coe_injective' := coe_hom.injective } @[simp, norm_cast] lemma coe_subset_coe : (s : set α) ⊆ t ↔ s ≤ t := (@coe_hom α _).le_iff_le @[simp, norm_cast] lemma coe_ssubset_coe : (s : set α) ⊂ t ↔ s < t := (@coe_hom α _).lt_iff_lt @[simp, norm_cast] lemma coe_pure (a : α) : (pure a : set α) = {a} := Icc_self _ @[simp, norm_cast] lemma coe_coe (s : nonempty_interval α) : ((s : interval α) : set α) = s := rfl @[simp, norm_cast] lemma coe_bot : ((⊥ : interval α) : set α) = ∅ := rfl @[simp, norm_cast] lemma coe_top [bounded_order α] : ((⊤ : interval α) : set α) = univ := Icc_bot_top @[simp, norm_cast] lemma coe_dual (s : interval α) : (s.dual : set αᵒᵈ) = of_dual ⁻¹' s := by { cases s, { refl }, exact s.coe_dual } lemma subset_coe_map (f : α →o β) : ∀ s : interval α, f '' s ⊆ s.map f | ⊥ := by simp | (s : nonempty_interval α) := s.subset_coe_map _ @[simp] lemma mem_pure : b ∈ pure a ↔ b = a := by rw [←set_like.mem_coe, coe_pure, mem_singleton_iff] lemma mem_pure_self (a : α) : a ∈ pure a := mem_pure.2 rfl end partial_order section lattice variables [lattice α] instance : semilattice_sup (interval α) := with_bot.semilattice_sup section decidable variables [@decidable_rel α (≤)] instance : lattice (interval α) := { inf := λ s t, match s, t with | ⊥, t := ⊥ | s, ⊥ := ⊥ | some s, some t := if h : s.fst ≤ t.snd ∧ t.fst ≤ s.snd then some ⟨⟨s.fst ⊔ t.fst, s.snd ⊓ t.snd⟩, sup_le (le_inf s.fst_le_snd h.1) $ le_inf h.2 t.fst_le_snd⟩ else ⊥ end, inf_le_left := λ s t, match s, t with | ⊥, ⊥ := bot_le | ⊥, some t := bot_le | some s, ⊥ := bot_le | some s, some t := begin change dite _ _ _ ≤ _, split_ifs, { exact with_bot.some_le_some.2 ⟨le_sup_left, inf_le_left⟩ }, { exact bot_le } end end, inf_le_right := λ s t, match s, t with | ⊥, ⊥ := bot_le | ⊥, some t := bot_le | some s, ⊥ := bot_le | some s, some t := begin change dite _ _ _ ≤ _, split_ifs, { exact with_bot.some_le_some.2 ⟨le_sup_right, inf_le_right⟩ }, { exact bot_le } end end, le_inf := λ s t c, match s, t, c with | ⊥, t, c := λ _ _, bot_le | some s, t, c := λ hb hc, begin lift t to nonempty_interval α using ne_bot_of_le_ne_bot with_bot.coe_ne_bot hb, lift c to nonempty_interval α using ne_bot_of_le_ne_bot with_bot.coe_ne_bot hc, change _ ≤ dite _ _ _, simp only [with_bot.some_eq_coe, with_bot.coe_le_coe] at ⊢ hb hc, rw [dif_pos, with_bot.coe_le_coe], exact ⟨sup_le hb.1 hc.1, le_inf hb.2 hc.2⟩, exact ⟨hb.1.trans $ s.fst_le_snd.trans hc.2, hc.1.trans $ s.fst_le_snd.trans hb.2⟩, end end, ..interval.semilattice_sup } @[simp, norm_cast] lemma coe_inf (s t : interval α) : (↑(s ⊓ t) : set α) = s ∩ t := begin cases s, { rw [with_bot.none_eq_bot, bot_inf_eq], exact (empty_inter _).symm }, cases t, { rw [with_bot.none_eq_bot, inf_bot_eq], exact (inter_empty _).symm }, refine (_ : coe (dite _ _ _) = _).trans Icc_inter_Icc.symm, split_ifs, { refl }, { exact (Icc_eq_empty $ λ H, h ⟨le_sup_left.trans $ H.trans inf_le_right, le_sup_right.trans $ H.trans inf_le_left⟩).symm } end end decidable @[simp, norm_cast] lemma disjoint_coe (s t : interval α) : disjoint (s : set α) t ↔ disjoint s t := begin classical, rw [disjoint_iff_inf_le, disjoint_iff_inf_le, le_eq_subset, ←coe_subset_coe, coe_inf], refl end end lattice end interval namespace nonempty_interval section preorder variables [preorder α] {s : nonempty_interval α} {a : α} @[simp, norm_cast] lemma coe_pure_interval (a : α) : (pure a : interval α) = interval.pure a := rfl @[simp, norm_cast] lemma coe_eq_pure : (s : interval α) = interval.pure a ↔ s = pure a := by rw [←interval.coe_inj, coe_pure_interval] @[simp, norm_cast] lemma coe_top_interval [bounded_order α] : ((⊤ : nonempty_interval α) : interval α) = ⊤ := rfl end preorder @[simp, norm_cast] lemma mem_coe_interval [partial_order α] {s : nonempty_interval α} {x : α} : x ∈ (s : interval α) ↔ x ∈ s := iff.rfl @[simp, norm_cast] lemma coe_sup_interval [lattice α] (s t : nonempty_interval α) : (↑(s ⊔ t) : interval α) = s ⊔ t := rfl end nonempty_interval namespace interval section complete_lattice variables [complete_lattice α] noncomputable instance [@decidable_rel α (≤)] : complete_lattice (interval α) := by classical; exact { Sup := λ S, if h : S ⊆ {⊥} then ⊥ else some ⟨⟨⨅ (s : nonempty_interval α) (h : ↑s ∈ S), s.fst, ⨆ (s : nonempty_interval α) (h : ↑s ∈ S), s.snd⟩, begin obtain ⟨s, hs, ha⟩ := not_subset.1 h, lift s to nonempty_interval α using ha, exact infi₂_le_of_le s hs (le_supr₂_of_le s hs s.fst_le_snd) end⟩, le_Sup := λ s s ha, begin split_ifs, { exact (h ha).le }, cases s, { exact bot_le }, { exact with_bot.some_le_some.2 ⟨infi₂_le _ ha, le_supr₂_of_le _ ha le_rfl⟩ } end, Sup_le := λ s s ha, begin split_ifs, { exact bot_le }, obtain ⟨b, hs, hb⟩ := not_subset.1 h, lift s to nonempty_interval α using ne_bot_of_le_ne_bot hb (ha _ hs), exact with_bot.coe_le_coe.2 ⟨le_infi₂ $ λ c hc, (with_bot.coe_le_coe.1 $ ha _ hc).1, supr₂_le $ λ c hc, (with_bot.coe_le_coe.1 $ ha _ hc).2⟩, end, Inf := λ S, if h : ⊥ ∉ S ∧ ∀ ⦃s : nonempty_interval α⦄, ↑s ∈ S → ∀ ⦃t : nonempty_interval α⦄, ↑t ∈ S → s.fst ≤ t.snd then some ⟨⟨⨆ (s : nonempty_interval α) (h : ↑s ∈ S), s.fst, ⨅ (s : nonempty_interval α) (h : ↑s ∈ S), s.snd⟩, supr₂_le $ λ s hs, le_infi₂ $ h.2 hs⟩ else ⊥, Inf_le := λ s s ha, begin split_ifs, { lift s to nonempty_interval α using ne_of_mem_of_not_mem ha h.1, exact with_bot.coe_le_coe.2 ⟨le_supr₂ s ha, infi₂_le s ha⟩ }, { exact bot_le } end, le_Inf := λ S s ha, begin cases s, { exact bot_le }, split_ifs, { exact with_bot.some_le_some.2 ⟨supr₂_le $ λ t hb, (with_bot.coe_le_coe.1 $ ha _ hb).1, le_infi₂ $ λ t hb, (with_bot.coe_le_coe.1 $ ha _ hb).2⟩ }, rw [not_and_distrib, not_not] at h, cases h, { exact ha _ h }, cases h (λ t hb c hc, (with_bot.coe_le_coe.1 $ ha _ hb).1.trans $ s.fst_le_snd.trans (with_bot.coe_le_coe.1 $ ha _ hc).2), end, ..interval.lattice, ..interval.bounded_order } @[simp, norm_cast] lemma coe_Inf [@decidable_rel α (≤)] (S : set (interval α)) : ↑(Inf S) = ⋂ s ∈ S, (s : set α) := begin change coe (dite _ _ _) = _, split_ifs, { ext, simp [with_bot.some_eq_coe, interval.forall, h.1, ←forall_and_distrib, ←nonempty_interval.mem_def] }, simp_rw [not_and_distrib, not_not] at h, cases h, { refine (eq_empty_of_subset_empty _).symm, exact Inter₂_subset_of_subset _ h subset.rfl }, { refine (not_nonempty_iff_eq_empty.1 _).symm, rintro ⟨x, hx⟩, rw mem_Inter₂ at hx, exact h (λ s ha t hb, (hx _ ha).1.trans (hx _ hb).2) } end @[simp, norm_cast] lemma coe_infi [@decidable_rel α (≤)] (f : ι → interval α) : ↑(⨅ i, f i) = ⋂ i, (f i : set α) := by simp [infi] @[simp, norm_cast] lemma coe_infi₂ [@decidable_rel α (≤)] (f : Π i, κ i → interval α) : ↑(⨅ i j, f i j) = ⋂ i j, (f i j : set α) := by simp_rw [coe_infi] end complete_lattice end interval
7e602896f174df715e550319b3876a8aa4926bbd
8d65764a9e5f0923a67fc435eb1a5a1d02fd80e3
/src/algebra/ordered_sub.lean
051c4bd7c1b48b046bbf05c20dda590fa429aa72
[ "Apache-2.0" ]
permissive
troyjlee/mathlib
e18d4b8026e32062ab9e89bc3b003a5d1cfec3f5
45e7eb8447555247246e3fe91c87066506c14875
refs/heads/master
1,689,248,035,046
1,629,470,528,000
1,629,470,528,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
25,609
lean
/- Copyright (c) 2021 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn -/ import algebra.ordered_monoid /-! # Ordered Subtraction This file proves lemmas relating (truncated) subtraction with an order. We provide a class `has_ordered_sub` stating that `a - b ≤ c ↔ a ≤ c + b`. The subtraction discussed here could both be normal subtraction in an additive group or truncated subtraction on a canonically ordered monoid (`ℕ`, `multiset`, `enat`, `ennreal`, ...) ## Implementation details `has_ordered_sub` is a mixin type-class, so that we can use the results in this file even in cases where we don't have a `canonically_ordered_add_monoid` instance (even though that is our main focus). Conversely, this means we can use `canonically_ordered_add_monoid` without necessarily having to define a subtraction. The results in this file are ordered by the type-class assumption needed to prove it. This means that similar results might not be close to each other. Furthermore, we don't prove implications if a bi-implication can be proven under the same assumptions. Many results about this subtraction are primed, to not conflict with similar lemmas about ordered groups. We provide a second version of most results that require `[contravariant_class α α (+) (≤)]`. In the second version we replace this type-class assumption by explicit `add_le_cancellable` assumptions. TODO: maybe we should make a multiplicative version of this, so that we can replace some identical lemmas about subtraction/division in `ordered_[add_]comm_group` with these. -/ variables {α : Type*} /-- `has_ordered_sub α` means that `α` has a subtraction characterized by `a - b ≤ c ↔ a ≤ c + b`. In other words, `a - b` is the least `c` such that `a ≤ b + c`. This is satisfied both by the subtraction in additive ordered groups and by truncated subtraction in canonically ordered monoids on many specific types. -/ class has_ordered_sub (α : Type*) [preorder α] [has_add α] [has_sub α] := (sub_le_iff_right : ∀ a b c : α, a - b ≤ c ↔ a ≤ c + b) section ordered_add_comm_monoid variables {a b c d : α} [partial_order α] [add_comm_monoid α] [has_sub α] [has_ordered_sub α] @[simp] lemma sub_le_iff_right : a - b ≤ c ↔ a ≤ c + b := has_ordered_sub.sub_le_iff_right a b c lemma sub_le_iff_left : a - b ≤ c ↔ a ≤ b + c := by rw [sub_le_iff_right, add_comm] lemma le_add_sub : a ≤ b + (a - b) := sub_le_iff_left.mp le_rfl /-- See `add_sub_cancel_left` for the equality if `contravariant_class α α (+) (≤)`. -/ lemma add_sub_le_left : a + b - a ≤ b := sub_le_iff_left.mpr le_rfl /-- See `add_sub_cancel_right` for the equality if `contravariant_class α α (+) (≤)`. -/ lemma add_sub_le_right : a + b - b ≤ a := sub_le_iff_right.mpr le_rfl lemma le_sub_add : b ≤ (b - a) + a := sub_le_iff_right.mp le_rfl lemma sub_le_sub_right' (h : a ≤ b) (c : α) : a - c ≤ b - c := sub_le_iff_left.mpr $ h.trans le_add_sub lemma sub_le_iff_sub_le : a - b ≤ c ↔ a - c ≤ b := by rw [sub_le_iff_left, sub_le_iff_right] lemma sub_sub' (b a c : α) : b - a - c = b - (a + c) := begin apply le_antisymm, { rw [sub_le_iff_left, sub_le_iff_left, ← add_assoc, ← sub_le_iff_left] }, { rw [sub_le_iff_left, add_assoc, ← sub_le_iff_left, ← sub_le_iff_left] } end /-- See `sub_sub_cancel_of_le` for the equality. -/ lemma sub_sub_le : b - (b - a) ≤ a := sub_le_iff_right.mpr le_add_sub section cov variable [covariant_class α α (+) (≤)] lemma sub_le_sub_left' (h : a ≤ b) (c : α) : c - b ≤ c - a := sub_le_iff_left.mpr $ le_add_sub.trans $ add_le_add_right h _ lemma sub_le_sub' (hab : a ≤ b) (hcd : c ≤ d) : a - d ≤ b - c := (sub_le_sub_right' hab _).trans $ sub_le_sub_left' hcd _ lemma sub_add_eq_sub_sub' : a - (b + c) = a - b - c := begin refine le_antisymm (sub_le_iff_left.mpr _) (sub_le_iff_left.mpr $ sub_le_iff_left.mpr _), { rw [add_assoc], refine le_trans le_add_sub (add_le_add_left le_add_sub _) }, { rw [← add_assoc], apply le_add_sub } end lemma sub_add_eq_sub_sub_swap' : a - (b + c) = a - c - b := by { rw [add_comm], exact sub_add_eq_sub_sub' } lemma add_le_add_add_sub : a + b ≤ (a + c) + (b - c) := by { rw [add_assoc], exact add_le_add_left le_add_sub a } lemma sub_right_comm' : a - b - c = a - c - b := by simp_rw [← sub_add_eq_sub_sub', add_comm] /-- See `add_sub_assoc_of_le` for the equality. -/ lemma add_sub_le_assoc : a + b - c ≤ a + (b - c) := by { rw [sub_le_iff_left, add_left_comm], exact add_le_add_left le_add_sub a } lemma le_sub_add_add : a + b ≤ (a - c) + (b + c) := by { rw [add_comm a, add_comm (a - c)], exact add_le_add_add_sub } lemma sub_le_sub_add_sub : a - c ≤ (a - b) + (b - c) := begin rw [sub_le_iff_left, ← add_assoc, add_right_comm], refine le_add_sub.trans (add_le_add_right le_add_sub _), end lemma sub_sub_sub_le_sub : (c - a) - (c - b) ≤ b - a := begin rw [sub_le_iff_left, sub_le_iff_left, add_left_comm], refine le_sub_add.trans (add_le_add_left le_add_sub _), end end cov /-! Lemmas that assume that an element is `add_le_cancellable`. -/ namespace add_le_cancellable protected lemma le_add_sub_swap (hb : add_le_cancellable b) : a ≤ b + a - b := hb le_add_sub protected lemma le_add_sub (hb : add_le_cancellable b) : a ≤ a + b - b := by { rw [add_comm], exact hb.le_add_sub_swap } protected lemma sub_eq_of_eq_add (hb : add_le_cancellable b) (h : a = c + b) : a - b = c := le_antisymm (sub_le_iff_right.mpr h.le) $ by { rw h, exact hb.le_add_sub } protected lemma eq_sub_of_add_eq (hc : add_le_cancellable c) (h : a + c = b) : a = b - c := (hc.sub_eq_of_eq_add h.symm).symm @[simp] protected lemma add_sub_cancel_right (hb : add_le_cancellable b) : a + b - b = a := hb.sub_eq_of_eq_add $ by rw [add_comm] @[simp] protected lemma add_sub_cancel_left (ha : add_le_cancellable a) : a + b - a = b := ha.sub_eq_of_eq_add $ add_comm a b protected lemma le_sub_of_add_le_left (ha : add_le_cancellable a) (h : a + b ≤ c) : b ≤ c - a := ha $ h.trans le_add_sub protected lemma le_sub_of_add_le_right (hb : add_le_cancellable b) (h : a + b ≤ c) : a ≤ c - b := hb.le_sub_of_add_le_left $ by rwa [add_comm] protected lemma lt_add_of_sub_lt_left (hb : add_le_cancellable b) (h : a - b < c) : a < b + c := begin rw [lt_iff_le_and_ne, ← sub_le_iff_left], refine ⟨h.le, _⟩, rintro rfl, simpa [hb] using h, end protected lemma lt_add_of_sub_lt_right (hc : add_le_cancellable c) (h : a - c < b) : a < b + c := begin rw [lt_iff_le_and_ne, ← sub_le_iff_right], refine ⟨h.le, _⟩, rintro rfl, simpa [hc] using h, end end add_le_cancellable /-! Lemmas where addition is order-reflecting. -/ section contra variable [contravariant_class α α (+) (≤)] lemma le_add_sub_swap : a ≤ b + a - b := contravariant.add_le_cancellable.le_add_sub_swap lemma le_add_sub' : a ≤ a + b - b := contravariant.add_le_cancellable.le_add_sub lemma sub_eq_of_eq_add'' (h : a = c + b) : a - b = c := contravariant.add_le_cancellable.sub_eq_of_eq_add h lemma eq_sub_of_add_eq'' (h : a + c = b) : a = b - c := contravariant.add_le_cancellable.eq_sub_of_add_eq h @[simp] lemma add_sub_cancel_right : a + b - b = a := contravariant.add_le_cancellable.add_sub_cancel_right @[simp] lemma add_sub_cancel_left : a + b - a = b := contravariant.add_le_cancellable.add_sub_cancel_left lemma le_sub_of_add_le_left' (h : a + b ≤ c) : b ≤ c - a := contravariant.add_le_cancellable.le_sub_of_add_le_left h lemma le_sub_of_add_le_right' (h : a + b ≤ c) : a ≤ c - b := contravariant.add_le_cancellable.le_sub_of_add_le_right h lemma lt_add_of_sub_lt_left' (h : a - b < c) : a < b + c := contravariant.add_le_cancellable.lt_add_of_sub_lt_left h lemma lt_add_of_sub_lt_right' (h : a - c < b) : a < b + c := contravariant.add_le_cancellable.lt_add_of_sub_lt_right h end contra section both variables [covariant_class α α (+) (≤)] [contravariant_class α α (+) (≤)] lemma add_sub_add_right_eq_sub' : (a + c) - (b + c) = a - b := begin apply le_antisymm, { rw [sub_le_iff_left, add_right_comm], exact add_le_add_right le_add_sub c }, { rw [sub_le_iff_left, add_comm b], apply le_of_add_le_add_right, rw [add_assoc], exact le_sub_add } end lemma add_sub_add_eq_sub_left' (a b c : α) : (a + b) - (a + c) = b - c := by rw [add_comm a b, add_comm a c, add_sub_add_right_eq_sub'] end both end ordered_add_comm_monoid /-! Lemmas in a linearly ordered monoid. -/ section linear_order variables {a b c d : α} [linear_order α] [add_comm_monoid α] [has_sub α] [has_ordered_sub α] /-- See `lt_of_sub_lt_sub_right_of_le` for a weaker statement in a partial order. -/ lemma lt_of_sub_lt_sub_right (h : a - c < b - c) : a < b := lt_imp_lt_of_le_imp_le (λ h, sub_le_sub_right' h c) h section cov variable [covariant_class α α (+) (≤)] /-- See `lt_of_sub_lt_sub_left_of_le` for a weaker statement in a partial order. -/ lemma lt_of_sub_lt_sub_left (h : a - b < a - c) : c < b := lt_imp_lt_of_le_imp_le (λ h, sub_le_sub_left' h a) h end cov end linear_order /-! Lemmas in a canonically ordered monoid. -/ section canonically_ordered_add_monoid variables [canonically_ordered_add_monoid α] [has_sub α] [has_ordered_sub α] {a b c d : α} lemma add_sub_cancel_of_le (h : a ≤ b) : a + (b - a) = b := begin refine le_antisymm _ le_add_sub, obtain ⟨c, rfl⟩ := le_iff_exists_add.1 h, exact add_le_add_left add_sub_le_left a, end lemma sub_add_cancel_of_le (h : a ≤ b) : b - a + a = b := by { rw [add_comm], exact add_sub_cancel_of_le h } lemma add_sub_cancel_iff_le : a + (b - a) = b ↔ a ≤ b := ⟨λ h, le_iff_exists_add.mpr ⟨b - a, h.symm⟩, add_sub_cancel_of_le⟩ lemma sub_add_cancel_iff_le : b - a + a = b ↔ a ≤ b := by { rw [add_comm], exact add_sub_cancel_iff_le } lemma add_le_of_le_sub_right_of_le (h : b ≤ c) (h2 : a ≤ c - b) : a + b ≤ c := (add_le_add_right h2 b).trans_eq $ sub_add_cancel_of_le h lemma add_le_of_le_sub_left_of_le (h : a ≤ c) (h2 : b ≤ c - a) : a + b ≤ c := (add_le_add_left h2 a).trans_eq $ add_sub_cancel_of_le h lemma sub_le_sub_iff_right' (h : c ≤ b) : a - c ≤ b - c ↔ a ≤ b := by rw [sub_le_iff_right, sub_add_cancel_of_le h] lemma sub_left_inj' (h1 : c ≤ a) (h2 : c ≤ b) : a - c = b - c ↔ a = b := by simp_rw [le_antisymm_iff, sub_le_sub_iff_right' h1, sub_le_sub_iff_right' h2] /-- See `lt_of_sub_lt_sub_right` for a stronger statement in a linear order. -/ lemma lt_of_sub_lt_sub_right_of_le (h : c ≤ b) (h2 : a - c < b - c) : a < b := by { refine ((sub_le_sub_iff_right' h).mp h2.le).lt_of_ne _, rintro rfl, exact h2.false } lemma sub_eq_zero_iff_le : a - b = 0 ↔ a ≤ b := by rw [← nonpos_iff_eq_zero, sub_le_iff_left, add_zero] @[simp] lemma sub_self' : a - a = 0 := sub_eq_zero_iff_le.mpr le_rfl @[simp] lemma sub_le_self' : a - b ≤ a := sub_le_iff_left.mpr $ le_add_left le_rfl @[simp] lemma sub_zero' : a - 0 = a := le_antisymm sub_le_self' $ le_add_sub.trans_eq $ zero_add _ @[simp] lemma zero_sub' : 0 - a = 0 := sub_eq_zero_iff_le.mpr $ zero_le a lemma sub_self_add (a b : α) : a - (a + b) = 0 := by { rw [sub_eq_zero_iff_le], apply self_le_add_right } lemma sub_inj_left (h₁ : a ≤ b) (h₂ : a ≤ c) (h₃ : b - a = c - a) : b = c := by rw [← sub_add_cancel_of_le h₁, ← sub_add_cancel_of_le h₂, h₃] lemma sub_pos_iff_not_le : 0 < a - b ↔ ¬ a ≤ b := by rw [pos_iff_ne_zero, ne.def, sub_eq_zero_iff_le] lemma sub_pos_of_lt' (h : a < b) : 0 < b - a := sub_pos_iff_not_le.mpr h.not_le lemma sub_add_sub_cancel'' (hab : b ≤ a) (hbc : c ≤ b) : (a - b) + (b - c) = a - c := begin convert sub_add_cancel_of_le (sub_le_sub_right' hab c) using 2, rw [sub_sub', add_sub_cancel_of_le hbc], end lemma sub_sub_sub_cancel_right' (h : c ≤ b) : (a - c) - (b - c) = a - b := by rw [sub_sub', add_sub_cancel_of_le h] /-! Lemmas that assume that an element is `add_le_cancellable`. -/ namespace add_le_cancellable protected lemma eq_sub_iff_add_eq_of_le (hc : add_le_cancellable c) (h : c ≤ b) : a = b - c ↔ a + c = b := begin split, { rintro rfl, exact sub_add_cancel_of_le h }, { rintro rfl, exact (hc.add_sub_cancel_right).symm } end protected lemma sub_eq_iff_eq_add_of_le (hb : add_le_cancellable b) (h : b ≤ a) : a - b = c ↔ a = c + b := by rw [eq_comm, hb.eq_sub_iff_add_eq_of_le h, eq_comm] protected lemma add_sub_assoc_of_le (hc : add_le_cancellable c) (h : c ≤ b) (a : α) : a + b - c = a + (b - c) := by conv_lhs { rw [← add_sub_cancel_of_le h, add_comm c, ← add_assoc, hc.add_sub_cancel_right] } protected lemma sub_add_eq_add_sub (hb : add_le_cancellable b) (h : b ≤ a) : a - b + c = a + c - b := by rw [add_comm a, hb.add_sub_assoc_of_le h, add_comm] protected lemma sub_sub_assoc (hbc : add_le_cancellable (b - c)) (h₁ : b ≤ a) (h₂ : c ≤ b) : a - (b - c) = a - b + c := by rw [hbc.sub_eq_iff_eq_add_of_le (sub_le_self'.trans h₁), add_assoc, add_sub_cancel_of_le h₂, sub_add_cancel_of_le h₁] protected lemma le_sub_iff_left (ha : add_le_cancellable a) (h : a ≤ c) : b ≤ c - a ↔ a + b ≤ c := ⟨add_le_of_le_sub_left_of_le h, ha.le_sub_of_add_le_left⟩ protected lemma le_sub_iff_right (ha : add_le_cancellable a) (h : a ≤ c) : b ≤ c - a ↔ b + a ≤ c := by { rw [add_comm], exact ha.le_sub_iff_left h } protected lemma sub_lt_iff_left (hb : add_le_cancellable b) (hba : b ≤ a) : a - b < c ↔ a < b + c := begin refine ⟨hb.lt_add_of_sub_lt_left, _⟩, intro h, refine (sub_le_iff_left.mpr h.le).lt_of_ne _, rintro rfl, exact h.ne' (add_sub_cancel_of_le hba) end protected lemma sub_lt_iff_right (hb : add_le_cancellable b) (hba : b ≤ a) : a - b < c ↔ a < c + b := by { rw [add_comm], exact hb.sub_lt_iff_left hba } protected lemma lt_sub_of_add_lt_right (hc : add_le_cancellable c) (h : a + c < b) : a < b - c := begin apply lt_of_le_of_ne, { rw [← add_sub_cancel_of_le h.le, add_right_comm, add_assoc], rw [hc.add_sub_assoc_of_le], refine le_self_add, refine le_add_self }, { rintro rfl, apply h.not_le, exact le_sub_add } end protected lemma lt_sub_of_add_lt_left (ha : add_le_cancellable a) (h : a + c < b) : c < b - a := by { apply ha.lt_sub_of_add_lt_right, rwa add_comm } protected lemma sub_lt_iff_sub_lt (hb : add_le_cancellable b) (hc : add_le_cancellable c) (h₁ : b ≤ a) (h₂ : c ≤ a) : a - b < c ↔ a - c < b := by rw [hb.sub_lt_iff_left h₁, hc.sub_lt_iff_right h₂] protected lemma le_sub_iff_le_sub (ha : add_le_cancellable a) (hc : add_le_cancellable c) (h₁ : a ≤ b) (h₂ : c ≤ b) : a ≤ b - c ↔ c ≤ b - a := by rw [ha.le_sub_iff_left h₁, hc.le_sub_iff_right h₂] protected lemma lt_sub_iff_right_of_le (hc : add_le_cancellable c) (h : c ≤ b) : a < b - c ↔ a + c < b := begin refine ⟨_, hc.lt_sub_of_add_lt_right⟩, intro h2, refine (add_le_of_le_sub_right_of_le h h2.le).lt_of_ne _, rintro rfl, apply h2.not_le, rw [hc.add_sub_cancel_right] end protected lemma lt_sub_iff_left_of_le (hc : add_le_cancellable c) (h : c ≤ b) : a < b - c ↔ c + a < b := by { rw [add_comm], exact hc.lt_sub_iff_right_of_le h } protected lemma lt_of_sub_lt_sub_left_of_le (hb : add_le_cancellable b) (hca : c ≤ a) (h : a - b < a - c) : c < b := begin conv_lhs at h { rw [← sub_add_cancel_of_le hca] }, exact lt_of_add_lt_add_left (hb.lt_add_of_sub_lt_right h), end protected lemma sub_le_sub_iff_left (ha : add_le_cancellable a) (hc : add_le_cancellable c) (h : c ≤ a) : a - b ≤ a - c ↔ c ≤ b := begin refine ⟨_, λ h, sub_le_sub_left' h a⟩, rw [sub_le_iff_left, ← hc.add_sub_assoc_of_le h, hc.le_sub_iff_right (h.trans le_add_self), add_comm b], apply ha, end protected lemma sub_right_inj (ha : add_le_cancellable a) (hb : add_le_cancellable b) (hc : add_le_cancellable c) (hba : b ≤ a) (hca : c ≤ a) : a - b = a - c ↔ b = c := by simp_rw [le_antisymm_iff, ha.sub_le_sub_iff_left hb hba, ha.sub_le_sub_iff_left hc hca, and_comm] protected lemma sub_lt_sub_right_of_le (hc : add_le_cancellable c) (h : c ≤ a) (h2 : a < b) : a - c < b - c := by { apply hc.lt_sub_of_add_lt_left, rwa [add_sub_cancel_of_le h] } protected lemma sub_inj_right (hab : add_le_cancellable (a - b)) (h₁ : b ≤ a) (h₂ : c ≤ a) (h₃ : a - b = a - c) : b = c := by { rw ← hab.inj, rw [sub_add_cancel_of_le h₁, h₃, sub_add_cancel_of_le h₂] } protected lemma sub_lt_sub_iff_left_of_le_of_le (hb : add_le_cancellable b) (hab : add_le_cancellable (a - b)) (h₁ : b ≤ a) (h₂ : c ≤ a) : a - b < a - c ↔ c < b := begin refine ⟨hb.lt_of_sub_lt_sub_left_of_le h₂, _⟩, intro h, refine (sub_le_sub_left' h.le _).lt_of_ne _, rintro h2, exact h.ne' (hab.sub_inj_right h₁ h₂ h2) end @[simp] protected lemma add_sub_sub_cancel (hac : add_le_cancellable (a - c)) (h : c ≤ a) : (a + b) - (a - c) = b + c := (hac.sub_eq_iff_eq_add_of_le $ sub_le_self'.trans le_self_add).mpr $ by rw [add_assoc, add_sub_cancel_of_le h, add_comm] protected lemma sub_sub_cancel_of_le (hba : add_le_cancellable (b - a)) (h : a ≤ b) : b - (b - a) = a := by rw [hba.sub_eq_iff_eq_add_of_le sub_le_self', add_sub_cancel_of_le h] end add_le_cancellable section contra /-! Lemmas where addition is order-reflecting. -/ variable [contravariant_class α α (+) (≤)] lemma eq_sub_iff_add_eq_of_le (h : c ≤ b) : a = b - c ↔ a + c = b := contravariant.add_le_cancellable.eq_sub_iff_add_eq_of_le h lemma sub_eq_iff_eq_add_of_le (h : b ≤ a) : a - b = c ↔ a = c + b := contravariant.add_le_cancellable.sub_eq_iff_eq_add_of_le h /-- See `add_sub_le_assoc` for an inequality. -/ lemma add_sub_assoc_of_le (h : c ≤ b) (a : α) : a + b - c = a + (b - c) := contravariant.add_le_cancellable.add_sub_assoc_of_le h a lemma sub_add_eq_add_sub' (h : b ≤ a) : a - b + c = a + c - b := contravariant.add_le_cancellable.sub_add_eq_add_sub h lemma sub_sub_assoc (h₁ : b ≤ a) (h₂ : c ≤ b) : a - (b - c) = a - b + c := contravariant.add_le_cancellable.sub_sub_assoc h₁ h₂ lemma le_sub_iff_left (h : a ≤ c) : b ≤ c - a ↔ a + b ≤ c := contravariant.add_le_cancellable.le_sub_iff_left h lemma le_sub_iff_right (h : a ≤ c) : b ≤ c - a ↔ b + a ≤ c := contravariant.add_le_cancellable.le_sub_iff_right h lemma sub_lt_iff_left (hbc : b ≤ a) : a - b < c ↔ a < b + c := contravariant.add_le_cancellable.sub_lt_iff_left hbc lemma sub_lt_iff_right (hbc : b ≤ a) : a - b < c ↔ a < c + b := contravariant.add_le_cancellable.sub_lt_iff_right hbc /-- This lemma (and some of its corollaries also holds for `ennreal`, but this proof doesn't work for it. Maybe we should add this lemma as field to `has_ordered_sub`? -/ lemma lt_sub_of_add_lt_right (h : a + c < b) : a < b - c := contravariant.add_le_cancellable.lt_sub_of_add_lt_right h lemma lt_sub_of_add_lt_left (h : a + c < b) : c < b - a := contravariant.add_le_cancellable.lt_sub_of_add_lt_left h lemma sub_lt_iff_sub_lt (h₁ : b ≤ a) (h₂ : c ≤ a) : a - b < c ↔ a - c < b := contravariant.add_le_cancellable.sub_lt_iff_sub_lt contravariant.add_le_cancellable h₁ h₂ lemma le_sub_iff_le_sub (h₁ : a ≤ b) (h₂ : c ≤ b) : a ≤ b - c ↔ c ≤ b - a := contravariant.add_le_cancellable.le_sub_iff_le_sub contravariant.add_le_cancellable h₁ h₂ /-- See `lt_sub_iff_right` for a stronger statement in a linear order. -/ lemma lt_sub_iff_right_of_le (h : c ≤ b) : a < b - c ↔ a + c < b := contravariant.add_le_cancellable.lt_sub_iff_right_of_le h /-- See `lt_sub_iff_left` for a stronger statement in a linear order. -/ lemma lt_sub_iff_left_of_le (h : c ≤ b) : a < b - c ↔ c + a < b := contravariant.add_le_cancellable.lt_sub_iff_left_of_le h /-- See `lt_of_sub_lt_sub_left` for a stronger statement in a linear order. -/ lemma lt_of_sub_lt_sub_left_of_le (hca : c ≤ a) (h : a - b < a - c) : c < b := contravariant.add_le_cancellable.lt_of_sub_lt_sub_left_of_le hca h lemma sub_le_sub_iff_left' (h : c ≤ a) : a - b ≤ a - c ↔ c ≤ b := contravariant.add_le_cancellable.sub_le_sub_iff_left contravariant.add_le_cancellable h lemma sub_right_inj' (hba : b ≤ a) (hca : c ≤ a) : a - b = a - c ↔ b = c := contravariant.add_le_cancellable.sub_right_inj contravariant.add_le_cancellable contravariant.add_le_cancellable hba hca lemma sub_lt_sub_right_of_le (h : c ≤ a) (h2 : a < b) : a - c < b - c := contravariant.add_le_cancellable.sub_lt_sub_right_of_le h h2 lemma sub_inj_right (h₁ : b ≤ a) (h₂ : c ≤ a) (h₃ : a - b = a - c) : b = c := contravariant.add_le_cancellable.sub_inj_right h₁ h₂ h₃ /-- See `sub_lt_sub_iff_left_of_le` for a stronger statement in a linear order. -/ lemma sub_lt_sub_iff_left_of_le_of_le (h₁ : b ≤ a) (h₂ : c ≤ a) : a - b < a - c ↔ c < b := contravariant.add_le_cancellable.sub_lt_sub_iff_left_of_le_of_le contravariant.add_le_cancellable h₁ h₂ @[simp] lemma add_sub_sub_cancel' (h : c ≤ a) : (a + b) - (a - c) = b + c := contravariant.add_le_cancellable.add_sub_sub_cancel h /-- See `sub_sub_le` for an inequality. -/ lemma sub_sub_cancel_of_le (h : a ≤ b) : b - (b - a) = a := contravariant.add_le_cancellable.sub_sub_cancel_of_le h end contra end canonically_ordered_add_monoid /-! Lemmas in a linearly canonically ordered monoid. -/ section canonically_linear_ordered_add_monoid variables [canonically_linear_ordered_add_monoid α] [has_sub α] [has_ordered_sub α] {a b c d : α} lemma sub_pos_iff_lt : 0 < a - b ↔ b < a := by rw [sub_pos_iff_not_le, not_le] lemma sub_eq_sub_min (a b : α) : a - b = a - min a b := begin cases le_total a b with h h, { rw [min_eq_left h, sub_self', sub_eq_zero_iff_le.mpr h] }, { rw [min_eq_right h] }, end namespace add_le_cancellable protected lemma lt_sub_iff_right (hc : add_le_cancellable c) : a < b - c ↔ a + c < b := ⟨lt_imp_lt_of_le_imp_le sub_le_iff_right.mpr, hc.lt_sub_of_add_lt_right⟩ protected lemma lt_sub_iff_left (hc : add_le_cancellable c) : a < b - c ↔ c + a < b := ⟨lt_imp_lt_of_le_imp_le sub_le_iff_left.mpr, hc.lt_sub_of_add_lt_left⟩ protected lemma sub_lt_sub_iff_right (hc : add_le_cancellable c) (h : c ≤ a) : a - c < b - c ↔ a < b := by rw [hc.lt_sub_iff_left, add_sub_cancel_of_le h] protected lemma lt_sub_iff_lt_sub (ha : add_le_cancellable a) (hc : add_le_cancellable c) : a < b - c ↔ c < b - a := by rw [hc.lt_sub_iff_left, ha.lt_sub_iff_right] protected lemma sub_lt_self (ha : add_le_cancellable a) (hb : add_le_cancellable b) (h₁ : 0 < a) (h₂ : 0 < b) : a - b < a := begin refine sub_le_self'.lt_of_ne _, intro h, rw [← h, sub_pos_iff_lt] at h₁, have := h.ge, rw [hb.le_sub_iff_left h₁.le, ha.add_le_iff_nonpos_left] at this, exact h₂.not_le this, end protected lemma sub_lt_self_iff (ha : add_le_cancellable a) (hb : add_le_cancellable b) : a - b < a ↔ 0 < a ∧ 0 < b := begin refine ⟨_, λ h, ha.sub_lt_self hb h.1 h.2⟩, intro h, refine ⟨(zero_le _).trans_lt h, (zero_le b).lt_of_ne _⟩, rintro rfl, rw [sub_zero'] at h, exact h.false end /-- See `lt_sub_iff_left_of_le_of_le` for a weaker statement in a partial order. -/ protected lemma sub_lt_sub_iff_left_of_le (ha : add_le_cancellable a) (hb : add_le_cancellable b) (h : b ≤ a) : a - b < a - c ↔ c < b := lt_iff_lt_of_le_iff_le $ ha.sub_le_sub_iff_left hb h end add_le_cancellable section contra variable [contravariant_class α α (+) (≤)] /-- See `lt_sub_iff_right_of_le` for a weaker statement in a partial order. This lemma also holds for `ennreal`, but we need a different proof for that. -/ lemma lt_sub_iff_right : a < b - c ↔ a + c < b := contravariant.add_le_cancellable.lt_sub_iff_right /-- See `lt_sub_iff_left_of_le` for a weaker statement in a partial order. This lemma also holds for `ennreal`, but we need a different proof for that. -/ lemma lt_sub_iff_left : a < b - c ↔ c + a < b := contravariant.add_le_cancellable.lt_sub_iff_left /-- This lemma also holds for `ennreal`, but we need a different proof for that. -/ lemma sub_lt_sub_iff_right' (h : c ≤ a) : a - c < b - c ↔ a < b := contravariant.add_le_cancellable.sub_lt_sub_iff_right h lemma lt_sub_iff_lt_sub : a < b - c ↔ c < b - a := contravariant.add_le_cancellable.lt_sub_iff_lt_sub contravariant.add_le_cancellable lemma sub_lt_self' (h₁ : 0 < a) (h₂ : 0 < b) : a - b < a := contravariant.add_le_cancellable.sub_lt_self contravariant.add_le_cancellable h₁ h₂ lemma sub_lt_self_iff' : a - b < a ↔ 0 < a ∧ 0 < b := contravariant.add_le_cancellable.sub_lt_self_iff contravariant.add_le_cancellable /-- See `lt_sub_iff_left_of_le_of_le` for a weaker statement in a partial order. -/ lemma sub_lt_sub_iff_left_of_le (h : b ≤ a) : a - b < a - c ↔ c < b := contravariant.add_le_cancellable.sub_lt_sub_iff_left_of_le contravariant.add_le_cancellable h end contra /-! Lemmas about `max` and `min`. -/ lemma sub_add_eq_max : a - b + b = max a b := begin cases le_total a b with h h, { rw [max_eq_right h, sub_eq_zero_iff_le.mpr h, zero_add] }, { rw [max_eq_left h, sub_add_cancel_of_le h] } end lemma add_sub_eq_max : a + (b - a) = max a b := by rw [add_comm, max_comm, sub_add_eq_max] lemma sub_min : a - min a b = a - b := begin cases le_total a b with h h, { rw [min_eq_left h, sub_self', sub_eq_zero_iff_le.mpr h] }, { rw [min_eq_right h] } end lemma sub_add_min : a - b + min a b = a := by { rw [← sub_min, sub_add_cancel_of_le], apply min_le_left } end canonically_linear_ordered_add_monoid
8ee0b6c36706ce1d5cb34f45ae2085f1717492e1
86f6f4f8d827a196a32bfc646234b73328aeb306
/examples/basics/unnamed_2030.lean
f679f590b075c312d0d70b77a77b7e87a2984669
[]
no_license
jamescheuk91/mathematics_in_lean
09f1f87d2b0dce53464ff0cbe592c568ff59cf5e
4452499264e2975bca2f42565c0925506ba5dda3
refs/heads/master
1,679,716,410,967
1,613,957,947,000
1,613,957,947,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
240
lean
import topology.metric_space.basic variables {X : Type*} [metric_space X] variables x y z : X #check (dist_self x : dist x x = 0) #check (dist_comm x y : dist x y = dist y x) #check (dist_triangle x y z : dist x z ≤ dist x y + dist y z)
7b4e28d6afd9116fd8c33d882cfe01656931191c
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/order/archimedean.lean
3fa825a3a4457cf9ed776167f8520a03e13469ed
[ "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
15,121
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.int.least_greatest import data.rat.floor /-! # Archimedean groups and fields. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines the archimedean property for ordered groups and proves several results connected to this notion. Being archimedean means that for all elements `x` and `y>0` there exists a natural number `n` such that `x ≤ n • y`. ## Main definitions * `archimedean` is a typeclass for an ordered additive commutative monoid to have the archimedean property. * `archimedean.floor_ring` defines a floor function on an archimedean linearly ordered ring making it into a `floor_ring`. ## Main statements * `ℕ`, `ℤ`, and `ℚ` are archimedean. -/ open int set variables {α : Type*} /-- An ordered additive commutative monoid is called `archimedean` if for any two elements `x`, `y` such that `0 < y` there exists a natural number `n` such that `x ≤ n • y`. -/ class archimedean (α) [ordered_add_comm_monoid α] : Prop := (arch : ∀ (x : α) {y}, 0 < y → ∃ n : ℕ, x ≤ n • y) instance order_dual.archimedean [ordered_add_comm_group α] [archimedean α] : archimedean αᵒᵈ := ⟨λ x y hy, let ⟨n, hn⟩ := archimedean.arch (-x : α) (neg_pos.2 hy) in ⟨n, by rwa [neg_nsmul, neg_le_neg_iff] at hn⟩⟩ section linear_ordered_add_comm_group variables [linear_ordered_add_comm_group α] [archimedean α] /-- An archimedean decidable linearly ordered `add_comm_group` has a version of the floor: for `a > 0`, any `g` in the group lies between some two consecutive multiples of `a`. -/ lemma exists_unique_zsmul_near_of_pos {a : α} (ha : 0 < a) (g : α) : ∃! k : ℤ, k • a ≤ g ∧ g < (k + 1) • a := begin let s : set ℤ := {n : ℤ | n • a ≤ g}, obtain ⟨k, hk : -g ≤ k • a⟩ := archimedean.arch (-g) ha, have h_ne : s.nonempty := ⟨-k, by simpa using neg_le_neg hk⟩, obtain ⟨k, hk⟩ := archimedean.arch g ha, have h_bdd : ∀ n ∈ s, n ≤ (k : ℤ), { assume n hn, apply (zsmul_le_zsmul_iff ha).mp, rw ← coe_nat_zsmul at hk, exact le_trans hn hk }, obtain ⟨m, hm, hm'⟩ := int.exists_greatest_of_bdd ⟨k, h_bdd⟩ h_ne, have hm'' : g < (m + 1) • a, { contrapose! hm', exact ⟨m + 1, hm', lt_add_one _⟩, }, refine ⟨m, ⟨hm, hm''⟩, λ n hn, (hm' n hn.1).antisymm $ int.le_of_lt_add_one _⟩, rw ← zsmul_lt_zsmul_iff ha, exact lt_of_le_of_lt hm hn.2 end lemma exists_unique_zsmul_near_of_pos' {a : α} (ha : 0 < a) (g : α) : ∃! k : ℤ, 0 ≤ g - k • a ∧ g - k • a < a := by simpa only [sub_nonneg, add_zsmul, one_zsmul, sub_lt_iff_lt_add'] using exists_unique_zsmul_near_of_pos ha g lemma exists_unique_sub_zsmul_mem_Ico {a : α} (ha : 0 < a) (b c : α) : ∃! m : ℤ, b - m • a ∈ set.Ico c (c + a) := by simpa only [mem_Ico, le_sub_iff_add_le, zero_add, add_comm c, sub_lt_iff_lt_add', add_assoc] using exists_unique_zsmul_near_of_pos' ha (b - c) lemma exists_unique_add_zsmul_mem_Ico {a : α} (ha : 0 < a) (b c : α) : ∃! m : ℤ, b + m • a ∈ set.Ico c (c + a) := (equiv.neg ℤ).bijective.exists_unique_iff.2 $ by simpa only [equiv.neg_apply, neg_zsmul, ← sub_eq_add_neg] using exists_unique_sub_zsmul_mem_Ico ha b c lemma exists_unique_add_zsmul_mem_Ioc {a : α} (ha : 0 < a) (b c : α) : ∃! m : ℤ, b + m • a ∈ set.Ioc c (c + a) := (equiv.add_right (1 : ℤ)).bijective.exists_unique_iff.2 $ by simpa only [add_one_zsmul, sub_lt_iff_lt_add', le_sub_iff_add_le', ← add_assoc, and.comm, mem_Ioc, equiv.coe_add_right, add_le_add_iff_right] using exists_unique_zsmul_near_of_pos ha (c - b) lemma exists_unique_sub_zsmul_mem_Ioc {a : α} (ha : 0 < a) (b c : α) : ∃! m : ℤ, b - m • a ∈ set.Ioc c (c + a) := (equiv.neg ℤ).bijective.exists_unique_iff.2 $ by simpa only [equiv.neg_apply, neg_zsmul, sub_neg_eq_add] using exists_unique_add_zsmul_mem_Ioc ha b c end linear_ordered_add_comm_group theorem exists_nat_gt [strict_ordered_semiring α] [archimedean α] (x : α) : ∃ n : ℕ, x < n := let ⟨n, h⟩ := archimedean.arch x zero_lt_one in ⟨n+1, lt_of_le_of_lt (by rwa ← nsmul_one) (nat.cast_lt.2 (nat.lt_succ_self _))⟩ theorem exists_nat_ge [strict_ordered_semiring α] [archimedean α] (x : α) : ∃ n : ℕ, x ≤ n := begin nontriviality α, exact (exists_nat_gt x).imp (λ n, le_of_lt) end lemma add_one_pow_unbounded_of_pos [strict_ordered_semiring α] [archimedean α] (x : α) {y : α} (hy : 0 < y) : ∃ n : ℕ, x < (y + 1) ^ n := have 0 ≤ 1 + y, from add_nonneg zero_le_one hy.le, let ⟨n, h⟩ := archimedean.arch x hy in ⟨n, calc x ≤ n • y : h ... = n * y : nsmul_eq_mul _ _ ... < 1 + n * y : lt_one_add _ ... ≤ (1 + y) ^ n : one_add_mul_le_pow' (mul_nonneg hy.le hy.le) (mul_nonneg this this) (add_nonneg zero_le_two hy.le) _ ... = (y + 1) ^ n : by rw [add_comm]⟩ section strict_ordered_ring variables [strict_ordered_ring α] [archimedean α] lemma pow_unbounded_of_one_lt (x : α) {y : α} (hy1 : 1 < y) : ∃ n : ℕ, x < y ^ n := sub_add_cancel y 1 ▸ add_one_pow_unbounded_of_pos _ (sub_pos.2 hy1) theorem exists_int_gt (x : α) : ∃ n : ℤ, x < n := let ⟨n, h⟩ := exists_nat_gt x in ⟨n, by rwa int.cast_coe_nat⟩ theorem exists_int_lt (x : α) : ∃ n : ℤ, (n : α) < x := let ⟨n, h⟩ := exists_int_gt (-x) in ⟨-n, by rw int.cast_neg; exact neg_lt.1 h⟩ theorem exists_floor (x : α) : ∃ (fl : ℤ), ∀ (z : ℤ), z ≤ fl ↔ (z : α) ≤ x := begin haveI := classical.prop_decidable, have : ∃ (ub : ℤ), (ub:α) ≤ x ∧ ∀ (z : ℤ), (z:α) ≤ x → z ≤ ub := int.exists_greatest_of_bdd (let ⟨n, hn⟩ := exists_int_gt x in ⟨n, λ z h', int.cast_le.1 $ le_trans h' $ le_of_lt hn⟩) (let ⟨n, hn⟩ := exists_int_lt x in ⟨n, le_of_lt hn⟩), refine this.imp (λ fl h z, _), cases h with h₁ h₂, exact ⟨λ h, le_trans (int.cast_le.2 h) h₁, h₂ z⟩, end end strict_ordered_ring section linear_ordered_ring variables [linear_ordered_ring α] [archimedean α] /-- Every x greater than or equal to 1 is between two successive natural-number powers of every y greater than one. -/ lemma exists_nat_pow_near {x : α} {y : α} (hx : 1 ≤ x) (hy : 1 < y) : ∃ n : ℕ, y ^ n ≤ x ∧ x < y ^ (n + 1) := have h : ∃ n : ℕ, x < y ^ n, from pow_unbounded_of_one_lt _ hy, by classical; exact let n := nat.find h in have hn : x < y ^ n, from nat.find_spec h, have hnp : 0 < n, from pos_iff_ne_zero.2 (λ hn0, by rw [hn0, pow_zero] at hn; exact (not_le_of_gt hn hx)), have hnsp : nat.pred n + 1 = n, from nat.succ_pred_eq_of_pos hnp, have hltn : nat.pred n < n, from nat.pred_lt (ne_of_gt hnp), ⟨nat.pred n, le_of_not_lt (nat.find_min h hltn), by rwa hnsp⟩ end linear_ordered_ring section linear_ordered_field variables [linear_ordered_field α] [archimedean α] {x y ε : α} /-- Every positive `x` is between two successive integer powers of another `y` greater than one. This is the same as `exists_mem_Ioc_zpow`, but with ≤ and < the other way around. -/ lemma exists_mem_Ico_zpow (hx : 0 < x) (hy : 1 < y) : ∃ n : ℤ, x ∈ Ico (y ^ n) (y ^ (n + 1)) := by classical; exact let ⟨N, hN⟩ := pow_unbounded_of_one_lt x⁻¹ hy in have he: ∃ m : ℤ, y ^ m ≤ x, from ⟨-N, le_of_lt (by { rw [zpow_neg y (↑N), zpow_coe_nat], exact (inv_lt hx (lt_trans (inv_pos.2 hx) hN)).1 hN })⟩, let ⟨M, hM⟩ := pow_unbounded_of_one_lt x hy in have hb: ∃ b : ℤ, ∀ m, y ^ m ≤ x → m ≤ b, from ⟨M, λ m hm, le_of_not_lt (λ hlt, not_lt_of_ge (zpow_le_of_le hy.le hlt.le) (lt_of_le_of_lt hm (by rwa ← zpow_coe_nat at hM)))⟩, let ⟨n, hn₁, hn₂⟩ := int.exists_greatest_of_bdd hb he in ⟨n, hn₁, lt_of_not_ge (λ hge, not_le_of_gt (int.lt_succ _) (hn₂ _ hge))⟩ /-- Every positive `x` is between two successive integer powers of another `y` greater than one. This is the same as `exists_mem_Ico_zpow`, but with ≤ and < the other way around. -/ lemma exists_mem_Ioc_zpow (hx : 0 < x) (hy : 1 < y) : ∃ n : ℤ, x ∈ Ioc (y ^ n) (y ^ (n + 1)) := let ⟨m, hle, hlt⟩ := exists_mem_Ico_zpow (inv_pos.2 hx) hy in have hyp : 0 < y, from lt_trans zero_lt_one hy, ⟨-(m+1), by rwa [zpow_neg, inv_lt (zpow_pos_of_pos hyp _) hx], by rwa [neg_add, neg_add_cancel_right, zpow_neg, le_inv hx (zpow_pos_of_pos hyp _)]⟩ /-- For any `y < 1` and any positive `x`, there exists `n : ℕ` with `y ^ n < x`. -/ lemma exists_pow_lt_of_lt_one (hx : 0 < x) (hy : y < 1) : ∃ n : ℕ, y ^ n < x := begin by_cases y_pos : y ≤ 0, { use 1, simp only [pow_one], linarith, }, rw [not_le] at y_pos, rcases pow_unbounded_of_one_lt (x⁻¹) (one_lt_inv y_pos hy) with ⟨q, hq⟩, exact ⟨q, by rwa [inv_pow, inv_lt_inv hx (pow_pos y_pos _)] at hq⟩ end /-- Given `x` and `y` between `0` and `1`, `x` is between two successive powers of `y`. This is the same as `exists_nat_pow_near`, but for elements between `0` and `1` -/ lemma exists_nat_pow_near_of_lt_one (xpos : 0 < x) (hx : x ≤ 1) (ypos : 0 < y) (hy : y < 1) : ∃ n : ℕ, y ^ (n + 1) < x ∧ x ≤ y ^ n := begin rcases exists_nat_pow_near (one_le_inv_iff.2 ⟨xpos, hx⟩) (one_lt_inv_iff.2 ⟨ypos, hy⟩) with ⟨n, hn, h'n⟩, refine ⟨n, _, _⟩, { rwa [inv_pow, inv_lt_inv xpos (pow_pos ypos _)] at h'n }, { rwa [inv_pow, inv_le_inv (pow_pos ypos _) xpos] at hn } end lemma exists_rat_gt (x : α) : ∃ q : ℚ, x < q := let ⟨n, h⟩ := exists_nat_gt x in ⟨n, by rwa rat.cast_coe_nat⟩ theorem exists_rat_lt (x : α) : ∃ q : ℚ, (q : α) < x := let ⟨n, h⟩ := exists_int_lt x in ⟨n, by rwa rat.cast_coe_int⟩ theorem exists_rat_btwn {x y : α} (h : x < y) : ∃ q : ℚ, x < q ∧ (q:α) < y := begin cases exists_nat_gt (y - x)⁻¹ with n nh, cases exists_floor (x * n) with z zh, refine ⟨(z + 1 : ℤ) / n, _⟩, have n0' := (inv_pos.2 (sub_pos.2 h)).trans nh, have n0 := nat.cast_pos.1 n0', rw [rat.cast_div_of_ne_zero, rat.cast_coe_nat, rat.cast_coe_int, div_lt_iff n0'], refine ⟨(lt_div_iff n0').2 $ (lt_iff_lt_of_le_iff_le (zh _)).1 (lt_add_one _), _⟩, rw [int.cast_add, int.cast_one], refine lt_of_le_of_lt (add_le_add_right ((zh _).1 le_rfl) _) _, rwa [← lt_sub_iff_add_lt', ← sub_mul, ← div_lt_iff' (sub_pos.2 h), one_div], { rw [rat.coe_int_denom, nat.cast_one], exact one_ne_zero }, { intro H, rw [rat.coe_nat_num, int.cast_coe_nat, nat.cast_eq_zero] at H, subst H, cases n0 }, { rw [rat.coe_nat_denom, nat.cast_one], exact one_ne_zero } end lemma le_of_forall_rat_lt_imp_le (h : ∀ q : ℚ, (q : α) < x → (q : α) ≤ y) : x ≤ y := le_of_not_lt $ λ hyx, let ⟨q, hy, hx⟩ := exists_rat_btwn hyx in hy.not_le $ h _ hx lemma le_of_forall_lt_rat_imp_le (h : ∀ q : ℚ, y < q → x ≤ q) : x ≤ y := le_of_not_lt $ λ hyx, let ⟨q, hy, hx⟩ := exists_rat_btwn hyx in hx.not_le $ h _ hy lemma eq_of_forall_rat_lt_iff_lt (h : ∀ q : ℚ, (q : α) < x ↔ (q : α) < y) : x = y := (le_of_forall_rat_lt_imp_le $ λ q hq, ((h q).1 hq).le).antisymm $ le_of_forall_rat_lt_imp_le $ λ q hq, ((h q).2 hq).le lemma eq_of_forall_lt_rat_iff_lt (h : ∀ q : ℚ, x < q ↔ y < q) : x = y := (le_of_forall_lt_rat_imp_le $ λ q hq, ((h q).2 hq).le).antisymm $ le_of_forall_lt_rat_imp_le $ λ q hq, ((h q).1 hq).le theorem exists_nat_one_div_lt {ε : α} (hε : 0 < ε) : ∃ n : ℕ, 1 / (n + 1: α) < ε := begin cases exists_nat_gt (1/ε) with n hn, use n, rw [div_lt_iff, ← div_lt_iff' hε], { apply hn.trans, simp [zero_lt_one] }, { exact n.cast_add_one_pos } end theorem exists_pos_rat_lt {x : α} (x0 : 0 < x) : ∃ q : ℚ, 0 < q ∧ (q : α) < x := by simpa only [rat.cast_pos] using exists_rat_btwn x0 lemma exists_rat_near (x : α) (ε0 : 0 < ε) : ∃ q : ℚ, |x - q| < ε := let ⟨q, h₁, h₂⟩ := exists_rat_btwn $ ((sub_lt_self_iff x).2 ε0).trans ((lt_add_iff_pos_left x).2 ε0) in ⟨q, abs_sub_lt_iff.2 ⟨sub_lt_comm.1 h₁, sub_lt_iff_lt_add.2 h₂⟩⟩ end linear_ordered_field section linear_ordered_field variables [linear_ordered_field α] lemma archimedean_iff_nat_lt : archimedean α ↔ ∀ x : α, ∃ n : ℕ, x < n := ⟨@exists_nat_gt α _, λ H, ⟨λ x y y0, (H (x / y)).imp $ λ n h, le_of_lt $ by rwa [div_lt_iff y0, ← nsmul_eq_mul] at h⟩⟩ lemma archimedean_iff_nat_le : archimedean α ↔ ∀ x : α, ∃ n : ℕ, x ≤ n := archimedean_iff_nat_lt.trans ⟨λ H x, (H x).imp $ λ _, le_of_lt, λ H x, let ⟨n, h⟩ := H x in ⟨n+1, lt_of_le_of_lt h (nat.cast_lt.2 (lt_add_one _))⟩⟩ lemma archimedean_iff_int_lt : archimedean α ↔ ∀ x : α, ∃ n : ℤ, x < n := ⟨@exists_int_gt α _, begin rw archimedean_iff_nat_lt, intros h x, obtain ⟨n, h⟩ := h x, refine ⟨n.to_nat, h.trans_le _⟩, exact_mod_cast int.le_to_nat _, end⟩ lemma archimedean_iff_int_le : archimedean α ↔ ∀ x : α, ∃ n : ℤ, x ≤ n := archimedean_iff_int_lt.trans ⟨λ H x, (H x).imp $ λ _, le_of_lt, λ H x, let ⟨n, h⟩ := H x in ⟨n+1, lt_of_le_of_lt h (int.cast_lt.2 (lt_add_one _))⟩⟩ lemma archimedean_iff_rat_lt : archimedean α ↔ ∀ x : α, ∃ q : ℚ, x < q := ⟨@exists_rat_gt α _, λ H, archimedean_iff_nat_lt.2 $ λ x, let ⟨q, h⟩ := H x in ⟨⌈q⌉₊, lt_of_lt_of_le h $ by simpa only [rat.cast_coe_nat] using (@rat.cast_le α _ _ _).2 (nat.le_ceil _)⟩⟩ lemma archimedean_iff_rat_le : archimedean α ↔ ∀ x : α, ∃ q : ℚ, x ≤ q := archimedean_iff_rat_lt.trans ⟨λ H x, (H x).imp $ λ _, le_of_lt, λ H x, let ⟨n, h⟩ := H x in ⟨n+1, lt_of_le_of_lt h (rat.cast_lt.2 (lt_add_one _))⟩⟩ end linear_ordered_field instance : archimedean ℕ := ⟨λ n m m0, ⟨n, by simpa only [mul_one, nat.nsmul_eq_mul] using nat.mul_le_mul_left n m0⟩⟩ instance : archimedean ℤ := ⟨λ n m m0, ⟨n.to_nat, le_trans (int.le_to_nat _) $ by simpa only [nsmul_eq_mul, zero_add, mul_one] using mul_le_mul_of_nonneg_left (int.add_one_le_iff.2 m0) (int.coe_zero_le n.to_nat)⟩⟩ instance : archimedean ℚ := archimedean_iff_rat_le.2 $ λ q, ⟨q, by rw rat.cast_id⟩ /-- A linear ordered archimedean ring is a floor ring. This is not an `instance` because in some cases we have a computable `floor` function. -/ noncomputable def archimedean.floor_ring (α) [linear_ordered_ring α] [archimedean α] : floor_ring α := floor_ring.of_floor α (λ a, classical.some (exists_floor a)) (λ z a, (classical.some_spec (exists_floor a) z).symm) /-- A linear ordered field that is a floor ring is archimedean. -/ @[priority 100] -- see Note [lower instance priority] instance floor_ring.archimedean (α) [linear_ordered_field α] [floor_ring α] : archimedean α := begin rw archimedean_iff_int_le, exact λ x, ⟨⌈x⌉, int.le_ceil x⟩ end
54d4b01f5144af7a7951210b841c3691cbd96416
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/topology/metric_space/emetric_space.lean
12a1d1ce88b3a87f77f9f6ad7fa98c206fa53406
[ "Apache-2.0" ]
permissive
agjftucker/mathlib
d634cd0d5256b6325e3c55bb7fb2403548371707
87fe50de17b00af533f72a102d0adefe4a2285e8
refs/heads/master
1,625,378,131,941
1,599,166,526,000
1,599,166,526,000
160,748,509
0
0
Apache-2.0
1,544,141,789,000
1,544,141,789,000
null
UTF-8
Lean
false
false
39,246
lean
/- Copyright (c) 2015, 2017 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Robert Y. Lewis, Johannes Hölzl, Mario Carneiro, Sébastien Gouëzel -/ import data.real.ennreal import data.finset.intervals import topology.uniform_space.uniform_embedding import topology.uniform_space.pi import topology.uniform_space.uniform_convergence /-! # Extended metric spaces This file is devoted to the definition and study of `emetric_spaces`, i.e., metric spaces in which the distance is allowed to take the value ∞. This extended distance is called `edist`, and takes values in `ennreal`. Many definitions and theorems expected on emetric spaces are already introduced on uniform spaces and topological spaces. For example: open and closed sets, compactness, completeness, continuity and uniform continuity The class `emetric_space` therefore extends `uniform_space` (and `topological_space`). -/ open set filter classical noncomputable theory open_locale uniformity topological_space big_operators filter universes u v w variables {α : Type u} {β : Type v} {γ : Type w} /-- Characterizing uniformities associated to a (generalized) distance function `D` in terms of the elements of the uniformity. -/ theorem uniformity_dist_of_mem_uniformity [linear_order β] {U : filter (α × α)} (z : β) (D : α → α → β) (H : ∀ s, s ∈ U ↔ ∃ε>z, ∀{a b:α}, D a b < ε → (a, b) ∈ s) : U = ⨅ ε>z, 𝓟 {p:α×α | D p.1 p.2 < ε} := le_antisymm (le_infi $ λ ε, le_infi $ λ ε0, le_principal_iff.2 $ (H _).2 ⟨ε, ε0, λ a b, id⟩) (λ r ur, let ⟨ε, ε0, h⟩ := (H _).1 ur in mem_infi_sets ε $ mem_infi_sets ε0 $ mem_principal_sets.2 $ λ ⟨a, b⟩, h) class has_edist (α : Type*) := (edist : α → α → ennreal) export has_edist (edist) /-- Creating a uniform space from an extended distance. -/ def uniform_space_of_edist (edist : α → α → ennreal) (edist_self : ∀ x : α, edist x x = 0) (edist_comm : ∀ x y : α, edist x y = edist y x) (edist_triangle : ∀ x y z : α, edist x z ≤ edist x y + edist y z) : uniform_space α := uniform_space.of_core { uniformity := (⨅ ε>0, 𝓟 {p:α×α | edist p.1 p.2 < ε}), refl := le_infi $ assume ε, le_infi $ by simp [set.subset_def, id_rel, edist_self, (>)] {contextual := tt}, comp := le_infi $ assume ε, le_infi $ assume h, have (2 : ennreal) = (2 : ℕ) := by simp, have A : 0 < ε / 2 := ennreal.div_pos_iff.2 ⟨ne_of_gt h, by { convert ennreal.nat_ne_top 2 }⟩, lift'_le (mem_infi_sets (ε / 2) $ mem_infi_sets A (subset.refl _)) $ have ∀ (a b c : α), edist a c < ε / 2 → edist c b < ε / 2 → edist a b < ε, from assume a b c hac hcb, calc edist a b ≤ edist a c + edist c b : edist_triangle _ _ _ ... < ε / 2 + ε / 2 : ennreal.add_lt_add hac hcb ... = ε : by rw [ennreal.add_halves], by simpa [comp_rel], symm := tendsto_infi.2 $ assume ε, tendsto_infi.2 $ assume h, tendsto_infi' ε $ tendsto_infi' h $ tendsto_principal_principal.2 $ by simp [edist_comm] } section prio set_option default_priority 100 -- see Note [default priority] -- the uniform structure is embedded in the emetric space structure -- to avoid instance diamond issues. See Note [forgetful inheritance]. /-- Extended metric spaces, with an extended distance `edist` possibly taking the value ∞ Each emetric space induces a canonical `uniform_space` and hence a canonical `topological_space`. This is enforced in the type class definition, by extending the `uniform_space` structure. When instantiating an `emetric_space` structure, the uniformity fields are not necessary, they will be filled in by default. There is a default value for the uniformity, that can be substituted in cases of interest, for instance when instantiating an `emetric_space` structure on a product. Continuity of `edist` is proved in `topology.instances.ennreal` -/ class emetric_space (α : Type u) extends has_edist α : Type u := (edist_self : ∀ x : α, edist x x = 0) (eq_of_edist_eq_zero : ∀ {x y : α}, edist x y = 0 → x = y) (edist_comm : ∀ x y : α, edist x y = edist y x) (edist_triangle : ∀ x y z : α, edist x z ≤ edist x y + edist y z) (to_uniform_space : uniform_space α := uniform_space_of_edist edist edist_self edist_comm edist_triangle) (uniformity_edist : 𝓤 α = ⨅ ε>0, 𝓟 {p:α×α | edist p.1 p.2 < ε} . control_laws_tac) end prio /- emetric spaces are less common than metric spaces. Therefore, we work in a dedicated namespace, while notions associated to metric spaces are mostly in the root namespace. -/ variables [emetric_space α] @[priority 100] -- see Note [lower instance priority] instance emetric_space.to_uniform_space' : uniform_space α := emetric_space.to_uniform_space export emetric_space (edist_self eq_of_edist_eq_zero edist_comm edist_triangle) attribute [simp] edist_self /-- Characterize the equality of points by the vanishing of their extended distance -/ @[simp] theorem edist_eq_zero {x y : α} : edist x y = 0 ↔ x = y := iff.intro eq_of_edist_eq_zero (assume : x = y, this ▸ edist_self _) @[simp] theorem zero_eq_edist {x y : α} : 0 = edist x y ↔ x = y := iff.intro (assume h, eq_of_edist_eq_zero (h.symm)) (assume : x = y, this ▸ (edist_self _).symm) theorem edist_le_zero {x y : α} : (edist x y ≤ 0) ↔ x = y := le_zero_iff_eq.trans edist_eq_zero /-- Triangle inequality for the extended distance -/ theorem edist_triangle_left (x y z : α) : edist x y ≤ edist z x + edist z y := by rw edist_comm z; apply edist_triangle theorem edist_triangle_right (x y z : α) : edist x y ≤ edist x z + edist y z := by rw edist_comm y; apply edist_triangle lemma edist_triangle4 (x y z t : α) : edist x t ≤ edist x y + edist y z + edist z t := calc edist x t ≤ edist x z + edist z t : edist_triangle x z t ... ≤ (edist x y + edist y z) + edist z t : add_le_add_right (edist_triangle x y z) _ /-- The triangle (polygon) inequality for sequences of points; `finset.Ico` version. -/ lemma edist_le_Ico_sum_edist (f : ℕ → α) {m n} (h : m ≤ n) : edist (f m) (f n) ≤ ∑ i in finset.Ico m n, edist (f i) (f (i + 1)) := begin revert n, refine nat.le_induction _ _, { simp only [finset.sum_empty, finset.Ico.self_eq_empty, edist_self], -- TODO: Why doesn't Lean close this goal automatically? `apply le_refl` fails too. exact le_refl (0:ennreal) }, { assume n hn hrec, calc edist (f m) (f (n+1)) ≤ edist (f m) (f n) + edist (f n) (f (n+1)) : edist_triangle _ _ _ ... ≤ ∑ i in finset.Ico m n, _ + _ : add_le_add hrec (le_refl _) ... = ∑ i in finset.Ico m (n+1), _ : by rw [finset.Ico.succ_top hn, finset.sum_insert, add_comm]; simp } end /-- The triangle (polygon) inequality for sequences of points; `finset.range` version. -/ lemma edist_le_range_sum_edist (f : ℕ → α) (n : ℕ) : edist (f 0) (f n) ≤ ∑ i in finset.range n, edist (f i) (f (i + 1)) := finset.Ico.zero_bot n ▸ edist_le_Ico_sum_edist f (nat.zero_le n) /-- A version of `edist_le_Ico_sum_edist` with each intermediate distance replaced with an upper estimate. -/ lemma edist_le_Ico_sum_of_edist_le {f : ℕ → α} {m n} (hmn : m ≤ n) {d : ℕ → ennreal} (hd : ∀ {k}, m ≤ k → k < n → edist (f k) (f (k + 1)) ≤ d k) : edist (f m) (f n) ≤ ∑ i in finset.Ico m n, d i := le_trans (edist_le_Ico_sum_edist f hmn) $ finset.sum_le_sum $ λ k hk, hd (finset.Ico.mem.1 hk).1 (finset.Ico.mem.1 hk).2 /-- A version of `edist_le_range_sum_edist` with each intermediate distance replaced with an upper estimate. -/ lemma edist_le_range_sum_of_edist_le {f : ℕ → α} (n : ℕ) {d : ℕ → ennreal} (hd : ∀ {k}, k < n → edist (f k) (f (k + 1)) ≤ d k) : edist (f 0) (f n) ≤ ∑ i in finset.range n, d i := finset.Ico.zero_bot n ▸ edist_le_Ico_sum_of_edist_le (zero_le n) (λ _ _, hd) /-- Two points coincide if their distance is `< ε` for all positive ε -/ theorem eq_of_forall_edist_le {x y : α} (h : ∀ε > 0, edist x y ≤ ε) : x = y := eq_of_edist_eq_zero (eq_of_le_of_forall_le_of_dense bot_le h) /-- Reformulation of the uniform structure in terms of the extended distance -/ theorem uniformity_edist : 𝓤 α = ⨅ ε>0, 𝓟 {p:α×α | edist p.1 p.2 < ε} := emetric_space.uniformity_edist theorem uniformity_basis_edist : (𝓤 α).has_basis (λ ε : ennreal, 0 < ε) (λ ε, {p:α×α | edist p.1 p.2 < ε}) := (@uniformity_edist α _).symm ▸ has_basis_binfi_principal (λ r hr p hp, ⟨min r p, lt_min hr hp, λ x hx, lt_of_lt_of_le hx (min_le_left _ _), λ x hx, lt_of_lt_of_le hx (min_le_right _ _)⟩) ⟨1, ennreal.zero_lt_one⟩ /-- Characterization of the elements of the uniformity in terms of the extended distance -/ theorem mem_uniformity_edist {s : set (α×α)} : s ∈ 𝓤 α ↔ (∃ε>0, ∀{a b:α}, edist a b < ε → (a, b) ∈ s) := uniformity_basis_edist.mem_uniformity_iff /-- Given `f : β → ennreal`, if `f` sends `{i | p i}` to a set of positive numbers accumulating to zero, then `f i`-neighborhoods of the diagonal form a basis of `𝓤 α`. For specific bases see `uniformity_basis_edist`, `uniformity_basis_edist'`, `uniformity_basis_edist_nnreal`, and `uniformity_basis_edist_inv_nat`. -/ protected theorem emetric.mk_uniformity_basis {β : Type*} {p : β → Prop} {f : β → ennreal} (hf₀ : ∀ x, p x → 0 < f x) (hf : ∀ ε, 0 < ε → ∃ x (hx : p x), f x ≤ ε) : (𝓤 α).has_basis p (λ x, {p:α×α | edist p.1 p.2 < f x}) := begin refine ⟨λ s, uniformity_basis_edist.mem_iff.trans _⟩, split, { rintros ⟨ε, ε₀, hε⟩, rcases hf ε ε₀ with ⟨i, hi, H⟩, exact ⟨i, hi, λ x hx, hε $ lt_of_lt_of_le hx H⟩ }, { exact λ ⟨i, hi, H⟩, ⟨f i, hf₀ i hi, H⟩ } end /-- Given `f : β → ennreal`, if `f` sends `{i | p i}` to a set of positive numbers accumulating to zero, then closed `f i`-neighborhoods of the diagonal form a basis of `𝓤 α`. For specific bases see `uniformity_basis_edist_le` and `uniformity_basis_edist_le'`. -/ protected theorem emetric.mk_uniformity_basis_le {β : Type*} {p : β → Prop} {f : β → ennreal} (hf₀ : ∀ x, p x → 0 < f x) (hf : ∀ ε, 0 < ε → ∃ x (hx : p x), f x ≤ ε) : (𝓤 α).has_basis p (λ x, {p:α×α | edist p.1 p.2 ≤ f x}) := begin refine ⟨λ s, uniformity_basis_edist.mem_iff.trans _⟩, split, { rintros ⟨ε, ε₀, hε⟩, rcases dense ε₀ with ⟨ε', hε'⟩, rcases hf ε' hε'.1 with ⟨i, hi, H⟩, exact ⟨i, hi, λ x hx, hε $ lt_of_le_of_lt (le_trans hx H) hε'.2⟩ }, { exact λ ⟨i, hi, H⟩, ⟨f i, hf₀ i hi, λ x hx, H (le_of_lt hx)⟩ } end theorem uniformity_basis_edist_le : (𝓤 α).has_basis (λ ε : ennreal, 0 < ε) (λ ε, {p:α×α | edist p.1 p.2 ≤ ε}) := emetric.mk_uniformity_basis_le (λ _, id) (λ ε ε₀, ⟨ε, ε₀, le_refl ε⟩) theorem uniformity_basis_edist' (ε' : ennreal) (hε' : 0 < ε') : (𝓤 α).has_basis (λ ε : ennreal, ε ∈ Ioo 0 ε') (λ ε, {p:α×α | edist p.1 p.2 < ε}) := emetric.mk_uniformity_basis (λ _, and.left) (λ ε ε₀, let ⟨δ, hδ⟩ := dense hε' in ⟨min ε δ, ⟨lt_min ε₀ hδ.1, lt_of_le_of_lt (min_le_right _ _) hδ.2⟩, min_le_left _ _⟩) theorem uniformity_basis_edist_le' (ε' : ennreal) (hε' : 0 < ε') : (𝓤 α).has_basis (λ ε : ennreal, ε ∈ Ioo 0 ε') (λ ε, {p:α×α | edist p.1 p.2 ≤ ε}) := emetric.mk_uniformity_basis_le (λ _, and.left) (λ ε ε₀, let ⟨δ, hδ⟩ := dense hε' in ⟨min ε δ, ⟨lt_min ε₀ hδ.1, lt_of_le_of_lt (min_le_right _ _) hδ.2⟩, min_le_left _ _⟩) theorem uniformity_basis_edist_nnreal : (𝓤 α).has_basis (λ ε : nnreal, 0 < ε) (λ ε, {p:α×α | edist p.1 p.2 < ε}) := emetric.mk_uniformity_basis (λ _, ennreal.coe_pos.2) (λ ε ε₀, let ⟨δ, hδ⟩ := ennreal.lt_iff_exists_nnreal_btwn.1 ε₀ in ⟨δ, ennreal.coe_pos.1 hδ.1, le_of_lt hδ.2⟩) theorem uniformity_basis_edist_inv_nat : (𝓤 α).has_basis (λ _, true) (λ n:ℕ, {p:α×α | edist p.1 p.2 < (↑n)⁻¹}) := emetric.mk_uniformity_basis (λ n _, ennreal.inv_pos.2 $ ennreal.nat_ne_top n) (λ ε ε₀, let ⟨n, hn⟩ := ennreal.exists_inv_nat_lt (ne_of_gt ε₀) in ⟨n, trivial, le_of_lt hn⟩) /-- Fixed size neighborhoods of the diagonal belong to the uniform structure -/ theorem edist_mem_uniformity {ε:ennreal} (ε0 : 0 < ε) : {p:α×α | edist p.1 p.2 < ε} ∈ 𝓤 α := mem_uniformity_edist.2 ⟨ε, ε0, λ a b, id⟩ namespace emetric theorem uniformity_has_countable_basis : is_countably_generated (𝓤 α) := is_countably_generated_of_seq ⟨_, uniformity_basis_edist_inv_nat.eq_infi⟩ /-- ε-δ characterization of uniform continuity on emetric spaces -/ theorem uniform_continuous_iff [emetric_space β] {f : α → β} : uniform_continuous f ↔ ∀ ε > 0, ∃ δ > 0, ∀{a b:α}, edist a b < δ → edist (f a) (f b) < ε := uniformity_basis_edist.uniform_continuous_iff uniformity_basis_edist /-- ε-δ characterization of uniform embeddings on emetric spaces -/ theorem uniform_embedding_iff [emetric_space β] {f : α → β} : uniform_embedding f ↔ function.injective f ∧ uniform_continuous f ∧ ∀ δ > 0, ∃ ε > 0, ∀ {a b : α}, edist (f a) (f b) < ε → edist a b < δ := uniform_embedding_def'.trans $ and_congr iff.rfl $ and_congr iff.rfl ⟨λ H δ δ0, let ⟨t, tu, ht⟩ := H _ (edist_mem_uniformity δ0), ⟨ε, ε0, hε⟩ := mem_uniformity_edist.1 tu in ⟨ε, ε0, λ a b h, ht _ _ (hε h)⟩, λ H s su, let ⟨δ, δ0, hδ⟩ := mem_uniformity_edist.1 su, ⟨ε, ε0, hε⟩ := H _ δ0 in ⟨_, edist_mem_uniformity ε0, λ a b h, hδ (hε h)⟩⟩ /-- A map between emetric spaces is a uniform embedding if and only if the edistance between `f x` and `f y` is controlled in terms of the distance between `x` and `y` and conversely. -/ theorem uniform_embedding_iff' [emetric_space β] {f : α → β} : uniform_embedding f ↔ (∀ ε > 0, ∃ δ > 0, ∀ {a b : α}, edist a b < δ → edist (f a) (f b) < ε) ∧ (∀ δ > 0, ∃ ε > 0, ∀ {a b : α}, edist (f a) (f b) < ε → edist a b < δ) := begin split, { assume h, exact ⟨uniform_continuous_iff.1 (uniform_embedding_iff.1 h).2.1, (uniform_embedding_iff.1 h).2.2⟩ }, { rintros ⟨h₁, h₂⟩, refine uniform_embedding_iff.2 ⟨_, uniform_continuous_iff.2 h₁, h₂⟩, assume x y hxy, have : edist x y ≤ 0, { refine le_of_forall_lt' (λδ δpos, _), rcases h₂ δ δpos with ⟨ε, εpos, hε⟩, have : edist (f x) (f y) < ε, by simpa [hxy], exact hε this }, simpa using this } end /-- ε-δ characterization of Cauchy sequences on emetric spaces -/ protected lemma cauchy_iff {f : filter α} : cauchy f ↔ f ≠ ⊥ ∧ ∀ ε > 0, ∃ t ∈ f, ∀ x y ∈ t, edist x y < ε := uniformity_basis_edist.cauchy_iff /-- A very useful criterion to show that a space is complete is to show that all sequences which satisfy a bound of the form `edist (u n) (u m) < B N` for all `n m ≥ N` are converging. This is often applied for `B N = 2^{-N}`, i.e., with a very fast convergence to `0`, which makes it possible to use arguments of converging series, while this is impossible to do in general for arbitrary Cauchy sequences. -/ theorem complete_of_convergent_controlled_sequences (B : ℕ → ennreal) (hB : ∀n, 0 < B n) (H : ∀u : ℕ → α, (∀N n m : ℕ, N ≤ n → N ≤ m → edist (u n) (u m) < B N) → ∃x, tendsto u at_top (𝓝 x)) : complete_space α := uniform_space.complete_of_convergent_controlled_sequences uniformity_has_countable_basis (λ n, {p:α×α | edist p.1 p.2 < B n}) (λ n, edist_mem_uniformity $ hB n) H /-- A sequentially complete emetric space is complete. -/ theorem complete_of_cauchy_seq_tendsto : (∀ u : ℕ → α, cauchy_seq u → ∃a, tendsto u at_top (𝓝 a)) → complete_space α := uniform_space.complete_of_cauchy_seq_tendsto uniformity_has_countable_basis /-- Expressing locally uniform convergence on a set using `edist`. -/ lemma tendsto_locally_uniformly_on_iff {ι : Type*} [topological_space β] {F : ι → β → α} {f : β → α} {p : filter ι} {s : set β} : tendsto_locally_uniformly_on F f p s ↔ ∀ ε > 0, ∀ x ∈ s, ∃ t ∈ 𝓝[s] x, ∀ᶠ n in p, ∀ y ∈ t, edist (f y) (F n y) < ε := begin refine ⟨λ H ε hε, H _ (edist_mem_uniformity hε), λ H u hu x hx, _⟩, rcases mem_uniformity_edist.1 hu with ⟨ε, εpos, hε⟩, rcases H ε εpos x hx with ⟨t, ht, Ht⟩, exact ⟨t, ht, Ht.mono (λ n hs x hx, hε (hs x hx))⟩ end /-- Expressing uniform convergence on a set using `edist`. -/ lemma tendsto_uniformly_on_iff {ι : Type*} {F : ι → β → α} {f : β → α} {p : filter ι} {s : set β} : tendsto_uniformly_on F f p s ↔ ∀ ε > 0, ∀ᶠ n in p, ∀ x ∈ s, edist (f x) (F n x) < ε := begin refine ⟨λ H ε hε, H _ (edist_mem_uniformity hε), λ H u hu, _⟩, rcases mem_uniformity_edist.1 hu with ⟨ε, εpos, hε⟩, exact (H ε εpos).mono (λ n hs x hx, hε (hs x hx)) end /-- Expressing locally uniform convergence using `edist`. -/ lemma tendsto_locally_uniformly_iff {ι : Type*} [topological_space β] {F : ι → β → α} {f : β → α} {p : filter ι} : tendsto_locally_uniformly F f p ↔ ∀ ε > 0, ∀ (x : β), ∃ t ∈ 𝓝 x, ∀ᶠ n in p, ∀ y ∈ t, edist (f y) (F n y) < ε := by simp only [← tendsto_locally_uniformly_on_univ, tendsto_locally_uniformly_on_iff, mem_univ, forall_const, exists_prop, nhds_within_univ] /-- Expressing uniform convergence using `edist`. -/ lemma tendsto_uniformly_iff {ι : Type*} {F : ι → β → α} {f : β → α} {p : filter ι} : tendsto_uniformly F f p ↔ ∀ ε > 0, ∀ᶠ n in p, ∀ x, edist (f x) (F n x) < ε := by simp only [← tendsto_uniformly_on_univ, tendsto_uniformly_on_iff, mem_univ, forall_const] end emetric open emetric /-- An emetric space is separated -/ @[priority 100] -- see Note [lower instance priority] instance to_separated : separated_space α := separated_def.2 $ λ x y h, eq_of_forall_edist_le $ λ ε ε0, le_of_lt (h _ (edist_mem_uniformity ε0)) /-- Auxiliary function to replace the uniformity on an emetric space with a uniformity which is equal to the original one, but maybe not defeq. This is useful if one wants to construct an emetric space with a specified uniformity. See Note [forgetful inheritance] explaining why having definitionally the right uniformity is often important. -/ def emetric_space.replace_uniformity {α} [U : uniform_space α] (m : emetric_space α) (H : @uniformity _ U = @uniformity _ emetric_space.to_uniform_space) : emetric_space α := { edist := @edist _ m.to_has_edist, edist_self := edist_self, eq_of_edist_eq_zero := @eq_of_edist_eq_zero _ _, edist_comm := edist_comm, edist_triangle := edist_triangle, to_uniform_space := U, uniformity_edist := H.trans (@emetric_space.uniformity_edist α _) } /-- The extended metric induced by an injective function taking values in an emetric space. -/ def emetric_space.induced {α β} (f : α → β) (hf : function.injective f) (m : emetric_space β) : emetric_space α := { edist := λ x y, edist (f x) (f y), edist_self := λ x, edist_self _, eq_of_edist_eq_zero := λ x y h, hf (edist_eq_zero.1 h), edist_comm := λ x y, edist_comm _ _, edist_triangle := λ x y z, edist_triangle _ _ _, to_uniform_space := uniform_space.comap f m.to_uniform_space, uniformity_edist := begin apply @uniformity_dist_of_mem_uniformity _ _ _ _ _ (λ x y, edist (f x) (f y)), refine λ s, mem_comap_sets.trans _, split; intro H, { rcases H with ⟨r, ru, rs⟩, rcases mem_uniformity_edist.1 ru with ⟨ε, ε0, hε⟩, refine ⟨ε, ε0, λ a b h, rs (hε _)⟩, exact h }, { rcases H with ⟨ε, ε0, hε⟩, exact ⟨_, edist_mem_uniformity ε0, λ ⟨a, b⟩, hε⟩ } end } /-- Emetric space instance on subsets of emetric spaces -/ instance {α : Type*} {p : α → Prop} [t : emetric_space α] : emetric_space (subtype p) := t.induced coe (λ x y, subtype.ext_iff_val.2) /-- The extended distance on a subset of an emetric space is the restriction of the original distance, by definition -/ theorem subtype.edist_eq {p : α → Prop} (x y : subtype p) : edist x y = edist (x : α) y := rfl /-- The product of two emetric spaces, with the max distance, is an extended metric spaces. We make sure that the uniform structure thus constructed is the one corresponding to the product of uniform spaces, to avoid diamond problems. -/ instance prod.emetric_space_max [emetric_space β] : emetric_space (α × β) := { edist := λ x y, max (edist x.1 y.1) (edist x.2 y.2), edist_self := λ x, by simp, eq_of_edist_eq_zero := λ x y h, begin cases max_le_iff.1 (le_of_eq h) with h₁ h₂, have A : x.fst = y.fst := edist_le_zero.1 h₁, have B : x.snd = y.snd := edist_le_zero.1 h₂, exact prod.ext_iff.2 ⟨A, B⟩ end, edist_comm := λ x y, by simp [edist_comm], edist_triangle := λ x y z, max_le (le_trans (edist_triangle _ _ _) (add_le_add (le_max_left _ _) (le_max_left _ _))) (le_trans (edist_triangle _ _ _) (add_le_add (le_max_right _ _) (le_max_right _ _))), uniformity_edist := begin refine uniformity_prod.trans _, simp [emetric_space.uniformity_edist, comap_infi], rw ← infi_inf_eq, congr, funext, rw ← infi_inf_eq, congr, funext, simp [inf_principal, ext_iff, max_lt_iff] end, to_uniform_space := prod.uniform_space } lemma prod.edist_eq [emetric_space β] (x y : α × β) : edist x y = max (edist x.1 y.1) (edist x.2 y.2) := rfl section pi open finset variables {π : β → Type*} [fintype β] /-- The product of a finite number of emetric spaces, with the max distance, is still an emetric space. This construction would also work for infinite products, but it would not give rise to the product topology. Hence, we only formalize it in the good situation of finitely many spaces. -/ instance emetric_space_pi [∀b, emetric_space (π b)] : emetric_space (Πb, π b) := { edist := λ f g, finset.sup univ (λb, edist (f b) (g b)), edist_self := assume f, bot_unique $ finset.sup_le $ by simp, edist_comm := assume f g, by unfold edist; congr; funext a; exact edist_comm _ _, edist_triangle := assume f g h, begin simp only [finset.sup_le_iff], assume b hb, exact le_trans (edist_triangle _ (g b) _) (add_le_add (le_sup hb) (le_sup hb)) end, eq_of_edist_eq_zero := assume f g eq0, begin have eq1 : sup univ (λ (b : β), edist (f b) (g b)) ≤ 0 := le_of_eq eq0, simp only [finset.sup_le_iff] at eq1, exact (funext $ assume b, edist_le_zero.1 $ eq1 b $ mem_univ b), end, to_uniform_space := Pi.uniform_space _, uniformity_edist := begin simp only [Pi.uniformity, emetric_space.uniformity_edist, comap_infi, gt_iff_lt, preimage_set_of_eq, comap_principal], rw infi_comm, congr, funext ε, rw infi_comm, congr, funext εpos, change 0 < ε at εpos, simp [set.ext_iff, εpos] end } end pi namespace emetric variables {x y z : α} {ε ε₁ ε₂ : ennreal} {s : set α} /-- `emetric.ball x ε` is the set of all points `y` with `edist y x < ε` -/ def ball (x : α) (ε : ennreal) : set α := {y | edist y x < ε} @[simp] theorem mem_ball : y ∈ ball x ε ↔ edist y x < ε := iff.rfl theorem mem_ball' : y ∈ ball x ε ↔ edist x y < ε := by rw edist_comm; refl /-- `emetric.closed_ball x ε` is the set of all points `y` with `edist y x ≤ ε` -/ def closed_ball (x : α) (ε : ennreal) := {y | edist y x ≤ ε} @[simp] theorem mem_closed_ball : y ∈ closed_ball x ε ↔ edist y x ≤ ε := iff.rfl theorem ball_subset_closed_ball : ball x ε ⊆ closed_ball x ε := assume y, by simp; intros h; apply le_of_lt h theorem pos_of_mem_ball (hy : y ∈ ball x ε) : 0 < ε := lt_of_le_of_lt (zero_le _) hy theorem mem_ball_self (h : 0 < ε) : x ∈ ball x ε := show edist x x < ε, by rw edist_self; assumption theorem mem_closed_ball_self : x ∈ closed_ball x ε := show edist x x ≤ ε, by rw edist_self; exact bot_le theorem mem_ball_comm : x ∈ ball y ε ↔ y ∈ ball x ε := by simp [edist_comm] theorem ball_subset_ball (h : ε₁ ≤ ε₂) : ball x ε₁ ⊆ ball x ε₂ := λ y (yx : _ < ε₁), lt_of_lt_of_le yx h theorem closed_ball_subset_closed_ball (h : ε₁ ≤ ε₂) : closed_ball x ε₁ ⊆ closed_ball x ε₂ := λ y (yx : _ ≤ ε₁), le_trans yx h theorem ball_disjoint (h : ε₁ + ε₂ ≤ edist x y) : ball x ε₁ ∩ ball y ε₂ = ∅ := eq_empty_iff_forall_not_mem.2 $ λ z ⟨h₁, h₂⟩, not_lt_of_le (edist_triangle_left x y z) (lt_of_lt_of_le (ennreal.add_lt_add h₁ h₂) h) theorem ball_subset (h : edist x y + ε₁ ≤ ε₂) (h' : edist x y < ⊤) : ball x ε₁ ⊆ ball y ε₂ := λ z zx, calc edist z y ≤ edist z x + edist x y : edist_triangle _ _ _ ... = edist x y + edist z x : add_comm _ _ ... < edist x y + ε₁ : (ennreal.add_lt_add_iff_left h').2 zx ... ≤ ε₂ : h theorem exists_ball_subset_ball (h : y ∈ ball x ε) : ∃ ε' > 0, ball y ε' ⊆ ball x ε := begin have : 0 < ε - edist y x := by simpa using h, refine ⟨ε - edist y x, this, ball_subset _ _⟩, { rw ennreal.add_sub_cancel_of_le (le_of_lt h), apply le_refl _}, { have : edist y x ≠ ⊤ := ne_top_of_lt h, apply lt_top_iff_ne_top.2 this } end theorem ball_eq_empty_iff : ball x ε = ∅ ↔ ε = 0 := eq_empty_iff_forall_not_mem.trans ⟨λh, le_bot_iff.1 (le_of_not_gt (λ ε0, h _ (mem_ball_self ε0))), λε0 y h, not_lt_of_le (le_of_eq ε0) (pos_of_mem_ball h)⟩ /-- Relation “two points are at a finite edistance” is an equivalence relation. -/ def edist_lt_top_setoid : setoid α := { r := λ x y, edist x y < ⊤, iseqv := ⟨λ x, by { rw edist_self, exact ennreal.coe_lt_top }, λ x y h, by rwa edist_comm, λ x y z hxy hyz, lt_of_le_of_lt (edist_triangle x y z) (ennreal.add_lt_top.2 ⟨hxy, hyz⟩)⟩ } @[simp] lemma ball_zero : ball x 0 = ∅ := by rw [emetric.ball_eq_empty_iff] theorem nhds_basis_eball : (𝓝 x).has_basis (λ ε:ennreal, 0 < ε) (ball x) := nhds_basis_uniformity uniformity_basis_edist theorem nhds_basis_closed_eball : (𝓝 x).has_basis (λ ε:ennreal, 0 < ε) (closed_ball x) := nhds_basis_uniformity uniformity_basis_edist_le theorem nhds_eq : 𝓝 x = (⨅ε>0, 𝓟 (ball x ε)) := nhds_basis_eball.eq_binfi theorem mem_nhds_iff : s ∈ 𝓝 x ↔ ∃ε>0, ball x ε ⊆ s := nhds_basis_eball.mem_iff theorem is_open_iff : is_open s ↔ ∀x∈s, ∃ε>0, ball x ε ⊆ s := by simp [is_open_iff_nhds, mem_nhds_iff] theorem is_open_ball : is_open (ball x ε) := is_open_iff.2 $ λ y, exists_ball_subset_ball theorem is_closed_ball_top : is_closed (ball x ⊤) := is_open_iff.2 $ λ y hy, ⟨⊤, ennreal.coe_lt_top, subset_compl_iff_disjoint.2 $ ball_disjoint $ by { rw ennreal.top_add, exact le_of_not_lt hy }⟩ theorem ball_mem_nhds (x : α) {ε : ennreal} (ε0 : 0 < ε) : ball x ε ∈ 𝓝 x := mem_nhds_sets is_open_ball (mem_ball_self ε0) /-- ε-characterization of the closure in emetric spaces -/ theorem mem_closure_iff : x ∈ closure s ↔ ∀ε>0, ∃y ∈ s, edist x y < ε := (mem_closure_iff_nhds_basis nhds_basis_eball).trans $ by simp only [mem_ball, edist_comm x] theorem tendsto_nhds {f : filter β} {u : β → α} {a : α} : tendsto u f (𝓝 a) ↔ ∀ ε > 0, ∀ᶠ x in f, edist (u x) a < ε := nhds_basis_eball.tendsto_right_iff theorem tendsto_at_top [nonempty β] [semilattice_sup β] (u : β → α) {a : α} : tendsto u at_top (𝓝 a) ↔ ∀ε>0, ∃N, ∀n≥N, edist (u n) a < ε := (at_top_basis.tendsto_iff nhds_basis_eball).trans $ by simp only [exists_prop, true_and, mem_Ici, mem_ball] /-- In an emetric space, Cauchy sequences are characterized by the fact that, eventually, the edistance between its elements is arbitrarily small -/ @[nolint ge_or_gt] -- see Note [nolint_ge] theorem cauchy_seq_iff [nonempty β] [semilattice_sup β] {u : β → α} : cauchy_seq u ↔ ∀ε>0, ∃N, ∀m n≥N, edist (u m) (u n) < ε := uniformity_basis_edist.cauchy_seq_iff /-- A variation around the emetric characterization of Cauchy sequences -/ theorem cauchy_seq_iff' [nonempty β] [semilattice_sup β] {u : β → α} : cauchy_seq u ↔ ∀ε>(0 : ennreal), ∃N, ∀n≥N, edist (u n) (u N) < ε := uniformity_basis_edist.cauchy_seq_iff' /-- A variation of the emetric characterization of Cauchy sequences that deals with `nnreal` upper bounds. -/ theorem cauchy_seq_iff_nnreal [nonempty β] [semilattice_sup β] {u : β → α} : cauchy_seq u ↔ ∀ ε : nnreal, 0 < ε → ∃ N, ∀ n, N ≤ n → edist (u n) (u N) < ε := uniformity_basis_edist_nnreal.cauchy_seq_iff' theorem totally_bounded_iff {s : set α} : totally_bounded s ↔ ∀ ε > 0, ∃t : set α, finite t ∧ s ⊆ ⋃y∈t, ball y ε := ⟨λ H ε ε0, H _ (edist_mem_uniformity ε0), λ H r ru, let ⟨ε, ε0, hε⟩ := mem_uniformity_edist.1 ru, ⟨t, ft, h⟩ := H ε ε0 in ⟨t, ft, subset.trans h $ Union_subset_Union $ λ y, Union_subset_Union $ λ yt z, hε⟩⟩ theorem totally_bounded_iff' {s : set α} : totally_bounded s ↔ ∀ ε > 0, ∃t⊆s, finite t ∧ s ⊆ ⋃y∈t, ball y ε := ⟨λ H ε ε0, (totally_bounded_iff_subset.1 H) _ (edist_mem_uniformity ε0), λ H r ru, let ⟨ε, ε0, hε⟩ := mem_uniformity_edist.1 ru, ⟨t, _, ft, h⟩ := H ε ε0 in ⟨t, ft, subset.trans h $ Union_subset_Union $ λ y, Union_subset_Union $ λ yt z, hε⟩⟩ section compact /-- A compact set in an emetric space is separable, i.e., it is the closure of a countable set -/ lemma countable_closure_of_compact {α : Type u} [emetric_space α] {s : set α} (hs : is_compact s) : ∃ t ⊆ s, (countable t ∧ s = closure t) := begin have A : ∀ (e:ennreal), e > 0 → ∃ t ⊆ s, (finite t ∧ s ⊆ (⋃x∈t, ball x e)) := totally_bounded_iff'.1 (compact_iff_totally_bounded_complete.1 hs).1, -- assume e, finite_cover_balls_of_compact hs, have B : ∀ (e:ennreal), ∃ t ⊆ s, finite t ∧ (e > 0 → s ⊆ (⋃x∈t, ball x e)), { intro e, cases le_or_gt e 0 with h, { exact ⟨∅, by finish⟩ }, { rcases A e h with ⟨s, ⟨finite_s, closure_s⟩⟩, existsi s, finish }}, /-The desired countable set is obtained by taking for each `n` the centers of a finite cover by balls of radius `1/n`, and then the union over `n`. -/ choose T T_in_s finite_T using B, let t := ⋃n:ℕ, T n⁻¹, have T₁ : t ⊆ s := begin apply Union_subset, assume n, apply T_in_s end, have T₂ : countable t := by finish [countable_Union, finite.countable], have T₃ : s ⊆ closure t, { intros x x_in_s, apply mem_closure_iff.2, intros ε εpos, rcases ennreal.exists_inv_nat_lt (bot_lt_iff_ne_bot.1 εpos) with ⟨n, hn⟩, have inv_n_pos : (0 : ennreal) < (n : ℕ)⁻¹ := by simp [ennreal.bot_lt_iff_ne_bot], have C : x ∈ (⋃y∈ T (n : ℕ)⁻¹, ball y (n : ℕ)⁻¹) := mem_of_mem_of_subset x_in_s ((finite_T (n : ℕ)⁻¹).2 inv_n_pos), rcases mem_Union.1 C with ⟨y, _, ⟨y_in_T, rfl⟩, Dxy⟩, simp at Dxy, -- Dxy : edist x y < 1 / ↑n have : y ∈ t := mem_of_mem_of_subset y_in_T (by apply subset_Union (λ (n:ℕ), T (n : ℕ)⁻¹)), have : edist x y < ε := lt_trans Dxy hn, exact ⟨y, ‹y ∈ t›, ‹edist x y < ε›⟩ }, have T₄ : closure t ⊆ s := calc closure t ⊆ closure s : closure_mono T₁ ... = s : hs.is_closed.closure_eq, exact ⟨t, ⟨T₁, T₂, subset.antisymm T₃ T₄⟩⟩ end end compact section first_countable @[priority 100] -- see Note [lower instance priority] instance (α : Type u) [emetric_space α] : topological_space.first_countable_topology α := uniform_space.first_countable_topology uniformity_has_countable_basis end first_countable section second_countable open topological_space /-- A separable emetric space is second countable: one obtains a countable basis by taking the balls centered at points in a dense subset, and with rational radii. We do not register this as an instance, as there is already an instance going in the other direction from second countable spaces to separable spaces, and we want to avoid loops. -/ lemma second_countable_of_separable (α : Type u) [emetric_space α] [separable_space α] : second_countable_topology α := let ⟨S, ⟨S_countable, S_dense⟩⟩ := separable_space.exists_countable_closure_eq_univ in ⟨⟨⋃x ∈ S, ⋃ (n : nat), {ball x (n⁻¹)}, ⟨show countable ⋃x ∈ S, ⋃ (n : nat), {ball x (n⁻¹)}, { apply S_countable.bUnion, intros a aS, apply countable_Union, simp }, show uniform_space.to_topological_space = generate_from (⋃x ∈ S, ⋃ (n : nat), {ball x (n⁻¹)}), { have A : ∀ (u : set α), (u ∈ ⋃x ∈ S, ⋃ (n : nat), ({ball x ((n : ennreal)⁻¹)} : set (set α))) → is_open u, { simp only [and_imp, exists_prop, set.mem_Union, set.mem_singleton_iff, exists_imp_distrib], intros u x hx i u_ball, rw [u_ball], exact is_open_ball }, have B : is_topological_basis (⋃x ∈ S, ⋃ (n : nat), ({ball x (n⁻¹)} : set (set α))), { refine is_topological_basis_of_open_of_nhds A (λa u au open_u, _), rcases is_open_iff.1 open_u a au with ⟨ε, εpos, εball⟩, have : ε / 2 > 0 := ennreal.half_pos εpos, /- The ball `ball a ε` is included in `u`. We need to find one of our balls `ball x (n⁻¹)` containing `a` and contained in `ball a ε`. For this, we take `n` larger than `2/ε`, and then `x` in `S` at distance at most `n⁻¹` of `a` -/ rcases ennreal.exists_inv_nat_lt (bot_lt_iff_ne_bot.1 (ennreal.half_pos εpos)) with ⟨n, εn⟩, have : (0 : ennreal) < n⁻¹ := by simp [ennreal.bot_lt_iff_ne_bot], have : (a : α) ∈ closure (S : set α) := by rw [S_dense]; simp, rcases mem_closure_iff.1 this _ ‹(0 : ennreal) < n⁻¹› with ⟨x, xS, xdist⟩, existsi ball x (↑n)⁻¹, have I : ball x (n⁻¹) ⊆ ball a ε := λy ydist, calc edist y a = edist a y : edist_comm _ _ ... ≤ edist a x + edist y x : edist_triangle_right _ _ _ ... < n⁻¹ + n⁻¹ : ennreal.add_lt_add xdist ydist ... < ε/2 + ε/2 : ennreal.add_lt_add εn εn ... = ε : ennreal.add_halves _, simp only [emetric.mem_ball, exists_prop, set.mem_Union, set.mem_singleton_iff], exact ⟨⟨x, ⟨xS, ⟨n, rfl⟩⟩⟩, ⟨by simpa, subset.trans I εball⟩⟩ }, exact B.2.2 }⟩⟩⟩ end second_countable section diam /-- The diameter of a set in an emetric space, named `emetric.diam` -/ def diam (s : set α) := ⨆ (x ∈ s) (y ∈ s), edist x y lemma diam_le_iff_forall_edist_le {d : ennreal} : diam s ≤ d ↔ ∀ (x ∈ s) (y ∈ s), edist x y ≤ d := by simp only [diam, supr_le_iff] /-- If two points belong to some set, their edistance is bounded by the diameter of the set -/ lemma edist_le_diam_of_mem (hx : x ∈ s) (hy : y ∈ s) : edist x y ≤ diam s := diam_le_iff_forall_edist_le.1 (le_refl _) x hx y hy /-- If the distance between any two points in a set is bounded by some constant, this constant bounds the diameter. -/ lemma diam_le_of_forall_edist_le {d : ennreal} (h : ∀ (x ∈ s) (y ∈ s), edist x y ≤ d) : diam s ≤ d := diam_le_iff_forall_edist_le.2 h /-- The diameter of a subsingleton vanishes. -/ lemma diam_subsingleton (hs : s.subsingleton) : diam s = 0 := le_zero_iff_eq.1 $ diam_le_of_forall_edist_le $ λ x hx y hy, (hs hx hy).symm ▸ edist_self y ▸ le_refl _ /-- The diameter of the empty set vanishes -/ @[simp] lemma diam_empty : diam (∅ : set α) = 0 := diam_subsingleton subsingleton_empty /-- The diameter of a singleton vanishes -/ @[simp] lemma diam_singleton : diam ({x} : set α) = 0 := diam_subsingleton subsingleton_singleton lemma diam_eq_zero_iff : diam s = 0 ↔ s.subsingleton := ⟨λ h x hx y hy, edist_le_zero.1 $ h ▸ edist_le_diam_of_mem hx hy, diam_subsingleton⟩ lemma diam_pos_iff : 0 < diam s ↔ ∃ (x ∈ s) (y ∈ s), x ≠ y := begin have := not_congr (@diam_eq_zero_iff _ _ s), dunfold set.subsingleton at this, push_neg at this, simpa only [zero_lt_iff_ne_zero, exists_prop] using this end lemma diam_insert : diam (insert x s) = max (⨆ y ∈ s, edist x y) (diam s) := eq_of_forall_ge_iff $ λ d, by simp only [diam_le_iff_forall_edist_le, ball_insert_iff, edist_self, edist_comm x, max_le_iff, supr_le_iff, zero_le, true_and, forall_and_distrib, and_self, ← and_assoc] lemma diam_pair : diam ({x, y} : set α) = edist x y := by simp only [supr_singleton, diam_insert, diam_singleton, ennreal.max_zero_right] lemma diam_triple : diam ({x, y, z} : set α) = max (max (edist x y) (edist x z)) (edist y z) := by simp only [diam_insert, supr_insert, supr_singleton, diam_singleton, ennreal.max_zero_right, ennreal.sup_eq_max] /-- The diameter is monotonous with respect to inclusion -/ lemma diam_mono {s t : set α} (h : s ⊆ t) : diam s ≤ diam t := diam_le_of_forall_edist_le $ λ x hx y hy, edist_le_diam_of_mem (h hx) (h hy) /-- The diameter of a union is controlled by the diameter of the sets, and the edistance between two points in the sets. -/ lemma diam_union {t : set α} (xs : x ∈ s) (yt : y ∈ t) : diam (s ∪ t) ≤ diam s + edist x y + diam t := begin have A : ∀a ∈ s, ∀b ∈ t, edist a b ≤ diam s + edist x y + diam t := λa ha b hb, calc edist a b ≤ edist a x + edist x y + edist y b : edist_triangle4 _ _ _ _ ... ≤ diam s + edist x y + diam t : add_le_add (add_le_add (edist_le_diam_of_mem ha xs) (le_refl _)) (edist_le_diam_of_mem yt hb), refine diam_le_of_forall_edist_le (λa ha b hb, _), cases (mem_union _ _ _).1 ha with h'a h'a; cases (mem_union _ _ _).1 hb with h'b h'b, { calc edist a b ≤ diam s : edist_le_diam_of_mem h'a h'b ... ≤ diam s + (edist x y + diam t) : le_add_right (le_refl _) ... = diam s + edist x y + diam t : by simp only [add_comm, eq_self_iff_true, add_left_comm] }, { exact A a h'a b h'b }, { have Z := A b h'b a h'a, rwa [edist_comm] at Z }, { calc edist a b ≤ diam t : edist_le_diam_of_mem h'a h'b ... ≤ (diam s + edist x y) + diam t : le_add_left (le_refl _) } end lemma diam_union' {t : set α} (h : (s ∩ t).nonempty) : diam (s ∪ t) ≤ diam s + diam t := let ⟨x, ⟨xs, xt⟩⟩ := h in by simpa using diam_union xs xt lemma diam_closed_ball {r : ennreal} : diam (closed_ball x r) ≤ 2 * r := diam_le_of_forall_edist_le $ λa ha b hb, calc edist a b ≤ edist a x + edist b x : edist_triangle_right _ _ _ ... ≤ r + r : add_le_add ha hb ... = 2 * r : by simp [mul_two, mul_comm] lemma diam_ball {r : ennreal} : diam (ball x r) ≤ 2 * r := le_trans (diam_mono ball_subset_closed_ball) diam_closed_ball end diam end emetric --namespace
0e47755dd698460f92e604f6219bc2f77aea866e
de91c42b87530c3bdcc2b138ef1a3c3d9bee0d41
/old/eval/luminousIntensityEval.lean
60be9b72f98d69508f3e40e22aa2096cd1a05e5d
[]
no_license
kevinsullivan/lang
d3e526ba363dc1ddf5ff1c2f36607d7f891806a7
e9d869bff94fb13ad9262222a6f3c4aafba82d5e
refs/heads/master
1,687,840,064,795
1,628,047,969,000
1,628,047,969,000
282,210,749
0
1
null
1,608,153,830,000
1,595,592,637,000
Lean
UTF-8
Lean
false
false
657
lean
import ..imperative_DSL.environment open lang.classicalLuminousIntensity attribute [reducible] def classicalLuminousIntensityEval : lang.classicalLuminousIntensity.spaceExpr → environment.env → classicalLuminousIntensity | (lang.classicalLuminousIntensity.spaceExpr.lit V) i := V | (lang.classicalLuminousIntensity.spaceExpr.var v) i := i.li.sp v attribute [reducible] def classicalLuminousIntensityQuantityEval : lang.classicalLuminousIntensity.QuantityExpr → environment.env → classicalLuminousIntensityQuantity | (lang.classicalLuminousIntensity.QuantityExpr.lit V) i := V | (lang.classicalLuminousIntensity.QuantityExpr.var v) i := i.li.s v
3f7a9617f9d635b97065001e1501d8e5ae3fca7d
4fa161becb8ce7378a709f5992a594764699e268
/src/topology/uniform_space/absolute_value.lean
3579ef6359c17986f5b46b42edf4e4431dab6fde
[ "Apache-2.0" ]
permissive
laughinggas/mathlib
e4aa4565ae34e46e834434284cb26bd9d67bc373
86dcd5cda7a5017c8b3c8876c89a510a19d49aad
refs/heads/master
1,669,496,232,688
1,592,831,995,000
1,592,831,995,000
274,155,979
0
0
Apache-2.0
1,592,835,190,000
1,592,835,189,000
null
UTF-8
Lean
false
false
2,972
lean
/- Copyright (c) 2019 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot -/ import data.real.cau_seq import topology.uniform_space.basic /-! # Uniform structure induced by an absolute value We build a uniform space structure on a commutative ring `R` equipped with an absolute value into a linear ordered field `𝕜`. Of course in the case `R` is `ℚ`, `ℝ` or `ℂ` and `𝕜 = ℝ`, we get the same thing as the metric space construction, and the general construction follows exactly the same path. ## Implementation details Note that we import `data.real.cau_seq` because this is where absolute values are defined, but the current file does not depend on real numbers. TODO: extract absolute values from that `data.real` folder. ## References * [N. Bourbaki, *Topologie générale*][bourbaki1966] ## Tags absolute value, uniform spaces -/ open set function filter uniform_space namespace is_absolute_value variables {𝕜 : Type*} [discrete_linear_ordered_field 𝕜] variables {R : Type*} [comm_ring R] (abv : R → 𝕜) [is_absolute_value abv] /-- The uniformity coming from an absolute value. -/ def uniform_space_core : uniform_space.core R := { uniformity := (⨅ ε>0, principal {p:R×R | abv (p.2 - p.1) < ε}), refl := le_infi $ assume ε, le_infi $ assume ε_pos, principal_mono.2 (λ ⟨x, y⟩ h, by simpa [show x = y, from h, abv_zero abv]), symm := tendsto_infi.2 $ assume ε, tendsto_infi.2 $ assume h, tendsto_infi' ε $ tendsto_infi' h $ tendsto_principal_principal.2 $ λ ⟨x, y⟩ h, have h : abv (y - x) < ε, by simpa [-sub_eq_add_neg] using h, by rwa abv_sub abv at h, comp := le_infi $ assume ε, le_infi $ assume h, lift'_le (mem_infi_sets (ε / 2) $ mem_infi_sets (div_pos_of_pos_of_pos h two_pos) (subset.refl _)) $ have ∀ (a b c : R), abv (c-a) < ε / 2 → abv (b-c) < ε / 2 → abv (b-a) < ε, from assume a b c hac hcb, calc abv (b - a) ≤ _ : abv_sub_le abv b c a ... = abv (c - a) + abv (b - c) : add_comm _ _ ... < ε / 2 + ε / 2 : add_lt_add hac hcb ... = ε : by rw [div_add_div_same, add_self_div_two], by simpa [comp_rel] } /-- The uniform structure coming from an absolute value. -/ def uniform_space : uniform_space R := uniform_space.of_core (uniform_space_core abv) @[nolint ge_or_gt] -- see Note [nolint_ge] theorem mem_uniformity {s : set (R×R)} : s ∈ (uniform_space_core abv).uniformity ↔ (∃ε>0, ∀{a b:R}, abv (b - a) < ε → (a, b) ∈ s) := begin suffices : s ∈ (⨅ ε: {ε : 𝕜 // ε > 0}, principal {p:R×R | abv (p.2 - p.1) < ε.val}) ↔ _, { rw infi_subtype at this, exact this }, rw mem_infi, { simp [subset_def] }, { exact assume ⟨r, hr⟩ ⟨p, hp⟩, ⟨⟨min r p, lt_min hr hp⟩, by simp [lt_min_iff, (≥)] {contextual := tt}⟩, }, { exact ⟨⟨1, zero_lt_one⟩⟩ } end end is_absolute_value
830629a65e2e4d51ab1bd72cb344f021da74293b
0dc59d2b959c9b11a672f655b104d7d7d3e37660
/other_peoples_work/vvs_NNG4.lean
58e7daaa4e81e27fcecf2cf1a6fea2cd99b3685a
[]
no_license
kbuzzard/lean4-filters
5aa17d95079ceb906622543209064151fa645e71
29f90055b7a2341c86d924954463c439bd128fb7
refs/heads/master
1,679,762,259,673
1,616,701,300,000
1,616,701,300,000
350,784,493
5
1
null
1,625,691,081,000
1,616,517,435,000
Lean
UTF-8
Lean
false
false
1,201
lean
theorem add_zero : x + 0 = x := by rfl theorem add_succ : x + Nat.succ y = Nat.succ (x + y) := by rfl theorem one_Eq_succ_zero : 1 = Nat.succ 0 := by rfl --set_option hygienicIntro false in theorem zero_add : 0 + x = x := by induction x with | succ _ ih => _ | _ => _ rfl rewrite add_succ apply congrArg -- or just `rw ih`/`rw v_0` assumption theorem add_assoc (a b c : Nat) : (a + b) + c = a + (b + c) := by induction c with | succ _ ih => _ | _ => _ rewrite add_zero rewrite add_zero rfl rewrite add_succ rewrite add_succ rewrite add_succ rewrite ih rfl theorem succ_add (a b : Nat) : Nat.succ a + b = Nat.succ (a + b) := by induction b with | succ _ ih => _ | _ => _ rfl rewrite add_succ rewrite add_succ rewrite ih rfl theorem add_comm (a b : Nat) : a + b = b + a := by induction b with | succ _ ih => _ | _ => _ rewrite zero_add rfl rewrite add_succ rewrite succ_add rewrite ih rfl theorem succ_Eq_add_one (n : Nat) : Nat.succ n = n + 1 := by rewrite one_Eq_succ_zero rewrite add_succ rfl theorem add_rightComm (a b c : Nat) : a + b + c = a + c + b := by rewrite add_assoc rewrite add_comm b rewrite add_assoc rfl
554f4d4d10ed268a1d80ded7c2b9a595f54e9992
acc85b4be2c618b11fc7cb3005521ae6858a8d07
/analysis/topology/uniform_space.lean
0acf70915c22a20952f5121fb944add20c7b56bc
[ "Apache-2.0" ]
permissive
linpingchuan/mathlib
d49990b236574df2a45d9919ba43c923f693d341
5ad8020f67eb13896a41cc7691d072c9331b1f76
refs/heads/master
1,626,019,377,808
1,508,048,784,000
1,508,048,784,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
71,500
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl Theory of uniform spaces. Uniform spaces are a generalization of metric spaces and topological groups. Many concepts directly generalize to uniform spaces, e.g. * completeness * completion (on Cauchy filters instead of Cauchy sequences) * extension of uniform continuous functions to complete spaces * uniform contiunuity & embedding * totally bounded * totally bounded ∧ complete → compact One reason to directly formalize uniform spaces is foundational: we define ℝ as a completion of ℚ. The central concept of uniform spaces is its uniformity: a filter relating two elemenets of the space. This filter is reflexive, symmetric and transitive. So a set (i.e. a relation) in this filter represents a 'distance': it is reflexive, symmetric and the uniformity contains a set for which the `triangular` rule holds. The formalization is mostly based on the books: N. Bourbaki: General Topology I. M. James: Topologies and Uniformities A major difference is that this formalization is heavily based on the filter library. -/ import order.filter data.quot analysis.topology.topological_space analysis.topology.continuity open set lattice filter classical local attribute [instance] decidable_inhabited prop_decidable set_option eqn_compiler.zeta true universes u section variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {ι : Sort*} def id_rel {α : Type*} := {p : α × α | p.1 = p.2} def comp_rel {α : Type u} (r₁ r₂ : set (α×α)) := {p : α × α | ∃z:α, (p.1, z) ∈ r₁ ∧ (z, p.2) ∈ r₂} @[simp] theorem swap_id_rel : prod.swap '' id_rel = @id_rel α := set.ext $ assume ⟨a, b⟩, by simp [image_swap_eq_preimage_swap]; exact eq_comm theorem monotone_comp_rel [preorder β] {f g : β → set (α×α)} (hf : monotone f) (hg : monotone g) : monotone (λx, comp_rel (f x) (g x)) := assume a b h p ⟨z, h₁, h₂⟩, ⟨z, hf h h₁, hg h h₂⟩ lemma prod_mk_mem_comp_rel {a b c : α} {s t : set (α×α)} (h₁ : (a, c) ∈ s) (h₂ : (c, b) ∈ t) : (a, b) ∈ comp_rel s t := ⟨c, h₁, h₂⟩ @[simp] lemma id_comp_rel {r : set (α×α)} : comp_rel id_rel r = r := set.ext $ assume ⟨a, b⟩, ⟨assume ⟨a', heq, ha'⟩, (show a' = a, from heq.symm) ▸ ha', assume ha, ⟨a, rfl, ha⟩⟩ /-- This core description of a uniform space is outside of the type class hierarchy. It is useful for constructions of uniform spaces, when the topology is derived from the uniform space. -/ structure uniform_space.core (α : Type u) := (uniformity : filter (α × α)) (refl : principal id_rel ≤ uniformity) (symm : tendsto prod.swap uniformity uniformity) (comp : uniformity.lift' (λs, comp_rel s s) ≤ uniformity) def uniform_space.core.to_topological_space {α : Type u} (u : uniform_space.core α) : topological_space α := { topological_space . is_open := λs, ∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ u.uniformity.sets, is_open_univ := by simp; intro; exact univ_mem_sets, is_open_inter := assume s t hs ht x ⟨xs, xt⟩, u.uniformity.upwards_sets (inter_mem_sets (hs x xs) (ht x xt)) $ assume p ⟨ps, pt⟩ h, ⟨ps h, pt h⟩, is_open_sUnion := assume s hs x ⟨t, ts, xt⟩, u.uniformity.upwards_sets (hs t ts x xt) $ assume p ph h, ⟨t, ts, ph h⟩ } lemma uniform_space.core_eq : ∀{u₁ u₂ : uniform_space.core α}, u₁.uniformity = u₂.uniformity → u₁ = u₂ | ⟨u₁, _, _, _⟩ ⟨u₂, _, _, _⟩ h := have u₁ = u₂, from h, by simp [*] /-- uniformity: usable typeclass incorporating a topology -/ class uniform_space (α : Type u) extends topological_space α, uniform_space.core α := (is_open_uniformity : ∀s, is_open s ↔ (∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ uniformity.sets)) def uniform_space.of_core {α : Type u} (u : uniform_space.core α) : uniform_space α := { to_core := u, to_topological_space := u.to_topological_space, is_open_uniformity := assume a, iff.refl _ } def uniform_space.of_core_eq {α : Type u} (u : uniform_space.core α) (t : topological_space α) (h : t = u.to_topological_space) : uniform_space α := { to_core := u, to_topological_space := t, is_open_uniformity := assume a, h.symm ▸ iff.refl _ } lemma uniform_space.to_core_to_topological_space (u : uniform_space α) : u.to_core.to_topological_space = u.to_topological_space := topological_space_eq $ funext $ assume s, by rw [uniform_space.core.to_topological_space, uniform_space.is_open_uniformity] lemma uniform_space_eq : ∀{u₁ u₂ : uniform_space α}, u₁.uniformity = u₂.uniformity → u₁ = u₂ | ⟨t₁, u₁, o₁⟩ ⟨t₂, u₂, o₂⟩ h := have u₁ = u₂, from uniform_space.core_eq h, have t₁ = t₂, from topological_space_eq $ funext $ assume s, by rw [o₁, o₂]; simp [this], by simp [*] lemma uniform_space.of_core_eq_to_core (u : uniform_space α) (t : topological_space α) (h : t = u.to_core.to_topological_space) : uniform_space.of_core_eq u.to_core t h = u := uniform_space_eq rfl section uniform_space variables [uniform_space α] def uniformity : filter (α × α) := (@uniform_space.to_core α _).uniformity lemma is_open_uniformity {s : set α} : is_open s ↔ (∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ (@uniformity α _).sets) := uniform_space.is_open_uniformity s lemma refl_le_uniformity : principal id_rel ≤ @uniformity α _ := (@uniform_space.to_core α _).refl lemma refl_mem_uniformity {x : α} {s : set (α × α)} (h : s ∈ (@uniformity α _).sets) : (x, x) ∈ s := refl_le_uniformity h rfl lemma symm_le_uniformity : map (@prod.swap α α) uniformity ≤ uniformity := (@uniform_space.to_core α _).symm lemma comp_le_uniformity : uniformity.lift' (λs:set (α×α), comp_rel s s) ≤ uniformity := (@uniform_space.to_core α _).comp lemma tendsto_swap_uniformity : tendsto prod.swap (@uniformity α _) uniformity := symm_le_uniformity lemma tendsto_const_uniformity {a : α} {f : filter β} : tendsto (λ_, (a, a)) f uniformity := assume s hs, show {x | (a, a) ∈ s} ∈ f.sets, from univ_mem_sets' $ assume b, refl_mem_uniformity hs lemma comp_mem_uniformity_sets {s : set (α × α)} (hs : s ∈ (@uniformity α _).sets) : ∃t∈(@uniformity α _).sets, comp_rel t t ⊆ s := have s ∈ (uniformity.lift' (λt:set (α×α), comp_rel t t)).sets, from comp_le_uniformity hs, (mem_lift'_iff $ monotone_comp_rel monotone_id monotone_id).mp this lemma symm_of_uniformity {s : set (α × α)} (hs : s ∈ (@uniformity α _).sets) : ∃t∈(@uniformity α _).sets, (∀a b, (a, b) ∈ t → (b, a) ∈ t) ∧ t ⊆ s := have preimage prod.swap s ∈ (@uniformity α _).sets, from symm_le_uniformity hs, ⟨s ∩ preimage prod.swap s, inter_mem_sets hs this, assume a b ⟨h₁, h₂⟩, ⟨h₂, h₁⟩, inter_subset_left _ _⟩ lemma comp_symm_of_uniformity {s : set (α × α)} (hs : s ∈ (@uniformity α _).sets) : ∃t∈(@uniformity α _).sets, (∀{a b}, (a, b) ∈ t → (b, a) ∈ t) ∧ comp_rel t t ⊆ s := let ⟨t, ht₁, ht₂⟩ := comp_mem_uniformity_sets hs in let ⟨t', ht', ht'₁, ht'₂⟩ := symm_of_uniformity ht₁ in ⟨t', ht', ht'₁, subset.trans (monotone_comp_rel monotone_id monotone_id ht'₂) ht₂⟩ lemma uniformity_le_symm : uniformity ≤ map (@prod.swap α α) uniformity := calc uniformity = id <$> uniformity : (functor.id_map _).symm ... = (@prod.swap α α ∘ prod.swap) <$> uniformity : congr_arg (λf : (α×α)→(α×α), f <$> uniformity) (by apply funext; intro x; cases x; refl) ... = (map prod.swap ∘ map prod.swap) uniformity : congr map_compose rfl ... ≤ (@prod.swap α α) <$> uniformity : map_mono symm_le_uniformity lemma uniformity_eq_symm : uniformity = (@prod.swap α α) <$> uniformity := le_antisymm uniformity_le_symm symm_le_uniformity theorem uniformity_lift_le_swap {g : set (α×α) → filter β} {f : filter β} (hg : monotone g) (h : uniformity.lift (λs, g (preimage prod.swap s)) ≤ f) : uniformity.lift g ≤ f := le_trans (lift_mono uniformity_le_symm (le_refl _)) (by rw [map_lift_eq2 hg, image_swap_eq_preimage_swap]; exact h) lemma uniformity_lift_le_comp {f : set (α×α) → filter β} (h : monotone f): uniformity.lift (λs, f (comp_rel s s)) ≤ uniformity.lift f := calc uniformity.lift (λs, f (comp_rel s s)) = (uniformity.lift' (λs:set (α×α), comp_rel s s)).lift f : begin rw [lift_lift'_assoc], exact monotone_comp_rel monotone_id monotone_id, exact h end ... ≤ uniformity.lift f : lift_mono comp_le_uniformity (le_refl _) lemma comp_le_uniformity3 : uniformity.lift' (λs:set (α×α), comp_rel s (comp_rel s s)) ≤ uniformity := calc uniformity.lift' (λd, comp_rel d (comp_rel d d)) = uniformity.lift (λs, uniformity.lift' (λt:set(α×α), comp_rel s (comp_rel t t))) : begin rw [lift_lift'_same_eq_lift'], exact (assume x, monotone_comp_rel monotone_const $ monotone_comp_rel monotone_id monotone_id), exact (assume x, monotone_comp_rel monotone_id monotone_const), end ... ≤ uniformity.lift (λs, uniformity.lift' (λt:set(α×α), comp_rel s t)) : lift_mono' $ assume s hs, @uniformity_lift_le_comp α _ _ (principal ∘ comp_rel s) $ monotone_comp (monotone_comp_rel monotone_const monotone_id) monotone_principal ... = uniformity.lift' (λs:set(α×α), comp_rel s s) : lift_lift'_same_eq_lift' (assume s, monotone_comp_rel monotone_const monotone_id) (assume s, monotone_comp_rel monotone_id monotone_const) ... ≤ uniformity : comp_le_uniformity lemma mem_nhds_uniformity_iff {x : α} {s : set α} : (s ∈ (nhds x).sets) ↔ ({p : α × α | p.1 = x → p.2 ∈ s} ∈ (@uniformity α _).sets) := ⟨ begin simp [mem_nhds_sets_iff, is_open_uniformity], exact assume t ts xt ht, uniformity.upwards_sets (ht x xt) $ assume ⟨x', y⟩ h eq, ts $ h eq end, assume hs, mem_nhds_sets_iff.mpr ⟨{x | {p : α × α | p.1 = x → p.2 ∈ s} ∈ (@uniformity α _).sets}, assume x', assume hx' : {p : α × α | p.fst = x' → p.snd ∈ s} ∈ (@uniformity α _).sets, refl_mem_uniformity hx' rfl, is_open_uniformity.mpr $ assume x' hx', let ⟨t, ht, tr⟩ := comp_mem_uniformity_sets hx' in uniformity.upwards_sets ht $ assume ⟨a, b⟩ hp' (eq : a = x'), have hp : (x', b) ∈ t, from eq ▸ hp', show {p : α × α | p.fst = b → p.snd ∈ s} ∈ (@uniformity α _).sets, from uniformity.upwards_sets ht $ assume ⟨a, b'⟩ hp' (heq : a = b), have (b, b') ∈ t, from heq ▸ hp', have (x', b') ∈ comp_rel t t, from ⟨b, hp, this⟩, show b' ∈ s, from tr this rfl, hs⟩⟩ lemma nhds_eq_vmap_uniformity {x : α} : nhds x = uniformity.vmap (prod.mk x) := filter_eq $ set.ext $ assume s, by rw [mem_nhds_uniformity_iff, mem_vmap]; from iff.intro (assume hs, ⟨_, hs, assume x hx, hx rfl⟩) (assume ⟨t, h, ht⟩, uniformity.upwards_sets h $ assume ⟨p₁, p₂⟩ hp (h : p₁ = x), ht $ by simp [h.symm, hp]) lemma nhds_eq_uniformity {x : α} : nhds x = uniformity.lift' (λs:set (α×α), {y | (x, y) ∈ s}) := filter_eq $ set.ext $ assume s, begin rw [mem_lift'_iff], tactic.swap, apply monotone_preimage, simp [mem_nhds_uniformity_iff], exact ⟨assume h, ⟨_, h, assume y h, h rfl⟩, assume ⟨t, h₁, h₂⟩, uniformity.upwards_sets h₁ $ assume ⟨x', y⟩ hp (eq : x' = x), h₂ $ show (x, y) ∈ t, from eq ▸ hp⟩ end lemma mem_nhds_left {x : α} {s : set (α×α)} (h : s ∈ (uniformity.sets : set (set (α×α)))) : {y : α | (x, y) ∈ s} ∈ (nhds x).sets := have nhds x ≤ principal {y : α | (x, y) ∈ s}, by rw [nhds_eq_uniformity]; exact infi_le_of_le s (infi_le _ h), by simp at this; assumption lemma mem_nhds_right {y : α} {s : set (α×α)} (h : s ∈ (uniformity.sets : set (set (α×α)))) : {x : α | (x, y) ∈ s} ∈ (nhds y).sets := mem_nhds_left (symm_le_uniformity h) lemma tendsto_right_nhds_uniformity {a : α} : tendsto (λa', (a', a)) (nhds a) uniformity := assume s hs, show {a' | (a', a) ∈ s} ∈ (nhds a).sets, from mem_nhds_right hs lemma tendsto_left_nhds_uniformity {a : α} : tendsto (λa', (a, a')) (nhds a) uniformity := assume s hs, show {a' | (a, a') ∈ s} ∈ (nhds a).sets, from mem_nhds_left hs lemma lift_nhds_left {x : α} {g : set α → filter β} (hg : monotone g) : (nhds x).lift g = uniformity.lift (λs:set (α×α), g {y | (x, y) ∈ s}) := eq.trans begin rw [nhds_eq_uniformity], exact (filter.lift_assoc $ monotone_comp monotone_preimage $ monotone_comp monotone_preimage monotone_principal) end (congr_arg _ $ funext $ assume s, filter.lift_principal hg) lemma lift_nhds_right {x : α} {g : set α → filter β} (hg : monotone g) : (nhds x).lift g = uniformity.lift (λs:set (α×α), g {y | (y, x) ∈ s}) := calc (nhds x).lift g = uniformity.lift (λs:set (α×α), g {y | (x, y) ∈ s}) : lift_nhds_left hg ... = ((@prod.swap α α) <$> uniformity).lift (λs:set (α×α), g {y | (x, y) ∈ s}) : by rw [←uniformity_eq_symm] ... = uniformity.lift (λs:set (α×α), g {y | (x, y) ∈ image prod.swap s}) : map_lift_eq2 $ monotone_comp monotone_preimage hg ... = _ : by simp [image_swap_eq_preimage_swap] lemma nhds_nhds_eq_uniformity_uniformity_prod {a b : α} : filter.prod (nhds a) (nhds b) = uniformity.lift (λs:set (α×α), uniformity.lift' (λt:set (α×α), set.prod {y : α | (y, a) ∈ s} {y : α | (b, y) ∈ t})) := show (nhds a).lift (λs:set α, (nhds b).lift (λt:set α, principal (set.prod s t))) = _, begin rw [lift_nhds_right], apply congr_arg, apply funext, intro s, rw [lift_nhds_left], refl, exact monotone_comp (monotone_prod monotone_const monotone_id) monotone_principal, exact (monotone_lift' monotone_const $ monotone_lam $ assume x, monotone_prod monotone_id monotone_const) end lemma nhds_eq_uniformity_prod {a b : α} : nhds (a, b) = uniformity.lift' (λs:set (α×α), set.prod {y : α | (y, a) ∈ s} {y : α | (b, y) ∈ s}) := begin rw [nhds_prod_eq, nhds_nhds_eq_uniformity_uniformity_prod, lift_lift'_same_eq_lift'], { intro s, exact monotone_prod monotone_const monotone_preimage }, { intro t, exact monotone_prod monotone_preimage monotone_const } end lemma nhdset_of_mem_uniformity {d : set (α×α)} (s : set (α×α)) (hd : d ∈ (@uniformity α _).sets) : ∃(t : set (α×α)), is_open t ∧ s ⊆ t ∧ t ⊆ {p | ∃x y, (p.1, x) ∈ d ∧ (x, y) ∈ s ∧ (y, p.2) ∈ d} := let cl_d := {p:α×α | ∃x y, (p.1, x) ∈ d ∧ (x, y) ∈ s ∧ (y, p.2) ∈ d} in have ∀p ∈ s, ∃t ⊆ cl_d, is_open t ∧ p ∈ t, from assume ⟨x, y⟩ hp, mem_nhds_sets_iff.mp $ show cl_d ∈ (nhds (x, y)).sets, begin rw [nhds_eq_uniformity_prod, mem_lift'_iff], exact ⟨d, hd, assume ⟨a, b⟩ ⟨ha, hb⟩, ⟨x, y, ha, hp, hb⟩⟩, exact monotone_prod monotone_preimage monotone_preimage end, have ∃t:(Π(p:α×α) (h:p ∈ s), set (α×α)), ∀p, ∀h:p ∈ s, t p h ⊆ cl_d ∧ is_open (t p h) ∧ p ∈ t p h, by simp [classical.skolem] at this; simp; assumption, match this with | ⟨t, ht⟩ := ⟨(⋃ p:α×α, ⋃ h : p ∈ s, t p h : set (α×α)), is_open_Union $ assume (p:α×α), is_open_Union $ assume hp, (ht p hp).right.left, assume ⟨a, b⟩ hp, begin simp; exact ⟨a, b, hp, (ht (a,b) hp).right.right⟩ end, Union_subset $ assume p, Union_subset $ assume hp, (ht p hp).left⟩ end lemma closure_eq_inter_uniformity {t : set (α×α)} : closure t = (⋂ d∈(@uniformity α _).sets, comp_rel d (comp_rel t d)) := set.ext $ assume ⟨a, b⟩, calc (a, b) ∈ closure t ↔ (nhds (a, b) ⊓ principal t ≠ ⊥) : by simp [closure_eq_nhds] ... ↔ (((@prod.swap α α) <$> uniformity).lift' (λ (s : set (α × α)), set.prod {x : α | (x, a) ∈ s} {y : α | (b, y) ∈ s}) ⊓ principal t ≠ ⊥) : by rw [←uniformity_eq_symm, nhds_eq_uniformity_prod] ... ↔ ((map (@prod.swap α α) uniformity).lift' (λ (s : set (α × α)), set.prod {x : α | (x, a) ∈ s} {y : α | (b, y) ∈ s}) ⊓ principal t ≠ ⊥) : by refl ... ↔ (uniformity.lift' (λ (s : set (α × α)), set.prod {y : α | (a, y) ∈ s} {x : α | (x, b) ∈ s}) ⊓ principal t ≠ ⊥) : begin rw [map_lift'_eq2], simp [image_swap_eq_preimage_swap, function.comp], exact monotone_prod monotone_preimage monotone_preimage end ... ↔ (∀s∈(@uniformity α _).sets, ∃x, x ∈ set.prod {y : α | (a, y) ∈ s} {x : α | (x, b) ∈ s} ∩ t) : begin rw [lift'_inf_principal_eq, lift'_neq_bot_iff], apply forall_congr, intro s, rw [ne_empty_iff_exists_mem], exact monotone_inter (monotone_prod monotone_preimage monotone_preimage) monotone_const end ... ↔ (∀s∈(@uniformity α _).sets, (a, b) ∈ comp_rel s (comp_rel t s)) : forall_congr $ assume s, forall_congr $ assume hs, ⟨assume ⟨⟨x, y⟩, ⟨⟨hx, hy⟩, hxyt⟩⟩, ⟨x, hx, y, hxyt, hy⟩, assume ⟨x, hx, y, hxyt, hy⟩, ⟨⟨x, y⟩, ⟨⟨hx, hy⟩, hxyt⟩⟩⟩ ... ↔ _ : by simp lemma uniformity_eq_uniformity_closure : (@uniformity α _) = uniformity.lift' closure := le_antisymm (le_infi $ assume s, le_infi $ assume hs, by simp; exact uniformity.upwards_sets hs subset_closure) (calc uniformity.lift' closure ≤ uniformity.lift' (λd, comp_rel d (comp_rel d d)) : lift'_mono' (by intros s hs; rw [closure_eq_inter_uniformity]; exact bInter_subset_of_mem hs) ... ≤ uniformity : comp_le_uniformity3) lemma uniformity_eq_uniformity_interior : (@uniformity α _) = uniformity.lift' interior := le_antisymm (le_infi $ assume d, le_infi $ assume hd, let ⟨s, hs, hs_comp⟩ := (mem_lift'_iff $ monotone_comp_rel monotone_id $ monotone_comp_rel monotone_id monotone_id).mp (comp_le_uniformity3 hd) in let ⟨t, ht, hst, ht_comp⟩ := nhdset_of_mem_uniformity s hs in have s ⊆ interior d, from calc s ⊆ t : hst ... ⊆ interior d : (subset_interior_iff_subset_of_open ht).mpr $ assume x, assume : x ∈ t, let ⟨x, y, h₁, h₂, h₃⟩ := ht_comp this in hs_comp ⟨x, h₁, y, h₂, h₃⟩, have interior d ∈ (@uniformity α _).sets, from (@uniformity α _).upwards_sets hs $ this, by simp [this]) (assume s hs, (uniformity.lift' interior).upwards_sets (mem_lift' hs) interior_subset) lemma interior_mem_uniformity {s : set (α × α)} (hs : s ∈ (@uniformity α _).sets) : interior s ∈ (@uniformity α _).sets := by rw [uniformity_eq_uniformity_interior]; exact mem_lift' hs lemma mem_uniformity_is_closed [uniform_space α] {s : set (α×α)} (h : s ∈ (@uniformity α _).sets) : ∃t∈(@uniformity α _).sets, is_closed t ∧ t ⊆ s := have s ∈ ((@uniformity α _).lift' closure).sets, by rwa [uniformity_eq_uniformity_closure] at h, have ∃t∈(@uniformity α _).sets, closure t ⊆ s, by rwa [mem_lift'_iff] at this; apply closure_mono, let ⟨t, ht, hst⟩ := this in ⟨closure t, uniformity.upwards_sets ht subset_closure, is_closed_closure, hst⟩ /- uniform continuity -/ definition uniform_continuous [uniform_space β] (f : α → β) := tendsto (λx:α×α, (f x.1, f x.2)) uniformity uniformity lemma uniform_continuous_id : uniform_continuous (@id α) := by simp [uniform_continuous]; exact tendsto_id lemma uniform_continuous_const [uniform_space β] {b : β} : uniform_continuous (λa:α, b) := @tendsto_const_uniformity _ _ _ b uniformity lemma uniform_continuous_compose [uniform_space β] [uniform_space γ] {f : α → β} {g : β → γ} (hf : uniform_continuous f) (hg : uniform_continuous g) : uniform_continuous (g ∘ f) := tendsto_compose hf hg definition uniform_embedding [uniform_space β] (f : α → β) := (∀a₁ a₂, f a₁ = f a₂ → a₁ = a₂) ∧ vmap (λx:α×α, (f x.1, f x.2)) uniformity = uniformity lemma uniform_continuous_of_embedding [uniform_space β] {f : α → β} (hf : uniform_embedding f) : uniform_continuous f := by simp [uniform_continuous, hf.right.symm]; exact tendsto_vmap lemma dense_embedding_of_uniform_embedding [uniform_space β] {f : α → β} (h : uniform_embedding f) (hd : ∀x, x ∈ closure (f '' univ)) : dense_embedding f := { dense_embedding . dense := hd, inj := h.left, induced := begin intro a, simp [h.right.symm, nhds_eq_uniformity], rw [vmap_lift'_eq, vmap_lift'_eq2], refl, exact monotone_preimage, exact monotone_preimage end } lemma continuous_of_uniform [uniform_space β] {f : α → β} (hf : uniform_continuous f) : continuous f := continuous_iff_tendsto.mpr $ assume a, calc map f (nhds a) ≤ (map (λp:α×α, (f p.1, f p.2)) uniformity).lift' (λs:set (β×β), {y | (f a, y) ∈ s}) : begin rw [nhds_eq_uniformity, map_lift'_eq, map_lift'_eq2], exact (lift'_mono' $ assume s hs b ⟨a', (ha' : (_, a') ∈ s), a'_eq⟩, ⟨(a, a'), ha', show (f a, f a') = (f a, b), from a'_eq ▸ rfl⟩), exact monotone_preimage, exact monotone_preimage end ... ≤ nhds (f a) : by rw [nhds_eq_uniformity]; exact lift'_mono hf (le_refl _) lemma closure_image_mem_nhds_of_uniform_embedding [uniform_space α] [uniform_space β] {s : set (α×α)} {e : α → β} (b : β) (he₁ : uniform_embedding e) (he₂ : dense_embedding e) (hs : s ∈ (@uniformity α _).sets) : ∃a, closure (e '' {a' | (a, a') ∈ s}) ∈ (nhds b).sets := have s ∈ (vmap (λp:α×α, (e p.1, e p.2)) $ uniformity).sets, from he₁.right.symm ▸ hs, let ⟨t₁, ht₁u, ht₁⟩ := this in have ht₁ : ∀p:α×α, (e p.1, e p.2) ∈ t₁ → p ∈ s, from ht₁, let ⟨t₂, ht₂u, ht₂s, ht₂c⟩ := comp_symm_of_uniformity ht₁u in let ⟨t, htu, hts, htc⟩ := comp_symm_of_uniformity ht₂u in have preimage e {b' | (b, b') ∈ t₂} ∈ (vmap e $ nhds b).sets, from preimage_mem_vmap $ mem_nhds_left ht₂u, let ⟨a, (ha : (b, e a) ∈ t₂)⟩ := inhabited_of_mem_sets (he₂.vmap_nhds_neq_bot) this in have ∀b' (s' : set (β × β)), (b, b') ∈ t → s' ∈ (@uniformity β _).sets → {y : β | (b', y) ∈ s'} ∩ e '' {a' : α | (a, a') ∈ s} ≠ ∅, from assume b' s' hb' hs', have preimage e {b'' | (b', b'') ∈ s' ∩ t} ∈ (vmap e $ nhds b').sets, from preimage_mem_vmap $ mem_nhds_left $ inter_mem_sets hs' htu, let ⟨a₂, ha₂s', ha₂t⟩ := inhabited_of_mem_sets (he₂.vmap_nhds_neq_bot) this in have (e a, e a₂) ∈ t₁, from ht₂c $ prod_mk_mem_comp_rel (ht₂s ha) $ htc $ prod_mk_mem_comp_rel hb' ha₂t, have e a₂ ∈ {b'':β | (b', b'') ∈ s'} ∩ e '' {a' | (a, a') ∈ s}, from ⟨ha₂s', mem_image_of_mem _ $ ht₁ (a, a₂) this⟩, ne_empty_of_mem this, have ∀b', (b, b') ∈ t → nhds b' ⊓ principal (e '' {a' | (a, a') ∈ s}) ≠ ⊥, begin intros b' hb', rw [nhds_eq_uniformity, lift'_inf_principal_eq, lift'_neq_bot_iff], exact assume s, this b' s hb', exact monotone_inter monotone_preimage monotone_const end, have ∀b', (b, b') ∈ t → b' ∈ closure (e '' {a' | (a, a') ∈ s}), from assume b' hb', by rw [closure_eq_nhds]; exact this b' hb', ⟨a, (nhds b).upwards_sets (mem_nhds_left htu) this⟩ /- cauchy filters -/ definition cauchy (f : filter α) := f ≠ ⊥ ∧ filter.prod f f ≤ uniformity lemma cauchy_iff [uniform_space α] {f : filter α} : cauchy f ↔ (f ≠ ⊥ ∧ (∀s∈(@uniformity α _).sets, ∃t∈f.sets, set.prod t t ⊆ s)) := and_congr (iff.refl _) $ forall_congr $ assume s, forall_congr $ assume hs, mem_prod_same_iff 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 (nhds a) := ⟨nhds_neq_bot, calc filter.prod (nhds a) (nhds a) = uniformity.lift (λs:set (α×α), uniformity.lift' (λt:set(α×α), set.prod {y : α | (y, a) ∈ s} {y : α | (a, y) ∈ t})) : nhds_nhds_eq_uniformity_uniformity_prod ... ≤ uniformity.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⟩ ... ≤ uniformity : comp_le_uniformity⟩ lemma cauchy_pure {a : α} : cauchy (pure a) := cauchy_downwards cauchy_nhds (show principal {a} ≠ ⊥, by simp) (return_le_nhds a) lemma le_nhds_of_cauchy_adhp {f : filter α} {x : α} (hf : cauchy f) (adhs : f ⊓ nhds x ≠ ⊥) : f ≤ nhds x := have ∀s∈f.sets, x ∈ closure s, begin intros s hs, simp [closure_eq_nhds, inf_comm], exact assume h', adhs $ bot_unique $ h' ▸ inf_le_inf (by simp; exact hs) (le_refl _) end, calc f ≤ f.lift' (λs:set α, {y | x ∈ closure s ∧ y ∈ closure s}) : le_infi $ assume s, le_infi $ assume hs, begin rw [←forall_sets_neq_empty_iff_neq_bot] at adhs, simp [this s hs], exact f.upwards_sets hs subset_closure end ... ≤ f.lift' (λs:set α, {y | (x, y) ∈ closure (set.prod s s)}) : by simp [closure_prod_eq]; exact le_refl _ ... = (filter.prod f f).lift' (λs:set (α×α), {y | (x, y) ∈ closure s}) : begin rw [prod_same_eq], rw [lift'_lift'_assoc], exact monotone_prod monotone_id monotone_id, exact monotone_comp (assume s t h x h', closure_mono h h') monotone_preimage end ... ≤ uniformity.lift' (λs:set (α×α), {y | (x, y) ∈ closure s}) : lift'_mono hf.right (le_refl _) ... = (uniformity.lift' closure).lift' (λs:set (α×α), {y | (x, y) ∈ s}) : begin rw [lift'_lift'_assoc], exact assume s t h, closure_mono h, exact monotone_preimage end ... = uniformity.lift' (λs:set (α×α), {y | (x, y) ∈ s}) : by rw [←uniformity_eq_uniformity_closure] ... = nhds x : by rw [nhds_eq_uniformity] lemma le_nhds_iff_adhp_of_cauchy {f : filter α} {x : α} (hf : cauchy f) : f ≤ nhds x ↔ f ⊓ nhds 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)) uniformity : map_mono hf.right ... ≤ uniformity : hm⟩ lemma cauchy_vmap [uniform_space β] {f : filter β} {m : α → β} (hm : vmap (λp:α×α, (m p.1, m p.2)) uniformity ≤ uniformity) (hf : cauchy f) (hb : vmap m f ≠ ⊥) : cauchy (vmap m f) := ⟨hb, calc filter.prod (vmap m f) (vmap m f) = vmap (λp:α×α, (m p.1, m p.2)) (filter.prod f f) : filter.prod_vmap_vmap_eq ... ≤ vmap (λp:α×α, (m p.1, m p.2)) uniformity : vmap_mono hf.right ... ≤ uniformity : hm⟩ /- separated uniformity -/ protected def separation_rel (α : Type u) [u : uniform_space α] := (⋂₀ (@uniformity α _).sets) lemma separated_equiv : equivalence (λx y, (x, y) ∈ separation_rel α) := ⟨assume x, assume s, refl_mem_uniformity, assume x y, assume h (s : set (α×α)) hs, have preimage prod.swap s ∈ (@uniformity α _).sets, from symm_le_uniformity hs, h _ this, assume x y z (hxy : (x, y) ∈ separation_rel α) (hyz : (y, z) ∈ separation_rel α) s (hs : s ∈ (@uniformity α _).sets), let ⟨t, ht, (h_ts : comp_rel t t ⊆ s)⟩ := comp_mem_uniformity_sets hs in h_ts $ show (x, z) ∈ comp_rel t t, from ⟨y, hxy t ht, hyz t ht⟩⟩ protected def separation_setoid (α : Type u) [u : uniform_space α] : setoid α := ⟨λx y, (x, y) ∈ separation_rel α, separated_equiv⟩ @[class] definition separated (α : Type u) [u : uniform_space α] := separation_rel α = id_rel instance separated_t2 [s : separated α] : t2_space α := ⟨assume x y, assume h : x ≠ y, have separation_rel α = id_rel, from s, have (x, y) ∉ separation_rel α, by simp [this]; exact h, let ⟨d, hd, (hxy : (x, y) ∉ d)⟩ := classical.not_ball.1 this in let ⟨d', hd', (hd'd' : comp_rel d' d' ⊆ d)⟩ := comp_mem_uniformity_sets hd in have {y | (x, y) ∈ d'} ∈ (nhds x).sets, from mem_nhds_left hd', let ⟨u, hu₁, hu₂, hu₃⟩ := mem_nhds_sets_iff.mp this in have {x | (x, y) ∈ d'} ∈ (nhds y).sets, from mem_nhds_right hd', let ⟨v, hv₁, hv₂, hv₃⟩ := mem_nhds_sets_iff.mp this in have u ∩ v = ∅, from eq_empty_of_subset_empty $ assume z ⟨(h₁ : z ∈ u), (h₂ : z ∈ v)⟩, have (x, y) ∈ comp_rel d' d', from ⟨z, hu₁ h₁, hv₁ h₂⟩, hxy $ hd'd' this, ⟨u, v, hu₂, hv₂, hu₃, hv₃, this⟩⟩ instance separated_regular [separated α] : regular_space α := { separated_t2 with regular := λs a hs ha, have -s ∈ (nhds a).sets, from mem_nhds_sets hs ha, have {p : α × α | p.1 = a → p.2 ∈ -s} ∈ uniformity.sets, from mem_nhds_uniformity_iff.mp this, let ⟨d, hd, h⟩ := comp_mem_uniformity_sets this in let e := {y:α| (a, y) ∈ d} in have hae : a ∈ closure e, from subset_closure $ refl_mem_uniformity hd, have set.prod (closure e) (closure e) ⊆ comp_rel d (comp_rel (set.prod e e) d), begin rw [←closure_prod_eq, closure_eq_inter_uniformity], change (⨅d' ∈ uniformity.sets, _) ≤ comp_rel d (comp_rel _ d), exact (infi_le_of_le d $ infi_le_of_le hd $ le_refl _) end, have e_subset : closure e ⊆ -s, from assume a' ha', let ⟨x, (hx : (a, x) ∈ d), y, ⟨hx₁, hx₂⟩, (hy : (y, _) ∈ d)⟩ := @this ⟨a, a'⟩ ⟨hae, ha'⟩ in have (a, a') ∈ comp_rel d d, from ⟨y, hx₂, hy⟩, h this rfl, have closure e ∈ (nhds a).sets, from (nhds a).upwards_sets (mem_nhds_left hd) subset_closure, have nhds a ⊓ principal (-closure e) = ⊥, from (@inf_eq_bot_iff_le_compl _ _ _ (principal (- closure e)) (principal (closure e)) (by simp [principal_univ]) (by simp)).mpr (by simp [this]), ⟨- closure e, is_closed_closure, assume x h₁ h₂, @e_subset x h₂ h₁, this⟩ } /- totally bounded -/ def totally_bounded (s : set α) : Prop := ∀d ∈ (@uniformity α _).sets, ∃t : set α, finite t ∧ s ⊆ (⋃y∈t, {x | (x,y) ∈ d}) lemma totally_bounded_subset [uniform_space α] {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_closure [uniform_space α] {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_Union hcf $ assume i hi, continuous_iff_is_closed.mp (continuous_prod_mk continuous_id 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 α] [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} ∈ (@uniformity α _).sets, from hf ht, let ⟨c, hfc, hct⟩ := hs _ this in ⟨f '' c, finite_image 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 : 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 f.upwards_sets (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).upwards_sets (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_right_antimono $ Union_subset_Union $ assume t, Union_subset_Union_const or.inl, principal_mono.mpr $ diff_right_antimono $ Union_subset_Union $ assume t, Union_subset_Union_const or.inr⟩) (assume ⟨t, ht⟩, by simp [diff_neq_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_insert finite.empty⟩ $ 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.upwards_sets 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, 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_of_totally_bounded_complete {s : set α} (ht : totally_bounded s) (hc : ∀{f:filter α}, cauchy f → f ≤ principal s → ∃x∈s, f ≤ nhds x) : compact s := begin rw [compact_iff_ultrafilter_le_nhds], rw [totally_bounded_iff_ultrafilter] at ht, exact assume f hf hfs, hc (ht _ hf hfs) hfs end /- complete space -/ class complete_space (α : Type u) [uniform_space α] : Prop := (complete : ∀{f:filter α}, cauchy f → ∃x, f ≤ nhds x) lemma complete_of_is_closed [complete_space α] {s : set α} {f : filter α} (h : is_closed s) (hf : cauchy f) (hfs : f ≤ principal s) : ∃x∈s, f ≤ nhds x := let ⟨x, hx⟩ := complete_space.complete hf in have x ∈ s, from is_closed_iff_nhds.mp h x $ neq_bot_of_le_neq_bot hf.left $ le_inf hx hfs, ⟨x, this, hx⟩ lemma compact_of_totally_bounded_is_closed [complete_space α] {s : set α} (ht : totally_bounded s) (hc : is_closed s) : compact s := @compact_of_totally_bounded_complete α _ s ht $ assume f, complete_of_is_closed hc lemma complete_space_extension [uniform_space β] {m : β → α} (hm : uniform_embedding m) (dense : ∀x, x ∈ closure (m '' univ)) (h : ∀f:filter β, cauchy f → ∃x:α, map m f ≤ nhds x) : complete_space α := ⟨assume (f : filter α), assume hf : cauchy f, let p : set (α × α) → set α → set α := λs t, {y : α| ∃x:α, x ∈ t ∧ (x, y) ∈ s}, g := uniformity.lift (λs, f.lift' (p s)) in have mp₀ : monotone p, from assume a b h t s ⟨x, xs, xa⟩, ⟨x, xs, h xa⟩, have mp₁ : ∀{s}, monotone (p s), from assume s a b h x ⟨y, ya, yxs⟩, ⟨y, h ya, yxs⟩, have f ≤ g, from le_infi $ assume s, le_infi $ assume hs, le_infi $ assume t, le_infi $ assume ht, le_principal_iff.mpr $ f.upwards_sets ht $ assume x hx, ⟨x, hx, refl_mem_uniformity hs⟩, have g ≠ ⊥, from neq_bot_of_le_neq_bot hf.left this, have vmap m g ≠ ⊥, from vmap_neq_bot $ assume t ht, let ⟨t', ht', ht_mem⟩ := (mem_lift_iff $ monotone_lift' monotone_const mp₀).mp ht in let ⟨t'', ht'', ht'_sub⟩ := (mem_lift'_iff mp₁).mp ht_mem in let ⟨x, (hx : x ∈ t'')⟩ := inhabited_of_mem_sets hf.left ht'' in have h₀ : nhds x ⊓ principal (m '' univ) ≠ ⊥, by simp [closure_eq_nhds] at dense; exact dense x, have h₁ : {y | (x, y) ∈ t'} ∈ (nhds x ⊓ principal (m '' univ)).sets, from @mem_inf_sets_of_left α (nhds x) (principal (m '' univ)) _ $ mem_nhds_left ht', have h₂ : m '' univ ∈ (nhds x ⊓ principal (m '' univ)).sets, from @mem_inf_sets_of_right α (nhds x) (principal (m '' univ)) _ $ subset.refl _, have {y | (x, y) ∈ t'} ∩ m '' univ ∈ (nhds x ⊓ principal (m '' univ)).sets, from @inter_mem_sets α (nhds x ⊓ principal (m '' univ)) _ _ h₁ h₂, let ⟨y, xyt', b, _, b_eq⟩ := inhabited_of_mem_sets h₀ this in ⟨b, b_eq.symm ▸ ht'_sub ⟨x, hx, xyt'⟩⟩, have cauchy g, from ⟨‹g ≠ ⊥›, assume s hs, let ⟨s₁, hs₁, (comp_s₁ : comp_rel s₁ s₁ ⊆ s)⟩ := comp_mem_uniformity_sets hs, ⟨s₂, hs₂, (comp_s₂ : comp_rel s₂ s₂ ⊆ s₁)⟩ := comp_mem_uniformity_sets hs₁, ⟨t, ht, (prod_t : set.prod t t ⊆ s₂)⟩ := mem_prod_same_iff.mp (hf.right hs₂) in have hg₁ : p (preimage prod.swap s₁) t ∈ g.sets, from mem_lift (symm_le_uniformity hs₁) $ @mem_lift' α α f _ t ht, have hg₂ : p s₂ t ∈ g.sets, from mem_lift hs₂ $ @mem_lift' α α f _ t ht, have hg : set.prod (p (preimage prod.swap s₁) t) (p s₂ t) ∈ (filter.prod g g).sets, from @prod_mem_prod α α _ _ g g hg₁ hg₂, (filter.prod g g).upwards_sets hg (assume ⟨a, b⟩ ⟨⟨c₁, c₁t, hc₁⟩, ⟨c₂, c₂t, hc₂⟩⟩, have (c₁, c₂) ∈ set.prod t t, from ⟨c₁t, c₂t⟩, comp_s₁ $ prod_mk_mem_comp_rel hc₁ $ comp_s₂ $ prod_mk_mem_comp_rel (prod_t this) hc₂)⟩, have cauchy (filter.vmap m g), from cauchy_vmap (le_of_eq hm.right) ‹cauchy g› (by assumption), let ⟨x, (hx : map m (filter.vmap m g) ≤ nhds x)⟩ := h _ this in have map m (filter.vmap m g) ⊓ nhds x ≠ ⊥, from (le_nhds_iff_adhp_of_cauchy (cauchy_map (uniform_continuous_of_embedding hm) this)).mp hx, have g ⊓ nhds x ≠ ⊥, from neq_bot_of_le_neq_bot this (inf_le_inf (assume s hs, ⟨s, hs, subset.refl _⟩) (le_refl _)), ⟨x, calc f ≤ g : by assumption ... ≤ nhds x : le_nhds_of_cauchy_adhp ‹cauchy g› this⟩⟩ /- separation space -/ section separation_space local attribute [instance] separation_setoid instance {α : Type u} [u : uniform_space α] : uniform_space (quotient (separation_setoid α)) := { uniform_space . to_topological_space := u.to_topological_space.coinduced (λx, ⟦x⟧), uniformity := map (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)) uniformity, refl := assume s hs ⟨a, b⟩ (h : a = b), have ∀a:α, (a, a) ∈ preimage (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧)) s, from assume a, refl_mem_uniformity hs, h ▸ quotient.induction_on a this, symm := tendsto_map' $ by simp [prod.swap, (∘)]; exact tendsto_compose tendsto_swap_uniformity tendsto_map, comp := calc (map (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧)) uniformity).lift' (λs, comp_rel s s) = uniformity.lift' ((λs, comp_rel s s) ∘ image (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧))) : map_lift'_eq2 $ monotone_comp_rel monotone_id monotone_id ... ≤ uniformity.lift' (image (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧)) ∘ (λs:set (α×α), comp_rel s (comp_rel s s))) : lift'_mono' $ assume s hs ⟨a, b⟩ ⟨c, ⟨⟨a₁, a₂⟩, ha, a_eq⟩, ⟨⟨b₁, b₂⟩, hb, b_eq⟩⟩, begin simp at a_eq, simp at b_eq, have h : ⟦a₂⟧ = ⟦b₁⟧, { rw [a_eq.right, b_eq.left] }, have h : (a₂, b₁) ∈ separation_rel α := quotient.exact h, simp [function.comp, set.image, comp_rel], exact ⟨a₁, a_eq.left, b₂, b_eq.right, a₂, ha, b₁, h s hs, hb⟩ end ... = map (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)) (uniformity.lift' (λs:set (α×α), comp_rel s (comp_rel s s))) : by rw [map_lift'_eq]; exact monotone_comp_rel monotone_id (monotone_comp_rel monotone_id monotone_id) ... ≤ map (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)) uniformity : map_mono comp_le_uniformity3, is_open_uniformity := assume s, have ∀a, ⟦a⟧ ∈ s → ({p:α×α | p.1 = a → ⟦p.2⟧ ∈ s} ∈ (@uniformity α _).sets ↔ {p:α×α | ⟦p.1⟧ = ⟦a⟧ → ⟦p.2⟧ ∈ s} ∈ (@uniformity α _).sets), from assume a ha, ⟨assume h, let ⟨t, ht, hts⟩ := comp_mem_uniformity_sets h in have hts : ∀{a₁ a₂}, (a, a₁) ∈ t → (a₁, a₂) ∈ t → ⟦a₂⟧ ∈ s, from assume a₁ a₂ ha₁ ha₂, @hts (a, a₂) ⟨a₁, ha₁, ha₂⟩ rfl, have ht' : ∀{a₁ a₂}, ⟦a₁⟧ = ⟦a₂⟧ → (a₁, a₂) ∈ t, from assume a₁ a₂ h, sInter_subset_of_mem ht (quotient.exact h), uniformity.upwards_sets ht $ assume ⟨a₁, a₂⟩ h₁ h₂, hts (ht' h₂.symm) h₁, assume h, uniformity.upwards_sets h $ by simp {contextual := tt}⟩, begin simp [topological_space.coinduced, u.is_open_uniformity, uniformity, forall_quotient_iff], exact ⟨λh a ha, (this a ha).mp $ h a ha, λh a ha, (this a ha).mpr $ h a ha⟩ end } lemma uniform_continuous_quotient_mk : uniform_continuous (quotient.mk : α → quotient (separation_setoid α)) := le_refl _ lemma vmap_quotient_le_uniformity : vmap (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧)) uniformity ≤ uniformity := assume t' ht', let ⟨t, ht, tt_t'⟩ := comp_mem_uniformity_sets ht' in let ⟨s, hs, ss_t⟩ := comp_mem_uniformity_sets ht in ⟨(λp:α×α, (⟦p.1⟧, ⟦p.2⟧)) '' s, (@uniformity α _).upwards_sets hs $ assume x hx, ⟨x, hx, rfl⟩, assume ⟨a₁, a₂⟩ ⟨⟨b₁, b₂⟩, hb, ab_eq⟩, have ⟦b₁⟧ = ⟦a₁⟧ ∧ ⟦b₂⟧ = ⟦a₂⟧, from prod.mk.inj ab_eq, have b₁ ≈ a₁ ∧ b₂ ≈ a₂, from and.imp quotient.exact quotient.exact this, have ab₁ : (a₁, b₁) ∈ t, from (setoid.symm this.left) t ht, have ba₂ : (b₂, a₂) ∈ s, from this.right s hs, tt_t' ⟨b₁, show ((a₁, a₂).1, b₁) ∈ t, from ab₁, ss_t ⟨b₂, show ((b₁, a₂).1, b₂) ∈ s, from hb, ba₂⟩⟩⟩ lemma vmap_quotient_eq_uniformity : vmap (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧)) uniformity = uniformity := le_antisymm vmap_quotient_le_uniformity (assume s ⟨t, ht, hs⟩, uniformity.upwards_sets ht hs) lemma complete_space_separation [h : complete_space α] : complete_space (quotient (separation_setoid α)) := ⟨assume f, assume hf : cauchy f, have cauchy (vmap (λx, ⟦x⟧) f), from cauchy_vmap vmap_quotient_le_uniformity hf $ vmap_neq_bot_of_surj hf.left $ assume b, quotient.exists_rep _, let ⟨x, (hx : vmap (λx, ⟦x⟧) f ≤ nhds x)⟩ := complete_space.complete this in ⟨⟦x⟧, calc f ≤ map (λx, ⟦x⟧) (vmap (λx, ⟦x⟧) f) : le_map_vmap $ assume b, quotient.exists_rep _ ... ≤ map (λx, ⟦x⟧) (nhds x) : map_mono hx ... ≤ _ : continuous_iff_tendsto.mp (continuous_of_uniform uniform_continuous_quotient_mk) _⟩⟩ lemma separated_separation [h : complete_space α] : separated (quotient (separation_setoid α)) := set.ext $ assume ⟨a, b⟩, quotient.induction_on₂ a b $ assume a b, ⟨assume h, have a ≈ b, from assume s hs, have s ∈ (vmap (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)) uniformity).sets, from vmap_quotient_le_uniformity hs, let ⟨t, ht, hts⟩ := this in hts begin dsimp, exact h t ht end, show ⟦a⟧ = ⟦b⟧, from quotient.sound this, assume heq : ⟦a⟧ = ⟦b⟧, assume h hs, heq ▸ refl_mem_uniformity hs⟩ end separation_space section uniform_extension variables [uniform_space β] [uniform_space γ] {e : β → α} (h_e : uniform_embedding e) (h_dense : ∀x, x ∈ closure (e '' univ)) {f : β → γ} (h_f : uniform_continuous f) [inhabited γ] local notation `ψ` := (dense_embedding_of_uniform_embedding h_e h_dense).ext f lemma uniformly_extend_of_emb [cγ : complete_space γ] [sγ : separated γ] {b : β} : ψ (e b) = f b := dense_embedding.ext_e_eq _ $ continuous_iff_tendsto.mp (continuous_of_uniform h_f) b lemma uniformly_extend_exists [complete_space γ] [sγ : separated γ] {a : α} : ∃c, tendsto f (vmap e (nhds a)) (nhds c) := let de := (dense_embedding_of_uniform_embedding h_e h_dense) in have cauchy (nhds a), from cauchy_nhds, have cauchy (vmap e (nhds a)), from cauchy_vmap (le_of_eq h_e.right) this de.vmap_nhds_neq_bot, have cauchy (map f (vmap e (nhds a))), from cauchy_map h_f this, complete_space.complete this lemma uniformly_extend_spec [complete_space γ] [sγ : separated γ] {a : α} : tendsto f (vmap e (nhds a)) (nhds (ψ a)) := lim_spec $ uniformly_extend_exists h_e h_dense h_f lemma uniform_continuous_uniformly_extend [cγ : complete_space γ] [sγ : separated γ] : uniform_continuous ψ := assume d hd, let ⟨s, hs, hs_comp⟩ := (mem_lift'_iff $ monotone_comp_rel monotone_id $ monotone_comp_rel monotone_id monotone_id).mp (comp_le_uniformity3 hd) in have h_pnt : ∀{a m}, m ∈ (nhds a).sets → ∃c, c ∈ f '' preimage e m ∧ (c, ψ a) ∈ s ∧ (ψ a, c) ∈ s, from assume a m hm, have nb : map f (vmap e (nhds a)) ≠ ⊥, from map_ne_bot (dense_embedding_of_uniform_embedding h_e h_dense).vmap_nhds_neq_bot, have (f '' preimage e m) ∩ ({c | (c, ψ a) ∈ s } ∩ {c | (ψ a, c) ∈ s }) ∈ (map f (vmap e (nhds a))).sets, from inter_mem_sets (image_mem_map $ preimage_mem_vmap $ hm) (uniformly_extend_spec h_e h_dense h_f $ inter_mem_sets (mem_nhds_right hs) (mem_nhds_left hs)), inhabited_of_mem_sets nb this, have preimage (λp:β×β, (f p.1, f p.2)) s ∈ (@uniformity β _).sets, from h_f hs, have preimage (λp:β×β, (f p.1, f p.2)) s ∈ (vmap (λx:β×β, (e x.1, e x.2)) uniformity).sets, by rwa [h_e.right.symm] at this, let ⟨t, ht, ts⟩ := this in show preimage (λp:(α×α), (ψ p.1, ψ p.2)) d ∈ uniformity.sets, from (@uniformity α _).upwards_sets (interior_mem_uniformity ht) $ assume ⟨x₁, x₂⟩ hx_t, have nhds (x₁, x₂) ≤ principal (interior t), from is_open_iff_nhds.mp is_open_interior (x₁, x₂) hx_t, have interior t ∈ (filter.prod (nhds x₁) (nhds x₂)).sets, by rwa [nhds_prod_eq, le_principal_iff] at this, let ⟨m₁, hm₁, m₂, hm₂, (hm : set.prod m₁ m₂ ⊆ interior t)⟩ := mem_prod_iff.mp this in let ⟨a, ha₁, _, ha₂⟩ := h_pnt hm₁ in let ⟨b, hb₁, hb₂, _⟩ := h_pnt hm₂ in have set.prod (preimage e m₁) (preimage e m₂) ⊆ preimage (λp:(β×β), (f p.1, f p.2)) s, from calc _ ⊆ preimage (λp:(β×β), (e p.1, e p.2)) (interior t) : preimage_mono hm ... ⊆ preimage (λp:(β×β), (e p.1, e p.2)) t : preimage_mono interior_subset ... ⊆ preimage (λp:(β×β), (f p.1, f p.2)) s : ts, have set.prod (f '' preimage e m₁) (f '' preimage e m₂) ⊆ s, from calc set.prod (f '' preimage e m₁) (f '' preimage e m₂) = (λp:(β×β), (f p.1, f p.2)) '' (set.prod (preimage e m₁) (preimage e m₂)) : prod_image_image_eq ... ⊆ (λp:(β×β), (f p.1, f p.2)) '' preimage (λp:(β×β), (f p.1, f p.2)) s : mono_image this ... ⊆ s : image_subset_iff.mpr $ subset.refl _, have (a, b) ∈ s, from @this (a, b) ⟨ha₁, hb₁⟩, hs_comp $ show (ψ x₁, ψ x₂) ∈ comp_rel s (comp_rel s s), from ⟨a, ha₂, ⟨b, this, hb₂⟩⟩ end uniform_extension end uniform_space end /-- Space of Cauchy filters This is essentially the completion of a uniform space. The embeddings are the neighbourhood filters. This space is not minimal, the separated uniform space (i.e. quotiented on the intersection of all entourages) is necessary for this. -/ def Cauchy (α : Type u) [uniform_space α] : Type u := { f : filter α // cauchy f } namespace Cauchy section parameters {α : Type u} [uniform_space α] def gen (s : set (α × α)) : set (Cauchy α × Cauchy α) := {p | s ∈ (filter.prod (p.1.val) (p.2.val)).sets } lemma monotone_gen : monotone gen := monotone_set_of $ assume p, @monotone_mem_sets (α×α) (filter.prod (p.1.val) (p.2.val)) private lemma symm_gen : map prod.swap (uniformity.lift' gen) ≤ uniformity.lift' gen := calc map prod.swap (uniformity.lift' gen) = uniformity.lift' (λs:set (α×α), {p | s ∈ (filter.prod (p.2.val) (p.1.val)).sets }) : begin delta gen, simp [map_lift'_eq, monotone_set_of, monotone_mem_sets, function.comp, image_swap_eq_preimage_swap] end ... ≤ uniformity.lift' gen : uniformity_lift_le_swap (monotone_comp (monotone_set_of $ assume p, @monotone_mem_sets (α×α) ((filter.prod ((p.2).val) ((p.1).val)))) monotone_principal) begin have h := λ(p:Cauchy α×Cauchy α), @filter.prod_comm _ _ (p.2.val) (p.1.val), simp [function.comp, h], exact le_refl _ end private lemma comp_rel_gen_gen_subset_gen_comp_rel {s t : set (α×α)} : comp_rel (gen s) (gen t) ⊆ (gen (comp_rel s t) : set (Cauchy α × Cauchy α)) := assume ⟨f, g⟩ ⟨h, h₁, h₂⟩, let ⟨t₁, (ht₁ : t₁ ∈ f.val.sets), t₂, (ht₂ : t₂ ∈ h.val.sets), (h₁ : set.prod t₁ t₂ ⊆ s)⟩ := mem_prod_iff.mp h₁ in let ⟨t₃, (ht₃ : t₃ ∈ h.val.sets), t₄, (ht₄ : t₄ ∈ g.val.sets), (h₂ : set.prod t₃ t₄ ⊆ t)⟩ := mem_prod_iff.mp h₂ in have t₂ ∩ t₃ ∈ h.val.sets, from inter_mem_sets ht₂ ht₃, let ⟨x, xt₂, xt₃⟩ := inhabited_of_mem_sets (h.property.left) this in (filter.prod f.val g.val).upwards_sets (prod_mem_prod ht₁ ht₄) (assume ⟨a, b⟩ ⟨(ha : a ∈ t₁), (hb : b ∈ t₄)⟩, ⟨x, h₁ (show (a, x) ∈ set.prod t₁ t₂, from ⟨ha, xt₂⟩), h₂ (show (x, b) ∈ set.prod t₃ t₄, from ⟨xt₃, hb⟩)⟩) private lemma comp_gen : (uniformity.lift' gen).lift' (λs, comp_rel s s) ≤ uniformity.lift' gen := calc (uniformity.lift' gen).lift' (λs, comp_rel s s) = uniformity.lift' (λs, comp_rel (gen s) (gen s)) : begin rw [lift'_lift'_assoc], exact monotone_gen, exact (monotone_comp_rel monotone_id monotone_id) end ... ≤ uniformity.lift' (λs, gen $ comp_rel s s) : lift'_mono' $ assume s hs, comp_rel_gen_gen_subset_gen_comp_rel ... = (uniformity.lift' $ λs:set(α×α), comp_rel s s).lift' gen : begin rw [lift'_lift'_assoc], exact (monotone_comp_rel monotone_id monotone_id), exact monotone_gen end ... ≤ uniformity.lift' gen : lift'_mono comp_le_uniformity (le_refl _) instance completion_space : uniform_space (Cauchy α) := uniform_space.of_core { uniformity := uniformity.lift' gen, refl := principal_le_lift' $ assume s hs ⟨a, b⟩ (a_eq_b : a = b), a_eq_b ▸ a.property.right hs, symm := symm_gen, comp := comp_gen } def pure_cauchy (a : α) : Cauchy α := ⟨pure a, cauchy_pure⟩ lemma uniform_embedding_pure_cauchy : uniform_embedding (pure_cauchy : α → Cauchy α) := ⟨assume a₁ a₂ h, have (pure_cauchy a₁).val = (pure_cauchy a₂).val, from congr_arg _ h, have {a₁} = ({a₂} : set α), from principal_eq_iff_eq.mp this, by simp at this; assumption, have (preimage (λ (x : α × α), (pure_cauchy (x.fst), pure_cauchy (x.snd))) ∘ gen) = id, from funext $ assume s, set.ext $ assume ⟨a₁, a₂⟩, by simp [preimage, gen, pure_cauchy, prod_principal_principal], calc vmap (λ (x : α × α), (pure_cauchy (x.fst), pure_cauchy (x.snd))) (uniformity.lift' gen) = uniformity.lift' (preimage (λ (x : α × α), (pure_cauchy (x.fst), pure_cauchy (x.snd))) ∘ gen) : vmap_lift'_eq monotone_gen ... = uniformity : by simp [this]⟩ lemma pure_cauchy_dense : ∀x, x ∈ closure (pure_cauchy '' univ) := assume f, have h_ex : ∀s∈(@uniformity (Cauchy α) _).sets, ∃y:α, (f, pure_cauchy y) ∈ s, from assume s hs, let ⟨t'', ht''₁, (ht''₂ : gen t'' ⊆ s)⟩ := (mem_lift'_iff monotone_gen).mp hs in let ⟨t', ht'₁, ht'₂⟩ := comp_mem_uniformity_sets ht''₁ in have t' ∈ (filter.prod (f.val) (f.val)).sets, from f.property.right ht'₁, let ⟨t, ht, (h : set.prod t t ⊆ t')⟩ := mem_prod_same_iff.mp this in let ⟨x, (hx : x ∈ t)⟩ := inhabited_of_mem_sets f.property.left ht in have t'' ∈ (filter.prod f.val (pure x)).sets, from mem_prod_iff.mpr ⟨t, ht, {y:α | (x, y) ∈ t'}, assume y, begin simp, intro h, simp [h], exact refl_mem_uniformity ht'₁ end, assume ⟨a, b⟩ ⟨(h₁ : a ∈ t), (h₂ : (x, b) ∈ t')⟩, ht'₂ $ prod_mk_mem_comp_rel (@h (a, x) ⟨h₁, hx⟩) h₂⟩, ⟨x, ht''₂ $ by dsimp [gen]; exact this⟩, begin simp [closure_eq_nhds, nhds_eq_uniformity, lift'_inf_principal_eq], exact (lift'_neq_bot_iff $ monotone_inter monotone_const monotone_preimage).mpr (assume s hs, let ⟨y, hy⟩ := h_ex s hs in have pure_cauchy y ∈ pure_cauchy '' univ ∩ {y : Cauchy α | (f, y) ∈ s}, from ⟨mem_image_of_mem _ $ mem_univ y, hy⟩, ne_empty_of_mem this) end instance : complete_space (Cauchy α) := complete_space_extension uniform_embedding_pure_cauchy pure_cauchy_dense $ assume f hf, let f' : Cauchy α := ⟨f, hf⟩ in have map pure_cauchy f ≤ uniformity.lift' (preimage (prod.mk f')), from le_lift' $ assume s hs, let ⟨t, ht₁, (ht₂ : gen t ⊆ s)⟩ := (mem_lift'_iff monotone_gen).mp hs in let ⟨t', ht', (h : set.prod t' t' ⊆ t)⟩ := mem_prod_same_iff.mp (hf.right ht₁) in have t' ⊆ { y : α | (f', pure_cauchy y) ∈ gen t }, from assume x hx, (filter.prod f (pure x)).upwards_sets (prod_mem_prod ht' $ mem_pure hx) h, f.upwards_sets ht' $ subset.trans this (preimage_mono ht₂), ⟨f', by simp [nhds_eq_uniformity]; assumption⟩ end end Cauchy instance nonempty_Cauchy {α : Type u} [h : nonempty α] [uniform_space α] : nonempty (Cauchy α) := h.rec_on $ assume a, nonempty.intro $ Cauchy.pure_cauchy a instance inhabited_Cauchy {α : Type u} [inhabited α] [uniform_space α] : inhabited (Cauchy α) := ⟨Cauchy.pure_cauchy $ default α⟩ section constructions variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {ι : Sort*} instance : partial_order (uniform_space α) := { le := λt s, s.uniformity ≤ t.uniformity, le_antisymm := assume t s h₁ h₂, uniform_space_eq $ le_antisymm h₂ h₁, le_refl := assume t, le_refl _, le_trans := assume a b c h₁ h₂, @le_trans _ _ c.uniformity b.uniformity a.uniformity h₂ h₁ } instance : has_Sup (uniform_space α) := ⟨assume s, uniform_space.of_core { uniform_space.core . uniformity := (⨅u∈s, @uniformity α u), refl := le_infi $ assume u, le_infi $ assume hu, u.refl, symm := le_infi $ assume u, le_infi $ assume hu, le_trans (map_mono $ infi_le_of_le _ $ infi_le _ hu) u.symm, comp := le_infi $ assume u, le_infi $ assume hu, le_trans (lift'_mono (infi_le_of_le _ $ infi_le _ hu) $ le_refl _) u.comp }⟩ private lemma le_Sup {tt : set (uniform_space α)} {t : uniform_space α} (h : t ∈ tt) : t ≤ Sup tt := show (⨅u∈tt, @uniformity α u) ≤ t.uniformity, from infi_le_of_le t $ infi_le _ h private lemma Sup_le {tt : set (uniform_space α)} {t : uniform_space α} (h : ∀t'∈tt, t' ≤ t) : Sup tt ≤ t := show t.uniformity ≤ (⨅u∈tt, @uniformity α u), from le_infi $ assume t', le_infi $ assume ht', h t' ht' instance : has_bot (uniform_space α) := ⟨uniform_space.of_core { uniformity := ⊤, refl := le_top, symm := le_top, comp := le_top }⟩ instance : has_top (uniform_space α) := ⟨{ to_topological_space := ⊤, uniformity := principal id_rel, refl := le_refl _, symm := by simp [tendsto]; apply subset.refl, comp := begin rw [lift'_principal], { simp, apply subset.refl }, exact monotone_comp_rel monotone_id monotone_id end, is_open_uniformity := by rw [topological_space.lattice.has_top]; simp [subset_def, id_rel] {contextual := tt } }⟩ instance : complete_lattice (uniform_space α) := { uniform_space.partial_order with 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 h₁ h₂, Sup_le $ assume t', begin simp, intro h, cases h with h h, repeat { subst h; assumption } end, inf := λa b, Sup {x | x ≤ a ∧ x ≤ b}, le_inf := assume a b c h₁ h₂, le_Sup ⟨h₁, h₂⟩, inf_le_left := assume a b, Sup_le $ assume x ⟨ha, hb⟩, ha, inf_le_right := assume a b, Sup_le $ assume x ⟨ha, hb⟩, hb, top := ⊤, le_top := assume u, u.refl, bot := ⊥, bot_le := assume a, show a.uniformity ≤ ⊤, from le_top, Sup := Sup, le_Sup := assume s u, le_Sup, Sup_le := assume s u, Sup_le, Inf := λtt, Sup {t | ∀t'∈tt, t ≤ t'}, le_Inf := assume s a hs, le_Sup hs, Inf_le := assume s a ha, Sup_le $ assume u hs, hs _ ha } lemma supr_uniformity {ι : Sort*} {u : ι → uniform_space α} : (supr u).uniformity = (⨅i, (u i).uniformity) := show (⨅a (h : ∃i:ι, a = u i), a.uniformity) = _, from le_antisymm (le_infi $ assume i, infi_le_of_le (u i) $ infi_le _ ⟨i, rfl⟩) (le_infi $ assume a, le_infi $ assume ⟨i, (ha : a = u i)⟩, ha.symm ▸ infi_le _ _) lemma sup_uniformity {u v : uniform_space α} : (u ⊔ v).uniformity = u.uniformity ⊓ v.uniformity := have (u ⊔ v) = (⨆i (h : i = u ∨ i = v), i), by simp [supr_or, supr_sup_eq], calc (u ⊔ v).uniformity = ((⨆i (h : i = u ∨ i = v), i) : uniform_space α).uniformity : by rw [this] ... = _ : by simp [supr_uniformity, infi_or, infi_inf_eq] instance inhabited_uniform_space : inhabited (uniform_space α) := ⟨⊤⟩ def uniform_space.vmap (f : α → β) (u : uniform_space β) : uniform_space α := { uniformity := u.uniformity.vmap (λp:α×α, (f p.1, f p.2)), to_topological_space := u.to_topological_space.induced f, refl := le_trans (by simp; exact assume ⟨a, b⟩ (h : a = b), h ▸ rfl) (vmap_mono u.refl), symm := tendsto_vmap' $ by simp [prod.swap, (∘)]; exact tendsto_compose tendsto_vmap tendsto_swap_uniformity, comp := le_trans begin rw [vmap_lift'_eq, vmap_lift'_eq2], exact (lift'_mono' $ assume s hs ⟨a₁, a₂⟩ ⟨x, h₁, h₂⟩, ⟨f x, h₁, h₂⟩), repeat { exact monotone_comp_rel monotone_id monotone_id } end (vmap_mono u.comp), is_open_uniformity := begin intro s, change (@is_open α (u.to_topological_space.induced f) s ↔ _), simp [is_open_iff_nhds, nhds_induced_eq_vmap, mem_nhds_uniformity_iff, filter.vmap], exact (ball_congr $ assume x hx, ⟨assume ⟨t, hts, ht⟩, ⟨_, ht, assume ⟨x₁, x₂⟩, by simp [*, subset_def] at * {contextual := tt} ⟩, assume ⟨t, ht, hts⟩, ⟨{y:β | (f x, y) ∈ t}, assume y (hy : (f x, f y) ∈ t), @hts (x, y) hy rfl, mem_nhds_uniformity_iff.mp $ mem_nhds_left ht⟩⟩) end } lemma uniform_continuous_vmap {f : α → β} [u : uniform_space β] : @uniform_continuous α β (uniform_space.vmap f u) u f := tendsto_vmap theorem to_topological_space_vmap {f : α → β} {u : uniform_space β} : @uniform_space.to_topological_space _ (uniform_space.vmap f u) = topological_space.induced f (@uniform_space.to_topological_space β u) := eq_of_nhds_eq_nhds $ assume a, begin simp [nhds_induced_eq_vmap, nhds_eq_uniformity, nhds_eq_uniformity], change vmap f (uniformity.lift' (preimage (λb, (f a, b)))) = (u.uniformity.vmap (λp:α×α, (f p.1, f p.2))).lift' (preimage (λa', (a, a'))), rw [vmap_lift'_eq monotone_preimage, vmap_lift'_eq2 monotone_preimage], exact rfl end lemma uniform_continuous_vmap' {f : γ → β} {g : α → γ} [v : uniform_space β] [u : uniform_space α] (h : uniform_continuous (f ∘ g)) : @uniform_continuous α γ u (uniform_space.vmap f v) g := tendsto_vmap' h lemma to_topological_space_mono {u₁ u₂ : uniform_space α} (h : u₁ ≤ u₂) : @uniform_space.to_topological_space _ u₁ ≤ @uniform_space.to_topological_space _ u₂ := le_of_nhds_le_nhds $ assume a, by rw [@nhds_eq_uniformity α u₁ a, @nhds_eq_uniformity α u₂ a]; exact (lift'_mono h $ le_refl _) lemma to_topological_space_top : @uniform_space.to_topological_space α ⊤ = ⊤ := rfl lemma to_topological_space_bot : @uniform_space.to_topological_space α ⊥ = ⊥ := bot_unique $ assume s hs, classical.by_cases (assume : s = ∅, this.symm ▸ @is_open_empty _ ⊥) (assume : s ≠ ∅, let ⟨x, hx⟩ := exists_mem_of_ne_empty this in have univ ⊆ _, from hs x hx, have s = univ, from top_unique $ assume y hy, @this (x, y) ⟨⟩ rfl, this.symm ▸ @is_open_univ _ ⊥) lemma to_topological_space_supr {ι : Sort*} {u : ι → uniform_space α} : @uniform_space.to_topological_space α (supr u) = (⨆i, @uniform_space.to_topological_space α (u i)) := classical.by_cases (assume h : nonempty ι, eq_of_nhds_eq_nhds $ assume a, begin rw [nhds_supr, nhds_eq_uniformity], change _ = (supr u).uniformity.lift' (preimage $ prod.mk a), begin rw [supr_uniformity, lift'_infi], exact (congr_arg _ $ funext $ assume i, @nhds_eq_uniformity α (u i) a), exact h, exact assume a b, rfl end end) (assume : ¬ nonempty ι, le_antisymm (have supr u = ⊥, from bot_unique $ supr_le $ assume i, (this ⟨i⟩).elim, have @uniform_space.to_topological_space _ (supr u) = ⊥, from this.symm ▸ to_topological_space_bot, this.symm ▸ bot_le) (supr_le $ assume i, to_topological_space_mono $ le_supr _ _)) lemma to_topological_space_Sup {s : set (uniform_space α)} : @uniform_space.to_topological_space α (Sup s) = (⨆i∈s, @uniform_space.to_topological_space α i) := begin rw [Sup_eq_supr, to_topological_space_supr], apply congr rfl, apply funext, intro x, exact to_topological_space_supr end lemma to_topological_space_sup {u v : uniform_space α} : @uniform_space.to_topological_space α (u ⊔ v) = @uniform_space.to_topological_space α u ⊔ @uniform_space.to_topological_space α v := ord_continuous_sup $ assume s, to_topological_space_Sup instance : uniform_space empty := ⊤ instance : uniform_space unit := ⊤ instance : uniform_space bool := ⊤ instance : uniform_space ℕ := ⊤ instance : uniform_space ℤ := ⊤ instance {p : α → Prop} [t : uniform_space α] : uniform_space (subtype p) := uniform_space.vmap subtype.val t lemma uniformity_subtype {p : α → Prop} [t : uniform_space α] : (@uniformity (subtype p) _) = vmap (λq:subtype p × subtype p, (q.1.1, q.2.1)) uniformity := rfl lemma uniform_continuous_subtype_val {p : α → Prop} [uniform_space α] : uniform_continuous (subtype.val : {a : α // p a} → α) := uniform_continuous_vmap lemma uniform_continuous_subtype_mk {p : α → Prop} [uniform_space α] [uniform_space β] {f : β → α} (hf : uniform_continuous f) (h : ∀x, p (f x)) : uniform_continuous (λx, ⟨f x, h x⟩ : β → subtype p) := uniform_continuous_vmap' hf instance [u₁ : uniform_space α] [u₂ : uniform_space β] : uniform_space (α × β) := uniform_space.of_core_eq (u₁.vmap prod.fst ⊔ u₂.vmap prod.snd).to_core prod.topological_space (calc prod.topological_space = (u₁.vmap prod.fst ⊔ u₂.vmap prod.snd).to_topological_space : by rw [to_topological_space_sup, to_topological_space_vmap, to_topological_space_vmap]; refl ... = _ : by rw [uniform_space.to_core_to_topological_space]) lemma uniform_embedding_subtype_emb {α : Type*} {β : Type*} [uniform_space α] [uniform_space β] (p : α → Prop) {e : α → β} (ue : uniform_embedding e) (de : dense_embedding e) : uniform_embedding (de.subtype_emb p) := ⟨(de.subtype p).inj, by simp [vmap_vmap_comp, (∘), dense_embedding.subtype_emb, uniformity_subtype, ue.right.symm]⟩ lemma uniform_extend_subtype {α : Type*} {β : Type*} {γ : Type*} [uniform_space α] [uniform_space β] [uniform_space γ] [complete_space γ] [inhabited γ] [separated γ] {p : α → Prop} {e : α → β} {f : α → γ} {b : β} {s : set α} (hf : uniform_continuous (λx:subtype p, f x.val)) (he : uniform_embedding e) (hd : ∀x:β, x ∈ closure (e '' univ)) (hb : closure (e '' s) ∈ (nhds b).sets) (hs : is_closed s) (hp : ∀x∈s, p x) : ∃c, tendsto f (vmap e (nhds b)) (nhds c) := have de : dense_embedding e, from dense_embedding_of_uniform_embedding he hd, have de' : dense_embedding (de.subtype_emb p), by exact de.subtype p, have ue' : uniform_embedding (de.subtype_emb p), from uniform_embedding_subtype_emb _ he de, have b ∈ closure (e '' {x | p x}), from (closure_mono $ mono_image $ hp) (mem_of_nhds hb), let ⟨c, (hc : tendsto (f ∘ subtype.val) (vmap (de.subtype_emb p) (nhds ⟨b, this⟩)) (nhds c))⟩ := uniformly_extend_exists ue' de'.dense hf in begin rw [nhds_subtype_eq_vmap] at hc, simp [vmap_vmap_comp] at hc, change (tendsto (f ∘ @subtype.val α p) (vmap (e ∘ @subtype.val α p) (nhds b)) (nhds c)) at hc, rw [←vmap_vmap_comp] at hc, existsi c, apply tendsto_vmap'' s _ _ hc, exact ⟨_, hb, assume x, begin change e x ∈ (closure (e '' s)) → x ∈ s, rw [←closure_induced, closure_eq_nhds], dsimp, rw [nhds_induced_eq_vmap, de.induced], change x ∈ {x | nhds x ⊓ principal s ≠ ⊥} → x ∈ s, rw [←closure_eq_nhds, closure_eq_of_is_closed hs], exact id, exact de.inj end⟩, exact (assume x hx, ⟨⟨x, hp x hx⟩, rfl⟩) end /- a similar product space is possible on the function space (uniformity of pointwise convergence), but we want to have the uniformity of uniform convergence on function spaces -/ lemma uniformity_prod [uniform_space α] [uniform_space β] : @uniformity (α×β) _ = vmap (λp:(α×β)×(α×β), (p.1.1, p.2.1)) uniformity ⊓ vmap (λp:(α×β)×(α×β), (p.1.2, p.2.2)) uniformity := by rw [prod.uniform_space, uniform_space.of_core_eq_to_core, uniformity, sup_uniformity]; refl lemma uniformity_prod_eq_prod [uniform_space α] [uniform_space β] : @uniformity (α×β) _ = map (λp:(α×α)×(β×β), ((p.1.1, p.2.1), (p.1.2, p.2.2))) (filter.prod uniformity uniformity) := have map (λp:(α×α)×(β×β), ((p.1.1, p.2.1), (p.1.2, p.2.2))) = vmap (λp:(α×β)×(α×β), ((p.1.1, p.2.1), (p.1.2, p.2.2))), from funext $ assume f, map_eq_vmap_of_inverse (funext $ assume ⟨⟨_, _⟩, ⟨_, _⟩⟩, rfl) (funext $ assume ⟨⟨_, _⟩, ⟨_, _⟩⟩, rfl), by rw [this, uniformity_prod, prod_def, vmap_inf, vmap_vmap_comp, vmap_vmap_comp] lemma mem_uniform_prod [t₁ : uniform_space α] [t₂ : uniform_space β] {a : set (α × α)} {b : set (β × β)} (ha : a ∈ (@uniformity α _).sets) (hb : b ∈ (@uniformity β _).sets) : {p:(α×β)×(α×β) | (p.1.1, p.2.1) ∈ a ∧ (p.1.2, p.2.2) ∈ b } ∈ (@uniformity (α × β) _).sets := by rw [uniformity_prod]; exact inter_mem_inf_sets (preimage_mem_vmap ha) (preimage_mem_vmap hb) lemma tendsto_prod_uniformity_fst [uniform_space α] [uniform_space β] : tendsto (λp:(α×β)×(α×β), (p.1.1, p.2.1)) uniformity uniformity := le_trans (map_mono (@le_sup_left (uniform_space (α×β)) _ _ _)) map_vmap_le lemma tendsto_prod_uniformity_snd [uniform_space α] [uniform_space β] : tendsto (λp:(α×β)×(α×β), (p.1.2, p.2.2)) uniformity uniformity := le_trans (map_mono (@le_sup_right (uniform_space (α×β)) _ _ _)) map_vmap_le lemma uniform_continuous_fst [uniform_space α] [uniform_space β] : uniform_continuous (λp:α×β, p.1) := tendsto_prod_uniformity_fst lemma uniform_continuous_snd [uniform_space α] [uniform_space β] : uniform_continuous (λp:α×β, p.2) := tendsto_prod_uniformity_snd lemma uniform_continuous_prod_mk [uniform_space α] [uniform_space β] [uniform_space γ] {f₁ : α → β} {f₂ : α → γ} (h₁ : uniform_continuous f₁) (h₂ : uniform_continuous f₂) : uniform_continuous (λa, (f₁ a, f₂ a)) := by rw [uniform_continuous, uniformity_prod]; exact tendsto_inf (tendsto_vmap' h₁) (tendsto_vmap' h₂) lemma uniform_embedding_prod {α' : Type*} {β' : Type*} [uniform_space α] [uniform_space β] [uniform_space α'] [uniform_space β'] {e₁ : α → α'} {e₂ : β → β'} (h₁ : uniform_embedding e₁) (h₂ : uniform_embedding e₂) : uniform_embedding (λp:α×β, (e₁ p.1, e₂ p.2)) := ⟨assume ⟨a₁, b₁⟩ ⟨a₂, b₂⟩, by simp [prod.mk.inj_iff]; exact assume eq₁ eq₂, ⟨h₁.left _ _ eq₁, h₂.left _ _ eq₂⟩, by simp [(∘), uniformity_prod, h₁.right.symm, h₂.right.symm, vmap_inf, vmap_vmap_comp]⟩ lemma to_topological_space_prod [u : uniform_space α] [v : uniform_space β] : @uniform_space.to_topological_space (α × β) prod.uniform_space = @prod.topological_space α β u.to_topological_space v.to_topological_space := rfl lemma to_topological_space_subtype [u : uniform_space α] {p : α → Prop} : @uniform_space.to_topological_space (subtype p) subtype.uniform_space = @subtype.topological_space α p u.to_topological_space := rfl end constructions
b956bb1271516e1143e2cfffabd0dbe823e36fed
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/1343.lean
ba16866aafaa45941da87d446dcbaefb55c4d992
[ "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
290
lean
universe variable u namespace ex1 inductive foo (α : Type (u+1)) : Type (u+1) | mk : α → foo inductive bug | leaf : bug | mk : foo bug → bug end ex1 namespace ex2 inductive foo (α : Type u) : Type u | mk : α → foo inductive bug | leaf : bug | mk : foo bug → bug end ex2
4091760f41e8e98ad6e248b44a17599b9a550f41
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/order/filter/filter_product.lean
2c8fc47977b60862e15b7c7caf62bd2784deced1
[ "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
16,808
lean
/- Copyright (c) 2019 Abhimanyu Pallavi Sudhir. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Abhimanyu Pallavi Sudhir "Filterproducts" (ultraproducts on general filters), ultraproducts. -/ import order.filter.basic universes u v variables {α : Type u} (β : Type v) (φ : filter α) local attribute [instance] classical.prop_decidable namespace filter /-- Two sequences are bigly equal iff the kernel of their difference is in φ -/ def bigly_equal : setoid (α → β) := ⟨ λ a b, {n | a n = b n} ∈ φ, λ a, by simp only [eq_self_iff_true, (set.univ_def).symm, univ_sets], λ a b ab, by simpa only [eq_comm], λ a b c ab bc, sets_of_superset φ (inter_sets φ ab bc) (λ n r, eq.trans r.1 r.2)⟩ /-- Ultraproduct, but on a general filter -/ def filterprod := quotient (bigly_equal β φ) local notation `β*` := filterprod β φ namespace filter_product variables {α β φ} include φ def of_seq : (α → β) → β* := @quotient.mk' (α → β) (bigly_equal β φ) /-- Equivalence class containing the constant sequence of a term in β -/ def of (b : β): β* := of_seq (function.const α b) /-- Lift function to filter product -/ def lift (f : β → β) : β* → β* := λ x, quotient.lift_on' x (λ a, (of_seq $ λ n, f (a n) : β*)) $ λ a b h, quotient.sound' $ show _ ∈ _, by filter_upwards [h] λ i hi, congr_arg _ hi /-- Lift binary operation to filter product -/ def lift₂ (f : β → β → β) : β* → β* → β* := λ x y, quotient.lift_on₂' x y (λ a b, (of_seq $ λ n, f (a n) (b n) : β*)) $ λ a₁ a₂ b₁ b₂ h1 h2, quotient.sound' $ show _ ∈ _, by filter_upwards [h1, h2] λ i hi1 hi2, congr (congr_arg _ hi1) hi2 /-- Lift properties to filter product -/ def lift_rel (R : β → Prop) : β* → Prop := λ x, quotient.lift_on' x (λ a, {i : α | R (a i)} ∈ φ) $ λ a b h, propext ⟨ λ ha, by filter_upwards [h, ha] λ i hi hia, by simpa [hi.symm], λ hb, by filter_upwards [h, hb] λ i hi hib, by simpa [hi.symm.symm] ⟩ /-- Lift binary relations to filter product -/ def lift_rel₂ (R : β → β → Prop) : β* → β* → Prop := λ x y, quotient.lift_on₂' x y (λ a b, {i : α | R (a i) (b i)} ∈ φ) $ λ a₁ a₂ b₁ b₂ h₁ h₂, propext ⟨ λ ha, by filter_upwards [h₁, h₂, ha] λ i hi1 hi2 hia, by simpa [hi1.symm, hi2.symm], λ hb, by filter_upwards [h₁, h₂, hb] λ i hi1 hi2 hib, by simpa [hi1.symm.symm, hi2.symm.symm] ⟩ instance coe_filterprod : has_coe β β* := ⟨ of ⟩ instance [has_add β] : has_add β* := { add := lift₂ has_add.add } instance [has_zero β] : has_zero β* := { zero := of 0 } instance [has_neg β] : has_neg β* := { neg := lift has_neg.neg } instance [add_semigroup β] : add_semigroup β* := { add_assoc := λ x y z, quotient.induction_on₃' x y z $ λ a b c, quotient.sound' $ show {n | _ + _ + _ = _ + (_ + _)} ∈ _, by simp only [add_assoc, eq_self_iff_true]; exact φ.univ_sets, ..filter_product.has_add } instance [add_monoid β] : add_monoid β* := { zero_add := λ x, quotient.induction_on' x (λ a, quotient.sound'(by simp only [zero_add]; apply (setoid.iseqv _).1)), add_zero := λ x, quotient.induction_on' x (λ a, quotient.sound'(by simp only [add_zero]; apply (setoid.iseqv _).1)), ..filter_product.add_semigroup, ..filter_product.has_zero } instance [add_comm_semigroup β] : add_comm_semigroup β* := { add_comm := λ x y, quotient.induction_on₂' x y (λ a b, quotient.sound' (by simp only [add_comm]; apply (setoid.iseqv _).1)), ..filter_product.add_semigroup } instance [add_comm_monoid β] : add_comm_monoid β* := { ..filter_product.add_comm_semigroup, ..filter_product.add_monoid } instance [add_group β] : add_group β* := { add_left_neg := λ x, quotient.induction_on' x (λ a, quotient.sound' (by simp only [add_left_neg]; apply (setoid.iseqv _).1)), ..filter_product.add_monoid, ..filter_product.has_neg } instance [add_comm_group β] : add_comm_group β* := { ..filter_product.add_comm_monoid, ..filter_product.add_group } instance [has_mul β] : has_mul β* := { mul := lift₂ has_mul.mul } instance [has_one β] : has_one β* := { one := of 1 } instance [has_inv β] : has_inv β* := { inv := lift has_inv.inv } instance [semigroup β] : semigroup β* := { mul_assoc := λ x y z, quotient.induction_on₃' x y z $ λ a b c, quotient.sound' $ show {n | _ * _ * _ = _ * (_ * _)} ∈ _, by simp only [mul_assoc, eq_self_iff_true]; exact φ.2, ..filter_product.has_mul } instance [monoid β] : monoid β* := { one_mul := λ x, quotient.induction_on' x (λ a, quotient.sound' (by simp only [one_mul]; apply (setoid.iseqv _).1)), mul_one := λ x, quotient.induction_on' x (λ a, quotient.sound' (by simp only [mul_one]; apply (setoid.iseqv _).1)), ..filter_product.semigroup, ..filter_product.has_one } instance [comm_semigroup β] : comm_semigroup β* := { mul_comm := λ x y, quotient.induction_on₂' x y (λ a b, quotient.sound' (by simp only [mul_comm]; apply (setoid.iseqv _).1)), ..filter_product.semigroup } instance [comm_monoid β] : comm_monoid β* := { ..filter_product.comm_semigroup, ..filter_product.monoid } instance [group β] : group β* := { mul_left_inv := λ x, quotient.induction_on' x (λ a, quotient.sound' (by simp only [mul_left_inv]; apply (setoid.iseqv _).1)), ..filter_product.monoid, ..filter_product.has_inv } instance [comm_group β] : comm_group β* := { ..filter_product.comm_monoid, ..filter_product.group } instance [distrib β] : distrib β* := { left_distrib := λ x y z, quotient.induction_on₃' x y z (λ x y z, quotient.sound' (by simp only [left_distrib]; apply (setoid.iseqv _).1)), right_distrib := λ x y z, quotient.induction_on₃' x y z (λ x y z, quotient.sound' (by simp only [right_distrib]; apply (setoid.iseqv _).1)), ..filter_product.has_add, ..filter_product.has_mul } instance [mul_zero_class β] : mul_zero_class β* := { zero_mul := λ x, quotient.induction_on' x (λ a, quotient.sound' (by simp only [zero_mul]; apply (setoid.iseqv _).1)), mul_zero := λ x, quotient.induction_on' x (λ a, quotient.sound' (by simp only [mul_zero]; apply (setoid.iseqv _).1)), ..filter_product.has_mul, ..filter_product.has_zero } instance [semiring β] : semiring β* := { ..filter_product.add_comm_monoid, ..filter_product.monoid, ..filter_product.distrib, ..filter_product.mul_zero_class } instance [ring β] : ring β* := { ..filter_product.add_comm_group, ..filter_product.monoid, ..filter_product.distrib } instance [comm_semiring β] : comm_semiring β* := { ..filter_product.semiring, ..filter_product.comm_monoid } instance [comm_ring β] : comm_ring β* := { ..filter_product.ring, ..filter_product.comm_semigroup } instance [zero_ne_one_class β] (NT : φ ≠ ⊥) : zero_ne_one_class β* := { zero_ne_one := λ c, have c' : _ := quotient.exact' c, by { change _ ∈ _ at c', simp only [set.set_of_false, zero_ne_one, empty_in_sets_eq_bot] at c', exact NT c' }, ..filter_product.has_zero, ..filter_product.has_one } instance [division_ring β] (U : is_ultrafilter φ) : division_ring β* := { mul_inv_cancel := λ x, quotient.induction_on' x $ λ a hx, quotient.sound' $ have hx1 : _ := (not_imp_not.mpr quotient.eq'.mpr) hx, have hx2 : _ := (ultrafilter_iff_compl_mem_iff_not_mem.mp U _).mpr hx1, have h : {n : α | ¬a n = 0} ⊆ {n : α | a n * (a n)⁻¹ = 1} := by rw [set.set_of_subset_set_of]; exact λ n, division_ring.mul_inv_cancel, mem_sets_of_superset hx2 h, inv_mul_cancel := λ x, quotient.induction_on' x $ λ a hx, quotient.sound' $ have hx1 : _ := (not_imp_not.mpr quotient.eq'.mpr) hx, have hx2 : _ := (ultrafilter_iff_compl_mem_iff_not_mem.mp U _).mpr hx1, have h : {n : α | ¬a n = 0} ⊆ {n : α | (a n)⁻¹ * a n = 1} := by rw [set.set_of_subset_set_of]; exact λ n, division_ring.inv_mul_cancel, mem_sets_of_superset hx2 h, ..filter_product.ring, ..filter_product.has_inv, ..filter_product.zero_ne_one_class U.1 } instance [field β] (U : is_ultrafilter φ) : field β* := { ..filter_product.comm_ring, ..filter_product.division_ring U } noncomputable instance [discrete_field β] (U : is_ultrafilter φ) : discrete_field β* := { inv_zero := quotient.sound' $ by show _ ∈ _; simp only [inv_zero, eq_self_iff_true, (set.univ_def).symm, univ_sets], has_decidable_eq := by apply_instance, ..filter_product.field U } instance [has_le β] : has_le β* := { le := lift_rel₂ has_le.le } instance [preorder β] : preorder β* := { le_refl := λ x, quotient.induction_on' x $ λ a, show _ ∈ _, by simp only [le_refl, (set.univ_def).symm, univ_sets], le_trans := λ x y z, quotient.induction_on₃' x y z $ λ a b c hab hbc, by filter_upwards [hab, hbc] λ i hiab hibc, le_trans hiab hibc, ..filter_product.has_le } instance [partial_order β] : partial_order β* := { le_antisymm := λ x y, quotient.induction_on₂' x y $ λ a b hab hba, quotient.sound' $ have hI : {n | a n = b n} = _ ∩ _ := set.ext (λ n, le_antisymm_iff), show _ ∈ _, by rw hI; exact inter_sets _ hab hba ..filter_product.preorder } instance [linear_order β] (U : is_ultrafilter φ) : linear_order β* := { le_total := λ x y, quotient.induction_on₂' x y $ λ a b, have hS : _ ⊆ {i | b i ≤ a i} := λ i, le_of_not_le, or.cases_on (mem_or_compl_mem_of_ultrafilter U {i | a i ≤ b i}) (λ h, or.inl h) (λ h, or.inr (sets_of_superset _ h hS)) ..filter_product.partial_order } theorem of_inj (NT : φ ≠ ⊥): function.injective (@of _ β φ) := begin intros r s rs, by_contra N, rw [of, of, of_seq, quotient.eq', bigly_equal] at rs, simp only [N, set.set_of_false, empty_in_sets_eq_bot] at rs, exact NT rs end theorem of_seq_fun (f g : α → β) (h : β → β) (H : {n : α | f n = h (g n) } ∈ φ) : of_seq f = (lift h) (@of_seq _ _ φ g) := quotient.sound' H theorem of_seq_fun₂ (f g₁ g₂ : α → β) (h : β → β → β) (H : {n : α | f n = h (g₁ n) (g₂ n) } ∈ φ) : of_seq f = (lift₂ h) (@of_seq _ _ φ g₁) (@of_seq _ _ φ g₂) := quotient.sound' H @[simp] lemma of_seq_zero [has_zero β] (f : α → β) : of_seq 0 = (0 : β*) := rfl @[simp] lemma of_seq_add [has_add β] (f g : α → β) : of_seq (f + g) = of_seq f + (of_seq g : β*) := rfl @[simp] lemma of_seq_neg [has_neg β] (f : α → β) : of_seq (-f) = - (of_seq f : β*) := rfl @[simp] lemma of_seq_one [has_one β] (f : α → β) : of_seq 1 = (1 : β*) := rfl @[simp] lemma of_seq_mul [has_mul β] (f g : α → β) : of_seq (f * g) = of_seq f * (of_seq g : β*) := rfl @[simp] lemma of_seq_inv [has_inv β] (f : α → β) : of_seq (f⁻¹) = (of_seq f : β*)⁻¹ := rfl lemma of_eq_coe (x : β) : of x = (↑x : β*) := rfl @[simp] lemma of_id (x : β) : of x = (x : β*) := rfl lemma of_eq (x y : β) (NT : φ ≠ ⊥) : x = y ↔ of x = (of y : β*) := ⟨λ h, by rw h, by apply of_inj NT⟩ lemma of_ne (x y : β) (NT : φ ≠ ⊥) : x ≠ y ↔ of x ≠ (of y : β*) := by show ¬ x = y ↔ of x ≠ of y; rwa [of_eq] lemma of_eq_zero [has_zero β] (NT : φ ≠ ⊥) (x : β) : x = 0 ↔ of x = (0 : β*) := of_eq _ _ NT lemma of_ne_zero [has_zero β] (NT : φ ≠ ⊥) (x : β) : x ≠ 0 ↔ of x ≠ (0 : β*) := of_ne _ _ NT @[simp] lemma of_zero [has_zero β] : of 0 = (0 : β*) := rfl @[simp] lemma of_add [has_add β] (x y : β) : of (x + y) = of x + (of y : β*) := rfl @[simp] lemma of_neg [has_neg β] (x : β) : of (- x) = - (of x : β*) := rfl @[simp] lemma of_one [has_one β] : of 1 = (1 : β*) := rfl @[simp] lemma of_mul [has_mul β] (x y : β) : of (x * y) = of x * (of y : β*) := rfl @[simp] lemma of_inv [has_inv β] (x : β) : of (x⁻¹) = (of x : β*)⁻¹ := rfl lemma of_rel_of_rel (R : β → Prop) (x : β) : R x → (lift_rel R) (of x : β*) := λ hx, by show {i | R x} ∈ _; simp only [hx]; exact univ_mem_sets lemma of_rel (R : β → Prop) (x : β) (NT: φ ≠ ⊥) : R x ↔ (lift_rel R) (of x : β*) := ⟨ of_rel_of_rel _ _, λ hxy, by change {i | R x} ∈ _ at hxy; by_contra h; simp only [h, set.set_of_false, empty_in_sets_eq_bot] at hxy; exact NT hxy ⟩ lemma of_rel_of_rel₂ (R : β → β → Prop) (x y : β) : R x y → (lift_rel₂ R) (of x) (of y : β*) := λ hxy, by show {i | R x y} ∈ _; simp only [hxy]; exact univ_mem_sets lemma of_rel₂ (R : β → β → Prop) (x y : β) (NT: φ ≠ ⊥) : R x y ↔ (lift_rel₂ R) (of x) (of y : β*) := ⟨ of_rel_of_rel₂ _ _ _, λ hxy, by change {i | R x y} ∈ _ at hxy; by_contra h; simp only [h, set.set_of_false, empty_in_sets_eq_bot] at hxy; exact NT hxy ⟩ lemma of_le_of_le [has_le β] (x y : β) : x ≤ y → of x ≤ (of y : β*) := of_rel_of_rel₂ _ _ _ lemma of_le [has_le β] (x y : β) (NT: φ ≠ ⊥) : x ≤ y ↔ of x ≤ (of y : β*) := of_rel₂ _ _ _ NT lemma lt_def [K : preorder β] (U : is_ultrafilter φ) (x y : β*) : (x < y) ↔ @lift_rel₂ _ _ φ K.lt x y := ⟨ quotient.induction_on₂' x y $ λ a b ⟨hxy, hyx⟩, have hyx' : _ := (ultrafilter_iff_compl_mem_iff_not_mem.mp U _).mpr hyx, by filter_upwards [hxy, hyx'] λ i hi1 hi2, lt_iff_le_not_le.mpr ⟨hi1, hi2⟩, quotient.induction_on₂' x y $ λ a b hab, ⟨ by filter_upwards [hab] λ i, le_of_lt, λ hba, have hc : ∀ i : α, a i < b i ∧ b i ≤ a i → false := λ i ⟨h1, h2⟩, not_lt_of_le h2 h1, have h0 : ∅ = {i : α | a i < b i} ∩ {i : α | b i ≤ a i} := by simp only [set.inter_def, hc, set.set_of_false, eq_self_iff_true, set.mem_set_of_eq], U.1 $ empty_in_sets_eq_bot.mp $ by rw [h0]; exact inter_sets _ hab hba ⟩ ⟩ lemma lt_def' [K : preorder β] (U : is_ultrafilter φ) : filter_product.preorder.lt = @lift_rel₂ _ _ φ K.lt := by ext x y; exact lt_def U x y lemma of_lt_of_lt [preorder β] (U : is_ultrafilter φ) (x y : β) : x < y → of x < (of y : β*) := by rw lt_def U; apply of_rel_of_rel₂ lemma of_lt [preorder β] (x y : β) (U : is_ultrafilter φ) : x < y ↔ of x < (of y : β*) := by rw lt_def U; exact of_rel₂ _ _ _ U.1 instance [ordered_comm_group β] (U : is_ultrafilter φ) : ordered_comm_group β* := { add_le_add_left := λ x y hxy z, by revert hxy; exact quotient.induction_on₃' x y z (λ a b c hab, by filter_upwards [hab] λ i hi, by simpa), add_lt_add_left := λ x y hxy z, by revert hxy; exact quotient.induction_on₃' x y z (λ a b c hab, by rw lt_def U at hab ⊢; filter_upwards [hab] λ i hi, add_lt_add_left hi (c i)), ..filter_product.partial_order, ..filter_product.add_comm_group } instance [ordered_ring β] (U : is_ultrafilter φ) : ordered_ring β* := { mul_nonneg := λ x y, quotient.induction_on₂' x y $ λ a b ha hb, by filter_upwards [ha, hb] λ i, by simp only [set.mem_set_of_eq]; exact mul_nonneg, mul_pos := λ x y, quotient.induction_on₂' x y $ λ a b ha hb, by rw lt_def U at ha hb ⊢; filter_upwards [ha, hb] λ i, mul_pos, ..filter_product.ring, ..filter_product.ordered_comm_group U, ..filter_product.zero_ne_one_class U.1 } instance [linear_ordered_ring β] (U : is_ultrafilter φ) : linear_ordered_ring β* := { zero_lt_one := by rw lt_def U; show {i | (0 : β) < 1} ∈ _; simp only [zero_lt_one, (set.univ_def).symm, univ_sets], ..filter_product.ordered_ring U, ..filter_product.linear_order U } instance [linear_ordered_field β] (U : is_ultrafilter φ) : linear_ordered_field β* := { ..filter_product.linear_ordered_ring U, ..filter_product.field U } instance [linear_ordered_comm_ring β] (U : is_ultrafilter φ) : linear_ordered_comm_ring β* := { ..filter_product.linear_ordered_ring U, ..filter_product.comm_monoid } noncomputable instance [decidable_linear_order β] (U : is_ultrafilter φ) : decidable_linear_order β* := { decidable_le := by apply_instance, ..filter_product.linear_order U } noncomputable instance [decidable_linear_ordered_comm_group β] (U : is_ultrafilter φ) : decidable_linear_ordered_comm_group β* := { ..filter_product.ordered_comm_group U, ..filter_product.decidable_linear_order U } noncomputable instance [decidable_linear_ordered_comm_ring β] (U : is_ultrafilter φ) : decidable_linear_ordered_comm_ring β* := { ..filter_product.linear_ordered_comm_ring U, ..filter_product.decidable_linear_ordered_comm_group U } noncomputable instance [discrete_linear_ordered_field β] (U : is_ultrafilter φ) : discrete_linear_ordered_field β* := { ..filter_product.linear_ordered_field U, ..filter_product.decidable_linear_ordered_comm_ring U, ..filter_product.discrete_field U } end filter_product end filter
0f9c4643a2e45769342fa6295bff3388f4561b05
54ce0561cebde424526f41d45f490ed56be2bd0c
/src/game/ch4_Integers_and_Rationals/2_The_Rationals.lean
078e07ca72858d6b925a283b6ac85862274fee03
[]
no_license
melembroucarlitos/Tao_Analysis-LEAN
cf7b3298d317891a09e4bf21cfe7c7ffcb57b9a9
3f4fc7e090d96b6cef64896492fba4bef124794b
refs/heads/master
1,692,952,385,694
1,636,287,522,000
1,636,287,522,000
400,630,166
3
0
null
1,635,910,807,000
1,630,096,823,000
Lean
UTF-8
Lean
false
false
170
lean
-- Level name : The Rational Numbers /- # Hey yall ## This is just to a placeholder to make sure all is working these are some words and these are some other words -/
f853121e4399b3745397e8a8834c9ae0e4323c0d
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/data/polynomial/identities.lean
7149747917e0c8747e74eca6afb3b1bfa3ac97d8
[ "Apache-2.0" ]
permissive
dupuisf/mathlib
62de4ec6544bf3b79086afd27b6529acfaf2c1bb
8582b06b0a5d06c33ee07d0bdf7c646cae22cf36
refs/heads/master
1,669,494,854,016
1,595,692,409,000
1,595,692,409,000
272,046,630
0
0
Apache-2.0
1,592,066,143,000
1,592,066,142,000
null
UTF-8
Lean
false
false
3,489
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Jens Wagemaker -/ import data.polynomial.derivative /-! # Theory of univariate polynomials The main def is `binom_expansion`. -/ noncomputable theory namespace polynomial universes u v w x y z variables {R : Type u} {S : Type v} {T : Type w} {ι : Type x} {k : Type y} {A : Type z} {a b : R} {m n : ℕ} section identities /- @TODO: pow_add_expansion and pow_sub_pow_factor are not specific to polynomials. These belong somewhere else. But not in group_power because they depend on tactic.ring_exp Maybe use data.nat.choose to prove it. -/ def pow_add_expansion {R : Type*} [comm_semiring R] (x y : R) : ∀ (n : ℕ), {k // (x + y)^n = x^n + n*x^(n-1)*y + k * y^2} | 0 := ⟨0, by simp⟩ | 1 := ⟨0, by simp⟩ | (n+2) := begin cases pow_add_expansion (n+1) with z hz, existsi x*z + (n+1)*x^n+z*y, calc (x + y) ^ (n + 2) = (x + y) * (x + y) ^ (n + 1) : by ring_exp ... = (x + y) * (x ^ (n + 1) + ↑(n + 1) * x ^ (n + 1 - 1) * y + z * y ^ 2) : by rw hz ... = x ^ (n + 2) + ↑(n + 2) * x ^ (n + 1) * y + (x*z + (n+1)*x^n+z*y) * y ^ 2 : by { push_cast, ring_exp! } end variables [comm_ring R] private def poly_binom_aux1 (x y : R) (e : ℕ) (a : R) : {k : R // a * (x + y)^e = a * (x^e + e*x^(e-1)*y + k*y^2)} := begin existsi (pow_add_expansion x y e).val, congr, apply (pow_add_expansion _ _ _).property end private lemma poly_binom_aux2 (f : polynomial R) (x y : R) : f.eval (x + y) = f.sum (λ e a, a * (x^e + e*x^(e-1)*y + (poly_binom_aux1 x y e a).val*y^2)) := begin unfold eval eval₂, congr, ext, apply (poly_binom_aux1 x y _ _).property end private lemma poly_binom_aux3 (f : polynomial R) (x y : R) : f.eval (x + y) = f.sum (λ e a, a * x^e) + f.sum (λ e a, (a * e * x^(e-1)) * y) + f.sum (λ e a, (a *(poly_binom_aux1 x y e a).val)*y^2) := by rw poly_binom_aux2; simp [left_distrib, finsupp.sum_add, mul_assoc] lemma derivative_eval (p : polynomial R) (x : R) : p.derivative.eval x = p.sum (λ n a, (a * n)*x^(n-1)) := by simp only [derivative, eval_sum, eval_pow, eval_C, eval_X, eval_nat_cast, eval_mul] def binom_expansion (f : polynomial R) (x y : R) : {k : R // f.eval (x + y) = f.eval x + (f.derivative.eval x) * y + k * y^2} := begin existsi f.sum (λ e a, a *((poly_binom_aux1 x y e a).val)), rw poly_binom_aux3, congr, { rw derivative_eval, symmetry, apply finsupp.sum_mul }, { symmetry, apply finsupp.sum_mul } end def pow_sub_pow_factor (x y : R) : Π (i : ℕ), {z : R // x^i - y^i = z * (x - y)} | 0 := ⟨0, by simp⟩ | 1 := ⟨1, by simp⟩ | (k+2) := begin cases @pow_sub_pow_factor (k+1) with z hz, existsi z*x + y^(k+1), calc x ^ (k + 2) - y ^ (k + 2) = x * (x ^ (k + 1) - y ^ (k + 1)) + (x * y ^ (k + 1) - y ^ (k + 2)) : by ring_exp ... = x * (z * (x - y)) + (x * y ^ (k + 1) - y ^ (k + 2)) : by rw hz ... = (z * x + y ^ (k + 1)) * (x - y) : by ring_exp end def eval_sub_factor (f : polynomial R) (x y : R) : {z : R // f.eval x - f.eval y = z * (x - y)} := begin refine ⟨f.sum (λ i r, r * (pow_sub_pow_factor x y i).val), _⟩, delta eval eval₂, rw ← finsupp.sum_sub, rw finsupp.sum_mul, delta finsupp.sum, congr, ext i r, dsimp, rw [mul_assoc, ←(pow_sub_pow_factor x y _).prop, mul_sub], end end identities end polynomial
d549c61b1b29ea3cc4b18deb6ab7c32befba7819
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebraic_geometry/elliptic_curve/point.lean
f8e6785033fa00d460b9741677d0cb216232568d
[ "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
39,400
lean
/- Copyright (c) 2022 David Kurniadi Angdinata. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: David Kurniadi Angdinata -/ import algebraic_geometry.elliptic_curve.weierstrass import linear_algebra.free_module.norm import ring_theory.class_group /-! # Nonsingular rational points on Weierstrass curves > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines the type of nonsingular rational points on a Weierstrass curve over a field and proves that it forms an abelian group under a geometric secant-and-tangent process. ## Mathematical background Let `W` be a Weierstrass curve over a field `F`. A rational point on `W` is simply a point $[X:Y:Z]$ defined over `F` in the projective plane satisfying the homogeneous cubic equation $Y^2Z + a_1XYZ + a_3YZ^2 = X^3 + a_2X^2Z + a_4XZ^2 + a_6Z^3$. Any such point either lies in the affine chart $Z \ne 0$ and satisfies the Weierstrass equation obtained by replacing $X/Z$ with $X$ and $Y/Z$ with $Y$, or is the unique point at infinity $0 := [0:1:0]$ when $Z = 0$. With this new description, a nonsingular rational point on `W` is either $0$ or an affine point $(x, y)$ where the partial derivatives $W_X(X, Y)$ and $W_Y(X, Y)$ do not vanish simultaneously. For a field extension `K` of `F`, a `K`-rational point is simply a rational point on `W` base changed to `K`. The set of nonsingular rational points forms an abelian group under a secant-and-tangent process. * The identity rational point is `0`. * Given a nonsingular rational point `P`, its negation `-P` is defined to be the unique third point of intersection between `W` and the line through `0` and `P`. Explicitly, if `P` is $(x, y)$, then `-P` is $(x, -y - a_1x - a_3)$. * Given two points `P` and `Q`, their addition `P + Q` is defined to be the negation of the unique third point of intersection between `W` and the line `L` through `P` and `Q`. Explicitly, let `P` be $(x_1, y_1)$ and let `Q` be $(x_2, y_2)$. * If $x_1 = x_2$ and $y_1 = -y_2 - a_1x_2 - a_3$, then `L` is vertical and `P + Q` is `0`. * If $x_1 = x_2$ and $y_1 \ne -y_2 - a_1x_2 - a_3$, then `L` is the tangent of `W` at `P = Q`, and has slope $\ell := (3x_1^2 + 2a_2x_1 + a_4 - a_1y_1) / (2y_1 + a_1x_1 + a_3)$. * Otherwise $x_1 \ne x_2$, then `L` is the secant of `W` through `P` and `Q`, and has slope $\ell := (y_1 - y_2) / (x_1 - x_2)$. In the latter two cases, the $X$-coordinate of `P + Q` is then the unique third solution of the equation obtained by substituting the line $Y = \ell(X - x_1) + y_1$ into the Weierstrass equation, and can be written down explicitly as $x := \ell^2 + a_1\ell - a_2 - x_1 - x_2$ by inspecting the $X^2$ terms. The $Y$-coordinate of `P + Q`, after applying the final negation that maps $Y$ to $-Y - a_1X - a_3$, is precisely $y := -(\ell(x - x_1) + y_1) - a_1x - a_3$. The group law on this set is then uniquely determined by these constructions. ## Main definitions * `weierstrass_curve.point`: the type of nonsingular rational points on a Weierstrass curve `W`. * `weierstrass_curve.point.add`: the addition of two nonsingular rational points on `W`. ## Main statements * `weierstrass_curve.point.add_comm_group`: the type of nonsingular rational points on `W` forms an abelian group under addition. ## Notations * `W⟮K⟯`: the group of nonsingular rational points on `W` base changed to `K`. ## References [J Silverman, *The Arithmetic of Elliptic Curves*][silverman2009] ## Tags elliptic curve, rational point, group law -/ private meta def map_simp : tactic unit := `[simp only [map_one, map_bit0, map_bit1, map_neg, map_add, map_sub, _root_.map_mul, map_pow, map_div₀]] private meta def eval_simp : tactic unit := `[simp only [eval_C, eval_X, eval_neg, eval_add, eval_sub, eval_mul, eval_pow]] private meta def C_simp : tactic unit := `[simp only [C_1, C_bit0, C_bit1, C_neg, C_add, C_sub, C_mul, C_pow]] private meta def derivative_simp : tactic unit := `[simp only [derivative_C, derivative_X, derivative_X_pow, derivative_neg, derivative_add, derivative_sub, derivative_mul, derivative_sq]] universes u v w namespace weierstrass_curve open coordinate_ring ideal polynomial open_locale non_zero_divisors polynomial polynomial_polynomial section basic /-! ### Polynomials associated to nonsingular rational points on a Weierstrass curve -/ variables {R : Type u} [comm_ring R] (W : weierstrass_curve R) (A : Type v) [comm_ring A] [algebra R A] (B : Type w) [comm_ring B] [algebra R B] [algebra A B] [is_scalar_tower R A B] (x₁ x₂ y₁ y₂ L : R) /-- The polynomial $-Y - a_1X - a_3$ associated to negation. -/ noncomputable def neg_polynomial : R[X][Y] := -Y - C (C W.a₁ * X + C W.a₃) /-- The $Y$-coordinate of the negation of an affine point in `W`. This depends on `W`, and has argument order: $x_1$, $y_1$. -/ @[simp] def neg_Y : R := -y₁ - W.a₁ * x₁ - W.a₃ lemma neg_Y_neg_Y : W.neg_Y x₁ (W.neg_Y x₁ y₁) = y₁ := by { simp only [neg_Y], ring1 } lemma base_change_neg_Y : (W.base_change A).neg_Y (algebra_map R A x₁) (algebra_map R A y₁) = algebra_map R A (W.neg_Y x₁ y₁) := by { simp only [neg_Y], map_simp, refl } lemma base_change_neg_Y_of_base_change (x₁ y₁ : A) : (W.base_change B).neg_Y (algebra_map A B x₁) (algebra_map A B y₁) = algebra_map A B ((W.base_change A).neg_Y x₁ y₁) := by rw [← base_change_neg_Y, base_change_base_change] @[simp] lemma eval_neg_polynomial : (W.neg_polynomial.eval $ C y₁).eval x₁ = W.neg_Y x₁ y₁ := by { rw [neg_Y, sub_sub, neg_polynomial], eval_simp } /-- The polynomial $L(X - x_1) + y_1$ associated to the line $Y = L(X - x_1) + y_1$, with a slope of $L$ that passes through an affine point $(x_1, y_1)$. This does not depend on `W`, and has argument order: $x_1$, $y_1$, $L$. -/ noncomputable def line_polynomial : R[X] := C L * (X - C x₁) + C y₁ lemma XY_ideal_eq₁ : XY_ideal W x₁ (C y₁) = XY_ideal W x₁ (line_polynomial x₁ y₁ L) := begin simp only [XY_ideal, X_class, Y_class, line_polynomial], rw [← span_pair_add_mul_right $ adjoin_root.mk _ $ C $ C $ -L, ← _root_.map_mul, ← map_add], apply congr_arg (_ ∘ _ ∘ _ ∘ _), C_simp, ring1 end /-- The polynomial obtained by substituting the line $Y = L*(X - x_1) + y_1$, with a slope of $L$ that passes through an affine point $(x_1, y_1)$, into the polynomial $W(X, Y)$ associated to `W`. If such a line intersects `W` at another point $(x_2, y_2)$, then the roots of this polynomial are precisely $x_1$, $x_2$, and the $X$-coordinate of the addition of $(x_1, y_1)$ and $(x_2, y_2)$. This depends on `W`, and has argument order: $x_1$, $y_1$, $L$. -/ noncomputable def add_polynomial : R[X] := W.polynomial.eval $ line_polynomial x₁ y₁ L lemma C_add_polynomial : C (W.add_polynomial x₁ y₁ L) = (Y - C (line_polynomial x₁ y₁ L)) * (W.neg_polynomial - C (line_polynomial x₁ y₁ L)) + W.polynomial := by { rw [add_polynomial, line_polynomial, weierstrass_curve.polynomial, neg_polynomial], eval_simp, C_simp, ring1 } lemma coordinate_ring.C_add_polynomial : adjoin_root.mk W.polynomial (C (W.add_polynomial x₁ y₁ L)) = adjoin_root.mk W.polynomial ((Y - C (line_polynomial x₁ y₁ L)) * (W.neg_polynomial - C (line_polynomial x₁ y₁ L))) := adjoin_root.mk_eq_mk.mpr ⟨1, by rw [C_add_polynomial, add_sub_cancel', mul_one]⟩ lemma add_polynomial_eq : W.add_polynomial x₁ y₁ L = -cubic.to_poly ⟨1, -L ^ 2 - W.a₁ * L + W.a₂, 2 * x₁ * L ^ 2 + (W.a₁ * x₁ - 2 * y₁ - W.a₃) * L + (-W.a₁ * y₁ + W.a₄), -x₁ ^ 2 * L ^ 2 + (2 * x₁ * y₁ + W.a₃ * x₁) * L - (y₁ ^ 2 + W.a₃ * y₁ - W.a₆)⟩ := by { rw [add_polynomial, line_polynomial, weierstrass_curve.polynomial, cubic.to_poly], eval_simp, C_simp, ring1 } /-- The $X$-coordinate of the addition of two affine points $(x_1, y_1)$ and $(x_2, y_2)$ in `W`, where the line through them is not vertical and has a slope of $L$. This depends on `W`, and has argument order: $x_1$, $x_2$, $L$. -/ @[simp] def add_X : R := L ^ 2 + W.a₁ * L - W.a₂ - x₁ - x₂ lemma base_change_add_X : (W.base_change A).add_X (algebra_map R A x₁) (algebra_map R A x₂) (algebra_map R A L) = algebra_map R A (W.add_X x₁ x₂ L) := by { simp only [add_X], map_simp, refl } lemma base_change_add_X_of_base_change (x₁ x₂ L : A) : (W.base_change B).add_X (algebra_map A B x₁) (algebra_map A B x₂) (algebra_map A B L) = algebra_map A B ((W.base_change A).add_X x₁ x₂ L) := by rw [← base_change_add_X, base_change_base_change] /-- The $Y$-coordinate, before applying the final negation, of the addition of two affine points $(x_1, y_1)$ and $(x_2, y_2)$, where the line through them is not vertical and has a slope of $L$. This depends on `W`, and has argument order: $x_1$, $x_2$, $y_1$, $L$. -/ @[simp] def add_Y' : R := L * (W.add_X x₁ x₂ L - x₁) + y₁ lemma base_change_add_Y' : (W.base_change A).add_Y' (algebra_map R A x₁) (algebra_map R A x₂) (algebra_map R A y₁) (algebra_map R A L) = algebra_map R A (W.add_Y' x₁ x₂ y₁ L) := by { simp only [add_Y', base_change_add_X], map_simp } lemma base_change_add_Y'_of_base_change (x₁ x₂ y₁ L : A) : (W.base_change B).add_Y' (algebra_map A B x₁) (algebra_map A B x₂) (algebra_map A B y₁) (algebra_map A B L) = algebra_map A B ((W.base_change A).add_Y' x₁ x₂ y₁ L) := by rw [← base_change_add_Y', base_change_base_change] /-- The $Y$-coordinate of the addition of two affine points $(x_1, y_1)$ and $(x_2, y_2)$ in `W`, where the line through them is not vertical and has a slope of $L$. This depends on `W`, and has argument order: $x_1$, $x_2$, $y_1$, $L$. -/ @[simp] def add_Y : R := W.neg_Y (W.add_X x₁ x₂ L) (W.add_Y' x₁ x₂ y₁ L) lemma base_change_add_Y : (W.base_change A).add_Y (algebra_map R A x₁) (algebra_map R A x₂) (algebra_map R A y₁) (algebra_map R A L) = algebra_map R A (W.add_Y x₁ x₂ y₁ L) := by simp only [add_Y, base_change_add_Y', base_change_add_X, base_change_neg_Y] lemma base_change_add_Y_of_base_change (x₁ x₂ y₁ L : A) : (W.base_change B).add_Y (algebra_map A B x₁) (algebra_map A B x₂) (algebra_map A B y₁) (algebra_map A B L) = algebra_map A B ((W.base_change A).add_Y x₁ x₂ y₁ L) := by rw [← base_change_add_Y, base_change_base_change] lemma XY_ideal_add_eq : XY_ideal W (W.add_X x₁ x₂ L) (C (W.add_Y x₁ x₂ y₁ L)) = span {adjoin_root.mk W.polynomial $ W.neg_polynomial - C (line_polynomial x₁ y₁ L)} ⊔ X_ideal W (W.add_X x₁ x₂ L) := begin simp only [XY_ideal, X_ideal, X_class, Y_class, add_Y, add_Y', neg_Y, neg_polynomial, line_polynomial], conv_rhs { rw [sub_sub, ← neg_add', map_neg, span_singleton_neg, sup_comm, ← span_insert] }, rw [← span_pair_add_mul_right $ adjoin_root.mk _ $ C $ C $ W.a₁ + L, ← _root_.map_mul, ← map_add], apply congr_arg (_ ∘ _ ∘ _ ∘ _), C_simp, ring1 end lemma equation_add_iff : W.equation (W.add_X x₁ x₂ L) (W.add_Y' x₁ x₂ y₁ L) ↔ (W.add_polynomial x₁ y₁ L).eval (W.add_X x₁ x₂ L) = 0 := by { rw [equation, add_Y', add_polynomial, line_polynomial, weierstrass_curve.polynomial], eval_simp } lemma nonsingular_add_of_eval_derivative_ne_zero (hx' : W.equation (W.add_X x₁ x₂ L) (W.add_Y' x₁ x₂ y₁ L)) (hx : (derivative $ W.add_polynomial x₁ y₁ L).eval (W.add_X x₁ x₂ L) ≠ 0) : W.nonsingular (W.add_X x₁ x₂ L) (W.add_Y' x₁ x₂ y₁ L) := begin rw [nonsingular, and_iff_right hx', add_Y', polynomial_X, polynomial_Y], eval_simp, contrapose! hx, rw [add_polynomial, line_polynomial, weierstrass_curve.polynomial], eval_simp, derivative_simp, simp only [zero_add, add_zero, sub_zero, zero_mul, mul_one], eval_simp, linear_combination hx.left + L * hx.right with { normalization_tactic := `[norm_num1, ring1] } end /-! ### The type of nonsingular rational points on a Weierstrass curve -/ /-- A nonsingular rational point on a Weierstrass curve `W` over `R`. This is either the point at infinity `weierstrass_curve.point.zero` or an affine point `weierstrass_curve.point.some` $(x, y)$ satisfying the equation $y^2 + a_1xy + a_3y = x^3 + a_2x^2 + a_4x + a_6$ of `W`. For an algebraic extension `S` of `R`, the type of nonsingular `S`-rational points on `W` is denoted `W⟮S⟯`. -/ inductive point | zero | some {x y : R} (h : W.nonsingular x y) localized "notation W⟮S⟯ := (W.base_change S).point" in weierstrass_curve namespace point instance : inhabited W.point := ⟨zero⟩ instance : has_zero W.point := ⟨zero⟩ @[simp] lemma zero_def : (zero : W.point) = 0 := rfl end point variables {W x₁ y₁} lemma equation_neg_iff : W.equation x₁ (W.neg_Y x₁ y₁) ↔ W.equation x₁ y₁ := by { rw [equation_iff, equation_iff, neg_Y], congr' 2, ring1 } lemma equation_neg_of (h : W.equation x₁ $ W.neg_Y x₁ y₁) : W.equation x₁ y₁ := equation_neg_iff.mp h /-- The negation of an affine point in `W` lies in `W`. -/ lemma equation_neg (h : W.equation x₁ y₁) : W.equation x₁ $ W.neg_Y x₁ y₁ := equation_neg_iff.mpr h lemma nonsingular_neg_iff : W.nonsingular x₁ (W.neg_Y x₁ y₁) ↔ W.nonsingular x₁ y₁ := begin rw [nonsingular_iff, equation_neg_iff, ← neg_Y, neg_Y_neg_Y, ← @ne_comm _ y₁, nonsingular_iff], exact and_congr_right' ((iff_congr not_and_distrib.symm not_and_distrib.symm).mpr $ not_iff_not_of_iff $ and_congr_left $ λ h, by rw [← h]) end lemma nonsingular_neg_of (h : W.nonsingular x₁ $ W.neg_Y x₁ y₁) : W.nonsingular x₁ y₁ := nonsingular_neg_iff.mp h /-- The negation of a nonsingular affine point in `W` is nonsingular. -/ lemma nonsingular_neg (h : W.nonsingular x₁ y₁) : W.nonsingular x₁ $ W.neg_Y x₁ y₁ := nonsingular_neg_iff.mpr h namespace point /-- The negation of a nonsingular rational point. Given a nonsingular rational point `P`, use `-P` instead of `neg P`. -/ def neg : W.point → W.point | 0 := 0 | (some h) := some $ nonsingular_neg h instance : has_neg W.point := ⟨neg⟩ @[simp] lemma neg_def (P : W.point) : P.neg = -P := rfl @[simp] lemma neg_zero : (-0 : W.point) = 0 := rfl @[simp] lemma neg_some (h : W.nonsingular x₁ y₁) : -some h = some (nonsingular_neg h) := rfl instance : has_involutive_neg W.point := ⟨neg, by { rintro (_ | _), { refl }, { simp, ring1 } }⟩ end point end basic section addition /-! ### Slopes of lines through nonsingular rational points on a Weierstrass curve -/ open_locale classical variables {F : Type u} [field F] (W : weierstrass_curve F) (K : Type v) [field K] [algebra F K] (x₁ x₂ y₁ y₂ : F) /-- The slope of the line through two affine points $(x_1, y_1)$ and $(x_2, y_2)$ in `W`. If $x_1 \ne x_2$, then this line is the secant of `W` through $(x_1, y_1)$ and $(x_2, y_2)$, and has slope $(y_1 - y_2) / (x_1 - x_2)$. Otherwise, if $y_1 \ne -y_1 - a_1x_1 - a_3$, then this line is the tangent of `W` at $(x_1, y_1) = (x_2, y_2)$, and has slope $(3x_1^2 + 2a_2x_1 + a_4 - a_1y_1) / (2y_1 + a_1x_1 + a_3)$. Otherwise, this line is vertical, and has undefined slope, in which case this function returns the value 0. This depends on `W`, and has argument order: $x_1$, $x_2$, $y_1$, $y_2$. -/ noncomputable def slope : F := if hx : x₁ = x₂ then if hy : y₁ = W.neg_Y x₂ y₂ then 0 else (3 * x₁ ^ 2 + 2 * W.a₂ * x₁ + W.a₄ - W.a₁ * y₁) / (y₁ - W.neg_Y x₁ y₁) else (y₁ - y₂) / (x₁ - x₂) variables {W x₁ x₂ y₁ y₂} (h₁ : W.nonsingular x₁ y₁) (h₂ : W.nonsingular x₂ y₂) (h₁' : W.equation x₁ y₁) (h₂' : W.equation x₂ y₂) @[simp] lemma slope_of_Y_eq (hx : x₁ = x₂) (hy : y₁ = W.neg_Y x₂ y₂) : W.slope x₁ x₂ y₁ y₂ = 0 := by rw [slope, dif_pos hx, dif_pos hy] @[simp] lemma slope_of_Y_ne (hx : x₁ = x₂) (hy : y₁ ≠ W.neg_Y x₂ y₂) : W.slope x₁ x₂ y₁ y₂ = (3 * x₁ ^ 2 + 2 * W.a₂ * x₁ + W.a₄ - W.a₁ * y₁) / (y₁ - W.neg_Y x₁ y₁) := by rw [slope, dif_pos hx, dif_neg hy] @[simp] lemma slope_of_X_ne (hx : x₁ ≠ x₂) : W.slope x₁ x₂ y₁ y₂ = (y₁ - y₂) / (x₁ - x₂) := by rw [slope, dif_neg hx] lemma slope_of_Y_ne_eq_eval (hx : x₁ = x₂) (hy : y₁ ≠ W.neg_Y x₂ y₂) : W.slope x₁ x₂ y₁ y₂ = -(W.polynomial_X.eval $ C y₁).eval x₁ / (W.polynomial_Y.eval $ C y₁).eval x₁ := by { rw [slope_of_Y_ne hx hy, eval_polynomial_X, neg_sub], congr' 1, rw [neg_Y, eval_polynomial_Y], ring1 } lemma base_change_slope : (W.base_change K).slope (algebra_map F K x₁) (algebra_map F K x₂) (algebra_map F K y₁) (algebra_map F K y₂) = algebra_map F K (W.slope x₁ x₂ y₁ y₂) := begin by_cases hx : x₁ = x₂, { by_cases hy : y₁ = W.neg_Y x₂ y₂, { rw [slope_of_Y_eq hx hy, slope_of_Y_eq $ congr_arg _ hx, map_zero], { rw [hy, base_change_neg_Y] } }, { rw [slope_of_Y_ne hx hy, slope_of_Y_ne $ congr_arg _ hx], { map_simp, simpa only [base_change_neg_Y] }, { rw [base_change_neg_Y], contrapose! hy, exact no_zero_smul_divisors.algebra_map_injective F K hy } } }, { rw [slope_of_X_ne hx, slope_of_X_ne], { map_simp }, { contrapose! hx, exact no_zero_smul_divisors.algebra_map_injective F K hx } } end lemma base_change_slope_of_base_change {R : Type u} [comm_ring R] (W : weierstrass_curve R) (F : Type v) [field F] [algebra R F] (K : Type w) [field K] [algebra R K] [algebra F K] [is_scalar_tower R F K] (x₁ x₂ y₁ y₂ : F) : (W.base_change K).slope (algebra_map F K x₁) (algebra_map F K x₂) (algebra_map F K y₁) (algebra_map F K y₂) = algebra_map F K ((W.base_change F).slope x₁ x₂ y₁ y₂) := by rw [← base_change_slope, base_change_base_change] include h₁' h₂' lemma Y_eq_of_X_eq (hx : x₁ = x₂) : y₁ = y₂ ∨ y₁ = W.neg_Y x₂ y₂ := begin rw [equation_iff] at h₁' h₂', rw [← sub_eq_zero, ← @sub_eq_zero _ _ y₁, ← mul_eq_zero, neg_Y], linear_combination h₁' - h₂' with { normalization_tactic := `[rw [hx], ring1] } end lemma Y_eq_of_Y_ne (hx : x₁ = x₂) (hy : y₁ ≠ W.neg_Y x₂ y₂) : y₁ = y₂ := or.resolve_right (Y_eq_of_X_eq h₁' h₂' hx) hy lemma XY_ideal_eq₂ (hxy : x₁ = x₂ → y₁ ≠ W.neg_Y x₂ y₂) : XY_ideal W x₂ (C y₂) = XY_ideal W x₂ (line_polynomial x₁ y₁ $ W.slope x₁ x₂ y₁ y₂) := begin have hy₂ : y₂ = (line_polynomial x₁ y₁ $ W.slope x₁ x₂ y₁ y₂).eval x₂ := begin by_cases hx : x₁ = x₂, { rcases ⟨hx, Y_eq_of_Y_ne h₁' h₂' hx $ hxy hx⟩ with ⟨rfl, rfl⟩, field_simp [line_polynomial, sub_ne_zero_of_ne (hxy rfl)] }, { field_simp [line_polynomial, slope_of_X_ne hx, sub_ne_zero_of_ne hx], ring1 } end, nth_rewrite_lhs 0 [hy₂], simp only [XY_ideal, X_class, Y_class, line_polynomial], rw [← span_pair_add_mul_right $ adjoin_root.mk W.polynomial $ C $ C $ -W.slope x₁ x₂ y₁ y₂, ← _root_.map_mul, ← map_add], apply congr_arg (_ ∘ _ ∘ _ ∘ _), eval_simp, C_simp, ring1 end lemma add_polynomial_slope (hxy : x₁ = x₂ → y₁ ≠ W.neg_Y x₂ y₂) : W.add_polynomial x₁ y₁ (W.slope x₁ x₂ y₁ y₂) = -((X - C x₁) * (X - C x₂) * (X - C (W.add_X x₁ x₂ $ W.slope x₁ x₂ y₁ y₂))) := begin rw [add_polynomial_eq, neg_inj, cubic.prod_X_sub_C_eq, cubic.to_poly_injective], by_cases hx : x₁ = x₂, { rcases ⟨hx, Y_eq_of_Y_ne h₁' h₂' hx (hxy hx)⟩ with ⟨rfl, rfl⟩, rw [equation_iff] at h₁' h₂', rw [slope_of_Y_ne rfl $ hxy rfl], rw [neg_Y, ← sub_ne_zero] at hxy, ext, { refl }, { simp only [add_X], ring1 }, { field_simp [hxy rfl], ring1 }, { linear_combination -h₁' with { normalization_tactic := `[field_simp [hxy rfl], ring1] } } }, { rw [equation_iff] at h₁' h₂', rw [slope_of_X_ne hx], rw [← sub_eq_zero] at hx, ext, { refl }, { simp only [add_X], ring1 }, { apply mul_right_injective₀ hx, linear_combination h₂' - h₁' with { normalization_tactic := `[field_simp [hx], ring1] } }, { apply mul_right_injective₀ hx, linear_combination x₂ * h₁' - x₁ * h₂' with { normalization_tactic := `[field_simp [hx], ring1] } } } end lemma coordinate_ring.C_add_polynomial_slope (hxy : x₁ = x₂ → y₁ ≠ W.neg_Y x₂ y₂) : adjoin_root.mk W.polynomial (C $ W.add_polynomial x₁ y₁ $ W.slope x₁ x₂ y₁ y₂) = -(X_class W x₁ * X_class W x₂ * X_class W (W.add_X x₁ x₂ $ W.slope x₁ x₂ y₁ y₂)) := by simpa only [add_polynomial_slope h₁' h₂' hxy, map_neg, neg_inj, _root_.map_mul] lemma derivative_add_polynomial_slope (hxy : x₁ = x₂ → y₁ ≠ W.neg_Y x₂ y₂) : derivative (W.add_polynomial x₁ y₁ $ W.slope x₁ x₂ y₁ y₂) = -((X - C x₁) * (X - C x₂) + (X - C x₁) * (X - C (W.add_X x₁ x₂ $ W.slope x₁ x₂ y₁ y₂)) + (X - C x₂) * (X - C (W.add_X x₁ x₂ $ W.slope x₁ x₂ y₁ y₂))) := by { rw [add_polynomial_slope h₁' h₂' hxy], derivative_simp, ring1 } /-! ### The addition law on nonsingular rational points on a Weierstrass curve -/ /-- The addition of two affine points in `W` on a sloped line, before applying the final negation that maps $Y$ to $-Y - a_1X - a_3$, lies in `W`. -/ lemma equation_add' (hxy : x₁ = x₂ → y₁ ≠ W.neg_Y x₂ y₂) : W.equation (W.add_X x₁ x₂ $ W.slope x₁ x₂ y₁ y₂) (W.add_Y' x₁ x₂ y₁ $ W.slope x₁ x₂ y₁ y₂) := by { rw [equation_add_iff, add_polynomial_slope h₁' h₂' hxy], eval_simp, rw [neg_eq_zero, sub_self, mul_zero] } /-- The addition of two affine points in `W` on a sloped line lies in `W`. -/ lemma equation_add (hxy : x₁ = x₂ → y₁ ≠ W.neg_Y x₂ y₂) : W.equation (W.add_X x₁ x₂ $ W.slope x₁ x₂ y₁ y₂) (W.add_Y x₁ x₂ y₁ $ W.slope x₁ x₂ y₁ y₂) := equation_neg $ equation_add' h₁' h₂' hxy omit h₁' h₂' include h₁ h₂ /-- The addition of two nonsingular affine points in `W` on a sloped line, before applying the final negation that maps $Y$ to $-Y - a_1X - a_3$, is nonsingular. -/ lemma nonsingular_add' (hxy : x₁ = x₂ → y₁ ≠ W.neg_Y x₂ y₂) : W.nonsingular (W.add_X x₁ x₂ $ W.slope x₁ x₂ y₁ y₂) (W.add_Y' x₁ x₂ y₁ $ W.slope x₁ x₂ y₁ y₂) := begin by_cases hx₁ : W.add_X x₁ x₂ (W.slope x₁ x₂ y₁ y₂) = x₁, { rwa [add_Y', hx₁, sub_self, mul_zero, zero_add] }, { by_cases hx₂ : W.add_X x₁ x₂ (W.slope x₁ x₂ y₁ y₂) = x₂, { by_cases hx : x₁ = x₂, { subst hx, contradiction }, { rwa [add_Y', ← neg_sub, mul_neg, hx₂, slope_of_X_ne hx, div_mul_cancel _ $ sub_ne_zero_of_ne hx, neg_sub, sub_add_cancel] } }, { apply W.nonsingular_add_of_eval_derivative_ne_zero _ _ _ _ (equation_add' h₁.1 h₂.1 hxy), rw [derivative_add_polynomial_slope h₁.left h₂.left hxy], eval_simp, simpa only [neg_ne_zero, sub_self, mul_zero, add_zero] using mul_ne_zero (sub_ne_zero_of_ne hx₁) (sub_ne_zero_of_ne hx₂) } } end /-- The addition of two nonsingular affine points in `W` on a sloped line is nonsingular. -/ lemma nonsingular_add (hxy : x₁ = x₂ → y₁ ≠ W.neg_Y x₂ y₂) : W.nonsingular (W.add_X x₁ x₂ $ W.slope x₁ x₂ y₁ y₂) (W.add_Y x₁ x₂ y₁ $ W.slope x₁ x₂ y₁ y₂) := nonsingular_neg $ nonsingular_add' h₁ h₂ hxy omit h₁ h₂ namespace point variables {h₁ h₂} /-- The addition of two nonsingular rational points. Given two nonsingular rational points `P` and `Q`, use `P + Q` instead of `add P Q`. -/ noncomputable def add : W.point → W.point → W.point | 0 P := P | P 0 := P | (@some _ _ _ x₁ y₁ h₁) (@some _ _ _ x₂ y₂ h₂) := if hx : x₁ = x₂ then if hy : y₁ = W.neg_Y x₂ y₂ then 0 else some $ nonsingular_add h₁ h₂ $ λ _, hy else some $ nonsingular_add h₁ h₂ $ λ h, (hx h).elim noncomputable instance : has_add W.point := ⟨add⟩ @[simp] lemma add_def (P Q : W.point) : P.add Q = P + Q := rfl noncomputable instance : add_zero_class W.point := ⟨0, (+), by rintro (_ | _); refl, by rintro (_ | _); refl⟩ @[simp] lemma some_add_some_of_Y_eq (hx : x₁ = x₂) (hy : y₁ = W.neg_Y x₂ y₂) : some h₁ + some h₂ = 0 := by rw [← add_def, add, dif_pos hx, dif_pos hy] @[simp] lemma some_add_self_of_Y_eq (hy : y₁ = W.neg_Y x₁ y₁) : some h₁ + some h₁ = 0 := some_add_some_of_Y_eq rfl hy @[simp] lemma some_add_some_of_Y_ne (hx : x₁ = x₂) (hy : y₁ ≠ W.neg_Y x₂ y₂) : some h₁ + some h₂ = some (nonsingular_add h₁ h₂ $ λ _, hy) := by rw [← add_def, add, dif_pos hx, dif_neg hy] lemma some_add_some_of_Y_ne' (hx : x₁ = x₂) (hy : y₁ ≠ W.neg_Y x₂ y₂) : some h₁ + some h₂ = -some (nonsingular_add' h₁ h₂ $ λ _, hy) := some_add_some_of_Y_ne hx hy @[simp] lemma some_add_self_of_Y_ne (hy : y₁ ≠ W.neg_Y x₁ y₁) : some h₁ + some h₁ = some (nonsingular_add h₁ h₁ $ λ _, hy) := some_add_some_of_Y_ne rfl hy lemma some_add_self_of_Y_ne' (hy : y₁ ≠ W.neg_Y x₁ y₁) : some h₁ + some h₁ = -some (nonsingular_add' h₁ h₁ $ λ _, hy) := some_add_some_of_Y_ne rfl hy @[simp] lemma some_add_some_of_X_ne (hx : x₁ ≠ x₂) : some h₁ + some h₂ = some (nonsingular_add h₁ h₂ $ λ h, (hx h).elim) := by rw [← add_def, add, dif_neg hx] lemma some_add_some_of_X_ne' (hx : x₁ ≠ x₂) : some h₁ + some h₂ = -some (nonsingular_add' h₁ h₂ $ λ h, (hx h).elim) := some_add_some_of_X_ne hx end point end addition section group /-! ### The axioms for nonsingular rational points on a Weierstrass curve -/ variables {F : Type u} [field F] {W : weierstrass_curve F} {x₁ x₂ y₁ y₂ : F} (h₁ : W.nonsingular x₁ y₁) (h₂ : W.nonsingular x₂ y₂) (h₁' : W.equation x₁ y₁) (h₂' : W.equation x₂ y₂) include h₁ lemma XY_ideal_neg_mul : XY_ideal W x₁ (C $ W.neg_Y x₁ y₁) * XY_ideal W x₁ (C y₁) = X_ideal W x₁ := begin have Y_rw : (Y - C (C y₁)) * (Y - C (C (W.neg_Y x₁ y₁))) - C (X - C x₁) * (C (X ^ 2 + C (x₁ + W.a₂) * X + C (x₁ ^ 2 + W.a₂ * x₁ + W.a₄)) - C (C W.a₁) * Y) = W.polynomial * 1 := by linear_combination congr_arg C (congr_arg C ((W.equation_iff _ _).mp h₁.left).symm) with { normalization_tactic := `[rw [neg_Y, weierstrass_curve.polynomial], C_simp, ring1] }, simp_rw [XY_ideal, X_class, Y_class, span_pair_mul_span_pair, mul_comm, ← _root_.map_mul, adjoin_root.mk_eq_mk.mpr ⟨1, Y_rw⟩, _root_.map_mul, span_insert, ← span_singleton_mul_span_singleton, ← mul_sup, ← span_insert], convert mul_top _ using 2, simp_rw [← @set.image_singleton _ _ $ adjoin_root.mk _, ← set.image_insert_eq, ← map_span], convert map_top (adjoin_root.mk W.polynomial) using 1, apply congr_arg, simp_rw [eq_top_iff_one, mem_span_insert', mem_span_singleton'], cases ((W.nonsingular_iff' _ _).mp h₁).right with hx hy, { let W_X := W.a₁ * y₁ - (3 * x₁ ^ 2 + 2 * W.a₂ * x₁ + W.a₄), refine ⟨C (C W_X⁻¹ * -(X + C (2 * x₁ + W.a₂))), C (C $ W_X⁻¹ * W.a₁), 0, C (C $ W_X⁻¹ * -1), _⟩, rw [← mul_right_inj' $ C_ne_zero.mpr $ C_ne_zero.mpr hx], simp only [mul_add, ← mul_assoc, ← C_mul, mul_inv_cancel hx], C_simp, ring1 }, { let W_Y := 2 * y₁ + W.a₁ * x₁ + W.a₃, refine ⟨0, C (C W_Y⁻¹), C (C $ W_Y⁻¹ * -1), 0, _⟩, rw [neg_Y, ← mul_right_inj' $ C_ne_zero.mpr $ C_ne_zero.mpr hy], simp only [mul_add, ← mul_assoc, ← C_mul, mul_inv_cancel hy], C_simp, ring1 } end private lemma XY_ideal'_mul_inv : (XY_ideal W x₁ (C y₁) : fractional_ideal W.coordinate_ring⁰ W.function_field) * (XY_ideal W x₁ (C $ W.neg_Y x₁ y₁) * (X_ideal W x₁)⁻¹) = 1 := by rw [← mul_assoc, ← fractional_ideal.coe_ideal_mul, mul_comm $ XY_ideal W _ _, XY_ideal_neg_mul h₁, X_ideal, fractional_ideal.coe_ideal_span_singleton_mul_inv W.function_field $ X_class_ne_zero W x₁] omit h₁ include h₁' h₂' lemma XY_ideal_mul_XY_ideal (hxy : x₁ = x₂ → y₁ ≠ W.neg_Y x₂ y₂) : X_ideal W (W.add_X x₁ x₂ $ W.slope x₁ x₂ y₁ y₂) * (XY_ideal W x₁ (C y₁) * XY_ideal W x₂ (C y₂)) = Y_ideal W (line_polynomial x₁ y₁ $ W.slope x₁ x₂ y₁ y₂) * XY_ideal W (W.add_X x₁ x₂ $ W.slope x₁ x₂ y₁ y₂) (C $ W.add_Y x₁ x₂ y₁ $ W.slope x₁ x₂ y₁ y₂) := begin have sup_rw : ∀ a b c d : ideal W.coordinate_ring, a ⊔ (b ⊔ (c ⊔ d)) = a ⊔ d ⊔ b ⊔ c := λ _ _ c _, by rw [← sup_assoc, @sup_comm _ _ c, sup_sup_sup_comm, ← sup_assoc], rw [XY_ideal_add_eq, X_ideal, mul_comm, W.XY_ideal_eq₁ x₁ y₁ $ W.slope x₁ x₂ y₁ y₂, XY_ideal, XY_ideal_eq₂ h₁' h₂' hxy, XY_ideal, span_pair_mul_span_pair], simp_rw [span_insert, sup_rw, sup_mul, span_singleton_mul_span_singleton], rw [← neg_eq_iff_eq_neg.mpr $ coordinate_ring.C_add_polynomial_slope h₁' h₂' hxy, span_singleton_neg, coordinate_ring.C_add_polynomial, _root_.map_mul, Y_class], simp_rw [mul_comm $ X_class W x₁, mul_assoc, ← span_singleton_mul_span_singleton, ← mul_sup], rw [span_singleton_mul_span_singleton, ← span_insert, ← span_pair_add_mul_right $ -(X_class W $ W.add_X x₁ x₂ $ W.slope x₁ x₂ y₁ y₂), mul_neg, ← sub_eq_add_neg, ← sub_mul, ← map_sub, sub_sub_sub_cancel_right, span_insert, ← span_singleton_mul_span_singleton, ← sup_rw, ← sup_mul, ← sup_mul], apply congr_arg (_ ∘ _), convert top_mul _, simp_rw [X_class, ← @set.image_singleton _ _ $ adjoin_root.mk _, ← map_span, ← ideal.map_sup, eq_top_iff_one, mem_map_iff_of_surjective _ $ adjoin_root.mk_surjective W.monic_polynomial, ← span_insert, mem_span_insert', mem_span_singleton'], by_cases hx : x₁ = x₂, { rcases ⟨hx, Y_eq_of_Y_ne h₁' h₂' hx (hxy hx)⟩ with ⟨rfl, rfl⟩, let y := (y₁ - W.neg_Y x₁ y₁) ^ 2, replace hxy := pow_ne_zero 2 (sub_ne_zero_of_ne $ hxy rfl), refine ⟨1 + C (C $ y⁻¹ * 4) * W.polynomial, ⟨C $ C y⁻¹ * (C 4 * X ^ 2 + C (4 * x₁ + W.b₂) * X + C (4 * x₁ ^ 2 + W.b₂ * x₁ + 2 * W.b₄)), 0, C (C y⁻¹) * (Y - W.neg_polynomial), _⟩, by rw [map_add, map_one, _root_.map_mul, adjoin_root.mk_self, mul_zero, add_zero]⟩, rw [weierstrass_curve.polynomial, neg_polynomial, ← mul_right_inj' $ C_ne_zero.mpr $ C_ne_zero.mpr hxy], simp only [mul_add, ← mul_assoc, ← C_mul, mul_inv_cancel hxy], linear_combination -4 * congr_arg C (congr_arg C $ (W.equation_iff _ _).mp h₁') with { normalization_tactic := `[rw [b₂, b₄, neg_Y], C_simp, ring1] } }, { replace hx := sub_ne_zero_of_ne hx, refine ⟨_, ⟨⟨C $ C (x₁ - x₂)⁻¹, C $ C $ (x₁ - x₂)⁻¹ * -1, 0, _⟩, map_one _⟩⟩, rw [← mul_right_inj' $ C_ne_zero.mpr $ C_ne_zero.mpr hx], simp only [← mul_assoc, mul_add, ← C_mul, mul_inv_cancel hx], C_simp, ring1 } end omit h₁' h₂' /-- The non-zero fractional ideal $\langle X - x, Y - y \rangle$ of $F(W)$ for some $x, y \in F$. -/ @[simp] noncomputable def XY_ideal' : (fractional_ideal W.coordinate_ring⁰ W.function_field)ˣ := units.mk_of_mul_eq_one _ _ $ XY_ideal'_mul_inv h₁ lemma XY_ideal'_eq : (XY_ideal' h₁ : fractional_ideal W.coordinate_ring⁰ W.function_field) = XY_ideal W x₁ (C y₁) := rfl local attribute [irreducible] coordinate_ring.comm_ring lemma mk_XY_ideal'_mul_mk_XY_ideal'_of_Y_eq : class_group.mk (XY_ideal' $ nonsingular_neg h₁) * class_group.mk (XY_ideal' h₁) = 1 := begin rw [← _root_.map_mul], exact (class_group.mk_eq_one_of_coe_ideal $ by exact (fractional_ideal.coe_ideal_mul _ _).symm.trans (fractional_ideal.coe_ideal_inj.mpr $ XY_ideal_neg_mul h₁)).mpr ⟨_, X_class_ne_zero W _, rfl⟩ end lemma mk_XY_ideal'_mul_mk_XY_ideal' (hxy : x₁ = x₂ → y₁ ≠ W.neg_Y x₂ y₂) : class_group.mk (XY_ideal' h₁) * class_group.mk (XY_ideal' h₂) = class_group.mk (XY_ideal' $ nonsingular_add h₁ h₂ hxy) := begin rw [← _root_.map_mul], exact (class_group.mk_eq_mk_of_coe_ideal (by exact (fractional_ideal.coe_ideal_mul _ _).symm) $ XY_ideal'_eq _).mpr ⟨_, _, X_class_ne_zero W _, Y_class_ne_zero W _, XY_ideal_mul_XY_ideal h₁.left h₂.left hxy⟩ end namespace point /-- The set function mapping an affine point $(x, y)$ of `W` to the class of the non-zero fractional ideal $\langle X - x, Y - y \rangle$ of $F(W)$ in the class group of $F[W]$. -/ @[simp] noncomputable def to_class_fun : W.point → additive (class_group W.coordinate_ring) | 0 := 0 | (some h) := additive.of_mul $ class_group.mk $ XY_ideal' h /-- The group homomorphism mapping an affine point $(x, y)$ of `W` to the class of the non-zero fractional ideal $\langle X - x, Y - y \rangle$ of $F(W)$ in the class group of $F[W]$. -/ @[simps] noncomputable def to_class : W.point →+ additive (class_group W.coordinate_ring) := { to_fun := to_class_fun, map_zero' := rfl, map_add' := begin rintro (_ | @⟨x₁, y₁, h₁⟩) (_ | @⟨x₂, y₂, h₂⟩), any_goals { simp only [zero_def, to_class_fun, _root_.zero_add, _root_.add_zero] }, by_cases hx : x₁ = x₂, { by_cases hy : y₁ = W.neg_Y x₂ y₂, { substs hx hy, simpa only [some_add_some_of_Y_eq rfl rfl] using (mk_XY_ideal'_mul_mk_XY_ideal'_of_Y_eq h₂).symm }, { simpa only [some_add_some_of_Y_ne hx hy] using (mk_XY_ideal'_mul_mk_XY_ideal' h₁ h₂ $ λ _, hy).symm } }, { simpa only [some_add_some_of_X_ne hx] using (mk_XY_ideal'_mul_mk_XY_ideal' h₁ h₂ $ λ h, (hx h).elim).symm } end } @[simp] lemma to_class_zero : to_class (0 : W.point) = 0 := rfl lemma to_class_some : to_class (some h₁) = class_group.mk (XY_ideal' h₁) := rfl @[simp] lemma add_eq_zero (P Q : W.point) : P + Q = 0 ↔ P = -Q := begin rcases ⟨P, Q⟩ with ⟨_ | @⟨x₁, y₁, _⟩, _ | @⟨x₂, y₂, _⟩⟩, any_goals { refl }, { rw [zero_def, zero_add, ← neg_eq_iff_eq_neg, neg_zero, eq_comm] }, { simp only [neg_some], split, { intro h, by_cases hx : x₁ = x₂, { by_cases hy : y₁ = W.neg_Y x₂ y₂, { exact ⟨hx, hy⟩ }, { rw [some_add_some_of_Y_ne hx hy] at h, contradiction } }, { rw [some_add_some_of_X_ne hx] at h, contradiction } }, { exact λ ⟨hx, hy⟩, some_add_some_of_Y_eq hx hy } } end @[simp] lemma add_left_neg (P : W.point) : -P + P = 0 := by rw [add_eq_zero] @[simp] lemma neg_add_eq_zero (P Q : W.point) : -P + Q = 0 ↔ P = Q := by rw [add_eq_zero, neg_inj] lemma to_class_eq_zero (P : W.point) : to_class P = 0 ↔ P = 0 := ⟨begin intro hP, rcases P with (_ | @⟨_, _, ⟨h, _⟩⟩), { refl }, { rcases (class_group.mk_eq_one_of_coe_ideal $ by refl).mp hP with ⟨p, h0, hp⟩, apply (p.nat_degree_norm_ne_one _).elim, rw [← finrank_quotient_span_eq_nat_degree_norm W^.coordinate_ring.basis h0, ← (quotient_equiv_alg_of_eq F hp).to_linear_equiv.finrank_eq, (quotient_XY_ideal_equiv W h).to_linear_equiv.finrank_eq, finite_dimensional.finrank_self] } end, congr_arg to_class⟩ lemma to_class_injective : function.injective $ @to_class _ _ W := begin rintro (_ | h) _ hP, all_goals { rw [← neg_add_eq_zero, ← to_class_eq_zero, map_add, ← hP] }, { exact zero_add 0 }, { exact mk_XY_ideal'_mul_mk_XY_ideal'_of_Y_eq h } end lemma add_comm (P Q : W.point) : P + Q = Q + P := to_class_injective $ by simp only [map_add, add_comm] lemma add_assoc (P Q R : W.point) : P + Q + R = P + (Q + R) := to_class_injective $ by simp only [map_add, add_assoc] noncomputable instance : add_comm_group W.point := { zero := zero, neg := neg, add := add, zero_add := zero_add, add_zero := add_zero, add_left_neg := add_left_neg, add_comm := add_comm, add_assoc := add_assoc } end point end group section base_change /-! ### Nonsingular rational points on a base changed Weierstrass curve -/ variables {R : Type u} [comm_ring R] (W : weierstrass_curve R) (F : Type v) [field F] [algebra R F] (K : Type w) [field K] [algebra R K] [algebra F K] [is_scalar_tower R F K] namespace point open_locale weierstrass_curve /-- The function from `W⟮F⟯` to `W⟮K⟯` induced by a base change from `F` to `K`. -/ def of_base_change_fun : W⟮F⟯ → W⟮K⟯ | 0 := 0 | (some h) := some $ (nonsingular_iff_base_change_of_base_change W F K _ _).mp h /-- The group homomorphism from `W⟮F⟯` to `W⟮K⟯` induced by a base change from `F` to `K`. -/ @[simps] def of_base_change : W⟮F⟯ →+ W⟮K⟯ := { to_fun := of_base_change_fun W F K, map_zero' := rfl, map_add' := begin rintro (_ | @⟨x₁, y₁, _⟩) (_ | @⟨x₂, y₂, _⟩), any_goals { refl }, by_cases hx : x₁ = x₂, { by_cases hy : y₁ = (W.base_change F).neg_Y x₂ y₂, { simp only [some_add_some_of_Y_eq hx hy, of_base_change_fun], rw [some_add_some_of_Y_eq $ congr_arg _ hx], { rw [hy, base_change_neg_Y_of_base_change] } }, { simp only [some_add_some_of_Y_ne hx hy, of_base_change_fun], rw [some_add_some_of_Y_ne $ congr_arg _ hx], { simp only [base_change_add_X_of_base_change, base_change_add_Y_of_base_change, base_change_slope_of_base_change], exact ⟨rfl, rfl⟩ }, { rw [base_change_neg_Y_of_base_change], contrapose! hy, exact no_zero_smul_divisors.algebra_map_injective F K hy } } }, { simp only [some_add_some_of_X_ne hx, of_base_change_fun], rw [some_add_some_of_X_ne], { simp only [base_change_add_X_of_base_change, base_change_add_Y_of_base_change, base_change_slope_of_base_change], exact ⟨rfl, rfl⟩ }, { contrapose! hx, exact no_zero_smul_divisors.algebra_map_injective F K hx } } end } lemma of_base_change_injective : function.injective $ of_base_change W F K := begin rintro (_ | _) (_ | _) h, { refl }, any_goals { contradiction }, simp only, exact ⟨no_zero_smul_divisors.algebra_map_injective F K (some.inj h).left, no_zero_smul_divisors.algebra_map_injective F K (some.inj h).right⟩ end end point end base_change end weierstrass_curve namespace elliptic_curve /-! ### Rational points on an elliptic curve -/ namespace point variables {R : Type} [nontrivial R] [comm_ring R] (E : elliptic_curve R) /-- An affine point on an elliptic curve `E` over `R`. -/ def mk {x y : R} (h : E.equation x y) : E.point := weierstrass_curve.point.some $ E.nonsingular h end point end elliptic_curve
b8c7540d861a08c8e14bd5c411163e6a1dbcb428
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/src/Lean/Elab/PreDefinition/WF.lean
f9e1021e5a7b60a1ab99386713d2fff4d5870c93
[ "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
396
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Elab.PreDefinition.Basic namespace Lean namespace Elab open Meta def WFRecursion (preDefs : Array PreDefinition) : TermElabM Unit := throwError "well founded recursion has not been implemented yet" end Elab end Lean
d940e3e00ee80f1d9e107b98af86e262804316bc
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/data/list/default.lean
1b9d0bb48acd80b21fc844312c2cbccb9a7e298d
[ "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
182
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad -/ import data.list.basic
774f4da3abf650d376bee4e4f81ffa5683204381
271e26e338b0c14544a889c31c30b39c989f2e0f
/src/Init/Lean/Elab/Import.lean
35ea571892024099e028032c0807044e79dffc72
[ "Apache-2.0" ]
permissive
dgorokho/lean4
805f99b0b60c545b64ac34ab8237a8504f89d7d4
e949a052bad59b1c7b54a82d24d516a656487d8a
refs/heads/master
1,607,061,363,851
1,578,006,086,000
1,578,006,086,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,993
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 -/ prelude import Init.Lean.Parser.Module namespace Lean namespace Elab def headerToImports (header : Syntax) : List Import := let header := header.asNode; let imports := if (header.getArg 0).isNone then [{Import . module := `Init.Default}] else []; imports ++ (header.getArg 1).getArgs.toList.map (fun stx => -- `stx` is of the form `(Module.import "import" "runtime"? id) let runtime := !(stx.getArg 1).isNone; let id := stx.getIdAt 2; { module := normalizeModuleName id, runtimeOnly := runtime }) def processHeader (header : Syntax) (messages : MessageLog) (ctx : Parser.ParserContextCore) (trustLevel : UInt32 := 0) : IO (Environment × MessageLog) := catch (do env ← importModules (headerToImports header) trustLevel; pure (env, messages)) (fun e => do env ← mkEmptyEnvironment; let spos := header.getPos.getD 0; let pos := ctx.fileMap.toPosition spos; pure (env, messages.add { fileName := ctx.fileName, data := toString e, pos := pos })) def parseImports (input : String) (fileName : Option String := none) : IO (List Import × Position × MessageLog) := do env ← mkEmptyEnvironment; let fileName := fileName.getD "<input>"; let ctx := Parser.mkParserContextCore env input fileName; match Parser.parseHeader env ctx with | (header, parserState, messages) => do pure (headerToImports header, ctx.fileMap.toPosition parserState.pos, messages) @[export lean_parse_imports] def parseImportsExport (input : String) (fileName : Option String) : IO (List Import × Position × List Message) := do (imports, pos, log) ← parseImports input fileName; pure (imports, pos, log.toList) @[export lean_print_deps] def printDeps (deps : List Import) : IO Unit := deps.forM $ fun dep => do fname ← findOLean dep.module; IO.println fname end Elab end Lean
9a73ebdeaded0e95693fd40a777afe5019c2558f
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/category_theory/preadditive/projective_resolution.lean
16f66b844bf9e05024b1b5f8e88eaa20d5ea0238
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
13,101
lean
/- Copyright (c) 2021 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.preadditive.projective import algebra.homology.single import algebra.homology.homotopy_category /-! # Projective resolutions > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. A projective resolution `P : ProjectiveResolution Z` of an object `Z : C` consists of a `ℕ`-indexed chain complex `P.complex` of projective objects, along with a chain map `P.π` from `C` to the chain complex consisting just of `Z` in degree zero, so that the augmented chain complex is exact. When `C` is abelian, this exactness condition is equivalent to `π` being a quasi-isomorphism. It turns out that this formulation allows us to set up the basic theory of derived functors without even assuming `C` is abelian. (Typically, however, to show `has_projective_resolutions C` one will assume `enough_projectives C` and `abelian C`. This construction appears in `category_theory.abelian.projectives`.) We show that given `P : ProjectiveResolution X` and `Q : ProjectiveResolution Y`, any morphism `X ⟶ Y` admits a lift to a chain map `P.complex ⟶ Q.complex`. (It is a lift in the sense that the projection maps `P.π` and `Q.π` intertwine the lift and the original morphism.) Moreover, we show that any two such lifts are homotopic. As a consequence, if every object admits a projective resolution, we can construct a functor `projective_resolutions C : C ⥤ homotopy_category C`. -/ noncomputable theory open category_theory open category_theory.limits universes v u namespace category_theory variables {C : Type u} [category.{v} C] open projective section variables [has_zero_object C] [has_zero_morphisms C] [has_equalizers C] [has_images C] /-- A `ProjectiveResolution Z` consists of a bundled `ℕ`-indexed chain complex of projective objects, along with a quasi-isomorphism to the complex consisting of just `Z` supported in degree `0`. (We don't actually ask here that the chain map is a quasi-iso, just exactness everywhere: that `π` is a quasi-iso is a lemma when the category is abelian. Should we just ask for it here?) Except in situations where you want to provide a particular projective resolution (for example to compute a derived functor), you will not typically need to use this bundled object, and will instead use * `projective_resolution Z`: the `ℕ`-indexed chain complex (equipped with `projective` and `exact` instances) * `projective_resolution.π Z`: the chain map from `projective_resolution Z` to `(single C _ 0).obj Z` (all the components are equipped with `epi` instances, and when the category is `abelian` we will show `π` is a quasi-iso). -/ @[nolint has_nonempty_instance] structure ProjectiveResolution (Z : C) := (complex : chain_complex C ℕ) (π : homological_complex.hom complex ((chain_complex.single₀ C).obj Z)) (projective : ∀ n, projective (complex.X n) . tactic.apply_instance) (exact₀ : exact (complex.d 1 0) (π.f 0)) (exact : ∀ n, exact (complex.d (n+2) (n+1)) (complex.d (n+1) n)) (epi : epi (π.f 0) . tactic.apply_instance) attribute [instance] ProjectiveResolution.projective ProjectiveResolution.epi /-- An object admits a projective resolution. -/ class has_projective_resolution (Z : C) : Prop := (out [] : nonempty (ProjectiveResolution Z)) section variables (C) /-- You will rarely use this typeclass directly: it is implied by the combination `[enough_projectives C]` and `[abelian C]`. By itself it's enough to set up the basic theory of derived functors. -/ class has_projective_resolutions : Prop := (out : ∀ Z : C, has_projective_resolution Z) attribute [instance, priority 100] has_projective_resolutions.out end namespace ProjectiveResolution @[simp] lemma π_f_succ {Z : C} (P : ProjectiveResolution Z) (n : ℕ) : P.π.f (n+1) = 0 := begin apply zero_of_target_iso_zero, dsimp, refl, end @[simp] lemma complex_d_comp_π_f_zero {Z : C} (P : ProjectiveResolution Z) : P.complex.d 1 0 ≫ P.π.f 0 = 0 := P.exact₀.w @[simp] lemma complex_d_succ_comp {Z : C} (P : ProjectiveResolution Z) (n : ℕ) : P.complex.d (n + 2) (n + 1) ≫ P.complex.d (n + 1) n = 0 := (P.exact _).w instance {Z : C} (P : ProjectiveResolution Z) (n : ℕ) : category_theory.epi (P.π.f n) := by cases n; apply_instance /-- A projective object admits a trivial projective resolution: itself in degree 0. -/ def self (Z : C) [category_theory.projective Z] : ProjectiveResolution Z := { complex := (chain_complex.single₀ C).obj Z, π := 𝟙 ((chain_complex.single₀ C).obj Z), projective := λ n, begin cases n, { dsimp, apply_instance, }, { dsimp, apply_instance, }, end, exact₀ := by { dsimp, exact exact_zero_mono _ }, exact := λ n, by { dsimp, exact exact_of_zero _ _ }, epi := by { dsimp, apply_instance, }, } /-- Auxiliary construction for `lift`. -/ def lift_f_zero {Y Z : C} (f : Y ⟶ Z) (P : ProjectiveResolution Y) (Q : ProjectiveResolution Z) : P.complex.X 0 ⟶ Q.complex.X 0 := factor_thru (P.π.f 0 ≫ f) (Q.π.f 0) /-- Auxiliary construction for `lift`. -/ def lift_f_one {Y Z : C} (f : Y ⟶ Z) (P : ProjectiveResolution Y) (Q : ProjectiveResolution Z) : P.complex.X 1 ⟶ Q.complex.X 1 := exact.lift (P.complex.d 1 0 ≫ lift_f_zero f P Q) (Q.complex.d 1 0) (Q.π.f 0) Q.exact₀ (by simp [lift_f_zero, P.exact₀.w_assoc]) /-- Auxiliary lemma for `lift`. -/ @[simp] lemma lift_f_one_zero_comm {Y Z : C} (f : Y ⟶ Z) (P : ProjectiveResolution Y) (Q : ProjectiveResolution Z) : lift_f_one f P Q ≫ Q.complex.d 1 0 = P.complex.d 1 0 ≫ lift_f_zero f P Q := begin dsimp [lift_f_zero, lift_f_one], simp, end /-- Auxiliary construction for `lift`. -/ def lift_f_succ {Y Z : C} (P : ProjectiveResolution Y) (Q : ProjectiveResolution Z) (n : ℕ) (g : P.complex.X n ⟶ Q.complex.X n) (g' : P.complex.X (n+1) ⟶ Q.complex.X (n+1)) (w : g' ≫ Q.complex.d (n+1) n = P.complex.d (n+1) n ≫ g) : Σ' g'' : P.complex.X (n+2) ⟶ Q.complex.X (n+2), g'' ≫ Q.complex.d (n+2) (n+1) = P.complex.d (n+2) (n+1) ≫ g' := ⟨exact.lift (P.complex.d (n+2) (n+1) ≫ g') ((Q.complex.d (n+2) (n+1))) (Q.complex.d (n+1) n) (Q.exact _) (by simp [w]), (by simp)⟩ /-- A morphism in `C` lifts to a chain map between projective resolutions. -/ def lift {Y Z : C} (f : Y ⟶ Z) (P : ProjectiveResolution Y) (Q : ProjectiveResolution Z) : P.complex ⟶ Q.complex := chain_complex.mk_hom _ _ (lift_f_zero f _ _) (lift_f_one f _ _) (lift_f_one_zero_comm f _ _) (λ n ⟨g, g', w⟩, lift_f_succ P Q n g g' w) /-- The resolution maps intertwine the lift of a morphism and that morphism. -/ @[simp, reassoc] lemma lift_commutes {Y Z : C} (f : Y ⟶ Z) (P : ProjectiveResolution Y) (Q : ProjectiveResolution Z) : lift f P Q ≫ Q.π = P.π ≫ (chain_complex.single₀ C).map f := by { ext, dsimp [lift, lift_f_zero], apply factor_thru_comp, } -- Now that we've checked this property of the lift, -- we can seal away the actual definition. attribute [irreducible] lift end ProjectiveResolution end namespace ProjectiveResolution variables [has_zero_object C] [preadditive C] [has_equalizers C] [has_images C] /-- An auxiliary definition for `lift_homotopy_zero`. -/ def lift_homotopy_zero_zero {Y Z : C} {P : ProjectiveResolution Y} {Q : ProjectiveResolution Z} (f : P.complex ⟶ Q.complex) (comm : f ≫ Q.π = 0) : P.complex.X 0 ⟶ Q.complex.X 1 := exact.lift (f.f 0) (Q.complex.d 1 0) (Q.π.f 0) Q.exact₀ (congr_fun (congr_arg homological_complex.hom.f comm) 0) /-- An auxiliary definition for `lift_homotopy_zero`. -/ def lift_homotopy_zero_one {Y Z : C} {P : ProjectiveResolution Y} {Q : ProjectiveResolution Z} (f : P.complex ⟶ Q.complex) (comm : f ≫ Q.π = 0) : P.complex.X 1 ⟶ Q.complex.X 2 := exact.lift (f.f 1 - P.complex.d 1 0 ≫ lift_homotopy_zero_zero f comm) (Q.complex.d 2 1) (Q.complex.d 1 0) (Q.exact _) (by simp [lift_homotopy_zero_zero]) /-- An auxiliary definition for `lift_homotopy_zero`. -/ def lift_homotopy_zero_succ {Y Z : C} {P : ProjectiveResolution Y} {Q : ProjectiveResolution Z} (f : P.complex ⟶ Q.complex) (n : ℕ) (g : P.complex.X n ⟶ Q.complex.X (n + 1)) (g' : P.complex.X (n + 1) ⟶ Q.complex.X (n + 2)) (w : f.f (n + 1) = P.complex.d (n + 1) n ≫ g + g' ≫ Q.complex.d (n + 2) (n + 1)) : P.complex.X (n + 2) ⟶ Q.complex.X (n + 3) := exact.lift (f.f (n+2) - P.complex.d (n+2) (n+1) ≫ g') (Q.complex.d (n+3) (n+2)) (Q.complex.d (n+2) (n+1)) (Q.exact _) (by simp [w]) /-- Any lift of the zero morphism is homotopic to zero. -/ def lift_homotopy_zero {Y Z : C} {P : ProjectiveResolution Y} {Q : ProjectiveResolution Z} (f : P.complex ⟶ Q.complex) (comm : f ≫ Q.π = 0) : homotopy f 0 := homotopy.mk_inductive _ (lift_homotopy_zero_zero f comm) (by simp [lift_homotopy_zero_zero]) (lift_homotopy_zero_one f comm) (by simp [lift_homotopy_zero_one]) (λ n ⟨g, g', w⟩, ⟨lift_homotopy_zero_succ f n g g' w, by simp [lift_homotopy_zero_succ, w]⟩) /-- Two lifts of the same morphism are homotopic. -/ def lift_homotopy {Y Z : C} (f : Y ⟶ Z) {P : ProjectiveResolution Y} {Q : ProjectiveResolution Z} (g h : P.complex ⟶ Q.complex) (g_comm : g ≫ Q.π = P.π ≫ (chain_complex.single₀ C).map f) (h_comm : h ≫ Q.π = P.π ≫ (chain_complex.single₀ C).map f) : homotopy g h := homotopy.equiv_sub_zero.inv_fun (lift_homotopy_zero _ (by simp [g_comm, h_comm])) /-- The lift of the identity morphism is homotopic to the identity chain map. -/ def lift_id_homotopy (X : C) (P : ProjectiveResolution X) : homotopy (lift (𝟙 X) P P) (𝟙 P.complex) := by { apply lift_homotopy (𝟙 X); simp, } /-- The lift of a composition is homotopic to the composition of the lifts. -/ def lift_comp_homotopy {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) (P : ProjectiveResolution X) (Q : ProjectiveResolution Y) (R : ProjectiveResolution Z) : homotopy (lift (f ≫ g) P R) (lift f P Q ≫ lift g Q R) := by { apply lift_homotopy (f ≫ g); simp, } -- We don't care about the actual definitions of these homotopies. attribute [irreducible] lift_homotopy_zero lift_homotopy lift_id_homotopy lift_comp_homotopy /-- Any two projective resolutions are homotopy equivalent. -/ def homotopy_equiv {X : C} (P Q : ProjectiveResolution X) : homotopy_equiv P.complex Q.complex := { hom := lift (𝟙 X) P Q, inv := lift (𝟙 X) Q P, homotopy_hom_inv_id := begin refine (lift_comp_homotopy (𝟙 X) (𝟙 X) P Q P).symm.trans _, simp [category.id_comp], apply lift_id_homotopy, end, homotopy_inv_hom_id := begin refine (lift_comp_homotopy (𝟙 X) (𝟙 X) Q P Q).symm.trans _, simp [category.id_comp], apply lift_id_homotopy, end, } @[simp, reassoc] lemma homotopy_equiv_hom_π {X : C} (P Q : ProjectiveResolution X) : (homotopy_equiv P Q).hom ≫ Q.π = P.π := by simp [homotopy_equiv] @[simp, reassoc] lemma homotopy_equiv_inv_π {X : C} (P Q : ProjectiveResolution X) : (homotopy_equiv P Q).inv ≫ P.π = Q.π := by simp [homotopy_equiv] end ProjectiveResolution section variables [has_zero_morphisms C] [has_zero_object C] [has_equalizers C] [has_images C] /-- An arbitrarily chosen projective resolution of an object. -/ abbreviation projective_resolution (Z : C) [has_projective_resolution Z] : chain_complex C ℕ := (has_projective_resolution.out Z).some.complex /-- The chain map from the arbitrarily chosen projective resolution `projective_resolution Z` back to the chain complex consisting of `Z` supported in degree `0`. -/ abbreviation projective_resolution.π (Z : C) [has_projective_resolution Z] : projective_resolution Z ⟶ (chain_complex.single₀ C).obj Z := (has_projective_resolution.out Z).some.π /-- The lift of a morphism to a chain map between the arbitrarily chosen projective resolutions. -/ abbreviation projective_resolution.lift {X Y : C} (f : X ⟶ Y) [has_projective_resolution X] [has_projective_resolution Y] : projective_resolution X ⟶ projective_resolution Y := ProjectiveResolution.lift f _ _ end variables (C) [preadditive C] [has_zero_object C] [has_equalizers C] [has_images C] [has_projective_resolutions C] /-- Taking projective resolutions is functorial, if considered with target the homotopy category (`ℕ`-indexed chain complexes and chain maps up to homotopy). -/ def projective_resolutions : C ⥤ homotopy_category C (complex_shape.down ℕ) := { obj := λ X, (homotopy_category.quotient _ _).obj (projective_resolution X), map := λ X Y f, (homotopy_category.quotient _ _).map (projective_resolution.lift f), map_id' := λ X, begin rw ←(homotopy_category.quotient _ _).map_id, apply homotopy_category.eq_of_homotopy, apply ProjectiveResolution.lift_id_homotopy, end, map_comp' := λ X Y Z f g, begin rw ←(homotopy_category.quotient _ _).map_comp, apply homotopy_category.eq_of_homotopy, apply ProjectiveResolution.lift_comp_homotopy, end, } end category_theory
e90dfad954fc0b058b57a5915deb26f82c43ed0b
9dc8cecdf3c4634764a18254e94d43da07142918
/src/group_theory/group_action/sub_mul_action.lean
5d03221e6e8cf93f833f69ec3c133574b7114e53
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
7,158
lean
/- Copyright (c) 2020 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import algebra.hom.group_action import algebra.module.basic import data.set_like.basic import group_theory.group_action.basic /-! # Sets invariant to a `mul_action` In this file we define `sub_mul_action R M`; a subset of a `mul_action R M` which is closed with respect to scalar multiplication. For most uses, typically `submodule R M` is more powerful. ## Main definitions * `sub_mul_action.mul_action` - the `mul_action R M` transferred to the subtype. * `sub_mul_action.mul_action'` - the `mul_action S M` transferred to the subtype when `is_scalar_tower S R M`. * `sub_mul_action.is_scalar_tower` - the `is_scalar_tower S R M` transferred to the subtype. ## Tags submodule, mul_action -/ open function universes u u' u'' v variables {S : Type u'} {T : Type u''} {R : Type u} {M : Type v} set_option old_structure_cmd true /-- A sub_mul_action is a set which is closed under scalar multiplication. -/ structure sub_mul_action (R : Type u) (M : Type v) [has_smul R M] : Type v := (carrier : set M) (smul_mem' : ∀ (c : R) {x : M}, x ∈ carrier → c • x ∈ carrier) namespace sub_mul_action variables [has_smul R M] instance : set_like (sub_mul_action R M) M := ⟨sub_mul_action.carrier, λ p q h, by cases p; cases q; congr'⟩ @[simp] lemma mem_carrier {p : sub_mul_action R M} {x : M} : x ∈ p.carrier ↔ x ∈ (p : set M) := iff.rfl @[ext] theorem ext {p q : sub_mul_action R M} (h : ∀ x, x ∈ p ↔ x ∈ q) : p = q := set_like.ext h /-- Copy of a sub_mul_action with a new `carrier` equal to the old one. Useful to fix definitional equalities.-/ protected def copy (p : sub_mul_action R M) (s : set M) (hs : s = ↑p) : sub_mul_action R M := { carrier := s, smul_mem' := hs.symm ▸ p.smul_mem' } @[simp] lemma coe_copy (p : sub_mul_action R M) (s : set M) (hs : s = ↑p) : (p.copy s hs : set M) = s := rfl lemma copy_eq (p : sub_mul_action R M) (s : set M) (hs : s = ↑p) : p.copy s hs = p := set_like.coe_injective hs instance : has_bot (sub_mul_action R M) := ⟨{ carrier := ∅, smul_mem' := λ c, set.not_mem_empty}⟩ instance : inhabited (sub_mul_action R M) := ⟨⊥⟩ end sub_mul_action namespace sub_mul_action section has_smul variables [has_smul R M] variables (p : sub_mul_action R M) variables {r : R} {x : M} lemma smul_mem (r : R) (h : x ∈ p) : r • x ∈ p := p.smul_mem' r h instance : has_smul R p := { smul := λ c x, ⟨c • x.1, smul_mem _ c x.2⟩ } variables {p} @[simp, norm_cast] lemma coe_smul (r : R) (x : p) : ((r • x : p) : M) = r • ↑x := rfl @[simp, norm_cast] lemma coe_mk (x : M) (hx : x ∈ p) : ((⟨x, hx⟩ : p) : M) = x := rfl variables (p) /-- Embedding of a submodule `p` to the ambient space `M`. -/ protected def subtype : p →[R] M := by refine {to_fun := coe, ..}; simp [coe_smul] @[simp] theorem subtype_apply (x : p) : p.subtype x = x := rfl lemma subtype_eq_val : ((sub_mul_action.subtype p) : p → M) = subtype.val := rfl end has_smul section mul_action_monoid variables [monoid R] [mul_action R M] section variables [has_smul S R] [has_smul S M] [is_scalar_tower S R M] variables (p : sub_mul_action R M) lemma smul_of_tower_mem (s : S) {x : M} (h : x ∈ p) : s • x ∈ p := by { rw [←one_smul R x, ←smul_assoc], exact p.smul_mem _ h } instance has_smul' : has_smul S p := { smul := λ c x, ⟨c • x.1, smul_of_tower_mem _ c x.2⟩ } instance : is_scalar_tower S R p := { smul_assoc := λ s r x, subtype.ext $ smul_assoc s r ↑x } @[simp, norm_cast] lemma coe_smul_of_tower (s : S) (x : p) : ((s • x : p) : M) = s • ↑x := rfl @[simp] lemma smul_mem_iff' {G} [group G] [has_smul G R] [mul_action G M] [is_scalar_tower G R M] (g : G) {x : M} : g • x ∈ p ↔ x ∈ p := ⟨λ h, inv_smul_smul g x ▸ p.smul_of_tower_mem g⁻¹ h, p.smul_of_tower_mem g⟩ instance [has_smul Sᵐᵒᵖ R] [has_smul Sᵐᵒᵖ M] [is_scalar_tower Sᵐᵒᵖ R M] [is_central_scalar S M] : is_central_scalar S p := { op_smul_eq_smul := λ r x, subtype.ext $ op_smul_eq_smul r x } end section variables [monoid S] [has_smul S R] [mul_action S M] [is_scalar_tower S R M] variables (p : sub_mul_action R M) /-- If the scalar product forms a `mul_action`, then the subset inherits this action -/ instance mul_action' : mul_action S p := { smul := (•), one_smul := λ x, subtype.ext $ one_smul _ x, mul_smul := λ c₁ c₂ x, subtype.ext $ mul_smul c₁ c₂ x } instance : mul_action R p := p.mul_action' end /-- Orbits in a `sub_mul_action` coincide with orbits in the ambient space. -/ lemma coe_image_orbit {p : sub_mul_action R M} (m : p) : coe '' mul_action.orbit R m = mul_action.orbit R (m : M) := (set.range_comp _ _).symm /- -- Previously, the relatively useless : lemma orbit_of_sub_mul {p : sub_mul_action R M} (m : p) : (mul_action.orbit R m : set M) = mul_action.orbit R (m : M) := rfl -/ /-- Stabilizers in monoid sub_mul_action coincide with stabilizers in the ambient space -/ lemma stabilizer_of_sub_mul.submonoid {p : sub_mul_action R M} (m : p) : mul_action.stabilizer.submonoid R m = mul_action.stabilizer.submonoid R (m : M) := begin ext, simp only [mul_action.mem_stabilizer_submonoid_iff, ← sub_mul_action.coe_smul, set_like.coe_eq_coe] end end mul_action_monoid section mul_action_group variables [group R] [mul_action R M] /-- Stabilizers in group sub_mul_action coincide with stabilizers in the ambient space -/ lemma stabilizer_of_sub_mul {p : sub_mul_action R M} (m : p) : mul_action.stabilizer R m = mul_action.stabilizer R (m : M) := begin rw ← subgroup.to_submonoid_eq, exact stabilizer_of_sub_mul.submonoid m, end end mul_action_group section module variables [semiring R] [add_comm_monoid M] variables [module R M] variables (p : sub_mul_action R M) lemma zero_mem (h : (p : set M).nonempty) : (0 : M) ∈ p := let ⟨x, hx⟩ := h in zero_smul R (x : M) ▸ p.smul_mem 0 hx /-- If the scalar product forms a `module`, and the `sub_mul_action` is not `⊥`, then the subset inherits the zero. -/ instance [n_empty : nonempty p] : has_zero p := { zero := ⟨0, n_empty.elim $ λ x, p.zero_mem ⟨x, x.prop⟩⟩ } end module section add_comm_group variables [ring R] [add_comm_group M] variables [module R M] variables (p p' : sub_mul_action R M) variables {r : R} {x y : M} lemma neg_mem (hx : x ∈ p) : -x ∈ p := by { rw ← neg_one_smul R, exact p.smul_mem _ hx } @[simp] lemma neg_mem_iff : -x ∈ p ↔ x ∈ p := ⟨λ h, by { rw ←neg_neg x, exact neg_mem _ h}, neg_mem _⟩ instance : has_neg p := ⟨λx, ⟨-x.1, neg_mem _ x.2⟩⟩ @[simp, norm_cast] lemma coe_neg (x : p) : ((-x : p) : M) = -x := rfl end add_comm_group end sub_mul_action namespace sub_mul_action variables [group_with_zero S] [monoid R] [mul_action R M] variables [has_smul S R] [mul_action S M] [is_scalar_tower S R M] variables (p : sub_mul_action R M) {s : S} {x y : M} theorem smul_mem_iff (s0 : s ≠ 0) : s • x ∈ p ↔ x ∈ p := p.smul_mem_iff' (units.mk0 s s0) end sub_mul_action
f446ca8ec5b63f4c3b2716519adf77e25a655639
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/check2.lean
3f2e5ca523042e0085233e91405de6f13b22f700
[ "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
20
lean
-- check eq.rec_on
10c9f52c9cce440b65c18d8c4ec07f4e5ae7ee76
bb31430994044506fa42fd667e2d556327e18dfe
/src/analysis/convex/hull.lean
e31a5497a850453f9d0e78c41161cf8fd63ea001
[ "Apache-2.0" ]
permissive
sgouezel/mathlib
0cb4e5335a2ba189fa7af96d83a377f83270e503
00638177efd1b2534fc5269363ebf42a7871df9a
refs/heads/master
1,674,527,483,042
1,673,665,568,000
1,673,665,568,000
119,598,202
0
0
null
1,517,348,647,000
1,517,348,646,000
null
UTF-8
Lean
false
false
7,084
lean
/- Copyright (c) 2020 Yury Kudriashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudriashov, Yaël Dillies -/ import analysis.convex.basic import order.closure /-! # Convex hull This file defines the convex hull of a set `s` in a module. `convex_hull 𝕜 s` is the smallest convex set containing `s`. In order theory speak, this is a closure operator. ## Implementation notes `convex_hull` is defined as a closure operator. This gives access to the `closure_operator` API while the impact on writing code is minimal as `convex_hull 𝕜 s` is automatically elaborated as `⇑(convex_hull 𝕜) s`. -/ open set open_locale pointwise variables {𝕜 E F : Type*} section convex_hull section ordered_semiring variables [ordered_semiring 𝕜] section add_comm_monoid variables (𝕜) [add_comm_monoid E] [add_comm_monoid F] [module 𝕜 E] [module 𝕜 F] /-- The convex hull of a set `s` is the minimal convex set that includes `s`. -/ def convex_hull : closure_operator (set E) := closure_operator.mk₃ (λ s, ⋂ (t : set E) (hst : s ⊆ t) (ht : convex 𝕜 t), t) (convex 𝕜) (λ s, set.subset_Inter (λ t, set.subset_Inter $ λ hst, set.subset_Inter $ λ ht, hst)) (λ s, convex_Inter $ λ t, convex_Inter $ λ ht, convex_Inter id) (λ s t hst ht, set.Inter_subset_of_subset t $ set.Inter_subset_of_subset hst $ set.Inter_subset _ ht) variables (s : set E) lemma subset_convex_hull : s ⊆ convex_hull 𝕜 s := (convex_hull 𝕜).le_closure s lemma convex_convex_hull : convex 𝕜 (convex_hull 𝕜 s) := closure_operator.closure_mem_mk₃ s lemma convex_hull_eq_Inter : convex_hull 𝕜 s = ⋂ (t : set E) (hst : s ⊆ t) (ht : convex 𝕜 t), t := rfl variables {𝕜 s} {t : set E} {x y : E} lemma mem_convex_hull_iff : x ∈ convex_hull 𝕜 s ↔ ∀ t, s ⊆ t → convex 𝕜 t → x ∈ t := by simp_rw [convex_hull_eq_Inter, mem_Inter] lemma convex_hull_min (hst : s ⊆ t) (ht : convex 𝕜 t) : convex_hull 𝕜 s ⊆ t := closure_operator.closure_le_mk₃_iff (show s ≤ t, from hst) ht lemma convex.convex_hull_subset_iff (ht : convex 𝕜 t) : convex_hull 𝕜 s ⊆ t ↔ s ⊆ t := ⟨(subset_convex_hull _ _).trans, λ h, convex_hull_min h ht⟩ @[mono] lemma convex_hull_mono (hst : s ⊆ t) : convex_hull 𝕜 s ⊆ convex_hull 𝕜 t := (convex_hull 𝕜).monotone hst lemma convex.convex_hull_eq (hs : convex 𝕜 s) : convex_hull 𝕜 s = s := closure_operator.mem_mk₃_closed hs @[simp] lemma convex_hull_univ : convex_hull 𝕜 (univ : set E) = univ := closure_operator.closure_top (convex_hull 𝕜) @[simp] lemma convex_hull_empty : convex_hull 𝕜 (∅ : set E) = ∅ := convex_empty.convex_hull_eq @[simp] lemma convex_hull_empty_iff : convex_hull 𝕜 s = ∅ ↔ s = ∅ := begin split, { intro h, rw [←set.subset_empty_iff, ←h], exact subset_convex_hull 𝕜 _ }, { rintro rfl, exact convex_hull_empty } end @[simp] lemma convex_hull_nonempty_iff : (convex_hull 𝕜 s).nonempty ↔ s.nonempty := begin rw [nonempty_iff_ne_empty, nonempty_iff_ne_empty, ne.def, ne.def], exact not_congr convex_hull_empty_iff, end alias convex_hull_nonempty_iff ↔ _ set.nonempty.convex_hull attribute [protected] set.nonempty.convex_hull lemma segment_subset_convex_hull (hx : x ∈ s) (hy : y ∈ s) : segment 𝕜 x y ⊆ convex_hull 𝕜 s := (convex_convex_hull _ _).segment_subset (subset_convex_hull _ _ hx) (subset_convex_hull _ _ hy) @[simp] lemma convex_hull_singleton (x : E) : convex_hull 𝕜 ({x} : set E) = {x} := (convex_singleton x).convex_hull_eq @[simp] lemma convex_hull_pair (x y : E) : convex_hull 𝕜 {x, y} = segment 𝕜 x y := begin refine (convex_hull_min _ $ convex_segment _ _).antisymm (segment_subset_convex_hull (mem_insert _ _) $ mem_insert_of_mem _ $ mem_singleton _), rw [insert_subset, singleton_subset_iff], exact ⟨left_mem_segment _ _ _, right_mem_segment _ _ _⟩, end lemma convex_hull_convex_hull_union_left (s t : set E) : convex_hull 𝕜 (convex_hull 𝕜 s ∪ t) = convex_hull 𝕜 (s ∪ t) := closure_operator.closure_sup_closure_left _ _ _ lemma convex_hull_convex_hull_union_right (s t : set E) : convex_hull 𝕜 (s ∪ convex_hull 𝕜 t) = convex_hull 𝕜 (s ∪ t) := closure_operator.closure_sup_closure_right _ _ _ lemma convex.convex_remove_iff_not_mem_convex_hull_remove {s : set E} (hs : convex 𝕜 s) (x : E) : convex 𝕜 (s \ {x}) ↔ x ∉ convex_hull 𝕜 (s \ {x}) := begin split, { rintro hsx hx, rw hsx.convex_hull_eq at hx, exact hx.2 (mem_singleton _) }, rintro hx, suffices h : s \ {x} = convex_hull 𝕜 (s \ {x}), { convert convex_convex_hull 𝕜 _ }, exact subset.antisymm (subset_convex_hull 𝕜 _) (λ y hy, ⟨convex_hull_min (diff_subset _ _) hs hy, by { rintro (rfl : y = x), exact hx hy }⟩), end lemma is_linear_map.convex_hull_image {f : E → F} (hf : is_linear_map 𝕜 f) (s : set E) : convex_hull 𝕜 (f '' s) = f '' convex_hull 𝕜 s := set.subset.antisymm (convex_hull_min (image_subset _ (subset_convex_hull 𝕜 s)) $ (convex_convex_hull 𝕜 s).is_linear_image hf) (image_subset_iff.2 $ convex_hull_min (image_subset_iff.1 $ subset_convex_hull 𝕜 _) ((convex_convex_hull 𝕜 _).is_linear_preimage hf)) lemma linear_map.convex_hull_image (f : E →ₗ[𝕜] F) (s : set E) : convex_hull 𝕜 (f '' s) = f '' convex_hull 𝕜 s := f.is_linear.convex_hull_image s end add_comm_monoid end ordered_semiring section ordered_comm_semiring variables [ordered_comm_semiring 𝕜] [add_comm_monoid E] [module 𝕜 E] lemma convex_hull_smul (a : 𝕜) (s : set E) : convex_hull 𝕜 (a • s) = a • convex_hull 𝕜 s := (linear_map.lsmul _ _ a).convex_hull_image _ end ordered_comm_semiring section ordered_ring variables [ordered_ring 𝕜] section add_comm_group variables [add_comm_group E] [add_comm_group F] [module 𝕜 E] [module 𝕜 F] (s : set E) lemma affine_map.image_convex_hull (f : E →ᵃ[𝕜] F) : f '' convex_hull 𝕜 s = convex_hull 𝕜 (f '' s) := begin apply set.subset.antisymm, { rw set.image_subset_iff, refine convex_hull_min _ ((convex_convex_hull 𝕜 (⇑f '' s)).affine_preimage f), rw ← set.image_subset_iff, exact subset_convex_hull 𝕜 (f '' s) }, { exact convex_hull_min (set.image_subset _ (subset_convex_hull 𝕜 s)) ((convex_convex_hull 𝕜 s).affine_image f) } end lemma convex_hull_subset_affine_span : convex_hull 𝕜 s ⊆ (affine_span 𝕜 s : set E) := convex_hull_min (subset_affine_span 𝕜 s) (affine_span 𝕜 s).convex @[simp] lemma affine_span_convex_hull : affine_span 𝕜 (convex_hull 𝕜 s) = affine_span 𝕜 s := begin refine le_antisymm _ (affine_span_mono 𝕜 (subset_convex_hull 𝕜 s)), rw affine_span_le, exact convex_hull_subset_affine_span s, end lemma convex_hull_neg (s : set E) : convex_hull 𝕜 (-s) = -convex_hull 𝕜 s := by { simp_rw ←image_neg, exact (affine_map.image_convex_hull _ $ -1).symm } end add_comm_group end ordered_ring end convex_hull
53e482d0cc9b62df7b7198277a5f6ec48d85d688
d5bef83c55d40cb88f9a01b755c882a93348a847
/tests/lean/run/soundness.lean
9fb8a97743887c281e071aa832cfe9d5c3dda1bb
[ "Apache-2.0" ]
permissive
urkud/lean
587d78216e1f0c7f651566e9e92cf8ade285d58d
3526539070ea6268df5dd373deeb3ac8b9621952
refs/heads/master
1,660,171,634,921
1,657,873,466,000
1,657,873,466,000
249,789,456
0
0
Apache-2.0
1,585,075,263,000
1,585,075,263,000
null
UTF-8
Lean
false
false
6,724
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura Define propositional calculus, valuation, provability, validity, prove soundness. This file is based on Floris van Doorn Coq files. Similar to soundness.lean, but defines Nc in Type. The idea is to be able to prove soundness using recursive equations. -/ open nat bool list decidable attribute [reducible] definition PropVar := nat inductive PropF | Var : PropVar → PropF | Bot : PropF | Conj : PropF → PropF → PropF | Disj : PropF → PropF → PropF | Impl : PropF → PropF → PropF namespace PropF notation `#`:max P:max := Var P local notation A ∨ B := Disj A B local notation A ∧ B := Conj A B local infixr `⇒`:27 := Impl notation `⊥` := Bot def Neg (A) := A ⇒ ⊥ notation `~` A := Neg A def Top := ~⊥ notation `⊤` := Top def BiImpl (A B) := A ⇒ B ∧ B ⇒ A infixr `⇔`:27 := BiImpl def valuation := PropVar → bool def TrueQ (v : valuation) : PropF → bool | (# P) := v P | ⊥ := ff | (A ∨ B) := TrueQ A || TrueQ B | (A ∧ B) := TrueQ A && TrueQ B | (A ⇒ B) := bnot (TrueQ A) || TrueQ B attribute [reducible] def is_true (b : bool) := b = tt -- the valuation v satisfies a list of PropF, if forall (A : PropF) in Γ, -- (TrueQ v A) is tt (the Boolean true) def Satisfies (v) (Γ : list PropF) := ∀ A, A ∈ Γ → is_true (TrueQ v A) def Models (Γ A) := ∀ v, Satisfies v Γ → is_true (TrueQ v A) infix `⊨`:80 := Models def Valid (p) := [] ⊨ p reserve infix ` ⊢ `:26 /- Provability -/ inductive Nc : list PropF → PropF → Type infix ⊢ := Nc | Nax : ∀ Γ A, A ∈ Γ → Γ ⊢ A | ImpI : ∀ Γ A B, A::Γ ⊢ B → Γ ⊢ A ⇒ B | ImpE : ∀ Γ A B, Γ ⊢ A ⇒ B → Γ ⊢ A → Γ ⊢ B | BotC : ∀ Γ A, (~A)::Γ ⊢ ⊥ → Γ ⊢ A | AndI : ∀ Γ A B, Γ ⊢ A → Γ ⊢ B → Γ ⊢ A ∧ B | AndE₁ : ∀ Γ A B, Γ ⊢ A ∧ B → Γ ⊢ A | AndE₂ : ∀ Γ A B, Γ ⊢ A ∧ B → Γ ⊢ B | OrI₁ : ∀ Γ A B, Γ ⊢ A → Γ ⊢ A ∨ B | OrI₂ : ∀ Γ A B, Γ ⊢ B → Γ ⊢ A ∨ B | OrE : ∀ Γ A B C, Γ ⊢ A ∨ B → A::Γ ⊢ C → B::Γ ⊢ C → Γ ⊢ C infix ⊢ := Nc def Provable (A) := [] ⊢ A def Prop_Soundness := ∀ A, Provable A → Valid A def Prop_Completeness := ∀ A, Valid A → Provable A open Nc def weakening2 : ∀ {Γ A Δ}, Γ ⊢ A → Γ ⊆ Δ → Δ ⊢ A | ._ ._ Δ (Nax Γ A Hin) Hs := Nax _ _ (Hs Hin) | ._ .(A ⇒ B) Δ (ImpI Γ A B H) Hs := ImpI _ _ _ (weakening2 H (cons_subset_cons A Hs)) | ._ ._ Δ (ImpE Γ A B H₁ H₂) Hs := ImpE _ _ _ (weakening2 H₁ Hs) (weakening2 H₂ Hs) | ._ ._ Δ (BotC Γ A H) Hs := BotC _ _ (weakening2 H (cons_subset_cons (~A) Hs)) | ._ .(A ∧ B) Δ (AndI Γ A B H₁ H₂) Hs := AndI _ _ _ (weakening2 H₁ Hs) (weakening2 H₂ Hs) | ._ ._ Δ (AndE₁ Γ A B H) Hs := AndE₁ _ _ _ (weakening2 H Hs) | ._ ._ Δ (AndE₂ Γ A B H) Hs := AndE₂ _ _ _ (weakening2 H Hs) | ._ .(A ∨ B) Δ (OrI₁ Γ A B H) Hs := OrI₁ _ _ _ (weakening2 H Hs) | ._ .(A ∨ B) Δ (OrI₂ Γ A B H) Hs := OrI₂ _ _ _ (weakening2 H Hs) | ._ ._ Δ (OrE Γ A B C H₁ H₂ H₃) Hs := OrE _ _ _ _ (weakening2 H₁ Hs) (weakening2 H₂ (cons_subset_cons A Hs)) (weakening2 H₃ (cons_subset_cons B Hs)) def weakening : ∀ Γ Δ A, Γ ⊢ A → Γ++Δ ⊢ A := λ Γ Δ A H, weakening2 H (subset_append_left Γ Δ) def deduction : ∀ Γ A B, Γ ⊢ A ⇒ B → A::Γ ⊢ B := λ Γ A B H, ImpE _ _ _ (weakening2 H (subset_cons A Γ)) (Nax _ _ (mem_cons_self A Γ)) def prov_impl : ∀ A B, Provable (A ⇒ B) → ∀ Γ, Γ ⊢ A → Γ ⊢ B := λ A B Hp Γ Ha, have wHp : Γ ⊢ (A ⇒ B), from weakening _ _ _ Hp, ImpE _ _ _ wHp Ha lemma Satisfies_cons : ∀ {A Γ v}, Satisfies v Γ → is_true (TrueQ v A) → Satisfies v (A::Γ) := λ A Γ v s t B BinAG, or.elim BinAG (λ e : B = A, by rewrite e; exact t) (λ i : B ∈ Γ, s _ i) attribute [simp] is_true TrueQ theorem Soundness_general {v : valuation} : ∀ {A Γ}, Γ ⊢ A → Satisfies v Γ → is_true (TrueQ v A) | ._ ._ (Nax Γ A Hin) s := s _ Hin | .(A ⇒ B) ._ (ImpI Γ A B H) s := by_cases (λ t : is_true (TrueQ v A), have Satisfies v (A::Γ), from Satisfies_cons s t, have TrueQ v B = tt, from Soundness_general H this, by simp[*]) (λ f : ¬ is_true (TrueQ v A), have TrueQ v A = ff, by simp at f; simp[*], have bnot (TrueQ v A) = tt, by simp[*], by simp[*]) | ._ ._ (ImpE Γ A B H₁ H₂) s := have aux : TrueQ v A = tt, from Soundness_general H₂ s, have bnot (TrueQ v A) || TrueQ v B = tt, from Soundness_general H₁ s, by simp [aux] at this; simp[*] | ._ ._ (BotC Γ A H) s := by_contradiction (λ n : TrueQ v A ≠ tt, have TrueQ v A = ff, by {simp at n; simp[*]}, have TrueQ v (~A) = tt, begin change (bnot (TrueQ v A) || ff = tt), simp[*] end, have Satisfies v ((~A)::Γ), from Satisfies_cons s this, have TrueQ v ⊥ = tt, from Soundness_general H this, absurd this ff_ne_tt) | .(A ∧ B) ._ (AndI Γ A B H₁ H₂) s := have TrueQ v A = tt, from Soundness_general H₁ s, have TrueQ v B = tt, from Soundness_general H₂ s, by simp[*] | ._ ._ (AndE₁ Γ A B H) s := have TrueQ v (A ∧ B) = tt, from Soundness_general H s, by simp [TrueQ] at this; simp [*, is_true] | ._ ._ (AndE₂ Γ A B H) s := have TrueQ v (A ∧ B) = tt, from Soundness_general H s, by simp at this; simp[*] | .(A ∨ B) ._ (OrI₁ Γ A B H) s := have TrueQ v A = tt, from Soundness_general H s, by simp[*] | .(A ∨ B) ._ (OrI₂ Γ A B H) s := have TrueQ v B = tt, from Soundness_general H s, by simp[*] | ._ ._ (OrE Γ A B C H₁ H₂ H₃) s := have TrueQ v A || TrueQ v B = tt, from Soundness_general H₁ s, have or (TrueQ v A = tt) (TrueQ v B = tt), by simp at this; simp[*], or.elim this (λ At, have Satisfies v (A::Γ), from Satisfies_cons s At, Soundness_general H₂ this) (λ Bt, have Satisfies v (B::Γ), from Satisfies_cons s Bt, Soundness_general H₃ this) theorem Soundness : Prop_Soundness := λ A H v s, Soundness_general H s end PropF
db3cc677b74ac7960f0f82a768ebba5c8ba66c9c
5ca7b1b12d14c4742e29366312ba2c2ef8201b21
/src/game/intro.lean
c6f666e648e37d9938bed80a6797e39b4266bc82
[ "Apache-2.0" ]
permissive
MatthiasHu/natural_number_game
2e464482ef3001863430b0336133b6697b275ba3
2d764f72669ae30861f6a1057fce0257f3e466c4
refs/heads/master
1,609,719,110,419
1,576,345,737,000
1,576,345,737,000
240,296,314
0
0
Apache-2.0
1,581,608,357,000
1,581,608,356,000
null
UTF-8
Lean
false
false
3,789
lean
/- # The Natural Number Game, version 1.1beta ## By Kevin Buzzard and Mohammad Pedramfar. # What is this game? Welcome to the natural number game -- a part-book part-game which shows the power of induction. Blue nodes on the graph are ones that you are ready to enter. Grey nodes you should stay away from -- a grey node turns blue when *all* nodes above it are complete. Green nodes are completed. In this game, you get own version of the natural numbers, called `mynat`, in a programming language called Lean. Your version of the natural numbers satisfies something called the principle of mathematical induction, and a couple of other things too (Peano's axioms). Unfortunately, nobody has proved any theorems about these natural numbers yet. For example, addition will be defined for you, but nobody has proved that `x + y = y + x` yet. This is your job. You're going to prove mathematical theorems using the Lean theorem prover. In other words, you're going to solve levels in a computer game. You're going to prove these theorems using *tactics*. The introductory world, Tutorial World, will take you through some of these tactics. During your proofs, your "goal" (i.e. what you're supposed to be proving) will be displayed with a `⊢` symbol in front of it. If the top right hand box reports "Theorem Proved!", you have closed all the goals in the level and can move on to the next level in the world you're in. When you've finished a world, hit "main menu" in the top left to get back here. # What's new? Pretty much all the <= levels of inequality world. I've <a href="https://github.com/ImperialCollegeLondon/natural_number_game/blob/master/src/game/world10/level18a.lean" target="blank"> written all the Lean code for "strictly less than"</a> but am really busy with real life right now. In my dreams -- even/odd world. Feel free to fork and add your name to the list of authors. Instructions on how to build new worlds is on <a href="https://github.com/mpedramfar/Lean-game-maker" target="blank"> Mohammad's Lean Game Maker site</a>. Any Imperial 1st year maths or JMC students -- do you want to help make <a href="https://github.com/ImperialCollegeLondon/real-number-game" target="blank">the real number game</a> in Lean so you can teach yourself and others how to prove $\operatorname{Sup}(X+Y)=\operatorname{Sup}(X)+\operatorname{Sup}(Y)$ *rigorously*? I've <a href="https://github.com/ImperialCollegeLondon/real-number-game/blob/a420eecef62209b729c910c2170d1dd27b74bc9f/world_plans/supinf.lean#L188" target="blank"> done the Lean proof</a> and most of the tactics you need to know to understand the proof are the ones in the natural number game anyway. # Thanks Special thanks to Rob Lewis for tactic hackery, Bryan Gin-Ge Chen for javascript hackery, Patrick Massot for his <a href="https://github.com/leanprover-community/format_lean" target="blank">Lean to html formatter</a>, Sian Carey for Power World, and, last but not least, all the people who fed back comments, including the 2019-20 Imperial College 1st year maths beta tester students, Marie-Amélie Lawn, Toby Gee, Joseph Myers, and all the people who have been in touch via the <a href="https://leanprover.zulipchat.com/" target="blank">Lean Zulip chat</a> or the <a href="https://xenaproject.wordpress.com/" target="blank">Xena Project blog</a> or via <a href="https://twitter.com/XenaProject" target="blank">Twitter</a>. The natural number game is brought to you by the Xena project, a project based at Imperial College London whose aim is to get mathematics undergraduates using computer theorem provers. Lean is a computer theorem prover being developed at Microsoft Research. Prove a theorem. Write a function. <a href="https://twitter.com/XenaProject" target="blank">@XenaProject</a>. -/
251a474e8afb2ddaa052aec5a448358201a13d21
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/scopedTokens.lean
50856ae653960a3445517e0b9d4ef83fde8dff06
[ "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
484
lean
namespace Foo scoped syntax "foo!" term:max : term macro_rules | `(foo! $x) => `($x + 1) #check foo! 20 theorem ex1 : foo! 20 = 21 := rfl end Foo #check foo! 10 -- Error def foo! := 10 theorem ex2 : foo! = 10 := rfl #check foo! open Foo #check foo! 20 theorem ex3 : foo! 10 = 11 := rfl namespace Bla scoped syntax "bla!" term:max : term macro_rules | `(bla! $x) => `($x * 2) theorem ex2 : bla! 3 = 6 := rfl end Bla def bla! := 20 theorem ex4 : bla! = 20 := rfl
1211dd7d1fe825551eb4ac16fd48601bb32ed17e
1437b3495ef9020d5413178aa33c0a625f15f15f
/category_theory/products.lean
1685ae716a118d448b978e06104ae25318c2a9b2
[ "Apache-2.0" ]
permissive
jean002/mathlib
c66bbb2d9fdc9c03ae07f869acac7ddbfce67a30
dc6c38a765799c99c4d9c8d5207d9e6c9e0e2cfd
refs/heads/master
1,587,027,806,375
1,547,306,358,000
1,547,306,358,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,537
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Stephen Morgan, Scott Morrison import category_theory.functor_category import category_theory.isomorphism import tactic.interactive namespace category_theory universes v₁ v₂ v₃ v₄ u₁ u₂ u₃ u₄ -- declare the `v`'s first; see `category_theory.category` for an explanation section variables (C : Type u₁) [𝒞 : category.{v₁} C] (D : Type u₂) [𝒟 : category.{v₂} D] include 𝒞 𝒟 /-- `prod C D` gives the cartesian product of two categories. -/ instance prod : category.{max v₁ v₂} (C × D) := { hom := λ X Y, ((X.1) ⟶ (Y.1)) × ((X.2) ⟶ (Y.2)), id := λ X, ⟨ 𝟙 (X.1), 𝟙 (X.2) ⟩, comp := λ _ _ _ f g, (f.1 ≫ g.1, f.2 ≫ g.2) } -- rfl lemmas for category.prod @[simp] lemma prod_id (X : C) (Y : D) : 𝟙 (X, Y) = (𝟙 X, 𝟙 Y) := rfl @[simp] lemma prod_comp {P Q R : C} {S T U : D} (f : (P, S) ⟶ (Q, T)) (g : (Q, T) ⟶ (R, U)) : f ≫ g = (f.1 ≫ g.1, f.2 ≫ g.2) := rfl @[simp] lemma prod_id_fst (X : prod C D) : _root_.prod.fst (𝟙 X) = 𝟙 X.fst := rfl @[simp] lemma prod_id_snd (X : prod C D) : _root_.prod.snd (𝟙 X) = 𝟙 X.snd := rfl @[simp] lemma prod_comp_fst {X Y Z : prod C D} (f : X ⟶ Y) (g : Y ⟶ Z) : (f ≫ g).1 = f.1 ≫ g.1 := rfl @[simp] lemma prod_comp_snd {X Y Z : prod C D} (f : X ⟶ Y) (g : Y ⟶ Z) : (f ≫ g).2 = f.2 ≫ g.2 := rfl end section variables (C : Type u₁) [𝒞 : category.{v₁} C] (D : Type u₁) [𝒟 : category.{v₁} D] include 𝒞 𝒟 /-- `prod.category.uniform C D` is an additional instance specialised so both factors have the same universe levels. This helps typeclass resolution. -/ instance uniform_prod : category (C × D) := category_theory.prod C D end -- Next we define the natural functors into and out of product categories. For now this doesn't address the universal properties. namespace prod variables (C : Type u₁) [𝒞 : category.{v₁} C] (D : Type u₂) [𝒟 : category.{v₂} D] include 𝒞 𝒟 /-- `inl C Z` is the functor `X ↦ (X, Z)`. -/ def inl (Z : D) : C ⥤ (C × D) := { obj := λ X, (X, Z), map := λ X Y f, (f, 𝟙 Z) } /-- `inr D Z` is the functor `X ↦ (Z, X)`. -/ def inr (Z : C) : D ⥤ (C × D) := { obj := λ X, (Z, X), map := λ X Y f, (𝟙 Z, f) } /-- `fst` is the functor `(X, Y) ↦ X`. -/ def fst : (C × D) ⥤ C := { obj := λ X, X.1, map := λ X Y f, f.1 } /-- `snd` is the functor `(X, Y) ↦ Y`. -/ def snd : (C × D) ⥤ D := { obj := λ X, X.2, map := λ X Y f, f.2 } def swap : (C × D) ⥤ (D × C) := { obj := λ X, (X.2, X.1), map := λ _ _ f, (f.2, f.1) } def symmetry : ((swap C D) ⋙ (swap D C)) ≅ (functor.id (C × D)) := { hom := { app := λ X, 𝟙 X, naturality' := begin intros, erw [category.comp_id (C × D), category.id_comp (C × D)], dsimp [swap], simp, end }, inv := { app := λ X, 𝟙 X, naturality' := begin intros, erw [category.comp_id (C × D), category.id_comp (C × D)], dsimp [swap], simp, end } } end prod section variables (C : Type u₁) [𝒞 : category.{v₁} C] (D : Type u₂) [𝒟 : category.{v₂} D] include 𝒞 𝒟 @[simp] def evaluation : C ⥤ (C ⥤ D) ⥤ D := { obj := λ X, { obj := λ F, F.obj X, map := λ F G α, α.app X, }, map := λ X Y f, { app := λ F, F.map f, naturality' := λ F G α, eq.symm (α.naturality f) }, map_comp' := λ X Y Z f g, begin ext, dsimp, rw functor.map_comp, end } @[simp] def evaluation_uncurried : (C × (C ⥤ D)) ⥤ D := { obj := λ p, p.2.obj p.1, map := λ x y f, (x.2.map f.1) ≫ (f.2.app y.1), map_comp' := begin intros X Y Z f g, cases g, cases f, cases Z, cases Y, cases X, dsimp at *, simp at *, erw [←nat_trans.vcomp_app, nat_trans.naturality, category.assoc, nat_trans.naturality] end } end variables {A : Type u₁} [𝒜 : category.{v₁} A] {B : Type u₂} [ℬ : category.{v₂} B] {C : Type u₃} [𝒞 : category.{v₃} C] {D : Type u₄} [𝒟 : category.{v₄} D] include 𝒜 ℬ 𝒞 𝒟 namespace functor /-- The cartesian product of two functors. -/ def prod (F : A ⥤ B) (G : C ⥤ D) : (A × C) ⥤ (B × D) := { obj := λ X, (F.obj X.1, G.obj X.2), map := λ _ _ f, (F.map f.1, G.map f.2) } /- Because of limitations in Lean 3's handling of notations, we do not setup a notation `F × G`. You can use `F.prod G` as a "poor man's infix", or just write `functor.prod F G`. -/ @[simp] lemma prod_obj (F : A ⥤ B) (G : C ⥤ D) (a : A) (c : C) : (F.prod G).obj (a, c) = (F.obj a, G.obj c) := rfl @[simp] lemma prod_map (F : A ⥤ B) (G : C ⥤ D) {a a' : A} {c c' : C} (f : (a, c) ⟶ (a', c')) : (F.prod G).map f = (F.map f.1, G.map f.2) := rfl end functor namespace nat_trans /-- The cartesian product of two natural transformations. -/ def prod {F G : A ⥤ B} {H I : C ⥤ D} (α : F ⟹ G) (β : H ⟹ I) : F.prod H ⟹ G.prod I := { app := λ X, (α.app X.1, β.app X.2), naturality' := begin /- `obviously'` says: -/ intros, cases f, cases Y, cases X, dsimp at *, simp, split, rw naturality, rw naturality end } /- Again, it is inadvisable in Lean 3 to setup a notation `α × β`; use instead `α.prod β` or `nat_trans.prod α β`. -/ @[simp] lemma prod_app {F G : A ⥤ B} {H I : C ⥤ D} (α : F ⟹ G) (β : H ⟹ I) (a : A) (c : C) : (nat_trans.prod α β).app (a, c) = (α.app a, β.app c) := rfl end nat_trans end category_theory
5e2f6649ca94f437f65667ba870cb1629e6ca704
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/1608.lean
8416246b60b9282e934a18b749b07d80f76b4b97
[ "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
216
lean
example {α : Type} {a b : α} (h : ¬ (a = b)) : b ≠ a := by cc example {α : Type} {a b : α} (h : ¬ (a = b)) : ¬ (b = a) := by cc example {α : Type} {a b : α} (h : ¬ (a = b)) : b ≠ a := begin [smt] end
cf8eb8277fcc7750010b999c21e937154667295e
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/stage0/src/Lean/Data/Lsp/Internal.lean
d82a9dae579c4c741c0b778a4a004acdfe98978a
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
EdAyers/lean4
57ac632d6b0789cb91fab2170e8c9e40441221bd
37ba0df5841bde51dbc2329da81ac23d4f6a4de4
refs/heads/master
1,676,463,245,298
1,660,619,433,000
1,660,619,433,000
183,433,437
1
0
Apache-2.0
1,657,612,672,000
1,556,196,574,000
Lean
UTF-8
Lean
false
false
3,038
lean
/- Copyright (c) 2022 Joscha Mennicken. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joscha Mennicken -/ import Lean.Expr import Lean.Data.Lsp.Basic /-! This file contains types for communication between the watchdog and the workers. These messages are not visible externally to users of the LSP server. -/ namespace Lean.Lsp open Std /-! Most reference-related types have custom FromJson/ToJson implementations to reduce the size of the resulting JSON. -/ inductive RefIdent where | const : Name → RefIdent | fvar : FVarId → RefIdent deriving BEq, Hashable, Inhabited namespace RefIdent def toString : RefIdent → String | RefIdent.const n => s!"c:{n}" | RefIdent.fvar id => s!"f:{id.name}" def fromString (s : String) : Except String RefIdent := do let sPrefix := s.take 2 let sName := s.drop 2 -- See `FromJson Name` let name ← match sName with | "[anonymous]" => pure Name.anonymous | _ => match Syntax.decodeNameLit ("`" ++ sName) with | some n => pure n | none => throw s!"expected a Name, got {sName}" match sPrefix with | "c:" => return RefIdent.const name | "f:" => return RefIdent.fvar <| FVarId.mk name | _ => throw "string must start with 'c:' or 'f:'" end RefIdent structure RefInfo where definition : Option Lsp.Range usages : Array Lsp.Range instance : ToJson RefInfo where toJson i := let rangeToList (r : Lsp.Range) : List Nat := [r.start.line, r.start.character, r.end.line, r.end.character] Json.mkObj [ ("definition", toJson $ i.definition.map rangeToList), ("usages", toJson $ i.usages.map rangeToList) ] instance : FromJson RefInfo where fromJson? j := do let listToRange (l : List Nat) : Except String Lsp.Range := match l with | [sLine, sChar, eLine, eChar] => pure ⟨⟨sLine, sChar⟩, ⟨eLine, eChar⟩⟩ | _ => throw s!"Expected list of length 4, not {l.length}" let definition ← j.getObjValAs? (Option $ List Nat) "definition" let definition ← match definition with | none => pure none | some list => some <$> listToRange list let usages ← j.getObjValAs? (Array $ List Nat) "usages" let usages ← usages.mapM listToRange pure { definition, usages } /-- References from a single module/file -/ def ModuleRefs := HashMap RefIdent RefInfo instance : ToJson ModuleRefs where toJson m := Json.mkObj <| m.toList.map fun (ident, info) => (ident.toString, toJson info) instance : FromJson ModuleRefs where fromJson? j := do let node ← j.getObj? node.foldM (init := HashMap.empty) fun m k v => return m.insert (← RefIdent.fromString k) (← fromJson? v) /-- `$/lean/ileanInfoUpdate` and `$/lean/ileanInfoFinal` watchdog<-worker notifications. Contains the file's definitions and references. -/ structure LeanIleanInfoParams where /-- Version of the file these references are from. -/ version : Nat references : ModuleRefs deriving FromJson, ToJson end Lean.Lsp
dcdfeda1e8c11a5e35173c483eee8085d710e3ce
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/tests/compiler/phashmap2.lean
c924b1389b801b7d8b459d7ffba53442c1b03646
[ "Apache-2.0" ]
permissive
mhuisi/lean4
28d35a4febc2e251c7f05492e13f3b05d6f9b7af
dda44bc47f3e5d024508060dac2bcb59fd12e4c0
refs/heads/master
1,621,225,489,283
1,585,142,689,000
1,585,142,689,000
250,590,438
0
2
Apache-2.0
1,602,443,220,000
1,585,327,814,000
C
UTF-8
Lean
false
false
1,569
lean
import Init.Data.PersistentHashMap import Init.Lean.Data.Format open Lean PersistentHashMap abbrev Map := PersistentHashMap Nat Nat partial def formatMap : Node Nat Nat → Format | Node.collision keys vals _ => Format.sbracket $ keys.size.fold (fun i fmt => let k := keys.get! i; let v := vals.get! i; let p := if i > 0 then fmt ++ format "," ++ Format.line else fmt; p ++ "c@" ++ Format.paren (format k ++ " => " ++ format v)) Format.nil | Node.entries entries => Format.sbracket $ entries.size.fold (fun i fmt => let entry := entries.get! i; let p := if i > 0 then fmt ++ format "," ++ Format.line else fmt; p ++ match entry with | Entry.null => "<null>" | Entry.ref node => formatMap node | Entry.entry k v => Format.paren (format k ++ " => " ++ format v)) Format.nil def main : IO Unit := do let a : Array Nat := [1, 2, 3].toArray; IO.println (a.indexOf 2); let m : Map := PersistentHashMap.empty; let m := m.insert 1 1; let m := m.insert 33 2; let m := m.insert 65 3; -- IO.println (formatMap m.root); IO.println m.stats; let m := m.erase 33; IO.println (m.find? 1); IO.println (m.find? 33); IO.println (m.find? 65); IO.println m.stats; let m := m.erase 1; IO.println (m.find? 1); IO.println (m.find? 33); IO.println (m.find? 65); IO.println m.stats; let m := m.erase 1; IO.println (m.find? 1); IO.println (m.find? 33); IO.println (m.find? 65); let m := m.erase 65; IO.println (m.find? 1); IO.println (m.find? 33); IO.println (m.find? 65); IO.println m.stats
3b94a4904e7fbc4e461a630f6f5c726af6ae6d84
9dc8cecdf3c4634764a18254e94d43da07142918
/src/ring_theory/ideal/operations.lean
bc0a4c1cce3836170dc0fde18d0f7466f95b2c68
[ "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
91,786
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import algebra.algebra.operations import algebra.ring.equiv import data.nat.choose.sum import ring_theory.coprime.lemmas import ring_theory.ideal.quotient import ring_theory.non_zero_divisors /-! # More operations on modules and ideals -/ universes u v w x open_locale big_operators pointwise namespace submodule variables {R : Type u} {M : Type v} {F : Type*} {G : Type*} section comm_semiring variables [comm_semiring R] [add_comm_monoid M] [module R M] open_locale pointwise instance has_smul' : has_smul (ideal R) (submodule R M) := ⟨submodule.map₂ (linear_map.lsmul R M)⟩ /-- This duplicates the global `smul_eq_mul`, but doesn't have to unfold anywhere near as much to apply. -/ protected lemma _root_.ideal.smul_eq_mul (I J : ideal R) : I • J = I * J := rfl /-- `N.annihilator` is the ideal of all elements `r : R` such that `r • N = 0`. -/ def annihilator (N : submodule R M) : ideal R := (linear_map.lsmul R N).ker variables {I J : ideal R} {N P : submodule R M} theorem mem_annihilator {r} : r ∈ N.annihilator ↔ ∀ n ∈ N, r • n = (0:M) := ⟨λ hr n hn, congr_arg subtype.val (linear_map.ext_iff.1 (linear_map.mem_ker.1 hr) ⟨n, hn⟩), λ h, linear_map.mem_ker.2 $ linear_map.ext $ λ n, subtype.eq $ h n.1 n.2⟩ theorem mem_annihilator' {r} : r ∈ N.annihilator ↔ N ≤ comap (r • (linear_map.id : M →ₗ[R] M)) ⊥ := mem_annihilator.trans ⟨λ H n hn, (mem_bot R).2 $ H n hn, λ H n hn, (mem_bot R).1 $ H hn⟩ lemma mem_annihilator_span (s : set M) (r : R) : r ∈ (submodule.span R s).annihilator ↔ ∀ n : s, r • (n : M) = 0 := begin rw submodule.mem_annihilator, split, { intros h n, exact h _ (submodule.subset_span n.prop) }, { intros h n hn, apply submodule.span_induction hn, { intros x hx, exact h ⟨x, hx⟩ }, { exact smul_zero _ }, { intros x y hx hy, rw [smul_add, hx, hy, zero_add] }, { intros a x hx, rw [smul_comm, hx, smul_zero] } } end lemma mem_annihilator_span_singleton (g : M) (r : R) : r ∈ (submodule.span R ({g} : set M)).annihilator ↔ r • g = 0 := by simp [mem_annihilator_span] theorem annihilator_bot : (⊥ : submodule R M).annihilator = ⊤ := (ideal.eq_top_iff_one _).2 $ mem_annihilator'.2 bot_le theorem annihilator_eq_top_iff : N.annihilator = ⊤ ↔ N = ⊥ := ⟨λ H, eq_bot_iff.2 $ λ (n:M) hn, (mem_bot R).2 $ one_smul R n ▸ mem_annihilator.1 ((ideal.eq_top_iff_one _).1 H) n hn, λ H, H.symm ▸ annihilator_bot⟩ theorem annihilator_mono (h : N ≤ P) : P.annihilator ≤ N.annihilator := λ r hrp, mem_annihilator.2 $ λ n hn, mem_annihilator.1 hrp n $ h hn theorem annihilator_supr (ι : Sort w) (f : ι → submodule R M) : (annihilator ⨆ i, f i) = ⨅ i, annihilator (f i) := le_antisymm (le_infi $ λ i, annihilator_mono $ le_supr _ _) (λ r H, mem_annihilator'.2 $ supr_le $ λ i, have _ := (mem_infi _).1 H i, mem_annihilator'.1 this) theorem smul_mem_smul {r} {n} (hr : r ∈ I) (hn : n ∈ N) : r • n ∈ I • N := apply_mem_map₂ _ hr hn theorem smul_le {P : submodule R M} : I • N ≤ P ↔ ∀ (r ∈ I) (n ∈ N), r • n ∈ P := map₂_le @[elab_as_eliminator] theorem smul_induction_on {p : M → Prop} {x} (H : x ∈ I • N) (Hb : ∀ (r ∈ I) (n ∈ N), p (r • n)) (H1 : ∀ x y, p x → p y → p (x + y)) : p x := begin have H0 : p 0 := by simpa only [zero_smul] using Hb 0 I.zero_mem 0 N.zero_mem, refine submodule.supr_induction _ H _ H0 H1, rintros ⟨i, hi⟩ m ⟨j, hj, (rfl : i • _ = m) ⟩, exact Hb _ hi _ hj, end theorem mem_smul_span_singleton {I : ideal R} {m : M} {x : M} : x ∈ I • span R ({m} : set M) ↔ ∃ y ∈ I, y • m = x := ⟨λ hx, smul_induction_on hx (λ r hri n hnm, let ⟨s, hs⟩ := mem_span_singleton.1 hnm in ⟨r * s, I.mul_mem_right _ hri, hs ▸ mul_smul r s m⟩) (λ m1 m2 ⟨y1, hyi1, hy1⟩ ⟨y2, hyi2, hy2⟩, ⟨y1 + y2, I.add_mem hyi1 hyi2, by rw [add_smul, hy1, hy2]⟩), λ ⟨y, hyi, hy⟩, hy ▸ smul_mem_smul hyi (subset_span $ set.mem_singleton m)⟩ theorem smul_le_right : I • N ≤ N := smul_le.2 $ λ r hr n, N.smul_mem r theorem smul_mono (hij : I ≤ J) (hnp : N ≤ P) : I • N ≤ J • P := map₂_le_map₂ hij hnp theorem smul_mono_left (h : I ≤ J) : I • N ≤ J • N := map₂_le_map₂_left h theorem smul_mono_right (h : N ≤ P) : I • N ≤ I • P := map₂_le_map₂_right h lemma map_le_smul_top (I : ideal R) (f : R →ₗ[R] M) : submodule.map f I ≤ I • (⊤ : submodule R M) := begin rintros _ ⟨y, hy, rfl⟩, rw [← mul_one y, ← smul_eq_mul, f.map_smul], exact smul_mem_smul hy mem_top end @[simp] theorem annihilator_smul (N : submodule R M) : annihilator N • N = ⊥ := eq_bot_iff.2 (smul_le.2 (λ r, mem_annihilator.1)) @[simp] theorem annihilator_mul (I : ideal R) : annihilator I * I = ⊥ := annihilator_smul I @[simp] theorem mul_annihilator (I : ideal R) : I * annihilator I = ⊥ := by rw [mul_comm, annihilator_mul] variables (I J N P) @[simp] theorem smul_bot : I • (⊥ : submodule R M) = ⊥ := map₂_bot_right _ _ @[simp] theorem bot_smul : (⊥ : ideal R) • N = ⊥ := map₂_bot_left _ _ @[simp] theorem top_smul : (⊤ : ideal R) • N = N := le_antisymm smul_le_right $ λ r hri, one_smul R r ▸ smul_mem_smul mem_top hri theorem smul_sup : I • (N ⊔ P) = I • N ⊔ I • P := map₂_sup_right _ _ _ _ theorem sup_smul : (I ⊔ J) • N = I • N ⊔ J • N := map₂_sup_left _ _ _ _ protected theorem smul_assoc : (I • J) • N = I • (J • N) := le_antisymm (smul_le.2 $ λ rs hrsij t htn, smul_induction_on hrsij (λ r hr s hs, (@smul_eq_mul R _ r s).symm ▸ smul_smul r s t ▸ smul_mem_smul hr (smul_mem_smul hs htn)) (λ x y, (add_smul x y t).symm ▸ submodule.add_mem _)) (smul_le.2 $ λ r hr sn hsn, suffices J • N ≤ submodule.comap (r • (linear_map.id : M →ₗ[R] M)) ((I • J) • N), from this hsn, smul_le.2 $ λ s hs n hn, show r • (s • n) ∈ (I • J) • N, from mul_smul r s n ▸ smul_mem_smul (smul_mem_smul hr hs) hn) lemma smul_inf_le (M₁ M₂ : submodule R M) : I • (M₁ ⊓ M₂) ≤ I • M₁ ⊓ I • M₂ := le_inf (submodule.smul_mono_right inf_le_left) (submodule.smul_mono_right inf_le_right) lemma smul_supr {ι : Sort*} {I : ideal R} {t : ι → submodule R M} : I • supr t = ⨆ i, I • t i := map₂_supr_right _ _ _ lemma smul_infi_le {ι : Sort*} {I : ideal R} {t : ι → submodule R M} : I • infi t ≤ ⨅ i, I • t i := le_infi (λ i, smul_mono_right (infi_le _ _)) variables (S : set R) (T : set M) theorem span_smul_span : (ideal.span S) • (span R T) = span R (⋃ (s ∈ S) (t ∈ T), {s • t}) := (map₂_span_span _ _ _ _).trans $ congr_arg _ $ set.image2_eq_Union _ _ _ lemma ideal_span_singleton_smul (r : R) (N : submodule R M) : (ideal.span {r} : ideal R) • N = r • N := begin have : span R (⋃ (t : M) (x : t ∈ N), {r • t}) = r • N, { convert span_eq _, exact (set.image_eq_Union _ (N : set M)).symm }, conv_lhs { rw [← span_eq N, span_smul_span] }, simpa end lemma span_smul_eq (r : R) (s : set M) : span R (r • s) = r • span R s := by rw [← ideal_span_singleton_smul, span_smul_span, ←set.image2_eq_Union, set.image2_singleton_left, set.image_smul] lemma mem_of_span_top_of_smul_mem (M' : submodule R M) (s : set R) (hs : ideal.span s = ⊤) (x : M) (H : ∀ r : s, (r : R) • x ∈ M') : x ∈ M' := begin suffices : (⊤ : ideal R) • (span R ({x} : set M)) ≤ M', { rw top_smul at this, exact this (subset_span (set.mem_singleton x)) }, rw [← hs, span_smul_span, span_le], simpa using H end /-- Given `s`, a generating set of `R`, to check that an `x : M` falls in a submodule `M'` of `x`, we only need to show that `r ^ n • x ∈ M'` for some `n` for each `r : s`. -/ lemma mem_of_span_eq_top_of_smul_pow_mem (M' : submodule R M) (s : set R) (hs : ideal.span s = ⊤) (x : M) (H : ∀ r : s, ∃ (n : ℕ), (r ^ n : R) • x ∈ M') : x ∈ M' := begin obtain ⟨s', hs₁, hs₂⟩ := (ideal.span_eq_top_iff_finite _).mp hs, replace H : ∀ r : s', ∃ (n : ℕ), (r ^ n : R) • x ∈ M' := λ r, H ⟨_, hs₁ r.prop⟩, choose n₁ n₂ using H, let N := s'.attach.sup n₁, have hs' := ideal.span_pow_eq_top (s' : set R) hs₂ N, apply M'.mem_of_span_top_of_smul_mem _ hs', rintro ⟨_, r, hr, rfl⟩, convert M'.smul_mem (r ^ (N - n₁ ⟨r, hr⟩)) (n₂ ⟨r, hr⟩) using 1, simp only [subtype.coe_mk, smul_smul, ← pow_add], rw tsub_add_cancel_of_le (finset.le_sup (s'.mem_attach _) : n₁ ⟨r, hr⟩ ≤ N), end variables {M' : Type w} [add_comm_monoid M'] [module R M'] theorem map_smul'' (f : M →ₗ[R] M') : (I • N).map f = I • N.map f := le_antisymm (map_le_iff_le_comap.2 $ smul_le.2 $ λ r hr n hn, show f (r • n) ∈ I • N.map f, from (f.map_smul r n).symm ▸ smul_mem_smul hr (mem_map_of_mem hn)) $ smul_le.2 $ λ r hr n hn, let ⟨p, hp, hfp⟩ := mem_map.1 hn in hfp ▸ f.map_smul r p ▸ mem_map_of_mem (smul_mem_smul hr hp) variables {I} lemma mem_smul_span {s : set M} {x : M} : x ∈ I • submodule.span R s ↔ x ∈ submodule.span R (⋃ (a ∈ I) (b ∈ s), ({a • b} : set M)) := by rw [← I.span_eq, submodule.span_smul_span, I.span_eq]; refl variables (I) /-- If `x` is an `I`-multiple of the submodule spanned by `f '' s`, then we can write `x` as an `I`-linear combination of the elements of `f '' s`. -/ lemma mem_ideal_smul_span_iff_exists_sum {ι : Type*} (f : ι → M) (x : M) : x ∈ I • span R (set.range f) ↔ ∃ (a : ι →₀ R) (ha : ∀ i, a i ∈ I), a.sum (λ i c, c • f i) = x := begin split, swap, { rintro ⟨a, ha, rfl⟩, exact submodule.sum_mem _ (λ c _, smul_mem_smul (ha c) $ subset_span $ set.mem_range_self _) }, refine λ hx, span_induction (mem_smul_span.mp hx) _ _ _ _, { simp only [set.mem_Union, set.mem_range, set.mem_singleton_iff], rintros x ⟨y, hy, x, ⟨i, rfl⟩, rfl⟩, refine ⟨finsupp.single i y, λ j, _, _⟩, { letI := classical.dec_eq ι, rw finsupp.single_apply, split_ifs, { assumption }, { exact I.zero_mem } }, refine @finsupp.sum_single_index ι R M _ _ i _ (λ i y, y • f i) _, simp }, { exact ⟨0, λ i, I.zero_mem, finsupp.sum_zero_index⟩ }, { rintros x y ⟨ax, hax, rfl⟩ ⟨ay, hay, rfl⟩, refine ⟨ax + ay, λ i, I.add_mem (hax i) (hay i), finsupp.sum_add_index _ _⟩; intros; simp only [zero_smul, add_smul] }, { rintros c x ⟨a, ha, rfl⟩, refine ⟨c • a, λ i, I.mul_mem_left c (ha i), _⟩, rw [finsupp.sum_smul_index, finsupp.smul_sum]; intros; simp only [zero_smul, mul_smul] }, end theorem mem_ideal_smul_span_iff_exists_sum' {ι : Type*} (s : set ι) (f : ι → M) (x : M) : x ∈ I • span R (f '' s) ↔ ∃ (a : s →₀ R) (ha : ∀ i, a i ∈ I), a.sum (λ i c, c • f i) = x := by rw [← submodule.mem_ideal_smul_span_iff_exists_sum, ← set.image_eq_range] @[simp] lemma smul_comap_le_comap_smul (f : M →ₗ[R] M') (S : submodule R M') (I : ideal R) : I • S.comap f ≤ (I • S).comap f := begin refine (submodule.smul_le.mpr (λ r hr x hx, _)), rw [submodule.mem_comap] at ⊢ hx, rw f.map_smul, exact submodule.smul_mem_smul hr hx end end comm_semiring section comm_ring variables [comm_ring R] [add_comm_group M] [module R M] variables {N N₁ N₂ P P₁ P₂ : submodule R M} /-- `N.colon P` is the ideal of all elements `r : R` such that `r • P ⊆ N`. -/ def colon (N P : submodule R M) : ideal R := annihilator (P.map N.mkq) theorem mem_colon {r} : r ∈ N.colon P ↔ ∀ p ∈ P, r • p ∈ N := mem_annihilator.trans ⟨λ H p hp, (quotient.mk_eq_zero N).1 (H (quotient.mk p) (mem_map_of_mem hp)), λ H m ⟨p, hp, hpm⟩, hpm ▸ (N.mkq).map_smul r p ▸ (quotient.mk_eq_zero N).2 $ H p hp⟩ theorem mem_colon' {r} : r ∈ N.colon P ↔ P ≤ comap (r • (linear_map.id : M →ₗ[R] M)) N := mem_colon theorem colon_mono (hn : N₁ ≤ N₂) (hp : P₁ ≤ P₂) : N₁.colon P₂ ≤ N₂.colon P₁ := λ r hrnp, mem_colon.2 $ λ p₁ hp₁, hn $ mem_colon.1 hrnp p₁ $ hp hp₁ theorem infi_colon_supr (ι₁ : Sort w) (f : ι₁ → submodule R M) (ι₂ : Sort x) (g : ι₂ → submodule R M) : (⨅ i, f i).colon (⨆ j, g j) = ⨅ i j, (f i).colon (g j) := le_antisymm (le_infi $ λ i, le_infi $ λ j, colon_mono (infi_le _ _) (le_supr _ _)) (λ r H, mem_colon'.2 $ supr_le $ λ j, map_le_iff_le_comap.1 $ le_infi $ λ i, map_le_iff_le_comap.2 $ mem_colon'.1 $ have _ := ((mem_infi _).1 H i), have _ := ((mem_infi _).1 this j), this) end comm_ring end submodule namespace ideal section add variables {R : Type u} [semiring R] @[simp] lemma add_eq_sup {I J : ideal R} : I + J = I ⊔ J := rfl @[simp] lemma zero_eq_bot : (0 : ideal R) = ⊥ := rfl end add section mul_and_radical variables {R : Type u} {ι : Type*} [comm_semiring R] variables {I J K L : ideal R} instance : has_mul (ideal R) := ⟨(•)⟩ @[simp] lemma one_eq_top : (1 : ideal R) = ⊤ := by erw [submodule.one_eq_range, linear_map.range_id] theorem mul_mem_mul {r s} (hr : r ∈ I) (hs : s ∈ J) : r * s ∈ I * J := submodule.smul_mem_smul hr hs theorem mul_mem_mul_rev {r s} (hr : r ∈ I) (hs : s ∈ J) : s * r ∈ I * J := mul_comm r s ▸ mul_mem_mul hr hs lemma pow_mem_pow {x : R} (hx : x ∈ I) (n : ℕ) : x ^ n ∈ I ^ n := submodule.pow_mem_pow _ hx _ lemma prod_mem_prod {ι : Type*} {s : finset ι} {I : ι → ideal R} {x : ι → R} : (∀ i ∈ s, x i ∈ I i) → ∏ i in s, x i ∈ ∏ i in s, I i := begin classical, apply finset.induction_on s, { intro _, rw [finset.prod_empty, finset.prod_empty, one_eq_top], exact submodule.mem_top }, { intros a s ha IH h, rw [finset.prod_insert ha, finset.prod_insert ha], exact mul_mem_mul (h a $ finset.mem_insert_self a s) (IH $ λ i hi, h i $ finset.mem_insert_of_mem hi) } end theorem mul_le : I * J ≤ K ↔ ∀ (r ∈ I) (s ∈ J), r * s ∈ K := submodule.smul_le lemma mul_le_left : I * J ≤ J := ideal.mul_le.2 (λ r hr s, J.mul_mem_left _) lemma mul_le_right : I * J ≤ I := ideal.mul_le.2 (λ r hr s hs, I.mul_mem_right _ hr) @[simp] lemma sup_mul_right_self : I ⊔ (I * J) = I := sup_eq_left.2 ideal.mul_le_right @[simp] lemma sup_mul_left_self : I ⊔ (J * I) = I := sup_eq_left.2 ideal.mul_le_left @[simp] lemma mul_right_self_sup : (I * J) ⊔ I = I := sup_eq_right.2 ideal.mul_le_right @[simp] lemma mul_left_self_sup : (J * I) ⊔ I = I := sup_eq_right.2 ideal.mul_le_left variables (I J K) protected theorem mul_comm : I * J = J * I := le_antisymm (mul_le.2 $ λ r hrI s hsJ, mul_mem_mul_rev hsJ hrI) (mul_le.2 $ λ r hrJ s hsI, mul_mem_mul_rev hsI hrJ) protected theorem mul_assoc : (I * J) * K = I * (J * K) := submodule.smul_assoc I J K theorem span_mul_span (S T : set R) : span S * span T = span ⋃ (s ∈ S) (t ∈ T), {s * t} := submodule.span_smul_span S T variables {I J K} lemma span_mul_span' (S T : set R) : span S * span T = span (S*T) := by { unfold span, rw submodule.span_mul_span, } lemma span_singleton_mul_span_singleton (r s : R) : span {r} * span {s} = (span {r * s} : ideal R) := by { unfold span, rw [submodule.span_mul_span, set.singleton_mul_singleton], } lemma span_singleton_pow (s : R) (n : ℕ): span {s} ^ n = (span {s ^ n} : ideal R) := begin induction n with n ih, { simp [set.singleton_one], }, simp only [pow_succ, ih, span_singleton_mul_span_singleton], end lemma mem_mul_span_singleton {x y : R} {I : ideal R} : x ∈ I * span {y} ↔ ∃ z ∈ I, z * y = x := submodule.mem_smul_span_singleton lemma mem_span_singleton_mul {x y : R} {I : ideal R} : x ∈ span {y} * I ↔ ∃ z ∈ I, y * z = x := by simp only [mul_comm, mem_mul_span_singleton] lemma le_span_singleton_mul_iff {x : R} {I J : ideal R} : I ≤ span {x} * J ↔ ∀ zI ∈ I, ∃ zJ ∈ J, x * zJ = zI := show (∀ {zI} (hzI : zI ∈ I), zI ∈ span {x} * J) ↔ ∀ zI ∈ I, ∃ zJ ∈ J, x * zJ = zI, by simp only [mem_span_singleton_mul] lemma span_singleton_mul_le_iff {x : R} {I J : ideal R} : span {x} * I ≤ J ↔ ∀ z ∈ I, x * z ∈ J := begin simp only [mul_le, mem_span_singleton_mul, mem_span_singleton], split, { intros h zI hzI, exact h x (dvd_refl x) zI hzI }, { rintros h _ ⟨z, rfl⟩ zI hzI, rw [mul_comm x z, mul_assoc], exact J.mul_mem_left _ (h zI hzI) }, end lemma span_singleton_mul_le_span_singleton_mul {x y : R} {I J : ideal R} : span {x} * I ≤ span {y} * J ↔ ∀ zI ∈ I, ∃ zJ ∈ J, x * zI = y * zJ := by simp only [span_singleton_mul_le_iff, mem_span_singleton_mul, eq_comm] lemma eq_span_singleton_mul {x : R} (I J : ideal R) : I = span {x} * J ↔ ((∀ zI ∈ I, ∃ zJ ∈ J, x * zJ = zI) ∧ (∀ z ∈ J, x * z ∈ I)) := by simp only [le_antisymm_iff, le_span_singleton_mul_iff, span_singleton_mul_le_iff] lemma span_singleton_mul_eq_span_singleton_mul {x y : R} (I J : ideal R) : span {x} * I = span {y} * J ↔ ((∀ zI ∈ I, ∃ zJ ∈ J, x * zI = y * zJ) ∧ (∀ zJ ∈ J, ∃ zI ∈ I, x * zI = y * zJ)) := by simp only [le_antisymm_iff, span_singleton_mul_le_span_singleton_mul, eq_comm] lemma prod_span {ι : Type*} (s : finset ι) (I : ι → set R) : (∏ i in s, ideal.span (I i)) = ideal.span (∏ i in s, I i) := submodule.prod_span s I lemma prod_span_singleton {ι : Type*} (s : finset ι) (I : ι → R) : (∏ i in s, ideal.span ({I i} : set R)) = ideal.span {∏ i in s, I i} := submodule.prod_span_singleton s I lemma finset_inf_span_singleton {ι : Type*} (s : finset ι) (I : ι → R) (hI : set.pairwise ↑s (is_coprime on I)) : (s.inf $ λ i, ideal.span ({I i} : set R)) = ideal.span {∏ i in s, I i} := begin ext x, simp only [submodule.mem_finset_inf, ideal.mem_span_singleton], exact ⟨finset.prod_dvd_of_coprime hI, λ h i hi, (finset.dvd_prod_of_mem _ hi).trans h⟩ end lemma infi_span_singleton {ι : Type*} [fintype ι] (I : ι → R) (hI : ∀ i j (hij : i ≠ j), is_coprime (I i) (I j)): (⨅ i, ideal.span ({I i} : set R)) = ideal.span {∏ i, I i} := begin rw [← finset.inf_univ_eq_infi, finset_inf_span_singleton], rwa [finset.coe_univ, set.pairwise_univ] end lemma sup_eq_top_iff_is_coprime {R : Type*} [comm_semiring R] (x y : R) : span ({x} : set R) ⊔ span {y} = ⊤ ↔ is_coprime x y := begin rw [eq_top_iff_one, submodule.mem_sup], split, { rintro ⟨u, hu, v, hv, h1⟩, rw mem_span_singleton' at hu hv, rw [← hu.some_spec, ← hv.some_spec] at h1, exact ⟨_, _, h1⟩ }, { exact λ ⟨u, v, h1⟩, ⟨_, mem_span_singleton'.mpr ⟨_, rfl⟩, _, mem_span_singleton'.mpr ⟨_, rfl⟩, h1⟩ }, end theorem mul_le_inf : I * J ≤ I ⊓ J := mul_le.2 $ λ r hri s hsj, ⟨I.mul_mem_right s hri, J.mul_mem_left r hsj⟩ theorem multiset_prod_le_inf {s : multiset (ideal R)} : s.prod ≤ s.inf := begin classical, refine s.induction_on _ _, { rw [multiset.inf_zero], exact le_top }, intros a s ih, rw [multiset.prod_cons, multiset.inf_cons], exact le_trans mul_le_inf (inf_le_inf le_rfl ih) end theorem prod_le_inf {s : finset ι} {f : ι → ideal R} : s.prod f ≤ s.inf f := multiset_prod_le_inf theorem mul_eq_inf_of_coprime (h : I ⊔ J = ⊤) : I * J = I ⊓ J := le_antisymm mul_le_inf $ λ r ⟨hri, hrj⟩, let ⟨s, hsi, t, htj, hst⟩ := submodule.mem_sup.1 ((eq_top_iff_one _).1 h) in mul_one r ▸ hst ▸ (mul_add r s t).symm ▸ ideal.add_mem (I * J) (mul_mem_mul_rev hsi hrj) (mul_mem_mul hri htj) lemma sup_mul_eq_of_coprime_left (h : I ⊔ J = ⊤) : I ⊔ (J * K) = I ⊔ K := le_antisymm (sup_le_sup_left mul_le_left _) $ λ i hi, begin rw eq_top_iff_one at h, rw submodule.mem_sup at h hi ⊢, obtain ⟨i1, hi1, j, hj, h⟩ := h, obtain ⟨i', hi', k, hk, hi⟩ := hi, refine ⟨_, add_mem hi' (mul_mem_right k _ hi1), _, mul_mem_mul hj hk, _⟩, rw [add_assoc, ← add_mul, h, one_mul, hi] end lemma sup_mul_eq_of_coprime_right (h : I ⊔ K = ⊤) : I ⊔ (J * K) = I ⊔ J := by { rw mul_comm, exact sup_mul_eq_of_coprime_left h } lemma mul_sup_eq_of_coprime_left (h : I ⊔ J = ⊤) : (I * K) ⊔ J = K ⊔ J := by { rw sup_comm at h, rw [sup_comm, sup_mul_eq_of_coprime_left h, sup_comm] } lemma mul_sup_eq_of_coprime_right (h : K ⊔ J = ⊤) : (I * K) ⊔ J = I ⊔ J := by { rw sup_comm at h, rw [sup_comm, sup_mul_eq_of_coprime_right h, sup_comm] } lemma sup_prod_eq_top {s : finset ι} {J : ι → ideal R} (h : ∀ i, i ∈ s → I ⊔ J i = ⊤) : I ⊔ ∏ i in s, J i = ⊤ := finset.prod_induction _ (λ J, I ⊔ J = ⊤) (λ J K hJ hK, (sup_mul_eq_of_coprime_left hJ).trans hK) (by rw [one_eq_top, sup_top_eq]) h lemma sup_infi_eq_top {s : finset ι} {J : ι → ideal R} (h : ∀ i, i ∈ s → I ⊔ J i = ⊤) : I ⊔ (⨅ i ∈ s, J i) = ⊤ := eq_top_iff.mpr $ le_of_eq_of_le (sup_prod_eq_top h).symm $ sup_le_sup_left (le_of_le_of_eq prod_le_inf $ finset.inf_eq_infi _ _) _ lemma prod_sup_eq_top {s : finset ι} {J : ι → ideal R} (h : ∀ i, i ∈ s → J i ⊔ I = ⊤) : (∏ i in s, J i) ⊔ I = ⊤ := sup_comm.trans (sup_prod_eq_top $ λ i hi, sup_comm.trans $ h i hi) lemma infi_sup_eq_top {s : finset ι} {J : ι → ideal R} (h : ∀ i, i ∈ s → J i ⊔ I = ⊤) : (⨅ i ∈ s, J i) ⊔ I = ⊤ := sup_comm.trans (sup_infi_eq_top $ λ i hi, sup_comm.trans $ h i hi) lemma sup_pow_eq_top {n : ℕ} (h : I ⊔ J = ⊤) : I ⊔ (J ^ n) = ⊤ := by { rw [← finset.card_range n, ← finset.prod_const], exact sup_prod_eq_top (λ _ _, h) } lemma pow_sup_eq_top {n : ℕ} (h : I ⊔ J = ⊤) : (I ^ n) ⊔ J = ⊤ := by { rw [← finset.card_range n, ← finset.prod_const], exact prod_sup_eq_top (λ _ _, h) } lemma pow_sup_pow_eq_top {m n : ℕ} (h : I ⊔ J = ⊤) : (I ^ m) ⊔ (J ^ n) = ⊤ := sup_pow_eq_top (pow_sup_eq_top h) variables (I) @[simp] theorem mul_bot : I * ⊥ = ⊥ := submodule.smul_bot I @[simp] theorem bot_mul : ⊥ * I = ⊥ := submodule.bot_smul I @[simp] theorem mul_top : I * ⊤ = I := ideal.mul_comm ⊤ I ▸ submodule.top_smul I @[simp] theorem top_mul : ⊤ * I = I := submodule.top_smul I variables {I} theorem mul_mono (hik : I ≤ K) (hjl : J ≤ L) : I * J ≤ K * L := submodule.smul_mono hik hjl theorem mul_mono_left (h : I ≤ J) : I * K ≤ J * K := submodule.smul_mono_left h theorem mul_mono_right (h : J ≤ K) : I * J ≤ I * K := submodule.smul_mono_right h variables (I J K) theorem mul_sup : I * (J ⊔ K) = I * J ⊔ I * K := submodule.smul_sup I J K theorem sup_mul : (I ⊔ J) * K = I * K ⊔ J * K := submodule.sup_smul I J K variables {I J K} lemma pow_le_pow {m n : ℕ} (h : m ≤ n) : I^n ≤ I^m := begin cases nat.exists_eq_add_of_le h with k hk, rw [hk, pow_add], exact le_trans (mul_le_inf) (inf_le_left) end lemma pow_le_self {n : ℕ} (hn : n ≠ 0) : I^n ≤ I := calc I^n ≤ I ^ 1 : pow_le_pow (nat.pos_of_ne_zero hn) ... = I : pow_one _ lemma pow_mono {I J : ideal R} (e : I ≤ J) (n : ℕ) : I ^ n ≤ J ^ n := begin induction n, { rw [pow_zero, pow_zero], exact rfl.le }, { rw [pow_succ, pow_succ], exact ideal.mul_mono e n_ih } end lemma mul_eq_bot {R : Type*} [comm_semiring R] [no_zero_divisors R] {I J : ideal R} : I * J = ⊥ ↔ I = ⊥ ∨ J = ⊥ := ⟨λ hij, or_iff_not_imp_left.mpr (λ I_ne_bot, J.eq_bot_iff.mpr (λ j hj, let ⟨i, hi, ne0⟩ := I.ne_bot_iff.mp I_ne_bot in or.resolve_left (mul_eq_zero.mp ((I * J).eq_bot_iff.mp hij _ (mul_mem_mul hi hj))) ne0)), λ h, by cases h; rw [← ideal.mul_bot, h, ideal.mul_comm]⟩ instance {R : Type*} [comm_semiring R] [no_zero_divisors R] : no_zero_divisors (ideal R) := { eq_zero_or_eq_zero_of_mul_eq_zero := λ I J, mul_eq_bot.1 } /-- A product of ideals in an integral domain is zero if and only if one of the terms is zero. -/ lemma prod_eq_bot {R : Type*} [comm_ring R] [is_domain R] {s : multiset (ideal R)} : s.prod = ⊥ ↔ ∃ I ∈ s, I = ⊥ := prod_zero_iff_exists_zero /-- The radical of an ideal `I` consists of the elements `r` such that `r^n ∈ I` for some `n`. -/ def radical (I : ideal R) : ideal R := { carrier := { r | ∃ n : ℕ, r ^ n ∈ I }, zero_mem' := ⟨1, (pow_one (0:R)).symm ▸ I.zero_mem⟩, add_mem' := λ x y ⟨m, hxmi⟩ ⟨n, hyni⟩, ⟨m + n, (add_pow x y (m + n)).symm ▸ I.sum_mem $ show ∀ c ∈ finset.range (nat.succ (m + n)), x ^ c * y ^ (m + n - c) * (nat.choose (m + n) c) ∈ I, from λ c hc, or.cases_on (le_total c m) (λ hcm, I.mul_mem_right _ $ I.mul_mem_left _ $ nat.add_comm n m ▸ (add_tsub_assoc_of_le hcm n).symm ▸ (pow_add y n (m-c)).symm ▸ I.mul_mem_right _ hyni) (λ hmc, I.mul_mem_right _ $ I.mul_mem_right _ $ add_tsub_cancel_of_le hmc ▸ (pow_add x m (c-m)).symm ▸ I.mul_mem_right _ hxmi)⟩, smul_mem' := λ r s ⟨n, hsni⟩, ⟨n, (mul_pow r s n).symm ▸ I.mul_mem_left (r^n) hsni⟩ } theorem le_radical : I ≤ radical I := λ r hri, ⟨1, (pow_one r).symm ▸ hri⟩ variables (R) theorem radical_top : (radical ⊤ : ideal R) = ⊤ := (eq_top_iff_one _).2 ⟨0, submodule.mem_top⟩ variables {R} theorem radical_mono (H : I ≤ J) : radical I ≤ radical J := λ r ⟨n, hrni⟩, ⟨n, H hrni⟩ variables (I) @[simp] theorem radical_idem : radical (radical I) = radical I := le_antisymm (λ r ⟨n, k, hrnki⟩, ⟨n * k, (pow_mul r n k).symm ▸ hrnki⟩) le_radical variables {I} theorem radical_le_radical_iff : radical I ≤ radical J ↔ I ≤ radical J := ⟨λ h, le_trans le_radical h, λ h, radical_idem J ▸ radical_mono h⟩ theorem radical_eq_top : radical I = ⊤ ↔ I = ⊤ := ⟨λ h, (eq_top_iff_one _).2 $ let ⟨n, hn⟩ := (eq_top_iff_one _).1 h in @one_pow R _ n ▸ hn, λ h, h.symm ▸ radical_top R⟩ theorem is_prime.radical (H : is_prime I) : radical I = I := le_antisymm (λ r ⟨n, hrni⟩, H.mem_of_pow_mem n hrni) le_radical variables (I J) theorem radical_sup : radical (I ⊔ J) = radical (radical I ⊔ radical J) := le_antisymm (radical_mono $ sup_le_sup le_radical le_radical) $ λ r ⟨n, hrnij⟩, let ⟨s, hs, t, ht, hst⟩ := submodule.mem_sup.1 hrnij in @radical_idem _ _ (I ⊔ J) ▸ ⟨n, hst ▸ ideal.add_mem _ (radical_mono le_sup_left hs) (radical_mono le_sup_right ht)⟩ theorem radical_inf : radical (I ⊓ J) = radical I ⊓ radical J := le_antisymm (le_inf (radical_mono inf_le_left) (radical_mono inf_le_right)) (λ r ⟨⟨m, hrm⟩, ⟨n, hrn⟩⟩, ⟨m + n, (pow_add r m n).symm ▸ I.mul_mem_right _ hrm, (pow_add r m n).symm ▸ J.mul_mem_left _ hrn⟩) theorem radical_mul : radical (I * J) = radical I ⊓ radical J := le_antisymm (radical_inf I J ▸ radical_mono $ @mul_le_inf _ _ I J) (λ r ⟨⟨m, hrm⟩, ⟨n, hrn⟩⟩, ⟨m + n, (pow_add r m n).symm ▸ mul_mem_mul hrm hrn⟩) variables {I J} theorem is_prime.radical_le_iff (hj : is_prime J) : radical I ≤ J ↔ I ≤ J := ⟨le_trans le_radical, λ hij r ⟨n, hrni⟩, hj.mem_of_pow_mem n $ hij hrni⟩ theorem radical_eq_Inf (I : ideal R) : radical I = Inf { J : ideal R | I ≤ J ∧ is_prime J } := le_antisymm (le_Inf $ λ J hJ, hJ.2.radical_le_iff.2 hJ.1) $ λ r hr, classical.by_contradiction $ λ hri, let ⟨m, (hrm : r ∉ radical m), him, hm⟩ := zorn_nonempty_partial_order₀ {K : ideal R | r ∉ radical K} (λ c hc hcc y hyc, ⟨Sup c, λ ⟨n, hrnc⟩, let ⟨y, hyc, hrny⟩ := (submodule.mem_Sup_of_directed ⟨y, hyc⟩ hcc.directed_on).1 hrnc in hc hyc ⟨n, hrny⟩, λ z, le_Sup⟩) I hri in have ∀ x ∉ m, r ∈ radical (m ⊔ span {x}) := λ x hxm, classical.by_contradiction $ λ hrmx, hxm $ hm (m ⊔ span {x}) hrmx le_sup_left ▸ (le_sup_right : _ ≤ m ⊔ span {x}) (subset_span $ set.mem_singleton _), have is_prime m, from ⟨by rintro rfl; rw radical_top at hrm; exact hrm trivial, λ x y hxym, or_iff_not_imp_left.2 $ λ hxm, classical.by_contradiction $ λ hym, let ⟨n, hrn⟩ := this _ hxm, ⟨p, hpm, q, hq, hpqrn⟩ := submodule.mem_sup.1 hrn, ⟨c, hcxq⟩ := mem_span_singleton'.1 hq in let ⟨k, hrk⟩ := this _ hym, ⟨f, hfm, g, hg, hfgrk⟩ := submodule.mem_sup.1 hrk, ⟨d, hdyg⟩ := mem_span_singleton'.1 hg in hrm ⟨n + k, by rw [pow_add, ← hpqrn, ← hcxq, ← hfgrk, ← hdyg, add_mul, mul_add (c*x), mul_assoc c x (d*y), mul_left_comm x, ← mul_assoc]; refine m.add_mem (m.mul_mem_right _ hpm) (m.add_mem (m.mul_mem_left _ hfm) (m.mul_mem_left _ hxym))⟩⟩, hrm $ this.radical.symm ▸ (Inf_le ⟨him, this⟩ : Inf {J : ideal R | I ≤ J ∧ is_prime J} ≤ m) hr @[simp] lemma radical_bot_of_is_domain {R : Type u} [comm_semiring R] [no_zero_divisors R] : radical (⊥ : ideal R) = ⊥ := eq_bot_iff.2 (λ x hx, hx.rec_on (λ n hn, pow_eq_zero hn)) instance : comm_semiring (ideal R) := submodule.comm_semiring variables (R) theorem top_pow (n : ℕ) : (⊤ ^ n : ideal R) = ⊤ := nat.rec_on n one_eq_top $ λ n ih, by rw [pow_succ, ih, top_mul] variables {R} variables (I) theorem radical_pow (n : ℕ) (H : n > 0) : radical (I^n) = radical I := nat.rec_on n (not.elim dec_trivial) (λ n ih H, or.cases_on (lt_or_eq_of_le $ nat.le_of_lt_succ H) (λ H, calc radical (I^(n+1)) = radical I ⊓ radical (I^n) : by { rw pow_succ, exact radical_mul _ _ } ... = radical I ⊓ radical I : by rw ih H ... = radical I : inf_idem) (λ H, H ▸ (pow_one I).symm ▸ rfl)) H theorem is_prime.mul_le {I J P : ideal R} (hp : is_prime P) : I * J ≤ P ↔ I ≤ P ∨ J ≤ P := ⟨λ h, or_iff_not_imp_left.2 $ λ hip j hj, let ⟨i, hi, hip⟩ := set.not_subset.1 hip in (hp.mem_or_mem $ h $ mul_mem_mul hi hj).resolve_left hip, λ h, or.cases_on h (le_trans $ le_trans mul_le_inf inf_le_left) (le_trans $ le_trans mul_le_inf inf_le_right)⟩ theorem is_prime.inf_le {I J P : ideal R} (hp : is_prime P) : I ⊓ J ≤ P ↔ I ≤ P ∨ J ≤ P := ⟨λ h, hp.mul_le.1 $ le_trans mul_le_inf h, λ h, or.cases_on h (le_trans inf_le_left) (le_trans inf_le_right)⟩ theorem is_prime.multiset_prod_le {s : multiset (ideal R)} {P : ideal R} (hp : is_prime P) (hne : s ≠ 0) : s.prod ≤ P ↔ ∃ I ∈ s, I ≤ P := suffices s.prod ≤ P → ∃ I ∈ s, I ≤ P, from ⟨this, λ ⟨i, his, hip⟩, le_trans multiset_prod_le_inf $ le_trans (multiset.inf_le his) hip⟩, begin classical, obtain ⟨b, hb⟩ : ∃ b, b ∈ s := multiset.exists_mem_of_ne_zero hne, obtain ⟨t, rfl⟩ : ∃ t, s = b ::ₘ t, from ⟨s.erase b, (multiset.cons_erase hb).symm⟩, refine t.induction_on _ _, { simp only [exists_prop, multiset.cons_zero, multiset.prod_singleton, multiset.mem_singleton, exists_eq_left, imp_self] }, intros a s ih h, rw [multiset.cons_swap, multiset.prod_cons, hp.mul_le] at h, rw multiset.cons_swap, cases h, { exact ⟨a, multiset.mem_cons_self a _, h⟩ }, obtain ⟨I, hI, ih⟩ : ∃ I ∈ b ::ₘ s, I ≤ P := ih h, exact ⟨I, multiset.mem_cons_of_mem hI, ih⟩ end theorem is_prime.multiset_prod_map_le {s : multiset ι} (f : ι → ideal R) {P : ideal R} (hp : is_prime P) (hne : s ≠ 0) : (s.map f).prod ≤ P ↔ ∃ i ∈ s, f i ≤ P := begin rw hp.multiset_prod_le (mt multiset.map_eq_zero.mp hne), simp_rw [exists_prop, multiset.mem_map, exists_exists_and_eq_and], end theorem is_prime.prod_le {s : finset ι} {f : ι → ideal R} {P : ideal R} (hp : is_prime P) (hne : s.nonempty) : s.prod f ≤ P ↔ ∃ i ∈ s, f i ≤ P := hp.multiset_prod_map_le f (mt finset.val_eq_zero.mp hne.ne_empty) theorem is_prime.inf_le' {s : finset ι} {f : ι → ideal R} {P : ideal R} (hp : is_prime P) (hsne: s.nonempty) : s.inf f ≤ P ↔ ∃ i ∈ s, f i ≤ P := ⟨λ h, (hp.prod_le hsne).1 $ le_trans prod_le_inf h, λ ⟨i, his, hip⟩, le_trans (finset.inf_le his) hip⟩ theorem subset_union {R : Type u} [ring R] {I J K : ideal R} : (I : set R) ⊆ J ∪ K ↔ I ≤ J ∨ I ≤ K := ⟨λ h, or_iff_not_imp_left.2 $ λ hij s hsi, let ⟨r, hri, hrj⟩ := set.not_subset.1 hij in classical.by_contradiction $ λ hsk, or.cases_on (h $ I.add_mem hri hsi) (λ hj, hrj $ add_sub_cancel r s ▸ J.sub_mem hj ((h hsi).resolve_right hsk)) (λ hk, hsk $ add_sub_cancel' r s ▸ K.sub_mem hk ((h hri).resolve_left hrj)), λ h, or.cases_on h (λ h, set.subset.trans h $ set.subset_union_left J K) (λ h, set.subset.trans h $ set.subset_union_right J K)⟩ theorem subset_union_prime' {R : Type u} [comm_ring R] {s : finset ι} {f : ι → ideal R} {a b : ι} (hp : ∀ i ∈ s, is_prime (f i)) {I : ideal R} : (I : set R) ⊆ f a ∪ f b ∪ (⋃ i ∈ (↑s : set ι), f i) ↔ I ≤ f a ∨ I ≤ f b ∨ ∃ i ∈ s, I ≤ f i := suffices (I : set R) ⊆ f a ∪ f b ∪ (⋃ i ∈ (↑s : set ι), f i) → I ≤ f a ∨ I ≤ f b ∨ ∃ i ∈ s, I ≤ f i, from ⟨this, λ h, or.cases_on h (λ h, set.subset.trans h $ set.subset.trans (set.subset_union_left _ _) (set.subset_union_left _ _)) $ λ h, or.cases_on h (λ h, set.subset.trans h $ set.subset.trans (set.subset_union_right _ _) (set.subset_union_left _ _)) $ λ ⟨i, his, hi⟩, by refine (set.subset.trans hi $ set.subset.trans _ $ set.subset_union_right _ _); exact set.subset_bUnion_of_mem (finset.mem_coe.2 his)⟩, begin generalize hn : s.card = n, intros h, unfreezingI { induction n with n ih generalizing a b s }, { clear hp, rw finset.card_eq_zero at hn, subst hn, rw [finset.coe_empty, set.bUnion_empty, set.union_empty, subset_union] at h, simpa only [exists_prop, finset.not_mem_empty, false_and, exists_false, or_false] }, classical, replace hn : ∃ (i : ι) (t : finset ι), i ∉ t ∧ insert i t = s ∧ t.card = n := finset.card_eq_succ.1 hn, unfreezingI { rcases hn with ⟨i, t, hit, rfl, hn⟩ }, replace hp : is_prime (f i) ∧ ∀ x ∈ t, is_prime (f x) := (t.forall_mem_insert _ _).1 hp, by_cases Ht : ∃ j ∈ t, f j ≤ f i, { obtain ⟨j, hjt, hfji⟩ : ∃ j ∈ t, f j ≤ f i := Ht, obtain ⟨u, hju, rfl⟩ : ∃ u, j ∉ u ∧ insert j u = t, { exact ⟨t.erase j, t.not_mem_erase j, finset.insert_erase hjt⟩ }, have hp' : ∀ k ∈ insert i u, is_prime (f k), { rw finset.forall_mem_insert at hp ⊢, exact ⟨hp.1, hp.2.2⟩ }, have hiu : i ∉ u := mt finset.mem_insert_of_mem hit, have hn' : (insert i u).card = n, { rwa finset.card_insert_of_not_mem at hn ⊢, exacts [hiu, hju] }, have h' : (I : set R) ⊆ f a ∪ f b ∪ (⋃ k ∈ (↑(insert i u) : set ι), f k), { rw finset.coe_insert at h ⊢, rw finset.coe_insert at h, simp only [set.bUnion_insert] at h ⊢, rw [← set.union_assoc ↑(f i)] at h, erw [set.union_eq_self_of_subset_right hfji] at h, exact h }, specialize @ih a b (insert i u) hp' hn' h', refine ih.imp id (or.imp id (exists_imp_exists $ λ k, _)), simp only [exists_prop], exact and.imp (λ hk, finset.insert_subset_insert i (finset.subset_insert j u) hk) id }, by_cases Ha : f a ≤ f i, { have h' : (I : set R) ⊆ f i ∪ f b ∪ (⋃ j ∈ (↑t : set ι), f j), { rw [finset.coe_insert, set.bUnion_insert, ← set.union_assoc, set.union_right_comm ↑(f a)] at h, erw [set.union_eq_self_of_subset_left Ha] at h, exact h }, specialize @ih i b t hp.2 hn h', right, rcases ih with ih | ih | ⟨k, hkt, ih⟩, { exact or.inr ⟨i, finset.mem_insert_self i t, ih⟩ }, { exact or.inl ih }, { exact or.inr ⟨k, finset.mem_insert_of_mem hkt, ih⟩ } }, by_cases Hb : f b ≤ f i, { have h' : (I : set R) ⊆ f a ∪ f i ∪ (⋃ j ∈ (↑t : set ι), f j), { rw [finset.coe_insert, set.bUnion_insert, ← set.union_assoc, set.union_assoc ↑(f a)] at h, erw [set.union_eq_self_of_subset_left Hb] at h, exact h }, specialize @ih a i t hp.2 hn h', rcases ih with ih | ih | ⟨k, hkt, ih⟩, { exact or.inl ih }, { exact or.inr (or.inr ⟨i, finset.mem_insert_self i t, ih⟩) }, { exact or.inr (or.inr ⟨k, finset.mem_insert_of_mem hkt, ih⟩) } }, by_cases Hi : I ≤ f i, { exact or.inr (or.inr ⟨i, finset.mem_insert_self i t, Hi⟩) }, have : ¬I ⊓ f a ⊓ f b ⊓ t.inf f ≤ f i, { rcases t.eq_empty_or_nonempty with (rfl | hsne), { rw [finset.inf_empty, inf_top_eq, hp.1.inf_le, hp.1.inf_le, not_or_distrib, not_or_distrib], exact ⟨⟨Hi, Ha⟩, Hb⟩ }, simp only [hp.1.inf_le, hp.1.inf_le' hsne, not_or_distrib], exact ⟨⟨⟨Hi, Ha⟩, Hb⟩, Ht⟩ }, rcases set.not_subset.1 this with ⟨r, ⟨⟨⟨hrI, hra⟩, hrb⟩, hr⟩, hri⟩, by_cases HI : (I : set R) ⊆ f a ∪ f b ∪ ⋃ j ∈ (↑t : set ι), f j, { specialize ih hp.2 hn HI, rcases ih with ih | ih | ⟨k, hkt, ih⟩, { left, exact ih }, { right, left, exact ih }, { right, right, exact ⟨k, finset.mem_insert_of_mem hkt, ih⟩ } }, exfalso, rcases set.not_subset.1 HI with ⟨s, hsI, hs⟩, rw [finset.coe_insert, set.bUnion_insert] at h, have hsi : s ∈ f i := ((h hsI).resolve_left (mt or.inl hs)).resolve_right (mt or.inr hs), rcases h (I.add_mem hrI hsI) with ⟨ha | hb⟩ | hi | ht, { exact hs (or.inl $ or.inl $ add_sub_cancel' r s ▸ (f a).sub_mem ha hra) }, { exact hs (or.inl $ or.inr $ add_sub_cancel' r s ▸ (f b).sub_mem hb hrb) }, { exact hri (add_sub_cancel r s ▸ (f i).sub_mem hi hsi) }, { rw set.mem_Union₂ at ht, rcases ht with ⟨j, hjt, hj⟩, simp only [finset.inf_eq_infi, set_like.mem_coe, submodule.mem_infi] at hr, exact hs (or.inr $ set.mem_bUnion hjt $ add_sub_cancel' r s ▸ (f j).sub_mem hj $ hr j hjt) } end /-- Prime avoidance. Atiyah-Macdonald 1.11, Eisenbud 3.3, Stacks 00DS, Matsumura Ex.1.6. -/ theorem subset_union_prime {R : Type u} [comm_ring R] {s : finset ι} {f : ι → ideal R} (a b : ι) (hp : ∀ i ∈ s, i ≠ a → i ≠ b → is_prime (f i)) {I : ideal R} : (I : set R) ⊆ (⋃ i ∈ (↑s : set ι), f i) ↔ ∃ i ∈ s, I ≤ f i := suffices (I : set R) ⊆ (⋃ i ∈ (↑s : set ι), f i) → ∃ i, i ∈ s ∧ I ≤ f i, from ⟨λ h, bex_def.2 $ this h, λ ⟨i, his, hi⟩, set.subset.trans hi $ set.subset_bUnion_of_mem $ show i ∈ (↑s : set ι), from his⟩, assume h : (I : set R) ⊆ (⋃ i ∈ (↑s : set ι), f i), begin classical, by_cases has : a ∈ s, { unfreezingI { obtain ⟨t, hat, rfl⟩ : ∃ t, a ∉ t ∧ insert a t = s := ⟨s.erase a, finset.not_mem_erase a s, finset.insert_erase has⟩ }, by_cases hbt : b ∈ t, { unfreezingI { obtain ⟨u, hbu, rfl⟩ : ∃ u, b ∉ u ∧ insert b u = t := ⟨t.erase b, finset.not_mem_erase b t, finset.insert_erase hbt⟩ }, have hp' : ∀ i ∈ u, is_prime (f i), { intros i hiu, refine hp i (finset.mem_insert_of_mem (finset.mem_insert_of_mem hiu)) _ _; unfreezingI { rintro rfl }; solve_by_elim only [finset.mem_insert_of_mem, *], }, rw [finset.coe_insert, finset.coe_insert, set.bUnion_insert, set.bUnion_insert, ← set.union_assoc, subset_union_prime' hp', bex_def] at h, rwa [finset.exists_mem_insert, finset.exists_mem_insert] }, { have hp' : ∀ j ∈ t, is_prime (f j), { intros j hj, refine hp j (finset.mem_insert_of_mem hj) _ _; unfreezingI { rintro rfl }; solve_by_elim only [finset.mem_insert_of_mem, *], }, rw [finset.coe_insert, set.bUnion_insert, ← set.union_self (f a : set R), subset_union_prime' hp', ← or_assoc, or_self, bex_def] at h, rwa finset.exists_mem_insert } }, { by_cases hbs : b ∈ s, { unfreezingI { obtain ⟨t, hbt, rfl⟩ : ∃ t, b ∉ t ∧ insert b t = s := ⟨s.erase b, finset.not_mem_erase b s, finset.insert_erase hbs⟩ }, have hp' : ∀ j ∈ t, is_prime (f j), { intros j hj, refine hp j (finset.mem_insert_of_mem hj) _ _; unfreezingI { rintro rfl }; solve_by_elim only [finset.mem_insert_of_mem, *], }, rw [finset.coe_insert, set.bUnion_insert, ← set.union_self (f b : set R), subset_union_prime' hp', ← or_assoc, or_self, bex_def] at h, rwa finset.exists_mem_insert }, cases s.eq_empty_or_nonempty with hse hsne, { substI hse, rw [finset.coe_empty, set.bUnion_empty, set.subset_empty_iff] at h, have : (I : set R) ≠ ∅ := set.nonempty.ne_empty (set.nonempty_of_mem I.zero_mem), exact absurd h this }, { cases hsne.bex with i his, unfreezingI { obtain ⟨t, hit, rfl⟩ : ∃ t, i ∉ t ∧ insert i t = s := ⟨s.erase i, finset.not_mem_erase i s, finset.insert_erase his⟩ }, have hp' : ∀ j ∈ t, is_prime (f j), { intros j hj, refine hp j (finset.mem_insert_of_mem hj) _ _; unfreezingI { rintro rfl }; solve_by_elim only [finset.mem_insert_of_mem, *], }, rw [finset.coe_insert, set.bUnion_insert, ← set.union_self (f i : set R), subset_union_prime' hp', ← or_assoc, or_self, bex_def] at h, rwa finset.exists_mem_insert } } end section dvd /-- If `I` divides `J`, then `I` contains `J`. In a Dedekind domain, to divide and contain are equivalent, see `ideal.dvd_iff_le`. -/ lemma le_of_dvd {I J : ideal R} : I ∣ J → J ≤ I | ⟨K, h⟩ := h.symm ▸ le_trans mul_le_inf inf_le_left lemma is_unit_iff {I : ideal R} : is_unit I ↔ I = ⊤ := is_unit_iff_dvd_one.trans ((@one_eq_top R _).symm ▸ ⟨λ h, eq_top_iff.mpr (ideal.le_of_dvd h), λ h, ⟨⊤, by rw [mul_top, h]⟩⟩) instance unique_units : unique ((ideal R)ˣ) := { default := 1, uniq := λ u, units.ext (show (u : ideal R) = 1, by rw [is_unit_iff.mp u.is_unit, one_eq_top]) } end dvd end mul_and_radical section map_and_comap variables {R : Type u} {S : Type v} section semiring variables {F : Type*} [semiring R] [semiring S] variables [rc : ring_hom_class F R S] variables (f : F) variables {I J : ideal R} {K L : ideal S} include rc /-- `I.map f` is the span of the image of the ideal `I` under `f`, which may be bigger than the image itself. -/ def map (I : ideal R) : ideal S := span (f '' I) /-- `I.comap f` is the preimage of `I` under `f`. -/ def comap (I : ideal S) : ideal R := { carrier := f ⁻¹' I, add_mem' := λ x y hx hy, by simp only [set.mem_preimage, set_like.mem_coe, map_add, add_mem hx hy] at *, zero_mem' := by simp only [set.mem_preimage, map_zero, set_like.mem_coe, submodule.zero_mem], smul_mem' := λ c x hx, by { simp only [smul_eq_mul, set.mem_preimage, map_mul, set_like.mem_coe] at *, exact mul_mem_left I _ hx } } variables {f} theorem map_mono (h : I ≤ J) : map f I ≤ map f J := span_mono $ set.image_subset _ h theorem mem_map_of_mem (f : F) {I : ideal R} {x : R} (h : x ∈ I) : f x ∈ map f I := subset_span ⟨x, h, rfl⟩ lemma apply_coe_mem_map (f : F) (I : ideal R) (x : I) : f x ∈ I.map f := mem_map_of_mem f x.prop theorem map_le_iff_le_comap : map f I ≤ K ↔ I ≤ comap f K := span_le.trans set.image_subset_iff @[simp] theorem mem_comap {x} : x ∈ comap f K ↔ f x ∈ K := iff.rfl theorem comap_mono (h : K ≤ L) : comap f K ≤ comap f L := set.preimage_mono (λ x hx, h hx) variables (f) theorem comap_ne_top (hK : K ≠ ⊤) : comap f K ≠ ⊤ := (ne_top_iff_one _).2 $ by rw [mem_comap, map_one]; exact (ne_top_iff_one _).1 hK variables {G : Type*} [rcg : ring_hom_class G S R] include rcg lemma map_le_comap_of_inv_on (g : G) (I : ideal R) (hf : set.left_inv_on g f I) : I.map f ≤ I.comap g := begin refine ideal.span_le.2 _, rintros x ⟨x, hx, rfl⟩, rw [set_like.mem_coe, mem_comap, hf hx], exact hx, end lemma comap_le_map_of_inv_on (g : G) (I : ideal S) (hf : set.left_inv_on g f (f ⁻¹' I)) : I.comap f ≤ I.map g := λ x (hx : f x ∈ I), hf hx ▸ ideal.mem_map_of_mem g hx /-- The `ideal` version of `set.image_subset_preimage_of_inverse`. -/ lemma map_le_comap_of_inverse (g : G) (I : ideal R) (h : function.left_inverse g f) : I.map f ≤ I.comap g := map_le_comap_of_inv_on _ _ _ $ h.left_inv_on _ /-- The `ideal` version of `set.preimage_subset_image_of_inverse`. -/ lemma comap_le_map_of_inverse (g : G) (I : ideal S) (h : function.left_inverse g f) : I.comap f ≤ I.map g := comap_le_map_of_inv_on _ _ _ $ h.left_inv_on _ omit rcg instance is_prime.comap [hK : K.is_prime] : (comap f K).is_prime := ⟨comap_ne_top _ hK.1, λ x y, by simp only [mem_comap, map_mul]; apply hK.2⟩ variables (I J K L) theorem map_top : map f ⊤ = ⊤ := (eq_top_iff_one _).2 $ subset_span ⟨1, trivial, map_one f⟩ variable (f) lemma gc_map_comap : galois_connection (ideal.map f) (ideal.comap f) := λ I J, ideal.map_le_iff_le_comap omit rc @[simp] lemma comap_id : I.comap (ring_hom.id R) = I := ideal.ext $ λ _, iff.rfl @[simp] lemma map_id : I.map (ring_hom.id R) = I := (gc_map_comap (ring_hom.id R)).l_unique galois_connection.id comap_id lemma comap_comap {T : Type*} [semiring T] {I : ideal T} (f : R →+* S) (g : S →+* T) : (I.comap g).comap f = I.comap (g.comp f) := rfl lemma map_map {T : Type*} [semiring T] {I : ideal R} (f : R →+* S) (g : S →+* T) : (I.map f).map g = I.map (g.comp f) := ((gc_map_comap f).compose (gc_map_comap g)).l_unique (gc_map_comap (g.comp f)) (λ _, comap_comap _ _) include rc lemma map_span (f : F) (s : set R) : map f (span s) = span (f '' s) := symm $ submodule.span_eq_of_le _ (λ y ⟨x, hy, x_eq⟩, x_eq ▸ mem_map_of_mem f (subset_span hy)) (map_le_iff_le_comap.2 $ span_le.2 $ set.image_subset_iff.1 subset_span) variables {f I J K L} lemma map_le_of_le_comap : I ≤ K.comap f → I.map f ≤ K := (gc_map_comap f).l_le lemma le_comap_of_map_le : I.map f ≤ K → I ≤ K.comap f := (gc_map_comap f).le_u lemma le_comap_map : I ≤ (I.map f).comap f := (gc_map_comap f).le_u_l _ lemma map_comap_le : (K.comap f).map f ≤ K := (gc_map_comap f).l_u_le _ @[simp] lemma comap_top : (⊤ : ideal S).comap f = ⊤ := (gc_map_comap f).u_top @[simp] lemma comap_eq_top_iff {I : ideal S} : I.comap f = ⊤ ↔ I = ⊤ := ⟨ λ h, I.eq_top_iff_one.mpr (map_one f ▸ mem_comap.mp ((I.comap f).eq_top_iff_one.mp h)), λ h, by rw [h, comap_top] ⟩ @[simp] lemma map_bot : (⊥ : ideal R).map f = ⊥ := (gc_map_comap f).l_bot variables (f I J K L) @[simp] lemma map_comap_map : ((I.map f).comap f).map f = I.map f := (gc_map_comap f).l_u_l_eq_l I @[simp] lemma comap_map_comap : ((K.comap f).map f).comap f = K.comap f := (gc_map_comap f).u_l_u_eq_u K lemma map_sup : (I ⊔ J).map f = I.map f ⊔ J.map f := (gc_map_comap f : galois_connection (map f) (comap f)).l_sup theorem comap_inf : comap f (K ⊓ L) = comap f K ⊓ comap f L := rfl variables {ι : Sort*} lemma map_supr (K : ι → ideal R) : (supr K).map f = ⨆ i, (K i).map f := (gc_map_comap f : galois_connection (map f) (comap f)).l_supr lemma comap_infi (K : ι → ideal S) : (infi K).comap f = ⨅ i, (K i).comap f := (gc_map_comap f : galois_connection (map f) (comap f)).u_infi lemma map_Sup (s : set (ideal R)): (Sup s).map f = ⨆ I ∈ s, (I : ideal R).map f := (gc_map_comap f : galois_connection (map f) (comap f)).l_Sup lemma comap_Inf (s : set (ideal S)): (Inf s).comap f = ⨅ I ∈ s, (I : ideal S).comap f := (gc_map_comap f : galois_connection (map f) (comap f)).u_Inf lemma comap_Inf' (s : set (ideal S)) : (Inf s).comap f = ⨅ I ∈ (comap f '' s), I := trans (comap_Inf f s) (by rw infi_image) theorem comap_is_prime [H : is_prime K] : is_prime (comap f K) := ⟨comap_ne_top f H.ne_top, λ x y h, H.mem_or_mem $ by rwa [mem_comap, map_mul] at h⟩ variables {I J K L} theorem map_inf_le : map f (I ⊓ J) ≤ map f I ⊓ map f J := (gc_map_comap f : galois_connection (map f) (comap f)).monotone_l.map_inf_le _ _ theorem le_comap_sup : comap f K ⊔ comap f L ≤ comap f (K ⊔ L) := (gc_map_comap f : galois_connection (map f) (comap f)).monotone_u.le_map_sup _ _ omit rc @[simp] lemma smul_top_eq_map {R S : Type*} [comm_semiring R] [comm_semiring S] [algebra R S] (I : ideal R) : I • (⊤ : submodule R S) = (I.map (algebra_map R S)).restrict_scalars R := begin refine le_antisymm (submodule.smul_le.mpr (λ r hr y _, _) ) (λ x hx, submodule.span_induction hx _ _ _ _), { rw algebra.smul_def, exact mul_mem_right _ _ (mem_map_of_mem _ hr) }, { rintros _ ⟨x, hx, rfl⟩, rw [← mul_one (algebra_map R S x), ← algebra.smul_def], exact submodule.smul_mem_smul hx submodule.mem_top }, { exact submodule.zero_mem _ }, { intros x y, exact submodule.add_mem _ }, intros a x hx, refine submodule.smul_induction_on hx _ _, { intros r hr s hs, rw smul_comm, exact submodule.smul_mem_smul hr submodule.mem_top }, { intros x y hx hy, rw smul_add, exact submodule.add_mem _ hx hy }, end @[simp] lemma coe_restrict_scalars {R S : Type*} [comm_semiring R] [semiring S] [algebra R S] (I : ideal S) : ((I.restrict_scalars R) : set S) = ↑I := rfl /-- The smallest `S`-submodule that contains all `x ∈ I * y ∈ J` is also the smallest `R`-submodule that does so. -/ @[simp] lemma restrict_scalars_mul {R S : Type*} [comm_semiring R] [comm_semiring S] [algebra R S] (I J : ideal S) : (I * J).restrict_scalars R = I.restrict_scalars R * J.restrict_scalars R := le_antisymm (λ x hx, submodule.mul_induction_on hx (λ x hx y hy, submodule.mul_mem_mul hx hy) (λ x y, submodule.add_mem _)) (submodule.mul_le.mpr (λ x hx y hy, ideal.mul_mem_mul hx hy)) section surjective variables (hf : function.surjective f) include hf open function theorem map_comap_of_surjective (I : ideal S) : map f (comap f I) = I := le_antisymm (map_le_iff_le_comap.2 le_rfl) (λ s hsi, let ⟨r, hfrs⟩ := hf s in hfrs ▸ (mem_map_of_mem f $ show f r ∈ I, from hfrs.symm ▸ hsi)) /-- `map` and `comap` are adjoint, and the composition `map f ∘ comap f` is the identity -/ def gi_map_comap : galois_insertion (map f) (comap f) := galois_insertion.monotone_intro ((gc_map_comap f).monotone_u) ((gc_map_comap f).monotone_l) (λ _, le_comap_map) (map_comap_of_surjective _ hf) lemma map_surjective_of_surjective : surjective (map f) := (gi_map_comap f hf).l_surjective lemma comap_injective_of_surjective : injective (comap f) := (gi_map_comap f hf).u_injective lemma map_sup_comap_of_surjective (I J : ideal S) : (I.comap f ⊔ J.comap f).map f = I ⊔ J := (gi_map_comap f hf).l_sup_u _ _ lemma map_supr_comap_of_surjective (K : ι → ideal S) : (⨆i, (K i).comap f).map f = supr K := (gi_map_comap f hf).l_supr_u _ lemma map_inf_comap_of_surjective (I J : ideal S) : (I.comap f ⊓ J.comap f).map f = I ⊓ J := (gi_map_comap f hf).l_inf_u _ _ lemma map_infi_comap_of_surjective (K : ι → ideal S) : (⨅i, (K i).comap f).map f = infi K := (gi_map_comap f hf).l_infi_u _ theorem mem_image_of_mem_map_of_surjective {I : ideal R} {y} (H : y ∈ map f I) : y ∈ f '' I := submodule.span_induction H (λ _, id) ⟨0, I.zero_mem, map_zero f⟩ (λ y1 y2 ⟨x1, hx1i, hxy1⟩ ⟨x2, hx2i, hxy2⟩, ⟨x1 + x2, I.add_mem hx1i hx2i, hxy1 ▸ hxy2 ▸ map_add f _ _⟩) (λ c y ⟨x, hxi, hxy⟩, let ⟨d, hdc⟩ := hf c in ⟨d * x, I.mul_mem_left _ hxi, hdc ▸ hxy ▸ map_mul f _ _⟩) lemma mem_map_iff_of_surjective {I : ideal R} {y} : y ∈ map f I ↔ ∃ x, x ∈ I ∧ f x = y := ⟨λ h, (set.mem_image _ _ _).2 (mem_image_of_mem_map_of_surjective f hf h), λ ⟨x, hx⟩, hx.right ▸ (mem_map_of_mem f hx.left)⟩ lemma le_map_of_comap_le_of_surjective : comap f K ≤ I → K ≤ map f I := λ h, (map_comap_of_surjective f hf K) ▸ map_mono h end surjective section injective variables (hf : function.injective f) include hf lemma comap_bot_le_of_injective : comap f ⊥ ≤ I := begin refine le_trans (λ x hx, _) bot_le, rw [mem_comap, submodule.mem_bot, ← map_zero f] at hx, exact eq.symm (hf hx) ▸ (submodule.zero_mem ⊥) end end injective end semiring section ring variables {F : Type*} [ring R] [ring S] variables [ring_hom_class F R S] (f : F) {I : ideal R} section surjective variables (hf : function.surjective f) include hf theorem comap_map_of_surjective (I : ideal R) : comap f (map f I) = I ⊔ comap f ⊥ := le_antisymm (assume r h, let ⟨s, hsi, hfsr⟩ := mem_image_of_mem_map_of_surjective f hf h in submodule.mem_sup.2 ⟨s, hsi, r - s, (submodule.mem_bot S).2 $ by rw [map_sub, hfsr, sub_self], add_sub_cancel'_right s r⟩) (sup_le (map_le_iff_le_comap.1 le_rfl) (comap_mono bot_le)) /-- Correspondence theorem -/ def rel_iso_of_surjective : ideal S ≃o { p : ideal R // comap f ⊥ ≤ p } := { to_fun := λ J, ⟨comap f J, comap_mono bot_le⟩, inv_fun := λ I, map f I.1, left_inv := λ J, map_comap_of_surjective f hf J, right_inv := λ I, subtype.eq $ show comap f (map f I.1) = I.1, from (comap_map_of_surjective f hf I).symm ▸ le_antisymm (sup_le le_rfl I.2) le_sup_left, map_rel_iff' := λ I1 I2, ⟨λ H, map_comap_of_surjective f hf I1 ▸ map_comap_of_surjective f hf I2 ▸ map_mono H, comap_mono⟩ } /-- The map on ideals induced by a surjective map preserves inclusion. -/ def order_embedding_of_surjective : ideal S ↪o ideal R := (rel_iso_of_surjective f hf).to_rel_embedding.trans (subtype.rel_embedding _ _) theorem map_eq_top_or_is_maximal_of_surjective {I : ideal R} (H : is_maximal I) : (map f I) = ⊤ ∨ is_maximal (map f I) := begin refine or_iff_not_imp_left.2 (λ ne_top, ⟨⟨λ h, ne_top h, λ J hJ, _⟩⟩), { refine (rel_iso_of_surjective f hf).injective (subtype.ext_iff.2 (eq.trans (H.1.2 (comap f J) (lt_of_le_of_ne _ _)) comap_top.symm)), { exact (map_le_iff_le_comap).1 (le_of_lt hJ) }, { exact λ h, hJ.right (le_map_of_comap_le_of_surjective f hf (le_of_eq h.symm)) } } end theorem comap_is_maximal_of_surjective {K : ideal S} [H : is_maximal K] : is_maximal (comap f K) := begin refine ⟨⟨comap_ne_top _ H.1.1, λ J hJ, _⟩⟩, suffices : map f J = ⊤, { replace this := congr_arg (comap f) this, rw [comap_top, comap_map_of_surjective _ hf, eq_top_iff] at this, rw eq_top_iff, exact le_trans this (sup_le (le_of_eq rfl) (le_trans (comap_mono (bot_le)) (le_of_lt hJ))) }, refine H.1.2 (map f J) (lt_of_le_of_ne (le_map_of_comap_le_of_surjective _ hf (le_of_lt hJ)) (λ h, ne_of_lt hJ (trans (congr_arg (comap f) h) _))), rw [comap_map_of_surjective _ hf, sup_eq_left], exact le_trans (comap_mono bot_le) (le_of_lt hJ) end theorem comap_le_comap_iff_of_surjective (I J : ideal S) : comap f I ≤ comap f J ↔ I ≤ J := ⟨λ h, (map_comap_of_surjective f hf I).symm.le.trans (map_le_of_le_comap h), λ h, le_comap_of_map_le ((map_comap_of_surjective f hf I).le.trans h)⟩ end surjective /-- If `f : R ≃+* S` is a ring isomorphism and `I : ideal R`, then `map f (map f.symm) = I`. -/ @[simp] lemma map_of_equiv (I : ideal R) (f : R ≃+* S) : (I.map (f : R →+* S)).map (f.symm : S →+* R) = I := by simp [← ring_equiv.to_ring_hom_eq_coe, map_map] /-- If `f : R ≃+* S` is a ring isomorphism and `I : ideal R`, then `comap f.symm (comap f) = I`. -/ @[simp] lemma comap_of_equiv (I : ideal R) (f : R ≃+* S) : (I.comap (f.symm : S →+* R)).comap (f : R →+* S) = I := by simp [← ring_equiv.to_ring_hom_eq_coe, comap_comap] /-- If `f : R ≃+* S` is a ring isomorphism and `I : ideal R`, then `map f I = comap f.symm I`. -/ lemma map_comap_of_equiv (I : ideal R) (f : R ≃+* S) : I.map (f : R →+* S) = I.comap f.symm := le_antisymm (le_comap_of_map_le (map_of_equiv I f).le) (le_map_of_comap_le_of_surjective _ f.surjective (comap_of_equiv I f).le) section bijective variables (hf : function.bijective f) include hf /-- Special case of the correspondence theorem for isomorphic rings -/ def rel_iso_of_bijective : ideal S ≃o ideal R := { to_fun := comap f, inv_fun := map f, left_inv := (rel_iso_of_surjective f hf.right).left_inv, right_inv := λ J, subtype.ext_iff.1 ((rel_iso_of_surjective f hf.right).right_inv ⟨J, comap_bot_le_of_injective f hf.left⟩), map_rel_iff' := λ _ _, (rel_iso_of_surjective f hf.right).map_rel_iff' } lemma comap_le_iff_le_map {I : ideal R} {K : ideal S} : comap f K ≤ I ↔ K ≤ map f I := ⟨λ h, le_map_of_comap_le_of_surjective f hf.right h, λ h, ((rel_iso_of_bijective f hf).right_inv I) ▸ comap_mono h⟩ theorem map.is_maximal {I : ideal R} (H : is_maximal I) : is_maximal (map f I) := by refine or_iff_not_imp_left.1 (map_eq_top_or_is_maximal_of_surjective f hf.right H) (λ h, H.1.1 _); calc I = comap f (map f I) : ((rel_iso_of_bijective f hf).right_inv I).symm ... = comap f ⊤ : by rw h ... = ⊤ : by rw comap_top end bijective lemma ring_equiv.bot_maximal_iff (e : R ≃+* S) : (⊥ : ideal R).is_maximal ↔ (⊥ : ideal S).is_maximal := ⟨λ h, (@map_bot _ _ _ _ _ _ e.to_ring_hom) ▸ map.is_maximal e.to_ring_hom e.bijective h, λ h, (@map_bot _ _ _ _ _ _ e.symm.to_ring_hom) ▸ map.is_maximal e.symm.to_ring_hom e.symm.bijective h⟩ end ring section comm_ring variables {F : Type*} [comm_ring R] [comm_ring S] variables [rc : ring_hom_class F R S] variables (f : F) variables {I J : ideal R} {K L : ideal S} variables (I J K L) include rc theorem map_mul : map f (I * J) = map f I * map f J := le_antisymm (map_le_iff_le_comap.2 $ mul_le.2 $ λ r hri s hsj, show f (r * s) ∈ _, by rw map_mul; exact mul_mem_mul (mem_map_of_mem f hri) (mem_map_of_mem f hsj)) (trans_rel_right _ (span_mul_span _ _) $ span_le.2 $ set.Union₂_subset $ λ i ⟨r, hri, hfri⟩, set.Union₂_subset $ λ j ⟨s, hsj, hfsj⟩, set.singleton_subset_iff.2 $ hfri ▸ hfsj ▸ by rw [← map_mul]; exact mem_map_of_mem f (mul_mem_mul hri hsj)) /-- The pushforward `ideal.map` as a monoid-with-zero homomorphism. -/ @[simps] def map_hom : ideal R →*₀ ideal S := { to_fun := map f, map_mul' := λ I J, ideal.map_mul f I J, map_one' := by convert ideal.map_top f; exact one_eq_top, map_zero' := ideal.map_bot } protected theorem map_pow (n : ℕ) : map f (I^n) = (map f I)^n := map_pow (map_hom f) I n theorem comap_radical : comap f (radical K) = radical (comap f K) := le_antisymm (λ r ⟨n, hfrnk⟩, ⟨n, show f (r ^ n) ∈ K, from (map_pow f r n).symm ▸ hfrnk⟩) (λ r ⟨n, hfrnk⟩, ⟨n, map_pow f r n ▸ hfrnk⟩) omit rc @[simp] lemma map_quotient_self : map (quotient.mk I) I = ⊥ := eq_bot_iff.2 $ ideal.map_le_iff_le_comap.2 $ λ x hx, (submodule.mem_bot (R ⧸ I)).2 $ ideal.quotient.eq_zero_iff_mem.2 hx variables {I J K L} include rc theorem map_radical_le : map f (radical I) ≤ radical (map f I) := map_le_iff_le_comap.2 $ λ r ⟨n, hrni⟩, ⟨n, map_pow f r n ▸ mem_map_of_mem f hrni⟩ theorem le_comap_mul : comap f K * comap f L ≤ comap f (K * L) := map_le_iff_le_comap.1 $ (map_mul f (comap f K) (comap f L)).symm ▸ mul_mono (map_le_iff_le_comap.2 $ le_rfl) (map_le_iff_le_comap.2 $ le_rfl) lemma le_comap_pow (n : ℕ) : (K.comap f) ^ n ≤ (K ^ n).comap f := begin induction n, { rw [pow_zero, pow_zero, ideal.one_eq_top, ideal.one_eq_top], exact rfl.le }, { rw [pow_succ, pow_succ], exact (ideal.mul_mono_right n_ih).trans (ideal.le_comap_mul f) } end omit rc end comm_ring end map_and_comap section is_primary variables {R : Type u} [comm_semiring R] /-- A proper ideal `I` is primary iff `xy ∈ I` implies `x ∈ I` or `y ∈ radical I`. -/ def is_primary (I : ideal R) : Prop := I ≠ ⊤ ∧ ∀ {x y : R}, x * y ∈ I → x ∈ I ∨ y ∈ radical I theorem is_prime.is_primary {I : ideal R} (hi : is_prime I) : is_primary I := ⟨hi.1, λ x y hxy, (hi.mem_or_mem hxy).imp id $ λ hyi, le_radical hyi⟩ theorem mem_radical_of_pow_mem {I : ideal R} {x : R} {m : ℕ} (hx : x ^ m ∈ radical I) : x ∈ radical I := radical_idem I ▸ ⟨m, hx⟩ theorem is_prime_radical {I : ideal R} (hi : is_primary I) : is_prime (radical I) := ⟨mt radical_eq_top.1 hi.1, λ x y ⟨m, hxy⟩, begin rw mul_pow at hxy, cases hi.2 hxy, { exact or.inl ⟨m, h⟩ }, { exact or.inr (mem_radical_of_pow_mem h) } end⟩ theorem is_primary_inf {I J : ideal R} (hi : is_primary I) (hj : is_primary J) (hij : radical I = radical J) : is_primary (I ⊓ J) := ⟨ne_of_lt $ lt_of_le_of_lt inf_le_left (lt_top_iff_ne_top.2 hi.1), λ x y ⟨hxyi, hxyj⟩, begin rw [radical_inf, hij, inf_idem], cases hi.2 hxyi with hxi hyi, cases hj.2 hxyj with hxj hyj, { exact or.inl ⟨hxi, hxj⟩ }, { exact or.inr hyj }, { rw hij at hyi, exact or.inr hyi } end⟩ end is_primary section total variables (ι : Type*) variables (M : Type*) [add_comm_group M] {R : Type*} [comm_ring R] [module R M] (I : ideal R) variables (v : ι → M) (hv : submodule.span R (set.range v) = ⊤) open_locale big_operators /-- A variant of `finsupp.total` that takes in vectors valued in `I`. -/ noncomputable def finsupp_total : (ι →₀ I) →ₗ[R] M := (finsupp.total ι M R v).comp (finsupp.map_range.linear_map I.subtype) variables {ι M v} lemma finsupp_total_apply (f : ι →₀ I) : finsupp_total ι M I v f = f.sum (λ i x, (x : R) • v i) := begin dsimp [finsupp_total], rw [finsupp.total_apply, finsupp.sum_map_range_index], exact λ _, zero_smul _ _ end lemma finsupp_total_apply_eq_of_fintype [fintype ι] (f : ι →₀ I) : finsupp_total ι M I v f = ∑ i, (f i : R) • v i := by { rw [finsupp_total_apply, finsupp.sum_fintype], exact λ _, zero_smul _ _ } lemma range_finsupp_total : (finsupp_total ι M I v).range = I • (submodule.span R (set.range v)) := begin ext, rw submodule.mem_ideal_smul_span_iff_exists_sum, refine ⟨λ ⟨f, h⟩, ⟨finsupp.map_range.linear_map I.subtype f, λ i, (f i).2, h⟩, _⟩, rintro ⟨a, ha, rfl⟩, classical, refine ⟨a.map_range (λ r, if h : r ∈ I then ⟨r, h⟩ else 0) (by split_ifs; refl), _⟩, rw [finsupp_total_apply, finsupp.sum_map_range_index], { apply finsupp.sum_congr, intros i _, rw dif_pos (ha i), refl }, { exact λ _, zero_smul _ _ }, end end total end ideal lemma associates.mk_ne_zero' {R : Type*} [comm_semiring R] {r : R} : (associates.mk (ideal.span {r} : ideal R)) ≠ 0 ↔ (r ≠ 0):= by rw [associates.mk_ne_zero, ideal.zero_eq_bot, ne.def, ideal.span_singleton_eq_bot] namespace ring_hom variables {R : Type u} {S : Type v} {T : Type v} section semiring variables {F : Type*} {G : Type*} [semiring R] [semiring S] [semiring T] variables [rcf : ring_hom_class F R S] [rcg : ring_hom_class G T S] (f : F) (g : G) include rcf /-- Kernel of a ring homomorphism as an ideal of the domain. -/ def ker : ideal R := ideal.comap f ⊥ /-- An element is in the kernel if and only if it maps to zero.-/ lemma mem_ker {r} : r ∈ ker f ↔ f r = 0 := by rw [ker, ideal.mem_comap, submodule.mem_bot] lemma ker_eq : ((ker f) : set R) = set.preimage f {0} := rfl lemma ker_eq_comap_bot (f : F) : ker f = ideal.comap f ⊥ := rfl omit rcf lemma comap_ker (f : S →+* R) (g : T →+* S) : f.ker.comap g = (f.comp g).ker := by rw [ring_hom.ker_eq_comap_bot, ideal.comap_comap, ring_hom.ker_eq_comap_bot] include rcf /-- If the target is not the zero ring, then one is not in the kernel.-/ lemma not_one_mem_ker [nontrivial S] (f : F) : (1:R) ∉ ker f := by { rw [mem_ker, map_one], exact one_ne_zero } lemma ker_ne_top [nontrivial S] (f : F) : ker f ≠ ⊤ := (ideal.ne_top_iff_one _).mpr $ not_one_mem_ker f omit rcf end semiring section ring variables {F : Type*} [ring R] [semiring S] [rc : ring_hom_class F R S] (f : F) include rc lemma injective_iff_ker_eq_bot : function.injective f ↔ ker f = ⊥ := by { rw [set_like.ext'_iff, ker_eq, set.ext_iff], exact injective_iff_map_eq_zero' f } lemma ker_eq_bot_iff_eq_zero : ker f = ⊥ ↔ ∀ x, f x = 0 → x = 0 := by { rw [← injective_iff_map_eq_zero f, injective_iff_ker_eq_bot] } omit rc @[simp] lemma ker_coe_equiv (f : R ≃+* S) : ker (f : R →+* S) = ⊥ := by simpa only [←injective_iff_ker_eq_bot] using equiv_like.injective f @[simp] lemma ker_equiv {F' : Type*} [ring_equiv_class F' R S] (f : F') : ker f = ⊥ := by simpa only [←injective_iff_ker_eq_bot] using equiv_like.injective f end ring section comm_ring variables [comm_ring R] [comm_ring S] (f : R →+* S) /-- The induced map from the quotient by the kernel to the codomain. This is an isomorphism if `f` has a right inverse (`quotient_ker_equiv_of_right_inverse`) / is surjective (`quotient_ker_equiv_of_surjective`). -/ def ker_lift (f : R →+* S) : R ⧸ f.ker →+* S := ideal.quotient.lift _ f $ λ r, f.mem_ker.mp @[simp] lemma ker_lift_mk (f : R →+* S) (r : R) : ker_lift f (ideal.quotient.mk f.ker r) = f r := ideal.quotient.lift_mk _ _ _ /-- The induced map from the quotient by the kernel is injective. -/ lemma ker_lift_injective (f : R →+* S) : function.injective (ker_lift f) := assume a b, quotient.induction_on₂' a b $ assume a b (h : f a = f b), ideal.quotient.eq.2 $ show a - b ∈ ker f, by rw [mem_ker, map_sub, h, sub_self] variable {f} /-- The **first isomorphism theorem** for commutative rings, computable version. -/ def quotient_ker_equiv_of_right_inverse {g : S → R} (hf : function.right_inverse g f) : R ⧸ f.ker ≃+* S := { to_fun := ker_lift f, inv_fun := (ideal.quotient.mk f.ker) ∘ g, left_inv := begin rintro ⟨x⟩, apply ker_lift_injective, simp [hf (f x)], end, right_inv := hf, ..ker_lift f} @[simp] lemma quotient_ker_equiv_of_right_inverse.apply {g : S → R} (hf : function.right_inverse g f) (x : R ⧸ f.ker) : quotient_ker_equiv_of_right_inverse hf x = ker_lift f x := rfl @[simp] lemma quotient_ker_equiv_of_right_inverse.symm.apply {g : S → R} (hf : function.right_inverse g f) (x : S) : (quotient_ker_equiv_of_right_inverse hf).symm x = ideal.quotient.mk f.ker (g x) := rfl /-- The **first isomorphism theorem** for commutative rings. -/ noncomputable def quotient_ker_equiv_of_surjective (hf : function.surjective f) : R ⧸ f.ker ≃+* S := quotient_ker_equiv_of_right_inverse (classical.some_spec hf.has_right_inverse) end comm_ring /-- The kernel of a homomorphism to a domain is a prime ideal. -/ lemma ker_is_prime {F : Type*} [ring R] [ring S] [is_domain S] [ring_hom_class F R S] (f : F) : (ker f).is_prime := ⟨by { rw [ne.def, ideal.eq_top_iff_one], exact not_one_mem_ker f }, λ x y, by simpa only [mem_ker, map_mul] using @eq_zero_or_eq_zero_of_mul_eq_zero S _ _ _ _ _⟩ /-- The kernel of a homomorphism to a field is a maximal ideal. -/ lemma ker_is_maximal_of_surjective {R K F : Type*} [ring R] [field K] [ring_hom_class F R K] (f : F) (hf : function.surjective f) : (ker f).is_maximal := begin refine ideal.is_maximal_iff.mpr ⟨λ h1, @one_ne_zero K _ _ $ map_one f ▸ (mem_ker f).mp h1, λ J x hJ hxf hxJ, _⟩, obtain ⟨y, hy⟩ := hf (f x)⁻¹, have H : 1 = y * x - (y * x - 1) := (sub_sub_cancel _ _).symm, rw H, refine J.sub_mem (J.mul_mem_left _ hxJ) (hJ _), rw mem_ker, simp only [hy, map_sub, map_one, map_mul, inv_mul_cancel (mt (mem_ker f).mpr hxf), sub_self], end end ring_hom namespace ideal variables {R : Type*} {S : Type*} {F : Type*} section semiring variables [semiring R] [semiring S] [rc : ring_hom_class F R S] include rc lemma map_eq_bot_iff_le_ker {I : ideal R} (f : F) : I.map f = ⊥ ↔ I ≤ (ring_hom.ker f) := by rw [ring_hom.ker, eq_bot_iff, map_le_iff_le_comap] lemma ker_le_comap {K : ideal S} (f : F) : ring_hom.ker f ≤ comap f K := λ x hx, mem_comap.2 (((ring_hom.mem_ker f).1 hx).symm ▸ K.zero_mem) end semiring section ring variables [ring R] [ring S] [rc : ring_hom_class F R S] include rc lemma map_Inf {A : set (ideal R)} {f : F} (hf : function.surjective f) : (∀ J ∈ A, ring_hom.ker f ≤ J) → map f (Inf A) = Inf (map f '' A) := begin refine λ h, le_antisymm (le_Inf _) _, { intros j hj y hy, cases (mem_map_iff_of_surjective f hf).1 hy with x hx, cases (set.mem_image _ _ _).mp hj with J hJ, rw [← hJ.right, ← hx.right], exact mem_map_of_mem f (Inf_le_of_le hJ.left (le_of_eq rfl) hx.left) }, { intros y hy, cases hf y with x hx, refine hx ▸ (mem_map_of_mem f _), have : ∀ I ∈ A, y ∈ map f I, by simpa using hy, rw [submodule.mem_Inf], intros J hJ, rcases (mem_map_iff_of_surjective f hf).1 (this J hJ) with ⟨x', hx', rfl⟩, have : x - x' ∈ J, { apply h J hJ, rw [ring_hom.mem_ker, map_sub, hx, sub_self] }, simpa only [sub_add_cancel] using J.add_mem this hx' } end theorem map_is_prime_of_surjective {f : F} (hf : function.surjective f) {I : ideal R} [H : is_prime I] (hk : ring_hom.ker f ≤ I) : is_prime (map f I) := begin refine ⟨λ h, H.ne_top (eq_top_iff.2 _), λ x y, _⟩, { replace h := congr_arg (comap f) h, rw [comap_map_of_surjective _ hf, comap_top] at h, exact h ▸ sup_le (le_of_eq rfl) hk }, { refine λ hxy, (hf x).rec_on (λ a ha, (hf y).rec_on (λ b hb, _)), rw [← ha, ← hb, ← _root_.map_mul f, mem_map_iff_of_surjective _ hf] at hxy, rcases hxy with ⟨c, hc, hc'⟩, rw [← sub_eq_zero, ← map_sub] at hc', have : a * b ∈ I, { convert I.sub_mem hc (hk (hc' : c - a * b ∈ ring_hom.ker f)), abel }, exact (H.mem_or_mem this).imp (λ h, ha ▸ mem_map_of_mem f h) (λ h, hb ▸ mem_map_of_mem f h) } end lemma map_eq_bot_iff_of_injective {I : ideal R} {f : F} (hf : function.injective f) : I.map f = ⊥ ↔ I = ⊥ := by rw [map_eq_bot_iff_le_ker, (ring_hom.injective_iff_ker_eq_bot f).mp hf, le_bot_iff] omit rc theorem map_is_prime_of_equiv {F' : Type*} [ring_equiv_class F' R S] (f : F') {I : ideal R} [is_prime I] : is_prime (map f I) := map_is_prime_of_surjective (equiv_like.surjective f) $ by simp only [ring_hom.ker_equiv, bot_le] end ring section comm_ring variables [comm_ring R] [comm_ring S] @[simp] lemma mk_ker {I : ideal R} : (quotient.mk I).ker = I := by ext; rw [ring_hom.ker, mem_comap, submodule.mem_bot, quotient.eq_zero_iff_mem] lemma map_mk_eq_bot_of_le {I J : ideal R} (h : I ≤ J) : I.map (J^.quotient.mk) = ⊥ := by { rw [map_eq_bot_iff_le_ker, mk_ker], exact h } lemma ker_quotient_lift {S : Type v} [comm_ring S] {I : ideal R} (f : R →+* S) (H : I ≤ f.ker) : (ideal.quotient.lift I f H).ker = (f.ker).map I^.quotient.mk := begin ext x, split, { intro hx, obtain ⟨y, hy⟩ := quotient.mk_surjective x, rw [ring_hom.mem_ker, ← hy, ideal.quotient.lift_mk, ← ring_hom.mem_ker] at hx, rw [← hy, mem_map_iff_of_surjective I^.quotient.mk quotient.mk_surjective], exact ⟨y, hx, rfl⟩ }, { intro hx, rw mem_map_iff_of_surjective I^.quotient.mk quotient.mk_surjective at hx, obtain ⟨y, hy⟩ := hx, rw [ring_hom.mem_ker, ← hy.right, ideal.quotient.lift_mk, ← (ring_hom.mem_ker f)], exact hy.left }, end theorem map_eq_iff_sup_ker_eq_of_surjective {I J : ideal R} (f : R →+* S) (hf : function.surjective f) : map f I = map f J ↔ I ⊔ f.ker = J ⊔ f.ker := by rw [← (comap_injective_of_surjective f hf).eq_iff, comap_map_of_surjective f hf, comap_map_of_surjective f hf, ring_hom.ker_eq_comap_bot] theorem map_radical_of_surjective {f : R →+* S} (hf : function.surjective f) {I : ideal R} (h : ring_hom.ker f ≤ I) : map f (I.radical) = (map f I).radical := begin rw [radical_eq_Inf, radical_eq_Inf], have : ∀ J ∈ {J : ideal R | I ≤ J ∧ J.is_prime}, f.ker ≤ J := λ J hJ, le_trans h hJ.left, convert map_Inf hf this, refine funext (λ j, propext ⟨_, _⟩), { rintros ⟨hj, hj'⟩, haveI : j.is_prime := hj', exact ⟨comap f j, ⟨⟨map_le_iff_le_comap.1 hj, comap_is_prime f j⟩, map_comap_of_surjective f hf j⟩⟩ }, { rintro ⟨J, ⟨hJ, hJ'⟩⟩, haveI : J.is_prime := hJ.right, refine ⟨hJ' ▸ map_mono hJ.left, hJ' ▸ map_is_prime_of_surjective hf (le_trans h hJ.left)⟩ }, end @[simp] lemma bot_quotient_is_maximal_iff (I : ideal R) : (⊥ : ideal (R ⧸ I)).is_maximal ↔ I.is_maximal := ⟨λ hI, (@mk_ker _ _ I) ▸ @comap_is_maximal_of_surjective _ _ _ _ _ _ (quotient.mk I) quotient.mk_surjective ⊥ hI, λ hI, @bot_is_maximal _ (@field.to_division_ring _ (@quotient.field _ _ I hI)) ⟩ /-- See also `ideal.mem_quotient_iff_mem` in case `I ≤ J`. -/ @[simp] lemma mem_quotient_iff_mem_sup {I J : ideal R} {x : R} : quotient.mk I x ∈ J.map (quotient.mk I) ↔ x ∈ J ⊔ I := by rw [← mem_comap, comap_map_of_surjective (quotient.mk I) quotient.mk_surjective, ← ring_hom.ker_eq_comap_bot, mk_ker] /-- See also `ideal.mem_quotient_iff_mem_sup` if the assumption `I ≤ J` is not available. -/ lemma mem_quotient_iff_mem {I J : ideal R} (hIJ : I ≤ J) {x : R} : quotient.mk I x ∈ J.map (quotient.mk I) ↔ x ∈ J := by rw [mem_quotient_iff_mem_sup, sup_eq_left.mpr hIJ] section quotient_algebra variables (R₁ R₂ : Type*) {A B : Type*} variables [comm_semiring R₁] [comm_semiring R₂] [comm_ring A] [comm_ring B] variables [algebra R₁ A] [algebra R₂ A] [algebra R₁ B] /-- The `R₁`-algebra structure on `A/I` for an `R₁`-algebra `A` -/ instance quotient.algebra {I : ideal A} : algebra R₁ (A ⧸ I) := { to_fun := λ x, ideal.quotient.mk I (algebra_map R₁ A x), smul := (•), smul_def' := λ r x, quotient.induction_on' x $ λ x, ((quotient.mk I).congr_arg $ algebra.smul_def _ _).trans (ring_hom.map_mul _ _ _), commutes' := λ _ _, mul_comm _ _, .. ring_hom.comp (ideal.quotient.mk I) (algebra_map R₁ A) } -- Lean can struggle to find this instance later if we don't provide this shortcut instance quotient.is_scalar_tower [has_smul R₁ R₂] [is_scalar_tower R₁ R₂ A] (I : ideal A) : is_scalar_tower R₁ R₂ (A ⧸ I) := by apply_instance /-- The canonical morphism `A →ₐ[R₁] A ⧸ I` as morphism of `R₁`-algebras, for `I` an ideal of `A`, where `A` is an `R₁`-algebra. -/ def quotient.mkₐ (I : ideal A) : A →ₐ[R₁] A ⧸ I := ⟨λ a, submodule.quotient.mk a, rfl, λ _ _, rfl, rfl, λ _ _, rfl, λ _, rfl⟩ lemma quotient.alg_hom_ext {I : ideal A} {S} [semiring S] [algebra R₁ S] ⦃f g : A ⧸ I →ₐ[R₁] S⦄ (h : f.comp (quotient.mkₐ R₁ I) = g.comp (quotient.mkₐ R₁ I)) : f = g := alg_hom.ext $ λ x, quotient.induction_on' x $ alg_hom.congr_fun h lemma quotient.alg_map_eq (I : ideal A) : algebra_map R₁ (A ⧸ I) = (algebra_map A (A ⧸ I)).comp (algebra_map R₁ A) := rfl lemma quotient.mkₐ_to_ring_hom (I : ideal A) : (quotient.mkₐ R₁ I).to_ring_hom = ideal.quotient.mk I := rfl @[simp] lemma quotient.mkₐ_eq_mk (I : ideal A) : ⇑(quotient.mkₐ R₁ I) = ideal.quotient.mk I := rfl @[simp] lemma quotient.algebra_map_eq (I : ideal R) : algebra_map R (R ⧸ I) = I^.quotient.mk := rfl @[simp] lemma quotient.mk_comp_algebra_map (I : ideal A) : (quotient.mk I).comp (algebra_map R₁ A) = algebra_map R₁ (A ⧸ I) := rfl @[simp] lemma quotient.mk_algebra_map (I : ideal A) (x : R₁) : quotient.mk I (algebra_map R₁ A x) = algebra_map R₁ (A ⧸ I) x := rfl /-- The canonical morphism `A →ₐ[R₁] I.quotient` is surjective. -/ lemma quotient.mkₐ_surjective (I : ideal A) : function.surjective (quotient.mkₐ R₁ I) := surjective_quot_mk _ /-- The kernel of `A →ₐ[R₁] I.quotient` is `I`. -/ @[simp] lemma quotient.mkₐ_ker (I : ideal A) : (quotient.mkₐ R₁ I : A →+* A ⧸ I).ker = I := ideal.mk_ker variables {R₁} /-- `ideal.quotient.lift` as an `alg_hom`. -/ def quotient.liftₐ (I : ideal A) (f : A →ₐ[R₁] B) (hI : ∀ (a : A), a ∈ I → f a = 0) : A ⧸ I →ₐ[R₁] B := { commutes' := λ r, begin -- this is is_scalar_tower.algebra_map_apply R₁ A (A ⧸ I) but the file `algebra.algebra.tower` -- imports this file. have : algebra_map R₁ (A ⧸ I) r = algebra_map A (A ⧸ I) (algebra_map R₁ A r), { simp_rw [algebra.algebra_map_eq_smul_one, smul_assoc, one_smul] }, rw [this, ideal.quotient.algebra_map_eq, ring_hom.to_fun_eq_coe, ideal.quotient.lift_mk, alg_hom.coe_to_ring_hom, algebra.algebra_map_eq_smul_one, algebra.algebra_map_eq_smul_one, map_smul, map_one], end ..(ideal.quotient.lift I (f : A →+* B) hI) } @[simp] lemma quotient.liftₐ_apply (I : ideal A) (f : A →ₐ[R₁] B) (hI : ∀ (a : A), a ∈ I → f a = 0) (x) : ideal.quotient.liftₐ I f hI x = ideal.quotient.lift I (f : A →+* B) hI x := rfl lemma quotient.liftₐ_comp (I : ideal A) (f : A →ₐ[R₁] B) (hI : ∀ (a : A), a ∈ I → f a = 0) : (ideal.quotient.liftₐ I f hI).comp (ideal.quotient.mkₐ R₁ I) = f := alg_hom.ext (λ x, (ideal.quotient.lift_mk I (f : A →+* B) hI : _)) lemma ker_lift.map_smul (f : A →ₐ[R₁] B) (r : R₁) (x : A ⧸ f.to_ring_hom.ker) : f.to_ring_hom.ker_lift (r • x) = r • f.to_ring_hom.ker_lift x := begin obtain ⟨a, rfl⟩ := quotient.mkₐ_surjective R₁ _ x, rw [← alg_hom.map_smul, quotient.mkₐ_eq_mk, ring_hom.ker_lift_mk], exact f.map_smul _ _ end /-- The induced algebras morphism from the quotient by the kernel to the codomain. This is an isomorphism if `f` has a right inverse (`quotient_ker_alg_equiv_of_right_inverse`) / is surjective (`quotient_ker_alg_equiv_of_surjective`). -/ def ker_lift_alg (f : A →ₐ[R₁] B) : (A ⧸ f.to_ring_hom.ker) →ₐ[R₁] B := alg_hom.mk' f.to_ring_hom.ker_lift (λ _ _, ker_lift.map_smul f _ _) @[simp] lemma ker_lift_alg_mk (f : A →ₐ[R₁] B) (a : A) : ker_lift_alg f (quotient.mk f.to_ring_hom.ker a) = f a := rfl @[simp] lemma ker_lift_alg_to_ring_hom (f : A →ₐ[R₁] B) : (ker_lift_alg f).to_ring_hom = ring_hom.ker_lift f := rfl /-- The induced algebra morphism from the quotient by the kernel is injective. -/ lemma ker_lift_alg_injective (f : A →ₐ[R₁] B) : function.injective (ker_lift_alg f) := ring_hom.ker_lift_injective f /-- The **first isomorphism** theorem for algebras, computable version. -/ def quotient_ker_alg_equiv_of_right_inverse {f : A →ₐ[R₁] B} {g : B → A} (hf : function.right_inverse g f) : (A ⧸ f.to_ring_hom.ker) ≃ₐ[R₁] B := { ..ring_hom.quotient_ker_equiv_of_right_inverse (λ x, show f.to_ring_hom (g x) = x, from hf x), ..ker_lift_alg f} @[simp] lemma quotient_ker_alg_equiv_of_right_inverse.apply {f : A →ₐ[R₁] B} {g : B → A} (hf : function.right_inverse g f) (x : A ⧸ f.to_ring_hom.ker) : quotient_ker_alg_equiv_of_right_inverse hf x = ker_lift_alg f x := rfl @[simp] lemma quotient_ker_alg_equiv_of_right_inverse_symm.apply {f : A →ₐ[R₁] B} {g : B → A} (hf : function.right_inverse g f) (x : B) : (quotient_ker_alg_equiv_of_right_inverse hf).symm x = quotient.mkₐ R₁ f.to_ring_hom.ker (g x) := rfl /-- The **first isomorphism theorem** for algebras. -/ noncomputable def quotient_ker_alg_equiv_of_surjective {f : A →ₐ[R₁] B} (hf : function.surjective f) : (A ⧸ f.to_ring_hom.ker) ≃ₐ[R₁] B := quotient_ker_alg_equiv_of_right_inverse (classical.some_spec hf.has_right_inverse) /-- The ring hom `R/I →+* S/J` induced by a ring hom `f : R →+* S` with `I ≤ f⁻¹(J)` -/ def quotient_map {I : ideal R} (J : ideal S) (f : R →+* S) (hIJ : I ≤ J.comap f) : R ⧸ I →+* S ⧸ J := (quotient.lift I ((quotient.mk J).comp f) (λ _ ha, by simpa [function.comp_app, ring_hom.coe_comp, quotient.eq_zero_iff_mem] using hIJ ha)) @[simp] lemma quotient_map_mk {J : ideal R} {I : ideal S} {f : R →+* S} {H : J ≤ I.comap f} {x : R} : quotient_map I f H (quotient.mk J x) = quotient.mk I (f x) := quotient.lift_mk J _ _ @[simp] lemma quotient_map_algebra_map {J : ideal A} {I : ideal S} {f : A →+* S} {H : J ≤ I.comap f} {x : R₁} : quotient_map I f H (algebra_map R₁ (A ⧸ J) x) = quotient.mk I (f (algebra_map _ _ x)) := quotient.lift_mk J _ _ lemma quotient_map_comp_mk {J : ideal R} {I : ideal S} {f : R →+* S} (H : J ≤ I.comap f) : (quotient_map I f H).comp (quotient.mk J) = (quotient.mk I).comp f := ring_hom.ext (λ x, by simp only [function.comp_app, ring_hom.coe_comp, ideal.quotient_map_mk]) /-- The ring equiv `R/I ≃+* S/J` induced by a ring equiv `f : R ≃+** S`, where `J = f(I)`. -/ @[simps] def quotient_equiv (I : ideal R) (J : ideal S) (f : R ≃+* S) (hIJ : J = I.map (f : R →+* S)) : R ⧸ I ≃+* S ⧸ J := { inv_fun := quotient_map I ↑f.symm (by {rw hIJ, exact le_of_eq (map_comap_of_equiv I f)}), left_inv := by {rintro ⟨r⟩, simp }, right_inv := by {rintro ⟨s⟩, simp }, ..quotient_map J ↑f (by {rw hIJ, exact @le_comap_map _ S _ _ _ _ _ _}) } @[simp] lemma quotient_equiv_mk (I : ideal R) (J : ideal S) (f : R ≃+* S) (hIJ : J = I.map (f : R →+* S)) (x : R) : quotient_equiv I J f hIJ (ideal.quotient.mk I x) = ideal.quotient.mk J (f x) := rfl @[simp] lemma quotient_equiv_symm_mk (I : ideal R) (J : ideal S) (f : R ≃+* S) (hIJ : J = I.map (f : R →+* S)) (x : S) : (quotient_equiv I J f hIJ).symm (ideal.quotient.mk J x) = ideal.quotient.mk I (f.symm x) := rfl /-- `H` and `h` are kept as separate hypothesis since H is used in constructing the quotient map. -/ lemma quotient_map_injective' {J : ideal R} {I : ideal S} {f : R →+* S} {H : J ≤ I.comap f} (h : I.comap f ≤ J) : function.injective (quotient_map I f H) := begin refine (injective_iff_map_eq_zero (quotient_map I f H)).2 (λ a ha, _), obtain ⟨r, rfl⟩ := quotient.mk_surjective a, rw [quotient_map_mk, quotient.eq_zero_iff_mem] at ha, exact (quotient.eq_zero_iff_mem).mpr (h ha), end /-- If we take `J = I.comap f` then `quotient_map` is injective automatically. -/ lemma quotient_map_injective {I : ideal S} {f : R →+* S} : function.injective (quotient_map I f le_rfl) := quotient_map_injective' le_rfl lemma quotient_map_surjective {J : ideal R} {I : ideal S} {f : R →+* S} {H : J ≤ I.comap f} (hf : function.surjective f) : function.surjective (quotient_map I f H) := λ x, let ⟨x, hx⟩ := quotient.mk_surjective x in let ⟨y, hy⟩ := hf x in ⟨(quotient.mk J) y, by simp [hx, hy]⟩ /-- Commutativity of a square is preserved when taking quotients by an ideal. -/ lemma comp_quotient_map_eq_of_comp_eq {R' S' : Type*} [comm_ring R'] [comm_ring S'] {f : R →+* S} {f' : R' →+* S'} {g : R →+* R'} {g' : S →+* S'} (hfg : f'.comp g = g'.comp f) (I : ideal S') : (quotient_map I g' le_rfl).comp (quotient_map (I.comap g') f le_rfl) = (quotient_map I f' le_rfl).comp (quotient_map (I.comap f') g (le_of_eq (trans (comap_comap f g') (hfg ▸ (comap_comap g f'))))) := begin refine ring_hom.ext (λ a, _), obtain ⟨r, rfl⟩ := quotient.mk_surjective a, simp only [ring_hom.comp_apply, quotient_map_mk], exact congr_arg (quotient.mk I) (trans (g'.comp_apply f r).symm (hfg ▸ (f'.comp_apply g r))), end /-- The algebra hom `A/I →+* B/J` induced by an algebra hom `f : A →ₐ[R₁] B` with `I ≤ f⁻¹(J)`. -/ def quotient_mapₐ {I : ideal A} (J : ideal B) (f : A →ₐ[R₁] B) (hIJ : I ≤ J.comap f) : A ⧸ I →ₐ[R₁] B ⧸ J := { commutes' := λ r, by simp, ..quotient_map J (f : A →+* B) hIJ } @[simp] lemma quotient_map_mkₐ {I : ideal A} (J : ideal B) (f : A →ₐ[R₁] B) (H : I ≤ J.comap f) {x : A} : quotient_mapₐ J f H (quotient.mk I x) = quotient.mkₐ R₁ J (f x) := rfl lemma quotient_map_comp_mkₐ {I : ideal A} (J : ideal B) (f : A →ₐ[R₁] B) (H : I ≤ J.comap f) : (quotient_mapₐ J f H).comp (quotient.mkₐ R₁ I) = (quotient.mkₐ R₁ J).comp f := alg_hom.ext (λ x, by simp only [quotient_map_mkₐ, quotient.mkₐ_eq_mk, alg_hom.comp_apply]) /-- The algebra equiv `A/I ≃ₐ[R] B/J` induced by an algebra equiv `f : A ≃ₐ[R] B`, where`J = f(I)`. -/ def quotient_equiv_alg (I : ideal A) (J : ideal B) (f : A ≃ₐ[R₁] B) (hIJ : J = I.map (f : A →+* B)) : (A ⧸ I) ≃ₐ[R₁] B ⧸ J := { commutes' := λ r, by simp, ..quotient_equiv I J (f : A ≃+* B) hIJ } @[priority 100] instance quotient_algebra {I : ideal A} [algebra R A] : algebra (R ⧸ I.comap (algebra_map R A)) (A ⧸ I) := (quotient_map I (algebra_map R A) (le_of_eq rfl)).to_algebra lemma algebra_map_quotient_injective {I : ideal A} [algebra R A]: function.injective (algebra_map (R ⧸ I.comap (algebra_map R A)) (A ⧸ I)) := begin rintros ⟨a⟩ ⟨b⟩ hab, replace hab := quotient.eq.mp hab, rw ← ring_hom.map_sub at hab, exact quotient.eq.mpr hab end end quotient_algebra end comm_ring end ideal namespace submodule variables {R : Type u} {M : Type v} variables [comm_semiring R] [add_comm_monoid M] [module R M] -- TODO: show `[algebra R A] : algebra (ideal R) A` too instance module_submodule : module (ideal R) (submodule R M) := { smul_add := smul_sup, add_smul := sup_smul, mul_smul := submodule.smul_assoc, one_smul := by simp, zero_smul := bot_smul, smul_zero := smul_bot } end submodule namespace ring_hom variables {A B C : Type*} [ring A] [ring B] [ring C] variables (f : A →+* B) (f_inv : B → A) /-- Auxiliary definition used to define `lift_of_right_inverse` -/ def lift_of_right_inverse_aux (hf : function.right_inverse f_inv f) (g : A →+* C) (hg : f.ker ≤ g.ker) : B →+* C := { to_fun := λ b, g (f_inv b), map_one' := begin rw [← g.map_one, ← sub_eq_zero, ← g.map_sub, ← g.mem_ker], apply hg, rw [f.mem_ker, f.map_sub, sub_eq_zero, f.map_one], exact hf 1 end, map_mul' := begin intros x y, rw [← g.map_mul, ← sub_eq_zero, ← g.map_sub, ← g.mem_ker], apply hg, rw [f.mem_ker, f.map_sub, sub_eq_zero, f.map_mul], simp only [hf _], end, .. add_monoid_hom.lift_of_right_inverse f.to_add_monoid_hom f_inv hf ⟨g.to_add_monoid_hom, hg⟩ } @[simp] lemma lift_of_right_inverse_aux_comp_apply (hf : function.right_inverse f_inv f) (g : A →+* C) (hg : f.ker ≤ g.ker) (a : A) : (f.lift_of_right_inverse_aux f_inv hf g hg) (f a) = g a := f.to_add_monoid_hom.lift_of_right_inverse_comp_apply f_inv hf ⟨g.to_add_monoid_hom, hg⟩ a /-- `lift_of_right_inverse f hf g hg` is the unique ring homomorphism `φ` * such that `φ.comp f = g` (`ring_hom.lift_of_right_inverse_comp`), * where `f : A →+* B` is has a right_inverse `f_inv` (`hf`), * and `g : B →+* C` satisfies `hg : f.ker ≤ g.ker`. See `ring_hom.eq_lift_of_right_inverse` for the uniqueness lemma. ``` A . | \ f | \ g | \ v \⌟ B ----> C ∃!φ ``` -/ def lift_of_right_inverse (hf : function.right_inverse f_inv f) : {g : A →+* C // f.ker ≤ g.ker} ≃ (B →+* C) := { to_fun := λ g, f.lift_of_right_inverse_aux f_inv hf g.1 g.2, inv_fun := λ φ, ⟨φ.comp f, λ x hx, (mem_ker _).mpr $ by simp [(mem_ker _).mp hx]⟩, left_inv := λ g, by { ext, simp only [comp_apply, lift_of_right_inverse_aux_comp_apply, subtype.coe_mk, subtype.val_eq_coe], }, right_inv := λ φ, by { ext b, simp [lift_of_right_inverse_aux, hf b], } } /-- A non-computable version of `ring_hom.lift_of_right_inverse` for when no computable right inverse is available, that uses `function.surj_inv`. -/ @[simp] noncomputable abbreviation lift_of_surjective (hf : function.surjective f) : {g : A →+* C // f.ker ≤ g.ker} ≃ (B →+* C) := f.lift_of_right_inverse (function.surj_inv hf) (function.right_inverse_surj_inv hf) lemma lift_of_right_inverse_comp_apply (hf : function.right_inverse f_inv f) (g : {g : A →+* C // f.ker ≤ g.ker}) (x : A) : (f.lift_of_right_inverse f_inv hf g) (f x) = g x := f.lift_of_right_inverse_aux_comp_apply f_inv hf g.1 g.2 x lemma lift_of_right_inverse_comp (hf : function.right_inverse f_inv f) (g : {g : A →+* C // f.ker ≤ g.ker}) : (f.lift_of_right_inverse f_inv hf g).comp f = g := ring_hom.ext $ f.lift_of_right_inverse_comp_apply f_inv hf g lemma eq_lift_of_right_inverse (hf : function.right_inverse f_inv f) (g : A →+* C) (hg : f.ker ≤ g.ker) (h : B →+* C) (hh : h.comp f = g) : h = (f.lift_of_right_inverse f_inv hf ⟨g, hg⟩) := begin simp_rw ←hh, exact ((f.lift_of_right_inverse f_inv hf).apply_symm_apply _).symm, end end ring_hom namespace double_quot open ideal variable {R : Type u} section variables [comm_ring R] (I J : ideal R) /-- The obvious ring hom `R/I → R/(I ⊔ J)` -/ def quot_left_to_quot_sup : R ⧸ I →+* R ⧸ (I ⊔ J) := ideal.quotient.factor I (I ⊔ J) le_sup_left /-- The kernel of `quot_left_to_quot_sup` -/ lemma ker_quot_left_to_quot_sup : (quot_left_to_quot_sup I J).ker = J.map (ideal.quotient.mk I) := by simp only [mk_ker, sup_idem, sup_comm, quot_left_to_quot_sup, quotient.factor, ker_quotient_lift, map_eq_iff_sup_ker_eq_of_surjective I^.quotient.mk quotient.mk_surjective, ← sup_assoc] /-- The ring homomorphism `(R/I)/J' -> R/(I ⊔ J)` induced by `quot_left_to_quot_sup` where `J'` is the image of `J` in `R/I`-/ def quot_quot_to_quot_sup : (R ⧸ I) ⧸ J.map (ideal.quotient.mk I) →+* R ⧸ I ⊔ J := by exact ideal.quotient.lift (J.map (ideal.quotient.mk I)) (quot_left_to_quot_sup I J) (ker_quot_left_to_quot_sup I J).symm.le /-- The composite of the maps `R → (R/I)` and `(R/I) → (R/I)/J'` -/ def quot_quot_mk : R →+* ((R ⧸ I) ⧸ J.map I^.quotient.mk) := by exact ((J.map I^.quotient.mk)^.quotient.mk).comp I^.quotient.mk /-- The kernel of `quot_quot_mk` -/ lemma ker_quot_quot_mk : (quot_quot_mk I J).ker = I ⊔ J := by rw [ring_hom.ker_eq_comap_bot, quot_quot_mk, ← comap_comap, ← ring_hom.ker, mk_ker, comap_map_of_surjective (ideal.quotient.mk I) (quotient.mk_surjective), ← ring_hom.ker, mk_ker, sup_comm] /-- The ring homomorphism `R/(I ⊔ J) → (R/I)/J' `induced by `quot_quot_mk` -/ def lift_sup_quot_quot_mk (I J : ideal R) : R ⧸ (I ⊔ J) →+* (R ⧸ I) ⧸ J.map (ideal.quotient.mk I) := ideal.quotient.lift (I ⊔ J) (quot_quot_mk I J) (ker_quot_quot_mk I J).symm.le /-- `quot_quot_to_quot_add` and `lift_sup_double_qot_mk` are inverse isomorphisms -/ def quot_quot_equiv_quot_sup : (R ⧸ I) ⧸ J.map (ideal.quotient.mk I) ≃+* R ⧸ I ⊔ J := ring_equiv.of_hom_inv (quot_quot_to_quot_sup I J) (lift_sup_quot_quot_mk I J) (by { ext z, refl }) (by { ext z, refl }) @[simp] lemma quot_quot_equiv_quot_sup_quot_quot_mk (x : R) : quot_quot_equiv_quot_sup I J (quot_quot_mk I J x) = ideal.quotient.mk (I ⊔ J) x := rfl @[simp] lemma quot_quot_equiv_quot_sup_symm_quot_quot_mk (x : R) : (quot_quot_equiv_quot_sup I J).symm (ideal.quotient.mk (I ⊔ J) x) = quot_quot_mk I J x := rfl /-- The obvious isomorphism `(R/I)/J' → (R/J)/I' ` -/ def quot_quot_equiv_comm : (R ⧸ I) ⧸ J.map I^.quotient.mk ≃+* (R ⧸ J) ⧸ I.map J^.quotient.mk := ((quot_quot_equiv_quot_sup I J).trans (quot_equiv_of_eq sup_comm)).trans (quot_quot_equiv_quot_sup J I).symm @[simp] lemma quot_quot_equiv_comm_quot_quot_mk (x : R) : quot_quot_equiv_comm I J (quot_quot_mk I J x) = quot_quot_mk J I x := rfl @[simp] lemma quot_quot_equiv_comm_comp_quot_quot_mk : ring_hom.comp ↑(quot_quot_equiv_comm I J) (quot_quot_mk I J) = quot_quot_mk J I := ring_hom.ext $ quot_quot_equiv_comm_quot_quot_mk I J @[simp] lemma quot_quot_equiv_comm_symm : (quot_quot_equiv_comm I J).symm = quot_quot_equiv_comm J I := rfl end section algebra @[simp] lemma quot_quot_equiv_comm_mk_mk [comm_ring R] (I J : ideal R) (x : R) : quot_quot_equiv_comm I J (ideal.quotient.mk _ (ideal.quotient.mk _ x)) = algebra_map R _ x := rfl variables [comm_semiring R] {A : Type v} [comm_ring A] [algebra R A] (I J : ideal A) @[simp] lemma quot_quot_equiv_quot_sup_quot_quot_algebra_map (x : R) : double_quot.quot_quot_equiv_quot_sup I J (algebra_map R _ x) = algebra_map _ _ x := rfl @[simp] lemma quot_quot_equiv_comm_algebra_map (x : R) : quot_quot_equiv_comm I J (algebra_map R _ x) = algebra_map _ _ x := rfl end algebra end double_quot
2aa3b2e1ccc14e223f482768efea629c25c55dbd
cf39355caa609c0f33405126beee2739aa3cb77e
/library/init/data/list/lemmas.lean
db03c74f1e95b613320b63360fff38b3e9d97ff4
[ "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
10,534
lean
/- Copyright (c) 2014 Parikshit Khanna. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Parikshit Khanna, Jeremy Avigad, Leonardo de Moura, Floris van Doorn -/ prelude import init.data.list.basic init.function init.meta init.data.nat.lemmas import init.meta.interactive init.meta.smt.rsimp universes u v w w₁ w₂ variables {α : Type u} {β : Type v} {γ : Type w} namespace list open nat /-! append -/ @[simp] lemma nil_append (s : list α) : [] ++ s = s := rfl @[simp] lemma cons_append (x : α) (s t : list α) : (x::s) ++ t = x::(s ++ t) := rfl @[simp] lemma append_nil (t : list α) : t ++ [] = t := by induction t; simp [*] @[simp] lemma append_assoc (s t u : list α) : s ++ t ++ u = s ++ (t ++ u) := by induction s; simp [*] /-! length -/ lemma length_cons (a : α) (l : list α) : length (a :: l) = length l + 1 := rfl @[simp] lemma length_append (s t : list α) : length (s ++ t) = length s + length t := begin induction s, { show length t = 0 + length t, by rw nat.zero_add }, { simp [*, nat.add_comm, nat.add_left_comm] }, end @[simp] lemma length_repeat (a : α) (n : ℕ) : length (repeat a n) = n := by induction n; simp [*]; refl @[simp] lemma length_tail (l : list α) : length (tail l) = length l - 1 := by cases l; refl -- TODO(Leo): cleanup proof after arith dec proc @[simp] lemma length_drop : ∀ (i : ℕ) (l : list α), length (drop i l) = length l - i | 0 l := rfl | (succ i) [] := eq.symm (nat.zero_sub (succ i)) | (succ i) (x::l) := calc length (drop (succ i) (x::l)) = length l - i : length_drop i l ... = succ (length l) - succ i : (nat.succ_sub_succ_eq_sub (length l) i).symm /-! map -/ lemma map_cons (f : α → β) (a l) : map f (a::l) = f a :: map f l := rfl @[simp] lemma map_append (f : α → β) : ∀ l₁ l₂, map f (l₁ ++ l₂) = (map f l₁) ++ (map f l₂) := by intro l₁; induction l₁; intros; simp [*] lemma map_singleton (f : α → β) (a : α) : map f [a] = [f a] := rfl @[simp] lemma map_id (l : list α) : map id l = l := by induction l; simp [*] @[simp] lemma map_map (g : β → γ) (f : α → β) (l : list α) : map g (map f l) = map (g ∘ f) l := by induction l; simp [*] @[simp] lemma length_map (f : α → β) (l : list α) : length (map f l) = length l := by induction l; simp [*] /-! bind -/ @[simp] lemma nil_bind (f : α → list β) : list.bind [] f = [] := by simp [join, list.bind] @[simp] lemma cons_bind (x xs) (f : α → list β) : list.bind (x :: xs) f = f x ++ list.bind xs f := by simp [join, list.bind] @[simp] lemma append_bind (xs ys) (f : α → list β) : list.bind (xs ++ ys) f = list.bind xs f ++ list.bind ys f := by induction xs; [refl, simp [*, cons_bind]] /-! mem -/ lemma mem_nil_iff (a : α) : a ∈ ([] : list α) ↔ false := iff.rfl @[simp] lemma not_mem_nil (a : α) : a ∉ ([] : list α) := not_false lemma mem_cons_self (a : α) (l : list α) : a ∈ a :: l := or.inl rfl @[simp] lemma mem_cons_iff (a y : α) (l : list α) : a ∈ y :: l ↔ (a = y ∨ a ∈ l) := iff.rfl @[rsimp] lemma mem_cons_eq (a y : α) (l : list α) : (a ∈ y :: l) = (a = y ∨ a ∈ l) := rfl lemma mem_cons_of_mem (y : α) {a : α} {l : list α} : a ∈ l → a ∈ y :: l := assume H, or.inr H lemma eq_or_mem_of_mem_cons {a y : α} {l : list α} : a ∈ y::l → a = y ∨ a ∈ l := assume h, h @[simp] lemma mem_append {a : α} {s t : list α} : a ∈ s ++ t ↔ a ∈ s ∨ a ∈ t := by induction s; simp [*, or_assoc] @[rsimp] lemma mem_append_eq (a : α) (s t : list α) : (a ∈ s ++ t) = (a ∈ s ∨ a ∈ t) := propext mem_append lemma mem_append_left {a : α} {l₁ : list α} (l₂ : list α) (h : a ∈ l₁) : a ∈ l₁ ++ l₂ := mem_append.2 (or.inl h) lemma mem_append_right {a : α} (l₁ : list α) {l₂ : list α} (h : a ∈ l₂) : a ∈ l₁ ++ l₂ := mem_append.2 (or.inr h) lemma not_bex_nil (p : α → Prop) : ¬ (∃ x ∈ @nil α, p x) := λ⟨x, hx, px⟩, hx lemma ball_nil (p : α → Prop) : ∀ x ∈ @nil α, p x := λx, false.elim lemma bex_cons (p : α → Prop) (a : α) (l : list α) : (∃ x ∈ (a :: l), p x) ↔ (p a ∨ ∃ x ∈ l, p x) := ⟨λ⟨x, h, px⟩, by { simp at h, cases h with h h, {cases h, exact or.inl px}, {exact or.inr ⟨x, h, px⟩}}, λo, o.elim (λpa, ⟨a, mem_cons_self _ _, pa⟩) (λ⟨x, h, px⟩, ⟨x, mem_cons_of_mem _ h, px⟩)⟩ lemma ball_cons (p : α → Prop) (a : α) (l : list α) : (∀ x ∈ (a :: l), p x) ↔ (p a ∧ ∀ x ∈ l, p x) := ⟨λal, ⟨al a (mem_cons_self _ _), λx h, al x (mem_cons_of_mem _ h)⟩, λ⟨pa, al⟩ x o, o.elim (λe, e.symm ▸ pa) (al x)⟩ /-! list subset -/ protected def subset (l₁ l₂ : list α) := ∀ ⦃a : α⦄, a ∈ l₁ → a ∈ l₂ instance : has_subset (list α) := ⟨list.subset⟩ @[simp] lemma nil_subset (l : list α) : [] ⊆ l := λ b i, false.elim (iff.mp (mem_nil_iff b) i) @[refl, simp] lemma subset.refl (l : list α) : l ⊆ l := λ b i, i @[trans] lemma subset.trans {l₁ l₂ l₃ : list α} (h₁ : l₁ ⊆ l₂) (h₂ : l₂ ⊆ l₃) : l₁ ⊆ l₃ := λ b i, h₂ (h₁ i) @[simp] lemma subset_cons (a : α) (l : list α) : l ⊆ a::l := λ b i, or.inr i lemma subset_of_cons_subset {a : α} {l₁ l₂ : list α} : a::l₁ ⊆ l₂ → l₁ ⊆ l₂ := λ s b i, s (mem_cons_of_mem _ i) lemma cons_subset_cons {l₁ l₂ : list α} (a : α) (s : l₁ ⊆ l₂) : (a::l₁) ⊆ (a::l₂) := λ b hin, or.elim (eq_or_mem_of_mem_cons hin) (λ e : b = a, or.inl e) (λ i : b ∈ l₁, or.inr (s i)) @[simp] lemma subset_append_left (l₁ l₂ : list α) : l₁ ⊆ l₁++l₂ := λ b, mem_append_left _ @[simp] lemma subset_append_right (l₁ l₂ : list α) : l₂ ⊆ l₁++l₂ := λ b, mem_append_right _ lemma subset_cons_of_subset (a : α) {l₁ l₂ : list α} : l₁ ⊆ l₂ → l₁ ⊆ (a::l₂) := λ (s : l₁ ⊆ l₂) (a : α) (i : a ∈ l₁), or.inr (s i) theorem eq_nil_of_length_eq_zero {l : list α} : length l = 0 → l = [] := by {induction l; intros, refl, contradiction} theorem ne_nil_of_length_eq_succ {l : list α} : ∀ {n : nat}, length l = succ n → l ≠ [] := by induction l; intros; contradiction @[simp] theorem length_map₂ (f : α → β → γ) (l₁) : ∀ l₂, length (map₂ f l₁ l₂) = min (length l₁) (length l₂) := by { induction l₁; intro l₂; cases l₂; simp [*, add_one, min_succ_succ, nat.zero_min, nat.min_zero] } @[simp] theorem length_take : ∀ (i : ℕ) (l : list α), length (take i l) = min i (length l) | 0 l := by simp [nat.zero_min] | (succ n) [] := by simp [nat.min_zero] | (succ n) (a::l) := by simp [*, nat.min_succ_succ, add_one] theorem length_take_le (n) (l : list α) : length (take n l) ≤ n := by simp [min_le_left] theorem length_remove_nth : ∀ (l : list α) (i : ℕ), i < length l → length (remove_nth l i) = length l - 1 | [] _ h := rfl | (x::xs) 0 h := by simp [remove_nth] | (x::xs) (i+1) h := have i < length xs, from lt_of_succ_lt_succ h, by dsimp [remove_nth]; rw [length_remove_nth xs i this, nat.sub_add_cancel (lt_of_le_of_lt (nat.zero_le _) this)]; refl @[simp] lemma partition_eq_filter_filter (p : α → Prop) [decidable_pred p] : ∀ (l : list α), partition p l = (filter p l, filter (not ∘ p) l) | [] := rfl | (a::l) := by { by_cases pa : p a; simp [partition, filter, pa, partition_eq_filter_filter l] } /-! sublists -/ inductive sublist : list α → list α → Prop | slnil : sublist [] [] | cons (l₁ l₂ a) : sublist l₁ l₂ → sublist l₁ (a::l₂) | cons2 (l₁ l₂ a) : sublist l₁ l₂ → sublist (a::l₁) (a::l₂) infix ` <+ `:50 := sublist lemma length_le_of_sublist : ∀ {l₁ l₂ : list α}, l₁ <+ l₂ → length l₁ ≤ length l₂ | _ _ sublist.slnil := le_refl 0 | _ _ (sublist.cons l₁ l₂ a s) := le_succ_of_le (length_le_of_sublist s) | _ _ (sublist.cons2 l₁ l₂ a s) := succ_le_succ (length_le_of_sublist s) /-! filter -/ @[simp] theorem filter_nil (p : α → Prop) [h : decidable_pred p] : filter p [] = [] := rfl @[simp] theorem filter_cons_of_pos {p : α → Prop} [h : decidable_pred p] {a : α} : ∀ l, p a → filter p (a::l) = a :: filter p l := λ l pa, if_pos pa @[simp] theorem filter_cons_of_neg {p : α → Prop} [h : decidable_pred p] {a : α} : ∀ l, ¬ p a → filter p (a::l) = filter p l := λ l pa, if_neg pa @[simp] theorem filter_append {p : α → Prop} [h : decidable_pred p] : ∀ (l₁ l₂ : list α), filter p (l₁++l₂) = filter p l₁ ++ filter p l₂ | [] l₂ := rfl | (a::l₁) l₂ := by by_cases pa : p a; simp [pa, filter_append] @[simp] theorem filter_sublist {p : α → Prop} [h : decidable_pred p] : Π (l : list α), filter p l <+ l | [] := sublist.slnil | (a::l) := if pa : p a then by simp [pa]; apply sublist.cons2; apply filter_sublist l else by simp [pa]; apply sublist.cons; apply filter_sublist l /-! map_accumr -/ section map_accumr variables {φ : Type w₁} {σ : Type w₂} -- This runs a function over a list returning the intermediate results and a -- a final result. def map_accumr (f : α → σ → σ × β) : list α → σ → (σ × list β) | [] c := (c, []) | (y::yr) c := let r := map_accumr yr c in let z := f y r.1 in (z.1, z.2 :: r.2) @[simp] theorem length_map_accumr : ∀ (f : α → σ → σ × β) (x : list α) (s : σ), length (map_accumr f x s).2 = length x | f (a::x) s := congr_arg succ (length_map_accumr f x s) | f [] s := rfl end map_accumr section map_accumr₂ variables {φ : Type w₁} {σ : Type w₂} -- This runs a function over two lists returning the intermediate results and a -- a final result. def map_accumr₂ (f : α → β → σ → σ × φ) : list α → list β → σ → σ × list φ | [] _ c := (c,[]) | _ [] c := (c,[]) | (x::xr) (y::yr) c := let r := map_accumr₂ xr yr c in let q := f x y r.1 in (q.1, q.2 :: r.2) @[simp] theorem length_map_accumr₂ : ∀ (f : α → β → σ → σ × φ) x y c, length (map_accumr₂ f x y c).2 = min (length x) (length y) | f (a::x) (b::y) c := calc succ (length (map_accumr₂ f x y c).2) = succ (min (length x) (length y)) : congr_arg succ (length_map_accumr₂ f x y c) ... = min (succ (length x)) (succ (length y)) : eq.symm (min_succ_succ (length x) (length y)) | f (a::x) [] c := rfl | f [] (b::y) c := rfl | f [] [] c := rfl end map_accumr₂ end list
c348bca33ab937bf0f6af285223a97dffb3d074e
9dd3f3912f7321eb58ee9aa8f21778ad6221f87c
/library/init/meta/tactic.lean
547ccc017c151e1bdc0d1075bfe5a69bdd599ea0
[ "Apache-2.0" ]
permissive
bre7k30/lean
de893411bcfa7b3c5572e61b9e1c52951b310aa4
5a924699d076dab1bd5af23a8f910b433e598d7a
refs/heads/master
1,610,900,145,817
1,488,006,845,000
1,488,006,845,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
38,396
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.function init.data.option.basic init.util import init.category.combinators init.category.monad init.category.alternative init.category.monad_fail import init.data.nat.div init.meta.exceptional init.meta.format init.meta.environment import init.meta.pexpr init.data.to_string init.data.string.basic init.meta.interaction_monad meta constant tactic_state : Type universes u v namespace tactic_state meta constant env : tactic_state → environment meta constant to_format : tactic_state → format /- Format expression with respect to the main goal in the tactic state. If the tactic state does not contain any goals, then format expression using an empty local context. -/ meta constant format_expr : tactic_state → expr → format meta constant get_options : tactic_state → options meta constant set_options : tactic_state → options → tactic_state end tactic_state meta instance : has_to_format tactic_state := ⟨tactic_state.to_format⟩ @[reducible] meta def tactic := interaction_monad tactic_state @[reducible] meta def tactic_result := interaction_monad.result tactic_state namespace tactic export interaction_monad (hiding failed fail) meta def failed {α : Type} : tactic α := interaction_monad.failed meta def fail {α : Type u} {β : Type v} [has_to_format β] (msg : β) : tactic α := interaction_monad.fail msg end tactic namespace tactic_result export interaction_monad.result end tactic_result open tactic open tactic_result infixl ` >>=[tactic] `:2 := interaction_monad_bind infixl ` >>[tactic] `:2 := interaction_monad_seq meta instance : alternative tactic := ⟨@interaction_monad_fmap tactic_state, (λ α a s, success a s), (@fapp _ _), @interaction_monad.failed tactic_state, @interaction_monad_orelse tactic_state⟩ meta def {u₁ u₂} tactic.up {α : Type u₂} (t : tactic α) : tactic (ulift.{u₁} α) := λ s, match t s with | success a s' := success (ulift.up a) s' | exception t ref s := exception t ref s end meta def {u₁ u₂} tactic.down {α : Type u₂} (t : tactic (ulift.{u₁} α)) : tactic α := λ s, match t s with | success (ulift.up a) s' := success a s' | exception t ref s := exception t ref s end namespace tactic variables {α : Type u} meta def try_core (t : tactic α) : tactic (option α) := λ s, result.cases_on (t s) (λ a, success (some a)) (λ e ref s', success none s) meta def skip : tactic unit := success () meta def try (t : tactic α) : tactic unit := try_core t >>[tactic] skip meta def fail_if_success {α : Type u} (t : tactic α) : tactic unit := λ s, result.cases_on (t s) (λ a s, mk_exception "fail_if_success combinator failed, given tactic succeeded" none s) (λ e ref s', success () s) open nat /- (repeat_at_most n t): repeat the given tactic at most n times or until t fails -/ meta def repeat_at_most : nat → tactic unit → tactic unit | 0 t := skip | (succ n) t := (do t, repeat_at_most n t) <|> skip /- (repeat_exactly n t) : execute t n times -/ meta def repeat_exactly : nat → tactic unit → tactic unit | 0 t := skip | (succ n) t := do t, repeat_exactly n t meta def repeat : tactic unit → tactic unit := repeat_at_most 100000 meta def returnopt (e : option α) : tactic α := λ s, match e with | (some a) := success a s | none := mk_exception "failed" none s end meta instance opt_to_tac : has_coe (option α) (tactic α) := ⟨returnopt⟩ /- Decorate t's exceptions with msg -/ meta def decorate_ex (msg : format) (t : tactic α) : tactic α := λ s, result.cases_on (t s) success (λ opt_thunk, match opt_thunk with | some e := exception (some (λ u, msg ++ format.nest 2 (format.line ++ e u))) | none := exception none end) @[inline] meta def write (s' : tactic_state) : tactic unit := λ s, success () s' @[inline] meta def read : tactic tactic_state := λ s, success s s meta def get_options : tactic options := do s ← read, return s^.get_options meta def set_options (o : options) : tactic unit := do s ← read, write (s^.set_options o) meta def save_options {α : Type} (t : tactic α) : tactic α := do o ← get_options, a ← t, set_options o, return a meta def returnex {α : Type} (e : exceptional α) : tactic α := λ s, match e with | exceptional.success a := success a s | exceptional.exception .α f := match get_options s with | success opt _ := exception (some (λ u, f opt)) none s | exception _ _ _ := exception (some (λ u, f options.mk)) none s end end meta instance ex_to_tac {α : Type} : has_coe (exceptional α) (tactic α) := ⟨returnex⟩ end tactic meta def tactic_format_expr (e : expr) : tactic format := do s ← tactic.read, return (tactic_state.format_expr s e) meta class has_to_tactic_format (α : Type u) := (to_tactic_format : α → tactic format) meta instance : has_to_tactic_format expr := ⟨tactic_format_expr⟩ meta def tactic.pp {α : Type u} [has_to_tactic_format α] : α → tactic format := has_to_tactic_format.to_tactic_format open tactic format meta instance {α : Type u} [has_to_tactic_format α] : has_to_tactic_format (list α) := ⟨fmap to_fmt ∘ monad.mapm pp⟩ meta instance (α : Type u) (β : Type v) [has_to_tactic_format α] [has_to_tactic_format β] : has_to_tactic_format (α × β) := ⟨λ ⟨a, b⟩, to_fmt <$> (prod.mk <$> pp a <*> pp b)⟩ meta def option_to_tactic_format {α : Type u} [has_to_tactic_format α] : option α → tactic format | (some a) := do fa ← pp a, return (to_fmt "(some " ++ fa ++ ")") | none := return "none" meta instance {α : Type u} [has_to_tactic_format α] : has_to_tactic_format (option α) := ⟨option_to_tactic_format⟩ meta instance has_to_format_to_has_to_tactic_format (α : Type) [has_to_format α] : has_to_tactic_format α := ⟨(λ x, return x) ∘ to_fmt⟩ namespace tactic open tactic_state meta def get_env : tactic environment := do s ← read, return $ env s meta def get_decl (n : name) : tactic declaration := do s ← read, (env s)^.get n meta def trace {α : Type u} [has_to_tactic_format α] (a : α) : tactic unit := do fmt ← pp a, return $ _root_.trace_fmt fmt (λ u, ()) meta def trace_call_stack : tactic unit := take state, _root_.trace_call_stack (success () state) meta def timetac {α : Type u} (desc : string) (t : tactic α) : tactic α := λ s, timeit desc (t s) meta def trace_state : tactic unit := do s ← read, trace $ to_fmt s inductive transparency | all | semireducible | reducible | none export transparency (reducible semireducible) /- (eval_expr α α_as_expr e) evaluates 'e' IF 'e' has type 'α'. 'α' must be a closed term. 'α_as_expr' is synthesized by the code generator. 'e' must be a closed expression at runtime. -/ meta constant eval_expr (α : Type u) {α_expr : pexpr} : expr → tactic α /- Return the partial term/proof constructed so far. Note that the resultant expression may contain variables that are not declarate in the current main goal. -/ meta constant result : tactic expr /- Display the partial term/proof constructed so far. This tactic is *not* equivalent to do { r ← result, s ← read, return (format_expr s r) } because this one will format the result with respect to the current goal, and trace_result will do it with respect to the initial goal. -/ meta constant format_result : tactic format /- Return target type of the main goal. Fail if tactic_state does not have any goal left. -/ meta constant target : tactic expr meta constant intro_core : name → tactic expr meta constant intron : nat → tactic unit meta constant rename : name → name → tactic unit /- Clear the given local constant. The tactic fails if the given expression is not a local constant. -/ meta constant clear : expr → tactic unit meta constant revert_lst : list expr → tactic nat /-- Return `e` in weak head normal form with respect to the given transparency setting. -/ meta constant whnf (e : expr) (md := semireducible) : tactic expr /- (head) eta expand the given expression -/ meta constant eta_expand : expr → tactic expr /- (head) beta reduction -/ meta constant beta : expr → tactic expr /- (head) zeta reduction -/ meta constant zeta : expr → tactic expr /- (head) eta reduction -/ meta constant eta : expr → tactic expr /-- Succeeds if `t` and `s` can be unified using the given transparency setting. -/ meta constant unify (t s : expr) (md := semireducible) : tactic unit /- Similar to `unify`, but it treats metavariables as constants. -/ meta constant is_def_eq (t s : expr) (md := semireducible) : tactic unit /- Infer the type of the given expression. Remark: transparency does not affect type inference -/ meta constant infer_type : expr → tactic expr meta constant get_local : name → tactic expr /- Resolve a name using the current local context, environment, aliases, etc. -/ meta constant resolve_name : name → tactic expr /- Return the hypothesis in the main goal. Fail if tactic_state does not have any goal left. -/ meta constant local_context : tactic (list expr) meta constant get_unused_name : name → option nat → tactic name /-- Helper tactic for creating simple applications where some arguments are inferred using type inference. Example, given ``` rel.{l_1 l_2} : Pi (α : Type.{l_1}) (β : α -> Type.{l_2}), (Pi x : α, β x) -> (Pi x : α, β x) -> , Prop nat : Type real : Type vec.{l} : Pi (α : Type l) (n : nat), Type.{l1} f g : Pi (n : nat), vec real n ``` then ``` mk_app_core semireducible "rel" [f, g] ``` returns the application ``` rel.{1 2} nat (fun n : nat, vec real n) f g ``` The unification constraints due to type inference are solved using the transparency `md`. -/ meta constant mk_app (fn : name) (args : list expr) (md := semireducible) : tactic expr /-- Similar to `mk_app`, but allows to specify which arguments are explicit/implicit. Example, given `(a b : nat)` then ``` mk_mapp "ite" [some (a > b), none, none, some a, some b] ``` returns the application ``` @ite.{1} (a > b) (nat.decidable_gt a b) nat a b ``` -/ meta constant mk_mapp (fn : name) (args : list (option expr)) (md := semireducible) : tactic expr /-- (mk_congr_arg h₁ h₂) is a more efficient version of (mk_app `congr_arg [h₁, h₂]) -/ meta constant mk_congr_arg : expr → expr → tactic expr /-- (mk_congr_fun h₁ h₂) is a more efficient version of (mk_app `congr_fun [h₁, h₂]) -/ meta constant mk_congr_fun : expr → expr → tactic expr /-- (mk_congr h₁ h₂) is a more efficient version of (mk_app `congr [h₁, h₂]) -/ meta constant mk_congr : expr → expr → tactic expr /-- (mk_eq_refl h) is a more efficient version of (mk_app `eq.refl [h]) -/ meta constant mk_eq_refl : expr → tactic expr /-- (mk_eq_symm h) is a more efficient version of (mk_app `eq.symm [h]) -/ meta constant mk_eq_symm : expr → tactic expr /-- (mk_eq_trans h₁ h₂) is a more efficient version of (mk_app `eq.trans [h₁, h₂]) -/ meta constant mk_eq_trans : expr → expr → tactic expr /-- (mk_eq_mp h₁ h₂) is a more efficient version of (mk_app `eq.mp [h₁, h₂]) -/ meta constant mk_eq_mp : expr → expr → tactic expr /-- (mk_eq_mpr h₁ h₂) is a more efficient version of (mk_app `eq.mpr [h₁, h₂]) -/ meta constant mk_eq_mpr : expr → expr → tactic expr /- Given a local constant t, if t has type (lhs = rhs) apply susbstitution. Otherwise, try to find a local constant that has type of the form (t = t') or (t' = t). The tactic fails if the given expression is not a local constant. -/ meta constant subst : expr → tactic unit /-- Close the current goal using `e`. Fail is the type of `e` is not definitionally equal to the target type. -/ meta constant exact (e : expr) (md := semireducible) : tactic unit /-- Elaborate the given quoted expression with respect to the current main goal. If `allow_mvars` is tt, then metavariables are tolerated and become new goals. If `report_errors` is ff, then errors are reported using position information from q. -/ meta constant to_expr (q : pexpr) (allow_mvars := tt) (report_errors := ff) : tactic expr /- Return true if the given expression is a type class. -/ meta constant is_class : expr → tactic bool /- Try to create an instance of the given type class. -/ meta constant mk_instance : expr → tactic expr /- Change the target of the main goal. The input expression must be definitionally equal to the current target. -/ meta constant change : expr → tactic unit /- (assert_core H T), adds a new goal for T, and change target to (T -> target). -/ meta constant assert_core : name → expr → tactic unit /- (assertv_core H T P), change target to (T -> target) if P has type T. -/ meta constant assertv_core : name → expr → expr → tactic unit /- (define_core H T), adds a new goal for T, and change target to (let H : T := ?M in target) in the current goal. -/ meta constant define_core : name → expr → tactic unit /- (definev_core H T P), change target to (Let H : T := P in target) if P has type T. -/ meta constant definev_core : name → expr → expr → tactic unit /- rotate goals to the left -/ meta constant rotate_left : nat → tactic unit meta constant get_goals : tactic (list expr) meta constant set_goals : list expr → tactic unit /-- Configuration options for the `apply` tactic. -/ structure apply_cfg := (md := semireducible) (approx := tt) (all := ff) (use_instances := tt) /-- Apply the expression `e` to the main goal, the unification is performed using the transparency mode in `cfg`. If cfg^.approx is `tt`, then fallback to first-order unification, and approximate context during unification. If cfg^.all is `tt`, then all unassigned meta-variables are added as new goals. If cfg^.use_instances is `tt`, then use type class resolution to instantiate unassigned meta-variables. It returns a list of all introduced meta variables, even the assigned ones. -/ meta constant apply_core (e : expr) (cfg : apply_cfg := {}) : tactic (list expr) /- Create a fresh meta universe variable. -/ meta constant mk_meta_univ : tactic level /- Create a fresh meta-variable with the given type. The scope of the new meta-variable is the local context of the main goal. -/ meta constant mk_meta_var : expr → tactic expr /- Return the value assigned to the given universe meta-variable. Fail if argument is not an universe meta-variable or if it is not assigned. -/ meta constant get_univ_assignment : level → tactic level /- Return the value assigned to the given meta-variable. Fail if argument is not a meta-variable or if it is not assigned. -/ meta constant get_assignment : expr → tactic expr meta constant mk_fresh_name : tactic name /- Return a hash code for expr that ignores inst_implicit arguments, and proofs. -/ meta constant abstract_hash : expr → tactic nat /- Return the "weight" of the given expr while ignoring inst_implicit arguments, and proofs. -/ meta constant abstract_weight : expr → tactic nat meta constant abstract_eq : expr → expr → tactic bool /- Induction on `h` using recursor `rec`, names for the new hypotheses are retrieved from `ns`. If `ns` does not have sufficient names, then use the internal binder names in the recursor. It returns for each new goal a list of new hypotheses and a list of substitutions for hypotheses depending on `h`. The substitutions map internal names to their replacement terms. If the replacement is again a hypothesis the user name stays the same. The internal names are only valid in the original goal, not in the type context of the new goal. If `rec` is none, then the type of `h` is inferred, if it is of the form `C ...`, tactic uses `C.rec` -/ meta constant induction (h : expr) (ns : list name := []) (rec : option name := none) (md := semireducible) : tactic (list (list expr × list (name × expr))) /- Apply `cases_on` recursor, names for the new hypotheses are retrieved from `ns`. `h` must be a local constant. It returns for each new goal the name of the constructor, a list of new hypotheses, and a list of substitutions for hypotheses depending on `h`. The number of new goals may be smaller than the number of constructors. Some goals may be discarded when the indices to not match. See `induction` for information on the list of substitutions. The `cases` tactic is implemented using this one, and it relaxes the restriction of `h`. -/ meta constant cases_core (h : expr) (ns : list name := []) (md := semireducible) : tactic (list (name × list expr × list (name × expr))) /- Similar to cases tactic, but does not revert/intro/clear hypotheses. -/ meta constant destruct (e : expr) (md := semireducible) : tactic unit /- Generalizes the target with respect to `e`. -/ meta constant generalize (e : expr) (n : name := `_x) (md := semireducible) : tactic unit /- instantiate assigned metavariables in the given expression -/ meta constant instantiate_mvars : expr → tactic expr /- Add the given declaration to the environment -/ meta constant add_decl : declaration → tactic unit /- (doc_string env d k) return the doc string for d (if available) -/ meta constant doc_string : name → tactic string meta constant add_doc_string : name → string → tactic unit /-- Create an auxiliary definition with name `c` where `type` and `value` may contain local constants and meta-variables. This function collects all dependencies (universe parameters, universe metavariables, local constants (aka hypotheses) and metavariables). It updates the environment in the tactic_state, and returns an expression of the form (c.{l_1 ... l_n} a_1 ... a_m) where l_i's and a_j's are the collected dependencies. -/ meta constant add_aux_decl (c : name) (type : expr) (val : expr) (is_lemma : bool) : tactic expr meta constant module_doc_strings : tactic (list (option name × string)) /- Set attribute `attr_name` for constant `c_name` with the given priority. If the priority is none, then use default -/ meta constant set_basic_attribute (attr_name : name) (c_name : name) (persistent := ff) (prio : option nat := none) : tactic unit /- (unset_attribute attr_name c_name) -/ meta constant unset_attribute : name → name → tactic unit /- (has_attribute attr_name c_name) succeeds if the declaration `decl_name` has the attribute `attr_name`. The result is the priority. -/ meta constant has_attribute : name → name → tactic nat /- (copy_attribute attr_name c_name d_name) copy attribute `attr_name` from `src` to `tgt` if it is defined for `src` -/ meta def copy_attribute (attr_name : name) (src : name) (p : bool) (tgt : name) : tactic unit := try $ do prio ← has_attribute attr_name src, set_basic_attribute attr_name tgt p (some prio) /-- Name of the declaration currently being elaborated. -/ meta constant decl_name : tactic name /- (save_type_info e ref) save (typeof e) at position associated with ref -/ meta constant save_type_info : expr → expr → tactic unit meta constant save_info_thunk : pos → (unit → format) → tactic unit meta constant report_error : nat → nat → format → tactic unit /-- Return list of currently open namespaces -/ meta constant open_namespaces : tactic (list name) /-- Return tt iff `t` "occurs" in `e`. The occurrence checking is performed using keyed matching with the given transparency setting. We say `t` occurs in `e` by keyed matching iff there is a subterm `s` s.t. `t` and `s` have the same head, and `is_def_eq t s md` The main idea is to minimize the number of `is_def_eq` checks performed. -/ meta constant kdepends_on (e t : expr) (md := reducible) : tactic bool open list nat meta def induction' (h : expr) (ns : list name := []) (rec : option name := none) (md := semireducible) : tactic unit := induction h ns rec md >> return () /-- Remark: set_goals will erase any solved goal -/ meta def cleanup : tactic unit := get_goals >>= set_goals /- Auxiliary definition used to implement begin ... end blocks -/ meta def step {α : Type u} (t : tactic α) : tactic unit := t >>[tactic] cleanup meta def istep {α : Type u} (line : nat) (col : nat) (t : tactic α) : tactic unit := λ s, @scope_trace _ line col ((t >>[tactic] cleanup) s) meta def report_exception {α : Type} (line col : nat) : option (unit → format) → tactic α | (some msg_thunk) := λ s, let msg := msg_thunk () ++ format.line ++ to_fmt "state:" ++ format.line ++ s^.to_format in (tactic.report_error line col msg >> silent_fail) s | none := silent_fail /- Auxiliary definition used to implement begin ... end blocks. It is similar to step, but it reports an error at the given line/col if the tactic t fails. -/ meta def rstep {α : Type u} (line : nat) (col : nat) (t : tactic α) : tactic unit := λ s, result.cases_on (istep line col t s) (λ a new_s, result.success () new_s) (λ msg_thunk e, report_exception line col msg_thunk) meta def is_prop (e : expr) : tactic bool := do t ← infer_type e, return (t = expr.prop) /-- Return true iff n is the name of declaration that is a proposition. -/ meta def is_prop_decl (n : name) : tactic bool := do env ← get_env, d ← env^.get n, t ← return $ d^.type, is_prop t meta def is_proof (e : expr) : tactic bool := infer_type e >>= is_prop meta def whnf_no_delta (e : expr) : tactic expr := whnf e transparency.none meta def whnf_target : tactic unit := target >>= whnf >>= change meta def intro (n : name) : tactic expr := do t ← target, if expr.is_pi t ∨ expr.is_let t then intro_core n else whnf_target >> intro_core n meta def intro1 : tactic expr := intro `_ meta def intros : tactic (list expr) := do t ← target, match t with | expr.pi _ _ _ _ := do H ← intro1, Hs ← intros, return (H :: Hs) | expr.elet _ _ _ _ := do H ← intro1, Hs ← intros, return (H :: Hs) | _ := return [] end meta def intro_lst : list name → tactic (list expr) | [] := return [] | (n::ns) := do H ← intro n, Hs ← intro_lst ns, return (H :: Hs) meta def to_expr_strict (q : pexpr) (report_errors := ff) : tactic expr := to_expr q report_errors meta def revert (l : expr) : tactic nat := revert_lst [l] meta def clear_lst : list name → tactic unit | [] := skip | (n::ns) := do H ← get_local n, clear H, clear_lst ns meta def match_not (e : expr) : tactic expr := match (expr.is_not e) with | (some a) := return a | none := fail "expression is not a negation" end meta def match_eq (e : expr) : tactic (expr × expr) := match (expr.is_eq e) with | (some (lhs, rhs)) := return (lhs, rhs) | none := fail "expression is not an equality" end meta def match_ne (e : expr) : tactic (expr × expr) := match (expr.is_ne e) with | (some (lhs, rhs)) := return (lhs, rhs) | none := fail "expression is not a disequality" end meta def match_heq (e : expr) : tactic (expr × expr × expr × expr) := do match (expr.is_heq e) with | (some (α, lhs, β, rhs)) := return (α, lhs, β, rhs) | none := fail "expression is not a heterogeneous equality" end meta def match_refl_app (e : expr) : tactic (name × expr × expr) := do env ← get_env, match (environment.is_refl_app env e) with | (some (R, lhs, rhs)) := return (R, lhs, rhs) | none := fail "expression is not an application of a reflexive relation" end meta def match_app_of (e : expr) (n : name) : tactic (list expr) := guard (expr.is_app_of e n) >> return e^.get_app_args meta def get_local_type (n : name) : tactic expr := get_local n >>= infer_type meta def trace_result : tactic unit := format_result >>= trace meta def rexact (e : expr) : tactic unit := exact e reducible /- (find_same_type t es) tries to find in es an expression with type definitionally equal to t -/ meta def find_same_type : expr → list expr → tactic expr | e [] := failed | e (H :: Hs) := do t ← infer_type H, (unify e t >> return H) <|> find_same_type e Hs meta def find_assumption (e : expr) : tactic expr := do ctx ← local_context, find_same_type e ctx meta def assumption : tactic unit := do { ctx ← local_context, t ← target, H ← find_same_type t ctx, exact H } <|> fail "assumption tactic failed" meta def save_info (p : pos) : tactic unit := do s ← read, tactic.save_info_thunk p (λ _, tactic_state.to_format s) notation `‹` p `›` := show p, by assumption /- Swap first two goals, do nothing if tactic state does not have at least two goals. -/ meta def swap : tactic unit := do gs ← get_goals, match gs with | (g₁ :: g₂ :: rs) := set_goals (g₂ :: g₁ :: rs) | e := skip end /- (assert h t), adds a new goal for t, and the hypothesis (h : t) in the current goal. -/ meta def assert (h : name) (t : expr) : tactic unit := assert_core h t >> swap >> intro h >> swap /- (assertv h t v), adds the hypothesis (h : t) in the current goal if v has type t. -/ meta def assertv (h : name) (t : expr) (v : expr) : tactic unit := assertv_core h t v >> intro h >> return () /- (define h t), adds a new goal for t, and the hypothesis (h : t := ?M) in the current goal. -/ meta def define (h : name) (t : expr) : tactic unit := define_core h t >> swap >> intro h >> swap /- (definev h t v), adds the hypothesis (h : t := v) in the current goal if v has type t. -/ meta def definev (h : name) (t : expr) (v : expr) : tactic unit := definev_core h t v >> intro h >> return () /- Add (h : t := pr) to the current goal -/ meta def pose (h : name) (pr : expr) : tactic unit := do t ← infer_type pr, definev h t pr /- Add (h : t) to the current goal, given a proof (pr : t) -/ meta def note (n : name) (pr : expr) : tactic unit := do t ← infer_type pr, assertv n t pr /- Return the number of goals that need to be solved -/ meta def num_goals : tactic nat := do gs ← get_goals, return (length gs) /- We have to provide the instance argument `[has_mod nat]` because mod for nat was not defined yet -/ meta def rotate_right (n : nat) [has_mod nat] : tactic unit := do ng ← num_goals, if ng = 0 then skip else rotate_left (ng - n % ng) meta def rotate : nat → tactic unit := rotate_left /- first [t_1, ..., t_n] applies the first tactic that doesn't fail. The tactic fails if all t_i's fail. -/ meta def first {α : Type u} : list (tactic α) → tactic α | [] := fail "first tactic failed, no more alternatives" | (t::ts) := t <|> first ts /- Applies the given tactic to the main goal and fails if it is not solved. -/ meta def solve1 (tac : tactic unit) : tactic unit := do gs ← get_goals, match gs with | [] := fail "focus tactic failed, there isn't any goal left to focus" | (g::rs) := do set_goals [g], tac, gs' ← get_goals, match gs' with | [] := set_goals rs | gs := fail "focus tactic failed, focused goal has not been solved" end end /- solve [t_1, ... t_n] applies the first tactic that solves the main goal. -/ meta def solve (ts : list (tactic unit)) : tactic unit := first $ map solve1 ts private meta def focus_aux : list (tactic unit) → list expr → list expr → tactic unit | [] gs rs := set_goals $ rs ++ gs | (t::ts) (g::gs) rs := do set_goals [g], t, rs' ← get_goals, focus_aux ts gs (rs ++ rs') | (t::ts) [] rs := fail "focus tactic failed, insufficient number of goals" /- focus [t_1, ..., t_n] applies t_i to the i-th goal. Fails if there are less tha n goals. -/ meta def focus (ts : list (tactic unit)) : tactic unit := do gs ← get_goals, focus_aux ts gs [] meta def focus1 {α} (tac : tactic α) : tactic α := do g::gs ← get_goals, match gs with | [] := tac | _ := do set_goals [g], a ← tac, gs' ← get_goals, set_goals (gs' ++ gs), return a end private meta def all_goals_core (tac : tactic unit) : list expr → list expr → tactic unit | [] ac := set_goals ac | (g :: gs) ac := do set_goals [g], tac, new_gs ← get_goals, all_goals_core gs (ac ++ new_gs) /- Apply the given tactic to all goals. -/ meta def all_goals (tac : tactic unit) : tactic unit := do gs ← get_goals, all_goals_core tac gs [] private meta def any_goals_core (tac : tactic unit) : list expr → list expr → bool → tactic unit | [] ac progress := guard progress >> set_goals ac | (g :: gs) ac progress := do set_goals [g], succeeded ← try_core tac, new_gs ← get_goals, any_goals_core gs (ac ++ new_gs) (succeeded^.is_some || progress) /- Apply the given tactic to any goal where it succeeds. The tactic succeeds only if tac succeeds for at least one goal. -/ meta def any_goals (tac : tactic unit) : tactic unit := do gs ← get_goals, any_goals_core tac gs [] ff /- LCF-style AND_THEN tactic. It applies tac1, and if succeed applies tac2 to each subgoal produced by tac1 -/ meta def seq (tac1 : tactic unit) (tac2 : tactic unit) : tactic unit := do g::gs ← get_goals, set_goals [g], tac1, all_goals tac2, gs' ← get_goals, set_goals (gs' ++ gs) meta instance : has_andthen (tactic unit) := ⟨seq⟩ meta constant is_trace_enabled_for : name → bool /- Execute tac only if option trace.n is set to true. -/ meta def when_tracing (n : name) (tac : tactic unit) : tactic unit := when (is_trace_enabled_for n = tt) tac /- Fail if there are no remaining goals. -/ meta def fail_if_no_goals : tactic unit := do n ← num_goals, when (n = 0) (fail "tactic failed, there are no goals to be solved") /- Fail if there are unsolved goals. -/ meta def now : tactic unit := do n ← num_goals, when (n ≠ 0) (fail "now tactic failed, there are unsolved goals") meta def apply (e : expr) : tactic unit := apply_core e >> return () meta def fapply (e : expr) : tactic unit := apply_core e {all := tt} >> return () /- Try to solve the main goal using type class resolution. -/ meta def apply_instance : tactic unit := do tgt ← target >>= instantiate_mvars, b ← is_class tgt, if b then mk_instance tgt >>= exact else fail "apply_instance tactic fail, target is not a type class" /- Create a list of universe meta-variables of the given size. -/ meta def mk_num_meta_univs : nat → tactic (list level) | 0 := return [] | (succ n) := do l ← mk_meta_univ, ls ← mk_num_meta_univs n, return (l::ls) /- Return (expr.const c [l_1, ..., l_n]) where l_i's are fresh universe meta-variables. -/ meta def mk_const (c : name) : tactic expr := do env ← get_env, decl ← env^.get c, let num := decl^.univ_params^.length, ls ← mk_num_meta_univs num, return (expr.const c ls) meta def save_const_type_info (n : name) (ref : expr) : tactic unit := try (do c ← mk_const n, save_type_info c ref) /- Create a fresh universe ?u, a metavariable (?T : Type.{?u}), and return metavariable (?M : ?T). This action can be used to create a meta-variable when we don't know its type at creation time -/ meta def mk_mvar : tactic expr := do u ← mk_meta_univ, t ← mk_meta_var (expr.sort u), mk_meta_var t /-- Makes a sorry macro with a meta-variable as its type. -/ meta def mk_sorry : tactic expr := do u ← mk_meta_univ, t ← mk_meta_var (expr.sort u), return $ expr.mk_sorry t /-- Closes the main goal using sorry. -/ meta def admit : tactic unit := target >>= exact ∘ expr.mk_sorry meta def mk_local' (pp_name : name) (bi : binder_info) (type : expr) : tactic expr := do uniq_name ← mk_fresh_name, return $ expr.local_const uniq_name pp_name bi type meta def mk_local_def (pp_name : name) (type : expr) : tactic expr := mk_local' pp_name binder_info.default type private meta def get_pi_arity_aux : expr → tactic nat | (expr.pi n bi d b) := do m ← mk_fresh_name, let l := expr.local_const m n bi d, new_b ← whnf (expr.instantiate_var b l), r ← get_pi_arity_aux new_b, return (r + 1) | e := return 0 /- Compute the arity of the given (Pi-)type -/ meta def get_pi_arity (type : expr) : tactic nat := whnf type >>= get_pi_arity_aux /- Compute the arity of the given function -/ meta def get_arity (fn : expr) : tactic nat := infer_type fn >>= get_pi_arity meta def triv : tactic unit := mk_const `trivial >>= exact notation `dec_trivial` := of_as_true (by tactic.triv) meta def by_contradiction (H : name) : tactic expr := do tgt : expr ← target, (match_not tgt >> return ()) <|> (mk_mapp `decidable.by_contradiction [some tgt, none] >>= apply) <|> fail "tactic by_contradiction failed, target is not a negation nor a decidable proposition (remark: when 'local attribute classical.prop_decidable [instance]' is used all propositions are decidable)", intro H private meta def generalizes_aux (md : transparency) : list expr → tactic unit | [] := skip | (e::es) := generalize e `x md >> generalizes_aux es meta def generalizes (es : list expr) (md := semireducible) : tactic unit := generalizes_aux md es private meta def kdependencies_core (e : expr) (md : transparency) : list expr → list expr → tactic (list expr) | [] r := return r | (h::hs) r := do type ← infer_type h, d ← kdepends_on type e md, if d then kdependencies_core hs (h::r) else kdependencies_core hs r /-- Return all hypotheses that depends on `e` The dependency test is performed using `kdepends_on` with the given transparency setting. -/ meta def kdependencies (e : expr) (md := reducible) : tactic (list expr) := do ctx ← local_context, kdependencies_core e md ctx [] /-- Revert all hypotheses that depend on `e` -/ meta def revert_kdependencies (e : expr) (md := reducible) : tactic nat := kdependencies e md >>= revert_lst meta def revert_kdeps (e : expr) (md := reducible) := revert_kdependencies e md /-- Similar to `cases_core`, but `e` doesn't need to be a hypothesis. Remark, it reverts dependencies using `revert_kdeps`. Two different transparency modes are used `md` and `dmd`. The mode `md` is used with `cases_core` and `dmd` with `generalize` and `revert_kdeps`. -/ meta def cases (e : expr) (ids : list name := []) (md := semireducible) (dmd := semireducible) : tactic unit := if e^.is_local_constant then cases_core e ids md >> return () else do x ← mk_fresh_name, n ← revert_kdependencies e dmd, (tactic.generalize e x dmd) <|> (do t ← infer_type e, tactic.assertv x t e, get_local x >>= tactic.revert, return ()), h ← tactic.intro1, (step (cases_core h ids md); intron n) meta def refine (e : pexpr) (report_errors := ff) : tactic unit := do tgt : expr ← target, to_expr ``(%%e : %%tgt) tt report_errors >>= exact private meta def get_undeclared_const (env : environment) (base : name) : ℕ → name | i := let n := base <.> ("_aux_" ++ to_string i) in if ¬env^.contains n then n else get_undeclared_const (i+1) meta def new_aux_decl_name : tactic name := do env ← get_env, n ← decl_name, return $ get_undeclared_const env n 1 private meta def mk_aux_decl_name : option name → tactic name | none := new_aux_decl_name | (some suffix) := do p ← decl_name, return $ p ++ suffix meta def abstract (tac : tactic unit) (suffix : option name := none) : tactic unit := do fail_if_no_goals, gs ← get_goals, type ← target, is_lemma ← is_prop type, m ← mk_meta_var type, set_goals [m], tac, n ← num_goals, when (n ≠ 0) (fail "abstract tactic failed, there are unsolved goals"), set_goals gs, val ← instantiate_mvars m, c ← mk_aux_decl_name suffix, e ← add_aux_decl c type val is_lemma, exact e /- (solve_aux type tac) synthesize an element of 'type' using tactic 'tac' -/ meta def solve_aux {α : Type} (type : expr) (tac : tactic α) : tactic (α × expr) := do m ← mk_meta_var type, gs ← get_goals, set_goals [m], a ← tac, set_goals gs, return (a, m) /-- Return tt iff 'd' is a declaration in one of the current open namespaces -/ meta def in_open_namespaces (d : name) : tactic bool := do ns ← open_namespaces, env ← get_env, return $ ns^.any (λ n, n^.is_prefix_of d) && env^.contains d /-- Execute tac for 'max' "heartbeats". The heartbeat is approx. the maximum number of memory allocations (in thousands) performed by 'tac'. This is a deterministic way of interrupting long running tactics. -/ meta def try_for {α} (max : nat) (tac : tactic α) : tactic α := λ s, match _root_.try_for max (tac s) with | some r := r | none := mk_exception "try_for tactic failed, timeout" none s end meta def add_meta_definition (n : name) (lvls : list name) (type value : expr) : tactic unit := add_decl (declaration.defn n lvls type value reducibility_hints.abbrev ff) end tactic notation [parsing_only] `command`:max := tactic unit open tactic namespace list meta def for_each {α} : list α → (α → tactic unit) → tactic unit | [] fn := skip | (e::es) fn := do fn e, for_each es fn meta def any_of {α β} : list α → (α → tactic β) → tactic β | [] fn := failed | (e::es) fn := do opt_b ← try_core (fn e), match opt_b with | some b := return b | none := any_of es fn end end list /- Define id_locked using meta-programming because we don't have syntax for setting reducibility_hints. See module init.meta.declaration. Remark: id_locked is used in the builtin implementation of tactic.change -/ run_command do let l := level.param `l, let Ty := expr.sort l, type ← to_expr ``(Π (α : %%Ty), α → α), val ← to_expr ``(λ (α : %%Ty) (a : α), a), add_decl (declaration.defn `id_locked [`l] type val reducibility_hints.opaque tt) lemma id_locked_eq {α : Type u} (a : α) : id_locked α a = a := rfl
778179924733a084184d168b1f5b241028108a63
8cb37a089cdb4af3af9d8bf1002b417e407a8e9e
/library/data/stream.lean
88a157d4770b40f125f797d6b87a878c94570ecb
[ "Apache-2.0" ]
permissive
kbuzzard/lean
ae3c3db4bb462d750dbf7419b28bafb3ec983ef7
ed1788fd674bb8991acffc8fca585ec746711928
refs/heads/master
1,620,983,366,617
1,618,937,600,000
1,618,937,600,000
359,886,396
1
0
Apache-2.0
1,618,936,987,000
1,618,936,987,000
null
UTF-8
Lean
false
false
21,705
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ open nat function option universes u v w def stream (α : Type u) := nat → α namespace stream variables {α : Type u} {β : Type v} {δ : Type w} def cons (a : α) (s : stream α) : stream α := λ i, match i with | 0 := a | succ n := s n end notation h :: t := cons h t @[reducible] def head (s : stream α) : α := s 0 def tail (s : stream α) : stream α := λ i, s (i+1) def drop (n : nat) (s : stream α) : stream α := λ i, s (i+n) @[reducible] def nth (n : nat) (s : stream α) : α := s n protected theorem eta (s : stream α) : head s :: tail s = s := funext (λ i, begin cases i; refl end) theorem nth_zero_cons (a : α) (s : stream α) : nth 0 (a :: s) = a := rfl theorem head_cons (a : α) (s : stream α) : head (a :: s) = a := rfl theorem tail_cons (a : α) (s : stream α) : tail (a :: s) = s := rfl theorem tail_drop (n : nat) (s : stream α) : tail (drop n s) = drop n (tail s) := funext (λ i, begin unfold tail drop, simp [nat.add_comm, nat.add_left_comm] end) theorem nth_drop (n m : nat) (s : stream α) : nth n (drop m s) = nth (n+m) s := rfl theorem tail_eq_drop (s : stream α) : tail s = drop 1 s := rfl theorem drop_drop (n m : nat) (s : stream α) : drop n (drop m s) = drop (n+m) s := funext (λ i, begin unfold drop, rw nat.add_assoc end) theorem nth_succ (n : nat) (s : stream α) : nth (succ n) s = nth n (tail s) := rfl theorem drop_succ (n : nat) (s : stream α) : drop (succ n) s = drop n (tail s) := rfl protected theorem ext {s₁ s₂ : stream α} : (∀ n, nth n s₁ = nth n s₂) → s₁ = s₂ := assume h, funext h def all (p : α → Prop) (s : stream α) := ∀ n, p (nth n s) def any (p : α → Prop) (s : stream α) := ∃ n, p (nth n s) theorem all_def (p : α → Prop) (s : stream α) : all p s = ∀ n, p (nth n s) := rfl theorem any_def (p : α → Prop) (s : stream α) : any p s = ∃ n, p (nth n s) := rfl protected def mem (a : α) (s : stream α) := any (λ b, a = b) s instance : has_mem α (stream α) := ⟨stream.mem⟩ theorem mem_cons (a : α) (s : stream α) : a ∈ (a::s) := exists.intro 0 rfl theorem mem_cons_of_mem {a : α} {s : stream α} (b : α) : a ∈ s → a ∈ b :: s := assume ⟨n, h⟩, exists.intro (succ n) (by rw [nth_succ, tail_cons, h]) theorem eq_or_mem_of_mem_cons {a b : α} {s : stream α} : a ∈ b::s → a = b ∨ a ∈ s := assume ⟨n, h⟩, begin cases n with n', {left, exact h}, {right, rw [nth_succ, tail_cons] at h, exact ⟨n', h⟩} end theorem mem_of_nth_eq {n : nat} {s : stream α} {a : α} : a = nth n s → a ∈ s := assume h, exists.intro n h section map variable (f : α → β) def map (s : stream α) : stream β := λ n, f (nth n s) theorem drop_map (n : nat) (s : stream α) : drop n (map f s) = map f (drop n s) := stream.ext (λ i, rfl) theorem nth_map (n : nat) (s : stream α) : nth n (map f s) = f (nth n s) := rfl theorem tail_map (s : stream α) : tail (map f s) = map f (tail s) := begin rw tail_eq_drop, refl end theorem head_map (s : stream α) : head (map f s) = f (head s) := rfl theorem map_eq (s : stream α) : map f s = f (head s) :: map f (tail s) := by rw [← stream.eta (map f s), tail_map, head_map] theorem map_cons (a : α) (s : stream α) : map f (a :: s) = f a :: map f s := begin rw [← stream.eta (map f (a :: s)), map_eq], refl end theorem map_id (s : stream α) : map id s = s := rfl theorem map_map (g : β → δ) (f : α → β) (s : stream α) : map g (map f s) = map (g ∘ f) s := rfl theorem map_tail (s : stream α) : map f (tail s) = tail (map f s) := rfl theorem mem_map {a : α} {s : stream α} : a ∈ s → f a ∈ map f s := assume ⟨n, h⟩, exists.intro n (by rw [nth_map, h]) theorem exists_of_mem_map {f} {b : β} {s : stream α} : b ∈ map f s → ∃ a, a ∈ s ∧ f a = b := assume ⟨n, h⟩, ⟨nth n s, ⟨n, rfl⟩, h.symm⟩ end map section zip variable (f : α → β → δ) def zip (s₁ : stream α) (s₂ : stream β) : stream δ := λ n, f (nth n s₁) (nth n s₂) theorem drop_zip (n : nat) (s₁ : stream α) (s₂ : stream β) : drop n (zip f s₁ s₂) = zip f (drop n s₁) (drop n s₂) := stream.ext (λ i, rfl) theorem nth_zip (n : nat) (s₁ : stream α) (s₂ : stream β) : nth n (zip f s₁ s₂) = f (nth n s₁) (nth n s₂) := rfl theorem head_zip (s₁ : stream α) (s₂ : stream β) : head (zip f s₁ s₂) = f (head s₁) (head s₂) := rfl theorem tail_zip (s₁ : stream α) (s₂ : stream β) : tail (zip f s₁ s₂) = zip f (tail s₁) (tail s₂) := rfl theorem zip_eq (s₁ : stream α) (s₂ : stream β) : zip f s₁ s₂ = f (head s₁) (head s₂) :: zip f (tail s₁) (tail s₂) := begin rw [← stream.eta (zip f s₁ s₂)], refl end end zip def const (a : α) : stream α := λ n, a theorem mem_const (a : α) : a ∈ const a := exists.intro 0 rfl theorem const_eq (a : α) : const a = a :: const a := begin apply stream.ext, intro n, cases n; refl end theorem tail_const (a : α) : tail (const a) = const a := suffices tail (a :: const a) = const a, by rwa [← const_eq] at this, rfl theorem map_const (f : α → β) (a : α) : map f (const a) = const (f a) := rfl theorem nth_const (n : nat) (a : α) : nth n (const a) = a := rfl theorem drop_const (n : nat) (a : α) : drop n (const a) = const a := stream.ext (λ i, rfl) def iterate (f : α → α) (a : α) : stream α := λ n, nat.rec_on n a (λ n r, f r) theorem head_iterate (f : α → α) (a : α) : head (iterate f a) = a := rfl theorem tail_iterate (f : α → α) (a : α) : tail (iterate f a) = iterate f (f a) := begin funext n, induction n with n' ih, {refl}, {unfold tail iterate, unfold tail iterate at ih, rw add_one at ih, dsimp at ih, rw add_one, dsimp, rw ih} end theorem iterate_eq (f : α → α) (a : α) : iterate f a = a :: iterate f (f a) := begin rw [← stream.eta (iterate f a)], rw tail_iterate, refl end theorem nth_zero_iterate (f : α → α) (a : α) : nth 0 (iterate f a) = a := rfl theorem nth_succ_iterate (n : nat) (f : α → α) (a : α) : nth (succ n) (iterate f a) = nth n (iterate f (f a)) := by rw [nth_succ, tail_iterate] section bisim variable (R : stream α → stream α → Prop) local infix ~ := R def is_bisimulation := ∀ ⦃s₁ s₂⦄, s₁ ~ s₂ → head s₁ = head s₂ ∧ tail s₁ ~ tail s₂ theorem nth_of_bisim (bisim : is_bisimulation R) : ∀ {s₁ s₂} n, s₁ ~ s₂ → nth n s₁ = nth n s₂ ∧ drop (n+1) s₁ ~ drop (n+1) s₂ | s₁ s₂ 0 h := bisim h | s₁ s₂ (n+1) h := match bisim h with | ⟨h₁, trel⟩ := nth_of_bisim n trel end -- If two streams are bisimilar, then they are equal theorem eq_of_bisim (bisim : is_bisimulation R) : ∀ {s₁ s₂}, s₁ ~ s₂ → s₁ = s₂ := λ s₁ s₂ r, stream.ext (λ n, and.elim_left (nth_of_bisim R bisim n r)) end bisim theorem bisim_simple (s₁ s₂ : stream α) : head s₁ = head s₂ → s₁ = tail s₁ → s₂ = tail s₂ → s₁ = s₂ := assume hh ht₁ ht₂, eq_of_bisim (λ s₁ s₂, head s₁ = head s₂ ∧ s₁ = tail s₁ ∧ s₂ = tail s₂) (λ s₁ s₂ ⟨h₁, h₂, h₃⟩, begin constructor, exact h₁, rw [← h₂, ← h₃], repeat { constructor }; assumption end) (and.intro hh (and.intro ht₁ ht₂)) theorem coinduction {s₁ s₂ : stream α} : head s₁ = head s₂ → (∀ (β : Type u) (fr : stream α → β), fr s₁ = fr s₂ → fr (tail s₁) = fr (tail s₂)) → s₁ = s₂ := assume hh ht, eq_of_bisim (λ s₁ s₂, head s₁ = head s₂ ∧ ∀ (β : Type u) (fr : stream α → β), fr s₁ = fr s₂ → fr (tail s₁) = fr (tail s₂)) (λ s₁ s₂ h, have h₁ : head s₁ = head s₂, from and.elim_left h, have h₂ : head (tail s₁) = head (tail s₂), from and.elim_right h α (@head α) h₁, have h₃ : ∀ (β : Type u) (fr : stream α → β), fr (tail s₁) = fr (tail s₂) → fr (tail (tail s₁)) = fr (tail (tail s₂)), from λ β fr, and.elim_right h β (λ s, fr (tail s)), and.intro h₁ (and.intro h₂ h₃)) (and.intro hh ht) theorem iterate_id (a : α) : iterate id a = const a := coinduction rfl (λ β fr ch, begin rw [tail_iterate, tail_const], exact ch end) local attribute [reducible] stream theorem map_iterate (f : α → α) (a : α) : iterate f (f a) = map f (iterate f a) := begin funext n, induction n with n' ih, {refl}, { unfold map iterate nth, dsimp, unfold map iterate nth at ih, dsimp at ih, rw ih } end section corec def corec (f : α → β) (g : α → α) : α → stream β := λ a, map f (iterate g a) def corec_on (a : α) (f : α → β) (g : α → α) : stream β := corec f g a theorem corec_def (f : α → β) (g : α → α) (a : α) : corec f g a = map f (iterate g a) := rfl theorem corec_eq (f : α → β) (g : α → α) (a : α) : corec f g a = f a :: corec f g (g a) := begin rw [corec_def, map_eq, head_iterate, tail_iterate], refl end theorem corec_id_id_eq_const (a : α) : corec id id a = const a := by rw [corec_def, map_id, iterate_id] theorem corec_id_f_eq_iterate (f : α → α) (a : α) : corec id f a = iterate f a := rfl end corec section corec' def corec' (f : α → β × α) : α → stream β := corec (prod.fst ∘ f) (prod.snd ∘ f) theorem corec'_eq (f : α → β × α) (a : α) : corec' f a = (f a).1 :: corec' f (f a).2 := corec_eq _ _ _ end corec' -- corec is also known as unfold def unfolds (g : α → β) (f : α → α) (a : α) : stream β := corec g f a theorem unfolds_eq (g : α → β) (f : α → α) (a : α) : unfolds g f a = g a :: unfolds g f (f a) := begin unfold unfolds, rw [corec_eq] end theorem nth_unfolds_head_tail : ∀ (n : nat) (s : stream α), nth n (unfolds head tail s) = nth n s := begin intro n, induction n with n' ih, {intro s, refl}, {intro s, rw [nth_succ, nth_succ, unfolds_eq, tail_cons, ih]} end theorem unfolds_head_eq : ∀ (s : stream α), unfolds head tail s = s := λ s, stream.ext (λ n, nth_unfolds_head_tail n s) def interleave (s₁ s₂ : stream α) : stream α := corec_on (s₁, s₂) (λ ⟨s₁, s₂⟩, head s₁) (λ ⟨s₁, s₂⟩, (s₂, tail s₁)) infix `⋈`:65 := interleave theorem interleave_eq (s₁ s₂ : stream α) : s₁ ⋈ s₂ = head s₁ :: head s₂ :: (tail s₁ ⋈ tail s₂) := begin unfold interleave corec_on, rw corec_eq, dsimp, rw corec_eq, refl end theorem tail_interleave (s₁ s₂ : stream α) : tail (s₁ ⋈ s₂) = s₂ ⋈ (tail s₁) := begin unfold interleave corec_on, rw corec_eq, refl end theorem interleave_tail_tail (s₁ s₂ : stream α) : tail s₁ ⋈ tail s₂ = tail (tail (s₁ ⋈ s₂)) := begin rw [interleave_eq s₁ s₂], refl end theorem nth_interleave_left : ∀ (n : nat) (s₁ s₂ : stream α), nth (2*n) (s₁ ⋈ s₂) = nth n s₁ | 0 s₁ s₂ := rfl | (succ n) s₁ s₂ := begin change nth (succ (succ (2*n))) (s₁ ⋈ s₂) = nth (succ n) s₁, rw [nth_succ, nth_succ, interleave_eq, tail_cons, tail_cons, nth_interleave_left], refl end theorem nth_interleave_right : ∀ (n : nat) (s₁ s₂ : stream α), nth (2*n+1) (s₁ ⋈ s₂) = nth n s₂ | 0 s₁ s₂ := rfl | (succ n) s₁ s₂ := begin change nth (succ (succ (2*n+1))) (s₁ ⋈ s₂) = nth (succ n) s₂, rw [nth_succ, nth_succ, interleave_eq, tail_cons, tail_cons, nth_interleave_right], refl end theorem mem_interleave_left {a : α} {s₁ : stream α} (s₂ : stream α) : a ∈ s₁ → a ∈ s₁ ⋈ s₂ := assume ⟨n, h⟩, exists.intro (2*n) (by rw [h, nth_interleave_left]) theorem mem_interleave_right {a : α} {s₁ : stream α} (s₂ : stream α) : a ∈ s₂ → a ∈ s₁ ⋈ s₂ := assume ⟨n, h⟩, exists.intro (2*n+1) (by rw [h, nth_interleave_right]) def even (s : stream α) : stream α := corec (λ s, head s) (λ s, tail (tail s)) s def odd (s : stream α) : stream α := even (tail s) theorem odd_eq (s : stream α) : odd s = even (tail s) := rfl theorem head_even (s : stream α) : head (even s) = head s := rfl theorem tail_even (s : stream α) : tail (even s) = even (tail (tail s)) := begin unfold even, rw corec_eq, refl end theorem even_cons_cons (a₁ a₂ : α) (s : stream α) : even (a₁ :: a₂ :: s) = a₁ :: even s := begin unfold even, rw corec_eq, refl end theorem even_tail (s : stream α) : even (tail s) = odd s := rfl theorem even_interleave (s₁ s₂ : stream α) : even (s₁ ⋈ s₂) = s₁ := eq_of_bisim (λ s₁' s₁, ∃ s₂, s₁' = even (s₁ ⋈ s₂)) (λ s₁' s₁ ⟨s₂, h₁⟩, begin rw h₁, constructor, {refl}, {exact ⟨tail s₂, by rw [interleave_eq, even_cons_cons, tail_cons]⟩} end) (exists.intro s₂ rfl) theorem interleave_even_odd (s₁ : stream α) : even s₁ ⋈ odd s₁ = s₁ := eq_of_bisim (λ s' s, s' = even s ⋈ odd s) (λ s' s (h : s' = even s ⋈ odd s), begin rw h, constructor, {refl}, {simp [odd_eq, odd_eq, tail_interleave, tail_even]} end) rfl theorem nth_even : ∀ (n : nat) (s : stream α), nth n (even s) = nth (2*n) s | 0 s := rfl | (succ n) s := begin change nth (succ n) (even s) = nth (succ (succ (2 * n))) s, rw [nth_succ, nth_succ, tail_even, nth_even], refl end theorem nth_odd : ∀ (n : nat) (s : stream α), nth n (odd s) = nth (2*n + 1) s := λ n s, begin rw [odd_eq, nth_even], refl end theorem mem_of_mem_even (a : α) (s : stream α) : a ∈ even s → a ∈ s := assume ⟨n, h⟩, exists.intro (2*n) (by rw [h, nth_even]) theorem mem_of_mem_odd (a : α) (s : stream α) : a ∈ odd s → a ∈ s := assume ⟨n, h⟩, exists.intro (2*n+1) (by rw [h, nth_odd]) def append_stream : list α → stream α → stream α | [] s := s | (list.cons a l) s := a :: append_stream l s theorem nil_append_stream (s : stream α) : append_stream [] s = s := rfl theorem cons_append_stream (a : α) (l : list α) (s : stream α) : append_stream (a::l) s = a :: append_stream l s := rfl infix `++ₛ`:65 := append_stream theorem append_append_stream : ∀ (l₁ l₂ : list α) (s : stream α), (l₁ ++ l₂) ++ₛ s = l₁ ++ₛ (l₂ ++ₛ s) | [] l₂ s := rfl | (list.cons a l₁) l₂ s := by rw [list.cons_append, cons_append_stream, cons_append_stream, append_append_stream] theorem map_append_stream (f : α → β) : ∀ (l : list α) (s : stream α), map f (l ++ₛ s) = list.map f l ++ₛ map f s | [] s := rfl | (list.cons a l) s := by rw [cons_append_stream, list.map_cons, map_cons, cons_append_stream, map_append_stream] theorem drop_append_stream : ∀ (l : list α) (s : stream α), drop l.length (l ++ₛ s) = s | [] s := by refl | (list.cons a l) s := by rw [list.length_cons, add_one, drop_succ, cons_append_stream, tail_cons, drop_append_stream] theorem append_stream_head_tail (s : stream α) : [head s] ++ₛ tail s = s := by rw [cons_append_stream, nil_append_stream, stream.eta] theorem mem_append_stream_right : ∀ {a : α} (l : list α) {s : stream α}, a ∈ s → a ∈ l ++ₛ s | a [] s h := h | a (list.cons b l) s h := have ih : a ∈ l ++ₛ s, from mem_append_stream_right l h, mem_cons_of_mem _ ih theorem mem_append_stream_left : ∀ {a : α} {l : list α} (s : stream α), a ∈ l → a ∈ l ++ₛ s | a [] s h := absurd h (list.not_mem_nil _) | a (list.cons b l) s h := or.elim (list.eq_or_mem_of_mem_cons h) (λ (aeqb : a = b), exists.intro 0 aeqb) (λ (ainl : a ∈ l), mem_cons_of_mem b (mem_append_stream_left s ainl)) def approx : nat → stream α → list α | 0 s := [] | (n+1) s := list.cons (head s) (approx n (tail s)) theorem approx_zero (s : stream α) : approx 0 s = [] := rfl theorem approx_succ (n : nat) (s : stream α) : approx (succ n) s = head s :: approx n (tail s) := rfl theorem nth_approx : ∀ (n : nat) (s : stream α), list.nth (approx (succ n) s) n = some (nth n s) | 0 s := rfl | (n+1) s := begin rw [approx_succ, add_one, list.nth, nth_approx], refl end theorem append_approx_drop : ∀ (n : nat) (s : stream α), append_stream (approx n s) (drop n s) = s := begin intro n, induction n with n' ih, {intro s, refl}, {intro s, rw [approx_succ, drop_succ, cons_append_stream, ih (tail s), stream.eta]} end -- Take theorem reduces a proof of equality of infinite streams to an -- induction over all their finite approximations. theorem take_theorem (s₁ s₂ : stream α) : (∀ (n : nat), approx n s₁ = approx n s₂) → s₁ = s₂ := begin intro h, apply stream.ext, intro n, induction n with n ih, { have aux := h 1, simp [approx] at aux, exact aux }, { have h₁ : some (nth (succ n) s₁) = some (nth (succ n) s₂), { rw [← nth_approx, ← nth_approx, h (succ (succ n))] }, injection h₁ } end -- auxiliary def for cycle corecursive def private def cycle_f : α × list α × α × list α → α | (v, _, _, _) := v -- auxiliary def for cycle corecursive def private def cycle_g : α × list α × α × list α → α × list α × α × list α | (v₁, [], v₀, l₀) := (v₀, l₀, v₀, l₀) | (v₁, list.cons v₂ l₂, v₀, l₀) := (v₂, l₂, v₀, l₀) private lemma cycle_g_cons (a : α) (a₁ : α) (l₁ : list α) (a₀ : α) (l₀ : list α) : cycle_g (a, a₁::l₁, a₀, l₀) = (a₁, l₁, a₀, l₀) := rfl def cycle : Π (l : list α), l ≠ [] → stream α | [] h := absurd rfl h | (list.cons a l) h := corec cycle_f cycle_g (a, l, a, l) theorem cycle_eq : ∀ (l : list α) (h : l ≠ []), cycle l h = l ++ₛ cycle l h | [] h := absurd rfl h | (list.cons a l) h := have gen : ∀ l' a', corec cycle_f cycle_g (a', l', a, l) = (a' :: l') ++ₛ corec cycle_f cycle_g (a, l, a, l), begin intro l', induction l' with a₁ l₁ ih, {intros, rw [corec_eq], refl}, {intros, rw [corec_eq, cycle_g_cons, ih a₁], refl} end, gen l a theorem mem_cycle {a : α} {l : list α} : ∀ (h : l ≠ []), a ∈ l → a ∈ cycle l h := assume h ainl, begin rw [cycle_eq], exact mem_append_stream_left _ ainl end theorem cycle_singleton (a : α) (h : [a] ≠ []) : cycle [a] h = const a := coinduction rfl (λ β fr ch, by rwa [cycle_eq, const_eq]) def tails (s : stream α) : stream (stream α) := corec id tail (tail s) theorem tails_eq (s : stream α) : tails s = tail s :: tails (tail s) := by unfold tails; rw [corec_eq]; refl theorem nth_tails : ∀ (n : nat) (s : stream α), nth n (tails s) = drop n (tail s) := begin intro n, induction n with n' ih, {intros, refl}, {intro s, rw [nth_succ, drop_succ, tails_eq, tail_cons, ih]} end theorem tails_eq_iterate (s : stream α) : tails s = iterate tail (tail s) := rfl def inits_core (l : list α) (s : stream α) : stream (list α) := corec_on (l, s) (λ ⟨a, b⟩, a) (λ p, match p with (l', s') := (l' ++ [head s'], tail s') end) def inits (s : stream α) : stream (list α) := inits_core [head s] (tail s) theorem inits_core_eq (l : list α) (s : stream α) : inits_core l s = l :: inits_core (l ++ [head s]) (tail s) := begin unfold inits_core corec_on, rw [corec_eq], refl end theorem tail_inits (s : stream α) : tail (inits s) = inits_core [head s, head (tail s)] (tail (tail s)) := begin unfold inits, rw inits_core_eq, refl end theorem inits_tail (s : stream α) : inits (tail s) = inits_core [head (tail s)] (tail (tail s)) := rfl theorem cons_nth_inits_core : ∀ (a : α) (n : nat) (l : list α) (s : stream α), a :: nth n (inits_core l s) = nth n (inits_core (a::l) s) := begin intros a n, induction n with n' ih, {intros, refl}, {intros l s, rw [nth_succ, inits_core_eq, tail_cons, ih, inits_core_eq (a::l) s], refl } end theorem nth_inits : ∀ (n : nat) (s : stream α), nth n (inits s) = approx (succ n) s := begin intro n, induction n with n' ih, {intros, refl}, {intros, rw [nth_succ, approx_succ, ← ih, tail_inits, inits_tail, cons_nth_inits_core]} end theorem inits_eq (s : stream α) : inits s = [head s] :: map (list.cons (head s)) (inits (tail s)) := begin apply stream.ext, intro n, cases n, {refl}, {rw [nth_inits, nth_succ, tail_cons, nth_map, nth_inits], refl} end theorem zip_inits_tails (s : stream α) : zip append_stream (inits s) (tails s) = const s := begin apply stream.ext, intro n, rw [nth_zip, nth_inits, nth_tails, nth_const, approx_succ, cons_append_stream, append_approx_drop, stream.eta] end def pure (a : α) : stream α := const a def apply (f : stream (α → β)) (s : stream α) : stream β := λ n, (nth n f) (nth n s) infix `⊛`:75 := apply -- input as \o* theorem identity (s : stream α) : pure id ⊛ s = s := rfl theorem composition (g : stream (β → δ)) (f : stream (α → β)) (s : stream α) : pure comp ⊛ g ⊛ f ⊛ s = g ⊛ (f ⊛ s) := rfl theorem homomorphism (f : α → β) (a : α) : pure f ⊛ pure a = pure (f a) := rfl theorem interchange (fs : stream (α → β)) (a : α) : fs ⊛ pure a = pure (λ f : α → β, f a) ⊛ fs := rfl theorem map_eq_apply (f : α → β) (s : stream α) : map f s = pure f ⊛ s := rfl def nats : stream nat := λ n, n theorem nth_nats (n : nat) : nth n nats = n := rfl theorem nats_eq : nats = 0 :: map succ nats := begin apply stream.ext, intro n, cases n, refl, rw [nth_succ], refl end end stream
416af155f10b69b9763d838850bddd62930acb74
9dc8cecdf3c4634764a18254e94d43da07142918
/src/group_theory/group_action/defs.lean
a11a76b7d6648999ac24e935f2bc389d1fe50fad
[ "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
33,842
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Yury Kudryashov -/ import algebra.group.type_tags import algebra.hom.group import algebra.opposites import logic.embedding /-! # Definitions of group actions This file defines a hierarchy of group action type-classes on top of the previously defined notation classes `has_smul` and its additive version `has_vadd`: * `mul_action M α` and its additive version `add_action G P` are typeclasses used for actions of multiplicative and additive monoids and groups; they extend notation classes `has_smul` and `has_vadd` that are defined in `algebra.group.defs`; * `distrib_mul_action M A` is a typeclass for an action of a multiplicative monoid on an additive monoid such that `a • (b + c) = a • b + a • c` and `a • 0 = 0`. The hierarchy is extended further by `module`, defined elsewhere. Also provided are typeclasses for faithful and transitive actions, and typeclasses regarding the interaction of different group actions, * `smul_comm_class M N α` and its additive version `vadd_comm_class M N α`; * `is_scalar_tower M N α` (no additive version). * `is_central_scalar M α` (no additive version). ## Notation - `a • b` is used as notation for `has_smul.smul a b`. - `a +ᵥ b` is used as notation for `has_vadd.vadd a b`. ## Implementation details This file should avoid depending on other parts of `group_theory`, to avoid import cycles. More sophisticated lemmas belong in `group_theory.group_action`. ## Tags group action -/ variables {M N G A B α β γ δ : Type*} open function (injective surjective) /-! ### Faithful actions -/ /-- Typeclass for faithful actions. -/ class has_faithful_vadd (G : Type*) (P : Type*) [has_vadd G P] : Prop := (eq_of_vadd_eq_vadd : ∀ {g₁ g₂ : G}, (∀ p : P, g₁ +ᵥ p = g₂ +ᵥ p) → g₁ = g₂) /-- Typeclass for faithful actions. -/ @[to_additive] class has_faithful_smul (M : Type*) (α : Type*) [has_smul M α] : Prop := (eq_of_smul_eq_smul : ∀ {m₁ m₂ : M}, (∀ a : α, m₁ • a = m₂ • a) → m₁ = m₂) export has_faithful_smul (eq_of_smul_eq_smul) has_faithful_vadd (eq_of_vadd_eq_vadd) @[to_additive] lemma smul_left_injective' [has_smul M α] [has_faithful_smul M α] : function.injective ((•) : M → α → α) := λ m₁ m₂ h, has_faithful_smul.eq_of_smul_eq_smul (congr_fun h) /-- See also `monoid.to_mul_action` and `mul_zero_class.to_smul_with_zero`. -/ @[priority 910, -- see Note [lower instance priority] to_additive "See also `add_monoid.to_add_action`"] instance has_mul.to_has_smul (α : Type*) [has_mul α] : has_smul α α := ⟨(*)⟩ @[simp, to_additive] lemma smul_eq_mul (α : Type*) [has_mul α] {a a' : α} : a • a' = a * a' := rfl /-- Type class for additive monoid actions. -/ @[ext, protect_proj] class add_action (G : Type*) (P : Type*) [add_monoid G] extends has_vadd G P := (zero_vadd : ∀ p : P, (0 : G) +ᵥ p = p) (add_vadd : ∀ (g₁ g₂ : G) (p : P), (g₁ + g₂) +ᵥ p = g₁ +ᵥ (g₂ +ᵥ p)) /-- Typeclass for multiplicative actions by monoids. This generalizes group actions. -/ @[ext, protect_proj, to_additive] class mul_action (α : Type*) (β : Type*) [monoid α] extends has_smul α β := (one_smul : ∀ b : β, (1 : α) • b = b) (mul_smul : ∀ (x y : α) (b : β), (x * y) • b = x • y • b) /-! ### (Pre)transitive action `M` acts pretransitively on `α` if for any `x y` there is `g` such that `g • x = y` (or `g +ᵥ x = y` for an additive action). A transitive action should furthermore have `α` nonempty. In this section we define typeclasses `mul_action.is_pretransitive` and `add_action.is_pretransitive` and provide `mul_action.exists_smul_eq`/`add_action.exists_vadd_eq`, `mul_action.surjective_smul`/`add_action.surjective_vadd` as public interface to access this property. We do not provide typeclasses `*_action.is_transitive`; users should assume `[mul_action.is_pretransitive M α] [nonempty α]` instead. -/ /-- `M` acts pretransitively on `α` if for any `x y` there is `g` such that `g +ᵥ x = y`. A transitive action should furthermore have `α` nonempty. -/ class add_action.is_pretransitive (M α : Type*) [has_vadd M α] : Prop := (exists_vadd_eq : ∀ x y : α, ∃ g : M, g +ᵥ x = y) /-- `M` acts pretransitively on `α` if for any `x y` there is `g` such that `g • x = y`. A transitive action should furthermore have `α` nonempty. -/ @[to_additive] class mul_action.is_pretransitive (M α : Type*) [has_smul M α] : Prop := (exists_smul_eq : ∀ x y : α, ∃ g : M, g • x = y) namespace mul_action variables (M) {α} [has_smul M α] [is_pretransitive M α] @[to_additive] lemma exists_smul_eq (x y : α) : ∃ m : M, m • x = y := is_pretransitive.exists_smul_eq x y @[to_additive] lemma surjective_smul (x : α) : surjective (λ c : M, c • x) := exists_smul_eq M x /-- The regular action of a group on itself is transitive. -/ @[to_additive "The regular action of a group on itself is transitive."] instance regular.is_pretransitive [group G] : is_pretransitive G G := ⟨λ x y, ⟨y * x⁻¹, inv_mul_cancel_right _ _⟩⟩ end mul_action /-! ### Scalar tower and commuting actions -/ /-- A typeclass mixin saying that two additive actions on the same space commute. -/ class vadd_comm_class (M N α : Type*) [has_vadd M α] [has_vadd N α] : Prop := (vadd_comm : ∀ (m : M) (n : N) (a : α), m +ᵥ (n +ᵥ a) = n +ᵥ (m +ᵥ a)) /-- A typeclass mixin saying that two multiplicative actions on the same space commute. -/ @[to_additive] class smul_comm_class (M N α : Type*) [has_smul M α] [has_smul N α] : Prop := (smul_comm : ∀ (m : M) (n : N) (a : α), m • n • a = n • m • a) export mul_action (mul_smul) add_action (add_vadd) smul_comm_class (smul_comm) vadd_comm_class (vadd_comm) /-- Frequently, we find ourselves wanting to express a bilinear map `M →ₗ[R] N →ₗ[R] P` or an equivalence between maps `(M →ₗ[R] N) ≃ₗ[R] (M' →ₗ[R] N')` where the maps have an associated ring `R`. Unfortunately, using definitions like these requires that `R` satisfy `comm_semiring R`, and not just `semiring R`. Using `M →ₗ[R] N →+ P` and `(M →ₗ[R] N) ≃+ (M' →ₗ[R] N')` avoids this problem, but throws away structure that is useful for when we _do_ have a commutative (semi)ring. To avoid making this compromise, we instead state these definitions as `M →ₗ[R] N →ₗ[S] P` or `(M →ₗ[R] N) ≃ₗ[S] (M' →ₗ[R] N')` and require `smul_comm_class S R` on the appropriate modules. When the caller has `comm_semiring R`, they can set `S = R` and `smul_comm_class_self` will populate the instance. If the caller only has `semiring R` they can still set either `R = ℕ` or `S = ℕ`, and `add_comm_monoid.nat_smul_comm_class` or `add_comm_monoid.nat_smul_comm_class'` will populate the typeclass, which is still sufficient to recover a `≃+` or `→+` structure. An example of where this is used is `linear_map.prod_equiv`. -/ library_note "bundled maps over different rings" /-- Commutativity of actions is a symmetric relation. This lemma can't be an instance because this would cause a loop in the instance search graph. -/ @[to_additive] lemma smul_comm_class.symm (M N α : Type*) [has_smul M α] [has_smul N α] [smul_comm_class M N α] : smul_comm_class N M α := ⟨λ a' a b, (smul_comm a a' b).symm⟩ /-- Commutativity of additive actions is a symmetric relation. This lemma can't be an instance because this would cause a loop in the instance search graph. -/ add_decl_doc vadd_comm_class.symm @[to_additive] instance smul_comm_class_self (M α : Type*) [comm_monoid M] [mul_action M α] : smul_comm_class M M α := ⟨λ a a' b, by rw [← mul_smul, mul_comm, mul_smul]⟩ /-- An instance of `vadd_assoc_class M N α` states that the additive action of `M` on `α` is determined by the additive actions of `M` on `N` and `N` on `α`. -/ class vadd_assoc_class (M N α : Type*) [has_vadd M N] [has_vadd N α] [has_vadd M α] : Prop := (vadd_assoc : ∀ (x : M) (y : N) (z : α), (x +ᵥ y) +ᵥ z = x +ᵥ (y +ᵥ z)) /-- An instance of `is_scalar_tower M N α` states that the multiplicative action of `M` on `α` is determined by the multiplicative actions of `M` on `N` and `N` on `α`. -/ @[to_additive] class is_scalar_tower (M N α : Type*) [has_smul M N] [has_smul N α] [has_smul M α] : Prop := (smul_assoc : ∀ (x : M) (y : N) (z : α), (x • y) • z = x • (y • z)) @[simp, to_additive] lemma smul_assoc {M N} [has_smul M N] [has_smul N α] [has_smul M α] [is_scalar_tower M N α] (x : M) (y : N) (z : α) : (x • y) • z = x • y • z := is_scalar_tower.smul_assoc x y z @[to_additive] instance semigroup.is_scalar_tower [semigroup α] : is_scalar_tower α α α := ⟨mul_assoc⟩ /-- A typeclass indicating that the right (aka `mul_opposite`) and left actions by `M` on `α` are equal, that is that `M` acts centrally on `α`. This can be thought of as a version of commutativity for `•`. -/ class is_central_scalar (M α : Type*) [has_smul M α] [has_smul Mᵐᵒᵖ α] : Prop := (op_smul_eq_smul : ∀ (m : M) (a : α), mul_opposite.op m • a = m • a) lemma is_central_scalar.unop_smul_eq_smul {M α : Type*} [has_smul M α] [has_smul Mᵐᵒᵖ α] [is_central_scalar M α] (m : Mᵐᵒᵖ) (a : α) : (mul_opposite.unop m) • a = m • a := mul_opposite.rec (by exact λ m, (is_central_scalar.op_smul_eq_smul _ _).symm) m export is_central_scalar (op_smul_eq_smul unop_smul_eq_smul) -- these instances are very low priority, as there is usually a faster way to find these instances @[priority 50] instance smul_comm_class.op_left [has_smul M α] [has_smul Mᵐᵒᵖ α] [is_central_scalar M α] [has_smul N α] [smul_comm_class M N α] : smul_comm_class Mᵐᵒᵖ N α := ⟨λ m n a, by rw [←unop_smul_eq_smul m (n • a), ←unop_smul_eq_smul m a, smul_comm]⟩ @[priority 50] instance smul_comm_class.op_right [has_smul M α] [has_smul N α] [has_smul Nᵐᵒᵖ α] [is_central_scalar N α] [smul_comm_class M N α] : smul_comm_class M Nᵐᵒᵖ α := ⟨λ m n a, by rw [←unop_smul_eq_smul n (m • a), ←unop_smul_eq_smul n a, smul_comm]⟩ @[priority 50] instance is_scalar_tower.op_left [has_smul M α] [has_smul Mᵐᵒᵖ α] [is_central_scalar M α] [has_smul M N] [has_smul Mᵐᵒᵖ N] [is_central_scalar M N] [has_smul N α] [is_scalar_tower M N α] : is_scalar_tower Mᵐᵒᵖ N α := ⟨λ m n a, by rw [←unop_smul_eq_smul m (n • a), ←unop_smul_eq_smul m n, smul_assoc]⟩ @[priority 50] instance is_scalar_tower.op_right [has_smul M α] [has_smul M N] [has_smul N α] [has_smul Nᵐᵒᵖ α] [is_central_scalar N α] [is_scalar_tower M N α] : is_scalar_tower M Nᵐᵒᵖ α := ⟨λ m n a, by rw [←unop_smul_eq_smul n a, ←unop_smul_eq_smul (m • n) a, mul_opposite.unop_smul, smul_assoc]⟩ namespace has_smul variables [has_smul M α] /-- Auxiliary definition for `has_smul.comp`, `mul_action.comp_hom`, `distrib_mul_action.comp_hom`, `module.comp_hom`, etc. -/ @[simp, to_additive /-" Auxiliary definition for `has_vadd.comp`, `add_action.comp_hom`, etc. "-/] def comp.smul (g : N → M) (n : N) (a : α) : α := g n • a variables (α) /-- An action of `M` on `α` and a function `N → M` induces an action of `N` on `α`. See note [reducible non-instances]. Since this is reducible, we make sure to go via `has_smul.comp.smul` to prevent typeclass inference unfolding too far. -/ @[reducible, to_additive /-" An additive action of `M` on `α` and a function `N → M` induces an additive action of `N` on `α` "-/] def comp (g : N → M) : has_smul N α := { smul := has_smul.comp.smul g } variables {α} /-- Given a tower of scalar actions `M → α → β`, if we use `has_smul.comp` to pull back both of `M`'s actions by a map `g : N → M`, then we obtain a new tower of scalar actions `N → α → β`. This cannot be an instance because it can cause infinite loops whenever the `has_smul` arguments are still metavariables. -/ @[priority 100, to_additive "Given a tower of additive actions `M → α → β`, if we use `has_smul.comp` to pull back both of `M`'s actions by a map `g : N → M`, then we obtain a new tower of scalar actions `N → α → β`. This cannot be an instance because it can cause infinite loops whenever the `has_smul` arguments are still metavariables."] lemma comp.is_scalar_tower [has_smul M β] [has_smul α β] [is_scalar_tower M α β] (g : N → M) : (by haveI := comp α g; haveI := comp β g; exact is_scalar_tower N α β) := by exact {smul_assoc := λ n, @smul_assoc _ _ _ _ _ _ _ (g n) } /-- This cannot be an instance because it can cause infinite loops whenever the `has_smul` arguments are still metavariables. -/ @[priority 100] lemma comp.smul_comm_class [has_smul β α] [smul_comm_class M β α] (g : N → M) : (by haveI := comp α g; exact smul_comm_class N β α) := by exact {smul_comm := λ n, @smul_comm _ _ _ _ _ _ (g n) } /-- This cannot be an instance because it can cause infinite loops whenever the `has_smul` arguments are still metavariables. -/ @[priority 100] lemma comp.smul_comm_class' [has_smul β α] [smul_comm_class β M α] (g : N → M) : (by haveI := comp α g; exact smul_comm_class β N α) := by exact {smul_comm := λ _ n, @smul_comm _ _ _ _ _ _ _ (g n) } end has_smul section /-- Note that the `smul_comm_class α β β` typeclass argument is usually satisfied by `algebra α β`. -/ @[to_additive, nolint to_additive_doc] lemma mul_smul_comm [has_mul β] [has_smul α β] [smul_comm_class α β β] (s : α) (x y : β) : x * (s • y) = s • (x * y) := (smul_comm s x y).symm /-- Note that the `is_scalar_tower α β β` typeclass argument is usually satisfied by `algebra α β`. -/ @[to_additive, nolint to_additive_doc] lemma smul_mul_assoc [has_mul β] [has_smul α β] [is_scalar_tower α β β] (r : α) (x y : β) : (r • x) * y = r • (x * y) := smul_assoc r x y @[to_additive] lemma smul_smul_smul_comm [has_smul α β] [has_smul α γ] [has_smul β δ] [has_smul α δ] [has_smul γ δ] [is_scalar_tower α β δ] [is_scalar_tower α γ δ] [smul_comm_class β γ δ] (a : α) (b : β) (c : γ) (d : δ) : (a • b) • (c • d) = (a • c) • b • d := by { rw [smul_assoc, smul_assoc, smul_comm b], apply_instance } variables [has_smul M α] @[to_additive] lemma commute.smul_right [has_mul α] [smul_comm_class M α α] [is_scalar_tower M α α] {a b : α} (h : commute a b) (r : M) : commute a (r • b) := (mul_smul_comm _ _ _).trans ((congr_arg _ h).trans $ (smul_mul_assoc _ _ _).symm) @[to_additive] lemma commute.smul_left [has_mul α] [smul_comm_class M α α] [is_scalar_tower M α α] {a b : α} (h : commute a b) (r : M) : commute (r • a) b := (h.symm.smul_right r).symm end section ite variables [has_smul M α] (p : Prop) [decidable p] @[to_additive] lemma ite_smul (a₁ a₂ : M) (b : α) : (ite p a₁ a₂) • b = ite p (a₁ • b) (a₂ • b) := by split_ifs; refl @[to_additive] lemma smul_ite (a : M) (b₁ b₂ : α) : a • (ite p b₁ b₂) = ite p (a • b₁) (a • b₂) := by split_ifs; refl end ite section variables [monoid M] [mul_action M α] @[to_additive] lemma smul_smul (a₁ a₂ : M) (b : α) : a₁ • a₂ • b = (a₁ * a₂) • b := (mul_smul _ _ _).symm variable (M) @[simp, to_additive] theorem one_smul (b : α) : (1 : M) • b = b := mul_action.one_smul _ /-- `has_smul` version of `one_mul_eq_id` -/ @[to_additive "`has_vadd` version of `zero_add_eq_id`"] lemma one_smul_eq_id : ((•) (1 : M) : α → α) = id := funext $ one_smul _ /-- `has_smul` version of `comp_mul_left` -/ @[to_additive "`has_vadd` version of `comp_add_left`"] lemma comp_smul_left (a₁ a₂ : M) : (•) a₁ ∘ (•) a₂ = ((•) (a₁ * a₂) : α → α) := funext $ λ _, (mul_smul _ _ _).symm variables {M} /-- Pullback a multiplicative action along an injective map respecting `•`. See note [reducible non-instances]. -/ @[reducible, to_additive "Pullback an additive action along an injective map respecting `+ᵥ`."] protected def function.injective.mul_action [has_smul M β] (f : β → α) (hf : injective f) (smul : ∀ (c : M) x, f (c • x) = c • f x) : mul_action M β := { smul := (•), one_smul := λ x, hf $ (smul _ _).trans $ one_smul _ (f x), mul_smul := λ c₁ c₂ x, hf $ by simp only [smul, mul_smul] } /-- Pushforward a multiplicative action along a surjective map respecting `•`. See note [reducible non-instances]. -/ @[reducible, to_additive "Pushforward an additive action along a surjective map respecting `+ᵥ`."] protected def function.surjective.mul_action [has_smul M β] (f : α → β) (hf : surjective f) (smul : ∀ (c : M) x, f (c • x) = c • f x) : mul_action M β := { smul := (•), one_smul := λ y, by { rcases hf y with ⟨x, rfl⟩, rw [← smul, one_smul] }, mul_smul := λ c₁ c₂ y, by { rcases hf y with ⟨x, rfl⟩, simp only [← smul, mul_smul] } } /-- Push forward the action of `R` on `M` along a compatible surjective map `f : R →* S`. See also `function.surjective.distrib_mul_action_left` and `function.surjective.module_left`. -/ @[reducible, to_additive "Push forward the action of `R` on `M` along a compatible surjective map `f : R →+ S`."] def function.surjective.mul_action_left {R S M : Type*} [monoid R] [mul_action R M] [monoid S] [has_smul S M] (f : R →* S) (hf : function.surjective f) (hsmul : ∀ c (x : M), f c • x = c • x) : mul_action S M := { smul := (•), one_smul := λ b, by rw [← f.map_one, hsmul, one_smul], mul_smul := hf.forall₂.mpr $ λ a b x, by simp only [← f.map_mul, hsmul, mul_smul] } section variables (M) /-- The regular action of a monoid on itself by left multiplication. This is promoted to a module by `semiring.to_module`. -/ @[priority 910, to_additive] -- see Note [lower instance priority] instance monoid.to_mul_action : mul_action M M := { smul := (*), one_smul := one_mul, mul_smul := mul_assoc } /-- The regular action of a monoid on itself by left addition. This is promoted to an `add_torsor` by `add_group_is_add_torsor`. -/ add_decl_doc add_monoid.to_add_action @[to_additive] instance is_scalar_tower.left : is_scalar_tower M M α := ⟨λ x y z, mul_smul x y z⟩ variables {M} /-- Note that the `is_scalar_tower M α α` and `smul_comm_class M α α` typeclass arguments are usually satisfied by `algebra M α`. -/ @[to_additive, nolint to_additive_doc] lemma smul_mul_smul [has_mul α] (r s : M) (x y : α) [is_scalar_tower M α α] [smul_comm_class M α α] : (r • x) * (s • y) = (r * s) • (x * y) := by rw [smul_mul_assoc, mul_smul_comm, ← smul_assoc, smul_eq_mul] end namespace mul_action variables (M α) /-- Embedding of `α` into functions `M → α` induced by a multiplicative action of `M` on `α`. -/ @[to_additive] def to_fun : α ↪ (M → α) := ⟨λ y x, x • y, λ y₁ y₂ H, one_smul M y₁ ▸ one_smul M y₂ ▸ by convert congr_fun H 1⟩ /-- Embedding of `α` into functions `M → α` induced by an additive action of `M` on `α`. -/ add_decl_doc add_action.to_fun variables {M α} @[simp, to_additive] lemma to_fun_apply (x : M) (y : α) : mul_action.to_fun M α y x = x • y := rfl variable (α) /-- A multiplicative action of `M` on `α` and a monoid homomorphism `N → M` induce a multiplicative action of `N` on `α`. See note [reducible non-instances]. -/ @[reducible, to_additive] def comp_hom [monoid N] (g : N →* M) : mul_action N α := { smul := has_smul.comp.smul g, one_smul := by simp [g.map_one, mul_action.one_smul], mul_smul := by simp [g.map_mul, mul_action.mul_smul] } /-- An additive action of `M` on `α` and an additive monoid homomorphism `N → M` induce an additive action of `N` on `α`. See note [reducible non-instances]. -/ add_decl_doc add_action.comp_hom end mul_action end section compatible_scalar @[simp, to_additive] lemma smul_one_smul {M} (N) [monoid N] [has_smul M N] [mul_action N α] [has_smul M α] [is_scalar_tower M N α] (x : M) (y : α) : (x • (1 : N)) • y = x • y := by rw [smul_assoc, one_smul] @[simp, to_additive] lemma smul_one_mul {M N} [mul_one_class N] [has_smul M N] [is_scalar_tower M N N] (x : M) (y : N) : (x • 1) * y = x • y := by rw [smul_mul_assoc, one_mul] @[simp, to_additive] lemma mul_smul_one {M N} [mul_one_class N] [has_smul M N] [smul_comm_class M N N] (x : M) (y : N) : y * (x • 1) = x • y := by rw [← smul_eq_mul, ← smul_comm, smul_eq_mul, mul_one] @[to_additive] lemma is_scalar_tower.of_smul_one_mul {M N} [monoid N] [has_smul M N] (h : ∀ (x : M) (y : N), (x • (1 : N)) * y = x • y) : is_scalar_tower M N N := ⟨λ x y z, by rw [← h, smul_eq_mul, mul_assoc, h, smul_eq_mul]⟩ @[to_additive] lemma smul_comm_class.of_mul_smul_one {M N} [monoid N] [has_smul M N] (H : ∀ (x : M) (y : N), y * (x • (1 : N)) = x • y) : smul_comm_class M N N := ⟨λ x y z, by rw [← H x z, smul_eq_mul, ← H, smul_eq_mul, mul_assoc]⟩ end compatible_scalar /-- Typeclass for multiplicative actions on additive structures. This generalizes group modules. -/ @[ext] class distrib_mul_action (M : Type*) (A : Type*) [monoid M] [add_monoid A] extends mul_action M A := (smul_add : ∀(r : M) (x y : A), r • (x + y) = r • x + r • y) (smul_zero : ∀(r : M), r • (0 : A) = 0) section variables [monoid M] [add_monoid A] [distrib_mul_action M A] theorem smul_add (a : M) (b₁ b₂ : A) : a • (b₁ + b₂) = a • b₁ + a • b₂ := distrib_mul_action.smul_add _ _ _ @[simp] theorem smul_zero (a : M) : a • (0 : A) = 0 := distrib_mul_action.smul_zero _ /-- Pullback a distributive multiplicative action along an injective additive monoid homomorphism. See note [reducible non-instances]. -/ @[reducible] protected def function.injective.distrib_mul_action [add_monoid B] [has_smul M B] (f : B →+ A) (hf : injective f) (smul : ∀ (c : M) x, f (c • x) = c • f x) : distrib_mul_action M B := { smul := (•), smul_add := λ c x y, hf $ by simp only [smul, f.map_add, smul_add], smul_zero := λ c, hf $ by simp only [smul, f.map_zero, smul_zero], .. hf.mul_action f smul } /-- Pushforward a distributive multiplicative action along a surjective additive monoid homomorphism. See note [reducible non-instances]. -/ @[reducible] protected def function.surjective.distrib_mul_action [add_monoid B] [has_smul M B] (f : A →+ B) (hf : surjective f) (smul : ∀ (c : M) x, f (c • x) = c • f x) : distrib_mul_action M B := { smul := (•), smul_add := λ c x y, by { rcases hf x with ⟨x, rfl⟩, rcases hf y with ⟨y, rfl⟩, simp only [smul_add, ← smul, ← f.map_add] }, smul_zero := λ c, by simp only [← f.map_zero, ← smul, smul_zero], .. hf.mul_action f smul } /-- Push forward the action of `R` on `M` along a compatible surjective map `f : R →* S`. See also `function.surjective.mul_action_left` and `function.surjective.module_left`. -/ @[reducible] def function.surjective.distrib_mul_action_left {R S M : Type*} [monoid R] [add_monoid M] [distrib_mul_action R M] [monoid S] [has_smul S M] (f : R →* S) (hf : function.surjective f) (hsmul : ∀ c (x : M), f c • x = c • x) : distrib_mul_action S M := { smul := (•), smul_zero := hf.forall.mpr $ λ c, by rw [hsmul, smul_zero], smul_add := hf.forall.mpr $ λ c x y, by simp only [hsmul, smul_add], .. hf.mul_action_left f hsmul } variable (A) /-- Compose a `distrib_mul_action` with a `monoid_hom`, with action `f r' • m`. See note [reducible non-instances]. -/ @[reducible] def distrib_mul_action.comp_hom [monoid N] (f : N →* M) : distrib_mul_action N A := { smul := has_smul.comp.smul f, smul_zero := λ x, smul_zero (f x), smul_add := λ x, smul_add (f x), .. mul_action.comp_hom A f } /-- Each element of the monoid defines a additive monoid homomorphism. -/ @[simps] def distrib_mul_action.to_add_monoid_hom (x : M) : A →+ A := { to_fun := (•) x, map_zero' := smul_zero x, map_add' := smul_add x } variables (M) /-- Each element of the monoid defines an additive monoid homomorphism. -/ @[simps] def distrib_mul_action.to_add_monoid_End : M →* add_monoid.End A := { to_fun := distrib_mul_action.to_add_monoid_hom A, map_one' := add_monoid_hom.ext $ one_smul M, map_mul' := λ x y, add_monoid_hom.ext $ mul_smul x y } instance add_monoid.nat_smul_comm_class : smul_comm_class ℕ M A := { smul_comm := λ n x y, ((distrib_mul_action.to_add_monoid_hom A x).map_nsmul y n).symm } -- `smul_comm_class.symm` is not registered as an instance, as it would cause a loop instance add_monoid.nat_smul_comm_class' : smul_comm_class M ℕ A := smul_comm_class.symm _ _ _ end section variables [monoid M] [add_group A] [distrib_mul_action M A] instance add_group.int_smul_comm_class : smul_comm_class ℤ M A := { smul_comm := λ n x y, ((distrib_mul_action.to_add_monoid_hom A x).map_zsmul y n).symm } -- `smul_comm_class.symm` is not registered as an instance, as it would cause a loop instance add_group.int_smul_comm_class' : smul_comm_class M ℤ A := smul_comm_class.symm _ _ _ @[simp] theorem smul_neg (r : M) (x : A) : r • (-x) = -(r • x) := eq_neg_of_add_eq_zero_left $ by rw [← smul_add, neg_add_self, smul_zero] theorem smul_sub (r : M) (x y : A) : r • (x - y) = r • x - r • y := by rw [sub_eq_add_neg, sub_eq_add_neg, smul_add, smul_neg] end /-- Typeclass for multiplicative actions on multiplicative structures. This generalizes conjugation actions. -/ @[ext] class mul_distrib_mul_action (M : Type*) (A : Type*) [monoid M] [monoid A] extends mul_action M A := (smul_mul : ∀ (r : M) (x y : A), r • (x * y) = (r • x) * (r • y)) (smul_one : ∀ (r : M), r • (1 : A) = 1) export mul_distrib_mul_action (smul_one) section variables [monoid M] [monoid A] [mul_distrib_mul_action M A] theorem smul_mul' (a : M) (b₁ b₂ : A) : a • (b₁ * b₂) = (a • b₁) * (a • b₂) := mul_distrib_mul_action.smul_mul _ _ _ /-- Pullback a multiplicative distributive multiplicative action along an injective monoid homomorphism. See note [reducible non-instances]. -/ @[reducible] protected def function.injective.mul_distrib_mul_action [monoid B] [has_smul M B] (f : B →* A) (hf : injective f) (smul : ∀ (c : M) x, f (c • x) = c • f x) : mul_distrib_mul_action M B := { smul := (•), smul_mul := λ c x y, hf $ by simp only [smul, f.map_mul, smul_mul'], smul_one := λ c, hf $ by simp only [smul, f.map_one, smul_one], .. hf.mul_action f smul } /-- Pushforward a multiplicative distributive multiplicative action along a surjective monoid homomorphism. See note [reducible non-instances]. -/ @[reducible] protected def function.surjective.mul_distrib_mul_action [monoid B] [has_smul M B] (f : A →* B) (hf : surjective f) (smul : ∀ (c : M) x, f (c • x) = c • f x) : mul_distrib_mul_action M B := { smul := (•), smul_mul := λ c x y, by { rcases hf x with ⟨x, rfl⟩, rcases hf y with ⟨y, rfl⟩, simp only [smul_mul', ← smul, ← f.map_mul] }, smul_one := λ c, by simp only [← f.map_one, ← smul, smul_one], .. hf.mul_action f smul } variable (A) /-- Compose a `mul_distrib_mul_action` with a `monoid_hom`, with action `f r' • m`. See note [reducible non-instances]. -/ @[reducible] def mul_distrib_mul_action.comp_hom [monoid N] (f : N →* M) : mul_distrib_mul_action N A := { smul := has_smul.comp.smul f, smul_one := λ x, smul_one (f x), smul_mul := λ x, smul_mul' (f x), .. mul_action.comp_hom A f } /-- Scalar multiplication by `r` as a `monoid_hom`. -/ def mul_distrib_mul_action.to_monoid_hom (r : M) : A →* A := { to_fun := (•) r, map_one' := smul_one r, map_mul' := smul_mul' r } variable {A} @[simp] lemma mul_distrib_mul_action.to_monoid_hom_apply (r : M) (x : A) : mul_distrib_mul_action.to_monoid_hom A r x = r • x := rfl variables (M A) /-- Each element of the monoid defines a monoid homomorphism. -/ @[simps] def mul_distrib_mul_action.to_monoid_End : M →* monoid.End A := { to_fun := mul_distrib_mul_action.to_monoid_hom A, map_one' := monoid_hom.ext $ one_smul M, map_mul' := λ x y, monoid_hom.ext $ mul_smul x y } end section variables [monoid M] [group A] [mul_distrib_mul_action M A] @[simp] theorem smul_inv' (r : M) (x : A) : r • (x⁻¹) = (r • x)⁻¹ := (mul_distrib_mul_action.to_monoid_hom A r).map_inv x theorem smul_div' (r : M) (x y : A) : r • (x / y) = (r • x) / (r • y) := map_div (mul_distrib_mul_action.to_monoid_hom A r) x y end variable (α) /-- The monoid of endomorphisms. Note that this is generalized by `category_theory.End` to categories other than `Type u`. -/ protected def function.End := α → α instance : monoid (function.End α) := { one := id, mul := (∘), mul_assoc := λ f g h, rfl, mul_one := λ f, rfl, one_mul := λ f, rfl, } instance : inhabited (function.End α) := ⟨1⟩ variable {α} /-- The tautological action by `function.End α` on `α`. This is generalized to bundled endomorphisms by: * `equiv.perm.apply_mul_action` * `add_monoid.End.apply_distrib_mul_action` * `add_aut.apply_distrib_mul_action` * `mul_aut.apply_mul_distrib_mul_action` * `ring_hom.apply_distrib_mul_action` * `linear_equiv.apply_distrib_mul_action` * `linear_map.apply_module` * `ring_hom.apply_mul_semiring_action` * `alg_equiv.apply_mul_semiring_action` -/ instance function.End.apply_mul_action : mul_action (function.End α) α := { smul := ($), one_smul := λ _, rfl, mul_smul := λ _ _ _, rfl } @[simp] lemma function.End.smul_def (f : function.End α) (a : α) : f • a = f a := rfl /-- `function.End.apply_mul_action` is faithful. -/ instance function.End.apply_has_faithful_smul : has_faithful_smul (function.End α) α := ⟨λ x y, funext⟩ /-- The tautological action by `add_monoid.End α` on `α`. This generalizes `function.End.apply_mul_action`. -/ instance add_monoid.End.apply_distrib_mul_action [add_monoid α] : distrib_mul_action (add_monoid.End α) α := { smul := ($), smul_zero := add_monoid_hom.map_zero, smul_add := add_monoid_hom.map_add, one_smul := λ _, rfl, mul_smul := λ _ _ _, rfl } @[simp] lemma add_monoid.End.smul_def [add_monoid α] (f : add_monoid.End α) (a : α) : f • a = f a := rfl /-- `add_monoid.End.apply_distrib_mul_action` is faithful. -/ instance add_monoid.End.apply_has_faithful_smul [add_monoid α] : has_faithful_smul (add_monoid.End α) α := ⟨add_monoid_hom.ext⟩ /-- The monoid hom representing a monoid action. When `M` is a group, see `mul_action.to_perm_hom`. -/ def mul_action.to_End_hom [monoid M] [mul_action M α] : M →* function.End α := { to_fun := (•), map_one' := funext (one_smul M), map_mul' := λ x y, funext (mul_smul x y) } /-- The monoid action induced by a monoid hom to `function.End α` See note [reducible non-instances]. -/ @[reducible] def mul_action.of_End_hom [monoid M] (f : M →* function.End α) : mul_action M α := mul_action.comp_hom α f /-- The tautological additive action by `additive (function.End α)` on `α`. -/ instance add_action.function_End : add_action (additive (function.End α)) α := { vadd := ($), zero_vadd := λ _, rfl, add_vadd := λ _ _ _, rfl } /-- The additive monoid hom representing an additive monoid action. When `M` is a group, see `add_action.to_perm_hom`. -/ def add_action.to_End_hom [add_monoid M] [add_action M α] : M →+ additive (function.End α) := { to_fun := (+ᵥ), map_zero' := funext (zero_vadd M), map_add' := λ x y, funext (add_vadd x y) } /-- The additive action induced by a hom to `additive (function.End α)` See note [reducible non-instances]. -/ @[reducible] def add_action.of_End_hom [add_monoid M] (f : M →+ additive (function.End α)) : add_action M α := add_action.comp_hom α f /-! ### `additive`, `multiplicative` -/ section open additive multiplicative instance additive.has_vadd [has_smul α β] : has_vadd (additive α) β := ⟨λ a, (•) (to_mul a)⟩ instance multiplicative.has_smul [has_vadd α β] : has_smul (multiplicative α) β := ⟨λ a, (+ᵥ) (to_add a)⟩ @[simp] lemma to_mul_smul [has_smul α β] (a) (b : β) : (to_mul a : α) • b = a +ᵥ b := rfl @[simp] lemma of_mul_vadd [has_smul α β] (a : α) (b : β) : of_mul a +ᵥ b = a • b := rfl @[simp] lemma to_add_vadd [has_vadd α β] (a) (b : β) : (to_add a : α) +ᵥ b = a • b := rfl @[simp] lemma of_add_smul [has_vadd α β] (a : α) (b : β) : of_add a • b = a +ᵥ b := rfl instance additive.add_action [monoid α] [mul_action α β] : add_action (additive α) β := { zero_vadd := mul_action.one_smul, add_vadd := mul_action.mul_smul } instance multiplicative.mul_action [add_monoid α] [add_action α β] : mul_action (multiplicative α) β := { one_smul := add_action.zero_vadd, mul_smul := add_action.add_vadd } instance additive.add_action_is_pretransitive [monoid α] [mul_action α β] [mul_action.is_pretransitive α β] : add_action.is_pretransitive (additive α) β := ⟨@mul_action.exists_smul_eq α _ _ _⟩ instance multiplicative.add_action_is_pretransitive [add_monoid α] [add_action α β] [add_action.is_pretransitive α β] : mul_action.is_pretransitive (multiplicative α) β := ⟨@add_action.exists_vadd_eq α _ _ _⟩ instance additive.vadd_comm_class [has_smul α γ] [has_smul β γ] [smul_comm_class α β γ] : vadd_comm_class (additive α) (additive β) γ := ⟨@smul_comm α β _ _ _ _⟩ instance multiplicative.smul_comm_class [has_vadd α γ] [has_vadd β γ] [vadd_comm_class α β γ] : smul_comm_class (multiplicative α) (multiplicative β) γ := ⟨@vadd_comm α β _ _ _ _⟩ end
8271076700effb7382dcf9fc068050c6644eb62b
4950bf76e5ae40ba9f8491647d0b6f228ddce173
/src/algebra/opposites.lean
8f63e89ceaeb912159d7c230e9686f20722caac5
[ "Apache-2.0" ]
permissive
ntzwq/mathlib
ca50b21079b0a7c6781c34b62199a396dd00cee2
36eec1a98f22df82eaccd354a758ef8576af2a7f
refs/heads/master
1,675,193,391,478
1,607,822,996,000
1,607,822,996,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,661
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import data.opposite import algebra.field import group_theory.group_action.defs import data.equiv.mul_add /-! # Algebraic operations on `αᵒᵖ` -/ namespace opposite universes u variables (α : Type u) instance [has_add α] : has_add (opposite α) := { add := λ x y, op (unop x + unop y) } instance [add_semigroup α] : add_semigroup (opposite α) := { add_assoc := λ x y z, unop_injective $ add_assoc (unop x) (unop y) (unop z), .. opposite.has_add α } instance [add_left_cancel_semigroup α] : add_left_cancel_semigroup (opposite α) := { add_left_cancel := λ x y z H, unop_injective $ add_left_cancel $ op_injective H, .. opposite.add_semigroup α } instance [add_right_cancel_semigroup α] : add_right_cancel_semigroup (opposite α) := { add_right_cancel := λ x y z H, unop_injective $ add_right_cancel $ op_injective H, .. opposite.add_semigroup α } instance [add_comm_semigroup α] : add_comm_semigroup (opposite α) := { add_comm := λ x y, unop_injective $ add_comm (unop x) (unop y), .. opposite.add_semigroup α } instance [has_zero α] : has_zero (opposite α) := { zero := op 0 } instance [nontrivial α] : nontrivial (opposite α) := let ⟨x, y, h⟩ := exists_pair_ne α in nontrivial_of_ne (op x) (op y) (op_injective.ne h) section local attribute [reducible] opposite @[simp] lemma unop_eq_zero_iff [has_zero α] (a : αᵒᵖ) : a.unop = (0 : α) ↔ a = (0 : αᵒᵖ) := iff.refl _ @[simp] lemma op_eq_zero_iff [has_zero α] (a : α) : op a = (0 : αᵒᵖ) ↔ a = (0 : α) := iff.refl _ end instance [add_monoid α] : add_monoid (opposite α) := { zero_add := λ x, unop_injective $ zero_add $ unop x, add_zero := λ x, unop_injective $ add_zero $ unop x, .. opposite.add_semigroup α, .. opposite.has_zero α } instance [add_comm_monoid α] : add_comm_monoid (opposite α) := { .. opposite.add_monoid α, .. opposite.add_comm_semigroup α } instance [has_neg α] : has_neg (opposite α) := { neg := λ x, op $ -(unop x) } instance [add_group α] : add_group (opposite α) := { add_left_neg := λ x, unop_injective $ add_left_neg $ unop x, .. opposite.add_monoid α, .. opposite.has_neg α } instance [add_comm_group α] : add_comm_group (opposite α) := { .. opposite.add_group α, .. opposite.add_comm_monoid α } instance [has_mul α] : has_mul (opposite α) := { mul := λ x y, op (unop y * unop x) } instance [semigroup α] : semigroup (opposite α) := { mul_assoc := λ x y z, unop_injective $ eq.symm $ mul_assoc (unop z) (unop y) (unop x), .. opposite.has_mul α } instance [right_cancel_semigroup α] : left_cancel_semigroup (opposite α) := { mul_left_cancel := λ x y z H, unop_injective $ mul_right_cancel $ op_injective H, .. opposite.semigroup α } instance [left_cancel_semigroup α] : right_cancel_semigroup (opposite α) := { mul_right_cancel := λ x y z H, unop_injective $ mul_left_cancel $ op_injective H, .. opposite.semigroup α } instance [comm_semigroup α] : comm_semigroup (opposite α) := { mul_comm := λ x y, unop_injective $ mul_comm (unop y) (unop x), .. opposite.semigroup α } instance [has_one α] : has_one (opposite α) := { one := op 1 } section local attribute [reducible] opposite @[simp] lemma unop_eq_one_iff [has_one α] (a : αᵒᵖ) : a.unop = 1 ↔ a = 1 := iff.refl _ @[simp] lemma op_eq_one_iff [has_one α] (a : α) : op a = 1 ↔ a = 1 := iff.refl _ end instance [monoid α] : monoid (opposite α) := { one_mul := λ x, unop_injective $ mul_one $ unop x, mul_one := λ x, unop_injective $ one_mul $ unop x, .. opposite.semigroup α, .. opposite.has_one α } instance [comm_monoid α] : comm_monoid (opposite α) := { .. opposite.monoid α, .. opposite.comm_semigroup α } instance [has_inv α] : has_inv (opposite α) := { inv := λ x, op $ (unop x)⁻¹ } instance [group α] : group (opposite α) := { mul_left_inv := λ x, unop_injective $ mul_inv_self $ unop x, .. opposite.monoid α, .. opposite.has_inv α } instance [comm_group α] : comm_group (opposite α) := { .. opposite.group α, .. opposite.comm_monoid α } instance [distrib α] : distrib (opposite α) := { left_distrib := λ x y z, unop_injective $ add_mul (unop y) (unop z) (unop x), right_distrib := λ x y z, unop_injective $ mul_add (unop z) (unop x) (unop y), .. opposite.has_add α, .. opposite.has_mul α } instance [semiring α] : semiring (opposite α) := { zero_mul := λ x, unop_injective $ mul_zero $ unop x, mul_zero := λ x, unop_injective $ zero_mul $ unop x, .. opposite.add_comm_monoid α, .. opposite.monoid α, .. opposite.distrib α } instance [ring α] : ring (opposite α) := { .. opposite.add_comm_group α, .. opposite.monoid α, .. opposite.semiring α } instance [comm_ring α] : comm_ring (opposite α) := { .. opposite.ring α, .. opposite.comm_semigroup α } instance [integral_domain α] : integral_domain (opposite α) := { eq_zero_or_eq_zero_of_mul_eq_zero := λ x y (H : op (_ * _) = op (0:α)), or.cases_on (eq_zero_or_eq_zero_of_mul_eq_zero $ op_injective H) (λ hy, or.inr $ unop_injective $ hy) (λ hx, or.inl $ unop_injective $ hx), .. opposite.comm_ring α, .. opposite.nontrivial α } instance [field α] : field (opposite α) := { mul_inv_cancel := λ x hx, unop_injective $ inv_mul_cancel $ λ hx', hx $ unop_injective hx', inv_zero := unop_injective inv_zero, .. opposite.comm_ring α, .. opposite.has_inv α, .. opposite.nontrivial α } instance (R : Type*) [has_scalar R α] : has_scalar R (opposite α) := { smul := λ c x, op (c • unop x) } instance (R : Type*) [monoid R] [mul_action R α] : mul_action R (opposite α) := { one_smul := λ x, unop_injective $ one_smul R (unop x), mul_smul := λ r₁ r₂ x, unop_injective $ mul_smul r₁ r₂ (unop x), ..opposite.has_scalar α R } instance (R : Type*) [monoid R] [add_monoid α] [distrib_mul_action R α] : distrib_mul_action R (opposite α) := { smul_add := λ r x₁ x₂, unop_injective $ smul_add r (unop x₁) (unop x₂), smul_zero := λ r, unop_injective $ smul_zero r, ..opposite.mul_action α R } @[simp] lemma op_zero [has_zero α] : op (0 : α) = 0 := rfl @[simp] lemma unop_zero [has_zero α] : unop (0 : αᵒᵖ) = 0 := rfl @[simp] lemma op_one [has_one α] : op (1 : α) = 1 := rfl @[simp] lemma unop_one [has_one α] : unop (1 : αᵒᵖ) = 1 := rfl variable {α} @[simp] lemma op_add [has_add α] (x y : α) : op (x + y) = op x + op y := rfl @[simp] lemma unop_add [has_add α] (x y : αᵒᵖ) : unop (x + y) = unop x + unop y := rfl @[simp] lemma op_neg [has_neg α] (x : α) : op (-x) = -op x := rfl @[simp] lemma unop_neg [has_neg α] (x : αᵒᵖ) : unop (-x) = -unop x := rfl @[simp] lemma op_mul [has_mul α] (x y : α) : op (x * y) = op y * op x := rfl @[simp] lemma unop_mul [has_mul α] (x y : αᵒᵖ) : unop (x * y) = unop y * unop x := rfl @[simp] lemma op_inv [has_inv α] (x : α) : op (x⁻¹) = (op x)⁻¹ := rfl @[simp] lemma unop_inv [has_inv α] (x : αᵒᵖ) : unop (x⁻¹) = (unop x)⁻¹ := rfl @[simp] lemma op_sub [add_group α] (x y : α) : op (x - y) = op x - op y := rfl @[simp] lemma unop_sub [add_group α] (x y : αᵒᵖ) : unop (x - y) = unop x - unop y := rfl @[simp] lemma op_smul {R : Type*} [has_scalar R α] (c : R) (a : α) : op (c • a) = c • op a := rfl @[simp] lemma unop_smul {R : Type*} [has_scalar R α] (c : R) (a : αᵒᵖ) : unop (c • a) = c • unop a := rfl /-- The function `op` is an additive equivalence. -/ def op_add_equiv [has_add α] : α ≃+ αᵒᵖ := { map_add' := λ a b, rfl, .. equiv_to_opposite } @[simp] lemma coe_op_add_equiv [has_add α] : (op_add_equiv : α → αᵒᵖ) = op := rfl @[simp] lemma coe_op_add_equiv_symm [has_add α] : (op_add_equiv.symm : αᵒᵖ → α) = unop := rfl @[simp] lemma op_add_equiv_to_equiv [has_add α] : (op_add_equiv : α ≃+ αᵒᵖ).to_equiv = equiv_to_opposite := rfl end opposite open opposite /-- A ring homomorphism `f : R →+* S` such that `f x` commutes with `f y` for all `x, y` defines a ring homomorphism to `Sᵒᵖ`. -/ def ring_hom.to_opposite {R S : Type*} [semiring R] [semiring S] (f : R →+* S) (hf : ∀ x y, commute (f x) (f y)) : R →+* Sᵒᵖ := { map_one' := congr_arg op f.map_one, map_mul' := λ x y, by simp [(hf x y).eq], .. (opposite.op_add_equiv : S ≃+ Sᵒᵖ).to_add_monoid_hom.comp ↑f } @[simp] lemma ring_hom.coe_to_opposite {R S : Type*} [semiring R] [semiring S] (f : R →+* S) (hf : ∀ x y, commute (f x) (f y)) : ⇑(f.to_opposite hf) = op ∘ f := rfl
75ddec6eb6bc18baecd332b6253933fb19fee600
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/data/vector2.lean
52dd6f0a79fd1e445c12067aadaab5e9f85e6ee0
[ "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
10,894
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro Additional theorems about the `vector` type. -/ import data.vector import data.list.nodup import data.list.of_fn import control.applicative universes u variables {n : ℕ} namespace vector variables {α : Type*} attribute [simp] head_cons tail_cons instance [inhabited α] : inhabited (vector α n) := ⟨of_fn (λ _, default α)⟩ theorem to_list_injective : function.injective (@to_list α n) := subtype.val_injective @[simp] theorem cons_val (a : α) : ∀ (v : vector α n), (a :: v).val = a :: v.val | ⟨_, _⟩ := rfl @[simp] theorem cons_head (a : α) : ∀ (v : vector α n), (a :: v).head = a | ⟨_, _⟩ := rfl @[simp] theorem cons_tail (a : α) : ∀ (v : vector α n), (a :: v).tail = v | ⟨_, _⟩ := rfl @[simp] theorem to_list_of_fn : ∀ {n} (f : fin n → α), to_list (of_fn f) = list.of_fn f | 0 f := rfl | (n+1) f := by rw [of_fn, list.of_fn_succ, to_list_cons, to_list_of_fn] @[simp] theorem mk_to_list : ∀ (v : vector α n) h, (⟨to_list v, h⟩ : vector α n) = v | ⟨l, h₁⟩ h₂ := rfl @[simp] lemma to_list_map {β : Type*} (v : vector α n) (f : α → β) : (v.map f).to_list = v.to_list.map f := by cases v; refl theorem nth_eq_nth_le : ∀ (v : vector α n) (i), nth v i = v.to_list.nth_le i.1 (by rw to_list_length; exact i.2) | ⟨l, h⟩ i := rfl @[simp] lemma nth_map {β : Type*} (v : vector α n) (f : α → β) (i : fin n) : (v.map f).nth i = f (v.nth i) := by simp [nth_eq_nth_le] @[simp] theorem nth_of_fn {n} (f : fin n → α) (i) : nth (of_fn f) i = f i := by rw [nth_eq_nth_le, ← list.nth_le_of_fn f]; congr; apply to_list_of_fn @[simp] theorem of_fn_nth (v : vector α n) : of_fn (nth v) = v := begin rcases v with ⟨l, rfl⟩, apply to_list_injective, change nth ⟨l, eq.refl _⟩ with λ i, nth ⟨l, rfl⟩ i, simpa only [to_list_of_fn] using list.of_fn_nth_le _ end @[simp] theorem nth_tail : ∀ (v : vector α n.succ) (i : fin n), nth (tail v) i = nth v i.succ | ⟨a::l, e⟩ ⟨i, h⟩ := by simp [nth_eq_nth_le]; refl @[simp] theorem tail_val : ∀ (v : vector α n.succ), v.tail.val = v.val.tail | ⟨a::l, e⟩ := rfl @[simp] theorem tail_of_fn {n : ℕ} (f : fin n.succ → α) : tail (of_fn f) = of_fn (λ i, f i.succ) := (of_fn_nth _).symm.trans $ by congr; funext i; simp lemma mem_iff_nth {a : α} {v : vector α n} : a ∈ v.to_list ↔ ∃ i, v.nth i = a := by simp only [list.mem_iff_nth_le, fin.exists_iff, vector.nth_eq_nth_le]; exact ⟨λ ⟨i, hi, h⟩, ⟨i, by rwa to_list_length at hi, h⟩, λ ⟨i, hi, h⟩, ⟨i, by rwa to_list_length, h⟩⟩ lemma nodup_iff_nth_inj {v : vector α n} : v.to_list.nodup ↔ function.injective v.nth := begin cases v with l hl, subst hl, simp only [list.nodup_iff_nth_le_inj], split, { intros h i j hij, cases i, cases j, simp [nth_eq_nth_le] at *, tauto }, { intros h i j hi hj hij, have := @h ⟨i, hi⟩ ⟨j, hj⟩, simp [nth_eq_nth_le] at *, tauto } end @[simp] lemma nth_mem (i : fin n) (v : vector α n) : v.nth i ∈ v.to_list := by rw [nth_eq_nth_le]; exact list.nth_le_mem _ _ _ theorem head'_to_list : ∀ (v : vector α n.succ), (to_list v).head' = some (head v) | ⟨a::l, e⟩ := rfl def reverse (v : vector α n) : vector α n := ⟨v.to_list.reverse, by simp⟩ @[simp] theorem nth_zero : ∀ (v : vector α n.succ), nth v 0 = head v | ⟨a::l, e⟩ := rfl @[simp] theorem head_of_fn {n : ℕ} (f : fin n.succ → α) : head (of_fn f) = f 0 := by rw [← nth_zero, nth_of_fn] @[simp] theorem nth_cons_zero (a : α) (v : vector α n) : nth (a :: v) 0 = a := by simp [nth_zero] @[simp] theorem nth_cons_succ (a : α) (v : vector α n) (i : fin n) : nth (a :: v) i.succ = nth v i := by rw [← nth_tail, tail_cons] def m_of_fn {m} [monad m] {α : Type u} : ∀ {n}, (fin n → m α) → m (vector α n) | 0 f := pure nil | (n+1) f := do a ← f 0, v ← m_of_fn (λi, f i.succ), pure (a :: v) theorem m_of_fn_pure {m} [monad m] [is_lawful_monad m] {α} : ∀ {n} (f : fin n → α), @m_of_fn m _ _ _ (λ i, pure (f i)) = pure (of_fn f) | 0 f := rfl | (n+1) f := by simp [m_of_fn, @m_of_fn_pure n, of_fn] def mmap {m} [monad m] {α} {β : Type u} (f : α → m β) : ∀ {n}, vector α n → m (vector β n) | _ ⟨[], rfl⟩ := pure nil | _ ⟨a::l, rfl⟩ := do h' ← f a, t' ← mmap ⟨l, rfl⟩, pure (h' :: t') @[simp] theorem mmap_nil {m} [monad m] {α β} (f : α → m β) : mmap f nil = pure nil := rfl @[simp] theorem mmap_cons {m} [monad m] {α β} (f : α → m β) (a) : ∀ {n} (v : vector α n), mmap f (a::v) = do h' ← f a, t' ← mmap f v, pure (h' :: t') | _ ⟨l, rfl⟩ := rfl @[ext] theorem ext : ∀ {v w : vector α n} (h : ∀ m : fin n, vector.nth v m = vector.nth w m), v = w | ⟨v, hv⟩ ⟨w, hw⟩ h := subtype.eq (list.ext_le (by rw [hv, hw]) (λ m hm hn, h ⟨m, hv ▸ hm⟩)) instance zero_subsingleton : subsingleton (vector α 0) := ⟨λ _ _, vector.ext (λ m, fin.elim0 m)⟩ def to_array : vector α n → array n α | ⟨xs, h⟩ := cast (by rw h) xs.to_array section insert_nth variable {a : α} def insert_nth (a : α) (i : fin (n+1)) (v : vector α n) : vector α (n+1) := ⟨v.1.insert_nth i a, begin rw [list.length_insert_nth, v.2], rw [v.2, ← nat.succ_le_succ_iff], exact i.2 end⟩ lemma insert_nth_val {i : fin (n+1)} {v : vector α n} : (v.insert_nth a i).val = v.val.insert_nth i.1 a := rfl @[simp] lemma remove_nth_val {i : fin n} : ∀{v : vector α n}, (remove_nth i v).val = v.val.remove_nth i | ⟨l, hl⟩ := rfl lemma remove_nth_insert_nth {v : vector α n} {i : fin (n+1)} : remove_nth i (insert_nth a i v) = v := subtype.eq $ list.remove_nth_insert_nth i.1 v.1 lemma remove_nth_insert_nth_ne {v : vector α (n+1)} : ∀{i j : fin (n+2)} (h : i ≠ j), remove_nth i (insert_nth a j v) = insert_nth a (i.pred_above j h.symm) (remove_nth (j.pred_above i h) v) | ⟨i, hi⟩ ⟨j, hj⟩ ne := begin have : i ≠ j := fin.vne_of_ne ne, refine subtype.eq _, dsimp [insert_nth, remove_nth, fin.pred_above, fin.cast_lt, -subtype.val_eq_coe], rcases lt_trichotomy i j with h | h | h, { have h_nji : ¬ j < i := lt_asymm h, have j_pos : 0 < j := lt_of_le_of_lt (zero_le i) h, rw [dif_neg], swap, { exact h_nji }, rw [dif_pos], swap, { exact h }, rw [fin.coe_pred, fin.coe_mk, remove_nth_val, fin.coe_mk], rw [list.insert_nth_remove_nth_of_ge, nat.sub_add_cancel j_pos], { rw [v.2], exact lt_of_lt_of_le h (nat.le_of_succ_le_succ hj) }, { exact nat.le_sub_right_of_add_le h } }, { exact (this h).elim }, { have h_nij : ¬ i < j := lt_asymm h, have i_pos : 0 < i := lt_of_le_of_lt (zero_le j) h, rw [dif_pos], swap, { exact h }, rw [dif_neg], swap, { exact h_nij }, rw [fin.coe_mk, remove_nth_val, fin.coe_pred, fin.coe_mk], rw [list.insert_nth_remove_nth_of_le, nat.sub_add_cancel i_pos], { show i - 1 + 1 ≤ v.val.length, rw [v.2, nat.sub_add_cancel i_pos], exact nat.le_of_lt_succ hi }, { exact nat.le_sub_right_of_add_le h } } end lemma insert_nth_comm (a b : α) (i j : fin (n+1)) (h : i ≤ j) : ∀(v : vector α n), (v.insert_nth a i).insert_nth b j.succ = (v.insert_nth b j).insert_nth a i.cast_succ | ⟨l, hl⟩ := begin refine subtype.eq _, simp only [insert_nth_val, fin.coe_succ, fin.cast_succ, fin.val_eq_coe, fin.coe_cast_add], apply list.insert_nth_comm, { assumption }, { rw hl, exact nat.le_of_succ_le_succ j.2 } end end insert_nth section update_nth /-- `update_nth v n a` replaces the `n`th element of `v` with `a` -/ def update_nth (v : vector α n) (i : fin n) (a : α) : vector α n := ⟨v.1.update_nth i.1 a, by rw [list.update_nth_length, v.2]⟩ @[simp] lemma nth_update_nth_same (v : vector α n) (i : fin n) (a : α) : (v.update_nth i a).nth i = a := by cases v; cases i; simp [vector.update_nth, vector.nth_eq_nth_le] lemma nth_update_nth_of_ne {v : vector α n} {i j : fin n} (h : i ≠ j) (a : α) : (v.update_nth i a).nth j = v.nth j := by cases v; cases i; cases j; simp [vector.update_nth, vector.nth_eq_nth_le, list.nth_le_update_nth_of_ne (fin.vne_of_ne h)] lemma nth_update_nth_eq_if {v : vector α n} {i j : fin n} (a : α) : (v.update_nth i a).nth j = if i = j then a else v.nth j := by split_ifs; try {simp *}; try {rw nth_update_nth_of_ne}; assumption end update_nth end vector namespace vector section traverse variables {F G : Type u → Type u} variables [applicative F] [applicative G] open applicative functor open list (cons) nat private def traverse_aux {α β : Type u} (f : α → F β) : Π (x : list α), F (vector β x.length) | [] := pure vector.nil | (x::xs) := vector.cons <$> f x <*> traverse_aux xs protected def traverse {α β : Type u} (f : α → F β) : vector α n → F (vector β n) | ⟨v, Hv⟩ := cast (by rw Hv) $ traverse_aux f v variables [is_lawful_applicative F] [is_lawful_applicative G] variables {α β γ : Type u} @[simp] protected lemma traverse_def (f : α → F β) (x : α) : ∀ (xs : vector α n), (x :: xs).traverse f = cons <$> f x <*> xs.traverse f := by rintro ⟨xs, rfl⟩; refl protected lemma id_traverse : ∀ (x : vector α n), x.traverse id.mk = x := begin rintro ⟨x, rfl⟩, dsimp [vector.traverse, cast], induction x with x xs IH, {refl}, simp! [IH], refl end open function protected lemma comp_traverse (f : β → F γ) (g : α → G β) : ∀ (x : vector α n), vector.traverse (comp.mk ∘ functor.map f ∘ g) x = comp.mk (vector.traverse f <$> vector.traverse g x) := by rintro ⟨x, rfl⟩; dsimp [vector.traverse, cast]; induction x with x xs; simp! [cast, *] with functor_norm; [refl, simp [(∘)]] protected lemma traverse_eq_map_id {α β} (f : α → β) : ∀ (x : vector α n), x.traverse (id.mk ∘ f) = id.mk (map f x) := by rintro ⟨x, rfl⟩; simp!; induction x; simp! * with functor_norm; refl variable (η : applicative_transformation F G) protected lemma naturality {α β : Type*} (f : α → F β) : ∀ (x : vector α n), η (x.traverse f) = x.traverse (@η _ ∘ f) := by rintro ⟨x, rfl⟩; simp! [cast]; induction x with x xs IH; simp! * with functor_norm end traverse instance : traversable.{u} (flip vector n) := { traverse := @vector.traverse n, map := λ α β, @vector.map.{u u} α β n } instance : is_lawful_traversable.{u} (flip vector n) := { id_traverse := @vector.id_traverse n, comp_traverse := @vector.comp_traverse n, traverse_eq_map_id := @vector.traverse_eq_map_id n, naturality := @vector.naturality n, id_map := by intros; cases x; simp! [(<$>)], comp_map := by intros; cases x; simp! [(<$>)] } end vector
88e36c7df337cd884b9f7d52abfc16c0c3979b7f
bdc51328652176125c43c2c9f2d3e4398f127ccb
/src/DFA.lean
4894f9b80e368437d8bbabf4c6a547990063c7aa
[]
no_license
atarnoam/lean-automata
d6ca17387b8e0ac6d7c21f12e78d26c237a57cd2
46c69ddaa142913b1f43ef57f700f2481cdfba76
refs/heads/main
1,678,898,675,345
1,614,977,921,000
1,614,977,921,000
344,927,186
6
1
null
null
null
null
UTF-8
Lean
false
false
4,519
lean
import computability.DFA import computability.language import data.fintype.basic import data.list import language universes u v w namespace DFA variables {α : Type u} variables {σ τ : Type v} section basics variables {A : DFA α σ} (p : σ) (a : α) (x y : list α) @[simp] lemma eval_from_nil : A.eval_from p [] = p := list.foldl_nil _ _ @[simp] lemma eval_from_cons : A.eval_from p (a :: x) = A.eval_from (A.step p a) x := list.foldl_cons _ _ _ _ @[simp] lemma eval_def : A.eval x = A.eval_from A.start x := rfl attribute [simp] mem_accepts end basics section intersection /-! ### Intersection automaton Here we construct from two DFAs a DFA whose language is the intersection of the two DFAs, and prove it. -/ variables (A : DFA α σ) (B : DFA α τ) (s : σ) (t : τ) (a : α) (x : list α) /-- Given two DFAs, returns a DFA whose language is the intersection of the two DFAs' languages. -/ def inter : DFA α (σ × τ):= { step := λ ⟨s, t⟩ a, ⟨A.step s a, B.step t a⟩, start := ⟨A.start, B.start⟩, accept := { st | st.1 ∈ A.accept ∧ st.2 ∈ B.accept} } @[simp] lemma inter_step : (inter A B).step (s, t) a = (A.step s a, B.step t a) := rfl @[simp] lemma inter_start : (inter A B).start = (A.start, B.start) := rfl @[simp] lemma inter_accept : (s, t) ∈ (inter A B).accept ↔ s ∈ A.accept ∧ t ∈ B.accept := iff.refl _ @[simp] lemma inter_eval_from : eval_from (inter A B) (s, t) x = (eval_from A s x, eval_from B t x) := begin induction x with a x ih generalizing s t, { tauto }, { simp [ih _ _] } end @[simp] lemma inter_accepts : accepts (inter A B) = (accepts A) ⊓ (accepts B) := by {ext, simp} end intersection section complement /-! ### Complement automaton Here we construct a DFA whose language is the complement of the given DFA's language. -/ variables (A : DFA α σ) (s : σ) (a : α) (x : list α) /-- Given a DFA, returns a DFA whose language is the complement of the given DFA's language. -/ def compl : DFA α σ := { step := A.step, start := A.start, accept := { s | s ∉ A.accept } } @[simp] lemma compl_step : A.compl.step = A.step := rfl @[simp] lemma compl_start : A.compl.start = A.start := rfl @[simp] lemma compl_accept : s ∈ A.compl.accept ↔ s ∉ A.accept := by refl @[simp] lemma compl_eval_from : eval_from A.compl s x = eval_from A s x := begin induction x with a x ih generalizing s, { tauto }, { simp [ih _] } end @[simp] lemma compl_accepts : accepts (compl A) = (accepts A)ᶜ := by {ext, simp} end complement section relation /-! ### Equivalence relation on `list α` Here we give the basics of the equivalence relation on `list α` that we get for every DFA `A`, defined as: `x ≈ y ↔ A.eval x = A.eval y`. -/ variables (A : DFA α σ) /-- A relation on `list α`, identifying `x, y` if `A.eval x = A.eval y`. -/ definition rel : list α → list α → Prop := λ x y, A.eval x = A.eval y @[simp] lemma rel_def {x y : list α} : rel A x y ↔ A.eval x = A.eval y := by refl lemma rel_refl : reflexive (rel A) := λ _, by rw rel_def lemma rel_symm : symmetric (rel A) := λ _ _ hxy, eq.symm hxy lemma rel_trans : transitive (rel A) := λ _ _ _ hxy hyz, eq.trans hxy hyz lemma rel_equiv : equivalence (rel A) := ⟨rel_refl A, rel_symm A, rel_trans A⟩ instance space.setoid : setoid (list α) := setoid.mk A.rel A.rel_equiv definition space := quotient (space.setoid A) variable {A} definition space.mk (x : list α) : space A := @quotient.mk _ (space.setoid A) x @[simp] lemma space.mk_def (x : list α) : space.mk x = @quotient.mk _ (space.setoid A) x := rfl @[simp] lemma space.mk_def' (x : list α) : @quotient.mk' _ (space.setoid A) x = space.mk x := rfl variable (A) -- The canonical map. We show it is injective, as a part of the proof of Myhill-Nerode. def to_states : space A → σ := begin apply quot.lift A.eval, intros x y rab, rw (rel_def A).1 rab end @[simp] lemma to_states_def (x : list α) : to_states A (space.mk x) = A.eval x := rfl lemma injective_to_states : function.injective (to_states A) := begin apply @quotient.ind₂' (list α) (list α) _ _ (λ ex ey, to_states A ex = to_states A ey → ex = ey) , intros x y h, repeat {rw space.mk_def' _ at h, rw f_def A _ at h}, simp, exact h, end -- What we actually care about, sadly noncomputable :( noncomputable instance fintype_space_of_fintype_states [fintype σ] : fintype (space A) := fintype.of_injective (to_states A) (injective_to_states A) end relation end DFA
697716519c787a1ed71cddef560d647e0a7af663
5ae26df177f810c5006841e9c73dc56e01b978d7
/src/category_theory/monoidal/functor.lean
d4b1bf965227bff5cc824d0e26bd6a9e935c85cf
[ "Apache-2.0" ]
permissive
ChrisHughes24/mathlib
98322577c460bc6b1fe5c21f42ce33ad1c3e5558
a2a867e827c2a6702beb9efc2b9282bd801d5f9a
refs/heads/master
1,583,848,251,477
1,565,164,247,000
1,565,164,247,000
129,409,993
0
1
Apache-2.0
1,565,164,817,000
1,523,628,059,000
Lean
UTF-8
Lean
false
false
6,665
lean
/- Copyright (c) 2018 Michael Jendrusch. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Michael Jendrusch, Scott Morrison -/ import category_theory.monoidal.category open category_theory universes v₁ v₂ v₃ u₁ u₂ u₃ open category_theory.category open category_theory.functor namespace category_theory section open monoidal_category variables (C : Type u₁) [𝒞 : monoidal_category.{v₁} C] (D : Type u₂) [𝒟 : monoidal_category.{v₂} D] include 𝒞 𝒟 structure lax_monoidal_functor extends C ⥤ D := -- unit morphism (ε : tensor_unit D ⟶ obj (tensor_unit C)) -- tensorator (μ : Π X Y : C, (obj X) ⊗ (obj Y) ⟶ obj (X ⊗ Y)) (μ_natural' : ∀ {X Y X' Y' : C} (f : X ⟶ Y) (g : X' ⟶ Y'), ((map f) ⊗ (map g)) ≫ μ Y Y' = μ X X' ≫ map (f ⊗ g) . obviously) -- associativity of the tensorator (associativity' : ∀ (X Y Z : C), (μ X Y ⊗ 𝟙 (obj Z)) ≫ μ (X ⊗ Y) Z ≫ map (associator X Y Z).hom = (associator (obj X) (obj Y) (obj Z)).hom ≫ (𝟙 (obj X) ⊗ μ Y Z) ≫ μ X (Y ⊗ Z) . obviously) -- unitality (left_unitality' : ∀ X : C, (left_unitor (obj X)).hom = (ε ⊗ 𝟙 (obj X)) ≫ μ (tensor_unit C) X ≫ map (left_unitor X).hom . obviously) (right_unitality' : ∀ X : C, (right_unitor (obj X)).hom = (𝟙 (obj X) ⊗ ε) ≫ μ X (tensor_unit C) ≫ map (right_unitor X).hom . obviously) restate_axiom lax_monoidal_functor.μ_natural' attribute [simp] lax_monoidal_functor.μ_natural restate_axiom lax_monoidal_functor.left_unitality' attribute [simp] lax_monoidal_functor.left_unitality restate_axiom lax_monoidal_functor.right_unitality' attribute [simp] lax_monoidal_functor.right_unitality restate_axiom lax_monoidal_functor.associativity' attribute [simp] lax_monoidal_functor.associativity -- When `rewrite_search` lands, add @[search] attributes to -- lax_monoidal_functor.μ_natural lax_monoidal_functor.left_unitality -- lax_monoidal_functor.right_unitality lax_monoidal_functor.associativity structure monoidal_functor extends lax_monoidal_functor.{v₁ v₂} C D := (ε_is_iso : is_iso ε . obviously) (μ_is_iso : Π X Y : C, is_iso (μ X Y) . obviously) attribute [instance] monoidal_functor.ε_is_iso monoidal_functor.μ_is_iso variables {C D} def monoidal_functor.ε_iso (F : monoidal_functor.{v₁ v₂} C D) : tensor_unit D ≅ F.obj (tensor_unit C) := as_iso F.ε def monoidal_functor.μ_iso (F : monoidal_functor.{v₁ v₂} C D) (X Y : C) : (F.obj X) ⊗ (F.obj Y) ≅ F.obj (X ⊗ Y) := as_iso (F.μ X Y) end open monoidal_category namespace monoidal_functor section -- In order to express the tensorator as a natural isomorphism, -- we need to be in at least `Type 0`, so we have products. variables {C : Type u₁} [𝒞 : monoidal_category.{v₁+1} C] variables {D : Type u₂} [𝒟 : monoidal_category.{v₂+1} D] include 𝒞 𝒟 def μ_nat_iso (F : monoidal_functor.{v₁+1 v₂+1} C D) : (functor.prod F.to_functor F.to_functor) ⋙ (tensor D) ≅ (tensor C) ⋙ F.to_functor := nat_iso.of_components (by { intros, apply F.μ_iso }) (by { intros, apply F.to_lax_monoidal_functor.μ_natural }) end section variables (C : Type u₁) [𝒞 : monoidal_category.{v₁} C] include 𝒞 def id : monoidal_functor.{v₁ v₁} C C := { ε := 𝟙 _, μ := λ X Y, 𝟙 _, .. functor.id C } @[simp] lemma id_obj (X : C) : (monoidal_functor.id C).obj X = X := rfl @[simp] lemma id_map {X X' : C} (f : X ⟶ X') : (monoidal_functor.id C).map f = f := rfl @[simp] lemma id_ε : (monoidal_functor.id C).ε = 𝟙 _ := rfl @[simp] lemma id_μ (X Y) : (monoidal_functor.id C).μ X Y = 𝟙 _ := rfl end end monoidal_functor variables {C : Type u₁} [𝒞 : monoidal_category.{v₁} C] variables {D : Type u₂} [𝒟 : monoidal_category.{v₂} D] variables {E : Type u₃} [ℰ : monoidal_category.{v₃} E] include 𝒞 𝒟 ℰ namespace lax_monoidal_functor variables (F : lax_monoidal_functor.{v₁ v₂} C D) (G : lax_monoidal_functor.{v₂ v₃} D E) -- The proofs here are horrendous; rewrite_search helps a lot. def comp : lax_monoidal_functor.{v₁ v₃} C E := { ε := G.ε ≫ (G.map F.ε), μ := λ X Y, G.μ (F.obj X) (F.obj Y) ≫ G.map (F.μ X Y), μ_natural' := λ _ _ _ _ f g, begin simp only [functor.comp_map, assoc], rw [←category.assoc, lax_monoidal_functor.μ_natural, category.assoc, ←map_comp, ←map_comp, ←lax_monoidal_functor.μ_natural] end, associativity' := λ X Y Z, begin dsimp, rw id_tensor_comp, slice_rhs 3 4 { rw [← G.to_functor.map_id, G.μ_natural], }, slice_rhs 1 3 { rw ←G.associativity, }, rw comp_tensor_id, slice_lhs 2 3 { rw [← G.to_functor.map_id, G.μ_natural], }, rw [category.assoc, category.assoc, category.assoc, category.assoc, category.assoc, ←G.to_functor.map_comp, ←G.to_functor.map_comp, ←G.to_functor.map_comp, ←G.to_functor.map_comp, F.associativity], end, left_unitality' := λ X, begin dsimp, rw [G.left_unitality, comp_tensor_id, category.assoc, category.assoc], apply congr_arg, rw [F.left_unitality, map_comp, ←nat_trans.id_app, ←category.assoc, ←lax_monoidal_functor.μ_natural, nat_trans.id_app, map_id, ←category.assoc, map_comp], end, right_unitality' := λ X, begin dsimp, rw [G.right_unitality, id_tensor_comp, category.assoc, category.assoc], apply congr_arg, rw [F.right_unitality, map_comp, ←nat_trans.id_app, ←category.assoc, ←lax_monoidal_functor.μ_natural, nat_trans.id_app, map_id, ←category.assoc, map_comp], end, .. (F.to_functor) ⋙ (G.to_functor) }. @[simp] lemma comp_obj (X : C) : (F.comp G).obj X = G.obj (F.obj X) := rfl @[simp] lemma comp_map {X X' : C} (f : X ⟶ X') : (F.comp G).map f = (G.map (F.map f) : G.obj (F.obj X) ⟶ G.obj (F.obj X')) := rfl @[simp] lemma comp_ε : (F.comp G).ε = G.ε ≫ (G.map F.ε) := rfl @[simp] lemma comp_μ (X Y : C) : (F.comp G).μ X Y = G.μ (F.obj X) (F.obj Y) ≫ G.map (F.μ X Y) := rfl end lax_monoidal_functor namespace monoidal_functor variables (F : monoidal_functor.{v₁ v₂} C D) (G : monoidal_functor.{v₂ v₃} D E) def comp : monoidal_functor.{v₁ v₃} C E := { ε_is_iso := by { dsimp, apply_instance }, -- TODO tidy would get this if we deferred ext μ_is_iso := by { dsimp, apply_instance }, -- TODO as above .. (F.to_lax_monoidal_functor).comp (G.to_lax_monoidal_functor) }. end monoidal_functor end category_theory
bad8ee8281b349874880a2930bb5436fe10474a5
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/linear_algebra/basis.lean
c7f2f38be3cd79adaf218490ddd95718fd827084
[ "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
57,800
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Alexander Bentkamp -/ import algebra.big_operators.finsupp import algebra.big_operators.finprod import data.fintype.big_operators import linear_algebra.finsupp import linear_algebra.linear_independent import linear_algebra.linear_pmap import linear_algebra.projection /-! # Bases > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines bases in a module or vector space. It is inspired by Isabelle/HOL's linear algebra, and hence indirectly by HOL Light. ## Main definitions All definitions are given for families of vectors, i.e. `v : ι → M` where `M` is the module or vector space and `ι : Type*` is an arbitrary indexing type. * `basis ι R M` is the type of `ι`-indexed `R`-bases for a module `M`, represented by a linear equiv `M ≃ₗ[R] ι →₀ R`. * the basis vectors of a basis `b : basis ι R M` are available as `b i`, where `i : ι` * `basis.repr` is the isomorphism sending `x : M` to its coordinates `basis.repr x : ι →₀ R`. The converse, turning this isomorphism into a basis, is called `basis.of_repr`. * If `ι` is finite, there is a variant of `repr` called `basis.equiv_fun b : M ≃ₗ[R] ι → R` (saving you from having to work with `finsupp`). The converse, turning this isomorphism into a basis, is called `basis.of_equiv_fun`. * `basis.constr hv f` constructs a linear map `M₁ →ₗ[R] M₂` given the values `f : ι → M₂` at the basis elements `⇑b : ι → M₁`. * `basis.reindex` uses an equiv to map a basis to a different indexing set. * `basis.map` uses a linear equiv to map a basis to a different module. ## Main statements * `basis.mk`: a linear independent set of vectors spanning the whole module determines a basis * `basis.ext` states that two linear maps are equal if they coincide on a basis. Similar results are available for linear equivs (if they coincide on the basis vectors), elements (if their coordinates coincide) and the functions `b.repr` and `⇑b`. * `basis.of_vector_space` states that every vector space has a basis. ## Implementation notes We use families instead of sets because it allows us to say that two identical vectors are linearly dependent. For bases, this is useful as well because we can easily derive ordered bases by using an ordered index type `ι`. ## Tags basis, bases -/ noncomputable theory universe u open function set submodule open_locale big_operators variables {ι : Type*} {ι' : Type*} {R : Type*} {R₂ : Type*} {K : Type*} variables {M : Type*} {M' M'' : Type*} {V : Type u} {V' : Type*} section module variables [semiring R] variables [add_comm_monoid M] [module R M] [add_comm_monoid M'] [module R M'] section variables (ι) (R) (M) /-- A `basis ι R M` for a module `M` is the type of `ι`-indexed `R`-bases of `M`. The basis vectors are available as `coe_fn (b : basis ι R M) : ι → M`. To turn a linear independent family of vectors spanning `M` into a basis, use `basis.mk`. They are internally represented as linear equivs `M ≃ₗ[R] (ι →₀ R)`, available as `basis.repr`. -/ structure basis := of_repr :: (repr : M ≃ₗ[R] (ι →₀ R)) end instance unique_basis [subsingleton R] : unique (basis ι R M) := ⟨⟨⟨default⟩⟩, λ ⟨b⟩, by rw subsingleton.elim b⟩ namespace basis instance : inhabited (basis ι R (ι →₀ R)) := ⟨basis.of_repr (linear_equiv.refl _ _)⟩ variables (b b₁ : basis ι R M) (i : ι) (c : R) (x : M) section repr lemma repr_injective : injective (repr : basis ι R M → M ≃ₗ[R] (ι →₀ R)) := λ f g h, by cases f; cases g; congr' /-- `b i` is the `i`th basis vector. -/ instance fun_like : fun_like (basis ι R M) ι (λ _, M) := { coe := λ b i, b.repr.symm (finsupp.single i 1), coe_injective' := λ f g h, repr_injective $ linear_equiv.symm_bijective.injective begin ext x, rw [←finsupp.sum_single x, map_finsupp_sum, map_finsupp_sum], congr' with i r, have := congr_fun h i, dsimp at this, rw [←mul_one r, ←finsupp.smul_single', linear_equiv.map_smul, linear_equiv.map_smul, this], end } @[simp] lemma coe_of_repr (e : M ≃ₗ[R] (ι →₀ R)) : ⇑(of_repr e) = λ i, e.symm (finsupp.single i 1) := rfl protected lemma injective [nontrivial R] : injective b := b.repr.symm.injective.comp (λ _ _, (finsupp.single_left_inj (one_ne_zero : (1 : R) ≠ 0)).mp) lemma repr_symm_single_one : b.repr.symm (finsupp.single i 1) = b i := rfl lemma repr_symm_single : b.repr.symm (finsupp.single i c) = c • b i := calc b.repr.symm (finsupp.single i c) = b.repr.symm (c • finsupp.single i 1) : by rw [finsupp.smul_single', mul_one] ... = c • b i : by rw [linear_equiv.map_smul, repr_symm_single_one] @[simp] lemma repr_self : b.repr (b i) = finsupp.single i 1 := linear_equiv.apply_symm_apply _ _ lemma repr_self_apply (j) [decidable (i = j)] : b.repr (b i) j = if i = j then 1 else 0 := by rw [repr_self, finsupp.single_apply] @[simp] lemma repr_symm_apply (v) : b.repr.symm v = finsupp.total ι M R b v := calc b.repr.symm v = b.repr.symm (v.sum finsupp.single) : by simp ... = ∑ i in v.support, b.repr.symm (finsupp.single i (v i)) : by rw [finsupp.sum, linear_equiv.map_sum] ... = finsupp.total ι M R b v : by simp [repr_symm_single, finsupp.total_apply, finsupp.sum] @[simp] lemma coe_repr_symm : ↑b.repr.symm = finsupp.total ι M R b := linear_map.ext (λ v, b.repr_symm_apply v) @[simp] lemma repr_total (v) : b.repr (finsupp.total _ _ _ b v) = v := by { rw ← b.coe_repr_symm, exact b.repr.apply_symm_apply v } @[simp] lemma total_repr : finsupp.total _ _ _ b (b.repr x) = x := by { rw ← b.coe_repr_symm, exact b.repr.symm_apply_apply x } lemma repr_range : (b.repr : M →ₗ[R] (ι →₀ R)).range = finsupp.supported R R univ := by rw [linear_equiv.range, finsupp.supported_univ] lemma mem_span_repr_support {ι : Type*} (b : basis ι R M) (m : M) : m ∈ span R (b '' (b.repr m).support) := (finsupp.mem_span_image_iff_total _).2 ⟨b.repr m, (by simp [finsupp.mem_supported_support])⟩ lemma repr_support_subset_of_mem_span {ι : Type*} (b : basis ι R M) (s : set ι) {m : M} (hm : m ∈ span R (b '' s)) : ↑(b.repr m).support ⊆ s := begin rcases (finsupp.mem_span_image_iff_total _).1 hm with ⟨l, hl, hlm⟩, rwa [←hlm, repr_total, ←finsupp.mem_supported R l] end end repr section coord /-- `b.coord i` is the linear function giving the `i`'th coordinate of a vector with respect to the basis `b`. `b.coord i` is an element of the dual space. In particular, for finite-dimensional spaces it is the `ι`th basis vector of the dual space. -/ @[simps] def coord : M →ₗ[R] R := (finsupp.lapply i) ∘ₗ ↑b.repr lemma forall_coord_eq_zero_iff {x : M} : (∀ i, b.coord i x = 0) ↔ x = 0 := iff.trans (by simp only [b.coord_apply, finsupp.ext_iff, finsupp.zero_apply]) b.repr.map_eq_zero_iff /-- The sum of the coordinates of an element `m : M` with respect to a basis. -/ noncomputable def sum_coords : M →ₗ[R] R := finsupp.lsum ℕ (λ i, linear_map.id) ∘ₗ (b.repr : M →ₗ[R] ι →₀ R) @[simp] lemma coe_sum_coords : (b.sum_coords : M → R) = λ m, (b.repr m).sum (λ i, id) := rfl lemma coe_sum_coords_eq_finsum : (b.sum_coords : M → R) = λ m, ∑ᶠ i, b.coord i m := begin ext m, simp only [basis.sum_coords, basis.coord, finsupp.lapply_apply, linear_map.id_coe, linear_equiv.coe_coe, function.comp_app, finsupp.coe_lsum, linear_map.coe_comp, finsum_eq_sum _ (b.repr m).finite_support, finsupp.sum, finset.finite_to_set_to_finset, id.def, finsupp.fun_support_eq], end @[simp] lemma coe_sum_coords_of_fintype [fintype ι] : (b.sum_coords : M → R) = ∑ i, b.coord i := begin ext m, simp only [sum_coords, finsupp.sum_fintype, linear_map.id_coe, linear_equiv.coe_coe, coord_apply, id.def, fintype.sum_apply, implies_true_iff, eq_self_iff_true, finsupp.coe_lsum, linear_map.coe_comp], end @[simp] lemma sum_coords_self_apply : b.sum_coords (b i) = 1 := by simp only [basis.sum_coords, linear_map.id_coe, linear_equiv.coe_coe, id.def, basis.repr_self, function.comp_app, finsupp.coe_lsum, linear_map.coe_comp, finsupp.sum_single_index] lemma dvd_coord_smul (i : ι) (m : M) (r : R) : r ∣ b.coord i (r • m) := ⟨b.coord i m, by simp⟩ lemma coord_repr_symm (b : basis ι R M) (i : ι) (f : ι →₀ R) : b.coord i (b.repr.symm f) = f i := by simp only [repr_symm_apply, coord_apply, repr_total] end coord section ext variables {R₁ : Type*} [semiring R₁] {σ : R →+* R₁} {σ' : R₁ →+* R} variables [ring_hom_inv_pair σ σ'] [ring_hom_inv_pair σ' σ] variables {M₁ : Type*} [add_comm_monoid M₁] [module R₁ M₁] /-- Two linear maps are equal if they are equal on basis vectors. -/ theorem ext {f₁ f₂ : M →ₛₗ[σ] M₁} (h : ∀ i, f₁ (b i) = f₂ (b i)) : f₁ = f₂ := by { ext x, rw [← b.total_repr x, finsupp.total_apply, finsupp.sum], simp only [linear_map.map_sum, linear_map.map_smulₛₗ, h] } include σ' /-- Two linear equivs are equal if they are equal on basis vectors. -/ theorem ext' {f₁ f₂ : M ≃ₛₗ[σ] M₁} (h : ∀ i, f₁ (b i) = f₂ (b i)) : f₁ = f₂ := by { ext x, rw [← b.total_repr x, finsupp.total_apply, finsupp.sum], simp only [linear_equiv.map_sum, linear_equiv.map_smulₛₗ, h] } omit σ' /-- Two elements are equal iff their coordinates are equal. -/ lemma ext_elem_iff {x y : M} : x = y ↔ (∀ i, b.repr x i = b.repr y i) := by simp only [← finsupp.ext_iff, embedding_like.apply_eq_iff_eq] alias ext_elem_iff ↔ _ _root_.basis.ext_elem lemma repr_eq_iff {b : basis ι R M} {f : M →ₗ[R] ι →₀ R} : ↑b.repr = f ↔ ∀ i, f (b i) = finsupp.single i 1 := ⟨λ h i, h ▸ b.repr_self i, λ h, b.ext (λ i, (b.repr_self i).trans (h i).symm)⟩ lemma repr_eq_iff' {b : basis ι R M} {f : M ≃ₗ[R] ι →₀ R} : b.repr = f ↔ ∀ i, f (b i) = finsupp.single i 1 := ⟨λ h i, h ▸ b.repr_self i, λ h, b.ext' (λ i, (b.repr_self i).trans (h i).symm)⟩ lemma apply_eq_iff {b : basis ι R M} {x : M} {i : ι} : b i = x ↔ b.repr x = finsupp.single i 1 := ⟨λ h, h ▸ b.repr_self i, λ h, b.repr.injective ((b.repr_self i).trans h.symm)⟩ /-- An unbundled version of `repr_eq_iff` -/ lemma repr_apply_eq (f : M → ι → R) (hadd : ∀ x y, f (x + y) = f x + f y) (hsmul : ∀ (c : R) (x : M), f (c • x) = c • f x) (f_eq : ∀ i, f (b i) = finsupp.single i 1) (x : M) (i : ι) : b.repr x i = f x i := begin let f_i : M →ₗ[R] R := { to_fun := λ x, f x i, map_add' := λ _ _, by rw [hadd, pi.add_apply], map_smul' := λ _ _, by { simp [hsmul, pi.smul_apply] } }, have : (finsupp.lapply i) ∘ₗ ↑b.repr = f_i, { refine b.ext (λ j, _), show b.repr (b j) i = f (b j) i, rw [b.repr_self, f_eq] }, calc b.repr x i = f_i x : by { rw ← this, refl } ... = f x i : rfl end /-- Two bases are equal if they assign the same coordinates. -/ lemma eq_of_repr_eq_repr {b₁ b₂ : basis ι R M} (h : ∀ x i, b₁.repr x i = b₂.repr x i) : b₁ = b₂ := repr_injective $ by { ext, apply h } /-- Two bases are equal if their basis vectors are the same. -/ @[ext] lemma eq_of_apply_eq {b₁ b₂ : basis ι R M} : (∀ i, b₁ i = b₂ i) → b₁ = b₂ := fun_like.ext _ _ end ext section map variables (f : M ≃ₗ[R] M') /-- Apply the linear equivalence `f` to the basis vectors. -/ @[simps] protected def map : basis ι R M' := of_repr (f.symm.trans b.repr) @[simp] lemma map_apply (i) : b.map f i = f (b i) := rfl end map section map_coeffs variables {R' : Type*} [semiring R'] [module R' M] (f : R ≃+* R') (h : ∀ c (x : M), f c • x = c • x) include f h b local attribute [instance] has_smul.comp.is_scalar_tower /-- If `R` and `R'` are isomorphic rings that act identically on a module `M`, then a basis for `M` as `R`-module is also a basis for `M` as `R'`-module. See also `basis.algebra_map_coeffs` for the case where `f` is equal to `algebra_map`. -/ @[simps {simp_rhs := tt}] def map_coeffs : basis ι R' M := begin letI : module R' R := module.comp_hom R (↑f.symm : R' →+* R), haveI : is_scalar_tower R' R M := { smul_assoc := λ x y z, begin dsimp [(•)], rw [mul_smul, ←h, f.apply_symm_apply], end }, exact (of_repr $ (b.repr.restrict_scalars R').trans $ finsupp.map_range.linear_equiv (module.comp_hom.to_linear_equiv f.symm).symm ) end lemma map_coeffs_apply (i : ι) : b.map_coeffs f h i = b i := apply_eq_iff.mpr $ by simp [f.to_add_equiv_eq_coe] @[simp] lemma coe_map_coeffs : (b.map_coeffs f h : ι → M) = b := funext $ b.map_coeffs_apply f h end map_coeffs section reindex variables (b' : basis ι' R M') variables (e : ι ≃ ι') /-- `b.reindex (e : ι ≃ ι')` is a basis indexed by `ι'` -/ def reindex : basis ι' R M := basis.of_repr (b.repr.trans (finsupp.dom_lcongr e)) lemma reindex_apply (i' : ι') : b.reindex e i' = b (e.symm i') := show (b.repr.trans (finsupp.dom_lcongr e)).symm (finsupp.single i' 1) = b.repr.symm (finsupp.single (e.symm i') 1), by rw [linear_equiv.symm_trans_apply, finsupp.dom_lcongr_symm, finsupp.dom_lcongr_single] @[simp] lemma coe_reindex : (b.reindex e : ι' → M) = b ∘ e.symm := funext (b.reindex_apply e) lemma repr_reindex_apply (i' : ι') : (b.reindex e).repr x i' = b.repr x (e.symm i') := show (finsupp.dom_lcongr e : _ ≃ₗ[R] _) (b.repr x) i' = _, by simp @[simp] lemma repr_reindex : (b.reindex e).repr x = (b.repr x).map_domain e := fun_like.ext _ _ $ by simp [repr_reindex_apply] @[simp] lemma reindex_refl : b.reindex (equiv.refl ι) = b := eq_of_apply_eq $ λ i, by simp /-- `simp` can prove this as `basis.coe_reindex` + `equiv_like.range_comp` -/ lemma range_reindex : set.range (b.reindex e) = set.range b := by rw [coe_reindex, equiv_like.range_comp] @[simp] lemma sum_coords_reindex : (b.reindex e).sum_coords = b.sum_coords := begin ext x, simp only [coe_sum_coords, repr_reindex], exact finsupp.sum_map_domain_index (λ _, rfl) (λ _ _ _, rfl), end /-- `b.reindex_range` is a basis indexed by `range b`, the basis vectors themselves. -/ def reindex_range : basis (range b) R M := by haveI := classical.dec (nontrivial R); exact if h : nontrivial R then by letI := h; exact b.reindex (equiv.of_injective b (basis.injective b)) else by letI : subsingleton R := not_nontrivial_iff_subsingleton.mp h; exact basis.of_repr (module.subsingleton_equiv R M (range b)) lemma reindex_range_self (i : ι) (h := set.mem_range_self i) : b.reindex_range ⟨b i, h⟩ = b i := begin by_cases htr : nontrivial R, { letI := htr, simp [htr, reindex_range, reindex_apply, equiv.apply_of_injective_symm b.injective, subtype.coe_mk] }, { letI : subsingleton R := not_nontrivial_iff_subsingleton.mp htr, letI := module.subsingleton R M, simp [reindex_range] } end lemma reindex_range_repr_self (i : ι) : b.reindex_range.repr (b i) = finsupp.single ⟨b i, mem_range_self i⟩ 1 := calc b.reindex_range.repr (b i) = b.reindex_range.repr (b.reindex_range ⟨b i, mem_range_self i⟩) : congr_arg _ (b.reindex_range_self _ _).symm ... = finsupp.single ⟨b i, mem_range_self i⟩ 1 : b.reindex_range.repr_self _ @[simp] lemma reindex_range_apply (x : range b) : b.reindex_range x = x := by { rcases x with ⟨bi, ⟨i, rfl⟩⟩, exact b.reindex_range_self i, } lemma reindex_range_repr' (x : M) {bi : M} {i : ι} (h : b i = bi) : b.reindex_range.repr x ⟨bi, ⟨i, h⟩⟩ = b.repr x i := begin nontriviality, subst h, refine (b.repr_apply_eq (λ x i, b.reindex_range.repr x ⟨b i, _⟩) _ _ _ x i).symm, { intros x y, ext i, simp only [pi.add_apply, linear_equiv.map_add, finsupp.coe_add] }, { intros c x, ext i, simp only [pi.smul_apply, linear_equiv.map_smul, finsupp.coe_smul] }, { intros i, ext j, simp only [reindex_range_repr_self], refine @finsupp.single_apply_left _ _ _ _ (λ i, (⟨b i, _⟩ : set.range b)) _ _ _ _, exact λ i j h, b.injective (subtype.mk.inj h) } end @[simp] lemma reindex_range_repr (x : M) (i : ι) (h := set.mem_range_self i) : b.reindex_range.repr x ⟨b i, h⟩ = b.repr x i := b.reindex_range_repr' _ rfl section fintype variables [fintype ι] [decidable_eq M] /-- `b.reindex_finset_range` is a basis indexed by `finset.univ.image b`, the finite set of basis vectors themselves. -/ def reindex_finset_range : basis (finset.univ.image b) R M := b.reindex_range.reindex ((equiv.refl M).subtype_equiv (by simp)) lemma reindex_finset_range_self (i : ι) (h := finset.mem_image_of_mem b (finset.mem_univ i)) : b.reindex_finset_range ⟨b i, h⟩ = b i := by { rw [reindex_finset_range, reindex_apply, reindex_range_apply], refl } @[simp] lemma reindex_finset_range_apply (x : finset.univ.image b) : b.reindex_finset_range x = x := by { rcases x with ⟨bi, hbi⟩, rcases finset.mem_image.mp hbi with ⟨i, -, rfl⟩, exact b.reindex_finset_range_self i } lemma reindex_finset_range_repr_self (i : ι) : b.reindex_finset_range.repr (b i) = finsupp.single ⟨b i, finset.mem_image_of_mem b (finset.mem_univ i)⟩ 1 := begin ext ⟨bi, hbi⟩, rw [reindex_finset_range, repr_reindex, finsupp.map_domain_equiv_apply, reindex_range_repr_self], convert finsupp.single_apply_left ((equiv.refl M).subtype_equiv _).symm.injective _ _ _, refl end @[simp] lemma reindex_finset_range_repr (x : M) (i : ι) (h := finset.mem_image_of_mem b (finset.mem_univ i)) : b.reindex_finset_range.repr x ⟨b i, h⟩ = b.repr x i := by simp [reindex_finset_range] end fintype end reindex protected lemma linear_independent : linear_independent R b := linear_independent_iff.mpr $ λ l hl, calc l = b.repr (finsupp.total _ _ _ b l) : (b.repr_total l).symm ... = 0 : by rw [hl, linear_equiv.map_zero] protected lemma ne_zero [nontrivial R] (i) : b i ≠ 0 := b.linear_independent.ne_zero i protected lemma mem_span (x : M) : x ∈ span R (range b) := by { rw [← b.total_repr x, finsupp.total_apply, finsupp.sum], exact submodule.sum_mem _ (λ i hi, submodule.smul_mem _ _ (submodule.subset_span ⟨i, rfl⟩)) } protected lemma span_eq : span R (range b) = ⊤ := eq_top_iff.mpr $ λ x _, b.mem_span x lemma index_nonempty (b : basis ι R M) [nontrivial M] : nonempty ι := begin obtain ⟨x, y, ne⟩ : ∃ (x y : M), x ≠ y := nontrivial.exists_pair_ne, obtain ⟨i, _⟩ := not_forall.mp (mt b.ext_elem_iff.2 ne), exact ⟨i⟩ end /-- If the submodule `P` has a basis, `x ∈ P` iff it is a linear combination of basis vectors. -/ lemma mem_submodule_iff {P : submodule R M} (b : basis ι R P) {x : M} : x ∈ P ↔ ∃ (c : ι →₀ R), x = finsupp.sum c (λ i x, x • b i) := begin conv_lhs { rw [← P.range_subtype, ← submodule.map_top, ← b.span_eq, submodule.map_span, ← set.range_comp, ← finsupp.range_total] }, simpa only [@eq_comm _ x], end section constr variables (S : Type*) [semiring S] [module S M'] variables [smul_comm_class R S M'] /-- Construct a linear map given the value at the basis. This definition is parameterized over an extra `semiring S`, such that `smul_comm_class R S M'` holds. If `R` is commutative, you can set `S := R`; if `R` is not commutative, you can recover an `add_equiv` by setting `S := ℕ`. See library note [bundled maps over different rings]. -/ def constr : (ι → M') ≃ₗ[S] (M →ₗ[R] M') := { to_fun := λ f, (finsupp.total M' M' R id).comp $ (finsupp.lmap_domain R R f) ∘ₗ ↑b.repr, inv_fun := λ f i, f (b i), left_inv := λ f, by { ext, simp }, right_inv := λ f, by { refine b.ext (λ i, _), simp }, map_add' := λ f g, by { refine b.ext (λ i, _), simp }, map_smul' := λ c f, by { refine b.ext (λ i, _), simp } } theorem constr_def (f : ι → M') : b.constr S f = (finsupp.total M' M' R id) ∘ₗ ((finsupp.lmap_domain R R f) ∘ₗ ↑b.repr) := rfl theorem constr_apply (f : ι → M') (x : M) : b.constr S f x = (b.repr x).sum (λ b a, a • f b) := by { simp only [constr_def, linear_map.comp_apply, finsupp.lmap_domain_apply, finsupp.total_apply], rw finsupp.sum_map_domain_index; simp [add_smul] } @[simp] lemma constr_basis (f : ι → M') (i : ι) : (b.constr S f : M → M') (b i) = f i := by simp [basis.constr_apply, b.repr_self] lemma constr_eq {g : ι → M'} {f : M →ₗ[R] M'} (h : ∀i, g i = f (b i)) : b.constr S g = f := b.ext $ λ i, (b.constr_basis S g i).trans (h i) lemma constr_self (f : M →ₗ[R] M') : b.constr S (λ i, f (b i)) = f := b.constr_eq S $ λ x, rfl lemma constr_range [nonempty ι] {f : ι → M'} : (b.constr S f).range = span R (range f) := by rw [b.constr_def S f, linear_map.range_comp, linear_map.range_comp, linear_equiv.range, ← finsupp.supported_univ, finsupp.lmap_domain_supported, ←set.image_univ, ← finsupp.span_image_eq_map_total, set.image_id] @[simp] lemma constr_comp (f : M' →ₗ[R] M') (v : ι → M') : b.constr S (f ∘ v) = f.comp (b.constr S v) := b.ext (λ i, by simp only [basis.constr_basis, linear_map.comp_apply]) end constr section equiv variables (b' : basis ι' R M') (e : ι ≃ ι') variables [add_comm_monoid M''] [module R M''] /-- If `b` is a basis for `M` and `b'` a basis for `M'`, and the index types are equivalent, `b.equiv b' e` is a linear equivalence `M ≃ₗ[R] M'`, mapping `b i` to `b' (e i)`. -/ protected def equiv : M ≃ₗ[R] M' := b.repr.trans (b'.reindex e.symm).repr.symm @[simp] lemma equiv_apply : b.equiv b' e (b i) = b' (e i) := by simp [basis.equiv] @[simp] lemma equiv_refl : b.equiv b (equiv.refl ι) = linear_equiv.refl R M := b.ext' (λ i, by simp) @[simp] lemma equiv_symm : (b.equiv b' e).symm = b'.equiv b e.symm := b'.ext' $ λ i, (b.equiv b' e).injective (by simp) @[simp] lemma equiv_trans {ι'' : Type*} (b'' : basis ι'' R M'') (e : ι ≃ ι') (e' : ι' ≃ ι'') : (b.equiv b' e).trans (b'.equiv b'' e') = b.equiv b'' (e.trans e') := b.ext' (λ i, by simp) @[simp] lemma map_equiv (b : basis ι R M) (b' : basis ι' R M') (e : ι ≃ ι') : b.map (b.equiv b' e) = b'.reindex e.symm := by { ext i, simp } end equiv section prod variables (b' : basis ι' R M') /-- `basis.prod` maps a `ι`-indexed basis for `M` and a `ι'`-indexed basis for `M'` to a `ι ⊕ ι'`-index basis for `M × M'`. For the specific case of `R × R`, see also `basis.fin_two_prod`. -/ protected def prod : basis (ι ⊕ ι') R (M × M') := of_repr ((b.repr.prod b'.repr).trans (finsupp.sum_finsupp_lequiv_prod_finsupp R).symm) @[simp] lemma prod_repr_inl (x) (i) : (b.prod b').repr x (sum.inl i) = b.repr x.1 i := rfl @[simp] lemma prod_repr_inr (x) (i) : (b.prod b').repr x (sum.inr i) = b'.repr x.2 i := rfl lemma prod_apply_inl_fst (i) : (b.prod b' (sum.inl i)).1 = b i := b.repr.injective $ by { ext j, simp only [basis.prod, basis.coe_of_repr, linear_equiv.symm_trans_apply, linear_equiv.prod_symm, linear_equiv.prod_apply, b.repr.apply_symm_apply, linear_equiv.symm_symm, repr_self, equiv.to_fun_as_coe, finsupp.fst_sum_finsupp_lequiv_prod_finsupp], apply finsupp.single_apply_left sum.inl_injective } lemma prod_apply_inr_fst (i) : (b.prod b' (sum.inr i)).1 = 0 := b.repr.injective $ by { ext i, simp only [basis.prod, basis.coe_of_repr, linear_equiv.symm_trans_apply, linear_equiv.prod_symm, linear_equiv.prod_apply, b.repr.apply_symm_apply, linear_equiv.symm_symm, repr_self, equiv.to_fun_as_coe, finsupp.fst_sum_finsupp_lequiv_prod_finsupp, linear_equiv.map_zero, finsupp.zero_apply], apply finsupp.single_eq_of_ne sum.inr_ne_inl } lemma prod_apply_inl_snd (i) : (b.prod b' (sum.inl i)).2 = 0 := b'.repr.injective $ by { ext j, simp only [basis.prod, basis.coe_of_repr, linear_equiv.symm_trans_apply, linear_equiv.prod_symm, linear_equiv.prod_apply, b'.repr.apply_symm_apply, linear_equiv.symm_symm, repr_self, equiv.to_fun_as_coe, finsupp.snd_sum_finsupp_lequiv_prod_finsupp, linear_equiv.map_zero, finsupp.zero_apply], apply finsupp.single_eq_of_ne sum.inl_ne_inr } lemma prod_apply_inr_snd (i) : (b.prod b' (sum.inr i)).2 = b' i := b'.repr.injective $ by { ext i, simp only [basis.prod, basis.coe_of_repr, linear_equiv.symm_trans_apply, linear_equiv.prod_symm, linear_equiv.prod_apply, b'.repr.apply_symm_apply, linear_equiv.symm_symm, repr_self, equiv.to_fun_as_coe, finsupp.snd_sum_finsupp_lequiv_prod_finsupp], apply finsupp.single_apply_left sum.inr_injective } @[simp] lemma prod_apply (i) : b.prod b' i = sum.elim (linear_map.inl R M M' ∘ b) (linear_map.inr R M M' ∘ b') i := by { ext; cases i; simp only [prod_apply_inl_fst, sum.elim_inl, linear_map.inl_apply, prod_apply_inr_fst, sum.elim_inr, linear_map.inr_apply, prod_apply_inl_snd, prod_apply_inr_snd, comp_app] } end prod section no_zero_smul_divisors -- Can't be an instance because the basis can't be inferred. protected lemma no_zero_smul_divisors [no_zero_divisors R] (b : basis ι R M) : no_zero_smul_divisors R M := ⟨λ c x hcx, or_iff_not_imp_right.mpr (λ hx, begin rw [← b.total_repr x, ← linear_map.map_smul] at hcx, have := linear_independent_iff.mp b.linear_independent (c • b.repr x) hcx, rw smul_eq_zero at this, exact this.resolve_right (λ hr, hx (b.repr.map_eq_zero_iff.mp hr)) end)⟩ protected lemma smul_eq_zero [no_zero_divisors R] (b : basis ι R M) {c : R} {x : M} : c • x = 0 ↔ c = 0 ∨ x = 0 := @smul_eq_zero _ _ _ _ _ b.no_zero_smul_divisors _ _ lemma _root_.eq_bot_of_rank_eq_zero [no_zero_divisors R] (b : basis ι R M) (N : submodule R M) (rank_eq : ∀ {m : ℕ} (v : fin m → N), linear_independent R (coe ∘ v : fin m → M) → m = 0) : N = ⊥ := begin rw submodule.eq_bot_iff, intros x hx, contrapose! rank_eq with x_ne, refine ⟨1, λ _, ⟨x, hx⟩, _, one_ne_zero⟩, rw fintype.linear_independent_iff, rintros g sum_eq i, cases i, simp only [function.const_apply, fin.default_eq_zero, submodule.coe_mk, finset.univ_unique, function.comp_const, finset.sum_singleton] at sum_eq, convert (b.smul_eq_zero.mp sum_eq).resolve_right x_ne end end no_zero_smul_divisors section singleton /-- `basis.singleton ι R` is the basis sending the unique element of `ι` to `1 : R`. -/ protected def singleton (ι R : Type*) [unique ι] [semiring R] : basis ι R R := of_repr { to_fun := λ x, finsupp.single default x, inv_fun := λ f, f default, left_inv := λ x, by simp, right_inv := λ f, finsupp.unique_ext (by simp), map_add' := λ x y, by simp, map_smul' := λ c x, by simp } @[simp] lemma singleton_apply (ι R : Type*) [unique ι] [semiring R] (i) : basis.singleton ι R i = 1 := apply_eq_iff.mpr (by simp [basis.singleton]) @[simp] lemma singleton_repr (ι R : Type*) [unique ι] [semiring R] (x i) : (basis.singleton ι R).repr x i = x := by simp [basis.singleton, unique.eq_default i] lemma basis_singleton_iff {R M : Type*} [ring R] [nontrivial R] [add_comm_group M] [module R M] [no_zero_smul_divisors R M] (ι : Type*) [unique ι] : nonempty (basis ι R M) ↔ ∃ x ≠ 0, ∀ y : M, ∃ r : R, r • x = y := begin fsplit, { rintro ⟨b⟩, refine ⟨b default, b.linear_independent.ne_zero _, _⟩, simpa [span_singleton_eq_top_iff, set.range_unique] using b.span_eq }, { rintro ⟨x, nz, w⟩, refine ⟨of_repr $ linear_equiv.symm { to_fun := λ f, f default • x, inv_fun := λ y, finsupp.single default (w y).some, left_inv := λ f, finsupp.unique_ext _, right_inv := λ y, _, map_add' := λ y z, _, map_smul' := λ c y, _ }⟩, { rw [finsupp.add_apply, add_smul] }, { rw [finsupp.smul_apply, smul_assoc], simp }, { refine smul_left_injective _ nz _, simp only [finsupp.single_eq_same], exact (w (f default • x)).some_spec }, { simp only [finsupp.single_eq_same], exact (w y).some_spec } } end end singleton section empty variables (M) /-- If `M` is a subsingleton and `ι` is empty, this is the unique `ι`-indexed basis for `M`. -/ protected def empty [subsingleton M] [is_empty ι] : basis ι R M := of_repr 0 instance empty_unique [subsingleton M] [is_empty ι] : unique (basis ι R M) := { default := basis.empty M, uniq := λ ⟨x⟩, congr_arg of_repr $ subsingleton.elim _ _ } end empty end basis section fintype open basis open fintype variables [fintype ι] (b : basis ι R M) /-- A module over `R` with a finite basis is linearly equivalent to functions from its basis to `R`. -/ def basis.equiv_fun : M ≃ₗ[R] (ι → R) := linear_equiv.trans b.repr ({ to_fun := coe_fn, map_add' := finsupp.coe_add, map_smul' := finsupp.coe_smul, ..finsupp.equiv_fun_on_finite } : (ι →₀ R) ≃ₗ[R] (ι → R)) /-- A module over a finite ring that admits a finite basis is finite. -/ def module.fintype_of_fintype (b : basis ι R M) [fintype R] : fintype M := by haveI := classical.dec_eq ι; exact fintype.of_equiv _ b.equiv_fun.to_equiv.symm theorem module.card_fintype (b : basis ι R M) [fintype R] [fintype M] : card M = (card R) ^ (card ι) := by classical; exact calc card M = card (ι → R) : card_congr b.equiv_fun.to_equiv ... = card R ^ card ι : card_fun /-- Given a basis `v` indexed by `ι`, the canonical linear equivalence between `ι → R` and `M` maps a function `x : ι → R` to the linear combination `∑_i x i • v i`. -/ @[simp] lemma basis.equiv_fun_symm_apply (x : ι → R) : b.equiv_fun.symm x = ∑ i, x i • b i := by simp [basis.equiv_fun, finsupp.total_apply, finsupp.sum_fintype] @[simp] lemma basis.equiv_fun_apply (u : M) : b.equiv_fun u = b.repr u := rfl @[simp] lemma basis.map_equiv_fun (f : M ≃ₗ[R] M') : (b.map f).equiv_fun = f.symm.trans b.equiv_fun := rfl lemma basis.sum_equiv_fun (u : M) : ∑ i, b.equiv_fun u i • b i = u := begin conv_rhs { rw ← b.total_repr u }, simp [finsupp.total_apply, finsupp.sum_fintype, b.equiv_fun_apply] end lemma basis.sum_repr (u : M) : ∑ i, b.repr u i • b i = u := b.sum_equiv_fun u @[simp] lemma basis.equiv_fun_self [decidable_eq ι] (i j : ι) : b.equiv_fun (b i) j = if i = j then 1 else 0 := by { rw [b.equiv_fun_apply, b.repr_self_apply] } lemma basis.repr_sum_self (c : ι → R) : ⇑(b.repr (∑ i, c i • b i)) = c := begin ext j, simp only [map_sum, linear_equiv.map_smul, repr_self, finsupp.smul_single, smul_eq_mul, mul_one, finset.sum_apply'], rw [finset.sum_eq_single j, finsupp.single_eq_same], { rintros i - hi, exact finsupp.single_eq_of_ne hi }, { intros, have := finset.mem_univ j, contradiction } end /-- Define a basis by mapping each vector `x : M` to its coordinates `e x : ι → R`, as long as `ι` is finite. -/ def basis.of_equiv_fun (e : M ≃ₗ[R] (ι → R)) : basis ι R M := basis.of_repr $ e.trans $ linear_equiv.symm $ finsupp.linear_equiv_fun_on_finite R R ι @[simp] lemma basis.of_equiv_fun_repr_apply (e : M ≃ₗ[R] (ι → R)) (x : M) (i : ι) : (basis.of_equiv_fun e).repr x i = e x i := rfl @[simp] lemma basis.coe_of_equiv_fun [decidable_eq ι] (e : M ≃ₗ[R] (ι → R)) : (basis.of_equiv_fun e : ι → M) = λ i, e.symm (function.update 0 i 1) := funext $ λ i, e.injective $ funext $ λ j, by simp [basis.of_equiv_fun, ←finsupp.single_eq_pi_single, finsupp.single_eq_update] @[simp] lemma basis.of_equiv_fun_equiv_fun (v : basis ι R M) : basis.of_equiv_fun v.equiv_fun = v := begin classical, ext j, simp only [basis.equiv_fun_symm_apply, basis.coe_of_equiv_fun], simp_rw [function.update_apply, ite_smul], simp only [finset.mem_univ, if_true, pi.zero_apply, one_smul, finset.sum_ite_eq', zero_smul], end @[simp] lemma basis.equiv_fun_of_equiv_fun (e : M ≃ₗ[R] (ι → R)) : (basis.of_equiv_fun e).equiv_fun = e := begin ext j, simp_rw [basis.equiv_fun_apply, basis.of_equiv_fun_repr_apply], end variables (S : Type*) [semiring S] [module S M'] variables [smul_comm_class R S M'] @[simp] theorem basis.constr_apply_fintype (f : ι → M') (x : M) : (b.constr S f : M → M') x = ∑ i, (b.equiv_fun x i) • f i := by simp [b.constr_apply, b.equiv_fun_apply, finsupp.sum_fintype] /-- If the submodule `P` has a finite basis, `x ∈ P` iff it is a linear combination of basis vectors. -/ lemma basis.mem_submodule_iff' {P : submodule R M} (b : basis ι R P) {x : M} : x ∈ P ↔ ∃ (c : ι → R), x = ∑ i, c i • b i := b.mem_submodule_iff.trans $ finsupp.equiv_fun_on_finite.exists_congr_left.trans $ exists_congr $ λ c, by simp [finsupp.sum_fintype] lemma basis.coord_equiv_fun_symm (i : ι) (f : ι → R) : b.coord i (b.equiv_fun.symm f) = f i := b.coord_repr_symm i (finsupp.equiv_fun_on_finite.symm f) end fintype end module section comm_semiring namespace basis variables [comm_semiring R] variables [add_comm_monoid M] [module R M] [add_comm_monoid M'] [module R M'] variables (b : basis ι R M) (b' : basis ι' R M') /-- If `b` is a basis for `M` and `b'` a basis for `M'`, and `f`, `g` form a bijection between the basis vectors, `b.equiv' b' f g hf hg hgf hfg` is a linear equivalence `M ≃ₗ[R] M'`, mapping `b i` to `f (b i)`. -/ def equiv' (f : M → M') (g : M' → M) (hf : ∀ i, f (b i) ∈ range b') (hg : ∀ i, g (b' i) ∈ range b) (hgf : ∀i, g (f (b i)) = b i) (hfg : ∀i, f (g (b' i)) = b' i) : M ≃ₗ[R] M' := { inv_fun := b'.constr R (g ∘ b'), left_inv := have (b'.constr R (g ∘ b')).comp (b.constr R (f ∘ b)) = linear_map.id, from (b.ext $ λ i, exists.elim (hf i) (λ i' hi', by rw [linear_map.comp_apply, b.constr_basis, function.comp_apply, ← hi', b'.constr_basis, function.comp_apply, hi', hgf, linear_map.id_apply])), λ x, congr_arg (λ (h : M →ₗ[R] M), h x) this, right_inv := have (b.constr R (f ∘ b)).comp (b'.constr R (g ∘ b')) = linear_map.id, from (b'.ext $ λ i, exists.elim (hg i) (λ i' hi', by rw [linear_map.comp_apply, b'.constr_basis, function.comp_apply, ← hi', b.constr_basis, function.comp_apply, hi', hfg, linear_map.id_apply])), λ x, congr_arg (λ (h : M' →ₗ[R] M'), h x) this, .. b.constr R (f ∘ b) } @[simp] lemma equiv'_apply (f : M → M') (g : M' → M) (hf hg hgf hfg) (i : ι) : b.equiv' b' f g hf hg hgf hfg (b i) = f (b i) := b.constr_basis R _ _ @[simp] lemma equiv'_symm_apply (f : M → M') (g : M' → M) (hf hg hgf hfg) (i : ι') : (b.equiv' b' f g hf hg hgf hfg).symm (b' i) = g (b' i) := b'.constr_basis R _ _ lemma sum_repr_mul_repr {ι'} [fintype ι'] (b' : basis ι' R M) (x : M) (i : ι) : ∑ (j : ι'), b.repr (b' j) i * b'.repr x j = b.repr x i := begin conv_rhs { rw [← b'.sum_repr x] }, simp_rw [linear_equiv.map_sum, linear_equiv.map_smul, finset.sum_apply'], refine finset.sum_congr rfl (λ j _, _), rw [finsupp.smul_apply, smul_eq_mul, mul_comm] end end basis end comm_semiring section module open linear_map variables {v : ι → M} variables [ring R] [comm_ring R₂] [add_comm_group M] [add_comm_group M'] [add_comm_group M''] variables [module R M] [module R₂ M] [module R M'] [module R M''] variables {c d : R} {x y : M} variables (b : basis ι R M) namespace basis /-- Any basis is a maximal linear independent set. -/ lemma maximal [nontrivial R] (b : basis ι R M) : b.linear_independent.maximal := λ w hi h, begin -- If `range w` is strictly bigger than `range b`, apply le_antisymm h, -- then choose some `x ∈ range w \ range b`, intros x p, by_contradiction q, -- and write it in terms of the basis. have e := b.total_repr x, -- This then expresses `x` as a linear combination -- of elements of `w` which are in the range of `b`, let u : ι ↪ w := ⟨λ i, ⟨b i, h ⟨i, rfl⟩⟩, λ i i' r, b.injective (by simpa only [subtype.mk_eq_mk] using r)⟩, have r : ∀ i, b i = u i := λ i, rfl, simp_rw [finsupp.total_apply, r] at e, change (b.repr x).sum (λ (i : ι) (a : R), (λ (x : w) (r : R), r • (x : M)) (u i) a) = ((⟨x, p⟩ : w) : M) at e, rw [←finsupp.sum_emb_domain, ←finsupp.total_apply] at e, -- Now we can contradict the linear independence of `hi` refine hi.total_ne_of_not_mem_support _ _ e, simp only [finset.mem_map, finsupp.support_emb_domain], rintro ⟨j, -, W⟩, simp only [embedding.coe_fn_mk, subtype.mk_eq_mk, ←r] at W, apply q ⟨j, W⟩, end section mk variables (hli : linear_independent R v) (hsp : ⊤ ≤ span R (range v)) /-- A linear independent family of vectors spanning the whole module is a basis. -/ protected noncomputable def mk : basis ι R M := basis.of_repr { inv_fun := finsupp.total _ _ _ v, left_inv := λ x, hli.total_repr ⟨x, _⟩, right_inv := λ x, hli.repr_eq rfl, .. hli.repr.comp (linear_map.id.cod_restrict _ (λ h, hsp submodule.mem_top)) } @[simp] lemma mk_repr : (basis.mk hli hsp).repr x = hli.repr ⟨x, hsp submodule.mem_top⟩ := rfl lemma mk_apply (i : ι) : basis.mk hli hsp i = v i := show finsupp.total _ _ _ v _ = v i, by simp @[simp] lemma coe_mk : ⇑(basis.mk hli hsp) = v := funext (mk_apply _ _) variables {hli hsp} /-- Given a basis, the `i`th element of the dual basis evaluates to 1 on the `i`th element of the basis. -/ lemma mk_coord_apply_eq (i : ι) : (basis.mk hli hsp).coord i (v i) = 1 := show hli.repr ⟨v i, submodule.subset_span (mem_range_self i)⟩ i = 1, by simp [hli.repr_eq_single i] /-- Given a basis, the `i`th element of the dual basis evaluates to 0 on the `j`th element of the basis if `j ≠ i`. -/ lemma mk_coord_apply_ne {i j : ι} (h : j ≠ i) : (basis.mk hli hsp).coord i (v j) = 0 := show hli.repr ⟨v j, submodule.subset_span (mem_range_self j)⟩ i = 0, by simp [hli.repr_eq_single j, h] /-- Given a basis, the `i`th element of the dual basis evaluates to the Kronecker delta on the `j`th element of the basis. -/ lemma mk_coord_apply [decidable_eq ι] {i j : ι} : (basis.mk hli hsp).coord i (v j) = if j = i then 1 else 0 := begin cases eq_or_ne j i, { simp only [h, if_true, eq_self_iff_true, mk_coord_apply_eq i], }, { simp only [h, if_false, mk_coord_apply_ne h], }, end end mk section span variables (hli : linear_independent R v) /-- A linear independent family of vectors is a basis for their span. -/ protected noncomputable def span : basis ι R (span R (range v)) := basis.mk (linear_independent_span hli) $ begin intros x _, have h₁ : (coe : span R (range v) → M) '' set.range (λ i, subtype.mk (v i) _) = range v, { rw ← set.range_comp, refl }, have h₂ : map (submodule.subtype (span R (range v))) (span R (set.range (λ i, subtype.mk (v i) _))) = span R (range v), { rw [← span_image, submodule.coe_subtype, h₁] }, have h₃ : (x : M) ∈ map (submodule.subtype (span R (range v))) (span R (set.range (λ i, subtype.mk (v i) _))), { rw h₂, apply subtype.mem x }, rcases mem_map.1 h₃ with ⟨y, hy₁, hy₂⟩, have h_x_eq_y : x = y, { rw [subtype.ext_iff, ← hy₂], simp }, rwa h_x_eq_y end protected lemma span_apply (i : ι) : (basis.span hli i : M) = v i := congr_arg (coe : span R (range v) → M) $ basis.mk_apply (linear_independent_span hli) _ i end span lemma group_smul_span_eq_top {G : Type*} [group G] [distrib_mul_action G R] [distrib_mul_action G M] [is_scalar_tower G R M] {v : ι → M} (hv : submodule.span R (set.range v) = ⊤) {w : ι → G} : submodule.span R (set.range (w • v)) = ⊤ := begin rw eq_top_iff, intros j hj, rw ← hv at hj, rw submodule.mem_span at hj ⊢, refine λ p hp, hj p (λ u hu, _), obtain ⟨i, rfl⟩ := hu, have : ((w i)⁻¹ • 1 : R) • w i • v i ∈ p := p.smul_mem ((w i)⁻¹ • 1 : R) (hp ⟨i, rfl⟩), rwa [smul_one_smul, inv_smul_smul] at this, end /-- Given a basis `v` and a map `w` such that for all `i`, `w i` are elements of a group, `group_smul` provides the basis corresponding to `w • v`. -/ def group_smul {G : Type*} [group G] [distrib_mul_action G R] [distrib_mul_action G M] [is_scalar_tower G R M] [smul_comm_class G R M] (v : basis ι R M) (w : ι → G) : basis ι R M := @basis.mk ι R M (w • v) _ _ _ (v.linear_independent.group_smul w) (group_smul_span_eq_top v.span_eq).ge lemma group_smul_apply {G : Type*} [group G] [distrib_mul_action G R] [distrib_mul_action G M] [is_scalar_tower G R M] [smul_comm_class G R M] {v : basis ι R M} {w : ι → G} (i : ι) : v.group_smul w i = (w • v : ι → M) i := mk_apply (v.linear_independent.group_smul w) (group_smul_span_eq_top v.span_eq).ge i lemma units_smul_span_eq_top {v : ι → M} (hv : submodule.span R (set.range v) = ⊤) {w : ι → Rˣ} : submodule.span R (set.range (w • v)) = ⊤ := group_smul_span_eq_top hv /-- Given a basis `v` and a map `w` such that for all `i`, `w i` is a unit, `smul_of_is_unit` provides the basis corresponding to `w • v`. -/ def units_smul (v : basis ι R M) (w : ι → Rˣ) : basis ι R M := @basis.mk ι R M (w • v) _ _ _ (v.linear_independent.units_smul w) (units_smul_span_eq_top v.span_eq).ge lemma units_smul_apply {v : basis ι R M} {w : ι → Rˣ} (i : ι) : v.units_smul w i = w i • v i := mk_apply (v.linear_independent.units_smul w) (units_smul_span_eq_top v.span_eq).ge i @[simp] lemma coord_units_smul (e : basis ι R₂ M) (w : ι → R₂ˣ) (i : ι) : (e.units_smul w).coord i = (w i)⁻¹ • e.coord i := begin classical, apply e.ext, intros j, transitivity ((e.units_smul w).coord i) ((w j)⁻¹ • (e.units_smul w) j), { congr, simp [basis.units_smul, ← mul_smul], }, simp only [basis.coord_apply, linear_map.smul_apply, basis.repr_self, units.smul_def, smul_hom_class.map_smul, finsupp.single_apply], split_ifs with h h, { simp [h] }, { simp } end @[simp] lemma repr_units_smul (e : basis ι R₂ M) (w : ι → R₂ˣ) (v : M) (i : ι) : (e.units_smul w).repr v i = (w i)⁻¹ • e.repr v i := congr_arg (λ f : M →ₗ[R₂] R₂, f v) (e.coord_units_smul w i) /-- A version of `smul_of_units` that uses `is_unit`. -/ def is_unit_smul (v : basis ι R M) {w : ι → R} (hw : ∀ i, is_unit (w i)): basis ι R M := units_smul v (λ i, (hw i).unit) lemma is_unit_smul_apply {v : basis ι R M} {w : ι → R} (hw : ∀ i, is_unit (w i)) (i : ι) : v.is_unit_smul hw i = w i • v i := units_smul_apply i section fin /-- Let `b` be a basis for a submodule `N` of `M`. If `y : M` is linear independent of `N` and `y` and `N` together span the whole of `M`, then there is a basis for `M` whose basis vectors are given by `fin.cons y b`. -/ noncomputable def mk_fin_cons {n : ℕ} {N : submodule R M} (y : M) (b : basis (fin n) R N) (hli : ∀ (c : R) (x ∈ N), c • y + x = 0 → c = 0) (hsp : ∀ (z : M), ∃ (c : R), z + c • y ∈ N) : basis (fin (n + 1)) R M := have span_b : submodule.span R (set.range (N.subtype ∘ b)) = N, { rw [set.range_comp, submodule.span_image, b.span_eq, submodule.map_subtype_top] }, @basis.mk _ _ _ (fin.cons y (N.subtype ∘ b) : fin (n + 1) → M) _ _ _ ((b.linear_independent.map' N.subtype (submodule.ker_subtype _)) .fin_cons' _ _ $ by { rintros c ⟨x, hx⟩ hc, rw span_b at hx, exact hli c x hx hc }) (λ x _, by { rw [fin.range_cons, submodule.mem_span_insert', span_b], exact hsp x }) @[simp] lemma coe_mk_fin_cons {n : ℕ} {N : submodule R M} (y : M) (b : basis (fin n) R N) (hli : ∀ (c : R) (x ∈ N), c • y + x = 0 → c = 0) (hsp : ∀ (z : M), ∃ (c : R), z + c • y ∈ N) : (mk_fin_cons y b hli hsp : fin (n + 1) → M) = fin.cons y (coe ∘ b) := coe_mk _ _ /-- Let `b` be a basis for a submodule `N ≤ O`. If `y ∈ O` is linear independent of `N` and `y` and `N` together span the whole of `O`, then there is a basis for `O` whose basis vectors are given by `fin.cons y b`. -/ noncomputable def mk_fin_cons_of_le {n : ℕ} {N O : submodule R M} (y : M) (yO : y ∈ O) (b : basis (fin n) R N) (hNO : N ≤ O) (hli : ∀ (c : R) (x ∈ N), c • y + x = 0 → c = 0) (hsp : ∀ (z ∈ O), ∃ (c : R), z + c • y ∈ N) : basis (fin (n + 1)) R O := mk_fin_cons ⟨y, yO⟩ (b.map (submodule.comap_subtype_equiv_of_le hNO).symm) (λ c x hc hx, hli c x (submodule.mem_comap.mp hc) (congr_arg coe hx)) (λ z, hsp z z.2) @[simp] lemma coe_mk_fin_cons_of_le {n : ℕ} {N O : submodule R M} (y : M) (yO : y ∈ O) (b : basis (fin n) R N) (hNO : N ≤ O) (hli : ∀ (c : R) (x ∈ N), c • y + x = 0 → c = 0) (hsp : ∀ (z ∈ O), ∃ (c : R), z + c • y ∈ N) : (mk_fin_cons_of_le y yO b hNO hli hsp : fin (n + 1) → O) = fin.cons ⟨y, yO⟩ (submodule.of_le hNO ∘ b) := coe_mk_fin_cons _ _ _ _ /-- The basis of `R × R` given by the two vectors `(1, 0)` and `(0, 1)`. -/ protected def fin_two_prod (R : Type*) [semiring R] : basis (fin 2) R (R × R) := basis.of_equiv_fun (linear_equiv.fin_two_arrow R R).symm @[simp] lemma fin_two_prod_zero (R : Type*) [semiring R] : basis.fin_two_prod R 0 = (1, 0) := by simp [basis.fin_two_prod] @[simp] lemma fin_two_prod_one (R : Type*) [semiring R] : basis.fin_two_prod R 1 = (0, 1) := by simp [basis.fin_two_prod] @[simp] lemma coe_fin_two_prod_repr {R : Type*} [semiring R] (x : R × R) : ⇑((basis.fin_two_prod R).repr x) = ![x.fst, x.snd] := rfl end fin end basis end module section induction variables [ring R] [is_domain R] variables [add_comm_group M] [module R M] {b : ι → M} /-- If `N` is a submodule with finite rank, do induction on adjoining a linear independent element to a submodule. -/ def submodule.induction_on_rank_aux (b : basis ι R M) (P : submodule R M → Sort*) (ih : ∀ (N : submodule R M), (∀ (N' ≤ N) (x ∈ N), (∀ (c : R) (y ∈ N'), c • x + y = (0 : M) → c = 0) → P N') → P N) (n : ℕ) (N : submodule R M) (rank_le : ∀ {m : ℕ} (v : fin m → N), linear_independent R (coe ∘ v : fin m → M) → m ≤ n) : P N := begin haveI : decidable_eq M := classical.dec_eq M, have Pbot : P ⊥, { apply ih, intros N N_le x x_mem x_ortho, exfalso, simpa using x_ortho 1 0 N.zero_mem }, induction n with n rank_ih generalizing N, { suffices : N = ⊥, { rwa this }, apply eq_bot_of_rank_eq_zero b _ (λ m v hv, le_zero_iff.mp (rank_le v hv)) }, apply ih, intros N' N'_le x x_mem x_ortho, apply rank_ih, intros m v hli, refine nat.succ_le_succ_iff.mp (rank_le (fin.cons ⟨x, x_mem⟩ (λ i, ⟨v i, N'_le (v i).2⟩)) _), convert hli.fin_cons' x _ _, { ext i, refine fin.cases _ _ i; simp }, { intros c y hcy, refine x_ortho c y (submodule.span_le.mpr _ y.2) hcy, rintros _ ⟨z, rfl⟩, exact (v z).2 } end end induction section division_ring variables [division_ring K] [add_comm_group V] [add_comm_group V'] [module K V] [module K V'] variables {v : ι → V} {s t : set V} {x y z : V} include K open submodule namespace basis section exists_basis /-- If `s` is a linear independent set of vectors, we can extend it to a basis. -/ noncomputable def extend (hs : linear_independent K (coe : s → V)) : basis _ K V := basis.mk (@linear_independent.restrict_of_comp_subtype _ _ _ id _ _ _ _ (hs.linear_independent_extend _)) (set_like.coe_subset_coe.mp $ by simpa using hs.subset_span_extend (subset_univ s)) lemma extend_apply_self (hs : linear_independent K (coe : s → V)) (x : hs.extend _) : basis.extend hs x = x := basis.mk_apply _ _ _ @[simp] lemma coe_extend (hs : linear_independent K (coe : s → V)) : ⇑(basis.extend hs) = coe := funext (extend_apply_self hs) lemma range_extend (hs : linear_independent K (coe : s → V)) : range (basis.extend hs) = hs.extend (subset_univ _) := by rw [coe_extend, subtype.range_coe_subtype, set_of_mem_eq] /-- If `v` is a linear independent family of vectors, extend it to a basis indexed by a sum type. -/ noncomputable def sum_extend (hs : linear_independent K v) : basis (ι ⊕ _) K V := let s := set.range v, e : ι ≃ s := equiv.of_injective v hs.injective, b := hs.to_subtype_range.extend (subset_univ (set.range v)) in (basis.extend hs.to_subtype_range).reindex $ equiv.symm $ calc ι ⊕ (b \ s : set V) ≃ s ⊕ (b \ s : set V) : equiv.sum_congr e (equiv.refl _) ... ≃ b : by haveI := classical.dec_pred (∈ s); exact equiv.set.sum_diff_subset (hs.to_subtype_range.subset_extend _) lemma subset_extend {s : set V} (hs : linear_independent K (coe : s → V)) : s ⊆ hs.extend (set.subset_univ _) := hs.subset_extend _ section variables (K V) /-- A set used to index `basis.of_vector_space`. -/ noncomputable def of_vector_space_index : set V := (linear_independent_empty K V).extend (subset_univ _) /-- Each vector space has a basis. -/ noncomputable def of_vector_space : basis (of_vector_space_index K V) K V := basis.extend (linear_independent_empty K V) lemma of_vector_space_apply_self (x : of_vector_space_index K V) : of_vector_space K V x = x := basis.mk_apply _ _ _ @[simp] lemma coe_of_vector_space : ⇑(of_vector_space K V) = coe := funext (λ x, of_vector_space_apply_self K V x) lemma of_vector_space_index.linear_independent : linear_independent K (coe : of_vector_space_index K V → V) := by { convert (of_vector_space K V).linear_independent, ext x, rw of_vector_space_apply_self } lemma range_of_vector_space : range (of_vector_space K V) = of_vector_space_index K V := range_extend _ lemma exists_basis : ∃ s : set V, nonempty (basis s K V) := ⟨of_vector_space_index K V, ⟨of_vector_space K V⟩⟩ end end exists_basis end basis open fintype variables (K V) theorem vector_space.card_fintype [fintype K] [fintype V] : ∃ n : ℕ, card V = (card K) ^ n := by classical; exact ⟨card (basis.of_vector_space_index K V), module.card_fintype (basis.of_vector_space K V)⟩ section atoms_of_submodule_lattice variables {K V} /-- For a module over a division ring, the span of a nonzero element is an atom of the lattice of submodules. -/ lemma nonzero_span_atom (v : V) (hv : v ≠ 0) : is_atom (span K {v} : submodule K V) := begin split, { rw submodule.ne_bot_iff, exact ⟨v, ⟨mem_span_singleton_self v, hv⟩⟩ }, { intros T hT, by_contra, apply hT.2, change (span K {v}) ≤ T, simp_rw [span_singleton_le_iff_mem, ← ne.def, submodule.ne_bot_iff] at *, rcases h with ⟨s, ⟨hs, hz⟩⟩, cases (mem_span_singleton.1 (hT.1 hs)) with a ha, have h : a ≠ 0, by { intro h, rw [h, zero_smul] at ha, exact hz ha.symm }, apply_fun (λ x, a⁻¹ • x) at ha, simp_rw [← mul_smul, inv_mul_cancel h, one_smul, ha] at *, exact smul_mem T _ hs}, end /-- The atoms of the lattice of submodules of a module over a division ring are the submodules equal to the span of a nonzero element of the module. -/ lemma atom_iff_nonzero_span (W : submodule K V) : is_atom W ↔ ∃ (v : V) (hv : v ≠ 0), W = span K {v} := begin refine ⟨λ h, _, λ h, _ ⟩, { cases h with hbot h, rcases ((submodule.ne_bot_iff W).1 hbot) with ⟨v, ⟨hW, hv⟩⟩, refine ⟨v, ⟨hv, _⟩⟩, by_contra heq, specialize h (span K {v}), rw [span_singleton_eq_bot, lt_iff_le_and_ne] at h, exact hv (h ⟨(span_singleton_le_iff_mem v W).2 hW, ne.symm heq⟩) }, { rcases h with ⟨v, ⟨hv, rfl⟩⟩, exact nonzero_span_atom v hv }, end /-- The lattice of submodules of a module over a division ring is atomistic. -/ instance : is_atomistic (submodule K V) := { eq_Sup_atoms := begin intro W, use {T : submodule K V | ∃ (v : V) (hv : v ∈ W) (hz : v ≠ 0), T = span K {v}}, refine ⟨submodule_eq_Sup_le_nonzero_spans W, _⟩, rintros _ ⟨w, ⟨_, ⟨hw, rfl⟩⟩⟩, exact nonzero_span_atom w hw end } end atoms_of_submodule_lattice variables {K V} lemma linear_map.exists_left_inverse_of_injective (f : V →ₗ[K] V') (hf_inj : f.ker = ⊥) : ∃g:V' →ₗ[K] V, g.comp f = linear_map.id := begin let B := basis.of_vector_space_index K V, let hB := basis.of_vector_space K V, have hB₀ : _ := hB.linear_independent.to_subtype_range, have : linear_independent K (λ x, x : f '' B → V'), { have h₁ : linear_independent K (λ (x : ↥(⇑f '' range (basis.of_vector_space _ _))), ↑x) := @linear_independent.image_subtype _ _ _ _ _ _ _ _ _ f hB₀ (show disjoint _ _, by simp [hf_inj]), rwa [basis.range_of_vector_space K V] at h₁ }, let C := this.extend (subset_univ _), have BC := this.subset_extend (subset_univ _), let hC := basis.extend this, haveI : inhabited V := ⟨0⟩, refine ⟨hC.constr ℕ (C.restrict (inv_fun f)), hB.ext (λ b, _)⟩, rw image_subset_iff at BC, have fb_eq : f b = hC ⟨f b, BC b.2⟩, { change f b = basis.extend this _, rw [basis.extend_apply_self, subtype.coe_mk] }, dsimp [hB], rw [basis.of_vector_space_apply_self, fb_eq, hC.constr_basis], exact left_inverse_inv_fun (linear_map.ker_eq_bot.1 hf_inj) _ end lemma submodule.exists_is_compl (p : submodule K V) : ∃ q : submodule K V, is_compl p q := let ⟨f, hf⟩ := p.subtype.exists_left_inverse_of_injective p.ker_subtype in ⟨f.ker, linear_map.is_compl_of_proj $ linear_map.ext_iff.1 hf⟩ instance module.submodule.complemented_lattice : complemented_lattice (submodule K V) := ⟨submodule.exists_is_compl⟩ lemma linear_map.exists_right_inverse_of_surjective (f : V →ₗ[K] V') (hf_surj : f.range = ⊤) : ∃g:V' →ₗ[K] V, f.comp g = linear_map.id := begin let C := basis.of_vector_space_index K V', let hC := basis.of_vector_space K V', haveI : inhabited V := ⟨0⟩, use hC.constr ℕ (C.restrict (inv_fun f)), refine hC.ext (λ c, _), rw [linear_map.comp_apply, hC.constr_basis], simp [right_inverse_inv_fun (linear_map.range_eq_top.1 hf_surj) c] end /-- Any linear map `f : p →ₗ[K] V'` defined on a subspace `p` can be extended to the whole space. -/ lemma linear_map.exists_extend {p : submodule K V} (f : p →ₗ[K] V') : ∃ g : V →ₗ[K] V', g.comp p.subtype = f := let ⟨g, hg⟩ := p.subtype.exists_left_inverse_of_injective p.ker_subtype in ⟨f.comp g, by rw [linear_map.comp_assoc, hg, f.comp_id]⟩ open submodule linear_map /-- If `p < ⊤` is a subspace of a vector space `V`, then there exists a nonzero linear map `f : V →ₗ[K] K` such that `p ≤ ker f`. -/ lemma submodule.exists_le_ker_of_lt_top (p : submodule K V) (hp : p < ⊤) : ∃ f ≠ (0 : V →ₗ[K] K), p ≤ ker f := begin rcases set_like.exists_of_lt hp with ⟨v, -, hpv⟩, clear hp, rcases (linear_pmap.sup_span_singleton ⟨p, 0⟩ v (1 : K) hpv).to_fun.exists_extend with ⟨f, hf⟩, refine ⟨f, _, _⟩, { rintro rfl, rw [linear_map.zero_comp] at hf, have := linear_pmap.sup_span_singleton_apply_mk ⟨p, 0⟩ v (1 : K) hpv 0 p.zero_mem 1, simpa using (linear_map.congr_fun hf _).trans this }, { refine λ x hx, mem_ker.2 _, have := linear_pmap.sup_span_singleton_apply_mk ⟨p, 0⟩ v (1 : K) hpv x hx 0, simpa using (linear_map.congr_fun hf _).trans this } end theorem quotient_prod_linear_equiv (p : submodule K V) : nonempty (((V ⧸ p) × p) ≃ₗ[K] V) := let ⟨q, hq⟩ := p.exists_is_compl in nonempty.intro $ ((quotient_equiv_of_is_compl p q hq).prod (linear_equiv.refl _ _)).trans (prod_equiv_of_is_compl q p hq.symm) end division_ring section restrict_scalars variables {S : Type*} [comm_ring R] [ring S] [nontrivial S] [add_comm_group M] variables [algebra R S] [module S M] [module R M] variables [is_scalar_tower R S M] [no_zero_smul_divisors R S] (b : basis ι S M) variables (R) open submodule /-- Let `b` be a `S`-basis of `M`. Let `R` be a comm_ring such that `algebra R S` with no zero smul divisors, then the submodule of `M` spanned by `b` over `R` admits `b` as a `R`-basis. -/ noncomputable def basis.restrict_scalars : basis ι R (span R (set.range b)) := basis.span (b.linear_independent.restrict_scalars (smul_left_injective R one_ne_zero)) @[simp] lemma basis.restrict_scalars_apply (i : ι) : (b.restrict_scalars R i : M) = b i := by simp only [basis.restrict_scalars, basis.span_apply] @[simp] lemma basis.restrict_scalars_repr_apply (m : span R (set.range b)) (i : ι) : algebra_map R S ((b.restrict_scalars R).repr m i) = b.repr m i := begin suffices : finsupp.map_range.linear_map (algebra.linear_map R S) ∘ₗ (b.restrict_scalars R).repr.to_linear_map = ((b.repr : M →ₗ[S] (ι →₀ S)).restrict_scalars R).dom_restrict _, { exact finsupp.congr_fun (linear_map.congr_fun this m) i, }, refine basis.ext (b.restrict_scalars R) (λ _, _), simp only [linear_map.coe_comp, linear_equiv.coe_to_linear_map, function.comp_app, map_one, basis.repr_self, finsupp.map_range.linear_map_apply, finsupp.map_range_single, algebra.linear_map_apply, linear_map.dom_restrict_apply, linear_equiv.coe_coe, basis.restrict_scalars_apply, linear_map.coe_restrict_scalars_eq_coe], end /-- Let `b` be a `S`-basis of `M`. Then `m : M` lies in the `R`-module spanned by `b` iff all the coordinates of `m` on the basis `b` are in `R` (see `basis.mem_span` for the case `R = S`). -/ lemma basis.mem_span_iff_repr_mem (m : M) : m ∈ span R (set.range b) ↔ ∀ i, b.repr m i ∈ set.range (algebra_map R S) := begin refine ⟨λ hm i, ⟨(b.restrict_scalars R).repr ⟨m, hm⟩ i, (b.restrict_scalars_repr_apply R ⟨m, hm⟩ i)⟩, λ h, _⟩, rw [← b.total_repr m, finsupp.total_apply S _], refine sum_mem (λ i _, _), obtain ⟨_, h⟩ := h i, simp_rw [← h, algebra_map_smul], exact smul_mem _ _ (subset_span (set.mem_range_self i)), end end restrict_scalars
2cc7b4f291e917315f180b8b8ff813c37e69d654
6dc0c8ce7a76229dd81e73ed4474f15f88a9e294
/stage0/src/Std/Data/HashSet.lean
a57adbea912c6ee5cb854479bcf8d97e0cc0aef6
[ "Apache-2.0" ]
permissive
williamdemeo/lean4
72161c58fe65c3ad955d6a3050bb7d37c04c0d54
6d00fcf1d6d873e195f9220c668ef9c58e9c4a35
refs/heads/master
1,678,305,356,877
1,614,708,995,000
1,614,708,995,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
6,069
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 -/ namespace Std universes u v w def HashSetBucket (α : Type u) := { b : Array (List α) // b.size > 0 } def HashSetBucket.update {α : Type u} (data : HashSetBucket α) (i : USize) (d : List α) (h : i.toNat < data.val.size) : HashSetBucket α := ⟨ data.val.uset i d h, by erw [Array.size_set]; exact data.property ⟩ structure HashSetImp (α : Type u) where size : Nat buckets : HashSetBucket α def mkHashSetImp {α : Type u} (nbuckets := 8) : HashSetImp α := let n := if nbuckets = 0 then 8 else nbuckets { size := 0, buckets := ⟨ mkArray n [], by rw [Array.size_mkArray]; cases nbuckets; decide!; apply Nat.zeroLtSucc ⟩ } namespace HashSetImp variable {α : Type u} def mkIdx {n : Nat} (h : n > 0) (u : USize) : { u : USize // u.toNat < n } := ⟨u % n, USize.modnLt _ h⟩ @[inline] def reinsertAux (hashFn : α → USize) (data : HashSetBucket α) (a : α) : HashSetBucket α := let ⟨i, h⟩ := mkIdx data.property (hashFn a) data.update i (a :: data.val.uget i h) h @[inline] def foldBucketsM {δ : Type w} {m : Type w → Type w} [Monad m] (data : HashSetBucket α) (d : δ) (f : δ → α → m δ) : m δ := data.val.foldlM (init := d) fun d as => as.foldlM f d @[inline] def foldBuckets {δ : Type w} (data : HashSetBucket α) (d : δ) (f : δ → α → δ) : δ := Id.run $ foldBucketsM data d f @[inline] def foldM {δ : Type w} {m : Type w → Type w} [Monad m] (f : δ → α → m δ) (d : δ) (h : HashSetImp α) : m δ := foldBucketsM h.buckets d f @[inline] def fold {δ : Type w} (f : δ → α → δ) (d : δ) (m : HashSetImp α) : δ := foldBuckets m.buckets d f def find? [BEq α] [Hashable α] (m : HashSetImp α) (a : α) : Option α := match m with | ⟨_, buckets⟩ => let ⟨i, h⟩ := mkIdx buckets.property (hash a) (buckets.val.uget i h).find? (fun a' => a == a') def contains [BEq α] [Hashable α] (m : HashSetImp α) (a : α) : Bool := match m with | ⟨_, buckets⟩ => let ⟨i, h⟩ := mkIdx buckets.property (hash a) (buckets.val.uget i h).contains a -- TODO: remove `partial` by using well-founded recursion partial def moveEntries [Hashable α] (i : Nat) (source : Array (List α)) (target : HashSetBucket α) : HashSetBucket α := if h : i < source.size then let idx : Fin source.size := ⟨i, h⟩ let es : List α := source.get idx -- We remove `es` from `source` to make sure we can reuse its memory cells when performing es.foldl let source := source.set idx [] let target := es.foldl (reinsertAux hash) target moveEntries (i+1) source target else target def expand [Hashable α] (size : Nat) (buckets : HashSetBucket α) : HashSetImp α := let nbuckets := buckets.val.size * 2 have nbuckets > 0 from Nat.mulPos buckets.property (decide! : 2 > 0) let new_buckets : HashSetBucket α := ⟨mkArray nbuckets [], by rw [Array.size_mkArray]; assumption⟩ { size := size, buckets := moveEntries 0 buckets.val new_buckets } def insert [BEq α] [Hashable α] (m : HashSetImp α) (a : α) : HashSetImp α := match m with | ⟨size, buckets⟩ => let ⟨i, h⟩ := mkIdx buckets.property (hash a) let bkt := buckets.val.uget i h if bkt.contains a then ⟨size, buckets.update i (bkt.replace a a) h⟩ else let size' := size + 1 let buckets' := buckets.update i (a :: bkt) h if size' ≤ buckets.val.size then { size := size', buckets := buckets' } else expand size' buckets' def erase [BEq α] [Hashable α] (m : HashSetImp α) (a : α) : HashSetImp α := match m with | ⟨ size, buckets ⟩ => let ⟨i, h⟩ := mkIdx buckets.property (hash a) let bkt := buckets.val.uget i h if bkt.contains a then ⟨size - 1, buckets.update i (bkt.erase a) h⟩ else m inductive WellFormed [BEq α] [Hashable α] : HashSetImp α → Prop where | mkWff : ∀ n, WellFormed (mkHashSetImp n) | insertWff : ∀ m a, WellFormed m → WellFormed (insert m a) | eraseWff : ∀ m a, WellFormed m → WellFormed (erase m a) end HashSetImp def HashSet (α : Type u) [BEq α] [Hashable α] := { m : HashSetImp α // m.WellFormed } open HashSetImp def mkHashSet {α : Type u} [BEq α] [Hashable α] (nbuckets := 8) : HashSet α := ⟨ mkHashSetImp nbuckets, WellFormed.mkWff nbuckets ⟩ namespace HashSet variable {α : Type u} [BEq α] [Hashable α] instance : Inhabited (HashSet α) where default := mkHashSet instance : EmptyCollection (HashSet α) := ⟨mkHashSet⟩ @[inline] def insert (m : HashSet α) (a : α) : HashSet α := match m with | ⟨ m, hw ⟩ => ⟨ m.insert a, WellFormed.insertWff m a hw ⟩ @[inline] def erase (m : HashSet α) (a : α) : HashSet α := match m with | ⟨ m, hw ⟩ => ⟨ m.erase a, WellFormed.eraseWff m a hw ⟩ @[inline] def find? (m : HashSet α) (a : α) : Option α := match m with | ⟨ m, _ ⟩ => m.find? a @[inline] def contains (m : HashSet α) (a : α) : Bool := match m with | ⟨ m, _ ⟩ => m.contains a @[inline] def foldM {δ : Type w} {m : Type w → Type w} [Monad m] (f : δ → α → m δ) (init : δ) (h : HashSet α) : m δ := match h with | ⟨ h, _ ⟩ => h.foldM f init @[inline] def fold {δ : Type w} (f : δ → α → δ) (init : δ) (m : HashSet α) : δ := match m with | ⟨ m, _ ⟩ => m.fold f init @[inline] def size (m : HashSet α) : Nat := match m with | ⟨ {size := sz, ..}, _ ⟩ => sz @[inline] def isEmpty (m : HashSet α) : Bool := m.size = 0 @[inline] def empty : HashSet α := mkHashSet def toList (m : HashSet α) : List α := m.fold (init := []) fun r a => a::r def toArray (m : HashSet α) : Array α := m.fold (init := #[]) fun r a => r.push a def numBuckets (m : HashSet α) : Nat := m.val.buckets.val.size end HashSet end Std
b156623f62a9479c2c73b4d5e076e7b70042e3ff
947b78d97130d56365ae2ec264df196ce769371a
/tests/lean/inst.lean
37cd398715ec6a913c34fa1b654adbd9c7af209f
[ "Apache-2.0" ]
permissive
shyamalschandra/lean4
27044812be8698f0c79147615b1d5090b9f4b037
6e7a883b21eaf62831e8111b251dc9b18f40e604
refs/heads/master
1,671,417,126,371
1,601,859,995,000
1,601,860,020,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
508
lean
import Lean.Expr new_frontend open Lean def tst : IO Unit := do let f := mkConst `f; let x := mkBVar 0; let y := mkBVar 1; let t := mkApp (mkApp (mkApp f x) y) x; let a := mkConst `a; let b := mkApp f (mkConst `b); let c := mkConst `c; IO.println t; IO.println (t.instantiate #[a, b]); IO.println (t.instantiateRange 0 2 #[a, b]); IO.println (t.instantiateRange 2 4 #[c, c, a, b, c]); IO.println (t.instantiateRev #[a, b]); IO.println (t.instantiate #[a]); IO.println (t.instantiate1 a); pure () #eval tst
25baecb81328ca57b80c92f3bba8a958a0867746
c777c32c8e484e195053731103c5e52af26a25d1
/src/algebraic_topology/dold_kan/gamma_comp_n.lean
b3d66c5c2cfccb0b0bbb45a03c10cef6309b4980
[ "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
6,614
lean
/- Copyright (c) 2022 Joël Riou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joël Riou -/ import algebraic_topology.dold_kan.functor_gamma import category_theory.idempotents.homological_complex /-! > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. The counit isomorphism of the Dold-Kan equivalence The purpose of this file is to construct natural isomorphisms `N₁Γ₀ : Γ₀ ⋙ N₁ ≅ to_karoubi (chain_complex C ℕ)` and `N₂Γ₂ : Γ₂ ⋙ N₂ ≅ 𝟭 (karoubi (chain_complex C ℕ))`. -/ noncomputable theory open category_theory category_theory.category category_theory.limits category_theory.idempotents opposite simplicial_object open_locale simplicial namespace algebraic_topology namespace dold_kan variables {C : Type*} [category C] [preadditive C] [has_finite_coproducts C] /-- The isomorphism `(Γ₀.splitting K).nondeg_complex ≅ K` for all `K : chain_complex C ℕ`. -/ @[simps] def Γ₀_nondeg_complex_iso (K : chain_complex C ℕ) : (Γ₀.splitting K).nondeg_complex ≅ K := homological_complex.hom.iso_of_components (λ n, iso.refl _) begin rintros _ n (rfl : n+1=_), dsimp, simp only [id_comp, comp_id, alternating_face_map_complex.obj_d_eq, preadditive.sum_comp, preadditive.comp_sum], rw fintype.sum_eq_single (0 : fin (n+2)), { simp only [fin.coe_zero, pow_zero, one_zsmul], erw [Γ₀.obj.map_mono_on_summand_id_assoc, Γ₀.obj.termwise.map_mono_δ₀, splitting.ι_π_summand_eq_id, comp_id], }, { intros i hi, dsimp, simp only [preadditive.zsmul_comp, preadditive.comp_zsmul, assoc], erw [Γ₀.obj.map_mono_on_summand_id_assoc, Γ₀.obj.termwise.map_mono_eq_zero, zero_comp, zsmul_zero], { intro h, replace h := congr_arg simplex_category.len h, change n+1 = n at h, linarith, }, { simpa only [is_δ₀.iff] using hi, }, }, end /-- The natural isomorphism `(Γ₀.splitting K).nondeg_complex ≅ K` for `K : chain_complex C ℕ`. -/ def Γ₀'_comp_nondeg_complex_functor : Γ₀' ⋙ split.nondeg_complex_functor ≅ 𝟭 (chain_complex C ℕ) := nat_iso.of_components Γ₀_nondeg_complex_iso (λ X Y f, by { ext n, dsimp, simp only [comp_id, id_comp], }) /-- The natural isomorphism `Γ₀ ⋙ N₁ ≅ to_karoubi (chain_complex C ℕ)`. -/ def N₁Γ₀ : Γ₀ ⋙ N₁ ≅ to_karoubi (chain_complex C ℕ) := calc Γ₀ ⋙ N₁ ≅ Γ₀' ⋙ split.forget C ⋙ N₁ : functor.associator _ _ _ ... ≅ Γ₀' ⋙ split.nondeg_complex_functor ⋙ to_karoubi _ : iso_whisker_left Γ₀' split.to_karoubi_nondeg_complex_functor_iso_N₁.symm ... ≅ (Γ₀' ⋙ split.nondeg_complex_functor) ⋙ to_karoubi _ : (functor.associator _ _ _).symm ... ≅ 𝟭 _ ⋙ to_karoubi (chain_complex C ℕ) : iso_whisker_right Γ₀'_comp_nondeg_complex_functor _ ... ≅ to_karoubi (chain_complex C ℕ) : functor.left_unitor _ lemma N₁Γ₀_app (K : chain_complex C ℕ) : N₁Γ₀.app K = (Γ₀.splitting K).to_karoubi_nondeg_complex_iso_N₁.symm ≪≫ (to_karoubi _).map_iso (Γ₀_nondeg_complex_iso K) := begin ext1, dsimp [N₁Γ₀], erw [id_comp, comp_id, comp_id], refl, end lemma N₁Γ₀_hom_app (K : chain_complex C ℕ) : N₁Γ₀.hom.app K = (Γ₀.splitting K).to_karoubi_nondeg_complex_iso_N₁.inv ≫ (to_karoubi _).map (Γ₀_nondeg_complex_iso K).hom := by { change (N₁Γ₀.app K).hom = _, simpa only [N₁Γ₀_app], } lemma N₁Γ₀_inv_app (K : chain_complex C ℕ) : N₁Γ₀.inv.app K = (to_karoubi _).map (Γ₀_nondeg_complex_iso K).inv ≫ (Γ₀.splitting K).to_karoubi_nondeg_complex_iso_N₁.hom := by { change (N₁Γ₀.app K).inv = _, simpa only [N₁Γ₀_app], } @[simp] lemma N₁Γ₀_hom_app_f_f (K : chain_complex C ℕ) (n : ℕ) : (N₁Γ₀.hom.app K).f.f n = (Γ₀.splitting K).to_karoubi_nondeg_complex_iso_N₁.inv.f.f n := by { rw N₁Γ₀_hom_app, apply comp_id, } @[simp] lemma N₁Γ₀_inv_app_f_f (K : chain_complex C ℕ) (n : ℕ) : (N₁Γ₀.inv.app K).f.f n = (Γ₀.splitting K).to_karoubi_nondeg_complex_iso_N₁.hom.f.f n := by { rw N₁Γ₀_inv_app, apply id_comp, } lemma N₂Γ₂_to_karoubi : to_karoubi (chain_complex C ℕ) ⋙ Γ₂ ⋙ N₂ = Γ₀ ⋙ N₁ := begin have h := functor.congr_obj (functor_extension₂_comp_whiskering_left_to_karoubi (chain_complex C ℕ) (simplicial_object C)) Γ₀, have h' := functor.congr_obj (functor_extension₁_comp_whiskering_left_to_karoubi (simplicial_object C) (chain_complex C ℕ)) N₁, dsimp [N₂, Γ₂, functor_extension₁] at h h' ⊢, rw [← functor.assoc, h, functor.assoc, h'], end /-- Compatibility isomorphism between `to_karoubi _ ⋙ Γ₂ ⋙ N₂` and `Γ₀ ⋙ N₁` which are functors `chain_complex C ℕ ⥤ karoubi (chain_complex C ℕ)`. -/ @[simps] def N₂Γ₂_to_karoubi_iso : to_karoubi (chain_complex C ℕ) ⋙ Γ₂ ⋙ N₂ ≅ Γ₀ ⋙ N₁ := eq_to_iso (N₂Γ₂_to_karoubi) /-- The counit isomorphism of the Dold-Kan equivalence for additive categories. -/ def N₂Γ₂ : Γ₂ ⋙ N₂ ≅ 𝟭 (karoubi (chain_complex C ℕ)) := ((whiskering_left _ _ _).obj (to_karoubi (chain_complex C ℕ))).preimage_iso (N₂Γ₂_to_karoubi_iso ≪≫ N₁Γ₀) lemma N₂Γ₂_compatible_with_N₁Γ₀ (K : chain_complex C ℕ) : N₂Γ₂.hom.app ((to_karoubi _).obj K) = N₂Γ₂_to_karoubi_iso.hom.app K ≫ N₁Γ₀.hom.app K := congr_app (((whiskering_left _ _ (karoubi (chain_complex C ℕ ))).obj (to_karoubi (chain_complex C ℕ))).image_preimage (N₂Γ₂_to_karoubi_iso.hom ≫ N₁Γ₀.hom : _ ⟶ to_karoubi _ ⋙ 𝟭 _)) K @[simp] lemma N₂Γ₂_inv_app_f_f (X : karoubi (chain_complex C ℕ)) (n : ℕ) : (N₂Γ₂.inv.app X).f.f n = X.p.f n ≫ (Γ₀.splitting X.X).ι_summand (splitting.index_set.id (op [n])) := begin dsimp only [N₂Γ₂, functor.preimage_iso, iso.trans], simp only [whiskering_left_obj_preimage_app, N₂Γ₂_to_karoubi_iso_inv, functor.id_map, nat_trans.comp_app, eq_to_hom_app, functor.comp_map, assoc, karoubi.comp_f, karoubi.eq_to_hom_f, eq_to_hom_refl, comp_id, karoubi.comp_p_assoc, N₂_map_f_f, homological_complex.comp_f, N₁Γ₀_inv_app_f_f, P_infty_on_Γ₀_splitting_summand_eq_self_assoc, splitting.to_karoubi_nondeg_complex_iso_N₁_hom_f_f, Γ₂_map_f_app, karoubi.decomp_id_p_f], dsimp [to_karoubi], rw [splitting.ι_desc], dsimp [splitting.index_set.id], rw karoubi.homological_complex.p_idem_assoc, end end dold_kan end algebraic_topology
611685738e0d83cb892ac9c624e6809a2bfe4646
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/algebra/group_power/order.lean
c6d689bc025af31a57a395898c3ce0ee6fe0f4c3
[ "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
10,636
lean
/- Copyright (c) 2015 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Robert Y. Lewis -/ import algebra.ordered_ring import algebra.group_power.basic /-! # Lemmas about the interaction of power operations with order Note that some lemmas are in `algebra/group_power/lemmas.lean` as they import files which depend on this file. -/ variables {A G M R : Type*} section preorder variables [monoid M] [preorder M] [covariant_class M M (*) (≤)] @[mono, to_additive nsmul_le_nsmul_of_le_right] lemma pow_le_pow_of_le_left' [covariant_class M M (function.swap (*)) (≤)] {a b : M} (hab : a ≤ b) : ∀ i : ℕ, a ^ i ≤ b ^ i | 0 := by simp | (k+1) := by { rw [pow_succ, pow_succ], exact mul_le_mul' hab (pow_le_pow_of_le_left' k) } @[to_additive nsmul_nonneg] theorem one_le_pow_of_one_le' {a : M} (H : 1 ≤ a) : ∀ n : ℕ, 1 ≤ a ^ n | 0 := by simp | (k + 1) := by { rw pow_succ, exact one_le_mul H (one_le_pow_of_one_le' k) } @[to_additive nsmul_nonpos] theorem pow_le_one' {a : M} (H : a ≤ 1) (n : ℕ) : a ^ n ≤ 1 := @one_le_pow_of_one_le' (order_dual M) _ _ _ _ H n @[to_additive nsmul_le_nsmul] theorem pow_le_pow' {a : M} {n m : ℕ} (ha : 1 ≤ a) (h : n ≤ m) : a ^ n ≤ a ^ m := let ⟨k, hk⟩ := nat.le.dest h in calc a ^ n ≤ a ^ n * a ^ k : le_mul_of_one_le_right' (one_le_pow_of_one_le' ha _) ... = a ^ m : by rw [← hk, pow_add] @[to_additive nsmul_le_nsmul_of_nonpos] theorem pow_le_pow_of_le_one' {a : M} {n m : ℕ} (ha : a ≤ 1) (h : n ≤ m) : a ^ m ≤ a ^ n := @pow_le_pow' (order_dual M) _ _ _ _ _ _ ha h @[to_additive nsmul_pos] theorem one_lt_pow' {a : M} (ha : 1 < a) {k : ℕ} (hk : k ≠ 0) : 1 < a ^ k := begin rcases nat.exists_eq_succ_of_ne_zero hk with ⟨l, rfl⟩, clear hk, induction l with l IH, { simpa using ha }, { rw pow_succ, exact one_lt_mul' ha IH } end @[to_additive nsmul_neg] theorem pow_lt_one' {a : M} (ha : a < 1) {k : ℕ} (hk : k ≠ 0) : a ^ k < 1 := @one_lt_pow' (order_dual M) _ _ _ _ ha k hk @[to_additive nsmul_lt_nsmul] theorem pow_lt_pow'' [covariant_class M M (*) (<)] {a : M} {n m : ℕ} (ha : 1 < a) (h : n < m) : a ^ n < a ^ m := begin rcases nat.le.dest h with ⟨k, rfl⟩, clear h, rw [pow_add, pow_succ', mul_assoc, ← pow_succ], exact lt_mul_of_one_lt_right' _ (one_lt_pow' ha k.succ_ne_zero) end end preorder section linear_order variables [monoid M] [linear_order M] [covariant_class M M (*) (≤)] @[to_additive nsmul_nonneg_iff] lemma one_le_pow_iff {x : M} {n : ℕ} (hn : n ≠ 0) : 1 ≤ x ^ n ↔ 1 ≤ x := ⟨le_imp_le_of_lt_imp_lt $ λ h, pow_lt_one' h hn, λ h, one_le_pow_of_one_le' h n⟩ @[to_additive nsmul_nonpos_iff] lemma pow_le_one_iff {x : M} {n : ℕ} (hn : n ≠ 0) : x ^ n ≤ 1 ↔ x ≤ 1 := @one_le_pow_iff (order_dual M) _ _ _ _ _ hn @[to_additive nsmul_pos_iff] lemma one_lt_pow_iff {x : M} {n : ℕ} (hn : n ≠ 0) : 1 < x ^ n ↔ 1 < x := lt_iff_lt_of_le_iff_le (pow_le_one_iff hn) @[to_additive nsmul_neg_iff] lemma pow_lt_one_iff {x : M} {n : ℕ} (hn : n ≠ 0) : x ^ n < 1 ↔ x < 1 := lt_iff_lt_of_le_iff_le (one_le_pow_iff hn) @[to_additive nsmul_eq_zero_iff] lemma pow_eq_one_iff {x : M} {n : ℕ} (hn : n ≠ 0) : x ^ n = 1 ↔ x = 1 := by simp only [le_antisymm_iff, pow_le_one_iff hn, one_le_pow_iff hn] end linear_order section group variables [group G] [preorder G] [covariant_class G G (*) (≤)] @[to_additive gsmul_nonneg] theorem one_le_gpow {x : G} (H : 1 ≤ x) {n : ℤ} (hn : 0 ≤ n) : 1 ≤ x ^ n := begin lift n to ℕ using hn, rw gpow_coe_nat, apply one_le_pow_of_one_le' H, end end group namespace canonically_ordered_comm_semiring variables [canonically_ordered_comm_semiring R] theorem pow_pos {a : R} (H : 0 < a) (n : ℕ) : 0 < a ^ n := pos_iff_ne_zero.2 $ pow_ne_zero _ H.ne' end canonically_ordered_comm_semiring section ordered_semiring variable [ordered_semiring R] @[simp] theorem pow_pos {a : R} (H : 0 < a) : ∀ (n : ℕ), 0 < a ^ n | 0 := by { nontriviality, rw pow_zero, exact zero_lt_one } | (n+1) := by { rw pow_succ, exact mul_pos H (pow_pos _) } @[simp] theorem pow_nonneg {a : R} (H : 0 ≤ a) : ∀ (n : ℕ), 0 ≤ a ^ n | 0 := by { rw pow_zero, exact zero_le_one} | (n+1) := by { rw pow_succ, exact mul_nonneg H (pow_nonneg _) } theorem pow_add_pow_le {x y : R} {n : ℕ} (hx : 0 ≤ x) (hy : 0 ≤ y) (hn : n ≠ 0) : x ^ n + y ^ n ≤ (x + y) ^ n := begin rcases nat.exists_eq_succ_of_ne_zero hn with ⟨k, rfl⟩, induction k with k ih, { simp only [pow_one] }, let n := k.succ, have h1 := add_nonneg (mul_nonneg hx (pow_nonneg hy n)) (mul_nonneg hy (pow_nonneg hx n)), have h2 := add_nonneg hx hy, calc x^n.succ + y^n.succ ≤ x*x^n + y*y^n + (x*y^n + y*x^n) : by { rw [pow_succ _ n, pow_succ _ n], exact le_add_of_nonneg_right h1 } ... = (x+y) * (x^n + y^n) : by rw [add_mul, mul_add, mul_add, add_comm (y*x^n), ← add_assoc, ← add_assoc, add_assoc (x*x^n) (x*y^n), add_comm (x*y^n) (y*y^n), ← add_assoc] ... ≤ (x+y)^n.succ : by { rw [pow_succ _ n], exact mul_le_mul_of_nonneg_left (ih (nat.succ_ne_zero k)) h2 } end theorem pow_lt_pow_of_lt_left {x y : R} {n : ℕ} (Hxy : x < y) (Hxpos : 0 ≤ x) (Hnpos : 0 < n) : x ^ n < y ^ n := begin cases lt_or_eq_of_le Hxpos, { rw ←nat.sub_add_cancel Hnpos, induction (n - 1), { simpa only [pow_one] }, rw [pow_add, pow_add, nat.succ_eq_add_one, pow_one, pow_one], apply mul_lt_mul ih (le_of_lt Hxy) h (le_of_lt (pow_pos (lt_trans h Hxy) _)) }, { rw [←h, zero_pow Hnpos], apply pow_pos (by rwa ←h at Hxy : 0 < y),} end theorem strict_mono_incr_on_pow {n : ℕ} (hn : 0 < n) : strict_mono_incr_on (λ x : R, x ^ n) (set.Ici 0) := λ x hx y hy h, pow_lt_pow_of_lt_left h hx hn theorem one_le_pow_of_one_le {a : R} (H : 1 ≤ a) : ∀ (n : ℕ), 1 ≤ a ^ n | 0 := by rw [pow_zero] | (n+1) := by { rw pow_succ, simpa only [mul_one] using mul_le_mul H (one_le_pow_of_one_le n) zero_le_one (le_trans zero_le_one H) } lemma pow_mono {a : R} (h : 1 ≤ a) : monotone (λ n : ℕ, a ^ n) := monotone_nat_of_le_succ $ λ n, by { rw pow_succ, exact le_mul_of_one_le_left (pow_nonneg (zero_le_one.trans h) _) h } theorem pow_le_pow {a : R} {n m : ℕ} (ha : 1 ≤ a) (h : n ≤ m) : a ^ n ≤ a ^ m := pow_mono ha h lemma strict_mono_pow {a : R} (h : 1 < a) : strict_mono (λ n : ℕ, a ^ n) := have 0 < a := zero_le_one.trans_lt h, strict_mono_nat_of_lt_succ $ λ n, by simpa only [one_mul, pow_succ] using mul_lt_mul h (le_refl (a ^ n)) (pow_pos this _) this.le lemma pow_lt_pow {a : R} {n m : ℕ} (h : 1 < a) (h2 : n < m) : a ^ n < a ^ m := strict_mono_pow h h2 lemma pow_lt_pow_iff {a : R} {n m : ℕ} (h : 1 < a) : a ^ n < a ^ m ↔ n < m := (strict_mono_pow h).lt_iff_lt @[mono] lemma pow_le_pow_of_le_left {a b : R} (ha : 0 ≤ a) (hab : a ≤ b) : ∀ i : ℕ, a^i ≤ b^i | 0 := by simp | (k+1) := by { rw [pow_succ, pow_succ], exact mul_le_mul hab (pow_le_pow_of_le_left _) (pow_nonneg ha _) (le_trans ha hab) } end ordered_semiring section linear_ordered_semiring variable [linear_ordered_semiring R] @[simp] theorem pow_left_inj {x y : R} {n : ℕ} (Hxpos : 0 ≤ x) (Hypos : 0 ≤ y) (Hnpos : 0 < n) : x ^ n = y ^ n ↔ x = y := (@strict_mono_incr_on_pow R _ _ Hnpos).inj_on.eq_iff Hxpos Hypos lemma lt_of_pow_lt_pow {a b : R} (n : ℕ) (hb : 0 ≤ b) (h : a ^ n < b ^ n) : a < b := lt_of_not_ge $ λ hn, not_lt_of_ge (pow_le_pow_of_le_left hb hn _) h lemma le_of_pow_le_pow {a b : R} (n : ℕ) (hb : 0 ≤ b) (hn : 0 < n) (h : a ^ n ≤ b ^ n) : a ≤ b := le_of_not_lt $ λ h1, not_le_of_lt (pow_lt_pow_of_lt_left h1 hb hn) h @[simp] lemma sq_eq_sq {a b : R} (ha : 0 ≤ a) (hb : 0 ≤ b) : a ^ 2 = b ^ 2 ↔ a = b := pow_left_inj ha hb dec_trivial end linear_ordered_semiring section linear_ordered_ring variable [linear_ordered_ring R] lemma pow_abs (a : R) (n : ℕ) : (abs a) ^ n = abs (a ^ n) := ((abs_hom.to_monoid_hom : R →* R).map_pow a n).symm lemma abs_neg_one_pow (n : ℕ) : abs ((-1 : R) ^ n) = 1 := by rw [←pow_abs, abs_neg, abs_one, one_pow] theorem pow_bit0_nonneg (a : R) (n : ℕ) : 0 ≤ a ^ bit0 n := by { rw pow_bit0, exact mul_self_nonneg _ } theorem sq_nonneg (a : R) : 0 ≤ a ^ 2 := pow_bit0_nonneg a 1 alias sq_nonneg ← pow_two_nonneg theorem pow_bit0_pos {a : R} (h : a ≠ 0) (n : ℕ) : 0 < a ^ bit0 n := (pow_bit0_nonneg a n).lt_of_ne (pow_ne_zero _ h).symm theorem sq_pos_of_ne_zero (a : R) (h : a ≠ 0) : 0 < a ^ 2 := pow_bit0_pos h 1 alias sq_pos_of_ne_zero ← pow_two_pos_of_ne_zero variables {x y : R} theorem sq_abs (x : R) : abs x ^ 2 = x ^ 2 := by simpa only [sq] using abs_mul_abs_self x theorem abs_sq (x : R) : abs (x ^ 2) = x ^ 2 := by simpa only [sq] using abs_mul_self x theorem sq_lt_sq (h : abs x < y) : x ^ 2 < y ^ 2 := by simpa only [sq_abs] using pow_lt_pow_of_lt_left h (abs_nonneg x) (1:ℕ).succ_pos theorem sq_lt_sq' (h1 : -y < x) (h2 : x < y) : x ^ 2 < y ^ 2 := sq_lt_sq (abs_lt.mpr ⟨h1, h2⟩) theorem sq_le_sq (h : abs x ≤ abs y) : x ^ 2 ≤ y ^ 2 := by simpa only [sq_abs] using pow_le_pow_of_le_left (abs_nonneg x) h 2 theorem sq_le_sq' (h1 : -y ≤ x) (h2 : x ≤ y) : x ^ 2 ≤ y ^ 2 := sq_le_sq (le_trans (abs_le.mpr ⟨h1, h2⟩) (le_abs_self _)) theorem abs_lt_abs_of_sq_lt_sq (h : x^2 < y^2) : abs x < abs y := lt_of_pow_lt_pow 2 (abs_nonneg y) $ by rwa [← sq_abs x, ← sq_abs y] at h theorem abs_lt_of_sq_lt_sq (h : x^2 < y^2) (hy : 0 ≤ y) : abs x < y := begin rw [← abs_of_nonneg hy], exact abs_lt_abs_of_sq_lt_sq h, end theorem abs_lt_of_sq_lt_sq' (h : x^2 < y^2) (hy : 0 ≤ y) : -y < x ∧ x < y := abs_lt.mp $ abs_lt_of_sq_lt_sq h hy theorem abs_le_abs_of_sq_le_sq (h : x^2 ≤ y^2) : abs x ≤ abs y := le_of_pow_le_pow 2 (abs_nonneg y) (1:ℕ).succ_pos $ by rwa [← sq_abs x, ← sq_abs y] at h theorem abs_le_of_sq_le_sq (h : x^2 ≤ y^2) (hy : 0 ≤ y) : abs x ≤ y := begin rw [← abs_of_nonneg hy], exact abs_le_abs_of_sq_le_sq h, end theorem abs_le_of_sq_le_sq' (h : x^2 ≤ y^2) (hy : 0 ≤ y) : -y ≤ x ∧ x ≤ y := abs_le.mp $ abs_le_of_sq_le_sq h hy end linear_ordered_ring section linear_ordered_comm_ring variables [linear_ordered_comm_ring R] /-- Arithmetic mean-geometric mean (AM-GM) inequality for linearly ordered commutative rings. -/ lemma two_mul_le_add_sq (a b : R) : 2 * a * b ≤ a ^ 2 + b ^ 2 := sub_nonneg.mp ((sub_add_eq_add_sub _ _ _).subst ((sub_sq a b).subst (sq_nonneg _))) alias two_mul_le_add_sq ← two_mul_le_add_pow_two end linear_ordered_comm_ring
8db9b5cee0e0f8f8913ee4c6e25923726016d601
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/combinatorics/quiver/basic.lean
2e3527deffeb22347ca478a95ee178c553334383
[ "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,176
lean
/- Copyright (c) 2021 David Wärn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: David Wärn, Scott Morrison -/ import data.opposite /-! # Quivers > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > https://github.com/leanprover-community/mathlib4/pull/749 > Any changes to this file require a corresponding PR to mathlib4. This module defines quivers. A quiver on a type `V` of vertices assigns to every pair `a b : V` of vertices a type `a ⟶ b` of arrows from `a` to `b`. This is a very permissive notion of directed graph. ## Implementation notes Currently `quiver` is defined with `arrow : V → V → Sort v`. This is different from the category theory setup, where we insist that morphisms live in some `Type`. There's some balance here: it's nice to allow `Prop` to ensure there are no multiple arrows, but it is also results in error-prone universe signatures when constraints require a `Type`. -/ open opposite -- We use the same universe order as in category theory. -- See note [category_theory universes] universes v v₁ v₂ u u₁ u₂ /-- A quiver `G` on a type `V` of vertices assigns to every pair `a b : V` of vertices a type `a ⟶ b` of arrows from `a` to `b`. For graphs with no repeated edges, one can use `quiver.{0} V`, which ensures `a ⟶ b : Prop`. For multigraphs, one can use `quiver.{v+1} V`, which ensures `a ⟶ b : Type v`. Because `category` will later extend this class, we call the field `hom`. Except when constructing instances, you should rarely see this, and use the `⟶` notation instead. -/ class quiver (V : Type u) := (hom : V → V → Sort v) infixr ` ⟶ `:10 := quiver.hom -- type as \h /-- A morphism of quivers. As we will later have categorical functors extend this structure, we call it a `prefunctor`. -/ structure prefunctor (V : Type u₁) [quiver.{v₁} V] (W : Type u₂) [quiver.{v₂} W] := (obj [] : V → W) (map : Π {X Y : V}, (X ⟶ Y) → (obj X ⟶ obj Y)) namespace prefunctor @[ext] lemma ext {V : Type u} [quiver.{v₁} V] {W : Type u₂} [quiver.{v₂} W] {F G : prefunctor V W} (h_obj : ∀ X, F.obj X = G.obj X) (h_map : ∀ (X Y : V) (f : X ⟶ Y), F.map f = eq.rec_on (h_obj Y).symm (eq.rec_on (h_obj X).symm (G.map f))) : F = G := begin cases F with F_obj _, cases G with G_obj _, obtain rfl : F_obj = G_obj, by { ext X, apply h_obj }, congr, funext X Y f, simpa using h_map X Y f, end /-- The identity morphism between quivers. -/ @[simps] def id (V : Type*) [quiver V] : prefunctor V V := { obj := id, map := λ X Y f, f, } instance (V : Type*) [quiver V] : inhabited (prefunctor V V) := ⟨id V⟩ /-- Composition of morphisms between quivers. -/ @[simps] def comp {U : Type*} [quiver U] {V : Type*} [quiver V] {W : Type*} [quiver W] (F : prefunctor U V) (G : prefunctor V W) : prefunctor U W := { obj := λ X, G.obj (F.obj X), map := λ X Y f, G.map (F.map f), } @[simp] lemma comp_assoc {U V W Z : Type*} [quiver U] [quiver V] [quiver W] [quiver Z] (F : prefunctor U V) (G : prefunctor V W) (H : prefunctor W Z) : (F.comp G).comp H = F.comp (G.comp H) := rfl infix ` ⥤q `:50 := prefunctor infix ` ⋙q `:50 := prefunctor.comp notation `𝟭q` := id end prefunctor namespace quiver /-- `Vᵒᵖ` reverses the direction of all arrows of `V`. -/ instance opposite {V} [quiver V] : quiver Vᵒᵖ := ⟨λ a b, (unop b) ⟶ (unop a)⟩ /-- The opposite of an arrow in `V`. -/ def hom.op {V} [quiver V] {X Y : V} (f : X ⟶ Y) : op Y ⟶ op X := f /-- Given an arrow in `Vᵒᵖ`, we can take the "unopposite" back in `V`. -/ def hom.unop {V} [quiver V] {X Y : Vᵒᵖ} (f : X ⟶ Y) : unop Y ⟶ unop X := f attribute [irreducible] quiver.opposite /-- A type synonym for a quiver with no arrows. -/ @[nolint has_nonempty_instance] def empty (V) : Type u := V instance empty_quiver (V : Type u) : quiver.{u} (empty V) := ⟨λ a b, pempty⟩ @[simp] lemma empty_arrow {V : Type u} (a b : empty V) : (a ⟶ b) = pempty := rfl /-- A quiver is thin if it has no parallel arrows. -/ @[reducible] def is_thin (V : Type u) [quiver V] := ∀ (a b : V), subsingleton (a ⟶ b) end quiver
50d42a9ac1992dea126827f09eeb80e64b54b641
75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2
/library/algebra/field.lean
4005daf5fcdde5b75dbd11d4d011bfd68d6462ea
[ "Apache-2.0" ]
permissive
jroesch/lean
30ef0860fa905d35b9ad6f76de1a4f65c9af6871
3de4ec1a6ce9a960feb2a48eeea8b53246fa34f2
refs/heads/master
1,586,090,835,348
1,455,142,203,000
1,455,142,277,000
51,536,958
1
0
null
1,455,215,811,000
1,455,215,811,000
null
UTF-8
Lean
false
false
20,340
lean
/- 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 logic.eq logic.connectives data.unit data.sigma data.prod import algebra.binary algebra.group algebra.ring open eq eq.ops variable {A : Type} 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 [simp] (a b : A) : a / b = a * b⁻¹ := rfl theorem mul_inv_cancel [simp] (H : a ≠ 0) : a * a⁻¹ = 1 := division_ring.mul_inv_cancel H theorem inv_mul_cancel [simp] (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 simp theorem mul_one_div_cancel [simp] (H : a ≠ 0) : a * (1 / a) = 1 := by simp theorem one_div_mul_cancel [simp] (H : a ≠ 0) : (1 / a) * a = 1 := by simp theorem div_self [simp] (H : a ≠ 0) : a / a = 1 := by simp theorem one_div_one [simp] : 1 / 1 = (1:A) := div_self (ne.symm zero_ne_one) theorem mul_div_assoc (a b : A) : (a * b) / c = a * (b / c) := by simp 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 [simp] : 1⁻¹ = (1:A) := by rewrite [-mul_one, inv_mul_cancel (ne.symm (@zero_ne_one A _))] theorem div_one [simp] (a : A) : a / 1 = a := by simp theorem zero_div [simp] (a : A) : 0 / a = 0 := by simp -- 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_and_ne_zero_of_mul_ne_zero H, division_ring.mul_ne_zero (and.right H2) (and.left H2) theorem eq_one_div_of_mul_eq_one (H : a * b = 1) : b = 1 / a := assert a ≠ 0, from suppose a = 0, have 0 = (1:A), by inst_simp, absurd this zero_ne_one, assert b = (1 / a) * a * b, by inst_simp, show b = 1 / a, by inst_simp theorem eq_one_div_of_mul_eq_one_left (H : b * a = 1) : b = 1 / a := assert a ≠ 0, from suppose a = 0, have 0 = (1:A), by inst_simp, absurd this zero_ne_one, by inst_simp 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 inst_simp, 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 inst_simp, 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 [simp] (Ha : a ≠ 0) (Hb : b ≠ 0) : (b * a)⁻¹ = a⁻¹ * b⁻¹ := eq.symm (calc a⁻¹ * b⁻¹ = (1 / a) * (1 / b) : by inst_simp ... = (1 / (b * a)) : division_ring.one_div_mul_one_div Ha Hb ... = (b * a)⁻¹ : by simp) theorem mul_div_cancel (a : A) {b : A} (Hb : b ≠ 0) : a * b / b = a := by simp theorem div_mul_cancel (a : A) {b : A} (Hb : b ≠ 0) : a / b * b = a := by simp 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, calc a = a / b * b : by inst_simp ... = 1 * b : this ... = b : by simp) (suppose a = b, by simp) 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) := by simp -- 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 := assert a ≠ 0, from and.left (ne_zero_and_ne_zero_of_mul_ne_zero H), symm (calc 1 / b = a * ((1 / a) * (1 / b)) : by inst_simp ... = a * (1 / (b * a)) : division_ring.one_div_mul_one_div this Hb ... = a * (a * b)⁻¹ : by inst_simp) 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 inst_simp 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 or division ring, -- but with fewer hypotheses since 0⁻¹ = 0 and equality is decidable. theorem discrete_field.eq_zero_or_eq_zero_of_mul_eq_zero (x y : A) (H : x * y = 0) : x = 0 ∨ y = 0 := decidable.by_cases (suppose x = 0, or.inl this) (suppose x ≠ 0, or.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_or_eq_zero_of_mul_eq_zero := discrete_field.eq_zero_or_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, false.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 eq.symm 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 eq.symm, 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
7cb03283084e0dc9003d8fa9fa4345e93d8b1e5f
a44280b79dc85615010e3fbda46abf82c6730fa3
/tests/playground/lazylist.lean
ef32658294b44545da2bd2b08bece81b753a73e9
[ "Apache-2.0" ]
permissive
kodyvajjha/lean4
8e1c613248b531d47367ca6e8d97ee1046645aa1
c8a045d69fac152fd5e3a577f718615cecb9c53d
refs/heads/master
1,589,684,450,102
1,555,200,447,000
1,556,139,945,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,912
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 -/ universes u v w inductive LazyList (α : Type u) | nil {} : LazyList | cons (hd : α) (tl : LazyList) : LazyList | delayed (t : Thunk LazyList) : LazyList @[extern cpp inline "#2"] def List.toLazy {α : Type u} : List α → LazyList α | [] := LazyList.nil | (h::t) := LazyList.cons h (List.toLazy t) namespace LazyList variables {α : Type u} {β : Type v} {δ : Type w} instance : Inhabited (LazyList α) := ⟨nil⟩ @[inline] def pure : α → LazyList α | a := cons a nil partial def isEmpty : LazyList α → Bool | nil := true | (cons _ _) := false | (delayed as) := isEmpty as.get partial def toList : LazyList α → List α | nil := [] | (cons a as) := a :: toList as | (delayed as) := toList as.get partial def head [Inhabited α] : LazyList α → α | nil := default α | (cons a as) := a | (delayed as) := head as.get partial def tail : LazyList α → LazyList α | nil := nil | (cons a as) := as | (delayed as) := tail as.get partial def append : LazyList α → LazyList α → LazyList α | nil bs := bs | (cons a as) bs := delayed (cons a (append as bs)) | (delayed as) bs := delayed (append as.get bs) instance : HasAppend (LazyList α) := ⟨LazyList.append⟩ partial def interleave : LazyList α → LazyList α → LazyList α | nil bs := bs | (cons a as) bs := delayed (cons a (interleave bs as)) | (delayed as) bs := delayed (interleave as.get bs) partial def map (f : α → β) : LazyList α → LazyList β | nil := nil | (cons a as) := delayed (cons (f a) (map as)) | (delayed as) := delayed (map as.get) partial def map₂ (f : α → β → δ) : LazyList α → LazyList β → LazyList δ | nil _ := nil | _ nil := nil | (cons a as) (cons b bs) := delayed (cons (f a b) (map₂ as bs)) | (delayed as) bs := delayed (map₂ as.get bs) | as (delayed bs) := delayed (map₂ as bs.get) @[inline] def zip : LazyList α → LazyList β → LazyList (α × β) := map₂ Prod.mk partial def join : LazyList (LazyList α) → LazyList α | nil := nil | (cons a as) := delayed (append a (join as)) | (delayed as) := delayed (join as.get) @[inline] partial def bind (x : LazyList α) (f : α → LazyList β) : LazyList β := join (x.map f) instance isMonad : Monad LazyList := { pure := @LazyList.pure, bind := @LazyList.bind, map := @LazyList.map } instance : Alternative LazyList := { failure := λ _, nil, orelse := @LazyList.append, .. LazyList.isMonad } partial def approx : Nat → LazyList α → List α | 0 as := [] | _ nil := [] | (i+1) (cons a as) := a :: approx i as | (i+1) (delayed as) := approx (i+1) as.get partial def iterate (f : α → α) : α → LazyList α | x := cons x (delayed (iterate (f x))) partial def iterate₂ (f : α → α → α) : α → α → LazyList α | x y := cons x (delayed (iterate₂ y (f x y))) partial def filter (p : α → Bool) : LazyList α → LazyList α | nil := nil | (cons a as) := delayed (if p a then cons a (filter as) else filter as) | (delayed as) := delayed (filter as.get) end LazyList def fib : LazyList Nat := LazyList.iterate₂ (+) 0 1 def iota (i : Nat := 0) : LazyList Nat := LazyList.iterate Nat.succ i def tst : LazyList String := do x ← [1, 2, 3].toLazy, y ← [2, 3, 4].toLazy, guard (x + y > 5), pure (toString x ++ " + " ++ toString y ++ " = " ++ toString (x+y)) def main : IO Unit := do let n := 10, IO.println $ tst.isEmpty, IO.println $ tst.head, IO.println $ (fib.interleave (iota.map (+100))).approx n, IO.println $ (((iota.map (+10)).filter (λ v, v % 2 == 0)).approx n)
07e924fd0b50187b84a4a4f98312868229d45c22
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/src/Lean/Elab/BuiltinNotation.lean
a37188cad1db4f7dda14ae6176d055651eb74929
[ "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
13,805
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Init.Data.ToString import Lean.Compiler.BorrowedAnnotation import Lean.Meta.KAbstract import Lean.Meta.Transform import Lean.Elab.Term import Lean.Elab.SyntheticMVars namespace Lean.Elab.Term open Meta @[builtinTermElab anonymousCtor] def elabAnonymousCtor : TermElab := fun stx expectedType? => match stx with | `(⟨$args,*⟩) => do tryPostponeIfNoneOrMVar expectedType? match expectedType? with | some expectedType => let expectedType ← whnf expectedType matchConstInduct expectedType.getAppFn (fun _ => throwError "invalid constructor ⟨...⟩, expected type must be an inductive type {indentExpr expectedType}") (fun ival us => do match ival.ctors with | [ctor] => let cinfo ← getConstInfoCtor ctor let numExplicitFields ← forallTelescopeReducing cinfo.type fun xs _ => do let mut n := 0 for i in [cinfo.numParams:xs.size] do if (← getFVarLocalDecl xs[i]).binderInfo.isExplicit then n := n + 1 return n let args := args.getElems if args.size < numExplicitFields then throwError "invalid constructor ⟨...⟩, insufficient number of arguments, constructs '{ctor}' has #{numExplicitFields} explicit fields, but only #{args.size} provided" let newStx ← if args.size == numExplicitFields then `($(mkCIdentFrom stx ctor) $(args)*) else if numExplicitFields == 0 then throwError "invalid constructor ⟨...⟩, insufficient number of arguments, constructs '{ctor}' does not have explicit fields, but #{args.size} provided" else let extra := args[numExplicitFields-1:args.size] let newLast ← `(⟨$[$extra],*⟩) let newArgs := args[0:numExplicitFields-1].toArray.push newLast `($(mkCIdentFrom stx ctor) $(newArgs)*) withMacroExpansion stx newStx $ elabTerm newStx expectedType? | _ => throwError "invalid constructor ⟨...⟩, expected type must be an inductive type with only one constructor {indentExpr expectedType}") | none => throwError "invalid constructor ⟨...⟩, expected type must be known" | _ => throwUnsupportedSyntax @[builtinTermElab borrowed] def elabBorrowed : TermElab := fun stx expectedType? => match stx with | `(@& $e) => return markBorrowed (← elabTerm e expectedType?) | _ => throwUnsupportedSyntax @[builtinMacro Lean.Parser.Term.show] def expandShow : Macro := fun stx => match stx with | `(show $type from $val) => let thisId := mkIdentFrom stx `this; `(let_fun $thisId : $type := $val; $thisId) | `(show $type by%$b $tac:tacticSeq) => `(show $type from by%$b $tac:tacticSeq) | _ => Macro.throwUnsupported @[builtinMacro Lean.Parser.Term.have] def expandHave : Macro := fun stx => let thisId := mkIdentFrom stx `this match stx with | `(have $x $bs* $[: $type]? := $val $[;]? $body) => `(let_fun $x $bs* $[: $type]? := $val; $body) | `(have $[: $type]? := $val $[;]? $body) => `(have $thisId:ident $[: $type]? := $val; $body) | `(have $x $bs* $[: $type]? $alts:matchAlts $[;]? $body) => `(let_fun $x $bs* $[: $type]? $alts:matchAlts; $body) | `(have $[: $type]? $alts:matchAlts $[;]? $body) => `(have $thisId:ident $[: $type]? $alts:matchAlts; $body) | `(have $pattern:term $[: $type]? := $val:term $[;]? $body) => `(let_fun $pattern:term $[: $type]? := $val:term ; $body) | _ => Macro.throwUnsupported @[builtinMacro Lean.Parser.Term.suffices] def expandSuffices : Macro | `(suffices $[$x :]? $type from $val $[;]? $body) => `(have $[$x]? : $type := $body; $val) | `(suffices $[$x :]? $type by%$b $tac:tacticSeq $[;]? $body) => `(have $[$x]? : $type := $body; by%$b $tac:tacticSeq) | _ => Macro.throwUnsupported open Lean.Parser in private def elabParserMacroAux (prec : Syntax) (e : Syntax) : TermElabM Syntax := do let (some declName) ← getDeclName? | throwError "invalid `leading_parser` macro, it must be used in definitions" match extractMacroScopes declName with | { name := Name.str _ s _, scopes := scps, .. } => let kind := quote declName let s := quote s -- if the parser decl is hidden by hygiene, it doesn't make sense to provide an antiquotation kind let antiquotKind ← if scps == [] then `(some $kind) else `(none) ``(withAntiquot (mkAntiquot $s $antiquotKind) (leadingNode $kind $prec $e)) | _ => throwError "invalid `leading_parser` macro, unexpected declaration name" @[builtinTermElab «leading_parser»] def elabLeadingParserMacro : TermElab := adaptExpander fun stx => match stx with | `(leading_parser $e) => elabParserMacroAux (quote Parser.maxPrec) e | `(leading_parser : $prec $e) => elabParserMacroAux prec e | _ => throwUnsupportedSyntax private def elabTParserMacroAux (prec lhsPrec : Syntax) (e : Syntax) : TermElabM Syntax := do let declName? ← getDeclName? match declName? with | some declName => let kind := quote declName; ``(Lean.Parser.trailingNode $kind $prec $lhsPrec $e) | none => throwError "invalid `trailing_parser` macro, it must be used in definitions" @[builtinTermElab «trailing_parser»] def elabTrailingParserMacro : TermElab := adaptExpander fun stx => match stx with | `(trailing_parser$[:$prec?]?$[:$lhsPrec?]? $e) => elabTParserMacroAux (prec?.getD <| quote Parser.maxPrec) (lhsPrec?.getD <| quote 0) e | _ => throwUnsupportedSyntax @[builtinTermElab panic] def elabPanic : TermElab := fun stx expectedType? => do let arg := stx[1] let pos ← getRefPosition let env ← getEnv let stxNew ← match (← getDeclName?) with | some declName => `(panicWithPosWithDecl $(quote (toString env.mainModule)) $(quote (toString declName)) $(quote pos.line) $(quote pos.column) $arg) | none => `(panicWithPos $(quote (toString env.mainModule)) $(quote pos.line) $(quote pos.column) $arg) withMacroExpansion stx stxNew $ elabTerm stxNew expectedType? @[builtinMacro Lean.Parser.Term.unreachable] def expandUnreachable : Macro := fun stx => `(panic! "unreachable code has been reached") @[builtinMacro Lean.Parser.Term.assert] def expandAssert : Macro := fun stx => -- TODO: support for disabling runtime assertions let cond := stx[1] let body := stx[3] match cond.reprint with | some code => `(if $cond then $body else panic! ("assertion violation: " ++ $(quote code))) | none => `(if $cond then $body else panic! ("assertion violation")) @[builtinMacro Lean.Parser.Term.dbgTrace] def expandDbgTrace : Macro := fun stx => let arg := stx[1] let body := stx[3] if arg.getKind == interpolatedStrKind then `(dbgTrace (s! $arg) fun _ => $body) else `(dbgTrace (toString $arg) fun _ => $body) @[builtinTermElab «sorry»] def elabSorry : TermElab := fun stx expectedType? => do logWarning "declaration uses 'sorry'" let stxNew ← `(sorryAx _ false) withMacroExpansion stx stxNew <| elabTerm stxNew expectedType? /-- Return syntax `Prod.mk elems[0] (Prod.mk elems[1] ... (Prod.mk elems[elems.size - 2] elems[elems.size - 1])))` -/ partial def mkPairs (elems : Array Syntax) : MacroM Syntax := let rec loop (i : Nat) (acc : Syntax) := do if i > 0 then let i := i - 1 let elem := elems[i] let acc ← `(Prod.mk $elem $acc) loop i acc else pure acc loop (elems.size - 1) elems.back private partial def hasCDot : Syntax → Bool | Syntax.node k args => if k == `Lean.Parser.Term.paren then false else if k == `Lean.Parser.Term.cdot then true else args.any hasCDot | _ => false /-- Return `some` if succeeded expanding `·` notation occurring in the given syntax. Otherwise, return `none`. Examples: - `· + 1` => `fun _a_1 => _a_1 + 1` - `f · · b` => `fun _a_1 _a_2 => f _a_1 _a_2 b` -/ partial def expandCDot? (stx : Syntax) : MacroM (Option Syntax) := do if hasCDot stx then let (newStx, binders) ← (go stx).run #[]; `(fun $binders* => $newStx) else pure none where /-- Auxiliary function for expanding the `·` notation. The extra state `Array Syntax` contains the new binder names. If `stx` is a `·`, we create a fresh identifier, store in the extra state, and return it. Otherwise, we just return `stx`. -/ go : Syntax → StateT (Array Syntax) MacroM Syntax | stx@(Syntax.node k args) => if k == `Lean.Parser.Term.paren then pure stx else if k == `Lean.Parser.Term.cdot then withFreshMacroScope do let id ← `(a) modify fun s => s.push id; pure id else do let args ← args.mapM go pure $ Syntax.node k args | stx => pure stx /-- Helper method for elaborating terms such as `(.+.)` where a constant name is expected. This method is usually used to implement tactics that function names as arguments (e.g., `simp`). -/ def elabCDotFunctionAlias? (stx : Syntax) : TermElabM (Option Expr) := do let some stx ← liftMacroM <| expandCDotArg? stx | pure none let stx ← liftMacroM <| expandMacros stx match stx with | `(fun $binders* => $f:ident $args*) => if binders == args then try Term.resolveId? f catch _ => return none else return none | `(fun $binders* => binop% $f:ident $a $b) => if binders == #[a, b] then try Term.resolveId? f catch _ => return none else return none | _ => return none where expandCDotArg? (stx : Syntax) : MacroM (Option Syntax) := match stx with | `(($e)) => Term.expandCDot? e | _ => Term.expandCDot? stx /-- Try to expand `·` notation. Recall that in Lean the `·` notation must be surrounded by parentheses. We may change this is the future, but right now, here are valid examples - `(· + 1)` - `(f ⟨·, 1⟩ ·)` - `(· + ·)` - `(f · a b)` -/ @[builtinMacro Lean.Parser.Term.paren] def expandParen : Macro | `(()) => `(Unit.unit) | `(($e : $type)) => do match (← expandCDot? e) with | some e => `(($e : $type)) | none => Macro.throwUnsupported | `(($e)) => return (← expandCDot? e).getD e | `(($e, $es,*)) => do let pairs ← mkPairs (#[e] ++ es) (← expandCDot? pairs).getD pairs | stx => if !stx[1][0].isMissing && stx[1][1].isMissing then -- parsed `(` and `term`, assume it's a basic parenthesis to get any elaboration output at all `(($(stx[1][0]))) else throw <| Macro.Exception.error stx "unexpected parentheses notation" @[builtinTermElab paren] def elabParen : TermElab := fun stx expectedType? => do match stx with | `(($e : $type)) => let type ← withSynthesize (mayPostpone := true) <| elabType type let e ← elabTerm e type ensureHasType type e | _ => throwUnsupportedSyntax @[builtinTermElab subst] def elabSubst : TermElab := fun stx expectedType? => do let expectedType ← tryPostponeIfHasMVars expectedType? "invalid `▸` notation" match stx with | `($heq ▸ $h) => do let mut heq ← elabTerm heq none let heqType ← inferType heq let heqType ← instantiateMVars heqType match (← Meta.matchEq? heqType) with | none => throwError "invalid `▸` notation, argument{indentExpr heq}\nhas type{indentExpr heqType}\nequality expected" | some (α, lhs, rhs) => let mut lhs := lhs let mut rhs := rhs let mkMotive (typeWithLooseBVar : Expr) := do withLocalDeclD (← mkFreshUserName `x) α fun x => do mkLambdaFVars #[x] $ typeWithLooseBVar.instantiate1 x let mut expectedAbst ← kabstract expectedType rhs unless expectedAbst.hasLooseBVars do expectedAbst ← kabstract expectedType lhs unless expectedAbst.hasLooseBVars do throwError "invalid `▸` notation, expected type{indentExpr expectedType}\ndoes contain equation left-hand-side nor right-hand-side{indentExpr heqType}" heq ← mkEqSymm heq (lhs, rhs) := (rhs, lhs) let hExpectedType := expectedAbst.instantiate1 lhs let h ← withRef h do let h ← elabTerm h hExpectedType try ensureHasType hExpectedType h catch ex => -- if `rhs` occurs in `hType`, we try to apply `heq` to `h` too let hType ← inferType h let hTypeAbst ← kabstract hType rhs unless hTypeAbst.hasLooseBVars do throw ex let hTypeNew := hTypeAbst.instantiate1 lhs unless (← isDefEq hExpectedType hTypeNew) do throw ex mkEqNDRec (← mkMotive hTypeAbst) h (← mkEqSymm heq) mkEqNDRec (← mkMotive expectedAbst) h heq | _ => throwUnsupportedSyntax @[builtinTermElab stateRefT] def elabStateRefT : TermElab := fun stx _ => do let σ ← elabType stx[1] let mut mStx := stx[2] if mStx.getKind == `Lean.Parser.Term.macroDollarArg then mStx := mStx[1] let m ← elabTerm mStx (← mkArrow (mkSort levelOne) (mkSort levelOne)) let ω ← mkFreshExprMVar (mkSort levelOne) let stWorld ← mkAppM `STWorld #[ω, m] discard <| mkInstMVar stWorld mkAppM `StateRefT' #[ω, σ, m] @[builtinTermElab noindex] def elabNoindex : TermElab := fun stx expectedType? => do let e ← elabTerm stx[1] expectedType? return DiscrTree.mkNoindexAnnotation e end Lean.Elab.Term
a665bd41168579a962dd6ff40f5afcc56a725b34
05b503addd423dd68145d68b8cde5cd595d74365
/src/group_theory/congruence.lean
b22c7d385bfabadd6cf56be34b0fd0877b4a69bd
[ "Apache-2.0" ]
permissive
aestriplex/mathlib
77513ff2b176d74a3bec114f33b519069788811d
e2fa8b2b1b732d7c25119229e3cdfba8370cb00f
refs/heads/master
1,621,969,960,692
1,586,279,279,000
1,586,279,279,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
43,494
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.submonoid import data.setoid import algebra.pi_instances /-! # Congruence relations This file defines congruence relations: equivalence relations that preserve a binary operation, which in this case is multiplication or addition. The principal definition is a `structure` extending a `setoid` (an equivalence relation), and the inductive definition of the smallest congruence relation containing a binary relation is also given (see `con_gen`). The file also proves basic properties of the quotient of a type by a congruence relation, and the complete lattice of congruence relations on a type. We then establish an order-preserving bijection between the set of congruence relations containing a congruence relation `c` and the set of congruence relations on the quotient by `c`. The second half of the file concerns congruence relations on monoids, in which case the quotient by the congruence relation is also a monoid. There are results about the universal property of quotients of monoids, and the isomorphism theorems for monoids. ## Implementation notes The inductive definition of a congruence relation could be a nested inductive type, defined using the equivalence closure of a binary relation `eqv_gen`, but the recursor generated does not work. A nested inductive definition could conceivably shorten proofs, because they would allow invocation of the corresponding lemmas about `eqv_gen`. The lemmas `refl`, `symm` and `trans` are not tagged with `@[refl]`, `@[symm]`, and `@[trans]` respectively as these tags do not work on a structure coerced to a binary relation. There is a coercion from elements of a type to the element's equivalence class under a congruence relation. A congruence relation on a monoid `M` can be thought of as a submonoid of `M × M` for which membership is an equivalence relation, but whilst this fact is established in the file, it is not used, since this perspective adds more layers of definitional unfolding. ## Tags congruence, congruence relation, quotient, quotient by congruence relation, monoid, quotient monoid, isomorphism theorems -/ variables (M : Type*) {N : Type*} {P : Type*} set_option old_structure_cmd true open function setoid /-- A congruence relation on a type with an addition is an equivalence relation which preserves addition. -/ structure add_con [has_add M] extends setoid M := (add' : ∀ {w x y z}, r w x → r y z → r (w + y) (x + z)) /-- A congruence relation on a type with a multiplication is an equivalence relation which preserves multiplication. -/ @[to_additive add_con] structure con [has_mul M] extends setoid M := (mul' : ∀ {w x y z}, r w x → r y z → r (w * y) (x * z)) variables {M} /-- The inductively defined smallest additive congruence relation containing a given binary relation. -/ inductive add_con_gen.rel [has_add M] (r : M → M → Prop) : M → M → Prop | of {} : Π x y, r x y → add_con_gen.rel x y | refl {} : Π x, add_con_gen.rel x x | symm {} : Π x y, add_con_gen.rel x y → add_con_gen.rel y x | trans {} : Π x y z, add_con_gen.rel x y → add_con_gen.rel y z → add_con_gen.rel x z | add {} : Π w x y z, add_con_gen.rel w x → add_con_gen.rel y z → add_con_gen.rel (w + y) (x + z) /-- The inductively defined smallest multiplicative congruence relation containing a given binary relation. -/ @[to_additive add_con_gen.rel] inductive con_gen.rel [has_mul M] (r : M → M → Prop) : M → M → Prop | of {} : Π x y, r x y → con_gen.rel x y | refl {} : Π x, con_gen.rel x x | symm {} : Π x y, con_gen.rel x y → con_gen.rel y x | trans {} : Π x y z, con_gen.rel x y → con_gen.rel y z → con_gen.rel x z | mul {} : Π w x y z, con_gen.rel w x → con_gen.rel y z → con_gen.rel (w * y) (x * z) /-- The inductively defined smallest multiplicative congruence relation containing a given binary relation. -/ @[to_additive add_con_gen "The inductively defined smallest additive congruence relation containing a given binary relation."] def con_gen [has_mul M] (r : M → M → Prop) : con M := ⟨con_gen.rel r, ⟨con_gen.rel.refl, con_gen.rel.symm, con_gen.rel.trans⟩, con_gen.rel.mul⟩ namespace con section variables [has_mul M] [has_mul N] [has_mul P] (c : con M) @[to_additive] instance : inhabited (con M) := ⟨con_gen empty_relation⟩ /-- A coercion from a congruence relation to its underlying binary relation. -/ @[to_additive "A coercion from an additive congruence relation to its underlying binary relation."] instance : has_coe_to_fun (con M) := ⟨_, λ c, λ x y, c.r x y⟩ /-- Congruence relations are reflexive. -/ @[to_additive "Additive congruence relations are reflexive."] protected lemma refl (x) : c x x := c.2.1 x /-- Congruence relations are symmetric. -/ @[to_additive "Additive congruence relations are symmetric."] protected lemma symm : ∀ {x y}, c x y → c y x := λ _ _ h, c.2.2.1 h /-- Congruence relations are transitive. -/ @[to_additive "Additive congruence relations are transitive."] protected lemma trans : ∀ {x y z}, c x y → c y z → c x z := λ _ _ _ h, c.2.2.2 h /-- Multiplicative congruence relations preserve multiplication. -/ @[to_additive "Additive congruence relations preserve addition."] protected lemma mul : ∀ {w x y z}, c w x → c y z → c (w * y) (x * z) := λ _ _ _ _ h1 h2, c.3 h1 h2 /-- Given a type `M` with a multiplication, a congruence relation `c` on `M`, and elements of `M` `x, y`, `(x, y) ∈ M × M` iff `x` is related to `y` by `c`. -/ @[to_additive "Given a type `M` with an addition, `x, y ∈ M`, and an additive congruence relation `c` on `M`, `(x, y) ∈ M × M` iff `x` is related to `y` by `c`."] instance : has_mem (M × M) (con M) := ⟨λ x c, c x.1 x.2⟩ variables {c} /-- The map sending a congruence relation to its underlying binary relation is injective. -/ @[to_additive "The map sending an additive congruence relation to its underlying binary relation is injective."] lemma ext' {c d : con M} (H : c.r = d.r) : c = d := by cases c; cases d; simpa using H /-- Extensionality rule for congruence relations. -/ @[ext, to_additive "Extensionality rule for additive congruence relations."] lemma ext {c d : con M} (H : ∀ x y, c x y ↔ d x y) : c = d := ext' $ by ext; apply H attribute [ext] add_con.ext /-- The map sending a congruence relation to its underlying equivalence relation is injective. -/ @[to_additive "The map sending an additive congruence relation to its underlying equivalence relation is injective."] lemma to_setoid_inj {c d : con M} (H : c.to_setoid = d.to_setoid) : c = d := ext $ ext_iff.1 H /-- Iff version of extensionality rule for congruence relations. -/ @[to_additive "Iff version of extensionality rule for additive congruence relations."] lemma ext_iff {c d : con M} : (∀ x y, c x y ↔ d x y) ↔ c = d := ⟨ext, λ h _ _, h ▸ iff.rfl⟩ /-- Two congruence relations are equal iff their underlying binary relations are equal. -/ @[to_additive "Two additive congruence relations are equal iff their underlying binary relations are equal."] lemma ext'_iff {c d : con M} : c.r = d.r ↔ c = d := ⟨ext', λ h, h ▸ rfl⟩ /-- The kernel of a multiplication-preserving function as a congruence relation. -/ @[to_additive "The kernel of an addition-preserving function as an additive congruence relation."] def mul_ker (f : M → P) (h : ∀ x y, f (x * y) = f x * f y) : con M := { r := λ x y, f x = f y, iseqv := ⟨λ _, rfl, λ _ _, eq.symm, λ _ _ _, eq.trans⟩, mul' := λ _ _ _ _ h1 h2, by rw [h, h1, h2, h] } /-- Given types with multiplications `M, N`, the product of two congruence relations `c` on `M` and `d` on `N`: `(x₁, x₂), (y₁, y₂) ∈ M × N` are related by `c.prod d` iff `x₁` is related to `y₁` by `c` and `x₂` is related to `y₂` by `d`. -/ @[to_additive prod "Given types with additions `M, N`, the product of two congruence relations `c` on `M` and `d` on `N`: `(x₁, x₂), (y₁, y₂) ∈ M × N` are related by `c.prod d` iff `x₁` is related to `y₁` by `c` and `x₂` is related to `y₂` by `d`."] protected def prod (c : con M) (d : con N) : con (M × N) := { mul' := λ _ _ _ _ h1 h2, ⟨c.mul h1.1 h2.1, d.mul h1.2 h2.2⟩, ..c.to_setoid.prod d.to_setoid } /-- The product of an indexed collection of congruence relations. -/ @[to_additive "The product of an indexed collection of additive congruence relations."] def pi {ι : Type*} {f : ι → Type*} [Π i, has_mul (f i)] (C : Π i, con (f i)) : con (Π i, f i) := { mul' := λ _ _ _ _ h1 h2 i, (C i).mul (h1 i) (h2 i), ..@pi_setoid _ _ $ λ i, (C i).to_setoid } variables (c) @[simp, to_additive] lemma coe_eq : c.to_setoid.r = c := rfl -- Quotients /-- Defining the quotient by a congruence relation of a type with a multiplication. -/ @[to_additive "Defining the quotient by an additive congruence relation of a type with an addition."] protected def quotient := quotient $ c.to_setoid /-- Coercion from a type with a multiplication to its quotient by a congruence relation. See Note [use has_coe_t]. -/ @[to_additive "Coercion from a type with an addition to its quotient by an additive congruence relation", priority 0] instance : has_coe_t M c.quotient := ⟨@quotient.mk _ c.to_setoid⟩ /-- The quotient of a type with decidable equality by a congruence relation also has decidable equality. -/ @[to_additive "The quotient of a type with decidable equality by an additive congruence relation also has decidable equality."] instance [d : ∀ a b, decidable (c a b)] : decidable_eq c.quotient := @quotient.decidable_eq M c.to_setoid d /-- The function on the quotient by a congruence relation `c` induced by a function that is constant on `c`'s equivalence classes. -/ @[elab_as_eliminator, to_additive "The function on the quotient by a congruence relation `c` induced by a function that is constant on `c`'s equivalence classes."] protected def lift_on {β} {c : con M} (q : c.quotient) (f : M → β) (h : ∀ a b, c a b → f a = f b) : β := quotient.lift_on' q f h variables {c} /-- The inductive principle used to prove propositions about the elements of a quotient by a congruence relation. -/ @[elab_as_eliminator, to_additive "The inductive principle used to prove propositions about the elements of a quotient by an additive congruence relation."] protected lemma induction_on {C : c.quotient → Prop} (q : c.quotient) (H : ∀ x : M, C x) : C q := quotient.induction_on' q H /-- A version of `con.induction_on` for predicates which take two arguments. -/ @[elab_as_eliminator, to_additive "A version of `add_con.induction_on` for predicates which take two arguments."] protected lemma induction_on₂ {d : con N} {C : c.quotient → d.quotient → Prop} (p : c.quotient) (q : d.quotient) (H : ∀ (x : M) (y : N), C x y) : C p q := quotient.induction_on₂' p q H variables (c) /-- Two elements are related by a congruence relation `c` iff they are represented by the same element of the quotient by `c`. -/ @[simp, to_additive "Two elements are related by an additive congruence relation `c` iff they are represented by the same element of the quotient by `c`."] protected lemma eq {a b : M} : (a : c.quotient) = b ↔ c a b := quotient.eq' /-- The multiplication induced on the quotient by a congruence relation on a type with a multiplication. -/ @[to_additive "The addition induced on the quotient by an additive congruence relation on a type with a addition."] instance has_mul : has_mul c.quotient := ⟨λ x y, quotient.lift_on₂' x y (λ w z, ((w * z : M) : c.quotient)) $ λ _ _ _ _ h1 h2, c.eq.2 $ c.mul h1 h2⟩ /-- The kernel of the quotient map induced by a congruence relation `c` equals `c`. -/ @[simp, to_additive "The kernel of the quotient map induced by an additive congruence relation `c` equals `c`."] lemma mul_ker_mk_eq : mul_ker (coe : M → c.quotient) (λ x y, rfl) = c := ext $ λ x y, quotient.eq' variables {c} /-- The coercion to the quotient of a congruence relation commutes with multiplication (by definition). -/ @[simp, to_additive "The coercion to the quotient of an additive congruence relation commutes with addition (by definition)."] lemma coe_mul (x y : M) : (↑(x * y) : c.quotient) = ↑x * ↑y := rfl /-- Definition of the function on the quotient by a congruence relation `c` induced by a function that is constant on `c`'s equivalence classes. -/ @[simp, to_additive "Definition of the function on the quotient by an additive congruence relation `c` induced by a function that is constant on `c`'s equivalence classes."] protected lemma lift_on_beta {β} (c : con M) (f : M → β) (h : ∀ a b, c a b → f a = f b) (x : M) : con.lift_on (x : c.quotient) f h = f x := rfl /-- Makes an isomorphism of quotients by two congruence relations, given that the relations are equal. -/ @[to_additive "Makes an additive isomorphism of quotients by two additive congruence relations, given that the relations are equal."] protected def congr {c d : con M} (h : c = d) : c.quotient ≃* d.quotient := { map_mul' := λ x y, by rcases x; rcases y; refl, ..quotient.congr (equiv.refl M) $ by apply ext_iff.2 h } -- The complete lattice of congruence relations on a type /-- For congruence relations `c, d` on a type `M` with a multiplication, `c ≤ d` iff `∀ x y ∈ M`, `x` is related to `y` by `d` if `x` is related to `y` by `c`. -/ @[to_additive "For additive congruence relations `c, d` on a type `M` with an addition, `c ≤ d` iff `∀ x y ∈ M`, `x` is related to `y` by `d` if `x` is related to `y` by `c`."] instance : has_le (con M) := ⟨λ c d, c.to_setoid ≤ d.to_setoid⟩ /-- Definition of `≤` for congruence relations. -/ @[to_additive "Definition of `≤` for additive congruence relations."] theorem le_def {c d : con M} : c ≤ d ↔ ∀ {x y}, c x y → d x y := iff.rfl /-- The infimum of a set of congruence relations on a given type with a multiplication. -/ @[to_additive "The infimum of a set of additive congruence relations on a given type with an addition."] instance : has_Inf (con M) := ⟨λ S, ⟨λ x y, ∀ c : con M, c ∈ S → c x y, ⟨λ x c hc, c.refl x, λ _ _ h c hc, c.symm $ h c hc, λ _ _ _ h1 h2 c hc, c.trans (h1 c hc) $ h2 c hc⟩, λ _ _ _ _ h1 h2 c hc, c.mul (h1 c hc) $ h2 c hc⟩⟩ /-- The infimum of a set of congruence relations is the same as the infimum of the set's image under the map to the underlying equivalence relation. -/ @[to_additive "The infimum of a set of additive congruence relations is the same as the infimum of the set's image under the map to the underlying equivalence relation."] lemma Inf_to_setoid (S : set (con M)) : (Inf S).to_setoid = Inf (to_setoid '' S) := setoid.ext' $ λ x y, ⟨λ h r ⟨c, hS, hr⟩, by rw ←hr; exact h c hS, λ h c hS, h c.to_setoid ⟨c, hS, rfl⟩⟩ /-- The infimum of a set of congruence relations is the same as the infimum of the set's image under the map to the underlying binary relation. -/ @[to_additive "The infimum of a set of additive congruence relations is the same as the infimum of the set's image under the map to the underlying binary relation."] lemma Inf_def (S : set (con M)) : (Inf S).r = Inf (r '' S) := by { ext, simp only [Inf_image, infi_apply, infi_Prop_eq], refl } /-- If a congruence relation `c` is contained in every element of a set `s` of congruence relations on the same type, `c` is contained in the infimum of `s`. -/ @[to_additive "If an additive congruence relation `c` is contained in every element of a set `s` of additive congruence relations on the same type, `c` is contained in the infimum of `s`."] lemma le_Inf (s : set (con M)) (c) : (∀d ∈ s, c ≤ d) → c ≤ Inf s := λ h _ _ hc r hr, h r hr _ _ hc /-- The infimum of a set of congruence relations on a given type is contained in every element of the set. -/ @[to_additive "The infimum of a set of additive congruence relations on a given type is contained in every element of the set."] lemma Inf_le (s : set (con M)) (c) : c ∈ s → Inf s ≤ c := λ hc _ _ h, h c hc /-- The complete lattice of congruence relations on a given type with a multiplication. -/ @[to_additive "The complete lattice of additive congruence relations on a given type with an addition."] instance : complete_lattice (con M) := { sup := λ c d, Inf { x | c ≤ x ∧ d ≤ x}, le := (≤), lt := λ c d, c ≤ d ∧ ¬d ≤ c, le_refl := λ c _ _, id, le_trans := λ c1 c2 c3 h1 h2 x y h, h2 x y $ h1 x y h, lt_iff_le_not_le := λ _ _, iff.rfl, le_antisymm := λ c d hc hd, ext $ λ x y, ⟨hc x y, hd x y⟩, le_sup_left := λ _ _ _ _ h r hr, hr.1 _ _ h, le_sup_right := λ _ _ _ _ h r hr, hr.2 _ _ h, sup_le := λ _ _ c h1 h2, Inf_le _ c ⟨h1, h2⟩, inf := λ c d, ⟨(c.to_setoid ⊓ d.to_setoid).1, (c.to_setoid ⊓ d.to_setoid).2, λ _ _ _ _ h1 h2, ⟨c.mul h1.1 h2.1, d.mul h1.2 h2.2⟩⟩, inf_le_left := λ _ _ _ _ h, h.1, inf_le_right := λ _ _ _ _ h, h.2, le_inf := λ _ _ _ hb hc _ _ h, ⟨hb _ _ h, hc _ _ h⟩, top := { mul' := by tauto, ..setoid.complete_lattice.top}, le_top := λ _ _ _ h, trivial, bot := { mul' := λ _ _ _ _ h1 h2, h1 ▸ h2 ▸ rfl, ..setoid.complete_lattice.bot}, bot_le := λ c x y h, h ▸ c.refl x, Sup := λ tt, Inf {t | ∀t'∈tt, t' ≤ t}, Inf := has_Inf.Inf, le_Sup := λ _ _ hs, le_Inf _ _ $ λ c' hc', hc' _ hs, Sup_le := λ _ _ hs, Inf_le _ _ hs, Inf_le := λ _ _, Inf_le _ _, le_Inf := λ _ _, le_Inf _ _ } /-- The infimum of two congruence relations equals the infimum of the underlying binary operations. -/ @[to_additive "The infimum of two additive congruence relations equals the infimum of the underlying binary operations."] lemma inf_def {c d : con M} : (c ⊓ d).r = c.r ⊓ d.r := rfl /-- Definition of the infimum of two congruence relations. -/ @[to_additive "Definition of the infimum of two additive congruence relations."] theorem inf_iff_and {c d : con M} {x y} : (c ⊓ d) x y ↔ c x y ∧ d x y := iff.rfl /-- The inductively defined smallest congruence relation containing a binary relation `r` equals the infimum of the set of congruence relations containing `r`. -/ @[to_additive add_con_gen_eq "The inductively defined smallest additive congruence relation containing a binary relation `r` equals the infimum of the set of additive congruence relations containing `r`."] theorem con_gen_eq (r : M → M → Prop) : con_gen r = Inf {s : con M | ∀ x y, r x y → s.r x y} := ext $ λ x y, ⟨λ H, con_gen.rel.rec_on H (λ _ _ h _ hs, hs _ _ h) (con.refl _) (λ _ _ _, con.symm _) (λ _ _ _ _ _, con.trans _) $ λ w x y z _ _ h1 h2 c hc, c.mul (h1 c hc) $ h2 c hc, Inf_le _ _ (λ _ _, con_gen.rel.of _ _) _ _⟩ /-- The smallest congruence relation containing a binary relation `r` is contained in any congruence relation containing `r`. -/ @[to_additive add_con_gen_le "The smallest additive congruence relation containing a binary relation `r` is contained in any additive congruence relation containing `r`."] theorem con_gen_le {r : M → M → Prop} {c : con M} (h : ∀ x y, r x y → c.r x y) : con_gen r ≤ c := by rw con_gen_eq; exact Inf_le _ _ h /-- Given binary relations `r, s` with `r` contained in `s`, the smallest congruence relation containing `s` contains the smallest congruence relation containing `r`. -/ @[to_additive add_con_gen_mono "Given binary relations `r, s` with `r` contained in `s`, the smallest additive congruence relation containing `s` contains the smallest additive congruence relation containing `r`."] theorem con_gen_mono {r s : M → M → Prop} (h : ∀ x y, r x y → s x y) : con_gen r ≤ con_gen s := con_gen_le $ λ x y hr, con_gen.rel.of _ _ $ h x y hr /-- Congruence relations equal the smallest congruence relation in which they are contained. -/ @[simp, to_additive add_con_gen_of_add_con "Additive congruence relations equal the smallest additive congruence relation in which they are contained."] lemma con_gen_of_con (c : con M) : con_gen c.r = c := le_antisymm (by rw con_gen_eq; exact Inf_le _ c (λ _ _, id)) con_gen.rel.of /-- The map sending a binary relation to the smallest congruence relation in which it is contained is idempotent. -/ @[simp, to_additive add_con_gen_idem "The map sending a binary relation to the smallest additive congruence relation in which it is contained is idempotent."] lemma con_gen_idem (r : M → M → Prop) : con_gen (con_gen r).r = con_gen r := con_gen_of_con _ /-- The supremum of congruence relations `c, d` equals the smallest congruence relation containing the binary relation '`x` is related to `y` by `c` or `d`'. -/ @[to_additive sup_eq_add_con_gen "The supremum of additive congruence relations `c, d` equals the smallest additive congruence relation containing the binary relation '`x` is related to `y` by `c` or `d`'."] lemma sup_eq_con_gen (c d : con M) : c ⊔ d = con_gen (λ x y, c x y ∨ d x y) := begin rw con_gen_eq, apply congr_arg Inf, ext, exact ⟨λ h _ _ H, or.elim H (h.1 _ _) (h.2 _ _), λ H, ⟨λ _ _ h, H _ _ $ or.inl h, λ _ _ h, H _ _ $ or.inr h⟩⟩, end /-- The supremum of two congruence relations equals the smallest congruence relation containing the supremum of the underlying binary operations. -/ @[to_additive "The supremum of two additive congruence relations equals the smallest additive congruence relation containing the supremum of the underlying binary operations."] lemma sup_def {c d : con M} : c ⊔ d = con_gen (c.r ⊔ d.r) := by rw sup_eq_con_gen; refl /-- The supremum of a set of congruence relations `S` equals the smallest congruence relation containing the binary relation 'there exists `c ∈ S` such that `x` is related to `y` by `c`'. -/ @[to_additive Sup_eq_add_con_gen "The supremum of a set of additive congruence relations S equals the smallest additive congruence relation containing the binary relation 'there exists `c ∈ S` such that `x` is related to `y` by `c`'."] lemma Sup_eq_con_gen (S : set (con M)) : Sup S = con_gen (λ x y, ∃ c : con M, c ∈ S ∧ c x y) := begin rw con_gen_eq, apply congr_arg Inf, ext, exact ⟨λ h _ _ ⟨r, hr⟩, h r hr.1 _ _ hr.2, λ h r hS _ _ hr, h _ _ ⟨r, hS, hr⟩⟩, end /-- The supremum of a set of congruence relations is the same as the smallest congruence relation containing the supremum of the set's image under the map to the underlying binary relation. -/ @[to_additive "The supremum of a set of additive congruence relations is the same as the smallest additive congruence relation containing the supremum of the set's image under the map to the underlying binary relation."] lemma Sup_def {S : set (con M)} : Sup S = con_gen (Sup (r '' S)) := begin rw Sup_eq_con_gen, congr, ext x y, erw [Sup_image, supr_apply, supr_apply, supr_Prop_eq], simp only [Sup_image, supr_Prop_eq, supr_apply, supr_Prop_eq, exists_prop], refl, end variables (M) /-- There is a Galois insertion of congruence relations on a type with a multiplication `M` into binary relations on `M`. -/ @[to_additive "There is a Galois insertion of additive congruence relations on a type with an addition `M` into binary relations on `M`."] protected def gi : @galois_insertion (M → M → Prop) (con M) _ _ con_gen r := { choice := λ r h, con_gen r, gc := λ r c, ⟨λ H _ _ h, H _ _ $ con_gen.rel.of _ _ h, λ H, con_gen_of_con c ▸ con_gen_mono H⟩, le_l_u := λ x, (con_gen_of_con x).symm ▸ le_refl x, choice_eq := λ _ _, rfl } variables {M} (c) /-- Given a function `f`, the smallest congruence relation containing the binary relation on `f`'s image defined by '`x ≈ y` iff the elements of `f⁻¹(x)` are related to the elements of `f⁻¹(y)` by a congruence relation `c`.' -/ @[to_additive "Given a function `f`, the smallest additive congruence relation containing the binary relation on `f`'s image defined by '`x ≈ y` iff the elements of `f⁻¹(x)` are related to the elements of `f⁻¹(y)` by an additive congruence relation `c`.'"] def map_gen (f : M → N) : con N := con_gen $ λ x y, ∃ a b, f a = x ∧ f b = y ∧ c a b /-- Given a surjective multiplicative-preserving function `f` whose kernel is contained in a congruence relation `c`, the congruence relation on `f`'s codomain defined by '`x ≈ y` iff the elements of `f⁻¹(x)` are related to the elements of `f⁻¹(y)` by `c`.' -/ @[to_additive "Given a surjective addition-preserving function `f` whose kernel is contained in an additive congruence relation `c`, the additive congruence relation on `f`'s codomain defined by '`x ≈ y` iff the elements of `f⁻¹(x)` are related to the elements of `f⁻¹(y)` by `c`.'"] def map_of_surjective (f : M → N) (H : ∀ x y, f (x * y) = f x * f y) (h : mul_ker f H ≤ c) (hf : surjective f) : con N := { mul' := λ w x y z ⟨a, b, hw, hx, h1⟩ ⟨p, q, hy, hz, h2⟩, ⟨a * p, b * q, by rw [H, hw, hy], by rw [H, hx, hz], c.mul h1 h2⟩, ..c.to_setoid.map_of_surjective f h hf } /-- A specialization of 'the smallest congruence relation containing a congruence relation `c` equals `c`'. -/ @[to_additive "A specialization of 'the smallest additive congruence relation containing an additive congruence relation `c` equals `c`'."] lemma map_of_surjective_eq_map_gen {c : con M} {f : M → N} (H : ∀ x y, f (x * y) = f x * f y) (h : mul_ker f H ≤ c) (hf : surjective f) : c.map_gen f = c.map_of_surjective f H h hf := by rw ←con_gen_of_con (c.map_of_surjective f H h hf); refl /-- Given types with multiplications `M, N` and a congruence relation `c` on `N`, a multiplication-preserving map `f : M → N` induces a congruence relation on `f`'s domain defined by '`x ≈ y` iff `f(x)` is related to `f(y)` by `c`.' -/ @[to_additive "Given types with additions `M, N` and an additive congruence relation `c` on `N`, an addition-preserving map `f : M → N` induces an additive congruence relation on `f`'s domain defined by '`x ≈ y` iff `f(x)` is related to `f(y)` by `c`.' "] def comap (f : M → N) (H : ∀ x y, f (x * y) = f x * f y) (c : con N) : con M := { mul' := λ w x y z h1 h2, show c (f (w * y)) (f (x * z)), by rw [H, H]; exact c.mul h1 h2, ..c.to_setoid.comap f } section open quotient /-- Given a congruence relation `c` on a type `M` with a multiplication, the order-preserving bijection between the set of congruence relations containing `c` and the congruence relations on the quotient of `M` by `c`. -/ @[to_additive "Given an additive congruence relation `c` on a type `M` with an addition, the order-preserving bijection between the set of additive congruence relations containing `c` and the additive congruence relations on the quotient of `M` by `c`."] def correspondence : ((≤) : {d // c ≤ d} → {d // c ≤ d} → Prop) ≃o ((≤) : con c.quotient → con c.quotient → Prop) := { to_fun := λ d, d.1.map_of_surjective coe _ (by rw mul_ker_mk_eq; exact d.2) $ @exists_rep _ c.to_setoid, inv_fun := λ d, ⟨comap (coe : M → c.quotient) (λ x y, rfl) d, λ _ _ h, show d _ _, by rw c.eq.2 h; exact d.refl _ ⟩, left_inv := λ d, subtype.ext.2 $ ext $ λ _ _, ⟨λ h, let ⟨a, b, hx, hy, H⟩ := h in d.1.trans (d.1.symm $ d.2 a _ $ c.eq.1 hx) $ d.1.trans H $ d.2 b _ $ c.eq.1 hy, λ h, ⟨_, _, rfl, rfl, h⟩⟩, right_inv := λ d, let Hm : mul_ker (coe : M → c.quotient) (λ x y, rfl) ≤ comap (coe : M → c.quotient) (λ x y, rfl) d := λ x y h, show d _ _, by rw mul_ker_mk_eq at h; exact c.eq.2 h ▸ d.refl _ in ext $ λ x y, ⟨λ h, let ⟨a, b, hx, hy, H⟩ := h in hx ▸ hy ▸ H, con.induction_on₂ x y $ λ w z h, ⟨w, z, rfl, rfl, h⟩⟩, ord := λ s t, ⟨λ h _ _ hs, let ⟨a, b, hx, hy, Hs⟩ := hs in ⟨a, b, hx, hy, h _ _ Hs⟩, λ h _ _ hs, let ⟨a, b, hx, hy, ht⟩ := h _ _ ⟨_, _, rfl, rfl, hs⟩ in t.1.trans (t.1.symm $ t.2 a _ $ eq_rel.1 hx) $ t.1.trans ht $ t.2 b _ $ eq_rel.1 hy⟩ } end end -- Monoids variables {M} [monoid M] [monoid N] [monoid P] (c : con M) /-- The quotient of a monoid by a congruence relation is a monoid. -/ @[to_additive add_monoid "The quotient of an `add_monoid` by an additive congruence relation is an `add_monoid`."] instance monoid : monoid c.quotient := { one := ((1 : M) : c.quotient), mul := (*), mul_assoc := λ x y z, quotient.induction_on₃' x y z $ λ _ _ _, congr_arg coe $ mul_assoc _ _ _, mul_one := λ x, quotient.induction_on' x $ λ _, congr_arg coe $ mul_one _, one_mul := λ x, quotient.induction_on' x $ λ _, congr_arg coe $ one_mul _ } /-- The quotient of a `comm_monoid` by a congruence relation is a `comm_monoid`. -/ @[to_additive add_comm_monoid "The quotient of an `add_comm_monoid` by an additive congruence relation is an `add_comm_monoid`."] instance comm_monoid {α : Type*} [comm_monoid α] (c : con α) : comm_monoid c.quotient := { mul_comm := λ x y, con.induction_on₂ x y $ λ w z, by rw [←coe_mul, ←coe_mul, mul_comm], ..c.monoid} variables {c} /-- The 1 of the quotient of a monoid by a congruence relation is the equivalence class of the monoid's 1. -/ @[simp, to_additive "The 0 of the quotient of an `add_monoid` by an additive congruence relation is the equivalence class of the `add_monoid`'s 0."] lemma coe_one : ((1 : M) : c.quotient) = 1 := rfl variables (M c) /-- The submonoid of `M × M` defined by a congruence relation on a monoid `M`. -/ @[to_additive add_submonoid "The `add_submonoid` of `M × M` defined by an additive congruence relation on an `add_monoid` `M`."] protected def submonoid : submonoid (M × M) := { carrier := { x | c x.1 x.2 }, one_mem' := c.iseqv.1 1, mul_mem' := λ _ _, c.mul } variables {M c} /-- The congruence relation on a monoid `M` from a submonoid of `M × M` for which membership is an equivalence relation. -/ @[to_additive of_add_submonoid "The additive congruence relation on an `add_monoid` `M` from an `add_submonoid` of `M × M` for which membership is an equivalence relation."] def of_submonoid (N : submonoid (M × M)) (H : equivalence (λ x y, (x, y) ∈ N)) : con M := { r := λ x y, (x, y) ∈ N, iseqv := H, mul' := λ _ _ _ _, N.mul_mem } /-- Coercion from a congruence relation `c` on a monoid `M` to the submonoid of `M × M` whose elements are `(x, y)` such that `x` is related to `y` by `c`. -/ @[to_additive to_add_submonoid "Coercion from a congruence relation `c` on an `add_monoid` `M` to the `add_submonoid` of `M × M` whose elements are `(x, y)` such that `x` is related to `y` by `c`."] instance to_submonoid : has_coe (con M) (submonoid (M × M)) := ⟨λ c, c.submonoid M⟩ @[to_additive] lemma mem_coe {c : con M} {x y} : (x, y) ∈ (↑c : submonoid (M × M)) ↔ (x, y) ∈ c := iff.rfl @[to_additive to_add_submonoid_inj] theorem to_submonoid_inj (c d : con M) (H : (c : submonoid (M × M)) = d) : c = d := ext $ λ x y, show (x, y) ∈ (c : submonoid (M × M)) ↔ (x, y) ∈ ↑d, by rw H @[to_additive] lemma le_iff {c d : con M} : c ≤ d ↔ (c : submonoid (M × M)) ≤ d := ⟨λ h x, h x.1 x.2, λ h x y hc, h $ show (x, y) ∈ c, from hc⟩ /-- The kernel of a monoid homomorphism as a congruence relation. -/ @[to_additive "The kernel of an `add_monoid` homomorphism as an additive congruence relation."] def ker (f : M →* P) : con M := mul_ker f f.3 /-- The definition of the congruence relation defined by a monoid homomorphism's kernel. -/ @[to_additive "The definition of the additive congruence relation defined by an `add_monoid` homomorphism's kernel."] lemma ker_rel (f : M →* P) {x y} : ker f x y ↔ f x = f y := iff.rfl /-- There exists an element of the quotient of a monoid by a congruence relation (namely 1). -/ @[to_additive "There exists an element of the quotient of an `add_monoid` by a congruence relation (namely 0)."] instance quotient.inhabited : inhabited c.quotient := ⟨((1 : M) : c.quotient)⟩ variables (c) /-- The natural homomorphism from a monoid to its quotient by a congruence relation. -/ @[to_additive "The natural homomorphism from an `add_monoid` to its quotient by an additive congruence relation."] def mk' : M →* c.quotient := ⟨coe, rfl, λ _ _, rfl⟩ variables (x y : M) /-- The kernel of the natural homomorphism from a monoid to its quotient by a congruence relation `c` equals `c`. -/ @[simp, to_additive "The kernel of the natural homomorphism from an `add_monoid` to its quotient by an additive congruence relation `c` equals `c`."] lemma mk'_ker : ker c.mk' = c := ext $ λ _ _, c.eq variables {c} /-- The natural homomorphism from a monoid to its quotient by a congruence relation is surjective. -/ @[to_additive "The natural homomorphism from an `add_monoid` to its quotient by a congruence relation is surjective."] lemma mk'_surjective : surjective c.mk' := λ x, by rcases x; exact ⟨x, rfl⟩ @[simp, to_additive] lemma comp_mk'_apply (g : c.quotient →* P) {x} : g.comp c.mk' x = g x := rfl /-- The elements related to `x ∈ M`, `M` a monoid, by the kernel of a monoid homomorphism are those in the preimage of `f(x)` under `f`. -/ @[to_additive "The elements related to `x ∈ M`, `M` an `add_monoid`, by the kernel of an `add_monoid` homomorphism are those in the preimage of `f(x)` under `f`. "] lemma ker_apply_eq_preimage {f : M →* P} (x) : (ker f) x = f ⁻¹' {f x} := set.ext $ λ x, ⟨λ h, set.mem_preimage.2 $ set.mem_singleton_iff.2 h.symm, λ h, (set.mem_singleton_iff.1 $ set.mem_preimage.1 h).symm⟩ /-- Given a monoid homomorphism `f : N → M` and a congruence relation `c` on `M`, the congruence relation induced on `N` by `f` equals the kernel of `c`'s quotient homomorphism composed with `f`. -/ @[to_additive "Given an `add_monoid` homomorphism `f : N → M` and an additive congruence relation `c` on `M`, the additive congruence relation induced on `N` by `f` equals the kernel of `c`'s quotient homomorphism composed with `f`."] lemma comap_eq {f : N →* M} : comap f f.map_mul c = ker (c.mk'.comp f) := ext $ λ x y, show c _ _ ↔ c.mk' _ = c.mk' _, by rw ←c.eq; refl variables (c) (f : M →* P) /-- The homomorphism on the quotient of a monoid by a congruence relation `c` induced by a homomorphism constant on `c`'s equivalence classes. -/ @[to_additive "The homomorphism on the quotient of an `add_monoid` by an additive congruence relation `c` induced by a homomorphism constant on `c`'s equivalence classes."] def lift (H : c ≤ ker f) : c.quotient →* P := { to_fun := λ x, con.lift_on x f $ λ _ _, H _ _, map_one' := by rw ←f.map_one; refl, map_mul' := λ x y, con.induction_on₂ x y $ λ m n, f.map_mul m n ▸ rfl } variables {c f} /-- The diagram describing the universal property for quotients of monoids commutes. -/ @[simp, to_additive "The diagram describing the universal property for quotients of `add_monoid`s commutes."] lemma lift_mk' (H : c ≤ ker f) (x) : c.lift f H (c.mk' x) = f x := rfl /-- The diagram describing the universal property for quotients of monoids commutes. -/ @[simp, to_additive "The diagram describing the universal property for quotients of `add_monoid`s commutes."] lemma lift_coe (H : c ≤ ker f) (x : M) : c.lift f H x = f x := rfl /-- The diagram describing the universal property for quotients of monoids commutes. -/ @[simp, to_additive "The diagram describing the universal property for quotients of `add_monoid`s commutes."] theorem lift_comp_mk' (H : c ≤ ker f) : (c.lift f H).comp c.mk' = f := by ext; refl /-- Given a homomorphism `f` from the quotient of a monoid by a congruence relation, `f` equals the homomorphism on the quotient induced by `f` composed with the natural map from the monoid to the quotient. -/ @[simp, to_additive "Given a homomorphism `f` from the quotient of an `add_monoid` by an additive congruence relation, `f` equals the homomorphism on the quotient induced by `f` composed with the natural map from the `add_monoid` to the quotient."] lemma lift_apply_mk' (f : c.quotient →* P) : c.lift (f.comp c.mk') (λ x y h, show f ↑x = f ↑y, by rw c.eq.2 h) = f := by ext; rcases x; refl /-- Homomorphisms on the quotient of a monoid by a congruence relation are equal if they are equal on elements that are coercions from the monoid. -/ @[to_additive "Homomorphisms on the quotient of an `add_monoid` by an additive congruence relation are equal if they are equal on elements that are coercions from the `add_monoid`."] lemma lift_funext (f g : c.quotient →* P) (h : ∀ a : M, f a = g a) : f = g := begin rw [←lift_apply_mk' f, ←lift_apply_mk' g], congr' 1, exact monoid_hom.ext_iff.2 h, end /-- The uniqueness part of the universal property for quotients of monoids. -/ @[to_additive "The uniqueness part of the universal property for quotients of `add_monoid`s."] theorem lift_unique (H : c ≤ ker f) (g : c.quotient →* P) (Hg : g.comp c.mk' = f) : g = c.lift f H := lift_funext g (c.lift f H) $ λ x, by rw [lift_coe H, ←comp_mk'_apply, Hg] /-- Given a congruence relation `c` on a monoid and a homomorphism `f` constant on `c`'s equivalence classes, `f` has the same image as the homomorphism that `f` induces on the quotient. -/ @[to_additive "Given an additive congruence relation `c` on an `add_monoid` and a homomorphism `f` constant on `c`'s equivalence classes, `f` has the same image as the homomorphism that `f` induces on the quotient."] theorem lift_range (H : c ≤ ker f) : (c.lift f H).mrange = f.mrange := submonoid.ext $ λ x, ⟨λ ⟨y, hy⟩, by revert hy; rcases y; exact λ hy, ⟨y, hy.1, by rw [hy.2.symm, ←lift_coe H]; refl⟩, λ ⟨y, hy⟩, ⟨↑y, hy.1, by rw ←hy.2; refl⟩⟩ /-- Surjective monoid homomorphisms constant on a congruence relation `c`'s equivalence classes induce a surjective homomorphism on `c`'s quotient. -/ @[to_additive "Surjective `add_monoid` homomorphisms constant on an additive congruence relation `c`'s equivalence classes induce a surjective homomorphism on `c`'s quotient."] lemma lift_surjective_of_surjective (h : c ≤ ker f) (hf : surjective f) : surjective (c.lift f h) := λ y, exists.elim (hf y) $ λ w hw, ⟨w, (lift_mk' h w).symm ▸ hw⟩ variables (c f) /-- Given a monoid homomorphism `f` from `M` to `P`, the kernel of `f` is the unique congruence relation on `M` whose induced map from the quotient of `M` to `P` is injective. -/ @[to_additive "Given an `add_monoid` homomorphism `f` from `M` to `P`, the kernel of `f` is the unique additive congruence relation on `M` whose induced map from the quotient of `M` to `P` is injective."] lemma ker_eq_lift_of_injective (H : c ≤ ker f) (h : injective (c.lift f H)) : ker f = c := to_setoid_inj $ ker_eq_lift_of_injective f H h variables {c} /-- The homomorphism induced on the quotient of a monoid by the kernel of a monoid homomorphism. -/ @[to_additive "The homomorphism induced on the quotient of an `add_monoid` by the kernel of an `add_monoid` homomorphism."] def ker_lift : (ker f).quotient →* P := (ker f).lift f $ λ _ _, id variables {f} /-- The diagram described by the universal property for quotients of monoids, when the congruence relation is the kernel of the homomorphism, commutes. -/ @[simp, to_additive "The diagram described by the universal property for quotients of `add_monoid`s, when the additive congruence relation is the kernel of the homomorphism, commutes."] lemma ker_lift_mk (x : M) : ker_lift f x = f x := rfl /-- Given a monoid homomorphism `f`, the induced homomorphism on the quotient by `f`'s kernel has the same image as `f`. -/ @[simp, to_additive "Given an `add_monoid` homomorphism `f`, the induced homomorphism on the quotient by `f`'s kernel has the same image as `f`."] lemma ker_lift_range_eq : (ker_lift f).mrange = f.mrange := lift_range $ λ _ _, id /-- A monoid homomorphism `f` induces an injective homomorphism on the quotient by `f`'s kernel. -/ @[to_additive "An `add_monoid` homomorphism `f` induces an injective homomorphism on the quotient by `f`'s kernel."] lemma injective_ker_lift (f : M →* P) : injective (ker_lift f) := λ x y, quotient.induction_on₂' x y $ λ _ _, (ker f).eq.2 /-- Given congruence relations `c, d` on a monoid such that `d` contains `c`, `d`'s quotient map induces a homomorphism from the quotient by `c` to the quotient by `d`. -/ @[to_additive "Given additive congruence relations `c, d` on an `add_monoid` such that `d` contains `c`, `d`'s quotient map induces a homomorphism from the quotient by `c` to the quotient by `d`."] def map (c d : con M) (h : c ≤ d) : c.quotient →* d.quotient := c.lift d.mk' $ λ x y hc, show (ker d.mk') x y, from (mk'_ker d).symm ▸ h x y hc /-- Given congruence relations `c, d` on a monoid such that `d` contains `c`, the definition of the homomorphism from the quotient by `c` to the quotient by `d` induced by `d`'s quotient map. -/ @[to_additive "Given additive congruence relations `c, d` on an `add_monoid` such that `d` contains `c`, the definition of the homomorphism from the quotient by `c` to the quotient by `d` induced by `d`'s quotient map."] lemma map_apply {c d : con M} (h : c ≤ d) (x) : c.map d h x = c.lift d.mk' (λ x y hc, d.eq.2 $ h x y hc) x := rfl variables (c) /-- The first isomorphism theorem for monoids. -/ @[to_additive "The first isomorphism theorem for `add_monoid`s."] noncomputable def quotient_ker_equiv_range (f : M →* P) : (ker f).quotient ≃* f.mrange := { map_mul' := monoid_hom.map_mul _, ..@equiv.of_bijective _ _ ((@mul_equiv.to_monoid_hom (ker_lift f).mrange _ _ _ $ mul_equiv.submonoid_congr ker_lift_range_eq).comp (ker_lift f).range_restrict) $ bijective_comp (equiv.bijective _) ⟨λ x y h, injective_ker_lift f $ by rcases x; rcases y; injections, λ ⟨w, z, hzm, hz⟩, ⟨z, by rcases hz; rcases _x; refl⟩⟩ } /-- The first isomorphism theorem for monoids in the case of a surjective homomorphism. -/ @[to_additive "The first isomorphism theorem for `add_monoid`s in the case of a surjective homomorphism."] noncomputable def quotient_ker_equiv_of_surjective (f : M →* P) (hf : surjective f) : (ker f).quotient ≃* P := { map_mul' := monoid_hom.map_mul _, ..@equiv.of_bijective _ _ (ker_lift f) ⟨injective_ker_lift f, lift_surjective_of_surjective (le_refl _) hf⟩ } /-- The second isomorphism theorem for monoids. -/ @[to_additive "The second isomorphism theorem for `add_monoid`s."] noncomputable def comap_quotient_equiv (f : N →* M) : (comap f f.map_mul c).quotient ≃* (c.mk'.comp f).mrange := (con.congr comap_eq).trans $ quotient_ker_equiv_range $ c.mk'.comp f /-- The third isomorphism theorem for monoids. -/ @[to_additive "The third isomorphism theorem for `add_monoid`s."] def quotient_quotient_equiv_quotient (c d : con M) (h : c ≤ d) : (ker (c.map d h)).quotient ≃* d.quotient := { map_mul' := λ x y, con.induction_on₂ x y $ λ w z, con.induction_on₂ w z $ λ a b, show _ = d.mk' a * d.mk' b, by rw ←d.mk'.map_mul; refl, ..quotient_quotient_equiv_quotient _ _ h } end con
9b9db26ed27478e0cffe4669b6d8e165d608924e
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/category_theory/sums/basic.lean
f17949c7f65c822b9ba6af4667caabbc08eaddb5
[]
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,425
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 Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.category_theory.eq_to_hom import Mathlib.PostPort universes u₁ v₁ namespace Mathlib /-# Disjoint unions of categories, functors, and natural transformations. -/ namespace category_theory /-- `sum C D` gives the direct sum of two categories. -/ protected instance sum (C : Type u₁) [category C] (D : Type u₁) [category D] : category (C ⊕ D) := category.mk @[simp] theorem sum_comp_inl (C : Type u₁) [category C] (D : Type u₁) [category D] {P : C} {Q : C} {R : C} (f : sum.inl P ⟶ sum.inl Q) (g : sum.inl Q ⟶ sum.inl R) : f ≫ g = f ≫ g := rfl @[simp] theorem sum_comp_inr (C : Type u₁) [category C] (D : Type u₁) [category D] {P : D} {Q : D} {R : D} (f : sum.inr P ⟶ sum.inr Q) (g : sum.inr Q ⟶ sum.inr R) : f ≫ g = f ≫ g := rfl namespace sum /-- `inl_` is the functor `X ↦ inl X`. -/ -- Unfortunate naming here, suggestions welcome. def inl_ (C : Type u₁) [category C] (D : Type u₁) [category D] : C ⥤ C ⊕ D := functor.mk (fun (X : C) => sum.inl X) fun (X Y : C) (f : X ⟶ Y) => f /-- `inr_` is the functor `X ↦ inr X`. -/ def inr_ (C : Type u₁) [category C] (D : Type u₁) [category D] : D ⥤ C ⊕ D := functor.mk (fun (X : D) => sum.inr X) fun (X Y : D) (f : X ⟶ Y) => f /-- The functor exchanging two direct summand categories. -/ def swap (C : Type u₁) [category C] (D : Type u₁) [category D] : C ⊕ D ⥤ D ⊕ C := functor.mk (fun (X : C ⊕ D) => sorry) fun (X Y : C ⊕ D) (f : X ⟶ Y) => sorry @[simp] theorem swap_obj_inl (C : Type u₁) [category C] (D : Type u₁) [category D] (X : C) : functor.obj (swap C D) (sum.inl X) = sum.inr X := rfl @[simp] theorem swap_obj_inr (C : Type u₁) [category C] (D : Type u₁) [category D] (X : D) : functor.obj (swap C D) (sum.inr X) = sum.inl X := rfl @[simp] theorem swap_map_inl (C : Type u₁) [category C] (D : Type u₁) [category D] {X : C} {Y : C} {f : sum.inl X ⟶ sum.inl Y} : functor.map (swap C D) f = f := rfl @[simp] theorem swap_map_inr (C : Type u₁) [category C] (D : Type u₁) [category D] {X : D} {Y : D} {f : sum.inr X ⟶ sum.inr Y} : functor.map (swap C D) f = f := rfl namespace swap /-- `swap` gives an equivalence between `C ⊕ D` and `D ⊕ C`. -/ def equivalence (C : Type u₁) [category C] (D : Type u₁) [category D] : C ⊕ D ≌ D ⊕ C := equivalence.mk (swap C D) (swap D C) (nat_iso.of_components (fun (X : C ⊕ D) => eq_to_iso sorry) sorry) (nat_iso.of_components (fun (X : D ⊕ C) => eq_to_iso sorry) sorry) protected instance is_equivalence (C : Type u₁) [category C] (D : Type u₁) [category D] : is_equivalence (swap C D) := is_equivalence.of_equivalence (equivalence C D) /-- The double swap on `C ⊕ D` is naturally isomorphic to the identity functor. -/ def symmetry (C : Type u₁) [category C] (D : Type u₁) [category D] : swap C D ⋙ swap D C ≅ 𝟭 := iso.symm (equivalence.unit_iso (equivalence C D)) end swap end sum namespace functor /-- The sum of two functors. -/ def sum {A : Type u₁} [category A] {B : Type u₁} [category B] {C : Type u₁} [category C] {D : Type u₁} [category D] (F : A ⥤ B) (G : C ⥤ D) : A ⊕ C ⥤ B ⊕ D := mk (fun (X : A ⊕ C) => sorry) fun (X Y : A ⊕ C) (f : X ⟶ Y) => sorry @[simp] theorem sum_obj_inl {A : Type u₁} [category A] {B : Type u₁} [category B] {C : Type u₁} [category C] {D : Type u₁} [category D] (F : A ⥤ B) (G : C ⥤ D) (a : A) : obj (sum F G) (sum.inl a) = sum.inl (obj F a) := rfl @[simp] theorem sum_obj_inr {A : Type u₁} [category A] {B : Type u₁} [category B] {C : Type u₁} [category C] {D : Type u₁} [category D] (F : A ⥤ B) (G : C ⥤ D) (c : C) : obj (sum F G) (sum.inr c) = sum.inr (obj G c) := rfl @[simp] theorem sum_map_inl {A : Type u₁} [category A] {B : Type u₁} [category B] {C : Type u₁} [category C] {D : Type u₁} [category D] (F : A ⥤ B) (G : C ⥤ D) {a : A} {a' : A} (f : sum.inl a ⟶ sum.inl a') : map (sum F G) f = map F f := rfl @[simp] theorem sum_map_inr {A : Type u₁} [category A] {B : Type u₁} [category B] {C : Type u₁} [category C] {D : Type u₁} [category D] (F : A ⥤ B) (G : C ⥤ D) {c : C} {c' : C} (f : sum.inr c ⟶ sum.inr c') : map (sum F G) f = map G f := rfl end functor namespace nat_trans /-- The sum of two natural transformations. -/ def sum {A : Type u₁} [category A] {B : Type u₁} [category B] {C : Type u₁} [category C] {D : Type u₁} [category D] {F : A ⥤ B} {G : A ⥤ B} {H : C ⥤ D} {I : C ⥤ D} (α : F ⟶ G) (β : H ⟶ I) : functor.sum F H ⟶ functor.sum G I := mk fun (X : A ⊕ C) => sorry @[simp] theorem sum_app_inl {A : Type u₁} [category A] {B : Type u₁} [category B] {C : Type u₁} [category C] {D : Type u₁} [category D] {F : A ⥤ B} {G : A ⥤ B} {H : C ⥤ D} {I : C ⥤ D} (α : F ⟶ G) (β : H ⟶ I) (a : A) : app (sum α β) (sum.inl a) = app α a := rfl @[simp] theorem sum_app_inr {A : Type u₁} [category A] {B : Type u₁} [category B] {C : Type u₁} [category C] {D : Type u₁} [category D] {F : A ⥤ B} {G : A ⥤ B} {H : C ⥤ D} {I : C ⥤ D} (α : F ⟶ G) (β : H ⟶ I) (c : C) : app (sum α β) (sum.inr c) = app β c := rfl
212e4053677a87d3475861d99c6cc3b1dc6107d3
b00eb947a9c4141624aa8919e94ce6dcd249ed70
/stage0/src/Init/Data/UInt.lean
bcbbd46633bbfd6f12626d6e3cc2899eecb5fbcc
[ "Apache-2.0" ]
permissive
gebner/lean4-old
a4129a041af2d4d12afb3a8d4deedabde727719b
ee51cdfaf63ee313c914d83264f91f414a0e3b6e
refs/heads/master
1,683,628,606,745
1,622,651,300,000
1,622,654,405,000
142,608,821
1
0
null
null
null
null
UTF-8
Lean
false
false
14,736
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 "((size_t)#1)"] def UInt64.toUSize (a : UInt64) : 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
670439c54f3086c0398ca1d032b2b5d5686f35d3
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/stage0/src/Lean/Server/FileWorker/WidgetRequests.lean
df9de092dcbaf84b26447fb41631ec8896aac3fd
[ "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
4,838
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Wojciech Nawrocki -/ import Lean.Widget.Basic import Lean.Widget.InteractiveCode import Lean.Widget.InteractiveGoal import Lean.Widget.InteractiveDiagnostic import Lean.Server.Rpc.RequestHandling import Lean.Server.FileWorker.RequestHandling /-! Registers all widget-related RPC procedures. -/ namespace Lean.Widget open Server structure MsgToInteractive where msg : WithRpcRef MessageData indent : Nat deriving Inhabited, RpcEncodable builtin_initialize registerBuiltinRpcProcedure `Lean.Widget.InteractiveDiagnostics.msgToInteractive MsgToInteractive (TaggedText MsgEmbed) fun ⟨⟨m⟩, i⟩ => RequestM.asTask do msgToInteractive m i (hasWidgets := true) /-- The information that the infoview uses to render a popup for when the user hovers over an expression. -/ structure InfoPopup where type : Option CodeWithInfos /-- Show the term with the implicit arguments. -/ exprExplicit : Option CodeWithInfos /-- Docstring. In markdown. -/ doc : Option String deriving Inhabited, RpcEncodable /-- Given elaborator info for a particular subexpression. Produce the `InfoPopup`. The intended usage of this is for the infoview to pass the `InfoWithCtx` which was stored for a particular `SubexprInfo` tag in a `TaggedText` generated with `ppExprTagged`. -/ def makePopup : WithRpcRef InfoWithCtx → RequestM (RequestTask InfoPopup) | ⟨i⟩ => RequestM.asTask do i.ctx.runMetaM i.info.lctx do let type? ← match (← i.info.type?) with | some type => some <$> ppExprTagged type | none => pure none let exprExplicit? ← match i.info with | Elab.Info.ofTermInfo ti => let ti ← ppExprTagged ti.expr (explicit := true) -- remove top-level expression highlight pure <| some <| match ti with | .tag _ tt => tt | tt => tt | Elab.Info.ofFieldInfo fi => pure <| some <| TaggedText.text fi.fieldName.toString | _ => pure none return { type := type? exprExplicit := exprExplicit? doc := ← i.info.docString? : InfoPopup } builtin_initialize registerBuiltinRpcProcedure `Lean.Widget.InteractiveDiagnostics.infoToInteractive (WithRpcRef InfoWithCtx) InfoPopup makePopup builtin_initialize registerBuiltinRpcProcedure `Lean.Widget.getInteractiveGoals Lsp.PlainGoalParams (Option InteractiveGoals) FileWorker.getInteractiveGoals builtin_initialize registerBuiltinRpcProcedure `Lean.Widget.getInteractiveTermGoal Lsp.PlainTermGoalParams (Option InteractiveTermGoal) FileWorker.getInteractiveTermGoal structure GetInteractiveDiagnosticsParams where /-- Return diagnostics for these lines only if present, otherwise return all diagnostics. -/ lineRange? : Option Lsp.LineRange deriving Inhabited, FromJson, ToJson open RequestM in def getInteractiveDiagnostics (params : GetInteractiveDiagnosticsParams) : RequestM (RequestTask (Array InteractiveDiagnostic)) := do let doc ← readDoc let rangeEnd := params.lineRange?.map fun range => doc.meta.text.lspPosToUtf8Pos ⟨range.«end», 0⟩ let t ← doc.cmdSnaps.waitAll fun snap => rangeEnd.all (snap.beginPos < ·) pure <| t.map fun (snaps, _) => let diags? := snaps.getLast?.map fun snap => snap.interactiveDiags.toArray.filter fun diag => params.lineRange?.all fun ⟨s, e⟩ => -- does [s,e) intersect [diag.fullRange.start.line,diag.fullRange.end.line)? s ≤ diag.fullRange.start.line ∧ diag.fullRange.start.line < e ∨ diag.fullRange.start.line ≤ s ∧ s < diag.fullRange.end.line pure <| diags?.getD #[] builtin_initialize registerBuiltinRpcProcedure `Lean.Widget.getInteractiveDiagnostics GetInteractiveDiagnosticsParams (Array InteractiveDiagnostic) getInteractiveDiagnostics structure GetGoToLocationParams where kind : GoToKind info : WithRpcRef InfoWithCtx deriving RpcEncodable builtin_initialize registerBuiltinRpcProcedure `Lean.Widget.getGoToLocation GetGoToLocationParams (Array Lsp.LocationLink) fun ⟨kind, ⟨i⟩⟩ => RequestM.asTask do let rc ← read let ls ← FileWorker.locationLinksOfInfo kind i.ctx i.info if !ls.isEmpty then return ls -- TODO(WN): unify handling of delab'd (infoview) and elab'd (editor) applications let .ofTermInfo ti := i.info | return #[] let .app _ _ := ti.expr | return #[] let some nm := ti.expr.getAppFn.constName? | return #[] i.ctx.runMetaM ti.lctx <| locationLinksFromDecl rc.srcSearchPath rc.doc.meta.uri nm none end Lean.Widget
7e0ed2b07f45dc6658dbea481cd26c3b561b5b54
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/algebra/opposites.lean
17032127e2c423e0b44ab9122bd995d4ae5d193f
[ "Apache-2.0" ]
permissive
gebner/mathlib
eab0150cc4f79ec45d2016a8c21750244a2e7ff0
cc6a6edc397c55118df62831e23bfbd6e6c6b4ab
refs/heads/master
1,625,574,853,976
1,586,712,827,000
1,586,712,827,000
99,101,412
1
0
Apache-2.0
1,586,716,389,000
1,501,667,958,000
Lean
UTF-8
Lean
false
false
5,752
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau Opposites. -/ import data.opposite namespace opposite universes u variables (α : Type u) instance [has_add α] : has_add (opposite α) := { add := λ x y, op (unop x + unop y) } instance [add_semigroup α] : add_semigroup (opposite α) := { add_assoc := λ x y z, unop_inj $ add_assoc (unop x) (unop y) (unop z), .. opposite.has_add α } instance [add_left_cancel_semigroup α] : add_left_cancel_semigroup (opposite α) := { add_left_cancel := λ x y z H, unop_inj $ add_left_cancel $ op_inj H, .. opposite.add_semigroup α } instance [add_right_cancel_semigroup α] : add_right_cancel_semigroup (opposite α) := { add_right_cancel := λ x y z H, unop_inj $ add_right_cancel $ op_inj H, .. opposite.add_semigroup α } instance [add_comm_semigroup α] : add_comm_semigroup (opposite α) := { add_comm := λ x y, unop_inj $ add_comm (unop x) (unop y), .. opposite.add_semigroup α } instance [has_zero α] : has_zero (opposite α) := { zero := op 0 } instance [add_monoid α] : add_monoid (opposite α) := { zero_add := λ x, unop_inj $ zero_add $ unop x, add_zero := λ x, unop_inj $ add_zero $ unop x, .. opposite.add_semigroup α, .. opposite.has_zero α } instance [add_comm_monoid α] : add_comm_monoid (opposite α) := { .. opposite.add_monoid α, .. opposite.add_comm_semigroup α } instance [has_neg α] : has_neg (opposite α) := { neg := λ x, op $ -(unop x) } instance [add_group α] : add_group (opposite α) := { add_left_neg := λ x, unop_inj $ add_left_neg $ unop x, .. opposite.add_monoid α, .. opposite.has_neg α } instance [add_comm_group α] : add_comm_group (opposite α) := { .. opposite.add_group α, .. opposite.add_comm_monoid α } instance [has_mul α] : has_mul (opposite α) := { mul := λ x y, op (unop y * unop x) } instance [semigroup α] : semigroup (opposite α) := { mul_assoc := λ x y z, unop_inj $ eq.symm $ mul_assoc (unop z) (unop y) (unop x), .. opposite.has_mul α } instance [right_cancel_semigroup α] : left_cancel_semigroup (opposite α) := { mul_left_cancel := λ x y z H, unop_inj $ mul_right_cancel $ op_inj H, .. opposite.semigroup α } instance [left_cancel_semigroup α] : right_cancel_semigroup (opposite α) := { mul_right_cancel := λ x y z H, unop_inj $ mul_left_cancel $ op_inj H, .. opposite.semigroup α } instance [comm_semigroup α] : comm_semigroup (opposite α) := { mul_comm := λ x y, unop_inj $ mul_comm (unop y) (unop x), .. opposite.semigroup α } instance [has_one α] : has_one (opposite α) := { one := op 1 } instance [monoid α] : monoid (opposite α) := { one_mul := λ x, unop_inj $ mul_one $ unop x, mul_one := λ x, unop_inj $ one_mul $ unop x, .. opposite.semigroup α, .. opposite.has_one α } instance [comm_monoid α] : comm_monoid (opposite α) := { .. opposite.monoid α, .. opposite.comm_semigroup α } instance [has_inv α] : has_inv (opposite α) := { inv := λ x, op $ (unop x)⁻¹ } instance [group α] : group (opposite α) := { mul_left_inv := λ x, unop_inj $ mul_inv_self $ unop x, .. opposite.monoid α, .. opposite.has_inv α } instance [comm_group α] : comm_group (opposite α) := { .. opposite.group α, .. opposite.comm_monoid α } instance [distrib α] : distrib (opposite α) := { left_distrib := λ x y z, unop_inj $ add_mul (unop y) (unop z) (unop x), right_distrib := λ x y z, unop_inj $ mul_add (unop z) (unop x) (unop y), .. opposite.has_add α, .. opposite.has_mul α } instance [semiring α] : semiring (opposite α) := { zero_mul := λ x, unop_inj $ mul_zero $ unop x, mul_zero := λ x, unop_inj $ zero_mul $ unop x, .. opposite.add_comm_monoid α, .. opposite.monoid α, .. opposite.distrib α } instance [ring α] : ring (opposite α) := { .. opposite.add_comm_group α, .. opposite.monoid α, .. opposite.semiring α } instance [comm_ring α] : comm_ring (opposite α) := { .. opposite.ring α, .. opposite.comm_semigroup α } instance [zero_ne_one_class α] : zero_ne_one_class (opposite α) := { zero_ne_one := λ h, zero_ne_one $ op_inj h, .. opposite.has_zero α, .. opposite.has_one α } instance [integral_domain α] : integral_domain (opposite α) := { eq_zero_or_eq_zero_of_mul_eq_zero := λ x y (H : op _ = op (0:α)), or.cases_on (eq_zero_or_eq_zero_of_mul_eq_zero $ op_inj H) (λ hy, or.inr $ unop_inj $ hy) (λ hx, or.inl $ unop_inj $ hx), .. opposite.comm_ring α, .. opposite.zero_ne_one_class α } instance [field α] : field (opposite α) := { mul_inv_cancel := λ x hx, unop_inj $ inv_mul_cancel $ λ hx', hx $ unop_inj hx', inv_zero := unop_inj inv_zero, .. opposite.comm_ring α, .. opposite.zero_ne_one_class α, .. opposite.has_inv α } @[simp] lemma op_zero [has_zero α] : op (0 : α) = 0 := rfl @[simp] lemma unop_zero [has_zero α] : unop (0 : αᵒᵖ) = 0 := rfl @[simp] lemma op_one [has_one α] : op (1 : α) = 1 := rfl @[simp] lemma unop_one [has_one α] : unop (1 : αᵒᵖ) = 1 := rfl variable {α} @[simp] lemma op_add [has_add α] (x y : α) : op (x + y) = op x + op y := rfl @[simp] lemma unop_add [has_add α] (x y : αᵒᵖ) : unop (x + y) = unop x + unop y := rfl @[simp] lemma op_neg [has_neg α] (x : α) : op (-x) = -op x := rfl @[simp] lemma unop_neg [has_neg α] (x : αᵒᵖ) : unop (-x) = -unop x := rfl @[simp] lemma op_mul [has_mul α] (x y : α) : op (x * y) = op y * op x := rfl @[simp] lemma unop_mul [has_mul α] (x y : αᵒᵖ) : unop (x * y) = unop y * unop x := rfl @[simp] lemma op_inv [has_inv α] (x : α) : op (x⁻¹) = (op x)⁻¹ := rfl @[simp] lemma unop_inv [has_inv α] (x : αᵒᵖ) : unop (x⁻¹) = (unop x)⁻¹ := rfl end opposite
0f7e216b870d3682582eb6bce08ad6c1054ef604
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/category_theory/discrete_category.lean
dc7a2173406831117e9feaa81c07874b72b8b114
[ "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
6,199
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, Floris van Doorn -/ import category_theory.eq_to_hom /-! # Discrete categories We define `discrete α := α` for any type `α`, and use this type alias to provide a `small_category` instance whose only morphisms are the identities. There is an annoying technical difficulty that it has turned out to be inconvenient to allow categories with morphisms living in `Prop`, so instead of defining `X ⟶ Y` in `discrete α` as `X = Y`, one might define it as `plift (X = Y)`. In fact, to allow `discrete α` to be a `small_category` (i.e. with morphisms in the same universe as the objects), we actually define the hom type `X ⟶ Y` as `ulift (plift (X = Y))`. `discrete.functor` promotes a function `f : I → C` (for any category `C`) to a functor `discrete.functor f : discrete I ⥤ C`. Similarly, `discrete.nat_trans` and `discrete.nat_iso` promote `I`-indexed families of morphisms, or `I`-indexed families of isomorphisms to natural transformations or natural isomorphism. We show equivalences of types are the same as (categorical) equivalences of the corresponding discrete categories. -/ namespace category_theory universes v₁ v₂ u₁ u₂ -- morphism levels before object levels. See note [category_theory universes]. /-- A type synonym for promoting any type to a category, with the only morphisms being equalities. -/ def discrete (α : Type u₁) := α /-- The "discrete" category on a type, whose morphisms are equalities. Because we do not allow morphisms in `Prop` (only in `Type`), somewhat annoyingly we have to define `X ⟶ Y` as `ulift (plift (X = Y))`. See https://stacks.math.columbia.edu/tag/001A -/ instance discrete_category (α : Type u₁) : small_category (discrete α) := { hom := λ X Y, ulift (plift (X = Y)), id := λ X, ulift.up (plift.up rfl), comp := λ X Y Z g f, by { rcases f with ⟨⟨rfl⟩⟩, exact g } } namespace discrete variables {α : Type u₁} instance [inhabited α] : inhabited (discrete α) := by { dsimp [discrete], apply_instance } instance [subsingleton α] : subsingleton (discrete α) := by { dsimp [discrete], apply_instance } /-- Extract the equation from a morphism in a discrete category. -/ lemma eq_of_hom {X Y : discrete α} (i : X ⟶ Y) : X = Y := i.down.down @[simp] lemma id_def (X : discrete α) : ulift.up (plift.up (eq.refl X)) = 𝟙 X := rfl variables {C : Type u₂} [category.{v₂} C] instance {I : Type u₁} {i j : discrete I} (f : i ⟶ j) : is_iso f := ⟨⟨eq_to_hom (eq_of_hom f).symm, by tidy⟩⟩ /-- Any function `I → C` gives a functor `discrete I ⥤ C`. -/ def functor {I : Type u₁} (F : I → C) : discrete I ⥤ C := { obj := F, map := λ X Y f, begin cases f, cases f, cases f, exact 𝟙 (F X) end } @[simp] lemma functor_obj {I : Type u₁} (F : I → C) (i : I) : (discrete.functor F).obj i = F i := rfl lemma functor_map {I : Type u₁} (F : I → C) {i : discrete I} (f : i ⟶ i) : (discrete.functor F).map f = 𝟙 (F i) := by { cases f, cases f, cases f, refl } /-- For functors out of a discrete category, a natural transformation is just a collection of maps, as the naturality squares are trivial. -/ def nat_trans {I : Type u₁} {F G : discrete I ⥤ C} (f : Π i : discrete I, F.obj i ⟶ G.obj i) : F ⟶ G := { app := f } @[simp] lemma nat_trans_app {I : Type u₁} {F G : discrete I ⥤ C} (f : Π i : discrete I, F.obj i ⟶ G.obj i) (i) : (discrete.nat_trans f).app i = f i := rfl /-- For functors out of a discrete category, a natural isomorphism is just a collection of isomorphisms, as the naturality squares are trivial. -/ def nat_iso {I : Type u₁} {F G : discrete I ⥤ C} (f : Π i : discrete I, F.obj i ≅ G.obj i) : F ≅ G := nat_iso.of_components f (by tidy) @[simp] lemma nat_iso_hom_app {I : Type u₁} {F G : discrete I ⥤ C} (f : Π i : discrete I, F.obj i ≅ G.obj i) (i : I) : (discrete.nat_iso f).hom.app i = (f i).hom := rfl @[simp] lemma nat_iso_inv_app {I : Type u₁} {F G : discrete I ⥤ C} (f : Π i : discrete I, F.obj i ≅ G.obj i) (i : I) : (discrete.nat_iso f).inv.app i = (f i).inv := rfl @[simp] lemma nat_iso_app {I : Type u₁} {F G : discrete I ⥤ C} (f : Π i : discrete I, F.obj i ≅ G.obj i) (i : I) : (discrete.nat_iso f).app i = f i := by tidy /-- Every functor `F` from a discrete category is naturally isomorphic (actually, equal) to `discrete.functor (F.obj)`. -/ def nat_iso_functor {I : Type u₁} {F : discrete I ⥤ C} : F ≅ discrete.functor (F.obj) := nat_iso $ λ i, iso.refl _ /-- We can promote a type-level `equiv` to an equivalence between the corresponding `discrete` categories. -/ @[simps] def equivalence {I J : Type u₁} (e : I ≃ J) : discrete I ≌ discrete J := { functor := discrete.functor (e : I → J), inverse := discrete.functor (e.symm : J → I), unit_iso := discrete.nat_iso (λ i, eq_to_iso (by simp)), counit_iso := discrete.nat_iso (λ j, eq_to_iso (by simp)), } /-- We can convert an equivalence of `discrete` categories to a type-level `equiv`. -/ @[simps] def equiv_of_equivalence {α β : Type u₁} (h : discrete α ≌ discrete β) : α ≃ β := { to_fun := h.functor.obj, inv_fun := h.inverse.obj, left_inv := λ a, eq_of_hom (h.unit_iso.app a).2, right_inv := λ a, eq_of_hom (h.counit_iso.app a).1 } end discrete namespace discrete variables {J : Type v₁} open opposite /-- A discrete category is equivalent to its opposite category. -/ protected def opposite (α : Type u₁) : (discrete α)ᵒᵖ ≌ discrete α := let F : discrete α ⥤ (discrete α)ᵒᵖ := discrete.functor (λ x, op x) in begin refine equivalence.mk (functor.left_op F) F _ (discrete.nat_iso $ λ X, by simp [F]), refine nat_iso.of_components (λ X, by simp [F]) _, tidy end variables {C : Type u₂} [category.{v₂} C] @[simp] lemma functor_map_id (F : discrete J ⥤ C) {j : discrete J} (f : j ⟶ j) : F.map f = 𝟙 (F.obj j) := begin have h : f = 𝟙 j, { cases f, cases f, ext, }, rw h, simp, end end discrete end category_theory
0538c9c7c03c2994beef94cc8cd5d373f2260a40
2385ce0e3b60d8dbea33dd439902a2070cca7a24
/tests/lean/guard_names.lean
29c8c9b9a01f13e07a328569c7deba40b6040008
[ "Apache-2.0" ]
permissive
TehMillhouse/lean
68d6fdd2fb11a6c65bc28dec308d70f04dad38b4
6bbf2fbd8912617e5a973575bab8c383c9c268a1
refs/heads/master
1,620,830,893,339
1,515,592,479,000
1,515,592,997,000
116,964,828
0
0
null
1,515,592,734,000
1,515,592,734,000
null
UTF-8
Lean
false
false
297
lean
inductive tree (α : Type) | leaf : tree | node (left : tree) (val : α) (right : tree) : tree constant foo {α : Type} : tree α → tree α example {α : Type} (a b : tree α) : foo a = a := begin with_cases { induction a }, { sorry }, case : l v r ih_l ih_r { trace_state, sorry }, end
aa76bcbf46b247f2af658b8dbf922aedb3e3fcb7
4727251e0cd73359b15b664c3170e5d754078599
/src/data/finsupp/fin.lean
e8ab345a5d6c90988b3119ce8c9184684ac96260
[ "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
2,828
lean
/- Copyright (c) 2021 Ivan Sadofschi Costa. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Ivan Sadofschi Costa -/ import data.fin.tuple import data.finsupp.basic /-! # `cons` and `tail` for maps `fin n →₀ M` We interpret maps `fin n →₀ M` as `n`-tuples of elements of `M`, We define the following operations: * `finsupp.tail` : the tail of a map `fin (n + 1) →₀ M`, i.e., its last `n` entries; * `finsupp.cons` : adding an element at the beginning of an `n`-tuple, to get an `n + 1`-tuple; In this context, we prove some usual properties of `tail` and `cons`, analogous to those of `data.fin.tuple.basic`. -/ noncomputable theory namespace finsupp variables {n : ℕ} (i : fin n) {M : Type*} [has_zero M] (y : M) (t : fin (n + 1) →₀ M) (s : fin n →₀ M) /-- `tail` for maps `fin (n + 1) →₀ M`. See `fin.tail` for more details. -/ def tail (s : fin (n + 1) →₀ M) : fin n →₀ M := finsupp.equiv_fun_on_fintype.inv_fun (fin.tail s.to_fun) /-- `cons` for maps `fin n →₀ M`. See `fin.cons` for more details. -/ def cons (y : M) (s : fin n →₀ M) : fin (n + 1) →₀ M := finsupp.equiv_fun_on_fintype.inv_fun (fin.cons y s.to_fun) lemma tail_apply : tail t i = t i.succ := begin simp only [tail, equiv_fun_on_fintype_symm_apply_to_fun, equiv.inv_fun_as_coe], refl, end @[simp] lemma cons_zero : cons y s 0 = y := by simp [cons, finsupp.equiv_fun_on_fintype] @[simp] lemma cons_succ : cons y s i.succ = s i := begin simp only [finsupp.cons, fin.cons, finsupp.equiv_fun_on_fintype, fin.cases_succ, finsupp.coe_mk], refl, end @[simp] lemma tail_cons : tail (cons y s) = s := begin simp only [finsupp.cons, fin.cons, finsupp.tail, fin.tail], ext, simp only [equiv_fun_on_fintype_symm_apply_to_fun, equiv.inv_fun_as_coe, finsupp.coe_mk, fin.cases_succ, equiv_fun_on_fintype], refl, end @[simp] lemma cons_tail : cons (t 0) (tail t) = t := begin ext, by_cases c_a : a = 0, { rw [c_a, cons_zero] }, { rw [←fin.succ_pred a c_a, cons_succ, ←tail_apply] }, end @[simp] lemma cons_zero_zero : cons 0 (0 : fin n →₀ M) = 0 := begin ext, by_cases c : a = 0, { simp [c] }, { rw [←fin.succ_pred a c, cons_succ], simp }, end variables {s} {y} lemma cons_ne_zero_of_left (h : y ≠ 0) : cons y s ≠ 0 := begin contrapose! h with c, rw [←cons_zero y s, c, finsupp.coe_zero, pi.zero_apply], end lemma cons_ne_zero_of_right (h : s ≠ 0) : cons y s ≠ 0 := begin contrapose! h with c, ext, simp [ ← cons_succ a y s, c], end lemma cons_ne_zero_iff : cons y s ≠ 0 ↔ y ≠ 0 ∨ s ≠ 0 := begin refine ⟨λ h, _, λ h, h.cases_on cons_ne_zero_of_left cons_ne_zero_of_right⟩, refine imp_iff_not_or.1 (λ h' c, h _), rw [h', c, finsupp.cons_zero_zero], end end finsupp
c81f94af2d94fcda294fa635f6401a72db4d5b4c
626e312b5c1cb2d88fca108f5933076012633192
/src/analysis/calculus/times_cont_diff.lean
117676c10a0288069ccbc07f4d579c20c898506f
[ "Apache-2.0" ]
permissive
Bioye97/mathlib
9db2f9ee54418d29dd06996279ba9dc874fd6beb
782a20a27ee83b523f801ff34efb1a9557085019
refs/heads/master
1,690,305,956,488
1,631,067,774,000
1,631,067,774,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
142,338
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import analysis.calculus.mean_value import analysis.normed_space.multilinear /-! # Higher differentiability A function is `C^1` on a domain if it is differentiable there, and its derivative is continuous. By induction, it is `C^n` if it is `C^{n-1}` and its (n-1)-th derivative is `C^1` there or, equivalently, if it is `C^1` and its derivative is `C^{n-1}`. Finally, it is `C^∞` if it is `C^n` for all n. We formalize these notions by defining iteratively the `n+1`-th derivative of a function as the derivative of the `n`-th derivative. It is called `iterated_fderiv 𝕜 n f x` where `𝕜` is the field, `n` is the number of iterations, `f` is the function and `x` is the point, and it is given as an `n`-multilinear map. We also define a version `iterated_fderiv_within` relative to a domain, as well as predicates `times_cont_diff_within_at`, `times_cont_diff_at`, `times_cont_diff_on` and `times_cont_diff` saying that the function is `C^n` within a set at a point, at a point, on a set and on the whole space respectively. To avoid the issue of choice when choosing a derivative in sets where the derivative is not necessarily unique, `times_cont_diff_on` is not defined directly in terms of the regularity of the specific choice `iterated_fderiv_within 𝕜 n f s` inside `s`, but in terms of the existence of a nice sequence of derivatives, expressed with a predicate `has_ftaylor_series_up_to_on`. We prove basic properties of these notions. ## Main definitions and results Let `f : E → F` be a map between normed vector spaces over a nondiscrete normed field `𝕜`. * `has_ftaylor_series_up_to n f p`: expresses that the formal multilinear series `p` is a sequence of iterated derivatives of `f`, up to the `n`-th term (where `n` is a natural number or `∞`). * `has_ftaylor_series_up_to_on n f p s`: same thing, but inside a set `s`. The notion of derivative is now taken inside `s`. In particular, derivatives don't have to be unique. * `times_cont_diff 𝕜 n f`: expresses that `f` is `C^n`, i.e., it admits a Taylor series up to rank `n`. * `times_cont_diff_on 𝕜 n f s`: expresses that `f` is `C^n` in `s`. * `times_cont_diff_at 𝕜 n f x`: expresses that `f` is `C^n` around `x`. * `times_cont_diff_within_at 𝕜 n f s x`: expresses that `f` is `C^n` around `x` within the set `s`. * `iterated_fderiv_within 𝕜 n f s x` is an `n`-th derivative of `f` over the field `𝕜` on the set `s` at the point `x`. It is a continuous multilinear map from `E^n` to `F`, defined as a derivative within `s` of `iterated_fderiv_within 𝕜 (n-1) f s` if one exists, and `0` otherwise. * `iterated_fderiv 𝕜 n f x` is the `n`-th derivative of `f` over the field `𝕜` at the point `x`. It is a continuous multilinear map from `E^n` to `F`, defined as a derivative of `iterated_fderiv 𝕜 (n-1) f` if one exists, and `0` otherwise. In sets of unique differentiability, `times_cont_diff_on 𝕜 n f s` can be expressed in terms of the properties of `iterated_fderiv_within 𝕜 m f s` for `m ≤ n`. In the whole space, `times_cont_diff 𝕜 n f` can be expressed in terms of the properties of `iterated_fderiv 𝕜 m f` for `m ≤ n`. We also prove that the usual operations (addition, multiplication, difference, composition, and so on) preserve `C^n` functions. ## Implementation notes The definitions in this file are designed to work on any field `𝕜`. They are sometimes slightly more complicated than the naive definitions one would guess from the intuition over the real or complex numbers, but they are designed to circumvent the lack of gluing properties and partitions of unity in general. In the usual situations, they coincide with the usual definitions. ### Definition of `C^n` functions in domains One could define `C^n` functions in a domain `s` by fixing an arbitrary choice of derivatives (this is what we do with `iterated_fderiv_within`) and requiring that all these derivatives up to `n` are continuous. If the derivative is not unique, this could lead to strange behavior like two `C^n` functions `f` and `g` on `s` whose sum is not `C^n`. A better definition is thus to say that a function is `C^n` inside `s` if it admits a sequence of derivatives up to `n` inside `s`. This definition still has the problem that a function which is locally `C^n` would not need to be `C^n`, as different choices of sequences of derivatives around different points might possibly not be glued together to give a globally defined sequence of derivatives. (Note that this issue can not happen over reals, thanks to partition of unity, but the behavior over a general field is not so clear, and we want a definition for general fields). Also, there are locality problems for the order parameter: one could image a function which, for each `n`, has a nice sequence of derivatives up to order `n`, but they do not coincide for varying `n` and can therefore not be glued to give rise to an infinite sequence of derivatives. This would give a function which is `C^n` for all `n`, but not `C^∞`. We solve this issue by putting locality conditions in space and order in our definition of `times_cont_diff_within_at` and `times_cont_diff_on`. The resulting definition is slightly more complicated to work with (in fact not so much), but it gives rise to completely satisfactory theorems. For instance, with this definition, a real function which is `C^m` (but not better) on `(-1/m, 1/m)` for each natural `m` is by definition `C^∞` at `0`. There is another issue with the definition of `times_cont_diff_within_at 𝕜 n f s x`. We can require the existence and good behavior of derivatives up to order `n` on a neighborhood of `x` within `s`. However, this does not imply continuity or differentiability within `s` of the function at `x` when `x` does not belong to `s`. Therefore, we require such existence and good behavior on a neighborhood of `x` within `s ∪ {x}` (which appears as `insert x s` in this file). ### Side of the composition, and universe issues With a naïve direct definition, the `n`-th derivative of a function belongs to the space `E →L[𝕜] (E →L[𝕜] (E ... F)...)))` where there are n iterations of `E →L[𝕜]`. This space may also be seen as the space of continuous multilinear functions on `n` copies of `E` with values in `F`, by uncurrying. This is the point of view that is usually adopted in textbooks, and that we also use. This means that the definition and the first proofs are slightly involved, as one has to keep track of the uncurrying operation. The uncurrying can be done from the left or from the right, amounting to defining the `n+1`-th derivative either as the derivative of the `n`-th derivative, or as the `n`-th derivative of the derivative. For proofs, it would be more convenient to use the latter approach (from the right), as it means to prove things at the `n+1`-th step we only need to understand well enough the derivative in `E →L[𝕜] F` (contrary to the approach from the left, where one would need to know enough on the `n`-th derivative to deduce things on the `n+1`-th derivative). However, the definition from the right leads to a universe polymorphism problem: if we define `iterated_fderiv 𝕜 (n + 1) f x = iterated_fderiv 𝕜 n (fderiv 𝕜 f) x` by induction, we need to generalize over all spaces (as `f` and `fderiv 𝕜 f` don't take values in the same space). It is only possible to generalize over all spaces in some fixed universe in an inductive definition. For `f : E → F`, then `fderiv 𝕜 f` is a map `E → (E →L[𝕜] F)`. Therefore, the definition will only work if `F` and `E →L[𝕜] F` are in the same universe. This issue does not appear with the definition from the left, where one does not need to generalize over all spaces. Therefore, we use the definition from the left. This means some proofs later on become a little bit more complicated: to prove that a function is `C^n`, the most efficient approach is to exhibit a formula for its `n`-th derivative and prove it is continuous (contrary to the inductive approach where one would prove smoothness statements without giving a formula for the derivative). In the end, this approach is still satisfactory as it is good to have formulas for the iterated derivatives in various constructions. One point where we depart from this explicit approach is in the proof of smoothness of a composition: there is a formula for the `n`-th derivative of a composition (Faà di Bruno's formula), but it is very complicated and barely usable, while the inductive proof is very simple. Thus, we give the inductive proof. As explained above, it works by generalizing over the target space, hence it only works well if all spaces belong to the same universe. To get the general version, we lift things to a common universe using a trick. ### Variables management The textbook definitions and proofs use various identifications and abuse of notations, for instance when saying that the natural space in which the derivative lives, i.e., `E →L[𝕜] (E →L[𝕜] ( ... →L[𝕜] F))`, is the same as a space of multilinear maps. When doing things formally, we need to provide explicit maps for these identifications, and chase some diagrams to see everything is compatible with the identifications. In particular, one needs to check that taking the derivative and then doing the identification, or first doing the identification and then taking the derivative, gives the same result. The key point for this is that taking the derivative commutes with continuous linear equivalences. Therefore, we need to implement all our identifications with continuous linear equivs. ## Notations We use the notation `E [×n]→L[𝕜] F` for the space of continuous multilinear maps on `E^n` with values in `F`. This is the space in which the `n`-th derivative of a function from `E` to `F` lives. In this file, we denote `⊤ : with_top ℕ` with `∞`. ## Tags derivative, differentiability, higher derivative, `C^n`, multilinear, Taylor series, formal series -/ noncomputable theory open_locale classical big_operators nnreal local notation `∞` := (⊤ : with_top ℕ) universes u v w local attribute [instance, priority 1001] normed_group.to_add_comm_group normed_space.to_module add_comm_group.to_add_comm_monoid open set fin filter open_locale topological_space variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {F : Type*} [normed_group F] [normed_space 𝕜 F] {G : Type*} [normed_group G] [normed_space 𝕜 G] {s s₁ t u : set E} {f f₁ : E → F} {g : F → G} {x : E} {c : F} {b : E × F → G} /-! ### Functions with a Taylor series on a domain -/ variable {p : E → formal_multilinear_series 𝕜 E F} /-- `has_ftaylor_series_up_to_on n f p s` registers the fact that `p 0 = f` and `p (m+1)` is a derivative of `p m` for `m < n`, and is continuous for `m ≤ n`. This is a predicate analogous to `has_fderiv_within_at` but for higher order derivatives. -/ structure has_ftaylor_series_up_to_on (n : with_top ℕ) (f : E → F) (p : E → formal_multilinear_series 𝕜 E F) (s : set E) : Prop := (zero_eq : ∀ x ∈ s, (p x 0).uncurry0 = f x) (fderiv_within : ∀ (m : ℕ) (hm : (m : with_top ℕ) < n), ∀ x ∈ s, has_fderiv_within_at (λ y, p y m) (p x m.succ).curry_left s x) (cont : ∀ (m : ℕ) (hm : (m : with_top ℕ) ≤ n), continuous_on (λ x, p x m) s) lemma has_ftaylor_series_up_to_on.zero_eq' {n : with_top ℕ} (h : has_ftaylor_series_up_to_on n f p s) {x : E} (hx : x ∈ s) : p x 0 = (continuous_multilinear_curry_fin0 𝕜 E F).symm (f x) := by { rw ← h.zero_eq x hx, symmetry, exact continuous_multilinear_map.uncurry0_curry0 _ } /-- If two functions coincide on a set `s`, then a Taylor series for the first one is as well a Taylor series for the second one. -/ lemma has_ftaylor_series_up_to_on.congr {n : with_top ℕ} (h : has_ftaylor_series_up_to_on n f p s) (h₁ : ∀ x ∈ s, f₁ x = f x) : has_ftaylor_series_up_to_on n f₁ p s := begin refine ⟨λ x hx, _, h.fderiv_within, h.cont⟩, rw h₁ x hx, exact h.zero_eq x hx end lemma has_ftaylor_series_up_to_on.mono {n : with_top ℕ} (h : has_ftaylor_series_up_to_on n f p s) {t : set E} (hst : t ⊆ s) : has_ftaylor_series_up_to_on n f p t := ⟨λ x hx, h.zero_eq x (hst hx), λ m hm x hx, (h.fderiv_within m hm x (hst hx)).mono hst, λ m hm, (h.cont m hm).mono hst⟩ lemma has_ftaylor_series_up_to_on.of_le {m n : with_top ℕ} (h : has_ftaylor_series_up_to_on n f p s) (hmn : m ≤ n) : has_ftaylor_series_up_to_on m f p s := ⟨h.zero_eq, λ k hk x hx, h.fderiv_within k (lt_of_lt_of_le hk hmn) x hx, λ k hk, h.cont k (le_trans hk hmn)⟩ lemma has_ftaylor_series_up_to_on.continuous_on {n : with_top ℕ} (h : has_ftaylor_series_up_to_on n f p s) : continuous_on f s := begin have := (h.cont 0 bot_le).congr (λ x hx, (h.zero_eq' hx).symm), rwa linear_isometry_equiv.comp_continuous_on_iff at this end lemma has_ftaylor_series_up_to_on_zero_iff : has_ftaylor_series_up_to_on 0 f p s ↔ continuous_on f s ∧ (∀ x ∈ s, (p x 0).uncurry0 = f x) := begin refine ⟨λ H, ⟨H.continuous_on, H.zero_eq⟩, λ H, ⟨H.2, λ m hm, false.elim (not_le.2 hm bot_le), _⟩⟩, assume m hm, obtain rfl : m = 0, by exact_mod_cast (hm.antisymm (zero_le _)), have : ∀ x ∈ s, p x 0 = (continuous_multilinear_curry_fin0 𝕜 E F).symm (f x), by { assume x hx, rw ← H.2 x hx, symmetry, exact continuous_multilinear_map.uncurry0_curry0 _ }, rw [continuous_on_congr this, linear_isometry_equiv.comp_continuous_on_iff], exact H.1 end lemma has_ftaylor_series_up_to_on_top_iff : (has_ftaylor_series_up_to_on ∞ f p s) ↔ (∀ (n : ℕ), has_ftaylor_series_up_to_on n f p s) := begin split, { assume H n, exact H.of_le le_top }, { assume H, split, { exact (H 0).zero_eq }, { assume m hm, apply (H m.succ).fderiv_within m (with_top.coe_lt_coe.2 (lt_add_one m)) }, { assume m hm, apply (H m).cont m (le_refl _) } } end /-- If a function has a Taylor series at order at least `1`, then the term of order `1` of this series is a derivative of `f`. -/ lemma has_ftaylor_series_up_to_on.has_fderiv_within_at {n : with_top ℕ} (h : has_ftaylor_series_up_to_on n f p s) (hn : 1 ≤ n) (hx : x ∈ s) : has_fderiv_within_at f (continuous_multilinear_curry_fin1 𝕜 E F (p x 1)) s x := begin have A : ∀ y ∈ s, f y = (continuous_multilinear_curry_fin0 𝕜 E F) (p y 0), { assume y hy, rw ← h.zero_eq y hy, refl }, suffices H : has_fderiv_within_at (λ y, continuous_multilinear_curry_fin0 𝕜 E F (p y 0)) (continuous_multilinear_curry_fin1 𝕜 E F (p x 1)) s x, by exact H.congr A (A x hx), rw linear_isometry_equiv.comp_has_fderiv_within_at_iff', have : ((0 : ℕ) : with_top ℕ) < n := lt_of_lt_of_le (with_top.coe_lt_coe.2 nat.zero_lt_one) hn, convert h.fderiv_within _ this x hx, ext y v, change (p x 1) (snoc 0 y) = (p x 1) (cons y v), unfold_coes, congr' with i, rw unique.eq_default i, refl end lemma has_ftaylor_series_up_to_on.differentiable_on {n : with_top ℕ} (h : has_ftaylor_series_up_to_on n f p s) (hn : 1 ≤ n) : differentiable_on 𝕜 f s := λ x hx, (h.has_fderiv_within_at hn hx).differentiable_within_at /-- If a function has a Taylor series at order at least `1` on a neighborhood of `x`, then the term of order `1` of this series is a derivative of `f` at `x`. -/ lemma has_ftaylor_series_up_to_on.has_fderiv_at {n : with_top ℕ} (h : has_ftaylor_series_up_to_on n f p s) (hn : 1 ≤ n) (hx : s ∈ 𝓝 x) : has_fderiv_at f (continuous_multilinear_curry_fin1 𝕜 E F (p x 1)) x := (h.has_fderiv_within_at hn (mem_of_mem_nhds hx)).has_fderiv_at hx /-- If a function has a Taylor series at order at least `1` on a neighborhood of `x`, then in a neighborhood of `x`, the term of order `1` of this series is a derivative of `f`. -/ lemma has_ftaylor_series_up_to_on.eventually_has_fderiv_at {n : with_top ℕ} (h : has_ftaylor_series_up_to_on n f p s) (hn : 1 ≤ n) (hx : s ∈ 𝓝 x) : ∀ᶠ y in 𝓝 x, has_fderiv_at f (continuous_multilinear_curry_fin1 𝕜 E F (p y 1)) y := (eventually_eventually_nhds.2 hx).mono $ λ y hy, h.has_fderiv_at hn hy /-- If a function has a Taylor series at order at least `1` on a neighborhood of `x`, then it is differentiable at `x`. -/ lemma has_ftaylor_series_up_to_on.differentiable_at {n : with_top ℕ} (h : has_ftaylor_series_up_to_on n f p s) (hn : 1 ≤ n) (hx : s ∈ 𝓝 x) : differentiable_at 𝕜 f x := (h.has_fderiv_at hn hx).differentiable_at /-- `p` is a Taylor series of `f` up to `n+1` if and only if `p` is a Taylor series up to `n`, and `p (n + 1)` is a derivative of `p n`. -/ theorem has_ftaylor_series_up_to_on_succ_iff_left {n : ℕ} : has_ftaylor_series_up_to_on (n + 1) f p s ↔ has_ftaylor_series_up_to_on n f p s ∧ (∀ x ∈ s, has_fderiv_within_at (λ y, p y n) (p x n.succ).curry_left s x) ∧ continuous_on (λ x, p x (n + 1)) s := begin split, { assume h, exact ⟨h.of_le (with_top.coe_le_coe.2 (nat.le_succ n)), h.fderiv_within _ (with_top.coe_lt_coe.2 (lt_add_one n)), h.cont (n + 1) (le_refl _)⟩ }, { assume h, split, { exact h.1.zero_eq }, { assume m hm, by_cases h' : m < n, { exact h.1.fderiv_within m (with_top.coe_lt_coe.2 h') }, { have : m = n := nat.eq_of_lt_succ_of_not_lt (with_top.coe_lt_coe.1 hm) h', rw this, exact h.2.1 } }, { assume m hm, by_cases h' : m ≤ n, { apply h.1.cont m (with_top.coe_le_coe.2 h') }, { have : m = (n + 1) := le_antisymm (with_top.coe_le_coe.1 hm) (not_le.1 h'), rw this, exact h.2.2 } } } end /-- `p` is a Taylor series of `f` up to `n+1` if and only if `p.shift` is a Taylor series up to `n` for `p 1`, which is a derivative of `f`. -/ theorem has_ftaylor_series_up_to_on_succ_iff_right {n : ℕ} : has_ftaylor_series_up_to_on ((n + 1) : ℕ) f p s ↔ (∀ x ∈ s, (p x 0).uncurry0 = f x) ∧ (∀ x ∈ s, has_fderiv_within_at (λ y, p y 0) (p x 1).curry_left s x) ∧ has_ftaylor_series_up_to_on n (λ x, continuous_multilinear_curry_fin1 𝕜 E F (p x 1)) (λ x, (p x).shift) s := begin split, { assume H, refine ⟨H.zero_eq, H.fderiv_within 0 (with_top.coe_lt_coe.2 (nat.succ_pos n)), _⟩, split, { assume x hx, refl }, { assume m (hm : (m : with_top ℕ) < n) x (hx : x ∈ s), have A : (m.succ : with_top ℕ) < n.succ, by { rw with_top.coe_lt_coe at ⊢ hm, exact nat.lt_succ_iff.mpr hm }, change has_fderiv_within_at ((continuous_multilinear_curry_right_equiv' 𝕜 m E F).symm ∘ (λ (y : E), p y m.succ)) (p x m.succ.succ).curry_right.curry_left s x, rw linear_isometry_equiv.comp_has_fderiv_within_at_iff', convert H.fderiv_within _ A x hx, ext y v, change (p x m.succ.succ) (snoc (cons y (init v)) (v (last _))) = (p x (nat.succ (nat.succ m))) (cons y v), rw [← cons_snoc_eq_snoc_cons, snoc_init_self] }, { assume m (hm : (m : with_top ℕ) ≤ n), have A : (m.succ : with_top ℕ) ≤ n.succ, by { rw with_top.coe_le_coe at ⊢ hm, exact nat.pred_le_iff.mp hm }, change continuous_on ((continuous_multilinear_curry_right_equiv' 𝕜 m E F).symm ∘ (λ (y : E), p y m.succ)) s, rw linear_isometry_equiv.comp_continuous_on_iff, exact H.cont _ A } }, { rintros ⟨Hzero_eq, Hfderiv_zero, Htaylor⟩, split, { exact Hzero_eq }, { assume m (hm : (m : with_top ℕ) < n.succ) x (hx : x ∈ s), cases m, { exact Hfderiv_zero x hx }, { have A : (m : with_top ℕ) < n, by { rw with_top.coe_lt_coe at hm ⊢, exact nat.lt_of_succ_lt_succ hm }, have : has_fderiv_within_at ((continuous_multilinear_curry_right_equiv' 𝕜 m E F).symm ∘ (λ (y : E), p y m.succ)) ((p x).shift m.succ).curry_left s x := Htaylor.fderiv_within _ A x hx, rw linear_isometry_equiv.comp_has_fderiv_within_at_iff' at this, convert this, ext y v, change (p x (nat.succ (nat.succ m))) (cons y v) = (p x m.succ.succ) (snoc (cons y (init v)) (v (last _))), rw [← cons_snoc_eq_snoc_cons, snoc_init_self] } }, { assume m (hm : (m : with_top ℕ) ≤ n.succ), cases m, { have : differentiable_on 𝕜 (λ x, p x 0) s := λ x hx, (Hfderiv_zero x hx).differentiable_within_at, exact this.continuous_on }, { have A : (m : with_top ℕ) ≤ n, by { rw with_top.coe_le_coe at hm ⊢, exact nat.lt_succ_iff.mp hm }, have : continuous_on ((continuous_multilinear_curry_right_equiv' 𝕜 m E F).symm ∘ (λ (y : E), p y m.succ)) s := Htaylor.cont _ A, rwa linear_isometry_equiv.comp_continuous_on_iff at this } } } end /-! ### Smooth functions within a set around a point -/ variable (𝕜) /-- A function is continuously differentiable up to order `n` within a set `s` at a point `x` if it admits continuous derivatives up to order `n` in a neighborhood of `x` in `s ∪ {x}`. For `n = ∞`, we only require that this holds up to any finite order (where the neighborhood may depend on the finite order we consider). For instance, a real function which is `C^m` on `(-1/m, 1/m)` for each natural `m`, but not better, is `C^∞` at `0` within `univ`. -/ def times_cont_diff_within_at (n : with_top ℕ) (f : E → F) (s : set E) (x : E) := ∀ (m : ℕ), (m : with_top ℕ) ≤ n → ∃ u ∈ 𝓝[insert x s] x, ∃ p : E → formal_multilinear_series 𝕜 E F, has_ftaylor_series_up_to_on m f p u variable {𝕜} lemma times_cont_diff_within_at_nat {n : ℕ} : times_cont_diff_within_at 𝕜 n f s x ↔ ∃ u ∈ 𝓝[insert x s] x, ∃ p : E → formal_multilinear_series 𝕜 E F, has_ftaylor_series_up_to_on n f p u := ⟨λ H, H n (le_refl _), λ ⟨u, hu, p, hp⟩ m hm, ⟨u, hu, p, hp.of_le hm⟩⟩ lemma times_cont_diff_within_at.of_le {m n : with_top ℕ} (h : times_cont_diff_within_at 𝕜 n f s x) (hmn : m ≤ n) : times_cont_diff_within_at 𝕜 m f s x := λ k hk, h k (le_trans hk hmn) lemma times_cont_diff_within_at_iff_forall_nat_le {n : with_top ℕ} : times_cont_diff_within_at 𝕜 n f s x ↔ ∀ m : ℕ, ↑m ≤ n → times_cont_diff_within_at 𝕜 m f s x := ⟨λ H m hm, H.of_le hm, λ H m hm, H m hm _ le_rfl⟩ lemma times_cont_diff_within_at_top : times_cont_diff_within_at 𝕜 ∞ f s x ↔ ∀ (n : ℕ), times_cont_diff_within_at 𝕜 n f s x := times_cont_diff_within_at_iff_forall_nat_le.trans $ by simp only [forall_prop_of_true, le_top] lemma times_cont_diff_within_at.continuous_within_at {n : with_top ℕ} (h : times_cont_diff_within_at 𝕜 n f s x) : continuous_within_at f s x := begin rcases h 0 bot_le with ⟨u, hu, p, H⟩, rw [mem_nhds_within_insert] at hu, exact (H.continuous_on.continuous_within_at hu.1).mono_of_mem hu.2 end lemma times_cont_diff_within_at.congr_of_eventually_eq {n : with_top ℕ} (h : times_cont_diff_within_at 𝕜 n f s x) (h₁ : f₁ =ᶠ[𝓝[s] x] f) (hx : f₁ x = f x) : times_cont_diff_within_at 𝕜 n f₁ s x := λ m hm, let ⟨u, hu, p, H⟩ := h m hm in ⟨{x ∈ u | f₁ x = f x}, filter.inter_mem hu (mem_nhds_within_insert.2 ⟨hx, h₁⟩), p, (H.mono (sep_subset _ _)).congr (λ _, and.right)⟩ lemma times_cont_diff_within_at.congr_of_eventually_eq' {n : with_top ℕ} (h : times_cont_diff_within_at 𝕜 n f s x) (h₁ : f₁ =ᶠ[𝓝[s] x] f) (hx : x ∈ s) : times_cont_diff_within_at 𝕜 n f₁ s x := h.congr_of_eventually_eq h₁ $ h₁.self_of_nhds_within hx lemma filter.eventually_eq.times_cont_diff_within_at_iff {n : with_top ℕ} (h₁ : f₁ =ᶠ[𝓝[s] x] f) (hx : f₁ x = f x) : times_cont_diff_within_at 𝕜 n f₁ s x ↔ times_cont_diff_within_at 𝕜 n f s x := ⟨λ H, times_cont_diff_within_at.congr_of_eventually_eq H h₁.symm hx.symm, λ H, H.congr_of_eventually_eq h₁ hx⟩ lemma times_cont_diff_within_at.congr {n : with_top ℕ} (h : times_cont_diff_within_at 𝕜 n f s x) (h₁ : ∀ y ∈ s, f₁ y = f y) (hx : f₁ x = f x) : times_cont_diff_within_at 𝕜 n f₁ s x := h.congr_of_eventually_eq (filter.eventually_eq_of_mem self_mem_nhds_within h₁) hx lemma times_cont_diff_within_at.congr' {n : with_top ℕ} (h : times_cont_diff_within_at 𝕜 n f s x) (h₁ : ∀ y ∈ s, f₁ y = f y) (hx : x ∈ s) : times_cont_diff_within_at 𝕜 n f₁ s x := h.congr h₁ (h₁ _ hx) lemma times_cont_diff_within_at.mono_of_mem {n : with_top ℕ} (h : times_cont_diff_within_at 𝕜 n f s x) {t : set E} (hst : s ∈ 𝓝[t] x) : times_cont_diff_within_at 𝕜 n f t x := begin assume m hm, rcases h m hm with ⟨u, hu, p, H⟩, exact ⟨u, nhds_within_le_of_mem (insert_mem_nhds_within_insert hst) hu, p, H⟩ end lemma times_cont_diff_within_at.mono {n : with_top ℕ} (h : times_cont_diff_within_at 𝕜 n f s x) {t : set E} (hst : t ⊆ s) : times_cont_diff_within_at 𝕜 n f t x := h.mono_of_mem $ filter.mem_of_superset self_mem_nhds_within hst lemma times_cont_diff_within_at.congr_nhds {n : with_top ℕ} (h : times_cont_diff_within_at 𝕜 n f s x) {t : set E} (hst : 𝓝[s] x = 𝓝[t] x) : times_cont_diff_within_at 𝕜 n f t x := h.mono_of_mem $ hst ▸ self_mem_nhds_within lemma times_cont_diff_within_at_congr_nhds {n : with_top ℕ} {t : set E} (hst : 𝓝[s] x = 𝓝[t] x) : times_cont_diff_within_at 𝕜 n f s x ↔ times_cont_diff_within_at 𝕜 n f t x := ⟨λ h, h.congr_nhds hst, λ h, h.congr_nhds hst.symm⟩ lemma times_cont_diff_within_at_inter' {n : with_top ℕ} (h : t ∈ 𝓝[s] x) : times_cont_diff_within_at 𝕜 n f (s ∩ t) x ↔ times_cont_diff_within_at 𝕜 n f s x := times_cont_diff_within_at_congr_nhds $ eq.symm $ nhds_within_restrict'' _ h lemma times_cont_diff_within_at_inter {n : with_top ℕ} (h : t ∈ 𝓝 x) : times_cont_diff_within_at 𝕜 n f (s ∩ t) x ↔ times_cont_diff_within_at 𝕜 n f s x := times_cont_diff_within_at_inter' (mem_nhds_within_of_mem_nhds h) /-- If a function is `C^n` within a set at a point, with `n ≥ 1`, then it is differentiable within this set at this point. -/ lemma times_cont_diff_within_at.differentiable_within_at' {n : with_top ℕ} (h : times_cont_diff_within_at 𝕜 n f s x) (hn : 1 ≤ n) : differentiable_within_at 𝕜 f (insert x s) x := begin rcases h 1 hn with ⟨u, hu, p, H⟩, rcases mem_nhds_within.1 hu with ⟨t, t_open, xt, tu⟩, rw inter_comm at tu, have := ((H.mono tu).differentiable_on (le_refl _)) x ⟨mem_insert x s, xt⟩, exact (differentiable_within_at_inter (is_open.mem_nhds t_open xt)).1 this, end lemma times_cont_diff_within_at.differentiable_within_at {n : with_top ℕ} (h : times_cont_diff_within_at 𝕜 n f s x) (hn : 1 ≤ n) : differentiable_within_at 𝕜 f s x := (h.differentiable_within_at' hn).mono (subset_insert x s) /-- A function is `C^(n + 1)` on a domain iff locally, it has a derivative which is `C^n`. -/ theorem times_cont_diff_within_at_succ_iff_has_fderiv_within_at {n : ℕ} : times_cont_diff_within_at 𝕜 ((n + 1) : ℕ) f s x ↔ ∃ u ∈ 𝓝[insert x s] x, ∃ f' : E → (E →L[𝕜] F), (∀ x ∈ u, has_fderiv_within_at f (f' x) u x) ∧ (times_cont_diff_within_at 𝕜 n f' u x) := begin split, { assume h, rcases h n.succ (le_refl _) with ⟨u, hu, p, Hp⟩, refine ⟨u, hu, λ y, (continuous_multilinear_curry_fin1 𝕜 E F) (p y 1), λ y hy, Hp.has_fderiv_within_at (with_top.coe_le_coe.2 (nat.le_add_left 1 n)) hy, _⟩, assume m hm, refine ⟨u, _, λ (y : E), (p y).shift, _⟩, { convert self_mem_nhds_within, have : x ∈ insert x s, by simp, exact (insert_eq_of_mem (mem_of_mem_nhds_within this hu)) }, { rw has_ftaylor_series_up_to_on_succ_iff_right at Hp, exact Hp.2.2.of_le hm } }, { rintros ⟨u, hu, f', f'_eq_deriv, Hf'⟩, rw times_cont_diff_within_at_nat, rcases Hf' n (le_refl _) with ⟨v, hv, p', Hp'⟩, refine ⟨v ∩ u, _, λ x, (p' x).unshift (f x), _⟩, { apply filter.inter_mem _ hu, apply nhds_within_le_of_mem hu, exact nhds_within_mono _ (subset_insert x u) hv }, { rw has_ftaylor_series_up_to_on_succ_iff_right, refine ⟨λ y hy, rfl, λ y hy, _, _⟩, { change has_fderiv_within_at (λ z, (continuous_multilinear_curry_fin0 𝕜 E F).symm (f z)) ((formal_multilinear_series.unshift (p' y) (f y) 1).curry_left) (v ∩ u) y, rw linear_isometry_equiv.comp_has_fderiv_within_at_iff', convert (f'_eq_deriv y hy.2).mono (inter_subset_right v u), rw ← Hp'.zero_eq y hy.1, ext z, change ((p' y 0) (init (@cons 0 (λ i, E) z 0))) (@cons 0 (λ i, E) z 0 (last 0)) = ((p' y 0) 0) z, unfold_coes, congr }, { convert (Hp'.mono (inter_subset_left v u)).congr (λ x hx, Hp'.zero_eq x hx.1), { ext x y, change p' x 0 (init (@snoc 0 (λ i : fin 1, E) 0 y)) y = p' x 0 0 y, rw init_snoc }, { ext x k v y, change p' x k (init (@snoc k (λ i : fin k.succ, E) v y)) (@snoc k (λ i : fin k.succ, E) v y (last k)) = p' x k v y, rw [snoc_last, init_snoc] } } } } end /-! ### Smooth functions within a set -/ variable (𝕜) /-- A function is continuously differentiable up to `n` on `s` if, for any point `x` in `s`, it admits continuous derivatives up to order `n` on a neighborhood of `x` in `s`. For `n = ∞`, we only require that this holds up to any finite order (where the neighborhood may depend on the finite order we consider). -/ definition times_cont_diff_on (n : with_top ℕ) (f : E → F) (s : set E) := ∀ x ∈ s, times_cont_diff_within_at 𝕜 n f s x variable {𝕜} lemma times_cont_diff_on.times_cont_diff_within_at {n : with_top ℕ} (h : times_cont_diff_on 𝕜 n f s) (hx : x ∈ s) : times_cont_diff_within_at 𝕜 n f s x := h x hx lemma times_cont_diff_within_at.times_cont_diff_on {n : with_top ℕ} {m : ℕ} (hm : (m : with_top ℕ) ≤ n) (h : times_cont_diff_within_at 𝕜 n f s x) : ∃ u ∈ 𝓝[insert x s] x, u ⊆ insert x s ∧ times_cont_diff_on 𝕜 m f u := begin rcases h m hm with ⟨u, u_nhd, p, hp⟩, refine ⟨u ∩ insert x s, filter.inter_mem u_nhd self_mem_nhds_within, inter_subset_right _ _, _⟩, assume y hy m' hm', refine ⟨u ∩ insert x s, _, p, (hp.mono (inter_subset_left _ _)).of_le hm'⟩, convert self_mem_nhds_within, exact insert_eq_of_mem hy end lemma times_cont_diff_on.of_le {m n : with_top ℕ} (h : times_cont_diff_on 𝕜 n f s) (hmn : m ≤ n) : times_cont_diff_on 𝕜 m f s := λ x hx, (h x hx).of_le hmn lemma times_cont_diff_on_iff_forall_nat_le {n : with_top ℕ} : times_cont_diff_on 𝕜 n f s ↔ ∀ m : ℕ, ↑m ≤ n → times_cont_diff_on 𝕜 m f s := ⟨λ H m hm, H.of_le hm, λ H x hx m hm, H m hm x hx m le_rfl⟩ lemma times_cont_diff_on_top : times_cont_diff_on 𝕜 ∞ f s ↔ ∀ (n : ℕ), times_cont_diff_on 𝕜 n f s := times_cont_diff_on_iff_forall_nat_le.trans $ by simp only [le_top, forall_prop_of_true] lemma times_cont_diff_on_all_iff_nat : (∀ n, times_cont_diff_on 𝕜 n f s) ↔ (∀ n : ℕ, times_cont_diff_on 𝕜 n f s) := begin refine ⟨λ H n, H n, _⟩, rintro H (_|n), exacts [times_cont_diff_on_top.2 H, H n] end lemma times_cont_diff_on.continuous_on {n : with_top ℕ} (h : times_cont_diff_on 𝕜 n f s) : continuous_on f s := λ x hx, (h x hx).continuous_within_at lemma times_cont_diff_on.congr {n : with_top ℕ} (h : times_cont_diff_on 𝕜 n f s) (h₁ : ∀ x ∈ s, f₁ x = f x) : times_cont_diff_on 𝕜 n f₁ s := λ x hx, (h x hx).congr h₁ (h₁ x hx) lemma times_cont_diff_on_congr {n : with_top ℕ} (h₁ : ∀ x ∈ s, f₁ x = f x) : times_cont_diff_on 𝕜 n f₁ s ↔ times_cont_diff_on 𝕜 n f s := ⟨λ H, H.congr (λ x hx, (h₁ x hx).symm), λ H, H.congr h₁⟩ lemma times_cont_diff_on.mono {n : with_top ℕ} (h : times_cont_diff_on 𝕜 n f s) {t : set E} (hst : t ⊆ s) : times_cont_diff_on 𝕜 n f t := λ x hx, (h x (hst hx)).mono hst lemma times_cont_diff_on.congr_mono {n : with_top ℕ} (hf : times_cont_diff_on 𝕜 n f s) (h₁ : ∀ x ∈ s₁, f₁ x = f x) (hs : s₁ ⊆ s) : times_cont_diff_on 𝕜 n f₁ s₁ := (hf.mono hs).congr h₁ /-- If a function is `C^n` on a set with `n ≥ 1`, then it is differentiable there. -/ lemma times_cont_diff_on.differentiable_on {n : with_top ℕ} (h : times_cont_diff_on 𝕜 n f s) (hn : 1 ≤ n) : differentiable_on 𝕜 f s := λ x hx, (h x hx).differentiable_within_at hn /-- If a function is `C^n` around each point in a set, then it is `C^n` on the set. -/ lemma times_cont_diff_on_of_locally_times_cont_diff_on {n : with_top ℕ} (h : ∀ x ∈ s, ∃u, is_open u ∧ x ∈ u ∧ times_cont_diff_on 𝕜 n f (s ∩ u)) : times_cont_diff_on 𝕜 n f s := begin assume x xs, rcases h x xs with ⟨u, u_open, xu, hu⟩, apply (times_cont_diff_within_at_inter _).1 (hu x ⟨xs, xu⟩), exact is_open.mem_nhds u_open xu end /-- A function is `C^(n + 1)` on a domain iff locally, it has a derivative which is `C^n`. -/ theorem times_cont_diff_on_succ_iff_has_fderiv_within_at {n : ℕ} : times_cont_diff_on 𝕜 ((n + 1) : ℕ) f s ↔ ∀ x ∈ s, ∃ u ∈ 𝓝[insert x s] x, ∃ f' : E → (E →L[𝕜] F), (∀ x ∈ u, has_fderiv_within_at f (f' x) u x) ∧ (times_cont_diff_on 𝕜 n f' u) := begin split, { assume h x hx, rcases (h x hx) n.succ (le_refl _) with ⟨u, hu, p, Hp⟩, refine ⟨u, hu, λ y, (continuous_multilinear_curry_fin1 𝕜 E F) (p y 1), λ y hy, Hp.has_fderiv_within_at (with_top.coe_le_coe.2 (nat.le_add_left 1 n)) hy, _⟩, rw has_ftaylor_series_up_to_on_succ_iff_right at Hp, assume z hz m hm, refine ⟨u, _, λ (x : E), (p x).shift, Hp.2.2.of_le hm⟩, convert self_mem_nhds_within, exact insert_eq_of_mem hz, }, { assume h x hx, rw times_cont_diff_within_at_succ_iff_has_fderiv_within_at, rcases h x hx with ⟨u, u_nhbd, f', hu, hf'⟩, have : x ∈ u := mem_of_mem_nhds_within (mem_insert _ _) u_nhbd, exact ⟨u, u_nhbd, f', hu, hf' x this⟩ } end /-! ### Iterated derivative within a set -/ variable (𝕜) /-- The `n`-th derivative of a function along a set, defined inductively by saying that the `n+1`-th derivative of `f` is the derivative of the `n`-th derivative of `f` along this set, together with an uncurrying step to see it as a multilinear map in `n+1` variables.. -/ noncomputable def iterated_fderiv_within (n : ℕ) (f : E → F) (s : set E) : E → (E [×n]→L[𝕜] F) := nat.rec_on n (λ x, continuous_multilinear_map.curry0 𝕜 E (f x)) (λ n rec x, continuous_linear_map.uncurry_left (fderiv_within 𝕜 rec s x)) /-- Formal Taylor series associated to a function within a set. -/ def ftaylor_series_within (f : E → F) (s : set E) (x : E) : formal_multilinear_series 𝕜 E F := λ n, iterated_fderiv_within 𝕜 n f s x variable {𝕜} @[simp] lemma iterated_fderiv_within_zero_apply (m : (fin 0) → E) : (iterated_fderiv_within 𝕜 0 f s x : ((fin 0) → E) → F) m = f x := rfl lemma iterated_fderiv_within_zero_eq_comp : iterated_fderiv_within 𝕜 0 f s = (continuous_multilinear_curry_fin0 𝕜 E F).symm ∘ f := rfl lemma iterated_fderiv_within_succ_apply_left {n : ℕ} (m : fin (n + 1) → E): (iterated_fderiv_within 𝕜 (n + 1) f s x : (fin (n + 1) → E) → F) m = (fderiv_within 𝕜 (iterated_fderiv_within 𝕜 n f s) s x : E → (E [×n]→L[𝕜] F)) (m 0) (tail m) := rfl /-- Writing explicitly the `n+1`-th derivative as the composition of a currying linear equiv, and the derivative of the `n`-th derivative. -/ lemma iterated_fderiv_within_succ_eq_comp_left {n : ℕ} : iterated_fderiv_within 𝕜 (n + 1) f s = (continuous_multilinear_curry_left_equiv 𝕜 (λ(i : fin (n + 1)), E) F) ∘ (fderiv_within 𝕜 (iterated_fderiv_within 𝕜 n f s) s) := rfl theorem iterated_fderiv_within_succ_apply_right {n : ℕ} (hs : unique_diff_on 𝕜 s) (hx : x ∈ s) (m : fin (n + 1) → E) : (iterated_fderiv_within 𝕜 (n + 1) f s x : (fin (n + 1) → E) → F) m = iterated_fderiv_within 𝕜 n (λy, fderiv_within 𝕜 f s y) s x (init m) (m (last n)) := begin induction n with n IH generalizing x, { rw [iterated_fderiv_within_succ_eq_comp_left, iterated_fderiv_within_zero_eq_comp, iterated_fderiv_within_zero_apply, function.comp_apply, linear_isometry_equiv.comp_fderiv_within _ (hs x hx)], refl }, { let I := continuous_multilinear_curry_right_equiv' 𝕜 n E F, have A : ∀ y ∈ s, iterated_fderiv_within 𝕜 n.succ f s y = (I ∘ (iterated_fderiv_within 𝕜 n (λy, fderiv_within 𝕜 f s y) s)) y, by { assume y hy, ext m, rw @IH m y hy, refl }, calc (iterated_fderiv_within 𝕜 (n+2) f s x : (fin (n+2) → E) → F) m = (fderiv_within 𝕜 (iterated_fderiv_within 𝕜 n.succ f s) s x : E → (E [×(n + 1)]→L[𝕜] F)) (m 0) (tail m) : rfl ... = (fderiv_within 𝕜 (I ∘ (iterated_fderiv_within 𝕜 n (fderiv_within 𝕜 f s) s)) s x : E → (E [×(n + 1)]→L[𝕜] F)) (m 0) (tail m) : by rw fderiv_within_congr (hs x hx) A (A x hx) ... = (I ∘ fderiv_within 𝕜 ((iterated_fderiv_within 𝕜 n (fderiv_within 𝕜 f s) s)) s x : E → (E [×(n + 1)]→L[𝕜] F)) (m 0) (tail m) : by { rw linear_isometry_equiv.comp_fderiv_within _ (hs x hx), refl } ... = (fderiv_within 𝕜 ((iterated_fderiv_within 𝕜 n (λ y, fderiv_within 𝕜 f s y) s)) s x : E → (E [×n]→L[𝕜] (E →L[𝕜] F))) (m 0) (init (tail m)) ((tail m) (last n)) : rfl ... = iterated_fderiv_within 𝕜 (nat.succ n) (λ y, fderiv_within 𝕜 f s y) s x (init m) (m (last (n + 1))) : by { rw [iterated_fderiv_within_succ_apply_left, tail_init_eq_init_tail], refl } } end /-- Writing explicitly the `n+1`-th derivative as the composition of a currying linear equiv, and the `n`-th derivative of the derivative. -/ lemma iterated_fderiv_within_succ_eq_comp_right {n : ℕ} (hs : unique_diff_on 𝕜 s) (hx : x ∈ s) : iterated_fderiv_within 𝕜 (n + 1) f s x = ((continuous_multilinear_curry_right_equiv' 𝕜 n E F) ∘ (iterated_fderiv_within 𝕜 n (λy, fderiv_within 𝕜 f s y) s)) x := by { ext m, rw iterated_fderiv_within_succ_apply_right hs hx, refl } @[simp] lemma iterated_fderiv_within_one_apply (hs : unique_diff_on 𝕜 s) (hx : x ∈ s) (m : (fin 1) → E) : (iterated_fderiv_within 𝕜 1 f s x : ((fin 1) → E) → F) m = (fderiv_within 𝕜 f s x : E → F) (m 0) := by { rw [iterated_fderiv_within_succ_apply_right hs hx, iterated_fderiv_within_zero_apply], refl } /-- If two functions coincide on a set `s` of unique differentiability, then their iterated differentials within this set coincide. -/ lemma iterated_fderiv_within_congr {n : ℕ} (hs : unique_diff_on 𝕜 s) (hL : ∀y∈s, f₁ y = f y) (hx : x ∈ s) : iterated_fderiv_within 𝕜 n f₁ s x = iterated_fderiv_within 𝕜 n f s x := begin induction n with n IH generalizing x, { ext m, simp [hL x hx] }, { have : fderiv_within 𝕜 (λ y, iterated_fderiv_within 𝕜 n f₁ s y) s x = fderiv_within 𝕜 (λ y, iterated_fderiv_within 𝕜 n f s y) s x := fderiv_within_congr (hs x hx) (λ y hy, IH hy) (IH hx), ext m, rw [iterated_fderiv_within_succ_apply_left, iterated_fderiv_within_succ_apply_left, this] } end /-- The iterated differential within a set `s` at a point `x` is not modified if one intersects `s` with an open set containing `x`. -/ lemma iterated_fderiv_within_inter_open {n : ℕ} (hu : is_open u) (hs : unique_diff_on 𝕜 (s ∩ u)) (hx : x ∈ s ∩ u) : iterated_fderiv_within 𝕜 n f (s ∩ u) x = iterated_fderiv_within 𝕜 n f s x := begin induction n with n IH generalizing x, { ext m, simp }, { have A : fderiv_within 𝕜 (λ y, iterated_fderiv_within 𝕜 n f (s ∩ u) y) (s ∩ u) x = fderiv_within 𝕜 (λ y, iterated_fderiv_within 𝕜 n f s y) (s ∩ u) x := fderiv_within_congr (hs x hx) (λ y hy, IH hy) (IH hx), have B : fderiv_within 𝕜 (λ y, iterated_fderiv_within 𝕜 n f s y) (s ∩ u) x = fderiv_within 𝕜 (λ y, iterated_fderiv_within 𝕜 n f s y) s x := fderiv_within_inter (is_open.mem_nhds hu hx.2) ((unique_diff_within_at_inter (is_open.mem_nhds hu hx.2)).1 (hs x hx)), ext m, rw [iterated_fderiv_within_succ_apply_left, iterated_fderiv_within_succ_apply_left, A, B] } end /-- The iterated differential within a set `s` at a point `x` is not modified if one intersects `s` with a neighborhood of `x` within `s`. -/ lemma iterated_fderiv_within_inter' {n : ℕ} (hu : u ∈ 𝓝[s] x) (hs : unique_diff_on 𝕜 s) (xs : x ∈ s) : iterated_fderiv_within 𝕜 n f (s ∩ u) x = iterated_fderiv_within 𝕜 n f s x := begin obtain ⟨v, v_open, xv, vu⟩ : ∃ v, is_open v ∧ x ∈ v ∧ v ∩ s ⊆ u := mem_nhds_within.1 hu, have A : (s ∩ u) ∩ v = s ∩ v, { apply subset.antisymm (inter_subset_inter (inter_subset_left _ _) (subset.refl _)), exact λ y ⟨ys, yv⟩, ⟨⟨ys, vu ⟨yv, ys⟩⟩, yv⟩ }, have : iterated_fderiv_within 𝕜 n f (s ∩ v) x = iterated_fderiv_within 𝕜 n f s x := iterated_fderiv_within_inter_open v_open (hs.inter v_open) ⟨xs, xv⟩, rw ← this, have : iterated_fderiv_within 𝕜 n f ((s ∩ u) ∩ v) x = iterated_fderiv_within 𝕜 n f (s ∩ u) x, { refine iterated_fderiv_within_inter_open v_open _ ⟨⟨xs, vu ⟨xv, xs⟩⟩, xv⟩, rw A, exact hs.inter v_open }, rw A at this, rw ← this end /-- The iterated differential within a set `s` at a point `x` is not modified if one intersects `s` with a neighborhood of `x`. -/ lemma iterated_fderiv_within_inter {n : ℕ} (hu : u ∈ 𝓝 x) (hs : unique_diff_on 𝕜 s) (xs : x ∈ s) : iterated_fderiv_within 𝕜 n f (s ∩ u) x = iterated_fderiv_within 𝕜 n f s x := iterated_fderiv_within_inter' (mem_nhds_within_of_mem_nhds hu) hs xs @[simp] lemma times_cont_diff_on_zero : times_cont_diff_on 𝕜 0 f s ↔ continuous_on f s := begin refine ⟨λ H, H.continuous_on, λ H, _⟩, assume x hx m hm, have : (m : with_top ℕ) = 0 := le_antisymm hm bot_le, rw this, refine ⟨insert x s, self_mem_nhds_within, ftaylor_series_within 𝕜 f s, _⟩, rw has_ftaylor_series_up_to_on_zero_iff, exact ⟨by rwa insert_eq_of_mem hx, λ x hx, by simp [ftaylor_series_within]⟩ end lemma times_cont_diff_within_at_zero (hx : x ∈ s) : times_cont_diff_within_at 𝕜 0 f s x ↔ ∃ u ∈ 𝓝[s] x, continuous_on f (s ∩ u) := begin split, { intros h, obtain ⟨u, H, p, hp⟩ := h 0 (by norm_num), refine ⟨u, _, _⟩, { simpa [hx] using H }, { simp only [with_top.coe_zero, has_ftaylor_series_up_to_on_zero_iff] at hp, exact hp.1.mono (inter_subset_right s u) } }, { rintros ⟨u, H, hu⟩, rw ← times_cont_diff_within_at_inter' H, have h' : x ∈ s ∩ u := ⟨hx, mem_of_mem_nhds_within hx H⟩, exact (times_cont_diff_on_zero.mpr hu).times_cont_diff_within_at h' } end /-- On a set with unique differentiability, any choice of iterated differential has to coincide with the one we have chosen in `iterated_fderiv_within 𝕜 m f s`. -/ theorem has_ftaylor_series_up_to_on.eq_ftaylor_series_of_unique_diff_on {n : with_top ℕ} (h : has_ftaylor_series_up_to_on n f p s) {m : ℕ} (hmn : (m : with_top ℕ) ≤ n) (hs : unique_diff_on 𝕜 s) (hx : x ∈ s) : p x m = iterated_fderiv_within 𝕜 m f s x := begin induction m with m IH generalizing x, { rw [h.zero_eq' hx, iterated_fderiv_within_zero_eq_comp] }, { have A : (m : with_top ℕ) < n := lt_of_lt_of_le (with_top.coe_lt_coe.2 (lt_add_one m)) hmn, have : has_fderiv_within_at (λ (y : E), iterated_fderiv_within 𝕜 m f s y) (continuous_multilinear_map.curry_left (p x (nat.succ m))) s x := (h.fderiv_within m A x hx).congr (λ y hy, (IH (le_of_lt A) hy).symm) (IH (le_of_lt A) hx).symm, rw [iterated_fderiv_within_succ_eq_comp_left, function.comp_apply, this.fderiv_within (hs x hx)], exact (continuous_multilinear_map.uncurry_curry_left _).symm } end /-- When a function is `C^n` in a set `s` of unique differentiability, it admits `ftaylor_series_within 𝕜 f s` as a Taylor series up to order `n` in `s`. -/ theorem times_cont_diff_on.ftaylor_series_within {n : with_top ℕ} (h : times_cont_diff_on 𝕜 n f s) (hs : unique_diff_on 𝕜 s) : has_ftaylor_series_up_to_on n f (ftaylor_series_within 𝕜 f s) s := begin split, { assume x hx, simp only [ftaylor_series_within, continuous_multilinear_map.uncurry0_apply, iterated_fderiv_within_zero_apply] }, { assume m hm x hx, rcases (h x hx) m.succ (with_top.add_one_le_of_lt hm) with ⟨u, hu, p, Hp⟩, rw insert_eq_of_mem hx at hu, rcases mem_nhds_within.1 hu with ⟨o, o_open, xo, ho⟩, rw inter_comm at ho, have : p x m.succ = ftaylor_series_within 𝕜 f s x m.succ, { change p x m.succ = iterated_fderiv_within 𝕜 m.succ f s x, rw ← iterated_fderiv_within_inter (is_open.mem_nhds o_open xo) hs hx, exact (Hp.mono ho).eq_ftaylor_series_of_unique_diff_on (le_refl _) (hs.inter o_open) ⟨hx, xo⟩ }, rw [← this, ← has_fderiv_within_at_inter (is_open.mem_nhds o_open xo)], have A : ∀ y ∈ s ∩ o, p y m = ftaylor_series_within 𝕜 f s y m, { rintros y ⟨hy, yo⟩, change p y m = iterated_fderiv_within 𝕜 m f s y, rw ← iterated_fderiv_within_inter (is_open.mem_nhds o_open yo) hs hy, exact (Hp.mono ho).eq_ftaylor_series_of_unique_diff_on (with_top.coe_le_coe.2 (nat.le_succ m)) (hs.inter o_open) ⟨hy, yo⟩ }, exact ((Hp.mono ho).fderiv_within m (with_top.coe_lt_coe.2 (lt_add_one m)) x ⟨hx, xo⟩).congr (λ y hy, (A y hy).symm) (A x ⟨hx, xo⟩).symm }, { assume m hm, apply continuous_on_of_locally_continuous_on, assume x hx, rcases h x hx m hm with ⟨u, hu, p, Hp⟩, rcases mem_nhds_within.1 hu with ⟨o, o_open, xo, ho⟩, rw insert_eq_of_mem hx at ho, rw inter_comm at ho, refine ⟨o, o_open, xo, _⟩, have A : ∀ y ∈ s ∩ o, p y m = ftaylor_series_within 𝕜 f s y m, { rintros y ⟨hy, yo⟩, change p y m = iterated_fderiv_within 𝕜 m f s y, rw ← iterated_fderiv_within_inter (is_open.mem_nhds o_open yo) hs hy, exact (Hp.mono ho).eq_ftaylor_series_of_unique_diff_on (le_refl _) (hs.inter o_open) ⟨hy, yo⟩ }, exact ((Hp.mono ho).cont m (le_refl _)).congr (λ y hy, (A y hy).symm) } end lemma times_cont_diff_on_of_continuous_on_differentiable_on {n : with_top ℕ} (Hcont : ∀ (m : ℕ), (m : with_top ℕ) ≤ n → continuous_on (λ x, iterated_fderiv_within 𝕜 m f s x) s) (Hdiff : ∀ (m : ℕ), (m : with_top ℕ) < n → differentiable_on 𝕜 (λ x, iterated_fderiv_within 𝕜 m f s x) s) : times_cont_diff_on 𝕜 n f s := begin assume x hx m hm, rw insert_eq_of_mem hx, refine ⟨s, self_mem_nhds_within, ftaylor_series_within 𝕜 f s, _⟩, split, { assume y hy, simp only [ftaylor_series_within, continuous_multilinear_map.uncurry0_apply, iterated_fderiv_within_zero_apply] }, { assume k hk y hy, convert (Hdiff k (lt_of_lt_of_le hk hm) y hy).has_fderiv_within_at, simp only [ftaylor_series_within, iterated_fderiv_within_succ_eq_comp_left, continuous_linear_equiv.coe_apply, function.comp_app, coe_fn_coe_base], exact continuous_linear_map.curry_uncurry_left _ }, { assume k hk, exact Hcont k (le_trans hk hm) } end lemma times_cont_diff_on_of_differentiable_on {n : with_top ℕ} (h : ∀(m : ℕ), (m : with_top ℕ) ≤ n → differentiable_on 𝕜 (iterated_fderiv_within 𝕜 m f s) s) : times_cont_diff_on 𝕜 n f s := times_cont_diff_on_of_continuous_on_differentiable_on (λ m hm, (h m hm).continuous_on) (λ m hm, (h m (le_of_lt hm))) lemma times_cont_diff_on.continuous_on_iterated_fderiv_within {n : with_top ℕ} {m : ℕ} (h : times_cont_diff_on 𝕜 n f s) (hmn : (m : with_top ℕ) ≤ n) (hs : unique_diff_on 𝕜 s) : continuous_on (iterated_fderiv_within 𝕜 m f s) s := (h.ftaylor_series_within hs).cont m hmn lemma times_cont_diff_on.differentiable_on_iterated_fderiv_within {n : with_top ℕ} {m : ℕ} (h : times_cont_diff_on 𝕜 n f s) (hmn : (m : with_top ℕ) < n) (hs : unique_diff_on 𝕜 s) : differentiable_on 𝕜 (iterated_fderiv_within 𝕜 m f s) s := λ x hx, ((h.ftaylor_series_within hs).fderiv_within m hmn x hx).differentiable_within_at lemma times_cont_diff_on_iff_continuous_on_differentiable_on {n : with_top ℕ} (hs : unique_diff_on 𝕜 s) : times_cont_diff_on 𝕜 n f s ↔ (∀ (m : ℕ), (m : with_top ℕ) ≤ n → continuous_on (λ x, iterated_fderiv_within 𝕜 m f s x) s) ∧ (∀ (m : ℕ), (m : with_top ℕ) < n → differentiable_on 𝕜 (λ x, iterated_fderiv_within 𝕜 m f s x) s) := begin split, { assume h, split, { assume m hm, exact h.continuous_on_iterated_fderiv_within hm hs }, { assume m hm, exact h.differentiable_on_iterated_fderiv_within hm hs } }, { assume h, exact times_cont_diff_on_of_continuous_on_differentiable_on h.1 h.2 } end /-- A function is `C^(n + 1)` on a domain with unique derivatives if and only if it is differentiable there, and its derivative (expressed with `fderiv_within`) is `C^n`. -/ theorem times_cont_diff_on_succ_iff_fderiv_within {n : ℕ} (hs : unique_diff_on 𝕜 s) : times_cont_diff_on 𝕜 ((n + 1) : ℕ) f s ↔ differentiable_on 𝕜 f s ∧ times_cont_diff_on 𝕜 n (λ y, fderiv_within 𝕜 f s y) s := begin split, { assume H, refine ⟨H.differentiable_on (with_top.coe_le_coe.2 (nat.le_add_left 1 n)), λ x hx, _⟩, rcases times_cont_diff_within_at_succ_iff_has_fderiv_within_at.1 (H x hx) with ⟨u, hu, f', hff', hf'⟩, rcases mem_nhds_within.1 hu with ⟨o, o_open, xo, ho⟩, rw [inter_comm, insert_eq_of_mem hx] at ho, have := hf'.mono ho, rw times_cont_diff_within_at_inter' (mem_nhds_within_of_mem_nhds (is_open.mem_nhds o_open xo)) at this, apply this.congr_of_eventually_eq' _ hx, have : o ∩ s ∈ 𝓝[s] x := mem_nhds_within.2 ⟨o, o_open, xo, subset.refl _⟩, rw inter_comm at this, apply filter.eventually_eq_of_mem this (λ y hy, _), have A : fderiv_within 𝕜 f (s ∩ o) y = f' y := ((hff' y (ho hy)).mono ho).fderiv_within (hs.inter o_open y hy), rwa fderiv_within_inter (is_open.mem_nhds o_open hy.2) (hs y hy.1) at A, }, { rintros ⟨hdiff, h⟩ x hx, rw [times_cont_diff_within_at_succ_iff_has_fderiv_within_at, insert_eq_of_mem hx], exact ⟨s, self_mem_nhds_within, fderiv_within 𝕜 f s, λ y hy, (hdiff y hy).has_fderiv_within_at, h x hx⟩ } end /-- A function is `C^(n + 1)` on an open domain if and only if it is differentiable there, and its derivative (expressed with `fderiv`) is `C^n`. -/ theorem times_cont_diff_on_succ_iff_fderiv_of_open {n : ℕ} (hs : is_open s) : times_cont_diff_on 𝕜 ((n + 1) : ℕ) f s ↔ differentiable_on 𝕜 f s ∧ times_cont_diff_on 𝕜 n (λ y, fderiv 𝕜 f y) s := begin rw times_cont_diff_on_succ_iff_fderiv_within hs.unique_diff_on, congr' 2, rw ← iff_iff_eq, apply times_cont_diff_on_congr, assume x hx, exact fderiv_within_of_open hs hx end /-- A function is `C^∞` on a domain with unique derivatives if and only if it is differentiable there, and its derivative (expressed with `fderiv_within`) is `C^∞`. -/ theorem times_cont_diff_on_top_iff_fderiv_within (hs : unique_diff_on 𝕜 s) : times_cont_diff_on 𝕜 ∞ f s ↔ differentiable_on 𝕜 f s ∧ times_cont_diff_on 𝕜 ∞ (λ y, fderiv_within 𝕜 f s y) s := begin split, { assume h, refine ⟨h.differentiable_on le_top, _⟩, apply times_cont_diff_on_top.2 (λ n, ((times_cont_diff_on_succ_iff_fderiv_within hs).1 _).2), exact h.of_le le_top }, { assume h, refine times_cont_diff_on_top.2 (λ n, _), have A : (n : with_top ℕ) ≤ ∞ := le_top, apply ((times_cont_diff_on_succ_iff_fderiv_within hs).2 ⟨h.1, h.2.of_le A⟩).of_le, exact with_top.coe_le_coe.2 (nat.le_succ n) } end /-- A function is `C^∞` on an open domain if and only if it is differentiable there, and its derivative (expressed with `fderiv`) is `C^∞`. -/ theorem times_cont_diff_on_top_iff_fderiv_of_open (hs : is_open s) : times_cont_diff_on 𝕜 ∞ f s ↔ differentiable_on 𝕜 f s ∧ times_cont_diff_on 𝕜 ∞ (λ y, fderiv 𝕜 f y) s := begin rw times_cont_diff_on_top_iff_fderiv_within hs.unique_diff_on, congr' 2, rw ← iff_iff_eq, apply times_cont_diff_on_congr, assume x hx, exact fderiv_within_of_open hs hx end lemma times_cont_diff_on.fderiv_within {m n : with_top ℕ} (hf : times_cont_diff_on 𝕜 n f s) (hs : unique_diff_on 𝕜 s) (hmn : m + 1 ≤ n) : times_cont_diff_on 𝕜 m (λ y, fderiv_within 𝕜 f s y) s := begin cases m, { change ∞ + 1 ≤ n at hmn, have : n = ∞, by simpa using hmn, rw this at hf, exact ((times_cont_diff_on_top_iff_fderiv_within hs).1 hf).2 }, { change (m.succ : with_top ℕ) ≤ n at hmn, exact ((times_cont_diff_on_succ_iff_fderiv_within hs).1 (hf.of_le hmn)).2 } end lemma times_cont_diff_on.fderiv_of_open {m n : with_top ℕ} (hf : times_cont_diff_on 𝕜 n f s) (hs : is_open s) (hmn : m + 1 ≤ n) : times_cont_diff_on 𝕜 m (λ y, fderiv 𝕜 f y) s := (hf.fderiv_within hs.unique_diff_on hmn).congr (λ x hx, (fderiv_within_of_open hs hx).symm) lemma times_cont_diff_on.continuous_on_fderiv_within {n : with_top ℕ} (h : times_cont_diff_on 𝕜 n f s) (hs : unique_diff_on 𝕜 s) (hn : 1 ≤ n) : continuous_on (λ x, fderiv_within 𝕜 f s x) s := ((times_cont_diff_on_succ_iff_fderiv_within hs).1 (h.of_le hn)).2.continuous_on lemma times_cont_diff_on.continuous_on_fderiv_of_open {n : with_top ℕ} (h : times_cont_diff_on 𝕜 n f s) (hs : is_open s) (hn : 1 ≤ n) : continuous_on (λ x, fderiv 𝕜 f x) s := ((times_cont_diff_on_succ_iff_fderiv_of_open hs).1 (h.of_le hn)).2.continuous_on /-- If a function is at least `C^1`, its bundled derivative (mapping `(x, v)` to `Df(x) v`) is continuous. -/ lemma times_cont_diff_on.continuous_on_fderiv_within_apply {n : with_top ℕ} (h : times_cont_diff_on 𝕜 n f s) (hs : unique_diff_on 𝕜 s) (hn : 1 ≤ n) : continuous_on (λp : E × E, (fderiv_within 𝕜 f s p.1 : E → F) p.2) (set.prod s univ) := begin have A : continuous (λq : (E →L[𝕜] F) × E, q.1 q.2) := is_bounded_bilinear_map_apply.continuous, have B : continuous_on (λp : E × E, (fderiv_within 𝕜 f s p.1, p.2)) (set.prod s univ), { apply continuous_on.prod _ continuous_snd.continuous_on, exact continuous_on.comp (h.continuous_on_fderiv_within hs hn) continuous_fst.continuous_on (prod_subset_preimage_fst _ _) }, exact A.comp_continuous_on B end /-! ### Functions with a Taylor series on the whole space -/ /-- `has_ftaylor_series_up_to n f p` registers the fact that `p 0 = f` and `p (m+1)` is a derivative of `p m` for `m < n`, and is continuous for `m ≤ n`. This is a predicate analogous to `has_fderiv_at` but for higher order derivatives. -/ structure has_ftaylor_series_up_to (n : with_top ℕ) (f : E → F) (p : E → formal_multilinear_series 𝕜 E F) : Prop := (zero_eq : ∀ x, (p x 0).uncurry0 = f x) (fderiv : ∀ (m : ℕ) (hm : (m : with_top ℕ) < n), ∀ x, has_fderiv_at (λ y, p y m) (p x m.succ).curry_left x) (cont : ∀ (m : ℕ) (hm : (m : with_top ℕ) ≤ n), continuous (λ x, p x m)) lemma has_ftaylor_series_up_to.zero_eq' {n : with_top ℕ} (h : has_ftaylor_series_up_to n f p) (x : E) : p x 0 = (continuous_multilinear_curry_fin0 𝕜 E F).symm (f x) := by { rw ← h.zero_eq x, symmetry, exact continuous_multilinear_map.uncurry0_curry0 _ } lemma has_ftaylor_series_up_to_on_univ_iff {n : with_top ℕ} : has_ftaylor_series_up_to_on n f p univ ↔ has_ftaylor_series_up_to n f p := begin split, { assume H, split, { exact λ x, H.zero_eq x (mem_univ x) }, { assume m hm x, rw ← has_fderiv_within_at_univ, exact H.fderiv_within m hm x (mem_univ x) }, { assume m hm, rw continuous_iff_continuous_on_univ, exact H.cont m hm } }, { assume H, split, { exact λ x hx, H.zero_eq x }, { assume m hm x hx, rw has_fderiv_within_at_univ, exact H.fderiv m hm x }, { assume m hm, rw ← continuous_iff_continuous_on_univ, exact H.cont m hm } } end lemma has_ftaylor_series_up_to.has_ftaylor_series_up_to_on {n : with_top ℕ} (h : has_ftaylor_series_up_to n f p) (s : set E) : has_ftaylor_series_up_to_on n f p s := (has_ftaylor_series_up_to_on_univ_iff.2 h).mono (subset_univ _) lemma has_ftaylor_series_up_to.of_le {m n : with_top ℕ} (h : has_ftaylor_series_up_to n f p) (hmn : m ≤ n) : has_ftaylor_series_up_to m f p := by { rw ← has_ftaylor_series_up_to_on_univ_iff at h ⊢, exact h.of_le hmn } lemma has_ftaylor_series_up_to.continuous {n : with_top ℕ} (h : has_ftaylor_series_up_to n f p) : continuous f := begin rw ← has_ftaylor_series_up_to_on_univ_iff at h, rw continuous_iff_continuous_on_univ, exact h.continuous_on end lemma has_ftaylor_series_up_to_zero_iff : has_ftaylor_series_up_to 0 f p ↔ continuous f ∧ (∀ x, (p x 0).uncurry0 = f x) := by simp [has_ftaylor_series_up_to_on_univ_iff.symm, continuous_iff_continuous_on_univ, has_ftaylor_series_up_to_on_zero_iff] /-- If a function has a Taylor series at order at least `1`, then the term of order `1` of this series is a derivative of `f`. -/ lemma has_ftaylor_series_up_to.has_fderiv_at {n : with_top ℕ} (h : has_ftaylor_series_up_to n f p) (hn : 1 ≤ n) (x : E) : has_fderiv_at f (continuous_multilinear_curry_fin1 𝕜 E F (p x 1)) x := begin rw [← has_fderiv_within_at_univ], exact (has_ftaylor_series_up_to_on_univ_iff.2 h).has_fderiv_within_at hn (mem_univ _) end lemma has_ftaylor_series_up_to.differentiable {n : with_top ℕ} (h : has_ftaylor_series_up_to n f p) (hn : 1 ≤ n) : differentiable 𝕜 f := λ x, (h.has_fderiv_at hn x).differentiable_at /-- `p` is a Taylor series of `f` up to `n+1` if and only if `p.shift` is a Taylor series up to `n` for `p 1`, which is a derivative of `f`. -/ theorem has_ftaylor_series_up_to_succ_iff_right {n : ℕ} : has_ftaylor_series_up_to ((n + 1) : ℕ) f p ↔ (∀ x, (p x 0).uncurry0 = f x) ∧ (∀ x, has_fderiv_at (λ y, p y 0) (p x 1).curry_left x) ∧ has_ftaylor_series_up_to n (λ x, continuous_multilinear_curry_fin1 𝕜 E F (p x 1)) (λ x, (p x).shift) := by simp [has_ftaylor_series_up_to_on_succ_iff_right, has_ftaylor_series_up_to_on_univ_iff.symm, -add_comm, -with_zero.coe_add] /-! ### Smooth functions at a point -/ variable (𝕜) /-- A function is continuously differentiable up to `n` at a point `x` if, for any integer `k ≤ n`, there is a neighborhood of `x` where `f` admits derivatives up to order `n`, which are continuous. -/ def times_cont_diff_at (n : with_top ℕ) (f : E → F) (x : E) := times_cont_diff_within_at 𝕜 n f univ x variable {𝕜} theorem times_cont_diff_within_at_univ {n : with_top ℕ} : times_cont_diff_within_at 𝕜 n f univ x ↔ times_cont_diff_at 𝕜 n f x := iff.rfl lemma times_cont_diff_at_top : times_cont_diff_at 𝕜 ∞ f x ↔ ∀ (n : ℕ), times_cont_diff_at 𝕜 n f x := by simp [← times_cont_diff_within_at_univ, times_cont_diff_within_at_top] lemma times_cont_diff_at.times_cont_diff_within_at {n : with_top ℕ} (h : times_cont_diff_at 𝕜 n f x) : times_cont_diff_within_at 𝕜 n f s x := h.mono (subset_univ _) lemma times_cont_diff_within_at.times_cont_diff_at {n : with_top ℕ} (h : times_cont_diff_within_at 𝕜 n f s x) (hx : s ∈ 𝓝 x) : times_cont_diff_at 𝕜 n f x := by rwa [times_cont_diff_at, ← times_cont_diff_within_at_inter hx, univ_inter] lemma times_cont_diff_at.congr_of_eventually_eq {n : with_top ℕ} (h : times_cont_diff_at 𝕜 n f x) (hg : f₁ =ᶠ[𝓝 x] f) : times_cont_diff_at 𝕜 n f₁ x := h.congr_of_eventually_eq' (by rwa nhds_within_univ) (mem_univ x) lemma times_cont_diff_at.of_le {m n : with_top ℕ} (h : times_cont_diff_at 𝕜 n f x) (hmn : m ≤ n) : times_cont_diff_at 𝕜 m f x := h.of_le hmn lemma times_cont_diff_at.continuous_at {n : with_top ℕ} (h : times_cont_diff_at 𝕜 n f x) : continuous_at f x := by simpa [continuous_within_at_univ] using h.continuous_within_at /-- If a function is `C^n` with `n ≥ 1` at a point, then it is differentiable there. -/ lemma times_cont_diff_at.differentiable_at {n : with_top ℕ} (h : times_cont_diff_at 𝕜 n f x) (hn : 1 ≤ n) : differentiable_at 𝕜 f x := by simpa [hn, differentiable_within_at_univ] using h.differentiable_within_at /-- A function is `C^(n + 1)` at a point iff locally, it has a derivative which is `C^n`. -/ theorem times_cont_diff_at_succ_iff_has_fderiv_at {n : ℕ} : times_cont_diff_at 𝕜 ((n + 1) : ℕ) f x ↔ (∃ f' : E → (E →L[𝕜] F), (∃ u ∈ 𝓝 x, (∀ x ∈ u, has_fderiv_at f (f' x) x)) ∧ (times_cont_diff_at 𝕜 n f' x)) := begin rw [← times_cont_diff_within_at_univ, times_cont_diff_within_at_succ_iff_has_fderiv_within_at], simp only [nhds_within_univ, exists_prop, mem_univ, insert_eq_of_mem], split, { rintros ⟨u, H, f', h_fderiv, h_times_cont_diff⟩, rcases mem_nhds_iff.mp H with ⟨t, htu, ht, hxt⟩, refine ⟨f', ⟨t, _⟩, h_times_cont_diff.times_cont_diff_at H⟩, refine ⟨mem_nhds_iff.mpr ⟨t, subset.rfl, ht, hxt⟩, _⟩, intros y hyt, refine (h_fderiv y (htu hyt)).has_fderiv_at _, exact mem_nhds_iff.mpr ⟨t, htu, ht, hyt⟩ }, { rintros ⟨f', ⟨u, H, h_fderiv⟩, h_times_cont_diff⟩, refine ⟨u, H, f', _, h_times_cont_diff.times_cont_diff_within_at⟩, intros x hxu, exact (h_fderiv x hxu).has_fderiv_within_at } end /-! ### Smooth functions -/ variable (𝕜) /-- A function is continuously differentiable up to `n` if it admits derivatives up to order `n`, which are continuous. Contrary to the case of definitions in domains (where derivatives might not be unique) we do not need to localize the definition in space or time. -/ definition times_cont_diff (n : with_top ℕ) (f : E → F) := ∃ p : E → formal_multilinear_series 𝕜 E F, has_ftaylor_series_up_to n f p variable {𝕜} theorem times_cont_diff_on_univ {n : with_top ℕ} : times_cont_diff_on 𝕜 n f univ ↔ times_cont_diff 𝕜 n f := begin split, { assume H, use ftaylor_series_within 𝕜 f univ, rw ← has_ftaylor_series_up_to_on_univ_iff, exact H.ftaylor_series_within unique_diff_on_univ }, { rintros ⟨p, hp⟩ x hx m hm, exact ⟨univ, filter.univ_sets _, p, (hp.has_ftaylor_series_up_to_on univ).of_le hm⟩ } end lemma times_cont_diff_iff_times_cont_diff_at {n : with_top ℕ} : times_cont_diff 𝕜 n f ↔ ∀ x, times_cont_diff_at 𝕜 n f x := by simp [← times_cont_diff_on_univ, times_cont_diff_on, times_cont_diff_at] lemma times_cont_diff.times_cont_diff_at {n : with_top ℕ} (h : times_cont_diff 𝕜 n f) : times_cont_diff_at 𝕜 n f x := times_cont_diff_iff_times_cont_diff_at.1 h x lemma times_cont_diff.times_cont_diff_within_at {n : with_top ℕ} (h : times_cont_diff 𝕜 n f) : times_cont_diff_within_at 𝕜 n f s x := h.times_cont_diff_at.times_cont_diff_within_at lemma times_cont_diff_top : times_cont_diff 𝕜 ∞ f ↔ ∀ (n : ℕ), times_cont_diff 𝕜 n f := by simp [times_cont_diff_on_univ.symm, times_cont_diff_on_top] lemma times_cont_diff_all_iff_nat : (∀ n, times_cont_diff 𝕜 n f) ↔ (∀ n : ℕ, times_cont_diff 𝕜 n f) := by simp only [← times_cont_diff_on_univ, times_cont_diff_on_all_iff_nat] lemma times_cont_diff.times_cont_diff_on {n : with_top ℕ} (h : times_cont_diff 𝕜 n f) : times_cont_diff_on 𝕜 n f s := (times_cont_diff_on_univ.2 h).mono (subset_univ _) @[simp] lemma times_cont_diff_zero : times_cont_diff 𝕜 0 f ↔ continuous f := begin rw [← times_cont_diff_on_univ, continuous_iff_continuous_on_univ], exact times_cont_diff_on_zero end lemma times_cont_diff_at_zero : times_cont_diff_at 𝕜 0 f x ↔ ∃ u ∈ 𝓝 x, continuous_on f u := by { rw ← times_cont_diff_within_at_univ, simp [times_cont_diff_within_at_zero, nhds_within_univ] } lemma times_cont_diff.of_le {m n : with_top ℕ} (h : times_cont_diff 𝕜 n f) (hmn : m ≤ n) : times_cont_diff 𝕜 m f := times_cont_diff_on_univ.1 $ (times_cont_diff_on_univ.2 h).of_le hmn lemma times_cont_diff.continuous {n : with_top ℕ} (h : times_cont_diff 𝕜 n f) : continuous f := times_cont_diff_zero.1 (h.of_le bot_le) /-- If a function is `C^n` with `n ≥ 1`, then it is differentiable. -/ lemma times_cont_diff.differentiable {n : with_top ℕ} (h : times_cont_diff 𝕜 n f) (hn : 1 ≤ n) : differentiable 𝕜 f := differentiable_on_univ.1 $ (times_cont_diff_on_univ.2 h).differentiable_on hn /-! ### Iterated derivative -/ variable (𝕜) /-- The `n`-th derivative of a function, as a multilinear map, defined inductively. -/ noncomputable def iterated_fderiv (n : ℕ) (f : E → F) : E → (E [×n]→L[𝕜] F) := nat.rec_on n (λ x, continuous_multilinear_map.curry0 𝕜 E (f x)) (λ n rec x, continuous_linear_map.uncurry_left (fderiv 𝕜 rec x)) /-- Formal Taylor series associated to a function within a set. -/ def ftaylor_series (f : E → F) (x : E) : formal_multilinear_series 𝕜 E F := λ n, iterated_fderiv 𝕜 n f x variable {𝕜} @[simp] lemma iterated_fderiv_zero_apply (m : (fin 0) → E) : (iterated_fderiv 𝕜 0 f x : ((fin 0) → E) → F) m = f x := rfl lemma iterated_fderiv_zero_eq_comp : iterated_fderiv 𝕜 0 f = (continuous_multilinear_curry_fin0 𝕜 E F).symm ∘ f := rfl lemma iterated_fderiv_succ_apply_left {n : ℕ} (m : fin (n + 1) → E): (iterated_fderiv 𝕜 (n + 1) f x : (fin (n + 1) → E) → F) m = (fderiv 𝕜 (iterated_fderiv 𝕜 n f) x : E → (E [×n]→L[𝕜] F)) (m 0) (tail m) := rfl /-- Writing explicitly the `n+1`-th derivative as the composition of a currying linear equiv, and the derivative of the `n`-th derivative. -/ lemma iterated_fderiv_succ_eq_comp_left {n : ℕ} : iterated_fderiv 𝕜 (n + 1) f = (continuous_multilinear_curry_left_equiv 𝕜 (λ(i : fin (n + 1)), E) F) ∘ (fderiv 𝕜 (iterated_fderiv 𝕜 n f)) := rfl lemma iterated_fderiv_within_univ {n : ℕ} : iterated_fderiv_within 𝕜 n f univ = iterated_fderiv 𝕜 n f := begin induction n with n IH, { ext x, simp }, { ext x m, rw [iterated_fderiv_succ_apply_left, iterated_fderiv_within_succ_apply_left, IH, fderiv_within_univ] } end lemma ftaylor_series_within_univ : ftaylor_series_within 𝕜 f univ = ftaylor_series 𝕜 f := begin ext1 x, ext1 n, change iterated_fderiv_within 𝕜 n f univ x = iterated_fderiv 𝕜 n f x, rw iterated_fderiv_within_univ end theorem iterated_fderiv_succ_apply_right {n : ℕ} (m : fin (n + 1) → E) : (iterated_fderiv 𝕜 (n + 1) f x : (fin (n + 1) → E) → F) m = iterated_fderiv 𝕜 n (λy, fderiv 𝕜 f y) x (init m) (m (last n)) := begin rw [← iterated_fderiv_within_univ, ← iterated_fderiv_within_univ, ← fderiv_within_univ], exact iterated_fderiv_within_succ_apply_right unique_diff_on_univ (mem_univ _) _ end /-- Writing explicitly the `n+1`-th derivative as the composition of a currying linear equiv, and the `n`-th derivative of the derivative. -/ lemma iterated_fderiv_succ_eq_comp_right {n : ℕ} : iterated_fderiv 𝕜 (n + 1) f x = ((continuous_multilinear_curry_right_equiv' 𝕜 n E F) ∘ (iterated_fderiv 𝕜 n (λy, fderiv 𝕜 f y))) x := by { ext m, rw iterated_fderiv_succ_apply_right, refl } @[simp] lemma iterated_fderiv_one_apply (m : (fin 1) → E) : (iterated_fderiv 𝕜 1 f x : ((fin 1) → E) → F) m = (fderiv 𝕜 f x : E → F) (m 0) := by { rw [iterated_fderiv_succ_apply_right, iterated_fderiv_zero_apply], refl } /-- When a function is `C^n` in a set `s` of unique differentiability, it admits `ftaylor_series_within 𝕜 f s` as a Taylor series up to order `n` in `s`. -/ theorem times_cont_diff_on_iff_ftaylor_series {n : with_top ℕ} : times_cont_diff 𝕜 n f ↔ has_ftaylor_series_up_to n f (ftaylor_series 𝕜 f) := begin split, { rw [← times_cont_diff_on_univ, ← has_ftaylor_series_up_to_on_univ_iff, ← ftaylor_series_within_univ], exact λ h, times_cont_diff_on.ftaylor_series_within h unique_diff_on_univ }, { assume h, exact ⟨ftaylor_series 𝕜 f, h⟩ } end lemma times_cont_diff_iff_continuous_differentiable {n : with_top ℕ} : times_cont_diff 𝕜 n f ↔ (∀ (m : ℕ), (m : with_top ℕ) ≤ n → continuous (λ x, iterated_fderiv 𝕜 m f x)) ∧ (∀ (m : ℕ), (m : with_top ℕ) < n → differentiable 𝕜 (λ x, iterated_fderiv 𝕜 m f x)) := by simp [times_cont_diff_on_univ.symm, continuous_iff_continuous_on_univ, differentiable_on_univ.symm, iterated_fderiv_within_univ, times_cont_diff_on_iff_continuous_on_differentiable_on unique_diff_on_univ] lemma times_cont_diff_of_differentiable_iterated_fderiv {n : with_top ℕ} (h : ∀(m : ℕ), (m : with_top ℕ) ≤ n → differentiable 𝕜 (iterated_fderiv 𝕜 m f)) : times_cont_diff 𝕜 n f := times_cont_diff_iff_continuous_differentiable.2 ⟨λ m hm, (h m hm).continuous, λ m hm, (h m (le_of_lt hm))⟩ /-- A function is `C^(n + 1)` on a domain with unique derivatives if and only if it is differentiable there, and its derivative is `C^n`. -/ theorem times_cont_diff_succ_iff_fderiv {n : ℕ} : times_cont_diff 𝕜 ((n + 1) : ℕ) f ↔ differentiable 𝕜 f ∧ times_cont_diff 𝕜 n (λ y, fderiv 𝕜 f y) := by simp [times_cont_diff_on_univ.symm, differentiable_on_univ.symm, fderiv_within_univ.symm, - fderiv_within_univ, times_cont_diff_on_succ_iff_fderiv_within unique_diff_on_univ, -with_zero.coe_add, -add_comm] /-- A function is `C^∞` on a domain with unique derivatives if and only if it is differentiable there, and its derivative is `C^∞`. -/ theorem times_cont_diff_top_iff_fderiv : times_cont_diff 𝕜 ∞ f ↔ differentiable 𝕜 f ∧ times_cont_diff 𝕜 ∞ (λ y, fderiv 𝕜 f y) := begin simp [times_cont_diff_on_univ.symm, differentiable_on_univ.symm, fderiv_within_univ.symm, - fderiv_within_univ], rw times_cont_diff_on_top_iff_fderiv_within unique_diff_on_univ, end lemma times_cont_diff.continuous_fderiv {n : with_top ℕ} (h : times_cont_diff 𝕜 n f) (hn : 1 ≤ n) : continuous (λ x, fderiv 𝕜 f x) := ((times_cont_diff_succ_iff_fderiv).1 (h.of_le hn)).2.continuous /-- If a function is at least `C^1`, its bundled derivative (mapping `(x, v)` to `Df(x) v`) is continuous. -/ lemma times_cont_diff.continuous_fderiv_apply {n : with_top ℕ} (h : times_cont_diff 𝕜 n f) (hn : 1 ≤ n) : continuous (λp : E × E, (fderiv 𝕜 f p.1 : E → F) p.2) := begin have A : continuous (λq : (E →L[𝕜] F) × E, q.1 q.2) := is_bounded_bilinear_map_apply.continuous, have B : continuous (λp : E × E, (fderiv 𝕜 f p.1, p.2)), { apply continuous.prod_mk _ continuous_snd, exact continuous.comp (h.continuous_fderiv hn) continuous_fst }, exact A.comp B end /-! ### Constants -/ lemma iterated_fderiv_within_zero_fun {n : ℕ} : iterated_fderiv 𝕜 n (λ x : E, (0 : F)) = 0 := begin induction n with n IH, { ext m, simp }, { ext x m, rw [iterated_fderiv_succ_apply_left, IH], change (fderiv 𝕜 (λ (x : E), (0 : (E [×n]→L[𝕜] F))) x : E → (E [×n]→L[𝕜] F)) (m 0) (tail m) = _, rw fderiv_const, refl } end lemma times_cont_diff_zero_fun {n : with_top ℕ} : times_cont_diff 𝕜 n (λ x : E, (0 : F)) := begin apply times_cont_diff_of_differentiable_iterated_fderiv (λm hm, _), rw iterated_fderiv_within_zero_fun, apply differentiable_const (0 : (E [×m]→L[𝕜] F)) end /-- Constants are `C^∞`. -/ lemma times_cont_diff_const {n : with_top ℕ} {c : F} : times_cont_diff 𝕜 n (λx : E, c) := begin suffices h : times_cont_diff 𝕜 ∞ (λx : E, c), by exact h.of_le le_top, rw times_cont_diff_top_iff_fderiv, refine ⟨differentiable_const c, _⟩, rw fderiv_const, exact times_cont_diff_zero_fun end lemma times_cont_diff_on_const {n : with_top ℕ} {c : F} {s : set E} : times_cont_diff_on 𝕜 n (λx : E, c) s := times_cont_diff_const.times_cont_diff_on lemma times_cont_diff_at_const {n : with_top ℕ} {c : F} : times_cont_diff_at 𝕜 n (λx : E, c) x := times_cont_diff_const.times_cont_diff_at lemma times_cont_diff_within_at_const {n : with_top ℕ} {c : F} : times_cont_diff_within_at 𝕜 n (λx : E, c) s x := times_cont_diff_at_const.times_cont_diff_within_at @[nontriviality] lemma times_cont_diff_of_subsingleton [subsingleton F] {n : with_top ℕ} : times_cont_diff 𝕜 n f := by { rw [subsingleton.elim f (λ _, 0)], exact times_cont_diff_const } @[nontriviality] lemma times_cont_diff_at_of_subsingleton [subsingleton F] {n : with_top ℕ} : times_cont_diff_at 𝕜 n f x := by { rw [subsingleton.elim f (λ _, 0)], exact times_cont_diff_at_const } @[nontriviality] lemma times_cont_diff_within_at_of_subsingleton [subsingleton F] {n : with_top ℕ} : times_cont_diff_within_at 𝕜 n f s x := by { rw [subsingleton.elim f (λ _, 0)], exact times_cont_diff_within_at_const } @[nontriviality] lemma times_cont_diff_on_of_subsingleton [subsingleton F] {n : with_top ℕ} : times_cont_diff_on 𝕜 n f s := by { rw [subsingleton.elim f (λ _, 0)], exact times_cont_diff_on_const } /-! ### Linear functions -/ /-- Unbundled bounded linear functions are `C^∞`. -/ lemma is_bounded_linear_map.times_cont_diff {n : with_top ℕ} (hf : is_bounded_linear_map 𝕜 f) : times_cont_diff 𝕜 n f := begin suffices h : times_cont_diff 𝕜 ∞ f, by exact h.of_le le_top, rw times_cont_diff_top_iff_fderiv, refine ⟨hf.differentiable, _⟩, simp [hf.fderiv], exact times_cont_diff_const end lemma continuous_linear_map.times_cont_diff {n : with_top ℕ} (f : E →L[𝕜] F) : times_cont_diff 𝕜 n f := f.is_bounded_linear_map.times_cont_diff lemma continuous_linear_equiv.times_cont_diff {n : with_top ℕ} (f : E ≃L[𝕜] F) : times_cont_diff 𝕜 n f := (f : E →L[𝕜] F).times_cont_diff lemma linear_isometry_map.times_cont_diff {n : with_top ℕ} (f : E →ₗᵢ[𝕜] F) : times_cont_diff 𝕜 n f := f.to_continuous_linear_map.times_cont_diff lemma linear_isometry_equiv.times_cont_diff {n : with_top ℕ} (f : E ≃ₗᵢ[𝕜] F) : times_cont_diff 𝕜 n f := (f : E →L[𝕜] F).times_cont_diff /-- The first projection in a product is `C^∞`. -/ lemma times_cont_diff_fst {n : with_top ℕ} : times_cont_diff 𝕜 n (prod.fst : E × F → E) := is_bounded_linear_map.times_cont_diff is_bounded_linear_map.fst /-- The first projection on a domain in a product is `C^∞`. -/ lemma times_cont_diff_on_fst {s : set (E×F)} {n : with_top ℕ} : times_cont_diff_on 𝕜 n (prod.fst : E × F → E) s := times_cont_diff.times_cont_diff_on times_cont_diff_fst /-- The first projection at a point in a product is `C^∞`. -/ lemma times_cont_diff_at_fst {p : E × F} {n : with_top ℕ} : times_cont_diff_at 𝕜 n (prod.fst : E × F → E) p := times_cont_diff_fst.times_cont_diff_at /-- The first projection within a domain at a point in a product is `C^∞`. -/ lemma times_cont_diff_within_at_fst {s : set (E × F)} {p : E × F} {n : with_top ℕ} : times_cont_diff_within_at 𝕜 n (prod.fst : E × F → E) s p := times_cont_diff_fst.times_cont_diff_within_at /-- The second projection in a product is `C^∞`. -/ lemma times_cont_diff_snd {n : with_top ℕ} : times_cont_diff 𝕜 n (prod.snd : E × F → F) := is_bounded_linear_map.times_cont_diff is_bounded_linear_map.snd /-- The second projection on a domain in a product is `C^∞`. -/ lemma times_cont_diff_on_snd {s : set (E×F)} {n : with_top ℕ} : times_cont_diff_on 𝕜 n (prod.snd : E × F → F) s := times_cont_diff.times_cont_diff_on times_cont_diff_snd /-- The second projection at a point in a product is `C^∞`. -/ lemma times_cont_diff_at_snd {p : E × F} {n : with_top ℕ} : times_cont_diff_at 𝕜 n (prod.snd : E × F → F) p := times_cont_diff_snd.times_cont_diff_at /-- The second projection within a domain at a point in a product is `C^∞`. -/ lemma times_cont_diff_within_at_snd {s : set (E × F)} {p : E × F} {n : with_top ℕ} : times_cont_diff_within_at 𝕜 n (prod.snd : E × F → F) s p := times_cont_diff_snd.times_cont_diff_within_at /-- The identity is `C^∞`. -/ lemma times_cont_diff_id {n : with_top ℕ} : times_cont_diff 𝕜 n (id : E → E) := is_bounded_linear_map.id.times_cont_diff lemma times_cont_diff_within_at_id {n : with_top ℕ} {s x} : times_cont_diff_within_at 𝕜 n (id : E → E) s x := times_cont_diff_id.times_cont_diff_within_at lemma times_cont_diff_at_id {n : with_top ℕ} {x} : times_cont_diff_at 𝕜 n (id : E → E) x := times_cont_diff_id.times_cont_diff_at lemma times_cont_diff_on_id {n : with_top ℕ} {s} : times_cont_diff_on 𝕜 n (id : E → E) s := times_cont_diff_id.times_cont_diff_on /-- Bilinear functions are `C^∞`. -/ lemma is_bounded_bilinear_map.times_cont_diff {n : with_top ℕ} (hb : is_bounded_bilinear_map 𝕜 b) : times_cont_diff 𝕜 n b := begin suffices h : times_cont_diff 𝕜 ∞ b, by exact h.of_le le_top, rw times_cont_diff_top_iff_fderiv, refine ⟨hb.differentiable, _⟩, simp [hb.fderiv], exact hb.is_bounded_linear_map_deriv.times_cont_diff end /-- If `f` admits a Taylor series `p` in a set `s`, and `g` is linear, then `g ∘ f` admits a Taylor series whose `k`-th term is given by `g ∘ (p k)`. -/ lemma has_ftaylor_series_up_to_on.continuous_linear_map_comp {n : with_top ℕ} (g : F →L[𝕜] G) (hf : has_ftaylor_series_up_to_on n f p s) : has_ftaylor_series_up_to_on n (g ∘ f) (λ x k, g.comp_continuous_multilinear_map (p x k)) s := begin set L : Π m : ℕ, (E [×m]→L[𝕜] F) →L[𝕜] (E [×m]→L[𝕜] G) := λ m, continuous_linear_map.comp_continuous_multilinear_mapL g, split, { exact λ x hx, congr_arg g (hf.zero_eq x hx) }, { intros m hm x hx, convert (L m).has_fderiv_at.comp_has_fderiv_within_at x (hf.fderiv_within m hm x hx) }, { intros m hm, convert (L m).continuous.comp_continuous_on (hf.cont m hm) } end /-- Composition by continuous linear maps on the left preserves `C^n` functions in a domain at a point. -/ lemma times_cont_diff_within_at.continuous_linear_map_comp {n : with_top ℕ} (g : F →L[𝕜] G) (hf : times_cont_diff_within_at 𝕜 n f s x) : times_cont_diff_within_at 𝕜 n (g ∘ f) s x := begin assume m hm, rcases hf m hm with ⟨u, hu, p, hp⟩, exact ⟨u, hu, _, hp.continuous_linear_map_comp g⟩, end /-- Composition by continuous linear maps on the left preserves `C^n` functions in a domain at a point. -/ lemma times_cont_diff_at.continuous_linear_map_comp {n : with_top ℕ} (g : F →L[𝕜] G) (hf : times_cont_diff_at 𝕜 n f x) : times_cont_diff_at 𝕜 n (g ∘ f) x := times_cont_diff_within_at.continuous_linear_map_comp g hf /-- Composition by continuous linear maps on the left preserves `C^n` functions on domains. -/ lemma times_cont_diff_on.continuous_linear_map_comp {n : with_top ℕ} (g : F →L[𝕜] G) (hf : times_cont_diff_on 𝕜 n f s) : times_cont_diff_on 𝕜 n (g ∘ f) s := λ x hx, (hf x hx).continuous_linear_map_comp g /-- Composition by continuous linear maps on the left preserves `C^n` functions. -/ lemma times_cont_diff.continuous_linear_map_comp {n : with_top ℕ} {f : E → F} (g : F →L[𝕜] G) (hf : times_cont_diff 𝕜 n f) : times_cont_diff 𝕜 n (λx, g (f x)) := times_cont_diff_on_univ.1 $ times_cont_diff_on.continuous_linear_map_comp _ (times_cont_diff_on_univ.2 hf) /-- Composition by continuous linear equivs on the left respects higher differentiability on domains. -/ lemma continuous_linear_equiv.comp_times_cont_diff_within_at_iff {n : with_top ℕ} (e : F ≃L[𝕜] G) : times_cont_diff_within_at 𝕜 n (e ∘ f) s x ↔ times_cont_diff_within_at 𝕜 n f s x := begin split, { assume H, have : f = e.symm ∘ (e ∘ f), by { ext y, simp only [function.comp_app], rw e.symm_apply_apply (f y) }, rw this, exact H.continuous_linear_map_comp _ }, { assume H, exact H.continuous_linear_map_comp _ } end /-- Composition by continuous linear equivs on the left respects higher differentiability on domains. -/ lemma continuous_linear_equiv.comp_times_cont_diff_on_iff {n : with_top ℕ} (e : F ≃L[𝕜] G) : times_cont_diff_on 𝕜 n (e ∘ f) s ↔ times_cont_diff_on 𝕜 n f s := by simp [times_cont_diff_on, e.comp_times_cont_diff_within_at_iff] /-- If `f` admits a Taylor series `p` in a set `s`, and `g` is linear, then `f ∘ g` admits a Taylor series in `g ⁻¹' s`, whose `k`-th term is given by `p k (g v₁, ..., g vₖ)` . -/ lemma has_ftaylor_series_up_to_on.comp_continuous_linear_map {n : with_top ℕ} (hf : has_ftaylor_series_up_to_on n f p s) (g : G →L[𝕜] E) : has_ftaylor_series_up_to_on n (f ∘ g) (λ x k, (p (g x) k).comp_continuous_linear_map (λ _, g)) (g ⁻¹' s) := begin let A : Π m : ℕ, (E [×m]→L[𝕜] F) → (G [×m]→L[𝕜] F) := λ m h, h.comp_continuous_linear_map (λ _, g), have hA : ∀ m, is_bounded_linear_map 𝕜 (A m) := λ m, is_bounded_linear_map_continuous_multilinear_map_comp_linear g, split, { assume x hx, simp only [(hf.zero_eq (g x) hx).symm, function.comp_app], change p (g x) 0 (λ (i : fin 0), g 0) = p (g x) 0 0, rw continuous_linear_map.map_zero, refl }, { assume m hm x hx, convert ((hA m).has_fderiv_at).comp_has_fderiv_within_at x ((hf.fderiv_within m hm (g x) hx).comp x (g.has_fderiv_within_at) (subset.refl _)), ext y v, change p (g x) (nat.succ m) (g ∘ (cons y v)) = p (g x) m.succ (cons (g y) (g ∘ v)), rw comp_cons }, { assume m hm, exact (hA m).continuous.comp_continuous_on ((hf.cont m hm).comp g.continuous.continuous_on (subset.refl _)) } end /-- Composition by continuous linear maps on the right preserves `C^n` functions at a point on a domain. -/ lemma times_cont_diff_within_at.comp_continuous_linear_map {n : with_top ℕ} {x : G} (g : G →L[𝕜] E) (hf : times_cont_diff_within_at 𝕜 n f s (g x)) : times_cont_diff_within_at 𝕜 n (f ∘ g) (g ⁻¹' s) x := begin assume m hm, rcases hf m hm with ⟨u, hu, p, hp⟩, refine ⟨g ⁻¹' u, _, _, hp.comp_continuous_linear_map g⟩, apply continuous_within_at.preimage_mem_nhds_within', { exact g.continuous.continuous_within_at }, { apply nhds_within_mono (g x) _ hu, rw image_insert_eq, exact insert_subset_insert (image_preimage_subset g s) } end /-- Composition by continuous linear maps on the right preserves `C^n` functions on domains. -/ lemma times_cont_diff_on.comp_continuous_linear_map {n : with_top ℕ} (hf : times_cont_diff_on 𝕜 n f s) (g : G →L[𝕜] E) : times_cont_diff_on 𝕜 n (f ∘ g) (g ⁻¹' s) := λ x hx, (hf (g x) hx).comp_continuous_linear_map g /-- Composition by continuous linear maps on the right preserves `C^n` functions. -/ lemma times_cont_diff.comp_continuous_linear_map {n : with_top ℕ} {f : E → F} {g : G →L[𝕜] E} (hf : times_cont_diff 𝕜 n f) : times_cont_diff 𝕜 n (f ∘ g) := times_cont_diff_on_univ.1 $ times_cont_diff_on.comp_continuous_linear_map (times_cont_diff_on_univ.2 hf) _ /-- Composition by continuous linear equivs on the right respects higher differentiability at a point in a domain. -/ lemma continuous_linear_equiv.times_cont_diff_within_at_comp_iff {n : with_top ℕ} (e : G ≃L[𝕜] E) : times_cont_diff_within_at 𝕜 n (f ∘ e) (e ⁻¹' s) (e.symm x) ↔ times_cont_diff_within_at 𝕜 n f s x := begin split, { assume H, have A : f = (f ∘ e) ∘ e.symm, by { ext y, simp only [function.comp_app], rw e.apply_symm_apply y }, have B : e.symm ⁻¹' (e ⁻¹' s) = s, by { rw [← preimage_comp, e.self_comp_symm], refl }, rw [A, ← B], exact H.comp_continuous_linear_map _}, { assume H, have : x = e (e.symm x), by simp, rw this at H, exact H.comp_continuous_linear_map _ }, end /-- Composition by continuous linear equivs on the right respects higher differentiability on domains. -/ lemma continuous_linear_equiv.times_cont_diff_on_comp_iff {n : with_top ℕ} (e : G ≃L[𝕜] E) : times_cont_diff_on 𝕜 n (f ∘ e) (e ⁻¹' s) ↔ times_cont_diff_on 𝕜 n f s := begin refine ⟨λ H, _, λ H, H.comp_continuous_linear_map _⟩, have A : f = (f ∘ e) ∘ e.symm, by { ext y, simp only [function.comp_app], rw e.apply_symm_apply y }, have B : e.symm ⁻¹' (e ⁻¹' s) = s, by { rw [← preimage_comp, e.self_comp_symm], refl }, rw [A, ← B], exact H.comp_continuous_linear_map _ end /-- If two functions `f` and `g` admit Taylor series `p` and `q` in a set `s`, then the cartesian product of `f` and `g` admits the cartesian product of `p` and `q` as a Taylor series. -/ lemma has_ftaylor_series_up_to_on.prod {n : with_top ℕ} (hf : has_ftaylor_series_up_to_on n f p s) {g : E → G} {q : E → formal_multilinear_series 𝕜 E G} (hg : has_ftaylor_series_up_to_on n g q s) : has_ftaylor_series_up_to_on n (λ y, (f y, g y)) (λ y k, (p y k).prod (q y k)) s := begin set L := λ m, continuous_multilinear_map.prodL 𝕜 (λ i : fin m, E) F G, split, { assume x hx, rw [← hf.zero_eq x hx, ← hg.zero_eq x hx], refl }, { assume m hm x hx, convert (L m).has_fderiv_at.comp_has_fderiv_within_at x ((hf.fderiv_within m hm x hx).prod (hg.fderiv_within m hm x hx)) }, { assume m hm, exact (L m).continuous.comp_continuous_on ((hf.cont m hm).prod (hg.cont m hm)) } end /-- The cartesian product of `C^n` functions at a point in a domain is `C^n`. -/ lemma times_cont_diff_within_at.prod {n : with_top ℕ} {s : set E} {f : E → F} {g : E → G} (hf : times_cont_diff_within_at 𝕜 n f s x) (hg : times_cont_diff_within_at 𝕜 n g s x) : times_cont_diff_within_at 𝕜 n (λx:E, (f x, g x)) s x := begin assume m hm, rcases hf m hm with ⟨u, hu, p, hp⟩, rcases hg m hm with ⟨v, hv, q, hq⟩, exact ⟨u ∩ v, filter.inter_mem hu hv, _, (hp.mono (inter_subset_left u v)).prod (hq.mono (inter_subset_right u v))⟩ end /-- The cartesian product of `C^n` functions on domains is `C^n`. -/ lemma times_cont_diff_on.prod {n : with_top ℕ} {s : set E} {f : E → F} {g : E → G} (hf : times_cont_diff_on 𝕜 n f s) (hg : times_cont_diff_on 𝕜 n g s) : times_cont_diff_on 𝕜 n (λx:E, (f x, g x)) s := λ x hx, (hf x hx).prod (hg x hx) /-- The cartesian product of `C^n` functions at a point is `C^n`. -/ lemma times_cont_diff_at.prod {n : with_top ℕ} {f : E → F} {g : E → G} (hf : times_cont_diff_at 𝕜 n f x) (hg : times_cont_diff_at 𝕜 n g x) : times_cont_diff_at 𝕜 n (λx:E, (f x, g x)) x := times_cont_diff_within_at_univ.1 $ times_cont_diff_within_at.prod (times_cont_diff_within_at_univ.2 hf) (times_cont_diff_within_at_univ.2 hg) /-- The cartesian product of `C^n` functions is `C^n`. -/ lemma times_cont_diff.prod {n : with_top ℕ} {f : E → F} {g : E → G} (hf : times_cont_diff 𝕜 n f) (hg : times_cont_diff 𝕜 n g) : times_cont_diff 𝕜 n (λx:E, (f x, g x)) := times_cont_diff_on_univ.1 $ times_cont_diff_on.prod (times_cont_diff_on_univ.2 hf) (times_cont_diff_on_univ.2 hg) /-! ### Smoothness of functions `f : E → Π i, F' i` -/ section pi variables {ι : Type*} [fintype ι] {F' : ι → Type*} [Π i, normed_group (F' i)] [Π i, normed_space 𝕜 (F' i)] {φ : Π i, E → F' i} {p' : Π i, E → formal_multilinear_series 𝕜 E (F' i)} {Φ : E → Π i, F' i} {P' : E → formal_multilinear_series 𝕜 E (Π i, F' i)} {n : with_top ℕ} lemma has_ftaylor_series_up_to_on_pi : has_ftaylor_series_up_to_on n (λ x i, φ i x) (λ x m, continuous_multilinear_map.pi (λ i, p' i x m)) s ↔ ∀ i, has_ftaylor_series_up_to_on n (φ i) (p' i) s := begin set pr := @continuous_linear_map.proj 𝕜 _ ι F' _ _ _, letI : Π (m : ℕ) (i : ι), normed_space 𝕜 (E [×m]→L[𝕜] (F' i)) := λ m i, infer_instance, set L : Π m : ℕ, (Π i, E [×m]→L[𝕜] (F' i)) ≃ₗᵢ[𝕜] (E [×m]→L[𝕜] (Π i, F' i)) := λ m, continuous_multilinear_map.piₗᵢ _ _, refine ⟨λ h i, _, λ h, ⟨λ x hx, _, _, _⟩⟩, { convert h.continuous_linear_map_comp (pr i), ext, refl }, { ext1 i, exact (h i).zero_eq x hx }, { intros m hm x hx, have := has_fderiv_within_at_pi.2 (λ i, (h i).fderiv_within m hm x hx), convert (L m).has_fderiv_at.comp_has_fderiv_within_at x this }, { intros m hm, have := continuous_on_pi.2 (λ i, (h i).cont m hm), convert (L m).continuous.comp_continuous_on this } end @[simp] lemma has_ftaylor_series_up_to_on_pi' : has_ftaylor_series_up_to_on n Φ P' s ↔ ∀ i, has_ftaylor_series_up_to_on n (λ x, Φ x i) (λ x m, (@continuous_linear_map.proj 𝕜 _ ι F' _ _ _ i).comp_continuous_multilinear_map (P' x m)) s := by { convert has_ftaylor_series_up_to_on_pi, ext, refl } lemma times_cont_diff_within_at_pi : times_cont_diff_within_at 𝕜 n Φ s x ↔ ∀ i, times_cont_diff_within_at 𝕜 n (λ x, Φ x i) s x := begin set pr := @continuous_linear_map.proj 𝕜 _ ι F' _ _ _, refine ⟨λ h i, h.continuous_linear_map_comp (pr i), λ h m hm, _⟩, choose u hux p hp using λ i, h i m hm, exact ⟨⋂ i, u i, filter.Inter_mem.2 hux, _, has_ftaylor_series_up_to_on_pi.2 (λ i, (hp i).mono $ Inter_subset _ _)⟩, end lemma times_cont_diff_on_pi : times_cont_diff_on 𝕜 n Φ s ↔ ∀ i, times_cont_diff_on 𝕜 n (λ x, Φ x i) s := ⟨λ h i x hx, times_cont_diff_within_at_pi.1 (h x hx) _, λ h x hx, times_cont_diff_within_at_pi.2 (λ i, h i x hx)⟩ lemma times_cont_diff_at_pi : times_cont_diff_at 𝕜 n Φ x ↔ ∀ i, times_cont_diff_at 𝕜 n (λ x, Φ x i) x := times_cont_diff_within_at_pi lemma times_cont_diff_pi : times_cont_diff 𝕜 n Φ ↔ ∀ i, times_cont_diff 𝕜 n (λ x, Φ x i) := by simp only [← times_cont_diff_on_univ, times_cont_diff_on_pi] end pi /-! ### Composition of `C^n` functions We show that the composition of `C^n` functions is `C^n`. One way to prove it would be to write the `n`-th derivative of the composition (this is Faà di Bruno's formula) and check its continuity, but this is very painful. Instead, we go for a simple inductive proof. Assume it is done for `n`. Then, to check it for `n+1`, one needs to check that the derivative of `g ∘ f` is `C^n`, i.e., that `Dg(f x) ⬝ Df(x)` is `C^n`. The term `Dg (f x)` is the composition of two `C^n` functions, so it is `C^n` by the inductive assumption. The term `Df(x)` is also `C^n`. Then, the matrix multiplication is the application of a bilinear map (which is `C^∞`, and therefore `C^n`) to `x ↦ (Dg(f x), Df x)`. As the composition of two `C^n` maps, it is again `C^n`, and we are done. There is a subtlety in this argument: we apply the inductive assumption to functions on other Banach spaces. In maths, one would say: prove by induction over `n` that, for all `C^n` maps between all pairs of Banach spaces, their composition is `C^n`. In Lean, this is fine as long as the spaces stay in the same universe. This is not the case in the above argument: if `E` lives in universe `u` and `F` lives in universe `v`, then linear maps from `E` to `F` (to which the derivative of `f` belongs) is in universe `max u v`. If one could quantify over finitely many universes, the above proof would work fine, but this is not the case. One could still write the proof considering spaces in any universe in `u, v, w, max u v, max v w, max u v w`, but it would be extremely tedious and lead to a lot of duplication. Instead, we formulate the above proof when all spaces live in the same universe (where everything is fine), and then we deduce the general result by lifting all our spaces to a common universe. We use the trick that any space `H` is isomorphic through a continuous linear equiv to `continuous_multilinear_map (λ (i : fin 0), E × F × G) H` to change the universe level, and then argue that composing with such a linear equiv does not change the fact of being `C^n`, which we have already proved previously. -/ /-- Auxiliary lemma proving that the composition of `C^n` functions on domains is `C^n` when all spaces live in the same universe. Use instead `times_cont_diff_on.comp` which removes the universe assumption (but is deduced from this one). -/ private lemma times_cont_diff_on.comp_same_univ {Eu : Type u} [normed_group Eu] [normed_space 𝕜 Eu] {Fu : Type u} [normed_group Fu] [normed_space 𝕜 Fu] {Gu : Type u} [normed_group Gu] [normed_space 𝕜 Gu] {n : with_top ℕ} {s : set Eu} {t : set Fu} {g : Fu → Gu} {f : Eu → Fu} (hg : times_cont_diff_on 𝕜 n g t) (hf : times_cont_diff_on 𝕜 n f s) (st : s ⊆ f ⁻¹' t) : times_cont_diff_on 𝕜 n (g ∘ f) s := begin unfreezingI { induction n using with_top.nat_induction with n IH Itop generalizing Eu Fu Gu }, { rw times_cont_diff_on_zero at hf hg ⊢, exact continuous_on.comp hg hf st }, { rw times_cont_diff_on_succ_iff_has_fderiv_within_at at hg ⊢, assume x hx, rcases (times_cont_diff_on_succ_iff_has_fderiv_within_at.1 hf) x hx with ⟨u, hu, f', hf', f'_diff⟩, rcases hg (f x) (st hx) with ⟨v, hv, g', hg', g'_diff⟩, rw insert_eq_of_mem hx at hu ⊢, have xu : x ∈ u := mem_of_mem_nhds_within hx hu, let w := s ∩ (u ∩ f⁻¹' v), have wv : w ⊆ f ⁻¹' v := λ y hy, hy.2.2, have wu : w ⊆ u := λ y hy, hy.2.1, have ws : w ⊆ s := λ y hy, hy.1, refine ⟨w, _, λ y, (g' (f y)).comp (f' y), _, _⟩, show w ∈ 𝓝[s] x, { apply filter.inter_mem self_mem_nhds_within, apply filter.inter_mem hu, apply continuous_within_at.preimage_mem_nhds_within', { rw ← continuous_within_at_inter' hu, exact (hf' x xu).differentiable_within_at.continuous_within_at.mono (inter_subset_right _ _) }, { apply nhds_within_mono _ _ hv, exact subset.trans (image_subset_iff.mpr st) (subset_insert (f x) t) } }, show ∀ y ∈ w, has_fderiv_within_at (g ∘ f) ((g' (f y)).comp (f' y)) w y, { rintros y ⟨ys, yu, yv⟩, exact (hg' (f y) yv).comp y ((hf' y yu).mono wu) wv }, show times_cont_diff_on 𝕜 n (λ y, (g' (f y)).comp (f' y)) w, { have A : times_cont_diff_on 𝕜 n (λ y, g' (f y)) w := IH g'_diff ((hf.of_le (with_top.coe_le_coe.2 (nat.le_succ n))).mono ws) wv, have B : times_cont_diff_on 𝕜 n f' w := f'_diff.mono wu, have C : times_cont_diff_on 𝕜 n (λ y, (f' y, g' (f y))) w := times_cont_diff_on.prod B A, have D : times_cont_diff_on 𝕜 n (λ(p : (Eu →L[𝕜] Fu) × (Fu →L[𝕜] Gu)), p.2.comp p.1) univ := is_bounded_bilinear_map_comp.times_cont_diff.times_cont_diff_on, exact IH D C (subset_univ _) } }, { rw times_cont_diff_on_top at hf hg ⊢, assume n, apply Itop n (hg n) (hf n) st } end /-- The composition of `C^n` functions on domains is `C^n`. -/ lemma times_cont_diff_on.comp {n : with_top ℕ} {s : set E} {t : set F} {g : F → G} {f : E → F} (hg : times_cont_diff_on 𝕜 n g t) (hf : times_cont_diff_on 𝕜 n f s) (st : s ⊆ f ⁻¹' t) : times_cont_diff_on 𝕜 n (g ∘ f) s := begin /- we lift all the spaces to a common universe, as we have already proved the result in this situation. For the lift, we use the trick that `H` is isomorphic through a continuous linear equiv to `continuous_multilinear_map 𝕜 (λ (i : fin 0), (E × F × G)) H`, and continuous linear equivs respect smoothness classes. -/ let Eu := continuous_multilinear_map 𝕜 (λ (i : fin 0), (E × F × G)) E, letI : normed_group Eu := by apply_instance, letI : normed_space 𝕜 Eu := by apply_instance, let Fu := continuous_multilinear_map 𝕜 (λ (i : fin 0), (E × F × G)) F, letI : normed_group Fu := by apply_instance, letI : normed_space 𝕜 Fu := by apply_instance, let Gu := continuous_multilinear_map 𝕜 (λ (i : fin 0), (E × F × G)) G, letI : normed_group Gu := by apply_instance, letI : normed_space 𝕜 Gu := by apply_instance, -- declare the isomorphisms let isoE : Eu ≃L[𝕜] E := continuous_multilinear_curry_fin0 𝕜 (E × F × G) E, let isoF : Fu ≃L[𝕜] F := continuous_multilinear_curry_fin0 𝕜 (E × F × G) F, let isoG : Gu ≃L[𝕜] G := continuous_multilinear_curry_fin0 𝕜 (E × F × G) G, -- lift the functions to the new spaces, check smoothness there, and then go back. let fu : Eu → Fu := (isoF.symm ∘ f) ∘ isoE, have fu_diff : times_cont_diff_on 𝕜 n fu (isoE ⁻¹' s), by rwa [isoE.times_cont_diff_on_comp_iff, isoF.symm.comp_times_cont_diff_on_iff], let gu : Fu → Gu := (isoG.symm ∘ g) ∘ isoF, have gu_diff : times_cont_diff_on 𝕜 n gu (isoF ⁻¹' t), by rwa [isoF.times_cont_diff_on_comp_iff, isoG.symm.comp_times_cont_diff_on_iff], have main : times_cont_diff_on 𝕜 n (gu ∘ fu) (isoE ⁻¹' s), { apply times_cont_diff_on.comp_same_univ gu_diff fu_diff, assume y hy, simp only [fu, continuous_linear_equiv.coe_apply, function.comp_app, mem_preimage], rw isoF.apply_symm_apply (f (isoE y)), exact st hy }, have : gu ∘ fu = (isoG.symm ∘ (g ∘ f)) ∘ isoE, { ext y, simp only [function.comp_apply, gu, fu], rw isoF.apply_symm_apply (f (isoE y)) }, rwa [this, isoE.times_cont_diff_on_comp_iff, isoG.symm.comp_times_cont_diff_on_iff] at main end /-- The composition of `C^n` functions on domains is `C^n`. -/ lemma times_cont_diff_on.comp' {n : with_top ℕ} {s : set E} {t : set F} {g : F → G} {f : E → F} (hg : times_cont_diff_on 𝕜 n g t) (hf : times_cont_diff_on 𝕜 n f s) : times_cont_diff_on 𝕜 n (g ∘ f) (s ∩ f⁻¹' t) := hg.comp (hf.mono (inter_subset_left _ _)) (inter_subset_right _ _) /-- The composition of a `C^n` function on a domain with a `C^n` function is `C^n`. -/ lemma times_cont_diff.comp_times_cont_diff_on {n : with_top ℕ} {s : set E} {g : F → G} {f : E → F} (hg : times_cont_diff 𝕜 n g) (hf : times_cont_diff_on 𝕜 n f s) : times_cont_diff_on 𝕜 n (g ∘ f) s := (times_cont_diff_on_univ.2 hg).comp hf subset_preimage_univ /-- The composition of `C^n` functions is `C^n`. -/ lemma times_cont_diff.comp {n : with_top ℕ} {g : F → G} {f : E → F} (hg : times_cont_diff 𝕜 n g) (hf : times_cont_diff 𝕜 n f) : times_cont_diff 𝕜 n (g ∘ f) := times_cont_diff_on_univ.1 $ times_cont_diff_on.comp (times_cont_diff_on_univ.2 hg) (times_cont_diff_on_univ.2 hf) (subset_univ _) /-- The composition of `C^n` functions at points in domains is `C^n`. -/ lemma times_cont_diff_within_at.comp {n : with_top ℕ} {s : set E} {t : set F} {g : F → G} {f : E → F} (x : E) (hg : times_cont_diff_within_at 𝕜 n g t (f x)) (hf : times_cont_diff_within_at 𝕜 n f s x) (st : s ⊆ f ⁻¹' t) : times_cont_diff_within_at 𝕜 n (g ∘ f) s x := begin assume m hm, rcases hg.times_cont_diff_on hm with ⟨u, u_nhd, ut, hu⟩, rcases hf.times_cont_diff_on hm with ⟨v, v_nhd, vs, hv⟩, have xmem : x ∈ f ⁻¹' u ∩ v := ⟨(mem_of_mem_nhds_within (mem_insert (f x) _) u_nhd : _), mem_of_mem_nhds_within (mem_insert x s) v_nhd⟩, have : f ⁻¹' u ∈ 𝓝[insert x s] x, { apply hf.continuous_within_at.insert_self.preimage_mem_nhds_within', apply nhds_within_mono _ _ u_nhd, rw image_insert_eq, exact insert_subset_insert (image_subset_iff.mpr st) }, have Z := ((hu.comp (hv.mono (inter_subset_right (f ⁻¹' u) v)) (inter_subset_left _ _)) .times_cont_diff_within_at) xmem m (le_refl _), have : 𝓝[f ⁻¹' u ∩ v] x = 𝓝[insert x s] x, { have A : f ⁻¹' u ∩ v = (insert x s) ∩ (f ⁻¹' u ∩ v), { apply subset.antisymm _ (inter_subset_right _ _), rintros y ⟨hy1, hy2⟩, simp [hy1, hy2, vs hy2] }, rw [A, ← nhds_within_restrict''], exact filter.inter_mem this v_nhd }, rwa [insert_eq_of_mem xmem, this] at Z, end /-- The composition of `C^n` functions at points in domains is `C^n`. -/ lemma times_cont_diff_within_at.comp' {n : with_top ℕ} {s : set E} {t : set F} {g : F → G} {f : E → F} (x : E) (hg : times_cont_diff_within_at 𝕜 n g t (f x)) (hf : times_cont_diff_within_at 𝕜 n f s x) : times_cont_diff_within_at 𝕜 n (g ∘ f) (s ∩ f⁻¹' t) x := hg.comp x (hf.mono (inter_subset_left _ _)) (inter_subset_right _ _) lemma times_cont_diff_at.comp_times_cont_diff_within_at {n} (x : E) (hg : times_cont_diff_at 𝕜 n g (f x)) (hf : times_cont_diff_within_at 𝕜 n f s x) : times_cont_diff_within_at 𝕜 n (g ∘ f) s x := hg.comp x hf (maps_to_univ _ _) /-- The composition of `C^n` functions at points is `C^n`. -/ lemma times_cont_diff_at.comp {n : with_top ℕ} (x : E) (hg : times_cont_diff_at 𝕜 n g (f x)) (hf : times_cont_diff_at 𝕜 n f x) : times_cont_diff_at 𝕜 n (g ∘ f) x := hg.comp x hf subset_preimage_univ lemma times_cont_diff.comp_times_cont_diff_within_at {n : with_top ℕ} {g : F → G} {f : E → F} (h : times_cont_diff 𝕜 n g) (hf : times_cont_diff_within_at 𝕜 n f t x) : times_cont_diff_within_at 𝕜 n (g ∘ f) t x := begin have : times_cont_diff_within_at 𝕜 n g univ (f x) := h.times_cont_diff_at.times_cont_diff_within_at, exact this.comp x hf (subset_univ _), end lemma times_cont_diff.comp_times_cont_diff_at {n : with_top ℕ} {g : F → G} {f : E → F} (x : E) (hg : times_cont_diff 𝕜 n g) (hf : times_cont_diff_at 𝕜 n f x) : times_cont_diff_at 𝕜 n (g ∘ f) x := hg.comp_times_cont_diff_within_at hf /-- The bundled derivative of a `C^{n+1}` function is `C^n`. -/ lemma times_cont_diff_on_fderiv_within_apply {m n : with_top ℕ} {s : set E} {f : E → F} (hf : times_cont_diff_on 𝕜 n f s) (hs : unique_diff_on 𝕜 s) (hmn : m + 1 ≤ n) : times_cont_diff_on 𝕜 m (λp : E × E, (fderiv_within 𝕜 f s p.1 : E →L[𝕜] F) p.2) (set.prod s (univ : set E)) := begin have A : times_cont_diff 𝕜 m (λp : (E →L[𝕜] F) × E, p.1 p.2), { apply is_bounded_bilinear_map.times_cont_diff, exact is_bounded_bilinear_map_apply }, have B : times_cont_diff_on 𝕜 m (λ (p : E × E), ((fderiv_within 𝕜 f s p.fst), p.snd)) (set.prod s univ), { apply times_cont_diff_on.prod _ _, { have I : times_cont_diff_on 𝕜 m (λ (x : E), fderiv_within 𝕜 f s x) s := hf.fderiv_within hs hmn, have J : times_cont_diff_on 𝕜 m (λ (x : E × E), x.1) (set.prod s univ) := times_cont_diff_fst.times_cont_diff_on, exact times_cont_diff_on.comp I J (prod_subset_preimage_fst _ _) }, { apply times_cont_diff.times_cont_diff_on _ , apply is_bounded_linear_map.snd.times_cont_diff } }, exact A.comp_times_cont_diff_on B end /-- The bundled derivative of a `C^{n+1}` function is `C^n`. -/ lemma times_cont_diff.times_cont_diff_fderiv_apply {n m : with_top ℕ} {f : E → F} (hf : times_cont_diff 𝕜 n f) (hmn : m + 1 ≤ n) : times_cont_diff 𝕜 m (λp : E × E, (fderiv 𝕜 f p.1 : E →L[𝕜] F) p.2) := begin rw ← times_cont_diff_on_univ at ⊢ hf, rw [← fderiv_within_univ, ← univ_prod_univ], exact times_cont_diff_on_fderiv_within_apply hf unique_diff_on_univ hmn end /-! ### Sum of two functions -/ /- The sum is smooth. -/ lemma times_cont_diff_add {n : with_top ℕ} : times_cont_diff 𝕜 n (λp : F × F, p.1 + p.2) := (is_bounded_linear_map.fst.add is_bounded_linear_map.snd).times_cont_diff /-- The sum of two `C^n` functions within a set at a point is `C^n` within this set at this point. -/ lemma times_cont_diff_within_at.add {n : with_top ℕ} {s : set E} {f g : E → F} (hf : times_cont_diff_within_at 𝕜 n f s x) (hg : times_cont_diff_within_at 𝕜 n g s x) : times_cont_diff_within_at 𝕜 n (λx, f x + g x) s x := times_cont_diff_add.times_cont_diff_within_at.comp x (hf.prod hg) subset_preimage_univ /-- The sum of two `C^n` functions at a point is `C^n` at this point. -/ lemma times_cont_diff_at.add {n : with_top ℕ} {f g : E → F} (hf : times_cont_diff_at 𝕜 n f x) (hg : times_cont_diff_at 𝕜 n g x) : times_cont_diff_at 𝕜 n (λx, f x + g x) x := by rw [← times_cont_diff_within_at_univ] at *; exact hf.add hg /-- The sum of two `C^n`functions is `C^n`. -/ lemma times_cont_diff.add {n : with_top ℕ} {f g : E → F} (hf : times_cont_diff 𝕜 n f) (hg : times_cont_diff 𝕜 n g) : times_cont_diff 𝕜 n (λx, f x + g x) := times_cont_diff_add.comp (hf.prod hg) /-- The sum of two `C^n` functions on a domain is `C^n`. -/ lemma times_cont_diff_on.add {n : with_top ℕ} {s : set E} {f g : E → F} (hf : times_cont_diff_on 𝕜 n f s) (hg : times_cont_diff_on 𝕜 n g s) : times_cont_diff_on 𝕜 n (λx, f x + g x) s := λ x hx, (hf x hx).add (hg x hx) /-! ### Negative -/ /- The negative is smooth. -/ lemma times_cont_diff_neg {n : with_top ℕ} : times_cont_diff 𝕜 n (λp : F, -p) := is_bounded_linear_map.id.neg.times_cont_diff /-- The negative of a `C^n` function within a domain at a point is `C^n` within this domain at this point. -/ lemma times_cont_diff_within_at.neg {n : with_top ℕ} {s : set E} {f : E → F} (hf : times_cont_diff_within_at 𝕜 n f s x) : times_cont_diff_within_at 𝕜 n (λx, -f x) s x := times_cont_diff_neg.times_cont_diff_within_at.comp x hf subset_preimage_univ /-- The negative of a `C^n` function at a point is `C^n` at this point. -/ lemma times_cont_diff_at.neg {n : with_top ℕ} {f : E → F} (hf : times_cont_diff_at 𝕜 n f x) : times_cont_diff_at 𝕜 n (λx, -f x) x := by rw ← times_cont_diff_within_at_univ at *; exact hf.neg /-- The negative of a `C^n`function is `C^n`. -/ lemma times_cont_diff.neg {n : with_top ℕ} {f : E → F} (hf : times_cont_diff 𝕜 n f) : times_cont_diff 𝕜 n (λx, -f x) := times_cont_diff_neg.comp hf /-- The negative of a `C^n` function on a domain is `C^n`. -/ lemma times_cont_diff_on.neg {n : with_top ℕ} {s : set E} {f : E → F} (hf : times_cont_diff_on 𝕜 n f s) : times_cont_diff_on 𝕜 n (λx, -f x) s := λ x hx, (hf x hx).neg /-! ### Subtraction -/ /-- The difference of two `C^n` functions within a set at a point is `C^n` within this set at this point. -/ lemma times_cont_diff_within_at.sub {n : with_top ℕ} {s : set E} {f g : E → F} (hf : times_cont_diff_within_at 𝕜 n f s x) (hg : times_cont_diff_within_at 𝕜 n g s x) : times_cont_diff_within_at 𝕜 n (λx, f x - g x) s x := by simpa only [sub_eq_add_neg] using hf.add hg.neg /-- The difference of two `C^n` functions at a point is `C^n` at this point. -/ lemma times_cont_diff_at.sub {n : with_top ℕ} {f g : E → F} (hf : times_cont_diff_at 𝕜 n f x) (hg : times_cont_diff_at 𝕜 n g x) : times_cont_diff_at 𝕜 n (λx, f x - g x) x := by simpa only [sub_eq_add_neg] using hf.add hg.neg /-- The difference of two `C^n` functions on a domain is `C^n`. -/ lemma times_cont_diff_on.sub {n : with_top ℕ} {s : set E} {f g : E → F} (hf : times_cont_diff_on 𝕜 n f s) (hg : times_cont_diff_on 𝕜 n g s) : times_cont_diff_on 𝕜 n (λx, f x - g x) s := by simpa only [sub_eq_add_neg] using hf.add hg.neg /-- The difference of two `C^n` functions is `C^n`. -/ lemma times_cont_diff.sub {n : with_top ℕ} {f g : E → F} (hf : times_cont_diff 𝕜 n f) (hg : times_cont_diff 𝕜 n g) : times_cont_diff 𝕜 n (λx, f x - g x) := by simpa only [sub_eq_add_neg] using hf.add hg.neg /-! ### Sum of finitely many functions -/ lemma times_cont_diff_within_at.sum {ι : Type*} {f : ι → E → F} {s : finset ι} {n : with_top ℕ} {t : set E} {x : E} (h : ∀ i ∈ s, times_cont_diff_within_at 𝕜 n (λ x, f i x) t x) : times_cont_diff_within_at 𝕜 n (λ x, (∑ i in s, f i x)) t x := begin classical, induction s using finset.induction_on with i s is IH, { simp [times_cont_diff_within_at_const] }, { simp only [is, finset.sum_insert, not_false_iff], exact (h _ (finset.mem_insert_self i s)).add (IH (λ j hj, h _ (finset.mem_insert_of_mem hj))) } end lemma times_cont_diff_at.sum {ι : Type*} {f : ι → E → F} {s : finset ι} {n : with_top ℕ} {x : E} (h : ∀ i ∈ s, times_cont_diff_at 𝕜 n (λ x, f i x) x) : times_cont_diff_at 𝕜 n (λ x, (∑ i in s, f i x)) x := by rw [← times_cont_diff_within_at_univ] at *; exact times_cont_diff_within_at.sum h lemma times_cont_diff_on.sum {ι : Type*} {f : ι → E → F} {s : finset ι} {n : with_top ℕ} {t : set E} (h : ∀ i ∈ s, times_cont_diff_on 𝕜 n (λ x, f i x) t) : times_cont_diff_on 𝕜 n (λ x, (∑ i in s, f i x)) t := λ x hx, times_cont_diff_within_at.sum (λ i hi, h i hi x hx) lemma times_cont_diff.sum {ι : Type*} {f : ι → E → F} {s : finset ι} {n : with_top ℕ} (h : ∀ i ∈ s, times_cont_diff 𝕜 n (λ x, f i x)) : times_cont_diff 𝕜 n (λ x, (∑ i in s, f i x)) := by simp [← times_cont_diff_on_univ] at *; exact times_cont_diff_on.sum h /-! ### Product of two functions -/ /- The product is smooth. -/ lemma times_cont_diff_mul {n : with_top ℕ} : times_cont_diff 𝕜 n (λ p : 𝕜 × 𝕜, p.1 * p.2) := is_bounded_bilinear_map_mul.times_cont_diff /-- The product of two `C^n` functions within a set at a point is `C^n` within this set at this point. -/ lemma times_cont_diff_within_at.mul {n : with_top ℕ} {s : set E} {f g : E → 𝕜} (hf : times_cont_diff_within_at 𝕜 n f s x) (hg : times_cont_diff_within_at 𝕜 n g s x) : times_cont_diff_within_at 𝕜 n (λ x, f x * g x) s x := times_cont_diff_mul.times_cont_diff_within_at.comp x (hf.prod hg) subset_preimage_univ /-- The product of two `C^n` functions at a point is `C^n` at this point. -/ lemma times_cont_diff_at.mul {n : with_top ℕ} {f g : E → 𝕜} (hf : times_cont_diff_at 𝕜 n f x) (hg : times_cont_diff_at 𝕜 n g x) : times_cont_diff_at 𝕜 n (λ x, f x * g x) x := by rw [← times_cont_diff_within_at_univ] at *; exact hf.mul hg /-- The product of two `C^n` functions on a domain is `C^n`. -/ lemma times_cont_diff_on.mul {n : with_top ℕ} {s : set E} {f g : E → 𝕜} (hf : times_cont_diff_on 𝕜 n f s) (hg : times_cont_diff_on 𝕜 n g s) : times_cont_diff_on 𝕜 n (λ x, f x * g x) s := λ x hx, (hf x hx).mul (hg x hx) /-- The product of two `C^n`functions is `C^n`. -/ lemma times_cont_diff.mul {n : with_top ℕ} {f g : E → 𝕜} (hf : times_cont_diff 𝕜 n f) (hg : times_cont_diff 𝕜 n g) : times_cont_diff 𝕜 n (λ x, f x * g x) := times_cont_diff_mul.comp (hf.prod hg) lemma times_cont_diff_within_at.div_const {f : E → 𝕜} {n} {c : 𝕜} (hf : times_cont_diff_within_at 𝕜 n f s x) : times_cont_diff_within_at 𝕜 n (λ x, f x / c) s x := by simpa only [div_eq_mul_inv] using hf.mul times_cont_diff_within_at_const lemma times_cont_diff_at.div_const {f : E → 𝕜} {n} {c : 𝕜} (hf : times_cont_diff_at 𝕜 n f x) : times_cont_diff_at 𝕜 n (λ x, f x / c) x := by simpa only [div_eq_mul_inv] using hf.mul times_cont_diff_at_const lemma times_cont_diff_on.div_const {f : E → 𝕜} {n} {c : 𝕜} (hf : times_cont_diff_on 𝕜 n f s) : times_cont_diff_on 𝕜 n (λ x, f x / c) s := by simpa only [div_eq_mul_inv] using hf.mul times_cont_diff_on_const lemma times_cont_diff.div_const {f : E → 𝕜} {n} {c : 𝕜} (hf : times_cont_diff 𝕜 n f) : times_cont_diff 𝕜 n (λ x, f x / c) := by simpa only [div_eq_mul_inv] using hf.mul times_cont_diff_const lemma times_cont_diff.pow {n : with_top ℕ} {f : E → 𝕜} (hf : times_cont_diff 𝕜 n f) : ∀ m : ℕ, times_cont_diff 𝕜 n (λ x, (f x) ^ m) | 0 := by simpa using times_cont_diff_const | (m + 1) := by simpa [pow_succ] using hf.mul (times_cont_diff.pow m) lemma times_cont_diff_at.pow {n : with_top ℕ} {f : E → 𝕜} (hf : times_cont_diff_at 𝕜 n f x) (m : ℕ) : times_cont_diff_at 𝕜 n (λ y, f y ^ m) x := (times_cont_diff_id.pow m).times_cont_diff_at.comp x hf lemma times_cont_diff_within_at.pow {n : with_top ℕ} {f : E → 𝕜} (hf : times_cont_diff_within_at 𝕜 n f s x) (m : ℕ) : times_cont_diff_within_at 𝕜 n (λ y, f y ^ m) s x := (times_cont_diff_id.pow m).times_cont_diff_at.comp_times_cont_diff_within_at x hf lemma times_cont_diff_on.pow {n : with_top ℕ} {f : E → 𝕜} (hf : times_cont_diff_on 𝕜 n f s) (m : ℕ) : times_cont_diff_on 𝕜 n (λ y, f y ^ m) s := λ y hy, (hf y hy).pow m /-! ### Scalar multiplication -/ /- The scalar multiplication is smooth. -/ lemma times_cont_diff_smul {n : with_top ℕ} : times_cont_diff 𝕜 n (λ p : 𝕜 × F, p.1 • p.2) := is_bounded_bilinear_map_smul.times_cont_diff /-- The scalar multiplication of two `C^n` functions within a set at a point is `C^n` within this set at this point. -/ lemma times_cont_diff_within_at.smul {n : with_top ℕ} {s : set E} {f : E → 𝕜} {g : E → F} (hf : times_cont_diff_within_at 𝕜 n f s x) (hg : times_cont_diff_within_at 𝕜 n g s x) : times_cont_diff_within_at 𝕜 n (λ x, f x • g x) s x := times_cont_diff_smul.times_cont_diff_within_at.comp x (hf.prod hg) subset_preimage_univ /-- The scalar multiplication of two `C^n` functions at a point is `C^n` at this point. -/ lemma times_cont_diff_at.smul {n : with_top ℕ} {f : E → 𝕜} {g : E → F} (hf : times_cont_diff_at 𝕜 n f x) (hg : times_cont_diff_at 𝕜 n g x) : times_cont_diff_at 𝕜 n (λ x, f x • g x) x := by rw [← times_cont_diff_within_at_univ] at *; exact hf.smul hg /-- The scalar multiplication of two `C^n` functions is `C^n`. -/ lemma times_cont_diff.smul {n : with_top ℕ} {f : E → 𝕜} {g : E → F} (hf : times_cont_diff 𝕜 n f) (hg : times_cont_diff 𝕜 n g) : times_cont_diff 𝕜 n (λ x, f x • g x) := times_cont_diff_smul.comp (hf.prod hg) /-- The scalar multiplication of two `C^n` functions on a domain is `C^n`. -/ lemma times_cont_diff_on.smul {n : with_top ℕ} {s : set E} {f : E → 𝕜} {g : E → F} (hf : times_cont_diff_on 𝕜 n f s) (hg : times_cont_diff_on 𝕜 n g s) : times_cont_diff_on 𝕜 n (λ x, f x • g x) s := λ x hx, (hf x hx).smul (hg x hx) /-! ### Cartesian product of two functions-/ section prod_map variables {E' : Type*} [normed_group E'] [normed_space 𝕜 E'] {F' : Type*} [normed_group F'] [normed_space 𝕜 F'] {n : with_top ℕ} /-- The product map of two `C^n` functions within a set at a point is `C^n` within the product set at the product point. -/ lemma times_cont_diff_within_at.prod_map' {s : set E} {t : set E'} {f : E → F} {g : E' → F'} {p : E × E'} (hf : times_cont_diff_within_at 𝕜 n f s p.1) (hg : times_cont_diff_within_at 𝕜 n g t p.2) : times_cont_diff_within_at 𝕜 n (prod.map f g) (set.prod s t) p := (hf.comp p times_cont_diff_within_at_fst (prod_subset_preimage_fst _ _)).prod (hg.comp p times_cont_diff_within_at_snd (prod_subset_preimage_snd _ _)) lemma times_cont_diff_within_at.prod_map {s : set E} {t : set E'} {f : E → F} {g : E' → F'} {x : E} {y : E'} (hf : times_cont_diff_within_at 𝕜 n f s x) (hg : times_cont_diff_within_at 𝕜 n g t y) : times_cont_diff_within_at 𝕜 n (prod.map f g) (set.prod s t) (x, y) := times_cont_diff_within_at.prod_map' hf hg /-- The product map of two `C^n` functions on a set is `C^n` on the product set. -/ lemma times_cont_diff_on.prod_map {E' : Type*} [normed_group E'] [normed_space 𝕜 E'] {F' : Type*} [normed_group F'] [normed_space 𝕜 F'] {s : set E} {t : set E'} {n : with_top ℕ} {f : E → F} {g : E' → F'} (hf : times_cont_diff_on 𝕜 n f s) (hg : times_cont_diff_on 𝕜 n g t) : times_cont_diff_on 𝕜 n (prod.map f g) (set.prod s t) := (hf.comp times_cont_diff_on_fst (prod_subset_preimage_fst _ _)).prod (hg.comp (times_cont_diff_on_snd) (prod_subset_preimage_snd _ _)) /-- The product map of two `C^n` functions within a set at a point is `C^n` within the product set at the product point. -/ lemma times_cont_diff_at.prod_map {f : E → F} {g : E' → F'} {x : E} {y : E'} (hf : times_cont_diff_at 𝕜 n f x) (hg : times_cont_diff_at 𝕜 n g y) : times_cont_diff_at 𝕜 n (prod.map f g) (x, y) := begin rw times_cont_diff_at at *, convert hf.prod_map hg, simp only [univ_prod_univ] end /-- The product map of two `C^n` functions within a set at a point is `C^n` within the product set at the product point. -/ lemma times_cont_diff_at.prod_map' {f : E → F} {g : E' → F'} {p : E × E'} (hf : times_cont_diff_at 𝕜 n f p.1) (hg : times_cont_diff_at 𝕜 n g p.2) : times_cont_diff_at 𝕜 n (prod.map f g) p := begin rcases p, exact times_cont_diff_at.prod_map hf hg end /-- The product map of two `C^n` functions is `C^n`. -/ lemma times_cont_diff.prod_map {f : E → F} {g : E' → F'} (hf : times_cont_diff 𝕜 n f) (hg : times_cont_diff 𝕜 n g) : times_cont_diff 𝕜 n (prod.map f g) := begin rw times_cont_diff_iff_times_cont_diff_at at *, exact λ ⟨x, y⟩, (hf x).prod_map (hg y) end end prod_map /-! ### Inversion in a complete normed algebra -/ section algebra_inverse variables (𝕜) {R : Type*} [normed_ring R] [normed_algebra 𝕜 R] open normed_ring continuous_linear_map ring /-- In a complete normed algebra, the operation of inversion is `C^n`, for all `n`, at each invertible element. The proof is by induction, bootstrapping using an identity expressing the derivative of inversion as a bilinear map of inversion itself. -/ lemma times_cont_diff_at_ring_inverse [complete_space R] {n : with_top ℕ} (x : units R) : times_cont_diff_at 𝕜 n ring.inverse (x : R) := begin induction n using with_top.nat_induction with n IH Itop, { intros m hm, refine ⟨{y : R | is_unit y}, _, _⟩, { simp [nhds_within_univ], exact x.nhds }, { use (ftaylor_series_within 𝕜 inverse univ), rw [le_antisymm hm bot_le, has_ftaylor_series_up_to_on_zero_iff], split, { rintros _ ⟨x', rfl⟩, exact (inverse_continuous_at x').continuous_within_at }, { simp [ftaylor_series_within] } } }, { apply times_cont_diff_at_succ_iff_has_fderiv_at.mpr, refine ⟨λ (x : R), - lmul_left_right 𝕜 R (inverse x) (inverse x), _, _⟩, { refine ⟨{y : R | is_unit y}, x.nhds, _⟩, rintros _ ⟨y, rfl⟩, rw [inverse_unit], exact has_fderiv_at_ring_inverse y }, { convert (lmul_left_right_is_bounded_bilinear 𝕜 R).times_cont_diff.neg.comp_times_cont_diff_at (x : R) (IH.prod IH) } }, { exact times_cont_diff_at_top.mpr Itop } end variables (𝕜) {𝕜' : Type*} [normed_field 𝕜'] [normed_algebra 𝕜 𝕜'] [complete_space 𝕜'] lemma times_cont_diff_at_inv {x : 𝕜'} (hx : x ≠ 0) {n} : times_cont_diff_at 𝕜 n has_inv.inv x := by simpa only [inverse_eq_has_inv] using times_cont_diff_at_ring_inverse 𝕜 (units.mk0 x hx) lemma times_cont_diff_on_inv {n} : times_cont_diff_on 𝕜 n (has_inv.inv : 𝕜' → 𝕜') {0}ᶜ := λ x hx, (times_cont_diff_at_inv 𝕜 hx).times_cont_diff_within_at variable {𝕜} -- TODO: the next few lemmas don't need `𝕜` or `𝕜'` to be complete -- A good way to show this is to generalize `times_cont_diff_at_ring_inverse` to the setting -- of a function `f` such that `∀ᶠ x in 𝓝 a, x * f x = 1`. lemma times_cont_diff_within_at.inv {f : E → 𝕜'} {n} (hf : times_cont_diff_within_at 𝕜 n f s x) (hx : f x ≠ 0) : times_cont_diff_within_at 𝕜 n (λ x, (f x)⁻¹) s x := (times_cont_diff_at_inv 𝕜 hx).comp_times_cont_diff_within_at x hf lemma times_cont_diff_on.inv {f : E → 𝕜'} {n} (hf : times_cont_diff_on 𝕜 n f s) (h : ∀ x ∈ s, f x ≠ 0) : times_cont_diff_on 𝕜 n (λ x, (f x)⁻¹) s := λ x hx, (hf.times_cont_diff_within_at hx).inv (h x hx) lemma times_cont_diff_at.inv {f : E → 𝕜'} {n} (hf : times_cont_diff_at 𝕜 n f x) (hx : f x ≠ 0) : times_cont_diff_at 𝕜 n (λ x, (f x)⁻¹) x := hf.inv hx lemma times_cont_diff.inv {f : E → 𝕜'} {n} (hf : times_cont_diff 𝕜 n f) (h : ∀ x, f x ≠ 0) : times_cont_diff 𝕜 n (λ x, (f x)⁻¹) := by { rw times_cont_diff_iff_times_cont_diff_at, exact λ x, hf.times_cont_diff_at.inv (h x) } -- TODO: generalize to `f g : E → 𝕜'` lemma times_cont_diff_within_at.div [complete_space 𝕜] {f g : E → 𝕜} {n} (hf : times_cont_diff_within_at 𝕜 n f s x) (hg : times_cont_diff_within_at 𝕜 n g s x) (hx : g x ≠ 0) : times_cont_diff_within_at 𝕜 n (λ x, f x / g x) s x := by simpa only [div_eq_mul_inv] using hf.mul (hg.inv hx) lemma times_cont_diff_on.div [complete_space 𝕜] {f g : E → 𝕜} {n} (hf : times_cont_diff_on 𝕜 n f s) (hg : times_cont_diff_on 𝕜 n g s) (h₀ : ∀ x ∈ s, g x ≠ 0) : times_cont_diff_on 𝕜 n (f / g) s := λ x hx, (hf x hx).div (hg x hx) (h₀ x hx) lemma times_cont_diff_at.div [complete_space 𝕜] {f g : E → 𝕜} {n} (hf : times_cont_diff_at 𝕜 n f x) (hg : times_cont_diff_at 𝕜 n g x) (hx : g x ≠ 0) : times_cont_diff_at 𝕜 n (λ x, f x / g x) x := hf.div hg hx lemma times_cont_diff.div [complete_space 𝕜] {f g : E → 𝕜} {n} (hf : times_cont_diff 𝕜 n f) (hg : times_cont_diff 𝕜 n g) (h0 : ∀ x, g x ≠ 0) : times_cont_diff 𝕜 n (λ x, f x / g x) := begin simp only [times_cont_diff_iff_times_cont_diff_at] at *, exact λ x, (hf x).div (hg x) (h0 x) end end algebra_inverse /-! ### Inversion of continuous linear maps between Banach spaces -/ section map_inverse open continuous_linear_map /-- At a continuous linear equivalence `e : E ≃L[𝕜] F` between Banach spaces, the operation of inversion is `C^n`, for all `n`. -/ lemma times_cont_diff_at_map_inverse [complete_space E] {n : with_top ℕ} (e : E ≃L[𝕜] F) : times_cont_diff_at 𝕜 n inverse (e : E →L[𝕜] F) := begin nontriviality E, -- first, we use the lemma `to_ring_inverse` to rewrite in terms of `ring.inverse` in the ring -- `E →L[𝕜] E` let O₁ : (E →L[𝕜] E) → (F →L[𝕜] E) := λ f, f.comp (e.symm : (F →L[𝕜] E)), let O₂ : (E →L[𝕜] F) → (E →L[𝕜] E) := λ f, (e.symm : (F →L[𝕜] E)).comp f, have : continuous_linear_map.inverse = O₁ ∘ ring.inverse ∘ O₂ := funext (to_ring_inverse e), rw this, -- `O₁` and `O₂` are `times_cont_diff`, -- so we reduce to proving that `ring.inverse` is `times_cont_diff` have h₁ : times_cont_diff 𝕜 n O₁, from is_bounded_bilinear_map_comp.times_cont_diff.comp (times_cont_diff_const.prod times_cont_diff_id), have h₂ : times_cont_diff 𝕜 n O₂, from is_bounded_bilinear_map_comp.times_cont_diff.comp (times_cont_diff_id.prod times_cont_diff_const), refine h₁.times_cont_diff_at.comp _ (times_cont_diff_at.comp _ _ h₂.times_cont_diff_at), convert times_cont_diff_at_ring_inverse 𝕜 (1 : units (E →L[𝕜] E)), simp [O₂, one_def] end end map_inverse section function_inverse open continuous_linear_map /-- If `f` is a local homeomorphism and the point `a` is in its target, and if `f` is `n` times continuously differentiable at `f.symm a`, and if the derivative at `f.symm a` is a continuous linear equivalence, then `f.symm` is `n` times continuously differentiable at the point `a`. This is one of the easy parts of the inverse function theorem: it assumes that we already have an inverse function. -/ theorem local_homeomorph.times_cont_diff_at_symm [complete_space E] {n : with_top ℕ} (f : local_homeomorph E F) {f₀' : E ≃L[𝕜] F} {a : F} (ha : a ∈ f.target) (hf₀' : has_fderiv_at f (f₀' : E →L[𝕜] F) (f.symm a)) (hf : times_cont_diff_at 𝕜 n f (f.symm a)) : times_cont_diff_at 𝕜 n f.symm a := begin -- We prove this by induction on `n` induction n using with_top.nat_induction with n IH Itop, { rw times_cont_diff_at_zero, exact ⟨f.target, is_open.mem_nhds f.open_target ha, f.continuous_inv_fun⟩ }, { obtain ⟨f', ⟨u, hu, hff'⟩, hf'⟩ := times_cont_diff_at_succ_iff_has_fderiv_at.mp hf, apply times_cont_diff_at_succ_iff_has_fderiv_at.mpr, -- For showing `n.succ` times continuous differentiability (the main inductive step), it -- suffices to produce the derivative and show that it is `n` times continuously differentiable have eq_f₀' : f' (f.symm a) = f₀', { exact (hff' (f.symm a) (mem_of_mem_nhds hu)).unique hf₀' }, -- This follows by a bootstrapping formula expressing the derivative as a function of `f` itself refine ⟨inverse ∘ f' ∘ f.symm, _, _⟩, { -- We first check that the derivative of `f` is that formula have h_nhds : {y : E | ∃ (e : E ≃L[𝕜] F), ↑e = f' y} ∈ 𝓝 ((f.symm) a), { have hf₀' := f₀'.nhds, rw ← eq_f₀' at hf₀', exact hf'.continuous_at.preimage_mem_nhds hf₀' }, obtain ⟨t, htu, ht, htf⟩ := mem_nhds_iff.mp (filter.inter_mem hu h_nhds), use f.target ∩ (f.symm) ⁻¹' t, refine ⟨is_open.mem_nhds _ _, _⟩, { exact f.preimage_open_of_open_symm ht }, { exact mem_inter ha (mem_preimage.mpr htf) }, intros x hx, obtain ⟨hxu, e, he⟩ := htu hx.2, have h_deriv : has_fderiv_at f ↑e ((f.symm) x), { rw he, exact hff' (f.symm x) hxu }, convert f.has_fderiv_at_symm hx.1 h_deriv, simp [← he] }, { -- Then we check that the formula, being a composition of `times_cont_diff` pieces, is -- itself `times_cont_diff` have h_deriv₁ : times_cont_diff_at 𝕜 n inverse (f' (f.symm a)), { rw eq_f₀', exact times_cont_diff_at_map_inverse _ }, have h_deriv₂ : times_cont_diff_at 𝕜 n f.symm a, { refine IH (hf.of_le _), norm_cast, exact nat.le_succ n }, exact (h_deriv₁.comp _ hf').comp _ h_deriv₂ } }, { refine times_cont_diff_at_top.mpr _, intros n, exact Itop n (times_cont_diff_at_top.mp hf n) } end /-- Let `f` be a local homeomorphism of a nondiscrete normed field, let `a` be a point in its target. if `f` is `n` times continuously differentiable at `f.symm a`, and if the derivative at `f.symm a` is nonzero, then `f.symm` is `n` times continuously differentiable at the point `a`. This is one of the easy parts of the inverse function theorem: it assumes that we already have an inverse function. -/ theorem local_homeomorph.times_cont_diff_at_symm_deriv [complete_space 𝕜] {n : with_top ℕ} (f : local_homeomorph 𝕜 𝕜) {f₀' a : 𝕜} (h₀ : f₀' ≠ 0) (ha : a ∈ f.target) (hf₀' : has_deriv_at f f₀' (f.symm a)) (hf : times_cont_diff_at 𝕜 n f (f.symm a)) : times_cont_diff_at 𝕜 n f.symm a := f.times_cont_diff_at_symm ha (hf₀'.has_fderiv_at_equiv h₀) hf end function_inverse section real /-! ### Results over `ℝ` or `ℂ` The results in this section rely on the Mean Value Theorem, and therefore hold only over `ℝ` (and its extension fields such as `ℂ`). -/ variables {𝕂 : Type*} [is_R_or_C 𝕂] {E' : Type*} [normed_group E'] [normed_space 𝕂 E'] {F' : Type*} [normed_group F'] [normed_space 𝕂 F'] /-- If a function has a Taylor series at order at least 1, then at points in the interior of the domain of definition, the term of order 1 of this series is a strict derivative of `f`. -/ lemma has_ftaylor_series_up_to_on.has_strict_fderiv_at {s : set E'} {f : E' → F'} {x : E'} {p : E' → formal_multilinear_series 𝕂 E' F'} {n : with_top ℕ} (hf : has_ftaylor_series_up_to_on n f p s) (hn : 1 ≤ n) (hs : s ∈ 𝓝 x) : has_strict_fderiv_at f ((continuous_multilinear_curry_fin1 𝕂 E' F') (p x 1)) x := has_strict_fderiv_at_of_has_fderiv_at_of_continuous_at (hf.eventually_has_fderiv_at hn hs) $ (continuous_multilinear_curry_fin1 𝕂 E' F').continuous_at.comp $ (hf.cont 1 hn).continuous_at hs /-- If a function is `C^n` with `1 ≤ n` around a point, and its derivative at that point is given to us as `f'`, then `f'` is also a strict derivative. -/ lemma times_cont_diff_at.has_strict_fderiv_at' {f : E' → F'} {f' : E' →L[𝕂] F'} {x : E'} {n : with_top ℕ} (hf : times_cont_diff_at 𝕂 n f x) (hf' : has_fderiv_at f f' x) (hn : 1 ≤ n) : has_strict_fderiv_at f f' x := begin rcases hf 1 hn with ⟨u, H, p, hp⟩, simp only [nhds_within_univ, mem_univ, insert_eq_of_mem] at H, have := hp.has_strict_fderiv_at le_rfl H, rwa hf'.unique this.has_fderiv_at end /-- If a function is `C^n` with `1 ≤ n` around a point, and its derivative at that point is given to us as `f'`, then `f'` is also a strict derivative. -/ lemma times_cont_diff_at.has_strict_deriv_at' {f : 𝕂 → F'} {f' : F'} {x : 𝕂} {n : with_top ℕ} (hf : times_cont_diff_at 𝕂 n f x) (hf' : has_deriv_at f f' x) (hn : 1 ≤ n) : has_strict_deriv_at f f' x := hf.has_strict_fderiv_at' hf' hn /-- If a function is `C^n` with `1 ≤ n` around a point, then the derivative of `f` at this point is also a strict derivative. -/ lemma times_cont_diff_at.has_strict_fderiv_at {f : E' → F'} {x : E'} {n : with_top ℕ} (hf : times_cont_diff_at 𝕂 n f x) (hn : 1 ≤ n) : has_strict_fderiv_at f (fderiv 𝕂 f x) x := hf.has_strict_fderiv_at' (hf.differentiable_at hn).has_fderiv_at hn /-- If a function is `C^n` with `1 ≤ n` around a point, then the derivative of `f` at this point is also a strict derivative. -/ lemma times_cont_diff_at.has_strict_deriv_at {f : 𝕂 → F'} {x : 𝕂} {n : with_top ℕ} (hf : times_cont_diff_at 𝕂 n f x) (hn : 1 ≤ n) : has_strict_deriv_at f (deriv f x) x := (hf.has_strict_fderiv_at hn).has_strict_deriv_at /-- If a function is `C^n` with `1 ≤ n`, then the derivative of `f` is also a strict derivative. -/ lemma times_cont_diff.has_strict_fderiv_at {f : E' → F'} {x : E'} {n : with_top ℕ} (hf : times_cont_diff 𝕂 n f) (hn : 1 ≤ n) : has_strict_fderiv_at f (fderiv 𝕂 f x) x := hf.times_cont_diff_at.has_strict_fderiv_at hn /-- If a function is `C^n` with `1 ≤ n`, then the derivative of `f` is also a strict derivative. -/ lemma times_cont_diff.has_strict_deriv_at {f : 𝕂 → F'} {x : 𝕂} {n : with_top ℕ} (hf : times_cont_diff 𝕂 n f) (hn : 1 ≤ n) : has_strict_deriv_at f (deriv f x) x := hf.times_cont_diff_at.has_strict_deriv_at hn /-- If `f` has a formal Taylor series `p` up to order `1` on `{x} ∪ s`, where `s` is a convex set, and `∥p x 1∥₊ < K`, then `f` is `K`-Lipschitz in a neighborhood of `x` within `s`. -/ lemma has_ftaylor_series_up_to_on.exists_lipschitz_on_with_of_nnnorm_lt {E F : Type*} [normed_group E] [normed_space ℝ E] [normed_group F] [normed_space ℝ F] {f : E → F} {p : E → formal_multilinear_series ℝ E F} {s : set E} {x : E} (hf : has_ftaylor_series_up_to_on 1 f p (insert x s)) (hs : convex s) (K : ℝ≥0) (hK : ∥p x 1∥₊ < K) : ∃ t ∈ 𝓝[s] x, lipschitz_on_with K f t := begin set f' := λ y, continuous_multilinear_curry_fin1 ℝ E F (p y 1), have hder : ∀ y ∈ s, has_fderiv_within_at f (f' y) s y, from λ y hy, (hf.has_fderiv_within_at le_rfl (subset_insert x s hy)).mono (subset_insert x s), have hcont : continuous_within_at f' s x, from (continuous_multilinear_curry_fin1 ℝ E F).continuous_at.comp_continuous_within_at ((hf.cont _ le_rfl _ (mem_insert _ _)).mono (subset_insert x s)), replace hK : ∥f' x∥₊ < K, by simpa only [linear_isometry_equiv.nnnorm_map], exact hs.exists_nhds_within_lipschitz_on_with_of_has_fderiv_within_at_of_nnnorm_lt (eventually_nhds_within_iff.2 $ eventually_of_forall hder) hcont K hK end /-- If `f` has a formal Taylor series `p` up to order `1` on `{x} ∪ s`, where `s` is a convex set, then `f` is Lipschitz in a neighborhood of `x` within `s`. -/ lemma has_ftaylor_series_up_to_on.exists_lipschitz_on_with {E F : Type*} [normed_group E] [normed_space ℝ E] [normed_group F] [normed_space ℝ F] {f : E → F} {p : E → formal_multilinear_series ℝ E F} {s : set E} {x : E} (hf : has_ftaylor_series_up_to_on 1 f p (insert x s)) (hs : convex s) : ∃ K (t ∈ 𝓝[s] x), lipschitz_on_with K f t := (no_top _).imp $ hf.exists_lipschitz_on_with_of_nnnorm_lt hs /-- If `f` is `C^1` within a conves set `s` at `x`, then it is Lipschitz on a neighborhood of `x` within `s`. -/ lemma times_cont_diff_within_at.exists_lipschitz_on_with {E F : Type*} [normed_group E] [normed_space ℝ E] [normed_group F] [normed_space ℝ F] {f : E → F} {s : set E} {x : E} (hf : times_cont_diff_within_at ℝ 1 f s x) (hs : convex s) : ∃ (K : ℝ≥0) (t ∈ 𝓝[s] x), lipschitz_on_with K f t := begin rcases hf 1 le_rfl with ⟨t, hst, p, hp⟩, rcases metric.mem_nhds_within_iff.mp hst with ⟨ε, ε0, hε⟩, replace hp : has_ftaylor_series_up_to_on 1 f p (metric.ball x ε ∩ insert x s) := hp.mono hε, clear hst hε t, rw [← insert_eq_of_mem (metric.mem_ball_self ε0), ← insert_inter] at hp, rcases hp.exists_lipschitz_on_with ((convex_ball _ _).inter hs) with ⟨K, t, hst, hft⟩, rw [inter_comm, ← nhds_within_restrict' _ (metric.ball_mem_nhds _ ε0)] at hst, exact ⟨K, t, hst, hft⟩ end /-- If `f` is `C^1` at `x` and `K > ∥fderiv 𝕂 f x∥`, then `f` is `K`-Lipschitz in a neighborhood of `x`. -/ lemma times_cont_diff_at.exists_lipschitz_on_with_of_nnnorm_lt {f : E' → F'} {x : E'} (hf : times_cont_diff_at 𝕂 1 f x) (K : ℝ≥0) (hK : ∥fderiv 𝕂 f x∥₊ < K) : ∃ t ∈ 𝓝 x, lipschitz_on_with K f t := (hf.has_strict_fderiv_at le_rfl).exists_lipschitz_on_with_of_nnnorm_lt K hK /-- If `f` is `C^1` at `x`, then `f` is Lipschitz in a neighborhood of `x`. -/ lemma times_cont_diff_at.exists_lipschitz_on_with {f : E' → F'} {x : E'} (hf : times_cont_diff_at 𝕂 1 f x) : ∃ K (t ∈ 𝓝 x), lipschitz_on_with K f t := (hf.has_strict_fderiv_at le_rfl).exists_lipschitz_on_with end real section deriv /-! ### One dimension All results up to now have been expressed in terms of the general Fréchet derivative `fderiv`. For maps defined on the field, the one-dimensional derivative `deriv` is often easier to use. In this paragraph, we reformulate some higher smoothness results in terms of `deriv`. -/ variables {f₂ : 𝕜 → F} {s₂ : set 𝕜} open continuous_linear_map (smul_right) /-- A function is `C^(n + 1)` on a domain with unique derivatives if and only if it is differentiable there, and its derivative (formulated with `deriv_within`) is `C^n`. -/ theorem times_cont_diff_on_succ_iff_deriv_within {n : ℕ} (hs : unique_diff_on 𝕜 s₂) : times_cont_diff_on 𝕜 ((n + 1) : ℕ) f₂ s₂ ↔ differentiable_on 𝕜 f₂ s₂ ∧ times_cont_diff_on 𝕜 n (deriv_within f₂ s₂) s₂ := begin rw times_cont_diff_on_succ_iff_fderiv_within hs, congr' 2, apply le_antisymm, { assume h, have : deriv_within f₂ s₂ = (λ u : 𝕜 →L[𝕜] F, u 1) ∘ (fderiv_within 𝕜 f₂ s₂), by { ext x, refl }, simp only [this], apply times_cont_diff.comp_times_cont_diff_on _ h, exact (is_bounded_bilinear_map_apply.is_bounded_linear_map_left _).times_cont_diff }, { assume h, have : fderiv_within 𝕜 f₂ s₂ = smul_right (1 : 𝕜 →L[𝕜] 𝕜) ∘ deriv_within f₂ s₂, by { ext x, simp [deriv_within] }, simp only [this], apply times_cont_diff.comp_times_cont_diff_on _ h, exact (is_bounded_bilinear_map_smul_right.is_bounded_linear_map_right _).times_cont_diff } end /-- A function is `C^(n + 1)` on an open domain if and only if it is differentiable there, and its derivative (formulated with `deriv`) is `C^n`. -/ theorem times_cont_diff_on_succ_iff_deriv_of_open {n : ℕ} (hs : is_open s₂) : times_cont_diff_on 𝕜 ((n + 1) : ℕ) f₂ s₂ ↔ differentiable_on 𝕜 f₂ s₂ ∧ times_cont_diff_on 𝕜 n (deriv f₂) s₂ := begin rw times_cont_diff_on_succ_iff_deriv_within hs.unique_diff_on, congr' 2, rw ← iff_iff_eq, apply times_cont_diff_on_congr, assume x hx, exact deriv_within_of_open hs hx end /-- A function is `C^∞` on a domain with unique derivatives if and only if it is differentiable there, and its derivative (formulated with `deriv_within`) is `C^∞`. -/ theorem times_cont_diff_on_top_iff_deriv_within (hs : unique_diff_on 𝕜 s₂) : times_cont_diff_on 𝕜 ∞ f₂ s₂ ↔ differentiable_on 𝕜 f₂ s₂ ∧ times_cont_diff_on 𝕜 ∞ (deriv_within f₂ s₂) s₂ := begin split, { assume h, refine ⟨h.differentiable_on le_top, _⟩, apply times_cont_diff_on_top.2 (λ n, ((times_cont_diff_on_succ_iff_deriv_within hs).1 _).2), exact h.of_le le_top }, { assume h, refine times_cont_diff_on_top.2 (λ n, _), have A : (n : with_top ℕ) ≤ ∞ := le_top, apply ((times_cont_diff_on_succ_iff_deriv_within hs).2 ⟨h.1, h.2.of_le A⟩).of_le, exact with_top.coe_le_coe.2 (nat.le_succ n) } end /-- A function is `C^∞` on an open domain if and only if it is differentiable there, and its derivative (formulated with `deriv`) is `C^∞`. -/ theorem times_cont_diff_on_top_iff_deriv_of_open (hs : is_open s₂) : times_cont_diff_on 𝕜 ∞ f₂ s₂ ↔ differentiable_on 𝕜 f₂ s₂ ∧ times_cont_diff_on 𝕜 ∞ (deriv f₂) s₂ := begin rw times_cont_diff_on_top_iff_deriv_within hs.unique_diff_on, congr' 2, rw ← iff_iff_eq, apply times_cont_diff_on_congr, assume x hx, exact deriv_within_of_open hs hx end lemma times_cont_diff_on.deriv_within {m n : with_top ℕ} (hf : times_cont_diff_on 𝕜 n f₂ s₂) (hs : unique_diff_on 𝕜 s₂) (hmn : m + 1 ≤ n) : times_cont_diff_on 𝕜 m (deriv_within f₂ s₂) s₂ := begin cases m, { change ∞ + 1 ≤ n at hmn, have : n = ∞, by simpa using hmn, rw this at hf, exact ((times_cont_diff_on_top_iff_deriv_within hs).1 hf).2 }, { change (m.succ : with_top ℕ) ≤ n at hmn, exact ((times_cont_diff_on_succ_iff_deriv_within hs).1 (hf.of_le hmn)).2 } end lemma times_cont_diff_on.deriv_of_open {m n : with_top ℕ} (hf : times_cont_diff_on 𝕜 n f₂ s₂) (hs : is_open s₂) (hmn : m + 1 ≤ n) : times_cont_diff_on 𝕜 m (deriv f₂) s₂ := (hf.deriv_within hs.unique_diff_on hmn).congr (λ x hx, (deriv_within_of_open hs hx).symm) lemma times_cont_diff_on.continuous_on_deriv_within {n : with_top ℕ} (h : times_cont_diff_on 𝕜 n f₂ s₂) (hs : unique_diff_on 𝕜 s₂) (hn : 1 ≤ n) : continuous_on (deriv_within f₂ s₂) s₂ := ((times_cont_diff_on_succ_iff_deriv_within hs).1 (h.of_le hn)).2.continuous_on lemma times_cont_diff_on.continuous_on_deriv_of_open {n : with_top ℕ} (h : times_cont_diff_on 𝕜 n f₂ s₂) (hs : is_open s₂) (hn : 1 ≤ n) : continuous_on (deriv f₂) s₂ := ((times_cont_diff_on_succ_iff_deriv_of_open hs).1 (h.of_le hn)).2.continuous_on /-- A function is `C^(n + 1)` on a domain with unique derivatives if and only if it is differentiable there, and its derivative is `C^n`. -/ theorem times_cont_diff_succ_iff_deriv {n : ℕ} : times_cont_diff 𝕜 ((n + 1) : ℕ) f₂ ↔ differentiable 𝕜 f₂ ∧ times_cont_diff 𝕜 n (deriv f₂) := by simp only [← times_cont_diff_on_univ, times_cont_diff_on_succ_iff_deriv_of_open, is_open_univ, differentiable_on_univ] end deriv section restrict_scalars /-! ### Restricting from `ℂ` to `ℝ`, or generally from `𝕜'` to `𝕜` If a function is `n` times continuously differentiable over `ℂ`, then it is `n` times continuously differentiable over `ℝ`. In this paragraph, we give variants of this statement, in the general situation where `ℂ` and `ℝ` are replaced respectively by `𝕜'` and `𝕜` where `𝕜'` is a normed algebra over `𝕜`. -/ variables (𝕜) {𝕜' : Type*} [nondiscrete_normed_field 𝕜'] [normed_algebra 𝕜 𝕜'] variables [normed_space 𝕜' E] [is_scalar_tower 𝕜 𝕜' E] variables [normed_space 𝕜' F] [is_scalar_tower 𝕜 𝕜' F] variables {p' : E → formal_multilinear_series 𝕜' E F} {n : with_top ℕ} lemma has_ftaylor_series_up_to_on.restrict_scalars (h : has_ftaylor_series_up_to_on n f p' s) : has_ftaylor_series_up_to_on n f (λ x, (p' x).restrict_scalars 𝕜) s := { zero_eq := λ x hx, h.zero_eq x hx, fderiv_within := begin intros m hm x hx, convert ((continuous_multilinear_map.restrict_scalars_linear 𝕜).has_fderiv_at) .comp_has_fderiv_within_at _ ((h.fderiv_within m hm x hx).restrict_scalars 𝕜), end, cont := λ m hm, continuous_multilinear_map.continuous_restrict_scalars.comp_continuous_on (h.cont m hm) } lemma times_cont_diff_within_at.restrict_scalars (h : times_cont_diff_within_at 𝕜' n f s x) : times_cont_diff_within_at 𝕜 n f s x := begin intros m hm, rcases h m hm with ⟨u, u_mem, p', hp'⟩, exact ⟨u, u_mem, _, hp'.restrict_scalars _⟩ end lemma times_cont_diff_on.restrict_scalars (h : times_cont_diff_on 𝕜' n f s) : times_cont_diff_on 𝕜 n f s := λ x hx, (h x hx).restrict_scalars _ lemma times_cont_diff_at.restrict_scalars (h : times_cont_diff_at 𝕜' n f x) : times_cont_diff_at 𝕜 n f x := times_cont_diff_within_at_univ.1 $ h.times_cont_diff_within_at.restrict_scalars _ lemma times_cont_diff.restrict_scalars (h : times_cont_diff 𝕜' n f) : times_cont_diff 𝕜 n f := times_cont_diff_iff_times_cont_diff_at.2 $ λ x, h.times_cont_diff_at.restrict_scalars _ end restrict_scalars
599a06e06a7fd9bd0894ddfcd878d3a53ff4b2bc
efa51dd2edbbbbd6c34bd0ce436415eb405832e7
/20170116_POPL/profile/leanfmt_optimized1.lean
2b8e3eb5d36a1e029c2d44f2e4728bf36f5332bd
[ "Apache-2.0" ]
permissive
leanprover/presentations
dd031a05bcb12c8855676c77e52ed84246bd889a
3ce2d132d299409f1de269fa8e95afa1333d644e
refs/heads/master
1,688,703,388,796
1,686,838,383,000
1,687,465,742,000
29,750,158
12
9
Apache-2.0
1,540,211,670,000
1,422,042,683,000
Lean
UTF-8
Lean
false
false
2,684
lean
open tactic -- set_option trace.compiler true namespace fmt meta def format.concat : list format -> format | [] := format.nil | (f :: fs) := f ++ format.concat fs meta definition mk_local (n : name) (ty : expr) : expr := expr.local_const n n binder_info.default ty meta def binder (n : format) (ty : format) : format := "(" ++ n ++ format.space ++ ":" ++ format.space ++ ty ++ ")" meta def let_binding (n : format) (ty : format) (val : format) : format := "x" ++ format.space ++ ":" ++ format.space ++ ":=" ++ val /- In this version we can fuse 3 loops over the arguments to an application, giving a ~20% speedup. -/ meta def exp_app (fmt_exp : expr -> format) : list expr → format | [] := format.nil | (e :: []) := "(" ++ fmt_exp e ++ ")" | (e :: es) := "(" ++ fmt_exp e ++ ") " ++ exp_app es meta def exp : expr → format | (expr.elet n ty val body) := "let" ++ let_binding (to_string n) (exp ty) (exp $ expr.instantiate_var body (mk_local n ty)) ++ format.line ++ "in" ++ format.space ++ exp body | (expr.app f arg) := let fn := expr.get_app_fn (expr.app f arg), args := expr.get_app_args (expr.app f arg) in exp fn ++ format.space ++ exp_app exp args | (expr.const c _) := to_string c | (expr.local_const n n' bi ty) := to_string n | (expr.macro _ _ _) := "macro" | (expr.pi n bi sort ty) := "forall" ++ format.space ++ binder (to_string n) (exp sort) ++ "," ++ format.group (format.line ++ format.space ++ exp (expr.instantiate_var ty (mk_local n sort))) | (expr.lam n bi ty body) := "fun" ++ format.space ++ binder (to_string n) (exp ty) ++ "," ++ format.group (format.line ++ exp (expr.instantiate_var body (mk_local n ty))) | (expr.mvar n ty) := "?" ++ to_string n | (expr.sort _) := "Type" | (expr.var i) := "i" meta def decl : declaration → format | (declaration.defn n us ty value _ _) := "def" ++ format.space ++ to_string n ++ format.space ++ ":" ++ format.space ++ exp ty ++ format.space ++ ":=" ++ format.indent (exp value) 2 | (declaration.ax n us ty) := "axiom" ++ format.space ++ to_string n | (declaration.cnst n us body _) := "constant" ++ format.space ++ to_string n | (declaration.thm n us ty body) := "theorem" ++ format.space ++ to_string n end fmt /- Turn on the profiler. -/ set_option profiler true meta def main : tactic unit := do env ← get_env, opts ← get_options, let fs := list.taken 10 $ environment.fold env [] (fun decl decls, fmt.decl decl :: decls) in monad.mapm (fun f, tactic.trace (format.to_string f opts ++ "\n")) fs, return () /- We can then just run the main function to format all declarations in the environment. -/ run_command main
b9f9c40219ff1a8430657b976468537cbaf9a4dc
a4673261e60b025e2c8c825dfa4ab9108246c32e
/stage0/src/Lean/Environment.lean
470bd977ca423116a8db3dfc2e162283859bd7ad
[ "Apache-2.0" ]
permissive
jcommelin/lean4
c02dec0cc32c4bccab009285475f265f17d73228
2909313475588cc20ac0436e55548a4502050d0a
refs/heads/master
1,674,129,550,893
1,606,415,348,000
1,606,415,348,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
28,593
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Std.Data.HashMap import Lean.Data.SMap import Lean.Declaration import Lean.LocalContext import Lean.Util.Path import Lean.Util.FindExpr import Lean.Util.Profile namespace Lean /- Opaque environment extension state. -/ constant EnvExtensionStateSpec : PointedType.{0} def EnvExtensionState : Type := EnvExtensionStateSpec.type instance : Inhabited EnvExtensionState := ⟨EnvExtensionStateSpec.val⟩ def ModuleIdx := Nat instance : Inhabited ModuleIdx := inferInstanceAs (Inhabited Nat) abbrev ConstMap := SMap Name ConstantInfo structure Import := (module : Name) (runtimeOnly : Bool := false) instance : ToString Import := ⟨fun imp => toString imp.module ++ if imp.runtimeOnly then " (runtime)" else ""⟩ /-- A compacted region holds multiple Lean objects in a contiguous memory region, which can be read/written to/from disk. Objects inside the region do not have reference counters and cannot be freed individually. The contents of .olean files are compacted regions. -/ def CompactedRegion := USize /-- Free a compacted region and its contents. No live references to the contents may exist at the time of invocation. -/ @[extern 2 "lean_compacted_region_free"] unsafe constant CompactedRegion.free : CompactedRegion → IO Unit /- Environment fields that are not used often. -/ structure EnvironmentHeader where trustLevel : UInt32 := 0 quotInit : Bool := false mainModule : Name := arbitrary imports : Array Import := #[] -- direct imports regions : Array CompactedRegion := #[] -- compacted regions of all imported modules moduleNames : NameSet := {} -- names of all imported modules open Std (HashMap) structure Environment := (const2ModIdx : HashMap Name ModuleIdx) (constants : ConstMap) (extensions : Array EnvExtensionState) (header : EnvironmentHeader := {}) namespace Environment instance : Inhabited Environment := ⟨{ const2ModIdx := {}, constants := {}, extensions := #[] }⟩ def addAux (env : Environment) (cinfo : ConstantInfo) : Environment := { env with constants := env.constants.insert cinfo.name cinfo } @[export lean_environment_find] def find? (env : Environment) (n : Name) : Option ConstantInfo := /- It is safe to use `find'` because we never overwrite imported declarations. -/ env.constants.find?' n def contains (env : Environment) (n : Name) : Bool := env.constants.contains n def imports (env : Environment) : Array Import := env.header.imports def allImportedModuleNames (env : Environment) : NameSet := env.header.moduleNames @[export lean_environment_set_main_module] def setMainModule (env : Environment) (m : Name) : Environment := { env with header := { env.header with mainModule := m } } @[export lean_environment_main_module] def mainModule (env : Environment) : Name := env.header.mainModule @[export lean_environment_mark_quot_init] private def markQuotInit (env : Environment) : Environment := { env with header := { env.header with quotInit := true } } @[export lean_environment_quot_init] private def isQuotInit (env : Environment) : Bool := env.header.quotInit @[export lean_environment_trust_level] private def getTrustLevel (env : Environment) : UInt32 := env.header.trustLevel def getModuleIdxFor? (env : Environment) (c : Name) : Option ModuleIdx := env.const2ModIdx.find? c def isConstructor (env : Environment) (c : Name) : Bool := match env.find? c with | ConstantInfo.ctorInfo _ => true | _ => false end Environment inductive KernelException := | unknownConstant (env : Environment) (name : Name) | alreadyDeclared (env : Environment) (name : Name) | declTypeMismatch (env : Environment) (decl : Declaration) (givenType : Expr) | declHasMVars (env : Environment) (name : Name) (expr : Expr) | declHasFVars (env : Environment) (name : Name) (expr : Expr) | funExpected (env : Environment) (lctx : LocalContext) (expr : Expr) | typeExpected (env : Environment) (lctx : LocalContext) (expr : Expr) | letTypeMismatch (env : Environment) (lctx : LocalContext) (name : Name) (givenType : Expr) (expectedType : Expr) | exprTypeMismatch (env : Environment) (lctx : LocalContext) (expr : Expr) (expectedType : Expr) | appTypeMismatch (env : Environment) (lctx : LocalContext) (app : Expr) (funType : Expr) (argType : Expr) | invalidProj (env : Environment) (lctx : LocalContext) (proj : Expr) | other (msg : String) namespace Environment /- Type check given declaration and add it to the environment -/ @[extern "lean_add_decl"] constant addDecl (env : Environment) (decl : @& Declaration) : Except KernelException Environment /- Compile the given declaration, it assumes the declaration has already been added to the environment using `addDecl`. -/ @[extern "lean_compile_decl"] constant compileDecl (env : Environment) (opt : @& Options) (decl : @& Declaration) : Except KernelException Environment def addAndCompile (env : Environment) (opt : Options) (decl : Declaration) : Except KernelException Environment := do let env ← addDecl env decl compileDecl env opt decl end Environment /- Interface for managing environment extensions. -/ structure EnvExtensionInterface := (ext : Type → Type) (inhabitedExt {σ} : Inhabited σ → Inhabited (ext σ)) (registerExt {σ} (mkInitial : IO σ) : IO (ext σ)) (setState {σ} (e : ext σ) (env : Environment) : σ → Environment) (modifyState {σ} (e : ext σ) (env : Environment) : (σ → σ) → Environment) (getState {σ} (e : ext σ) (env : Environment) : σ) (mkInitialExtStates : IO (Array EnvExtensionState)) instance : Inhabited EnvExtensionInterface := ⟨{ ext := id, inhabitedExt := id, registerExt := fun mk => mk, setState := fun _ env _ => env, modifyState := fun _ env _ => env, getState := fun ext _ => ext, mkInitialExtStates := pure #[] }⟩ /- Unsafe implementation of `EnvExtensionInterface` -/ namespace EnvExtensionInterfaceUnsafe structure Ext (σ : Type) := (idx : Nat) (mkInitial : IO σ) instance {σ} : Inhabited (Ext σ) := ⟨{idx := 0, mkInitial := arbitrary }⟩ private def mkEnvExtensionsRef : IO (IO.Ref (Array (Ext EnvExtensionState))) := IO.mkRef #[] @[builtinInit mkEnvExtensionsRef] private constant envExtensionsRef : IO.Ref (Array (Ext EnvExtensionState)) unsafe def setState {σ} (ext : Ext σ) (env : Environment) (s : σ) : Environment := { env with extensions := env.extensions.set! ext.idx (unsafeCast s) } @[inline] unsafe def modifyState {σ : Type} (ext : Ext σ) (env : Environment) (f : σ → σ) : Environment := { env with extensions := env.extensions.modify ext.idx fun s => let s : σ := unsafeCast s; let s : σ := f s; unsafeCast s } unsafe def getState {σ} (ext : Ext σ) (env : Environment) : σ := let s : EnvExtensionState := env.extensions.get! ext.idx unsafeCast s unsafe def registerExt {σ} (mkInitial : IO σ) : IO (Ext σ) := do let initializing ← IO.initializing unless initializing do throw (IO.userError "failed to register environment, extensions can only be registered during initialization") let exts ← envExtensionsRef.get let idx := exts.size let ext : Ext σ := { idx := idx, mkInitial := mkInitial, } envExtensionsRef.modify fun exts => exts.push (unsafeCast ext) pure ext def mkInitialExtStates : IO (Array EnvExtensionState) := do let exts ← envExtensionsRef.get exts.mapM fun ext => ext.mkInitial unsafe def imp : EnvExtensionInterface := { ext := Ext, inhabitedExt := fun _ => ⟨arbitrary⟩, registerExt := registerExt, setState := setState, modifyState := modifyState, getState := getState, mkInitialExtStates := mkInitialExtStates } end EnvExtensionInterfaceUnsafe @[implementedBy EnvExtensionInterfaceUnsafe.imp] constant EnvExtensionInterfaceImp : EnvExtensionInterface def EnvExtension (σ : Type) : Type := EnvExtensionInterfaceImp.ext σ namespace EnvExtension instance {σ} [s : Inhabited σ] : Inhabited (EnvExtension σ) := EnvExtensionInterfaceImp.inhabitedExt s def setState {σ : Type} (ext : EnvExtension σ) (env : Environment) (s : σ) : Environment := EnvExtensionInterfaceImp.setState ext env s def modifyState {σ : Type} (ext : EnvExtension σ) (env : Environment) (f : σ → σ) : Environment := EnvExtensionInterfaceImp.modifyState ext env f def getState {σ : Type} (ext : EnvExtension σ) (env : Environment) : σ := EnvExtensionInterfaceImp.getState ext env end EnvExtension /- Environment extensions can only be registered during initialization. Reasons: 1- Our implementation assumes the number of extensions does not change after an environment object is created. 2- We do not use any synchronization primitive to access `envExtensionsRef`. -/ def registerEnvExtension {σ : Type} (mkInitial : IO σ) : IO (EnvExtension σ) := EnvExtensionInterfaceImp.registerExt mkInitial private def mkInitialExtensionStates : IO (Array EnvExtensionState) := EnvExtensionInterfaceImp.mkInitialExtStates @[export lean_mk_empty_environment] def mkEmptyEnvironment (trustLevel : UInt32 := 0) : IO Environment := do let initializing ← IO.initializing if initializing then throw (IO.userError "environment objects cannot be created during initialization") let exts ← mkInitialExtensionStates pure { const2ModIdx := {}, constants := {}, header := { trustLevel := trustLevel }, extensions := exts } structure PersistentEnvExtensionState (α : Type) (σ : Type) := (importedEntries : Array (Array α)) -- entries per imported module (state : σ) structure ImportM.Context := (env : Environment) (opts : Options) abbrev ImportM := ReaderT Lean.ImportM.Context IO /- An environment extension with support for storing/retrieving entries from a .olean file. - α is the type of the entries that are stored in .olean files. - β is the type of values used to update the state. - σ is the actual state. Remark: for most extensions α and β coincide. Note that `addEntryFn` is not in `IO`. This is intentional, and allows us to write simple functions such as ``` def addAlias (env : Environment) (a : Name) (e : Name) : Environment := aliasExtension.addEntry env (a, e) ``` without using `IO`. We have many functions like `addAlias`. `α` and ‵β` do not coincide for extensions where the data used to update the state contains, for example, closures which we currently cannot store in files. -/ structure PersistentEnvExtension (α : Type) (β : Type) (σ : Type) := (toEnvExtension : EnvExtension (PersistentEnvExtensionState α σ)) (name : Name) (addImportedFn : Array (Array α) → ImportM σ) (addEntryFn : σ → β → σ) (exportEntriesFn : σ → Array α) (statsFn : σ → Format) /- Opaque persistent environment extension entry. -/ constant EnvExtensionEntrySpec : PointedType.{0} def EnvExtensionEntry : Type := EnvExtensionEntrySpec.type instance : Inhabited EnvExtensionEntry := ⟨EnvExtensionEntrySpec.val⟩ instance {α σ} [Inhabited σ] : Inhabited (PersistentEnvExtensionState α σ) := ⟨{importedEntries := #[], state := arbitrary }⟩ instance {α β σ} [Inhabited σ] : Inhabited (PersistentEnvExtension α β σ) := ⟨{ toEnvExtension := arbitrary, name := arbitrary, addImportedFn := fun _ => arbitrary, addEntryFn := fun s _ => s, exportEntriesFn := fun _ => #[], statsFn := fun _ => Format.nil }⟩ namespace PersistentEnvExtension def getModuleEntries {α β σ : Type} (ext : PersistentEnvExtension α β σ) (env : Environment) (m : ModuleIdx) : Array α := (ext.toEnvExtension.getState env).importedEntries.get! m def addEntry {α β σ : Type} (ext : PersistentEnvExtension α β σ) (env : Environment) (b : β) : Environment := ext.toEnvExtension.modifyState env fun s => let state := ext.addEntryFn s.state b; { s with state := state } def getState {α β σ : Type} (ext : PersistentEnvExtension α β σ) (env : Environment) : σ := (ext.toEnvExtension.getState env).state def setState {α β σ : Type} (ext : PersistentEnvExtension α β σ) (env : Environment) (s : σ) : Environment := ext.toEnvExtension.modifyState env $ fun ps => { ps with state := s } def modifyState {α β σ : Type} (ext : PersistentEnvExtension α β σ) (env : Environment) (f : σ → σ) : Environment := ext.toEnvExtension.modifyState env $ fun ps => { ps with state := f (ps.state) } end PersistentEnvExtension builtin_initialize persistentEnvExtensionsRef : IO.Ref (Array (PersistentEnvExtension EnvExtensionEntry EnvExtensionEntry EnvExtensionState)) ← IO.mkRef #[] structure PersistentEnvExtensionDescr (α β σ : Type) := (name : Name) (mkInitial : IO σ) (addImportedFn : Array (Array α) → ImportM σ) (addEntryFn : σ → β → σ) (exportEntriesFn : σ → Array α) (statsFn : σ → Format := fun _ => Format.nil) unsafe def registerPersistentEnvExtensionUnsafe {α β σ : Type} [Inhabited σ] (descr : PersistentEnvExtensionDescr α β σ) : IO (PersistentEnvExtension α β σ) := do let pExts ← persistentEnvExtensionsRef.get if pExts.any (fun ext => ext.name == descr.name) then throw (IO.userError s!"invalid environment extension, '{descr.name}' has already been used") let ext ← registerEnvExtension do let initial ← descr.mkInitial let s : PersistentEnvExtensionState α σ := { importedEntries := #[], state := initial } pure s let pExt : PersistentEnvExtension α β σ := { toEnvExtension := ext, name := descr.name, addImportedFn := descr.addImportedFn, addEntryFn := descr.addEntryFn, exportEntriesFn := descr.exportEntriesFn, statsFn := descr.statsFn } persistentEnvExtensionsRef.modify fun pExts => pExts.push (unsafeCast pExt) pure pExt @[implementedBy registerPersistentEnvExtensionUnsafe] constant registerPersistentEnvExtension {α β σ : Type} [Inhabited σ] (descr : PersistentEnvExtensionDescr α β σ) : IO (PersistentEnvExtension α β σ) /- Simple PersistentEnvExtension that implements exportEntriesFn using a list of entries. -/ def SimplePersistentEnvExtension (α σ : Type) := PersistentEnvExtension α α (List α × σ) @[specialize] def mkStateFromImportedEntries {α σ : Type} (addEntryFn : σ → α → σ) (initState : σ) (as : Array (Array α)) : σ := as.foldl (fun r es => es.foldl (fun r e => addEntryFn r e) r) initState structure SimplePersistentEnvExtensionDescr (α σ : Type) := (name : Name) (addEntryFn : σ → α → σ) (addImportedFn : Array (Array α) → σ) (toArrayFn : List α → Array α := fun es => es.toArray) def registerSimplePersistentEnvExtension {α σ : Type} [Inhabited σ] (descr : SimplePersistentEnvExtensionDescr α σ) : IO (SimplePersistentEnvExtension α σ) := registerPersistentEnvExtension { name := descr.name, mkInitial := pure ([], descr.addImportedFn #[]), addImportedFn := fun as => pure ([], descr.addImportedFn as), addEntryFn := fun s e => match s with | (entries, s) => (e::entries, descr.addEntryFn s e), exportEntriesFn := fun s => descr.toArrayFn s.1.reverse, statsFn := fun s => format "number of local entries: " ++ format s.1.length } namespace SimplePersistentEnvExtension instance {α σ : Type} [Inhabited σ] : Inhabited (SimplePersistentEnvExtension α σ) := inferInstanceAs (Inhabited (PersistentEnvExtension α α (List α × σ))) def getEntries {α σ : Type} (ext : SimplePersistentEnvExtension α σ) (env : Environment) : List α := (PersistentEnvExtension.getState ext env).1 def getState {α σ : Type} (ext : SimplePersistentEnvExtension α σ) (env : Environment) : σ := (PersistentEnvExtension.getState ext env).2 def setState {α σ : Type} (ext : SimplePersistentEnvExtension α σ) (env : Environment) (s : σ) : Environment := PersistentEnvExtension.modifyState ext env (fun ⟨entries, _⟩ => (entries, s)) def modifyState {α σ : Type} (ext : SimplePersistentEnvExtension α σ) (env : Environment) (f : σ → σ) : Environment := PersistentEnvExtension.modifyState ext env (fun ⟨entries, s⟩ => (entries, f s)) end SimplePersistentEnvExtension /-- Environment extension for tagging declarations. Declarations must only be tagged in the module where they were declared. -/ def TagDeclarationExtension := SimplePersistentEnvExtension Name NameSet def mkTagDeclarationExtension (name : Name) : IO TagDeclarationExtension := registerSimplePersistentEnvExtension { name := name, addImportedFn := fun as => {}, addEntryFn := fun s n => s.insert n, toArrayFn := fun es => es.toArray.qsort Name.quickLt } namespace TagDeclarationExtension instance : Inhabited TagDeclarationExtension := inferInstanceAs (Inhabited (SimplePersistentEnvExtension Name NameSet)) def tag (ext : TagDeclarationExtension) (env : Environment) (n : Name) : Environment := ext.addEntry env n def isTagged (ext : TagDeclarationExtension) (env : Environment) (n : Name) : Bool := match env.getModuleIdxFor? n with | some modIdx => (ext.getModuleEntries env modIdx).binSearchContains n Name.quickLt | none => (ext.getState env).contains n end TagDeclarationExtension /- Content of a .olean file. We use `compact.cpp` to generate the image of this object in disk. -/ structure ModuleData := (imports : Array Import) (constants : Array ConstantInfo) (entries : Array (Name × Array EnvExtensionEntry)) instance : Inhabited ModuleData := ⟨{imports := arbitrary, constants := arbitrary, entries := arbitrary }⟩ @[extern 3 "lean_save_module_data"] constant saveModuleData (fname : @& String) (m : ModuleData) : IO Unit @[extern 2 "lean_read_module_data"] constant readModuleData (fname : @& String) : IO (ModuleData × CompactedRegion) /-- Free compacted regions of imports. No live references to imported objects may exist at the time of invocation; in particular, `env` should be the last reference to any `Environment` derived from these imports. -/ @[noinline, export lean_environment_free_regions] unsafe def Environment.freeRegions (env : Environment) : IO Unit := /- NOTE: This assumes `env` is not inferred as a borrowed parameter, and is freed after extracting the `header` field. Otherwise, we would encounter undefined behavior when the constant map in `env`, which may reference objects in compacted regions, is freed after the regions. In the currently produced IR, we indeed see: ``` def Lean.Environment.freeRegions (x_1 : obj) (x_2 : obj) : obj := let x_3 : obj := proj[3] x_1; inc x_3; dec x_1; ... ``` TODO: statically check for this. -/ env.header.regions.forM CompactedRegion.free def mkModuleData (env : Environment) : IO ModuleData := do let pExts ← persistentEnvExtensionsRef.get let entries : Array (Name × Array EnvExtensionEntry) := pExts.size.fold (fun i result => let state := (pExts.get! i).getState env let exportEntriesFn := (pExts.get! i).exportEntriesFn let extName := (pExts.get! i).name result.push (extName, exportEntriesFn state)) #[] pure { imports := env.header.imports, constants := env.constants.foldStage2 (fun cs _ c => cs.push c) #[], entries := entries } @[export lean_write_module] def writeModule (env : Environment) (fname : String) : IO Unit := do let modData ← mkModuleData env; saveModuleData fname modData partial def importModulesAux : List Import → (NameSet × Array ModuleData × Array CompactedRegion) → IO (NameSet × Array ModuleData × Array CompactedRegion) | [], r => pure r | i::is, (s, mods, regions) => if i.runtimeOnly || s.contains i.module then importModulesAux is (s, mods, regions) else do let s := s.insert i.module let mFile ← findOLean i.module unless (← IO.fileExists mFile) do throw $ IO.userError s!"object file '{mFile}' of module {i.module} does not exist" let (mod, region) ← readModuleData mFile let (s, mods, regions) ← importModulesAux mod.imports.toList (s, mods, regions) let mods := mods.push mod let regions := regions.push region importModulesAux is (s, mods, regions) private partial def getEntriesFor (mod : ModuleData) (extId : Name) (i : Nat) : Array EnvExtensionEntry := if i < mod.entries.size then let curr := mod.entries.get! i; if curr.1 == extId then curr.2 else getEntriesFor mod extId (i+1) else #[] private def setImportedEntries (env : Environment) (mods : Array ModuleData) : IO Environment := do let mut env := env let pExtDescrs ← persistentEnvExtensionsRef.get for mod in mods do for extDescr in pExtDescrs do let entries := getEntriesFor mod extDescr.name 0 env ← extDescr.toEnvExtension.modifyState env fun s => { s with importedEntries := s.importedEntries.push entries } return env private def finalizePersistentExtensions (env : Environment) (opts : Options) : IO Environment := do let mut env := env let pExtDescrs ← persistentEnvExtensionsRef.get for extDescr in pExtDescrs do let s := extDescr.toEnvExtension.getState env let newState ← extDescr.addImportedFn s.importedEntries { env := env, opts := opts } env ← extDescr.toEnvExtension.setState env { s with state := newState } return env @[export lean_import_modules] def importModules (imports : List Import) (opts : Options) (trustLevel : UInt32 := 0) : IO Environment := profileitIO "import" ⟨0, 0⟩ do let (moduleNames, mods, regions) ← importModulesAux imports ({}, #[], #[]) let mut modIdx : Nat := 0 let mut const2ModIdx : HashMap Name ModuleIdx := {} let mut constants : ConstMap := SMap.empty for mod in mods do for cinfo in mod.constants do const2ModIdx := const2ModIdx.insert cinfo.name modIdx if constants.contains cinfo.name then throw (IO.userError s!"import failed, environment already contains '{cinfo.name}'") constants := constants.insert cinfo.name cinfo modIdx := modIdx + 1 constants := constants.switch let exts ← mkInitialExtensionStates let env : Environment := { const2ModIdx := const2ModIdx, constants := constants, extensions := exts, header := { quotInit := !imports.isEmpty, -- We assume `core.lean` initializes quotient module trustLevel := trustLevel, imports := imports.toArray, regions := regions, moduleNames := moduleNames } } let env ← setImportedEntries env mods let env ← finalizePersistentExtensions env opts pure env /-- Create environment object from imports and free compacted regions after calling `act`. No live references to the environment object or imported objects may exist after `act` finishes. -/ unsafe def withImportModules {α : Type} (imports : List Import) (opts : Options) (trustLevel : UInt32 := 0) (x : Environment → IO α) : IO α := do let env ← importModules imports opts trustLevel try x env finally env.freeRegions builtin_initialize namespacesExt : SimplePersistentEnvExtension Name NameSet ← registerSimplePersistentEnvExtension { name := `namespaces, addImportedFn := fun as => mkStateFromImportedEntries NameSet.insert {} as, addEntryFn := fun s n => s.insert n } namespace Environment def registerNamespace (env : Environment) (n : Name) : Environment := if (namespacesExt.getState env).contains n then env else namespacesExt.addEntry env n def isNamespace (env : Environment) (n : Name) : Bool := (namespacesExt.getState env).contains n def getNamespaceSet (env : Environment) : NameSet := namespacesExt.getState env private def isNamespaceName : Name → Bool | Name.str Name.anonymous _ _ => true | Name.str p _ _ => isNamespaceName p | _ => false private def registerNamePrefixes : Environment → Name → Environment | env, Name.str p _ _ => if isNamespaceName p then registerNamePrefixes (registerNamespace env p) p else env | env, _ => env @[export lean_environment_add] def add (env : Environment) (cinfo : ConstantInfo) : Environment := let env := registerNamePrefixes env cinfo.name env.addAux cinfo @[export lean_display_stats] def displayStats (env : Environment) : IO Unit := do let pExtDescrs ← persistentEnvExtensionsRef.get let numModules := ((pExtDescrs.get! 0).toEnvExtension.getState env).importedEntries.size; IO.println ("direct imports: " ++ toString env.header.imports); IO.println ("number of imported modules: " ++ toString numModules); IO.println ("number of consts: " ++ toString env.constants.size); IO.println ("number of imported consts: " ++ toString env.constants.stageSizes.1); IO.println ("number of local consts: " ++ toString env.constants.stageSizes.2); IO.println ("number of buckets for imported consts: " ++ toString env.constants.numBuckets); IO.println ("trust level: " ++ toString env.header.trustLevel); IO.println ("number of extensions: " ++ toString env.extensions.size); pExtDescrs.forM $ fun extDescr => do IO.println ("extension '" ++ toString extDescr.name ++ "'") let s := extDescr.toEnvExtension.getState env let fmt := extDescr.statsFn s.state unless fmt.isNil do IO.println (" " ++ toString (Format.nest 2 (extDescr.statsFn s.state))) IO.println (" number of imported entries: " ++ toString (s.importedEntries.foldl (fun sum es => sum + es.size) 0)) @[extern "lean_eval_const"] unsafe constant evalConst (α) (env : @& Environment) (opts : @& Options) (constName : @& Name) : Except String α private def throwUnexpectedType {α} (typeName : Name) (constName : Name) : ExceptT String Id α := throw ("unexpected type at '" ++ toString constName ++ "', `" ++ toString typeName ++ "` expected") /-- Like `evalConst`, but first check that `constName` indeed is a declaration of type `typeName`. This function is still unsafe because it cannot guarantee that `typeName` is in fact the name of the type `α`. -/ unsafe def evalConstCheck (α) (env : Environment) (opts : Options) (typeName : Name) (constName : Name) : ExceptT String Id α := match env.find? constName with | none => throw ("unknow constant '" ++ toString constName ++ "'") | some info => match info.type with | Expr.const c _ _ => if c != typeName then throwUnexpectedType typeName constName else env.evalConst α opts constName | _ => throwUnexpectedType typeName constName def hasUnsafe (env : Environment) (e : Expr) : Bool := let c? := e.find? $ fun e => match e with | Expr.const c _ _ => match env.find? c with | some cinfo => cinfo.isUnsafe | none => false | _ => false; c?.isSome end Environment namespace Kernel /- Kernel API -/ /-- Kernel isDefEq predicate. We use it mainly for debugging purposes. Recall that the Kernel type checker does not support metavariables. When implementing automation, consider using the `MetaM` methods. -/ @[extern "lean_kernel_is_def_eq"] constant isDefEq (env : Environment) (lctx : LocalContext) (a b : Expr) : Bool /-- Kernel WHNF function. We use it mainly for debugging purposes. Recall that the Kernel type checker does not support metavariables. When implementing automation, consider using the `MetaM` methods. -/ @[extern "lean_kernel_whnf"] constant whnf (env : Environment) (lctx : LocalContext) (a : Expr) : Expr end Kernel class MonadEnv (m : Type → Type) := (getEnv : m Environment) (modifyEnv : (Environment → Environment) → m Unit) export MonadEnv (getEnv modifyEnv) instance (m n) [MonadEnv m] [MonadLift m n] : MonadEnv n := { getEnv := liftM (getEnv : m Environment), modifyEnv := fun f => liftM (modifyEnv f : m Unit) } end Lean
ec65ef812ee8c7622a03ea9d12875144b42691b6
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/order/sup_indep.lean
70c982f5ccad450165ce96287f20593663bd8962
[ "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
14,363
lean
/- Copyright (c) 2021 Aaron Anderson, Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson, Kevin Buzzard, Yaël Dillies, Eric Wieser -/ import data.finset.pairwise import data.finset.powerset import data.fintype.basic /-! # Supremum independence In this file, we define supremum independence of indexed sets. An indexed family `f : ι → α` is sup-independent if, for all `a`, `f a` and the supremum of the rest are disjoint. ## Main definitions * `finset.sup_indep s f`: a family of elements `f` are supremum independent on the finite set `s`. * `complete_lattice.set_independent s`: a set of elements are supremum independent. * `complete_lattice.independent f`: a family of elements are supremum independent. ## Main statements * In a distributive lattice, supremum independence is equivalent to pairwise disjointness: * `finset.sup_indep_iff_pairwise_disjoint` * `complete_lattice.set_independent_iff_pairwise_disjoint` * `complete_lattice.independent_iff_pairwise_disjoint` * Otherwise, supremum independence is stronger than pairwise disjointness: * `finset.sup_indep.pairwise_disjoint` * `complete_lattice.set_independent.pairwise_disjoint` * `complete_lattice.independent.pairwise_disjoint` ## Implementation notes For the finite version, we avoid the "obvious" definition `∀ i ∈ s, disjoint (f i) ((s.erase i).sup f)` because `erase` would require decidable equality on `ι`. -/ variables {α β ι ι' : Type*} /-! ### On lattices with a bottom element, via `finset.sup` -/ namespace finset section lattice variables [lattice α] [order_bot α] /-- Supremum independence of finite sets. We avoid the "obvious" definition using `s.erase i` because `erase` would require decidable equality on `ι`. -/ def sup_indep (s : finset ι) (f : ι → α) : Prop := ∀ ⦃t⦄, t ⊆ s → ∀ ⦃i⦄, i ∈ s → i ∉ t → disjoint (f i) (t.sup f) variables {s t : finset ι} {f : ι → α} {i : ι} instance [decidable_eq ι] [decidable_eq α] : decidable (sup_indep s f) := begin apply @finset.decidable_forall_of_decidable_subsets _ _ _ _, intros t ht, apply @finset.decidable_dforall_finset _ _ _ _, exact λ i hi, @implies.decidable _ _ _ (decidable_of_iff' (_ = ⊥) disjoint_iff), end lemma sup_indep.subset (ht : t.sup_indep f) (h : s ⊆ t) : s.sup_indep f := λ u hu i hi, ht (hu.trans h) (h hi) lemma sup_indep_empty (f : ι → α) : (∅ : finset ι).sup_indep f := λ _ _ a ha, ha.elim lemma sup_indep_singleton (i : ι) (f : ι → α) : ({i} : finset ι).sup_indep f := λ s hs j hji hj, begin rw [eq_empty_of_ssubset_singleton ⟨hs, λ h, hj (h hji)⟩, sup_empty], exact disjoint_bot_right, end lemma sup_indep.pairwise_disjoint (hs : s.sup_indep f) : (s : set ι).pairwise_disjoint f := λ a ha b hb hab, sup_singleton.subst $ hs (singleton_subset_iff.2 hb) ha $ not_mem_singleton.2 hab /-- The RHS looks like the definition of `complete_lattice.independent`. -/ lemma sup_indep_iff_disjoint_erase [decidable_eq ι] : s.sup_indep f ↔ ∀ i ∈ s, disjoint (f i) ((s.erase i).sup f) := ⟨λ hs i hi, hs (erase_subset _ _) hi (not_mem_erase _ _), λ hs t ht i hi hit, (hs i hi).mono_right (sup_mono $ λ j hj, mem_erase.2 ⟨ne_of_mem_of_not_mem hj hit, ht hj⟩)⟩ @[simp] lemma sup_indep_pair [decidable_eq ι] {i j : ι} (hij : i ≠ j) : ({i, j} : finset ι).sup_indep f ↔ disjoint (f i) (f j) := ⟨λ h, h.pairwise_disjoint (by simp) (by simp) hij, λ h, begin rw sup_indep_iff_disjoint_erase, intros k hk, rw [finset.mem_insert, finset.mem_singleton] at hk, obtain rfl | rfl := hk, { convert h using 1, rw [finset.erase_insert, finset.sup_singleton], simpa using hij }, { convert h.symm using 1, have : ({i, k} : finset ι).erase k = {i}, { ext, rw [mem_erase, mem_insert, mem_singleton, mem_singleton, and_or_distrib_left, ne.def, not_and_self, or_false, and_iff_right_of_imp], rintro rfl, exact hij }, rw [this, finset.sup_singleton] } end⟩ lemma sup_indep_univ_bool (f : bool → α) : (finset.univ : finset bool).sup_indep f ↔ disjoint (f ff) (f tt) := begin have : tt ≠ ff := by simp only [ne.def, not_false_iff], exact (sup_indep_pair this).trans disjoint.comm, end @[simp] lemma sup_indep_univ_fin_two (f : fin 2 → α) : (finset.univ : finset (fin 2)).sup_indep f ↔ disjoint (f 0) (f 1) := begin have : (0 : fin 2) ≠ 1 := by simp, exact sup_indep_pair this, end lemma sup_indep.attach (hs : s.sup_indep f) : s.attach.sup_indep (f ∘ subtype.val) := begin intros t ht i _ hi, classical, rw ←finset.sup_image, refine hs (image_subset_iff.2 $ λ (j : {x // x ∈ s}) _, j.2) i.2 (λ hi', hi _), rw mem_image at hi', obtain ⟨j, hj, hji⟩ := hi', rwa subtype.ext hji at hj, end end lattice section distrib_lattice variables [distrib_lattice α] [order_bot α] {s : finset ι} {f : ι → α} lemma sup_indep_iff_pairwise_disjoint : s.sup_indep f ↔ (s : set ι).pairwise_disjoint f := ⟨sup_indep.pairwise_disjoint, λ hs t ht i hi hit, disjoint_sup_right.2 $ λ j hj, hs hi (ht hj) (ne_of_mem_of_not_mem hj hit).symm⟩ alias sup_indep_iff_pairwise_disjoint ↔ sup_indep.pairwise_disjoint _root_.set.pairwise_disjoint.sup_indep /-- Bind operation for `sup_indep`. -/ lemma sup_indep.sup [decidable_eq ι] {s : finset ι'} {g : ι' → finset ι} {f : ι → α} (hs : s.sup_indep (λ i, (g i).sup f)) (hg : ∀ i' ∈ s, (g i').sup_indep f) : (s.sup g).sup_indep f := begin simp_rw sup_indep_iff_pairwise_disjoint at ⊢ hs hg, rw [sup_eq_bUnion, coe_bUnion], exact hs.bUnion_finset hg, end /-- Bind operation for `sup_indep`. -/ lemma sup_indep.bUnion [decidable_eq ι] {s : finset ι'} {g : ι' → finset ι} {f : ι → α} (hs : s.sup_indep (λ i, (g i).sup f)) (hg : ∀ i' ∈ s, (g i').sup_indep f) : (s.bUnion g).sup_indep f := by { rw ←sup_eq_bUnion, exact hs.sup hg } end distrib_lattice end finset /-! ### On complete lattices via `has_Sup.Sup` -/ namespace complete_lattice variables [complete_lattice α] open set function /-- An independent set of elements in a complete lattice is one in which every element is disjoint from the `Sup` of the rest. -/ def set_independent (s : set α) : Prop := ∀ ⦃a⦄, a ∈ s → disjoint a (Sup (s \ {a})) variables {s : set α} (hs : set_independent s) @[simp] lemma set_independent_empty : set_independent (∅ : set α) := λ x hx, (set.not_mem_empty x hx).elim theorem set_independent.mono {t : set α} (hst : t ⊆ s) : set_independent t := λ a ha, (hs (hst ha)).mono_right (Sup_le_Sup (diff_subset_diff_left hst)) /-- If the elements of a set are independent, then any pair within that set is disjoint. -/ lemma set_independent.pairwise_disjoint : s.pairwise_disjoint id := λ x hx y hy h, disjoint_Sup_right (hs hx) ((mem_diff y).mpr ⟨hy, h.symm⟩) lemma set_independent_pair {a b : α} (hab : a ≠ b) : set_independent ({a, b} : set α) ↔ disjoint a b := begin split, { intro h, exact h.pairwise_disjoint (mem_insert _ _) (mem_insert_of_mem _ (mem_singleton _)) hab, }, { rintros h c ((rfl : c = a) | (rfl : c = b)), { convert h using 1, simp [hab, Sup_singleton] }, { convert h.symm using 1, simp [hab, Sup_singleton] }, }, end include hs /-- If the elements of a set are independent, then any element is disjoint from the `Sup` of some subset of the rest. -/ lemma set_independent.disjoint_Sup {x : α} {y : set α} (hx : x ∈ s) (hy : y ⊆ s) (hxy : x ∉ y) : disjoint x (Sup y) := begin have := (hs.mono $ insert_subset.mpr ⟨hx, hy⟩) (mem_insert x _), rw [insert_diff_of_mem _ (mem_singleton _), diff_singleton_eq_self hxy] at this, exact this, end omit hs /-- An independent indexed family of elements in a complete lattice is one in which every element is disjoint from the `supr` of the rest. Example: an indexed family of non-zero elements in a vector space is linearly independent iff the indexed family of subspaces they generate is independent in this sense. Example: an indexed family of submodules of a module is independent in this sense if and only the natural map from the direct sum of the submodules to the module is injective. -/ def independent {ι : Sort*} {α : Type*} [complete_lattice α] (t : ι → α) : Prop := ∀ i : ι, disjoint (t i) (⨆ (j ≠ i), t j) lemma set_independent_iff {α : Type*} [complete_lattice α] (s : set α) : set_independent s ↔ independent (coe : s → α) := begin simp_rw [independent, set_independent, set_coe.forall, Sup_eq_supr], refine forall₂_congr (λ a ha, _), congr' 2, convert supr_subtype.symm, simp [supr_and], end variables {t : ι → α} (ht : independent t) theorem independent_def : independent t ↔ ∀ i : ι, disjoint (t i) (⨆ (j ≠ i), t j) := iff.rfl theorem independent_def' : independent t ↔ ∀ i, disjoint (t i) (Sup (t '' {j | j ≠ i})) := by {simp_rw Sup_image, refl} theorem independent_def'' : independent t ↔ ∀ i, disjoint (t i) (Sup {a | ∃ j ≠ i, t j = a}) := by {rw independent_def', tidy} @[simp] lemma independent_empty (t : empty → α) : independent t. @[simp] lemma independent_pempty (t : pempty → α) : independent t. /-- If the elements of a set are independent, then any pair within that set is disjoint. -/ lemma independent.pairwise_disjoint : pairwise (disjoint on t) := λ x y h, disjoint_Sup_right (ht x) ⟨y, supr_pos h.symm⟩ lemma independent.mono {s t : ι → α} (hs : independent s) (hst : t ≤ s) : independent t := λ i, (hs i).mono (hst i) $ supr₂_mono $ λ j _, hst j /-- Composing an independent indexed family with an injective function on the index results in another indepedendent indexed family. -/ lemma independent.comp {ι ι' : Sort*} {t : ι → α} {f : ι' → ι} (ht : independent t) (hf : injective f) : independent (t ∘ f) := λ i, (ht (f i)).mono_right $ begin refine (supr_mono $ λ i, _).trans (supr_comp_le _ f), exact supr_const_mono hf.ne, end lemma independent.comp' {ι ι' : Sort*} {t : ι → α} {f : ι' → ι} (ht : independent $ t ∘ f) (hf : surjective f) : independent t := begin intros i, obtain ⟨i', rfl⟩ := hf i, rw ← hf.supr_comp, exact (ht i').mono_right (bsupr_mono $ λ j' hij, mt (congr_arg f) hij), end lemma independent.set_independent_range (ht : independent t) : set_independent $ range t := begin rw set_independent_iff, rw ← coe_comp_range_factorization t at ht, exact ht.comp' surjective_onto_range, end lemma independent.injective (ht : independent t) (h_ne_bot : ∀ i, t i ≠ ⊥) : injective t := begin intros i j h, by_contra' contra, apply h_ne_bot j, suffices : t j ≤ ⨆ k (hk : k ≠ i), t k, { replace ht := (ht i).mono_right this, rwa [h, disjoint_self] at ht, }, replace contra : j ≠ i, { exact ne.symm contra, }, exact le_supr₂ j contra, end lemma independent_pair {i j : ι} (hij : i ≠ j) (huniv : ∀ k, k = i ∨ k = j): independent t ↔ disjoint (t i) (t j) := begin split, { exact λ h, h.pairwise_disjoint hij }, { rintros h k, obtain rfl | rfl := huniv k, { refine h.mono_right (supr_le $ λ i, supr_le $ λ hi, eq.le _), rw (huniv i).resolve_left hi }, { refine h.symm.mono_right (supr_le $ λ j, supr_le $ λ hj, eq.le _), rw (huniv j).resolve_right hj } }, end /-- Composing an indepedent indexed family with an order isomorphism on the elements results in another indepedendent indexed family. -/ lemma independent.map_order_iso {ι : Sort*} {α β : Type*} [complete_lattice α] [complete_lattice β] (f : α ≃o β) {a : ι → α} (ha : independent a) : independent (f ∘ a) := λ i, ((ha i).map_order_iso f).mono_right (f.monotone.le_map_supr₂ _) @[simp] lemma independent_map_order_iso_iff {ι : Sort*} {α β : Type*} [complete_lattice α] [complete_lattice β] (f : α ≃o β) {a : ι → α} : independent (f ∘ a) ↔ independent a := ⟨ λ h, have hf : f.symm ∘ f ∘ a = a := congr_arg (∘ a) f.left_inv.comp_eq_id, hf ▸ h.map_order_iso f.symm, λ h, h.map_order_iso f⟩ /-- If the elements of a set are independent, then any element is disjoint from the `supr` of some subset of the rest. -/ lemma independent.disjoint_bsupr {ι : Type*} {α : Type*} [complete_lattice α] {t : ι → α} (ht : independent t) {x : ι} {y : set ι} (hx : x ∉ y) : disjoint (t x) (⨆ i ∈ y, t i) := disjoint.mono_right (bsupr_mono $ λ i hi, (ne_of_mem_of_not_mem hi hx : _)) (ht x) end complete_lattice lemma complete_lattice.independent_iff_sup_indep [complete_lattice α] {s : finset ι} {f : ι → α} : complete_lattice.independent (f ∘ (coe : s → ι)) ↔ s.sup_indep f := begin classical, rw finset.sup_indep_iff_disjoint_erase, refine subtype.forall.trans (forall₂_congr $ λ a b, _), rw finset.sup_eq_supr, congr' 2, refine supr_subtype.trans _, congr' 1 with x, simp [supr_and, @supr_comm _ (x ∈ s)], end alias complete_lattice.independent_iff_sup_indep ↔ complete_lattice.independent.sup_indep finset.sup_indep.independent /-- A variant of `complete_lattice.independent_iff_sup_indep` for `fintype`s. -/ lemma complete_lattice.independent_iff_sup_indep_univ [complete_lattice α] [fintype ι] {f : ι → α} : complete_lattice.independent f ↔ finset.univ.sup_indep f := begin classical, simp [finset.sup_indep_iff_disjoint_erase, complete_lattice.independent, finset.sup_eq_supr], end alias complete_lattice.independent_iff_sup_indep_univ ↔ complete_lattice.independent.sup_indep_univ finset.sup_indep.independent_of_univ section frame namespace complete_lattice variables [order.frame α] lemma set_independent_iff_pairwise_disjoint {s : set α} : set_independent s ↔ s.pairwise_disjoint id := ⟨set_independent.pairwise_disjoint, λ hs i hi, disjoint_Sup_iff.2 $ λ j hj, hs hi hj.1 $ ne.symm hj.2⟩ alias set_independent_iff_pairwise_disjoint ↔ _ _root_.set.pairwise_disjoint.set_independent lemma independent_iff_pairwise_disjoint {f : ι → α} : independent f ↔ pairwise (disjoint on f) := ⟨independent.pairwise_disjoint, λ hs i, disjoint_supr_iff.2 $ λ j, disjoint_supr_iff.2 $ λ hij, hs hij.symm⟩ end complete_lattice end frame
6a6f783bc7397738c264bba74587ed39d1b40444
9dc8cecdf3c4634764a18254e94d43da07142918
/src/data/multiset/powerset.lean
675cee9ba82be9a44387ece1ff08095bb93efeff
[ "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
10,631
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.multiset.basic import data.multiset.range import data.multiset.bind /-! # The powerset of a multiset -/ namespace multiset open list variables {α : Type*} /-! ### powerset -/ /-- A helper function for the powerset of a multiset. Given a list `l`, returns a list of sublists of `l` (using `sublists_aux`), as multisets. -/ def powerset_aux (l : list α) : list (multiset α) := 0 :: sublists_aux l (λ x y, x :: y) theorem powerset_aux_eq_map_coe {l : list α} : powerset_aux l = (sublists l).map coe := by simp [powerset_aux, sublists]; rw [← show @sublists_aux₁ α (multiset α) l (λ x, [↑x]) = sublists_aux l (λ x, list.cons ↑x), from sublists_aux₁_eq_sublists_aux _ _, sublists_aux_cons_eq_sublists_aux₁, ← bind_ret_eq_map, sublists_aux₁_bind]; refl @[simp] theorem mem_powerset_aux {l : list α} {s} : s ∈ powerset_aux l ↔ s ≤ ↑l := quotient.induction_on s $ by simp [powerset_aux_eq_map_coe, subperm, and.comm] /-- Helper function for the powerset of a multiset. Given a list `l`, returns a list of sublists of `l` (using `sublists'`), as multisets. -/ def powerset_aux' (l : list α) : list (multiset α) := (sublists' l).map coe theorem powerset_aux_perm_powerset_aux' {l : list α} : powerset_aux l ~ powerset_aux' l := by rw powerset_aux_eq_map_coe; exact (sublists_perm_sublists' _).map _ @[simp] theorem powerset_aux'_nil : powerset_aux' (@nil α) = [0] := rfl @[simp] theorem powerset_aux'_cons (a : α) (l : list α) : powerset_aux' (a::l) = powerset_aux' l ++ list.map (cons a) (powerset_aux' l) := by simp [powerset_aux']; refl theorem powerset_aux'_perm {l₁ l₂ : list α} (p : l₁ ~ l₂) : powerset_aux' l₁ ~ powerset_aux' l₂ := begin induction p with a l₁ l₂ p IH a b l l₁ l₂ l₃ p₁ p₂ IH₁ IH₂, {simp}, { simp, exact IH.append (IH.map _) }, { simp, apply perm.append_left, rw [← append_assoc, ← append_assoc, (by funext s; simp [cons_swap] : cons b ∘ cons a = cons a ∘ cons b)], exact perm_append_comm.append_right _ }, { exact IH₁.trans IH₂ } end theorem powerset_aux_perm {l₁ l₂ : list α} (p : l₁ ~ l₂) : powerset_aux l₁ ~ powerset_aux l₂ := powerset_aux_perm_powerset_aux'.trans $ (powerset_aux'_perm p).trans powerset_aux_perm_powerset_aux'.symm /-- The power set of a multiset. -/ def powerset (s : multiset α) : multiset (multiset α) := quot.lift_on s (λ l, (powerset_aux l : multiset (multiset α))) (λ l₁ l₂ h, quot.sound (powerset_aux_perm h)) theorem powerset_coe (l : list α) : @powerset α l = ((sublists l).map coe : list (multiset α)) := congr_arg coe powerset_aux_eq_map_coe @[simp] theorem powerset_coe' (l : list α) : @powerset α l = ((sublists' l).map coe : list (multiset α)) := quot.sound powerset_aux_perm_powerset_aux' @[simp] theorem powerset_zero : @powerset α 0 = {0} := rfl @[simp] theorem powerset_cons (a : α) (s) : powerset (a ::ₘ s) = powerset s + map (cons a) (powerset s) := quotient.induction_on s $ λ l, by simp; refl @[simp] theorem mem_powerset {s t : multiset α} : s ∈ powerset t ↔ s ≤ t := quotient.induction_on₂ s t $ by simp [subperm, and.comm] theorem map_single_le_powerset (s : multiset α) : s.map singleton ≤ powerset s := quotient.induction_on s $ λ l, begin simp only [powerset_coe, quot_mk_to_coe, coe_le, coe_map], show l.map (coe ∘ list.ret) <+~ (sublists l).map coe, rw ← list.map_map, exact ((map_ret_sublist_sublists _).map _).subperm end @[simp] theorem card_powerset (s : multiset α) : card (powerset s) = 2 ^ card s := quotient.induction_on s $ by simp theorem revzip_powerset_aux {l : list α} ⦃x⦄ (h : x ∈ revzip (powerset_aux l)) : x.1 + x.2 = ↑l := begin rw [revzip, powerset_aux_eq_map_coe, ← map_reverse, zip_map, ← revzip] at h, simp at h, rcases h with ⟨l₁, l₂, h, rfl, rfl⟩, exact quot.sound (revzip_sublists _ _ _ h) end theorem revzip_powerset_aux' {l : list α} ⦃x⦄ (h : x ∈ revzip (powerset_aux' l)) : x.1 + x.2 = ↑l := begin rw [revzip, powerset_aux', ← map_reverse, zip_map, ← revzip] at h, simp at h, rcases h with ⟨l₁, l₂, h, rfl, rfl⟩, exact quot.sound (revzip_sublists' _ _ _ h) end theorem revzip_powerset_aux_lemma [decidable_eq α] (l : list α) {l' : list (multiset α)} (H : ∀ ⦃x : _ × _⦄, x ∈ revzip l' → x.1 + x.2 = ↑l) : revzip l' = l'.map (λ x, (x, ↑l - x)) := begin have : forall₂ (λ (p : multiset α × multiset α) (s : multiset α), p = (s, ↑l - s)) (revzip l') ((revzip l').map prod.fst), { rw [forall₂_map_right_iff, forall₂_same], rintro ⟨s, t⟩ h, dsimp, rw [← H h, add_tsub_cancel_left] }, rw [← forall₂_eq_eq_eq, forall₂_map_right_iff], simpa end theorem revzip_powerset_aux_perm_aux' {l : list α} : revzip (powerset_aux l) ~ revzip (powerset_aux' l) := begin haveI := classical.dec_eq α, rw [revzip_powerset_aux_lemma l revzip_powerset_aux, revzip_powerset_aux_lemma l revzip_powerset_aux'], exact powerset_aux_perm_powerset_aux'.map _ end theorem revzip_powerset_aux_perm {l₁ l₂ : list α} (p : l₁ ~ l₂) : revzip (powerset_aux l₁) ~ revzip (powerset_aux l₂) := begin haveI := classical.dec_eq α, simp [λ l:list α, revzip_powerset_aux_lemma l revzip_powerset_aux, coe_eq_coe.2 p], exact (powerset_aux_perm p).map _ end /-! ### powerset_len -/ /-- Helper function for `powerset_len`. Given a list `l`, `powerset_len_aux n l` is the list of sublists of length `n`, as multisets. -/ def powerset_len_aux (n : ℕ) (l : list α) : list (multiset α) := sublists_len_aux n l coe [] theorem powerset_len_aux_eq_map_coe {n} {l : list α} : powerset_len_aux n l = (sublists_len n l).map coe := by rw [powerset_len_aux, sublists_len_aux_eq, append_nil] @[simp] theorem mem_powerset_len_aux {n} {l : list α} {s} : s ∈ powerset_len_aux n l ↔ s ≤ ↑l ∧ card s = n := quotient.induction_on s $ by simp [powerset_len_aux_eq_map_coe, subperm]; exact λ l₁, ⟨λ ⟨l₂, ⟨s, e⟩, p⟩, ⟨⟨_, p, s⟩, p.symm.length_eq.trans e⟩, λ ⟨⟨l₂, p, s⟩, e⟩, ⟨_, ⟨s, p.length_eq.trans e⟩, p⟩⟩ @[simp] theorem powerset_len_aux_zero (l : list α) : powerset_len_aux 0 l = [0] := by simp [powerset_len_aux_eq_map_coe] @[simp] theorem powerset_len_aux_nil (n : ℕ) : powerset_len_aux (n+1) (@nil α) = [] := rfl @[simp] theorem powerset_len_aux_cons (n : ℕ) (a : α) (l : list α) : powerset_len_aux (n+1) (a::l) = powerset_len_aux (n+1) l ++ list.map (cons a) (powerset_len_aux n l) := by simp [powerset_len_aux_eq_map_coe]; refl theorem powerset_len_aux_perm {n} {l₁ l₂ : list α} (p : l₁ ~ l₂) : powerset_len_aux n l₁ ~ powerset_len_aux n l₂ := begin induction n with n IHn generalizing l₁ l₂, {simp}, induction p with a l₁ l₂ p IH a b l l₁ l₂ l₃ p₁ p₂ IH₁ IH₂, {refl}, { simp, exact IH.append ((IHn p).map _) }, { simp, apply perm.append_left, cases n, {simp, apply perm.swap}, simp, rw [← append_assoc, ← append_assoc, (by funext s; simp [cons_swap] : cons b ∘ cons a = cons a ∘ cons b)], exact perm_append_comm.append_right _ }, { exact IH₁.trans IH₂ } end /-- `powerset_len n s` is the multiset of all submultisets of `s` of length `n`. -/ def powerset_len (n : ℕ) (s : multiset α) : multiset (multiset α) := quot.lift_on s (λ l, (powerset_len_aux n l : multiset (multiset α))) (λ l₁ l₂ h, quot.sound (powerset_len_aux_perm h)) theorem powerset_len_coe' (n) (l : list α) : @powerset_len α n l = powerset_len_aux n l := rfl theorem powerset_len_coe (n) (l : list α) : @powerset_len α n l = ((sublists_len n l).map coe : list (multiset α)) := congr_arg coe powerset_len_aux_eq_map_coe @[simp] theorem powerset_len_zero_left (s : multiset α) : powerset_len 0 s = {0} := quotient.induction_on s $ λ l, by simp [powerset_len_coe']; refl theorem powerset_len_zero_right (n : ℕ) : @powerset_len α (n + 1) 0 = 0 := rfl @[simp] theorem powerset_len_cons (n : ℕ) (a : α) (s) : powerset_len (n + 1) (a ::ₘ s) = powerset_len (n + 1) s + map (cons a) (powerset_len n s) := quotient.induction_on s $ λ l, by simp [powerset_len_coe']; refl @[simp] theorem mem_powerset_len {n : ℕ} {s t : multiset α} : s ∈ powerset_len n t ↔ s ≤ t ∧ card s = n := quotient.induction_on t $ λ l, by simp [powerset_len_coe'] @[simp] theorem card_powerset_len (n : ℕ) (s : multiset α) : card (powerset_len n s) = nat.choose (card s) n := quotient.induction_on s $ by simp [powerset_len_coe] theorem powerset_len_le_powerset (n : ℕ) (s : multiset α) : powerset_len n s ≤ powerset s := quotient.induction_on s $ λ l, by simp [powerset_len_coe]; exact ((sublists_len_sublist_sublists' _ _).map _).subperm theorem powerset_len_mono (n : ℕ) {s t : multiset α} (h : s ≤ t) : powerset_len n s ≤ powerset_len n t := le_induction_on h $ λ l₁ l₂ h, by simp [powerset_len_coe]; exact ((sublists_len_sublist_of_sublist _ h).map _).subperm @[simp] theorem powerset_len_empty {α : Type*} (n : ℕ) {s : multiset α} (h : s.card < n) : powerset_len n s = 0 := card_eq_zero.mp (nat.choose_eq_zero_of_lt h ▸ card_powerset_len _ _) @[simp] lemma powerset_len_card_add (s : multiset α) {i : ℕ} (hi : 0 < i) : s.powerset_len (s.card + i) = 0 := powerset_len_empty _ (lt_add_of_pos_right (card s) hi) theorem powerset_len_map {β : Type*} (f : α → β) (n : ℕ) (s : multiset α) : powerset_len n (s.map f) = (powerset_len n s).map (map f) := begin induction s using multiset.induction with t s ih generalizing n, { cases n; simp [powerset_len_zero_left, powerset_len_zero_right], }, { cases n; simp [ih, map_comp_cons], }, end lemma disjoint_powerset_len (s : multiset α) {i j : ℕ} (h : i ≠ j) : multiset.disjoint (s.powerset_len i) (s.powerset_len j) := λ x hi hj, h (eq.trans (multiset.mem_powerset_len.mp hi).right.symm (multiset.mem_powerset_len.mp hj).right) lemma bind_powerset_len {α : Type*} (S : multiset α) : bind (multiset.range (S.card + 1)) (λ k, S.powerset_len k) = S.powerset := begin induction S using quotient.induction_on, simp_rw [quot_mk_to_coe, powerset_coe', powerset_len_coe, ←coe_range, coe_bind, ←list.bind_map, coe_card], exact coe_eq_coe.mpr ((list.range_bind_sublists_len_perm S).map _), end end multiset
e0954cf5d6f26c144279d495ea197056d0d02950
c777c32c8e484e195053731103c5e52af26a25d1
/src/probability/kernel/invariance.lean
75ccfd8c63442e949bf628b55f9afde17842ff2d
[ "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
5,311
lean
/- Copyright (c) 2023 Kexing Ying. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kexing Ying -/ import probability.kernel.composition /-! # Invariance of measures along a kernel We define the push-forward of a measure along a kernel which results in another measure. In the case that the push-forward measure is the same as the original measure, we say that the measure is invariant with respect to the kernel. ## Main definitions * `probability_theory.kernel.map_measure`: the push-forward of a measure along a kernel. * `probability_theory.kernel.invariant`: invariance of a given measure with respect to a kernel. ## Useful lemmas * `probability_theory.kernel.comp_apply_eq_map_measure`, `probability_theory.kernel.const_map_measure_eq_comp_const`, and `probability_theory.kernel.comp_const_apply_eq_map_measure` established the relationship between the push-forward measure and the composition of kernels. -/ open measure_theory open_locale measure_theory ennreal probability_theory namespace probability_theory variables {α β γ : Type*} {mα : measurable_space α} {mβ : measurable_space β} {mγ : measurable_space γ} include mα mβ namespace kernel /-! ### Push-forward of measures along a kernel -/ /-- The push-forward of a measure along a kernel. -/ noncomputable def map_measure (κ : kernel α β) (μ : measure α) : measure β := measure.of_measurable (λ s hs, ∫⁻ x, κ x s ∂μ) (by simp only [measure_empty, measure_theory.lintegral_const, zero_mul]) begin intros f hf₁ hf₂, simp_rw [measure_Union hf₂ hf₁, lintegral_tsum (λ i, (kernel.measurable_coe κ (hf₁ i)).ae_measurable)], end @[simp] lemma map_measure_apply (κ : kernel α β) (μ : measure α) {s : set β} (hs : measurable_set s) : map_measure κ μ s = ∫⁻ x, κ x s ∂μ := by rw [map_measure, measure.of_measurable_apply s hs] @[simp] lemma map_measure_zero (κ : kernel α β) : map_measure κ 0 = 0 := begin ext1 s hs, rw [map_measure_apply κ 0 hs, lintegral_zero_measure, measure.coe_zero, pi.zero_apply], end @[simp] lemma map_measure_add (κ : kernel α β) (μ ν : measure α) : map_measure κ (μ + ν) = map_measure κ μ + map_measure κ ν := begin ext1 s hs, rw [map_measure_apply κ (μ + ν) hs, lintegral_add_measure, measure.coe_add, pi.add_apply, map_measure_apply κ μ hs, map_measure_apply κ ν hs], end @[simp] lemma map_measure_smul (κ : kernel α β) (μ : measure α) (r : ℝ≥0∞) : map_measure κ (r • μ) = r • map_measure κ μ := begin ext1 s hs, rw [map_measure_apply κ (r • μ) hs, lintegral_smul_measure, measure.coe_smul, pi.smul_apply, map_measure_apply κ μ hs, smul_eq_mul], end include mγ lemma comp_apply_eq_map_measure (η : kernel β γ) [is_s_finite_kernel η] (κ : kernel α β) [is_s_finite_kernel κ] (a : α) : (η ∘ₖ κ) a = map_measure η (κ a) := begin ext1 s hs, rw [comp_apply η κ a hs, map_measure_apply η _ hs], end omit mγ lemma const_map_measure_eq_comp_const (κ : kernel α β) [is_s_finite_kernel κ] (μ : measure α) [is_finite_measure μ] : const α (map_measure κ μ) = κ ∘ₖ const α μ := begin ext1 a, ext1 s hs, rw [const_apply, map_measure_apply _ _ hs, comp_apply _ _ _ hs, const_apply], end lemma comp_const_apply_eq_map_measure (κ : kernel α β) [is_s_finite_kernel κ] (μ : measure α) [is_finite_measure μ] (a : α) : (κ ∘ₖ const α μ) a = map_measure κ μ := by rw [← const_apply (map_measure κ μ) a, const_map_measure_eq_comp_const κ μ] lemma lintegral_map_measure (κ : kernel α β) [is_s_finite_kernel κ] (μ : measure α) [is_finite_measure μ] {f : β → ℝ≥0∞} (hf : measurable f) : ∫⁻ b, f b ∂(map_measure κ μ) = ∫⁻ a, ∫⁻ b, f b ∂(κ a) ∂μ := begin by_cases hα : nonempty α, { have := const_apply μ hα.some, swap, apply_instance, conv_rhs { rw [← this] }, rw [← lintegral_comp _ _ _ hf, ← comp_const_apply_eq_map_measure κ μ hα.some] }, { haveI := not_nonempty_iff.1 hα, rw [μ.eq_zero_of_is_empty, map_measure_zero, lintegral_zero_measure, lintegral_zero_measure] } end omit mβ /-! ### Invariant measures of kernels -/ /-- A measure `μ` is invariant with respect to the kernel `κ` if the push-forward measure of `μ` along `κ` equals `μ`. -/ def invariant (κ : kernel α α) (μ : measure α) : Prop := map_measure κ μ = μ variables {κ η : kernel α α} {μ : measure α} lemma invariant.def (hκ : invariant κ μ) : map_measure κ μ = μ := hκ lemma invariant.comp_const [is_s_finite_kernel κ] [is_finite_measure μ] (hκ : invariant κ μ) : (κ ∘ₖ const α μ) = const α μ := by rw [← const_map_measure_eq_comp_const κ μ, hκ.def] lemma invariant.comp [is_s_finite_kernel κ] [is_s_finite_kernel η] [is_finite_measure μ] (hκ : invariant κ μ) (hη : invariant η μ) : invariant (κ ∘ₖ η) μ := begin by_cases hα : nonempty α, { simp_rw [invariant, ← comp_const_apply_eq_map_measure (κ ∘ₖ η) μ hα.some, comp_assoc, hη.comp_const, hκ.comp_const, const_apply] }, { haveI := not_nonempty_iff.1 hα, exact subsingleton.elim _ _ }, end end kernel end probability_theory